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
blame on this site's /mcp
CLI
abso blame worker/project/project.ts --version 258 --json
JSON
/christopher/abso-core/blame/worker/project/project.ts?version=258&format=json
3,117 linesFirst import 75% · codex-capacity-chair 16% · capacity 7% · engine 1% · speed 1% · candidates 1% · Last change capacity in version 258,

3,117 lines from 56 changes in 43 versions.

init0Start the project1// 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.
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare15import {
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare16 type Atom,
17 type AtomId,
18 EngineError,
19 Graph,
20 type LineId,
21 type ReadView,
22 View,
23} from "../../src/engine/index.ts";
24import {
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare25 CachedStateStorage,
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare26 differenceSet,
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare27 type GraphStateStorage,
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare28 isClosedSet,
29 markClosed,
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare30 StableOverlaySet,
31 StableSet,
32 StableUnionSet,
33 StoredMap,
34 storedArray,
codex-capacity-chair142Avoid full-base membership copies during collision checksCompare35 unionOverlay,
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare36} from "../../src/engine/state-source.ts";
init0Start the project37import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
38import { type AmendHost, amend as hostedAmend } from "./amend.ts";
39import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
40import { type ApplyEntryHost, applyEntry as hostedApplyEntry } from "./apply-entry.ts";
41import {
42 type ChangeHost,
43 change as hostedChange,
44 changeRecord as hostedChangeRecord,
45 changes as hostedChanges,
46 joinChange as hostedJoinChange,
47 namedFiles as hostedNamedFiles,
48} from "./change-records.ts";
49import { type ChangesSinceHost, changesSince as hostedChangesSince } from "./changes-since.ts";
50import { type CheckClashHost, checkClash as hostedCheckClash } from "./check-clash.ts";
51import {
52 type CollisionHost,
53 describePair,
54 duplicateCollisions,
55 openPairs as hostedOpenPairs,
56 type Origin,
57 originOf,
58 type Pair,
59 pairsIn,
60 strandedFiles,
capacity237touchedBeyond, with named tests for 235's wrong draft diff (disk-first 2; abso Capacity). 236 fixed the wrong diff Disk-first Testing found on typescript-rs with 235 (cloud-ts-01's diff showed lib.rs and passes.rs from its older base). This moves that fix into a named function with its own tests, as Agent VCS asked. - collisions.ts touchedBeyond(graph, below, mine, views): the files a view over below plus mine can lay out differently from below, or undefined when any of it moves lines. It counts mine and whatever mine depends on that below lacks, since a view's set is closed. Project.#agentView's shareFiles uses it. - touched-beyond.test.ts: a publish's tie writes no files, but it depends on the published change. Counted from version 0 its files include the changed file, which 235's count (the atoms alone) missed. A move beyond the base turns sharing off. - agent-views-shared.test.ts adds a merge-queue landing with a move, then more drafting in the moved-to file. Checks: typescript-rs adopted fresh, diff for cloud-ts-01 matches replay (it differs on 235). Every worker/project test (341 of 341) and every engine test; tsc and biome clean.Compare61 touchedBeyond,
init0Start the project62 touchedFiles,
63} from "./collisions.ts";
64import { type DefinitionCollision, DefinitionRule } from "./definition-rule.ts";
65import { type DraftCollisionHost, draftCollisions } from "./draft-collisions.ts";
66import { type DraftDiffHost, diffOfAgent, diffOf as draftDiffOf } from "./draft-diff.ts";
67import { type DraftStateHost, draftState as hostedDraftState } from "./draft-state.ts";
68import { type DropHost, drop as hostedDrop } from "./drop.ts";
69import { type EditHost, edit as hostedEdit } from "./edit.ts";
70import { type ExpressMovesHost, expressMoves as hostedExpressMoves } from "./express-moves.ts";
71import {
72 type HistoryHost,
73 follow as historyFollow,
74 pathLife as historyPathLife,
75 tree as historyTree,
76} from "./history.ts";
77import { ingest as hostedIngest, type IngestHost } from "./ingest.ts";
78import { init as hostedInit, type InitHost } from "./init.ts";
capacity249Collisions step 3: each draft's definition work kept between calls, under a hard 4 MB budget (abso Capacity, issue 664). KeptParts (kept-parts.ts) holds what draft collisions work out about each draft and each pair of drafts: the names a draft's new lines use, the definitions a draft's changes touch before and after (the changed-definition rule), and the names two drafts both define in a file. Each entry is weighed as the view cache weighs views (line ids, texts, names: view.ts's stringBytes) and the whole stays under 4 MB, oldest out first; an entry over the budget isn't kept. Keys name everything an entry depends on: shared's version, the draft's base and its atoms. Each collisions call drops every entry it didn't use, so a draft that changes, an agent that leaves or shared moving on drops theirs at once. On a stored writer only; the publish check (land.ts) and the in-memory project work as before. On the abso export (my machine): a warm collisions call takes 322 ms instead of 3.4 s, with the same answer as replay. A full warm run's held heap is at most 42.9 MB (41.7 MB without it), and all 33 answers match. Tests: kept-parts (new: the budget, oldest out first, an oversized entry never kept, a round dropping what it didn't use) and collisions-kept-views, which now runs through the kept parts on the writer (a draft changing, shared moving on, a draft dropped, each asked twice against the in-memory project). With the collision, definition, path and view tests: 47 of 47.Compare79import { KeptParts } from "./kept-parts.ts";
init0Start the project80import { label as hostedLabel, type LabelHost } from "./label.ts";
81import {
82 land as hostedLand,
83 landCollisions as hostedLandCollisions,
84 landDraft as hostedLandDraft,
85 type LandHost,
86} from "./land.ts";
87import {
88 blocksIn,
89 markedCollisions as hostedMarkedCollisions,
90 markedFiles as hostedMarkedFiles,
91 markerCollisions as hostedMarkerCollisions,
92 markersSettled as hostedMarkersSettled,
93 openCollisions as hostedOpenCollisions,
94 type MarkerHost,
95} from "./markers.ts";
96import { MemoryStore } from "./memory-store.ts";
97import { mergeIdentical as hostedMergeIdentical, type MergeHost } from "./merge-identical.ts";
98import { move as hostedMove, type MoveHost } from "./move.ts";
99import {
100 addressedItem,
101 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
102 newsForOthers as hostedNewsForOthers,
103 markedItem,
104 type NewsHost,
105 type NewsItem,
106 reviewItem,
107 settledItem,
108} from "./news.ts";
109import {
110 closeNote as hostedCloseNote,
111 noteAnswer as hostedNoteAnswer,
112 notes as hostedNotes,
113 startingNotes as hostedStartingNotes,
114 writeNote as hostedWriteNote,
115 type NoteHost,
116 type NoteWriteHost,
117 type ReviewRule,
118 reviewersOf,
119 reviewRulesIn,
120} from "./notes.ts";
121import {
122 draftFiles as hostedDraftFiles,
123 overlapNews as hostedOverlapNews,
124 overlaps as hostedOverlaps,
125 type OverlapHost,
126} from "./overlaps.ts";
127import { checkPath } from "./path-rules.ts";
128import { PathIndex } from "./pathindex.ts";
129import { pathKey } from "./pathkey.ts";
130import { pluck as hostedPluck, type PluckHost } from "./pluck.ts";
131import { ProjectError } from "./project-error.ts";
engine25Read abso.json first, then avcs.json (abso 224, ask 238): one helper (projectFileIn) for the queue, files kept whole, reviewers and init; publish, init and git intake check both files the same way; when shared has both, abso.json counts and status says avcs.json is ignored (status answer projectFile, printed by abso status). .abso/ is kept out of projects like .avcs/. Old projects with only avcs.json work as before.Compare132import { checkDraftName, checkPerson, NAME, projectFileIn } from "./project-helpers.ts";
init0Start the project133import {
134 type SnapshotHost,
135 agentPaths as snapshotAgentPaths,
136 labels as snapshotLabels,
137 pathsAt as snapshotPathsAt,
138 pathsOf as snapshotPathsOf,
139 status as snapshotStatus,
140} from "./project-status.ts";
141import type {
142 AgentState,
143 AgentStatus,
144 ChangeAnswer,
145 ChangeRecord,
146 Collision,
147 DiffAnswer,
148 DraftSyncAnswer,
149 DropAnswer,
150 EditsVia,
151 Entry,
152 LandAnswer,
153 MergedLine,
154 Modes,
155 NoteAnswer,
156 NoteBody,
157 NoteRecord,
158 PersonSender,
159 PluckAnswer,
160 ProjectOptions,
161 ProjectStore,
162 PublishAnswer,
163 QueuedPublish,
164 Refusal,
165 Settled,
166 Starting,
167 Tail,
pinch31status lists the newest tells and who has heard each: every recipient, with the time its client handed the tell over (or not yet). It's read from the news and heard entries the log already keeps, so nothing new is recorded. Unlike announcements, which lists only what is still undelivered, a tell stays listed once heard, and two tells with the same words stay two. The last 50 are kept. A sync's reset hears no tell. Tests in worker/project/test/tells.test.ts.Compare168 TellRecord,
init0Start the project169} from "./project-types.ts";
170import { publish as hostedPublish, publishDraft as hostedPublishDraft, type PublishHost } from "./publish.ts";
171import { publishOf as hostedPublishOf, type PublishOfHost } from "./publish-of.ts";
172import {
173 enqueue as hostedEnqueue,
174 notQueuedYet as hostedNotQueuedYet,
175 queue as hostedQueue,
176 queueCandidate as hostedQueueCandidate,
177 queueChecking as hostedQueueChecking,
178 queuedAtoms as hostedQueuedAtoms,
179 queueLand as hostedQueueLand,
180 queueOn as hostedQueueOn,
181 queuePull as hostedQueuePull,
182 unqueue as hostedUnqueue,
183 type QueueHost,
184} from "./queue.ts";
185import { record as hostedRecord, type RecordHost } from "./record.ts";
186import { recordFile as hostedRecordFile, type RecordFileHost } from "./record-file.ts";
187import { refusals as hostedRefusals, refuse as hostedRefuse, type RefuseHost } from "./refuse.ts";
188import { restore as hostedRestore, type RestoreHost } from "./restore.ts";
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare189import {
190 closureChangedAt,
191 indexClosure,
192 last,
193 Membership,
194 SHARED,
195 SharedAdditions,
196 type Space,
197 sharedBaseOf,
198} from "./spaces.ts";
init0Start the project199import { starting as hostedStarting, type StartingHost } from "./start.ts";
200import { switchTo as hostedSwitchTo, type SwitchHost } from "./switch-to.ts";
201import { sync as hostedSync, type SyncHost } from "./sync.ts";
202import { treeHash } from "./tree.ts";
capacity251Author totals: each shared file's lines by author and its size, kept as versions land, so tree with authors reads them instead of laying every file out (abso Capacity, issue 664; docs/disk-first-2.md; Security yes on ask 2096). version-files.ts keeps, beside the head line counts, each file's totals at the newest version (head-authors) and at every version that changed them (author-totals), from version 0 on and only while every version since has kept them. A version on the fast path adds each inserted visible line to its author and takes each deleted one off its writer's, with its UTF-8 bytes and newline (joinLines). A version with moves, drops or a closure change counts every touched file from its layout, so a line rewritten with the same text by someone else still moves its author. Shared only; a draft's view takes its base's totals for the files the draft doesn't touch (touchedBeyond) and lays out the rest, and a named draft never reads them. Kept in the writer's state, so whatever replaces or clears it (a new adoption, a restore, a live drop) takes them too. A writer adopted before this keeps none and lays out as before. On a fresh abso adoption (my machine): tree with authors at 1224 takes 333 ms first and 50 ms again (11 to 16 s and 1.8 to 2.4 s before); an agent's tree with authors 619 ms again (2 to 3.4 s). Adoption 7.2 min, the same as before. A full run matches 33 of 33 answers. Test: author-totals.test.ts, tree with authors at every version and in every agent's view, the stored writer against the in-memory project: moved lines, a rename by record and by move, a drop, a binary file, text beyond ASCII, drafts that edit, move lines or have nothing. With the path, move, drop, draft, adoption and version-files tests: 47 of 47.Compare203import {
204 authoredVersion,
205 authorTotalsAt,
206 type FileTotals,
207 versionFiles as keptVersionFiles,
208 type VersionFilesHost,
209} from "./version-files.ts";
init0Start the project210import {
211 type LogHost,
212 compare as versionCompare,
capacity244compare keeps its own answer type; the summary is compareSummary (abso issue 680; abso Capacity). 243 gave compare one answer type for both shapes, full and summary. abso's own callers read compare(...).files as file changes (worker/src/engine-project.ts, scripts/versions-check.ts, test/versions.test.ts), and the union broke their types, which showed when I pinned 243 into abso. Core's own tests didn't catch it. - version-log.ts: compared() works out the files and both views; compare answers {from, to, files: FileChange[]} as before 243, and compareSummary answers {from, to, summary: true, files}. Project.compareSummary calls it. - server/src/engine-project.ts: compare(..., summary) calls compareSummary when summary is set. http.ts and ProjectHistory are unchanged from 243 (?summary=1, a fifth argument). - compare-summary.test.ts calls compareSummary. Answers are the same as 243's. Every engine test (292 of 292), every worker/project test (342 of 342); tsc (worker and server) and biome clean.Compare213 compareSummary as versionCompareSummary,
init0Start the project214 fileAt as versionFileAt,
215 log as versionLog,
216 ribbon as versionRibbon,
217 show as versionShow,
218 viewAt as versionViewAt,
219} from "./version-log.ts";
220import {
221 checkVersion as hostedCheckVersion,
222 lastVersion as hostedLastVersion,
223 versionMeta as hostedVersionMeta,
224 type VersionMetaHost,
225} from "./version-meta.ts";
226import { modesOf } from "./view-changes.ts";
227import { ViewCache } from "./views.ts";
228import {
229 isWhole as hostedIsWhole,
230 wholeOut as hostedWholeOut,
231 wholeRules as hostedWholeRules,
232 type WholeHost,
233} from "./whole-files.ts";
candidates186Read a version of shared without some earlier versions: abso show <N> --without A,B shows what differs and abso export <dir> --version N --without A,B writes the files. The server's GET without?version=&versions= checks the set left exactly as asked: when a version it keeps builds on one left out, it refuses with that chain, the files and the wider set that works, and never widens it. Atoms keep their ids and authors; shared and its log don't change; the same ask gives the same tree hash.Compare234import { without as hostedWithout, type WithoutHost } from "./without.ts";
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare235import { WriterAgents } from "./writer-agents.ts";
init0Start the project236
237export { MemoryStore } from "./memory-store.ts";
238export { checkReadPath, pathProblem } from "./path-rules.ts";
239export { ProjectError } from "./project-error.ts";
240export { shapeStamp, utf8Bytes } from "./project-helpers.ts";
241export type * from "./project-types.ts";
242export { differs } from "./view-changes.ts";
244/** Entry kinds that had no time before #41; new ones get one. */
245const UNTIMED = new Set<Entry["type"]>(["join", "sync", "news", "heard", "discard", "switch"]);
247/** A start note lasts this long after the agent's last activity (#44). */
248const NOTE_IDLE = 2 * 60 * 60 * 1000;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare249const WRITER_REOPEN = Symbol("verified writer checkpoint");
capacity222A stored writer's read cache holds 4 MB and 16,384 rows (disk-first 2; abso Capacity). Agent VCS's first disk-first reads on staging (commonmark-ts) found diff 9.7 s on the first call, against 1.8 s replayed. On typescript-rs, with one opened writer, an agent's diff made 59,000 row reads. It touches more rows than the old cache's 4,096, so it read the same rows many times: the membership and closure events of each atom it checks, and the list of atoms that move lines. At 4 MB and 16,384 rows, the same diff makes 22,000 reads and takes 1.1-2.8 s locally instead of 1.7-2.4 s. Locally a row read is cheap; in a Durable Object each one costs more, which is where staging's 9.7 s comes from. 8 MB saves only another 1,800. show is unchanged (5,000-8,500 reads, all distinct). Named tests: project-writer-storage, membership-cache, view-cache, draft-reads-stored, packed-crossings (19 of 19); tsc and biome clean.Compare250/**
251 * The stored writer's read cache (abso Capacity). An agent's diff on typescript-rs touches more rows than the old
252 * 4,096 held, so it read many of them again: 59,000 reads cold, against 22,000 at this size.
253 */
254const WRITER_CACHE_BYTES = 4 * 1_048_576;
255const WRITER_CACHE_ROWS = 16_384;
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare256/** The biggest row the writer cache keeps (abso Capacity): an agent and all the news it was told can be 100 KB. */
257const WRITER_CACHE_ROW_BYTES = 16_384;
capacity258Told lists out of agent rows, in 64 bucket rows per agent; layout pages read through the writer cache; a laid-out file's authors counted by writer (abso Capacity, issue 664; Security yes on ask 2102; Agent VCS approved). - writer-agents.ts: each agent's told keys (the news it has been told) live in 64 rows of their own, project:agents:told, keyed by the agent's name and a fixed hash bucket (FNV-1a mod 64), each holding its bucket's keys sorted; the agent row no longer carries them. told.has reads one bucket and told.add rewrites one; status, where and drafts never read them. A row written before keeps its list, read alongside the buckets (StoredTold.listed) until the agent's row is next written, which moves the list into the buckets; a fresh adoption writes the new form from the start. Removing an agent clears its buckets; delete and purge clear the writer state with them. abso's 109 agent rows were 4.3 MB, the largest 100.9 KB. - CachedStateStorage can read collections straight through; the writer passes file-lines, file-texts and file-deletes pages, which are read only to lay a file out (the view keeps the layout) and pushed out the small rows read on every call. - authorsInView: a laid-out file's lines by author from its visible lines' writers, each writer's author once (tree with authors, folder blame, and the totals adoption keeps), instead of an atom id and line id per line. Tests: told-buckets (new: news on a stored writer against the in-memory project, every step's news asked twice, before and after an agent's told keys are half in an old row's list and half in buckets, with a writer opened afresh; the old list moves into the buckets on the agent's next write; an agent never reads another's buckets; a rollback leaves the buckets as they were). state-cache: a collection read straight through is never kept and pushes nothing out. All of src/engine/test (295) and worker/project/test (351, one skipped) pass.Compare258/** A file's packed line pages: read only to lay it out, and the view keeps the layout (abso Capacity). */
259const LAYOUT_PAGES: ReadonlySet<string> = new Set(["file-lines:pages", "file-texts:pages", "file-deletes:pages"]);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare260export interface WriterSource {
261 readonly generation: number;
262 readonly logLength: number;
263 readonly sharedVersion: number;
265interface WriterAdoption {
266 source: WriterSource;
267 next: number;
268 ready: boolean;
init0Start the project270
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare271/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */
272export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry };
273function adoptionFrameBytes(frame: WriterAdoptionFrame): number {
274 return "json" in frame
275 ? typeof frame.json === "string"
276 ? new TextEncoder().encode(frame.json).byteLength
277 : NaN
278 : frame.bytes;
280function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry {
281 return "json" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry;
init0Start the project284export class Project {
285 readonly #store: ProjectStore;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare286 readonly #writerStorage?: GraphStateStorage;
init0Start the project287 readonly #graph: Graph;
288 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
289 readonly #views: ViewCache;
capacity249Collisions step 3: each draft's definition work kept between calls, under a hard 4 MB budget (abso Capacity, issue 664). KeptParts (kept-parts.ts) holds what draft collisions work out about each draft and each pair of drafts: the names a draft's new lines use, the definitions a draft's changes touch before and after (the changed-definition rule), and the names two drafts both define in a file. Each entry is weighed as the view cache weighs views (line ids, texts, names: view.ts's stringBytes) and the whole stays under 4 MB, oldest out first; an entry over the budget isn't kept. Keys name everything an entry depends on: shared's version, the draft's base and its atoms. Each collisions call drops every entry it didn't use, so a draft that changes, an agent that leaves or shared moving on drops theirs at once. On a stored writer only; the publish check (land.ts) and the in-memory project work as before. On the abso export (my machine): a warm collisions call takes 322 ms instead of 3.4 s, with the same answer as replay. A full warm run's held heap is at most 42.9 MB (41.7 MB without it), and all 33 answers match. Tests: kept-parts (new: the budget, oldest out first, an oversized entry never kept, a round dropping what it didn't use) and collisions-kept-views, which now runs through the kept parts on the writer (a draft changing, shared moving on, a draft dropped, each asked twice against the in-memory project). With the collision, definition, path and view tests: 47 of 47.Compare290 /** What draft collisions keep between calls, under its own byte budget (kept-parts.ts). */
291 #keptParts: KeptParts | undefined;
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare292 /** Each agent's draft files, under the key they were worked out for (#draftFiles). */
293 readonly #draftFilesKept = new Map<string, { key: string; files: Set<string> }>();
init0Start the project294 /** Each version's files and each path's history (pathindex.ts). */
295 readonly #paths: PathIndex;
296 /** For each atom (by seq) that wrote lines, the log position of the entry that recorded it (#46). */
297 readonly #atomAt: number[] = [];
298 /** Which atoms are in which space at which version (#46, disk-first 1): the rules live in spaces.ts. */
299 readonly #membership = new Membership();
300 get #spaces(): Map<string, Space> {
301 return this.#membership.spaces;
302 }
303 readonly #agents = new Map<string, AgentState>();
304 readonly #refusals: Refusal[] = [];
305 /** Labels on shared's versions: name -> versions, ascending. */
306 readonly #labels = new Map<string, number[]>();
pinch31status lists the newest tells and who has heard each: every recipient, with the time its client handed the tell over (or not yet). It's read from the news and heard entries the log already keeps, so nothing new is recorded. Unlike announcements, which lists only what is still undelivered, a tell stays listed once heard, and two tells with the same words stay two. The last 50 are kept. A sync's reset hears no tell. Tests in worker/project/test/tells.test.ts.Compare307 /** The newest tells and who has heard each (apply-entry.ts). */
308 readonly #tells = new Map<number, TellRecord>();
init0Start the project309 /**
310 * Entries applied but not stored yet, in order. Every applied entry is
311 * stored at the next flush, even when the call that applied it threw
312 * afterwards; otherwise the log could miss a join that later entries rely on.
313 */
314 #pending: Entry[] = [];
315 /**
316 * Whether something runs the merge queue's check (#39). Until the Worker has
317 * a checker it stays false, and `"queue": true` in avcs.json does nothing:
318 * publishes would otherwise wait for a check that never comes. Replay
319 * doesn't depend on it.
320 */
321 checkerReady = false;
322 readonly #now: (() => number) | undefined;
323 readonly #whole: ProjectOptions["whole"];
324 readonly #shapes: ProjectOptions["shapes"];
325 /** For each log position, the newest time up to it (#41): time to position in one search. */
326 readonly #timeAt: number[] = [];
327 /** For each version of shared, the log position of the entry that made it (#41). */
328 readonly #versionAt: number[] = [];
329 /** The newest time any applied entry carries: the clock when none was given. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare330 #lastTimeMemory = 0;
331 get #lastTime(): number {
332 return this.#writerStorage
333 ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0)
334 : this.#lastTimeMemory;
335 }
336 set #lastTime(value: number) {
337 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value);
338 else this.#lastTimeMemory = value;
339 }
init0Start the project340 /** Every change (#44), by id. */
341 readonly #changes = new Map<number, ChangeRecord>();
342 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
343 readonly #versionChange = new Map<string, number>();
344 /** Every note (#44), by id. */
345 readonly #notes = new Map<number, NoteRecord>();
pinch54The client and the edit mods send and read X-Abso-* headers only (Client, Name, Run-Key, Kind, Admin; Run, Box, Prep from answers). Servers have read X-Abso-* beside the old names for a while and answer under both, so this works with any current server.Compare346 /** Mod versions (X-Abso-Client) in the order they first sent an edit (#41): the last is taken as the installed one. */
init0Start the project347 #mods: string[] = [];
348 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
349 #queue: QueuedPublish[] = [];
350 /** The newest note's id (#44). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare351 #lastNoteMemory = 0;
352 get #lastNote(): number {
353 return this.#writerStorage
354 ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0)
355 : this.#lastNoteMemory;
356 }
357 set #lastNote(value: number) {
358 if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value);
359 else this.#lastNoteMemory = value;
360 }
361 #queuedIdMemory = 0;
362 get #queuedId(): number {
363 return this.#writerStorage
364 ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0)
365 : this.#queuedIdMemory;
366 }
367 set #queuedId(value: number) {
368 if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value);
369 else this.#queuedIdMemory = value;
370 }
init0Start the project371 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
372 #checking = new Set<number>();
373 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare374 #storedMemory = 0;
375 get #stored(): number {
376 return this.#writerStorage
377 ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0)
378 : this.#storedMemory;
379 }
380 set #stored(value: number) {
381 if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value);
382 else this.#storedMemory = value;
383 }
init0Start the project384 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
385 #rule?: DefinitionRule;
386 get #definitionRule(): DefinitionRule {
387 this.#rule ??= new DefinitionRule(this.#graph, (atom, space) => this.#origin(atom, space));
388 return this.#rule;
389 }
390 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare391 #announcedMemory = 0;
392 get #announced(): number {
393 return this.#writerStorage
394 ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0)
395 : this.#announcedMemory;
396 }
397 set #announced(value: number) {
398 if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value);
399 else this.#announcedMemory = value;
400 }
init0Start the project401 #loading = false;
403 readonly #hasBlob: (sha256: string) => boolean;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare405 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare406 if (options.indexAcceptedAtom && !options.writerStorage)
407 throw Error("accepted atom indexing requires writer storage");
init0Start the project408 this.#store = store;
capacity222A stored writer's read cache holds 4 MB and 16,384 rows (disk-first 2; abso Capacity). Agent VCS's first disk-first reads on staging (commonmark-ts) found diff 9.7 s on the first call, against 1.8 s replayed. On typescript-rs, with one opened writer, an agent's diff made 59,000 row reads. It touches more rows than the old cache's 4,096, so it read the same rows many times: the membership and closure events of each atom it checks, and the list of atoms that move lines. At 4 MB and 16,384 rows, the same diff makes 22,000 reads and takes 1.1-2.8 s locally instead of 1.7-2.4 s. Locally a row read is cheap; in a Durable Object each one costs more, which is where staging's 9.7 s comes from. 8 MB saves only another 1,800. show is unchanged (5,000-8,500 reads, all distinct). Named tests: project-writer-storage, membership-cache, view-cache, draft-reads-stored, packed-crossings (19 of 19); tsc and biome clean.Compare409 this.#writerStorage = options.writerStorage
capacity258Told lists out of agent rows, in 64 bucket rows per agent; layout pages read through the writer cache; a laid-out file's authors counted by writer (abso Capacity, issue 664; Security yes on ask 2102; Agent VCS approved). - writer-agents.ts: each agent's told keys (the news it has been told) live in 64 rows of their own, project:agents:told, keyed by the agent's name and a fixed hash bucket (FNV-1a mod 64), each holding its bucket's keys sorted; the agent row no longer carries them. told.has reads one bucket and told.add rewrites one; status, where and drafts never read them. A row written before keeps its list, read alongside the buckets (StoredTold.listed) until the agent's row is next written, which moves the list into the buckets; a fresh adoption writes the new form from the start. Removing an agent clears its buckets; delete and purge clear the writer state with them. abso's 109 agent rows were 4.3 MB, the largest 100.9 KB. - CachedStateStorage can read collections straight through; the writer passes file-lines, file-texts and file-deletes pages, which are read only to lay a file out (the view keeps the layout) and pushed out the small rows read on every call. - authorsInView: a laid-out file's lines by author from its visible lines' writers, each writer's author once (tree with authors, folder blame, and the totals adoption keeps), instead of an atom id and line id per line. Tests: told-buckets (new: news on a stored writer against the in-memory project, every step's news asked twice, before and after an agent's told keys are half in an old row's list and half in buckets, with a writer opened afresh; the old list moves into the buckets on the agent's next write; an agent never reads another's buckets; a rollback leaves the buckets as they were). state-cache: a collection read straight through is never kept and pushes nothing out. All of src/engine/test (295) and worker/project/test (351, one skipped) pass.Compare410 ? new CachedStateStorage(
411 options.writerStorage,
412 WRITER_CACHE_BYTES,
413 WRITER_CACHE_ROWS,
414 WRITER_CACHE_ROW_BYTES,
415 (collection) => LAYOUT_PAGES.has(collection),
416 )
capacity222A stored writer's read cache holds 4 MB and 16,384 rows (disk-first 2; abso Capacity). Agent VCS's first disk-first reads on staging (commonmark-ts) found diff 9.7 s on the first call, against 1.8 s replayed. On typescript-rs, with one opened writer, an agent's diff made 59,000 row reads. It touches more rows than the old cache's 4,096, so it read the same rows many times: the membership and closure events of each atom it checks, and the list of atoms that move lines. At 4 MB and 16,384 rows, the same diff makes 22,000 reads and takes 1.1-2.8 s locally instead of 1.7-2.4 s. Locally a row read is cheap; in a Durable Object each one costs more, which is where staging's 9.7 s comes from. 8 MB saves only another 1,800. show is unchanged (5,000-8,500 reads, all distinct). Named tests: project-writer-storage, membership-cache, view-cache, draft-reads-stored, packed-crossings (19 of 19); tsc and biome clean.Compare417 : undefined;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare418 if (this.#writerStorage) {
419 const storage = this.#writerStorage;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare420 // A stored Graph cannot be replayed over itself. Check before any
421 // constructor writes so an accidental reopen preserves the namespace.
422 if (
423 checkpoint !== WRITER_REOPEN &&
424 ((storage.read("atoms:meta", "length") as number | undefined) ||
425 (storage.read('membership:"":versions:meta', "length") as number | undefined))
426 )
427 throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
428 this.#membership = new Membership(storage);
429 this.#atomAt = storedArray(storage, "project:atom-at");
430 this.#timeAt = storedArray(storage, "project:time-at");
431 this.#versionAt = storedArray(storage, "project:version-at");
432 this.#notes = new StoredMap(storage, "project:notes");
433 this.#changes = new StoredMap(storage, "project:changes");
434 this.#labels = new StoredMap(storage, "project:labels");
435 this.#versionChange = new StoredMap(storage, "project:version-change");
436 this.#refusals = storedArray(storage, "project:refusals");
437 this.#agents = new WriterAgents(storage);
438 if (checkpoint === WRITER_REOPEN) {
439 this.#mods = storage.read("project:meta", "mods") as string[];
440 this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
441 const tells = storage.read("project:meta", "tells") as [
442 number,
443 Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
444 ][];
445 this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
446 }
447 }
init0Start the project448 this.#hasBlob = options.hasBlob ?? (() => false);
449 this.#now = options.now;
450 this.#whole = options.whole;
451 this.#shapes = options.shapes;
452 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store.
453 const testing =
454 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
455 "1";
456 const entryAt =
457 options.entryAt ??
458 (testing && store instanceof MemoryStore ? (at: number) => (store as MemoryStore).entries[at]! : undefined);
459 // An atom as its log entry stores it. Not stored yet: still in this call's pending entries; while loading, every entry is stored.
460 const stored = (seq: number): Atom => {
461 const at = this.#atomAt[seq]!;
462 const entry = !this.#loading && at >= this.#stored ? this.#pending[at - this.#stored]! : entryAt!(at);
463 if (entry?.type === "init" || entry?.type === "draft") return entry.atom;
464 // A publish's or land's tie atom (#46: its lists are read back too).
465 if (entry?.type === "publish" || entry?.type === "land") return entry.tie;
466 throw new Error(`log entry ${at} holds no atom ${seq}`);
467 };
468 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare469 this.#graph = this.#writerStorage
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare470 ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom })
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare471 : entryAt
472 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
473 : new Graph();
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare474 this.#views = new ViewCache(this.#graph, options.readViewProvider);
init0Start the project475 this.#paths = new PathIndex({
476 graph: this.#graph,
477 at: (space, version) => this.#at(space, version),
478 viewAt: (space, version) => this.#viewAt(space, version),
479 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
480 shapes: this.#shapes,
481 });
482 }
484 /** Rebuild a project from its stored entries. New entries go to `store`. */
485 static load(entries: Iterable<Entry>, store: ProjectStore, options: ProjectOptions = {}): Project {
486 const testing =
487 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG ===
488 "1";
489 if (testing && !options.entryAt && Array.isArray(entries)) {
490 // Loaded from someone else's entries: its text is read back from them (and from the new store after them).
491 const from = entries as Entry[];
492 const after = store instanceof MemoryStore ? store : undefined;
493 options = { ...options, entryAt: (at) => (at < from.length ? from[at]! : after!.entries[at - from.length]!) };
494 }
495 const project = new Project(store, options);
496 project.#loading = true;
497 for (const entry of entries) {
498 project.#apply(entry);
499 project.#stored++;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare500 project.#persistMutable();
init0Start the project501 }
502 project.#loading = false;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare503 project.#writeCheckpoint();
init0Start the project504 return project;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare505 }
507 /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
508 static openWriter(
509 store: ProjectStore,
510 storage: GraphStateStorage,
511 logLength: number,
512 options: Omit<ProjectOptions, "writerStorage"> = {},
513 ): Project {
514 const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
515 if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
516 return Project.#openWriter(store, storage, logLength, options);
init0Start the project517 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare519 static #openWriter(
520 store: ProjectStore,
521 storage: GraphStateStorage,
522 logLength: number,
523 options: Omit<ProjectOptions, "writerStorage">,
524 ): Project {
525 const checkpoint = storage.read("project:meta", "checkpoint") as
526 | { format: number; logLength: number; atoms: number; version: number }
527 | undefined;
528 const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
529 if (
530 !Number.isSafeInteger(logLength) ||
531 logLength < 1 ||
532 checkpoint?.format !== 1 ||
533 checkpoint.logLength !== logLength ||
534 storage.read("project:meta", "stored") !== logLength ||
535 length("project:time-at") !== logLength ||
536 length("atoms") !== checkpoint.atoms ||
537 length("project:atom-at") !== checkpoint.atoms ||
538 length('membership:"":versions') !== checkpoint.version + 1 ||
539 length("project:version-at") !== checkpoint.version + 1 ||
540 !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
541 )
542 throw new Error("writer checkpoint does not match the canonical log and indexes");
543 return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
544 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare546 /** Open a host-verified historical prefix. Its state must be immutable and
547 * scoped to canonical authority; adoption readiness describes the live writer,
548 * not whether this individual prefix has a complete checkpoint. */
549 static openHistorical(
550 storage: GraphStateStorage,
551 logLength: number,
552 scratch: GraphStateStorage,
553 assertScope: () => void = () => {
554 storage.read("project:meta", "checkpoint");
555 },
556 readViewProvider?: ProjectOptions["readViewProvider"],
557 ): Project {
558 const refuse = (): never => {
559 throw new Error("historical project is read-only");
560 };
561 const selected = (collection: string) => {
562 // Revalidate the historical scope even when accessing derived scratch.
563 assertScope();
564 return collection.startsWith("projection-scratch:") ? scratch : storage;
565 };
566 return Project.#openWriter(
567 { append: refuse },
568 {
569 read: (collection, key) => selected(collection).read(collection, key),
570 entries: (collection) => selected(collection).entries(collection),
codex-capacity-chair147Batch immutable locator writes for sequence updatesCompare571 write: (collection, key, value) => {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare572 if (selected(collection) !== scratch) refuse();
573 scratch.write(collection, key, value);
574 },
575 remove: (collection, key) => {
576 if (selected(collection) !== scratch) refuse();
577 scratch.remove(collection, key);
578 },
579 transaction: (body) => storage.transaction(() => scratch.transaction(body)),
580 },
581 logLength,
582 { readViewProvider },
583 );
584 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare586 /**
587 * Derive one bounded page from the host's canonical frames. The host reads
588 * those frames from its own log and revalidates the source inside this same
589 * transaction. Partial adoption cannot be opened for normal operations.
590 */
591 static adoptWriterPage(
592 storage: GraphStateStorage,
593 input: {
594 source: WriterSource;
595 from: number;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare596 frames: Iterable<WriterAdoptionFrame>;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare597 maxEntries: number;
598 maxBytes: number;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare599 /** The host supplies disk-backed decoded entries and verified byte counts. */
600 decodedFrames?: boolean;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare601 currentSource(): WriterSource;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare602 /** Select the host's derived historical revision before applying a frame.
603 * Each selected revision receives a complete Project checkpoint. */
604 beginRevision?(logLength: number): void;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare605 },
606 options: Omit<ProjectOptions, "writerStorage"> = {},
607 ): { next: number; ready: boolean; entries: number; bytes: number } {
608 const same = (a: WriterSource, b: WriterSource) =>
609 a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
610 if (
611 ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
612 (n) => Number.isSafeInteger(n) && n >= 0,
613 ) ||
614 input.source.logLength < 1 ||
615 !Number.isSafeInteger(input.maxEntries) ||
616 input.maxEntries < 1 ||
617 input.maxEntries > 256 ||
618 !Number.isSafeInteger(input.maxBytes) ||
619 input.maxBytes < 1 ||
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare620 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare621 )
622 throw new Error("invalid writer adoption bounds or source");
623 return storage.transaction(() => {
624 if (!same(input.currentSource(), input.source))
625 throw new Error("canonical source changed before writer adoption");
626 const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
627 if (
628 (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
629 (!previous && input.from !== 0)
630 )
631 throw new Error("writer adoption source or cursor does not match");
632 const noAppend: ProjectStore = {
633 append: () => {
634 throw new Error("adoption must never append canonical history");
635 },
636 };
637 const project = previous
638 ? Project.#openWriter(noAppend, storage, input.from, options)
639 : new Project(noAppend, { ...options, writerStorage: storage });
640 project.#loading = true;
641 let count = 0;
642 let bytes = 0;
643 for (const frame of input.frames) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare644 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
645 const size = adoptionFrameBytes(frame);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare646 if (
647 count >= input.maxEntries ||
648 frame.seq !== input.from + count ||
649 frame.seq >= input.source.logLength ||
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare650 !Number.isSafeInteger(size) ||
651 size < 1 ||
652 size > input.maxBytes - bytes
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare653 )
654 throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare655 bytes += size;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare656 if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare657 input.beginRevision?.(frame.seq + 1);
658 project.#apply(adoptionFrameEntry(frame));
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare659 project.#stored++;
660 project.#persistMutable();
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare661 if (input.beginRevision) project.#writeCheckpoint();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare662 count++;
663 }
664 if (count === 0) throw new Error("writer adoption page must advance");
665 project.#loading = false;
666 const next = input.from + count;
667 const ready = next === input.source.logLength;
668 if (!same(input.currentSource(), input.source))
669 throw new Error("canonical source changed during writer adoption");
670 if (ready && project.version !== input.source.sharedVersion)
671 throw new Error("adopted shared version differs from canonical source");
672 project.#writeCheckpoint();
673 storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
674 return { next, ready, entries: count, bytes };
675 });
676 }
init0Start the project678 /**
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare679 * Extend derived historical indexes from an already checkpointed prefix.
680 * The host supplies only new canonical frames inside its commit transaction.
init0Start the project681 */
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare682 static extendHistoricalPage(
683 storage: GraphStateStorage,
684 input: {
685 from: number;
686 frames: Iterable<WriterAdoptionFrame>;
687 maxEntries: number;
688 maxBytes: number;
689 /** The host supplies disk-backed decoded entries and verified byte counts. */
690 decodedFrames?: boolean;
691 beginRevision(logLength: number): void;
692 /** Verify both the saved prefix and the new frames against canonical authority. */
693 validateAuthority(): void;
694 },
695 ): { next: number; entries: number; bytes: number } {
696 if (
697 !Number.isSafeInteger(input.from) ||
698 input.from < 1 ||
699 !Number.isSafeInteger(input.maxEntries) ||
700 input.maxEntries < 1 ||
701 input.maxEntries > 256 ||
702 !Number.isSafeInteger(input.maxBytes) ||
703 input.maxBytes < 1 ||
704 (input.maxBytes > 8_000_000 && input.decodedFrames !== true)
705 )
706 throw new Error("invalid historical extension bounds");
707 const validate = () => {
708 const result: unknown = input.validateAuthority();
709 if (result && (typeof result === "object" || typeof result === "function") && "then" in result)
710 throw new Error("historical authority must be synchronous");
711 };
712 return storage.transaction(() => {
713 validate();
714 const project = Project.#openWriter(
715 {
716 append: () => {
717 throw new Error("history derivation cannot append canonical entries");
718 },
719 },
720 storage,
721 input.from,
722 {},
723 );
724 project.#loading = true;
725 let entries = 0,
726 bytes = 0;
727 for (const frame of input.frames) {
728 if (input.decodedFrames && "json" in frame) throw new Error("decoded adoption requires decoded frames");
729 const size = adoptionFrameBytes(frame);
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare730 if (
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare731 entries >= input.maxEntries ||
732 frame.seq !== input.from + entries ||
733 !Number.isSafeInteger(size) ||
734 size < 1 ||
735 size > input.maxBytes - bytes
736 )
737 throw new Error("historical extension exceeds bounds or is not contiguous");
738 bytes += size;
739 if (bytes > input.maxBytes) throw new Error("historical extension exceeds byte bound");
740 input.beginRevision(frame.seq + 1);
741 project.#apply(adoptionFrameEntry(frame));
742 project.#stored++;
743 project.#persistMutable();
744 project.#writeCheckpoint();
745 entries++;
746 }
747 if (!entries) throw new Error("historical extension must advance");
748 validate();
749 return { next: input.from + entries, entries, bytes };
750 });
751 }
753 /** Apply more entries to a replay copy. Never for the live project. */
init0Start the project754 catchUp(entries: Iterable<Entry>): void {
755 this.#loading = true;
756 try {
757 for (const entry of entries) {
758 this.#apply(entry);
759 this.#stored++;
760 }
761 } finally {
762 this.#loading = false;
763 }
764 }
766 /** The log position of the next entry: how many entries the log holds (#41). */
767 get logLength(): number {
768 return this.#stored;
769 }
771 get initialized(): boolean {
772 return this.#shared.versions.length > 0;
773 }
775 /** The current shared version. */
776 get version(): number {
777 this.#needInit();
778 return this.#shared.versions.length - 1;
779 }
781 /** Shared's files, for the push out to Artifacts. */
782 files(): Record<string, string> {
783 return this.#sharedView().files();
784 }
786 /** Shared's binary files, for the push out to Artifacts: path -> the SHA-256 of its bytes. Not in `files()`. */
787 blobs(): Record<string, string> {
788 return this.#sharedView().blobs();
789 }
791 /** Shared's executable files and links, for the push out to Artifacts: path -> mode. Other files are plain. */
792 modes(): Modes {
793 return modesOf(this.#sharedView());
794 }
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare796 /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */
797 sharedView(): ReadView {
init0Start the project798 return this.#sharedView();
799 }
801 /** The agents the project knows, by name. */
802 agents(): string[] {
803 return [...this.#agents.keys()].sort();
804 }
speed83where lays out an agent's view only when it reads it draftOf's view is now built on first use. where asks every agent for its draft, most agents have no changes, and a big project has more agents than the view cache holds (32), so each call built every view again. On a 17,000-entry log with 52 agents, where went from about 730 ms a call to about 10 ms. Test: worker/project/test/where-many-agents.test.ts.Compare806 /**
807 * An agent's unpublished changes, oldest first, and its view (its space at its base plus its changes). Read only.
808 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more
809 * agents than the view cache holds, so building every view cost each call about 0.7 s.
810 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare811 draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {
init0Start the project812 const agent = this.#agents.get(agentName);
speed83where lays out an agent's view only when it reads it draftOf's view is now built on first use. where asks every agent for its draft, most agents have no changes, and a big project has more agents than the view cache holds (32), so each call built every view again. On a 17,000-entry log with 52 agents, where went from about 730 ms a call to about 10 ms. Test: worker/project/test/where-many-agents.test.ts.Compare813 if (!agent) return undefined;
814 const view = () => this.#agentView(agent);
815 return {
816 atoms: this.#draft(agent),
817 get view() {
818 return view();
819 },
820 };
init0Start the project821 }
823 /** The shared version an atom was published in, or undefined while it's only in a draft. */
824 versionOf(atom: AtomId): number | undefined {
825 return this.#shared.publishedIn.get(atom);
826 }
828 /**
829 * Where an atom was published: shared if it's there, else the named draft
830 * that has it (by name), else undefined (it's only in a draft so far).
831 */
832 publishOf(...args: Tail<Parameters<typeof hostedPublishOf>>): ReturnType<typeof hostedPublishOf> {
833 return hostedPublishOf(this.#publishOfHost, ...args);
834 }
836 /** The newest version of shared, or of a named draft. */
837 lastVersion(...args: Tail<Parameters<typeof hostedLastVersion>>): ReturnType<typeof hostedLastVersion> {
838 return hostedLastVersion(this.#versionMetaHost, ...args);
839 }
841 /** Shared (null), then each named draft by name: every space with versions (abso issue 80). */
842 spaceNames(): (string | null)[] {
843 return [null, ...[...this.#spaces.keys()].filter((n) => n !== SHARED).sort()];
844 }
846 /** Who made a version of shared or a named draft, why and when, and a draft's shared base (abso issue 80). */
847 versionMeta(...args: Tail<Parameters<typeof hostedVersionMeta>>): ReturnType<typeof hostedVersionMeta> {
848 return hostedVersionMeta(this.#versionMetaHost, ...args);
849 }
851 /** Who published a version of shared, and why. */
852 published(version: number): { agent: string; message: string; time: number } | undefined {
853 const p = this.#shared.versions[version];
854 return p && { agent: p.agent, message: p.message, time: p.time };
855 }
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare857 /** The atoms a version of shared, or of a named draft, added to its space: what was pushed together (blame's trail). */
858 versionAtoms(version: number, draft: string | null = null): readonly AtomId[] {
859 const space = draft === null ? this.#shared : this.#spaces.get(draft);
860 return space?.versions[version]?.atoms ?? [];
861 }
init0Start the project863 /** The graph, for reading (blame, history). Don't add to it. */
864 get graph(): Graph {
865 return this.#graph;
866 }
868 // Calls -------------------------------------------------------------------
870 /** Create the project from a folder's text files. Empty files are skipped (the engine can't hold them). */
871 init(...args: Tail<Parameters<typeof hostedInit>>): ReturnType<typeof hostedInit> {
872 return hostedInit(this.#initHost, ...args);
873 }
875 /** An Edit, Write or MultiEdit from the hook, against the agent's view. */
876 edit(...args: Tail<Parameters<typeof hostedEdit>>): ReturnType<typeof hostedEdit> {
877 return hostedEdit(this.#editHost, ...args);
878 }
880 /** Whole files as the agent's folder has them; each is diffed against its view. */
881 record(...args: Tail<Parameters<typeof hostedRecord>>): ReturnType<typeof hostedRecord> {
882 return hostedRecord(this.#recordHost, ...args);
883 }
885 /** Add the agent's draft to its space (publish.ts). */
886 publish(...args: Tail<Parameters<typeof hostedPublish>>): ReturnType<typeof hostedPublish> {
887 return hostedPublish(this.#publishHost, ...args);
888 }
890 #publish(
891 agent: AgentState,
892 message: string,
893 time: number,
894 entries: Entry[],
895 asIs = false,
896 direct = false,
897 ): PublishAnswer {
898 return hostedPublishDraft(this.#publishHost, agent, message, time, entries, asIs, direct);
899 }
901 /**
pinch54The client and the edit mods send and read X-Abso-* headers only (Client, Name, Run-Key, Kind, Admin; Run, Box, Prep from answers). Servers have read X-Abso-* beside the old names for a while and answer under both, so this works with any current server.Compare902 * How the agent's newest edit arrived (#41). The mod sends X-Abso-Client
init0Start the project903 * avcs-mod/<stamp>; the hook sends abso-cli/<version> (avcs-cli/ before #59) with the chat's
904 * session; abso record and git pushes send no session. Edits stored before
905 * the client was recorded have only the session: those count as the mod
906 * (the hook stands down where the mod is installed), with modCurrent null.
907 */
908 #editsOf(agent: AgentState): {
909 edits: EditsVia;
910 modCurrent: boolean | null;
911 lastEdit: number | null;
912 joined: number | null;
913 } {
914 const last = agent.lastEdit;
915 const joined = agent.joined ?? null;
916 if (!last) return { edits: "none", modCurrent: null, lastEdit: null, joined };
917 const { client, session } = last;
918 if (client?.startsWith("avcs-mod/"))
919 return { edits: "mod", modCurrent: client === this.#mods[this.#mods.length - 1], lastEdit: last.time, joined };
920 if (client === undefined && session) return { edits: "mod", modCurrent: null, lastEdit: last.time, joined };
921 return { edits: session ? "hook" : "commands", modCurrent: null, lastEdit: last.time, joined };
922 }
924 // Spellings and moves (#49) --------------------------------------------------------
926 /** Refuse work whose paths would clash in shared (#49), before anything of it is written. */
927 #checkClash(...args: Tail<Parameters<typeof hostedCheckClash>>): ReturnType<typeof hostedCheckClash> {
928 return hostedCheckClash(this.#checkClashHost, ...args);
929 }
931 /**
932 * Move a file in the agent's draft (#49): its lines keep their ids, as with
933 * git mv, so blame and why follow it. The only way to change a file's case.
934 * Refused when `to` is another existing file, ignoring case.
935 */
936 move(...args: Tail<Parameters<typeof hostedMove>>): ReturnType<typeof hostedMove> {
937 return hostedMove(this.#moveHost, ...args);
938 }
940 // Files kept whole (#46) ----------------------------------------------------------
942 /** avcs.json's `"whole": [globs]`: paths kept whole. From `config` when given (init), else shared's. */
943 #wholeRules(config?: string): string[] {
944 return hostedWholeRules(this.#wholeHost, config);
945 }
947 /**
948 * Whether a file is kept whole: its path matches avcs.json's "whole", its
949 * text passes WHOLE_LIMIT, or it is already a blob where it's going. The
950 * last makes it one-way: a file kept whole stays whole while it exists,
951 * even if it shrinks or the rule changes, so it never flips back and forth.
952 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare953 #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {
init0Start the project954 return hostedIsWhole(this.#wholeHost, path, length, view, rules);
955 }
957 /** Files and blobs with every whole file's text moved into the blob store. */
958 #wholeOut(
959 files: Readonly<Record<string, string | null>>,
960 blobs: Readonly<Record<string, string>>,
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare961 view: ReadView | undefined,
init0Start the project962 config?: string,
963 ): { files: Record<string, string | null>; blobs: Record<string, string> } {
964 return hostedWholeOut(this.#wholeHost, files, blobs, view, config);
965 }
967 // Changes (#44) -------------------------------------------------------------------
969 /** The agent did something at `time`: its start note ends first if it had been idle over 2 hours. */
970 #active(agent: AgentState, time: number): void {
971 if (agent.starting && agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE) {
972 delete agent.starting;
973 delete agent.noteAt;
974 }
975 if (agent.lastActive === undefined || time > agent.lastActive) agent.lastActive = time;
976 }
978 /** The agent's start note, unless it has been idle over 2 hours. */
979 #liveNote(agent: AgentState): Starting | undefined {
980 if (!agent.starting) return undefined;
981 const now = this.#now?.() ?? this.#lastTime;
982 return agent.lastActive !== undefined && now - agent.lastActive > NOTE_IDLE ? undefined : agent.starting;
983 }
985 /** The change the agent is working on at `time`: its named draft's, or its start note's; none for a lone publish. */
986 #currentChange(agent: AgentState, time: number): number | undefined {
987 if (agent.space !== SHARED) return this.#spaces.get(agent.space)?.startedAt;
988 if (!agent.starting || agent.noteAt === undefined) return undefined;
989 return agent.lastActive !== undefined && time - agent.lastActive > NOTE_IDLE ? undefined : agent.noteAt;
990 }
992 /** The position the next entry written will have. */
993 get #nextAt(): number {
994 return this.#stored + this.#pending.length;
995 }
997 #changeRecord(id: number, agent: AgentState, time: number, queuedNote?: Starting): ChangeRecord {
998 return hostedChangeRecord(this.#changeHost, id, agent, time, queuedNote);
999 }
1001 /** A publish or land joins its change. Entries from before changes: the start note named it, and the publish ended the note. */
1002 #joinChange(
1003 agent: AgentState,
1004 entry: Extract<Entry, { type: "publish" | "land" }>,
1005 at: number,
1006 draft: string | null,
1007 landed?: string,
1008 ): void {
1009 hostedJoinChange(this.#changeHost, agent, entry, at, draft, landed);
1012 /**
1013 * One change (#44): the start note, named draft or publish that began it,
1014 * each of its versions and the files they changed, what it settled, and its
1015 * refusals. `id` is the log position of the entry that began it.
1016 */
1017 change(id: number): ChangeAnswer {
1018 return hostedChange(this.#changeHost, id);
1021 /** The files a version's changes name: cheap, for lists (the change page works out the net changes). */
1022 #namedFiles(space: Space, version: number): string[] {
1023 return hostedNamedFiles(this.#graph, space, version);
1026 /**
1027 * "Since you last looked" (#44): the changes with anything new at or after
1028 * log position `since`, newest first, at most `limit`. Their files are the
1029 * ones their changes name; the change page has the net changes.
1030 */
1031 changes(
1032 since = 0,
1033 limit = 50,
1034 before?: number,
1035 issue?: number,
1036 ): { since: number; next: number; changes: ChangeAnswer[]; older?: number } {
1037 return hostedChanges(this.#changeHost, since, limit, before, issue);
1040 // Notes on lines (#44) --------------------------------------------------------------
1042 /**
1043 * Leave a note on lines of a file (#44): lines `from` to `to` (1-based) as
1044 * shared shows them now, as `of`'s draft shows them (to note work before
1045 * it's published), or at `version`. Or answer a note with `reply`. The
1046 * lines' authors, the change's agent and the thread hear it as news.
1047 */
1048 note(
1049 agentName: string,
1050 body: NoteBody,
1051 time: number,
1052 ): { id: number; change: number | null; lines: [number, number] } {
1053 this.#needInit();
1054 const entries: Entry[] = [];
1055 return this.#note(entries, () => ({ name: this.#agent(agentName, entries).name }), body, time);
1058 /**
1059 * A signed-in person's note from the website (#41). The Worker has checked
1060 * who it is. The writer is recorded as "person:<id>" with `person`, never
1061 * as an agent, and the news quotes the text.
1062 */
1063 notePerson(
1064 person: { id: unknown; name: unknown },
1065 body: NoteBody,
1066 time: number,
1067 ): { id: number; change: number | null; lines: [number, number] } {
1068 this.#needInit();
1069 const from = checkPerson(person);
1070 return this.#note([], () => ({ name: `person:${from.person.id}`, person: from }), body, time);
1073 /** Close a person's own note (#41): only the person who wrote it can. */
1074 closeNotePerson(person: { id: unknown; name: unknown }, id: number, how: unknown, time: number): NoteAnswer {
1075 const from = checkPerson(person);
1076 return this.#closeNote(`person:${from.person.id}`, id, how, time, from);
1079 #note(
1080 entries: Entry[],
1081 writerOf: () => { name: string; person?: PersonSender },
1082 body: NoteBody,
1083 time: number,
1084 ): { id: number; change: number | null; lines: [number, number] } {
1085 return hostedWriteNote(this.#noteWriteHost, entries, writerOf, body, time);
1088 /** The project's reviewers per area (#44): avcs.json's `"review": [{"paths": [...], "reviewer": "..."}]` in shared. */
1089 #reviewRules(): ReviewRule[] {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1090 if (["abso.json", "avcs.json"].every((path) => this.#graph.startCodeOf(path) === undefined)) return [];
engine25Read abso.json first, then avcs.json (abso 224, ask 238): one helper (projectFileIn) for the queue, files kept whole, reviewers and init; publish, init and git intake check both files the same way; when shared has both, abso.json counts and status says avcs.json is ignored (status answer projectFile, printed by abso status). .abso/ is kept out of projects like .avcs/. Old projects with only avcs.json work as before.Compare1091 return reviewRulesIn(projectFileIn(this.#sharedView())?.text);
init0Start the project1092 }
1094 /** Each reviewer whose area these files fall in, the files that do, and whether it has noted change `id`. */
1095 #reviewersOf(files: readonly string[], id: number): { agent: string; files: string[]; read: boolean }[] {
1096 return reviewersOf(this.#reviewRules(), files, (agent) =>
1097 [...this.#notes.values()].some((n) => n.change === id && n.agent === agent),
1098 );
1101 /** After a version of shared: the reviewers whose areas it touches hear of its change, once per change (#44). */
1102 #reviewNews(agent: AgentState, version: number, entries: Entry[]): void {
1103 const id = this.#versionChange.get(` ${version}`);
1104 if (id === undefined) return;
1105 const rec = this.#changes.get(id);
1106 const files = this.#namedFiles(this.#shared, version);
1107 for (const r of this.#reviewersOf(files, id)) {
1108 if (r.agent === agent.name) continue;
1109 const reviewer = this.#agents.get(r.agent);
1110 if (!reviewer) continue;
1111 const title =
1112 rec?.note?.text ?? (rec?.kind === "draft" ? `draft ${rec.draft}` : (rec?.versions[0]?.message ?? ""));
1113 this.#queueNews(reviewer, [reviewItem(agent.name, id, title, r.files, version)], entries);
1117 /** After a version of shared: each open objection whose lines it took out tells its writer (#44). */
1118 #addressedNews(agent: AgentState, version: number, entries: Entry[]): void {
1119 for (const n of this.#notes.values()) {
1120 if (n.kind !== "objection" || n.closed || n.reply !== undefined || n.agent === agent.name) continue;
1121 if (this.#noteAnswer(n).state !== "addressed") continue;
1122 const writer = this.#agents.get(n.agent);
1123 if (writer) this.#queueNews(writer, [addressedItem(agent.name, version, n)], entries);
1127 /** Close a note: only its writer can (#44). */
1128 closeNote(agentName: string, id: number, how: unknown, time: number): NoteAnswer {
1129 return this.#closeNote(agentName, id, how, time);
1132 #closeNote(agentName: string, id: number, how: unknown, time: number, person?: PersonSender): NoteAnswer {
1133 return hostedCloseNote(this.#noteWriteHost, agentName, id, how, time, person);
1136 /** Notes, oldest first: on a file, on a change, or only the ones still open. */
1137 notes(...args: Tail<Parameters<typeof hostedNotes>>): ReturnType<typeof hostedNotes> {
1138 return hostedNotes(this.#notesHost, ...args);
1141 /** The change the newest of these lines was written in: its version's, or its author's current one if unpublished. */
1142 #changeOfLines(lines: readonly LineId[]): number | undefined {
1143 let newest: Atom | undefined;
1144 for (const l of lines) {
1145 const info = this.#graph.line(l);
1146 const atom = info && this.#graph.atom(info.atom);
1147 if (atom && (!newest || atom.seq > newest.seq)) newest = atom;
1149 if (!newest) return undefined;
1150 for (const space of [this.#shared, ...[...this.#spaces.values()].filter((s) => s.name !== SHARED)]) {
1151 const v = space.publishedIn.get(newest.id);
1152 if (v !== undefined) return this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${v}`);
1154 const author = this.#agents.get(newest.author);
1155 return author ? this.#currentChange(author, this.#now?.() ?? this.#lastTime) : undefined;
1158 #noteAnswer(n: NoteRecord): NoteAnswer {
1159 return hostedNoteAnswer(this.#notesHost, n);
1162 // The merge queue (#39) ------------------------------------------------------------
1164 /** Whether shared's avcs.json turns the merge queue on (`"queue": true`). */
1165 #queueOn(): boolean {
1166 return hostedQueueOn(this.#queueHost);
1169 /** With the queue on, nothing lands in shared unchecked; land and pluck don't go through the queue yet. */
1170 #notQueuedYet(what: string): void {
1171 hostedNotQueuedYet(this.#queueHost, what);
1174 /** Atoms of every queued publish, or only other agents' with `except`. */
1175 #queuedAtoms(except?: string): Set<AtomId> {
1176 return hostedQueuedAtoms(this.#queueHost, except);
1179 /** Queue the agent's publish (#39). */
1180 #enqueue(
1181 agent: AgentState,
1182 message: string,
1183 time: number,
1184 draft: readonly AtomId[],
1185 resolves: readonly AtomId[],
1186 entries: Entry[],
1187 ): PublishAnswer {
1188 return hostedEnqueue(this.#queueHost, agent, message, time, draft, resolves, entries);
1191 /** The merge queue now (#39): waiting publishes in order, and which are in the batch being checked. */
1192 queue(...args: Tail<Parameters<typeof hostedQueue>>): ReturnType<typeof hostedQueue> {
1193 return hostedQueue(this.#queueHost, ...args);
1196 /** Mark the first `n` queued publishes as the batch being checked (0 ends it). Not logged. */
1197 queueChecking(...args: Tail<Parameters<typeof hostedQueueChecking>>): ReturnType<typeof hostedQueueChecking> {
1198 return hostedQueueChecking(this.#queueHost, ...args);
1201 /** Shared with the first `n` queued publishes on top (#39): the files a batch's check runs on, and their tree hash. */
1202 queueCandidate(...args: Tail<Parameters<typeof hostedQueueCandidate>>): ReturnType<typeof hostedQueueCandidate> {
1203 return hostedQueueCandidate(this.#queueHost, ...args);
1206 /** The tree hash of a version of shared (#39): it equals a candidate's when that's what landed. */
1207 treeAt(version: number): string {
1208 const view = this.viewAt(version);
1209 return treeHash({ files: view.files(), modes: modesOf(view), blobs: view.blobs() });
1212 /**
1213 * Land the first `n` queued publishes (#39), in order, each as its own
1214 * version, after their batch passed. Each tells others what arrived, its
1215 * author that it landed, and the authors of what it settled what it kept.
1216 */
1217 queueLand(...args: Tail<Parameters<typeof hostedQueueLand>>): ReturnType<typeof hostedQueueLand> {
1218 return hostedQueueLand(this.#queueHost, ...args);
1221 /**
1222 * Take a queued publish out (#39): its check failed, or its author withdrew
1223 * it. Its changes are simply still in its author's draft. Later queued
1224 * publishes that build on its changes come out with it.
1225 */
1226 queuePull(...args: Tail<Parameters<typeof hostedQueuePull>>): ReturnType<typeof hostedQueuePull> {
1227 return hostedQueuePull(this.#queueHost, ...args);
1230 /** The agent withdraws its queued publishes (#39): refused while one is in the batch being checked. */
1231 unqueue(...args: Tail<Parameters<typeof hostedUnqueue>>): ReturnType<typeof hostedUnqueue> {
1232 return hostedUnqueue(this.#queueHost, ...args);
1235 /**
1236 * Correct the message of the agent's newest publish in its space (#27).
1237 * Only the message changes: shared only grows, so a version's changes are
1238 * fixed by publishing again (or dropping it). The log keeps the original.
1239 */
1240 amend(...args: Tail<Parameters<typeof hostedAmend>>): ReturnType<typeof hostedAmend> {
1241 return hostedAmend(this.#amendHost, ...args);
1244 /**
1245 * Put a label on a version of shared (the newest by default), or take it
1246 * off with `remove`. A label can mark many versions ("passed-ci"); a folder
1247 * follows the newest with `sync {label}`.
1248 */
1249 label(...args: Tail<Parameters<typeof hostedLabel>>): ReturnType<typeof hostedLabel> {
1250 return hostedLabel(this.#labelHost, ...args);
1253 /**
1254 * Drop published versions of shared (#10): a new shared version whose set
1255 * leaves out their changes. Later work that doesn't depend on them stays;
1256 * history keeps them. When later published work built on them, they are
1257 * refused with that work listed, unless `withDependents`, which drops it
1258 * too. Unpublished work that builds on them (an agent's draft, a named
1259 * draft not yet landed) always refuses it: drop never touches it.
1260 */
1261 drop(
1262 agentName: string,
1263 versions: readonly number[],
1264 message: string,
1265 time: number,
1266 options: { withDependents?: boolean } = {},
1267 ): DropAnswer {
1268 return hostedDrop(this.#dropHost, agentName, versions, message, time, options);
1271 /**
1272 * After a sync, merge files where the agent's draft and the newer work
1273 * collide, the way git merges a file (#25, Fuzzer): from the agent's old
1274 * base, its draft's text and the newer text. Changes both made identically
1275 * are kept once; changes on one side are kept. Only when every file
1276 * involved merges with no conflict are the draft's changes to them dropped
1277 * (a discard entry) and made again as the merged text. Otherwise nothing
1278 * changes, and the collision stands with both sides' lines in the file.
1279 */
1280 #mergeIdentical(
1281 agent: AgentState,
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare1282 before: ReadView,
init0Start the project1283 oldBase: ReadonlySet<AtomId>,
1284 oldVersion: number,
1285 time: number,
1286 entries: Entry[],
1287 ): MergedLine[] {
1288 return hostedMergeIdentical(this.#mergeHost, agent, before, oldBase, oldVersion, time, entries);
1291 /**
1292 * Names the agent's draft defines at the top level of a file where other
1293 * work defines them too, so they are defined twice there (#25, Fuzzer).
1294 */
1295 #duplicates(agent: AgentState): Collision[] {
1296 return duplicateCollisions(this.#collisionHost, agent);
1299 /**
1300 * Draft changes that build on atoms a set doesn't have (a drop took them
1301 * out): the files they touch. Those changes can't move onto that set.
1302 */
1303 #strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
1304 return strandedFiles(this.#graph, draft, set);
1307 /** Answer a refusal, and log it (an entry that changes nothing but the counts). */
1308 #refuse(...args: Tail<Parameters<typeof hostedRefuse>>): ReturnType<typeof hostedRefuse> {
1309 return hostedRefuse(this.#refuseHost, ...args);
1312 /**
1313 * Tell other agents something, as news: "Announcement from <agent>:
1314 * <text>". It reaches each one with its next edit, record or news call.
1315 * `to` names agents; without it, every other agent the project has now.
1316 */
1317 announce(...args: Tail<Parameters<typeof hostedAnnounce>>): ReturnType<typeof hostedAnnounce> {
1318 return hostedAnnounce(this.#announceHost, ...args);
1321 /**
1322 * A signed-in person's announcement from the website (#41). The Worker has
1323 * checked who sent it; the engine records it on each recipient's news with
1324 * `from`, and never makes the person an agent. The text is JSON-quoted, so
1325 * a line break in it can't pass for another item.
1326 */
1327 announcePerson(...args: Tail<Parameters<typeof hostedAnnouncePerson>>): ReturnType<typeof hostedAnnouncePerson> {
1328 return hostedAnnouncePerson(this.#announceHost, ...args);
1331 /**
1332 * Say what the agent is starting on (#37, #13), before any edit lands:
1333 * `text`, and the files it expects to change if it knows them. Nothing is
1334 * locked or refused. where and status show it until the agent publishes,
1335 * lands, or sends null. The answer names who already has unpublished
1336 * changes in, or a starting note on, those files; they hear of it too.
1337 */
1338 starting(...args: Tail<Parameters<typeof hostedStarting>>): ReturnType<typeof hostedStarting> {
1339 return hostedStarting(this.#startingHost, ...args);
1342 /** Every agent's starting note, by agent name. */
1343 startingNotes(): ReturnType<typeof hostedStartingNotes> {
1344 return hostedStartingNotes(this.#notesHost);
1347 #openCollisions(agent: AgentState): { collisions?: AgentStatus["collisions"] } {
1348 return hostedOpenCollisions(this.#markerHost, agent);
1351 /**
1352 * News when an edit leaves a file holding blocks of collision markers
1353 * (#11): how many, and how to settle them. Again whenever the count changes.
1354 */
1355 #markedNews(agent: AgentState, files: readonly string[], entries: Entry[]): void {
1356 const marked = new Set(this.#markedFiles(agent));
1357 const view = this.#agentView(agent);
1358 const items: NewsItem[] = [];
1359 for (const file of [...new Set(files)].sort()) {
1360 if (!marked.has(file) || !view.hasFile(file)) continue;
1361 const n = blocksIn(view.lines(file).map((l) => l.text)).length;
1362 if (n === 0) continue;
1363 items.push(markedItem(this.#draft(agent)[0] ?? "", file, n));
1365 this.#queueNews(agent, items, entries);
1368 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare1369 #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
init0Start the project1370 return hostedMarkersSettled(this.#markerHost, agent, view, atom);
1373 /** Files where a sync wrote the agent collision markers in its current space (#11). */
1374 #markedFiles(agent: AgentState): string[] {
1375 return hostedMarkedFiles(agent);
1378 /** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
1379 #markedCollisions(agent: AgentState): Collision[] {
1380 return hostedMarkedCollisions(this.#markerHost, agent);
1383 /**
1384 * Marker lines the agent's draft adds (#11), as collisions: each
1385 * well-formed block, and any marker line left outside one. Only the labeled
1386 * lines the engine writes count, so a document that shows markers can be
1387 * published.
1388 */
1389 #markerCollisions(agent: AgentState): Collision[] {
1390 return hostedMarkerCollisions(this.#markerHost, agent);
1393 /** One line of news for each other author whose marked collision a publish settled (#11): what was kept, and any lines lost. */
1394 #settledNews(agent: AgentState, version: number, settled: readonly Settled[], entries: Entry[]): void {
1395 for (const s of settled) {
1396 const other = this.#agents.get(s.theirs.agent);
1397 if (!other || other === agent) continue;
1398 this.#queueNews(other, [settledItem(agent.name, version, s)], entries);
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare1402 /**
1403 * The files the agent's unpublished changes touch, in its own view. Kept per agent under what they're
engine75Comments only: take issue numbers out of the engine's comments, so they read for anyone.Compare1404 * made of: its view's key and its draft. Most agents haven't moved since the last
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare1405 * status, and the view cache holds fewer views than a big project has agents, so working them out again
1406 * on every call cost about 0.5 s on abso. A copy goes out, so no caller can change what's kept.
1407 */
1408 #draftFiles(agent: AgentState): Set<string> {
1409 const key = `${this.#agentViewKey(agent)}|${this.#draft(agent).join(",")}`;
1410 let kept = this.#draftFilesKept.get(agent.name);
1411 if (kept?.key !== key) {
1412 kept = { key, files: hostedDraftFiles(this.#overlapHost, agent) };
1413 this.#draftFilesKept.set(agent.name, kept);
1415 return new Set(kept.files);
init0Start the project1416 }
1418 /** Other agents in the agent's space whose unpublished changes or starting note meet `patterns`. */
1419 #overlaps(...args: Tail<Parameters<typeof hostedOverlaps>>): ReturnType<typeof hostedOverlaps> {
1420 return hostedOverlaps(this.#overlapHost, ...args);
1423 /**
1424 * News the first time a draft touches a file someone else in its space has
infra-split37Comments and test names give each reason in plain words, without naming who raised it Notes like "(#37, Builder 5)" or "(AVCS - Security)" become "(#37)" or go, and a private commit hash after a name goes with it. Issue numbers and references such as git's CVE-2019-1353 stay. Only comments and test names change; no behavior changes.Compare1425 * unpublished changes in, or a starting note on (#37): one line per file and agent, once per draft. It tells; it never stops
init0Start the project1426 * the edit.
1427 */
1428 #overlapNews(...args: Tail<Parameters<typeof hostedOverlapNews>>): ReturnType<typeof hostedOverlapNews> {
1429 return hostedOverlapNews(this.#overlapHost, ...args);
1432 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
1433 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
1434 const entries: Entry[] = [];
1435 const agent = this.#agent(agentName, entries);
1436 const items = agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null }));
1437 const news = this.#takeNews(agent, entries);
1438 this.#flush(entries);
1439 return { news, items };
1442 /** Refused publishes and lands, newest first (`limit` defaults to 50), with counts over all of them. */
1443 refusals(...args: Tail<Parameters<typeof hostedRefusals>>): ReturnType<typeof hostedRefusals> {
1444 return hostedRefusals(this.#refuseHost, ...args);
1447 /**
1448 * Move the agent's base to its space's newest version. Returns every file
1449 * whose text in its view changes (null when it's gone), and the collisions
1450 * it now has to settle. A first sync returns every file (that's how a
1451 * folder joins).
1452 */
1453 sync(...args: Tail<Parameters<typeof hostedSync>>): ReturnType<typeof hostedSync> {
1454 return hostedSync(this.#syncHost, ...args);
1457 /**
1458 * Move the agent to a named draft, or back to shared with null. Its
1459 * unpublished changes stay parked on the server in the space it leaves,
1460 * and what it parked in the space it moves to comes back. Nothing is lost
1461 * and nothing has to be published or stashed first. A new named draft
1462 * starts on shared's newest version; with `carry`, the agent's current
1463 * unpublished changes move into it instead of being parked. Answers like a
1464 * sync: the files that change in its folder.
1465 */
1466 switchTo(...args: Tail<Parameters<typeof hostedSwitchTo>>): ReturnType<typeof hostedSwitchTo> {
1467 return hostedSwitchTo(this.#switchHost, ...args);
1470 /**
1471 * Move the agent's named draft onto shared's newest version. The draft's
1472 * agents see it when they next sync; anything it collides with is theirs
1473 * to settle before the draft lands.
1474 */
1475 syncDraft(agentName: string, time: number): DraftSyncAnswer {
1476 const entries: Entry[] = [];
1477 const agent = this.#agent(agentName, entries);
1478 const space = this.#namedSpaceOf(agent);
1479 const ownOnly = [...space.own].filter((id) => !this.#shared.own.has(id) && !this.#shared.droppedIn.has(id));
1480 const stranded = this.#strandedFiles(ownOnly, this.#shared.own);
1481 if (stranded.length > 0) {
1482 throw new ProjectError(
1483 "conflict",
1484 `draft ${space.name} has changes to ${stranded.join(", ")} that build on lines a drop took out of shared`,
1485 );
1487 if (sharedBaseOf(space) !== this.version) {
1488 entries.push({
1489 type: "space-sync",
1490 space: space.name,
1491 agent: agent.name,
1492 time,
1493 version: last(space) + 1,
1494 sharedBase: this.version,
1495 });
1496 this.#apply(entries[entries.length - 1]!);
1498 this.#flush(entries);
1499 return { draft: space.name, version: last(space), sharedBase: sharedBaseOf(space) };
1502 /**
1503 * Land the agent's named draft in shared as one unit: every change
1504 * published into it that shared doesn't have yet. Refused, like a publish,
1505 * when those changes collide with work that landed in shared after the
1506 * draft's base; sync the draft, settle, and land again.
1507 */
1508 land(...args: Tail<Parameters<typeof hostedLand>>): ReturnType<typeof hostedLand> {
1509 return hostedLand(this.#landHost, ...args);
1512 /**
1513 * What landing `changes` of a named draft would collide with in shared now (#41, the Drafts page reads it
1514 * too): the same pairs and definitions land refuses on.
1515 */
1516 #landCollisions(
1517 space: Space,
1518 changes: AtomId[],
1519 pick: boolean,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1520 ): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {
init0Start the project1521 return hostedLandCollisions(this.#landHost, space, changes, pick);
1524 /**
1525 * A named draft's state in one read (#41, the Drafts page, D3 and D16): the shared version it builds on and
1526 * how far behind shared that is, its versions, when its first edit was, who works in it, and what landing it
1527 * now would collide with (the same check land makes, so nothing is written).
1528 */
1529 draftState(...args: Tail<Parameters<typeof hostedDraftState>>): ReturnType<typeof hostedDraftState> {
1530 return hostedDraftState(this.#draftStateHost, ...args);
1533 #land(
1534 agent: AgentState,
1535 message: string,
1536 time: number,
1537 entries: Entry[],
1538 pick?: { space: Space; changes: AtomId[] },
1539 ): LandAnswer {
1540 return hostedLandDraft(this.#landHost, agent, message, time, entries, pick);
1543 /**
1544 * Take part of a named draft into shared (#27): the changes of some of its
1545 * versions, as one new version of shared, checked for collisions like a
1546 * land. When they build on other versions of the draft, those are listed
1547 * and it is refused, unless `withDependencies` takes them too. The draft
1548 * stays as it is; landing it later brings in only what's left.
1549 */
1550 pluck(
1551 agentName: string,
1552 draftName: string,
1553 versions: readonly number[],
1554 message: string,
1555 time: number,
1556 options: { withDependencies?: boolean } = {},
1557 ): PluckAnswer {
1558 return hostedPluck(this.#pluckHost, agentName, draftName, versions, message, time, options);
1561 /**
1562 * Take in commits a person pushed with plain git (demo moment 5, #5, #8).
1563 * `base` is the shared version their first commit builds on (the
1564 * `avcs-version` of the commit they cloned). Each commit gives its whole
1565 * tree as text; a file of the view missing from it is deleted. The commits
1566 * go into a named draft `git-<sha>` on that version, one publish each, and
1567 * the draft lands in shared at once if nothing collides. The push already
1568 * happened, so a collision isn't refused: the draft waits, with its
1569 * collisions listed, for someone to switch to it, settle and land it.
1570 */
1571 ingest(...args: Tail<Parameters<typeof hostedIngest>>): ReturnType<typeof hostedIngest> {
1572 return hostedIngest(this.#ingestHost, ...args);
1575 // Reading history, and discarding -------------------------------------------
1577 #checkVersion(space: Space, version: number): void {
1578 hostedCheckVersion(space, version);
1581 /**
1582 * Discard the agent's unpublished changes to some files (all of them with
1583 * `files` null), like git restore. Changes that touch only those files and
1584 * that no kept change builds on leave the draft; anything left over is
1585 * undone by a new change that puts the files back. Answers with each
1586 * file's text now, for the folder.
1587 */
1588 restore(...args: Tail<Parameters<typeof hostedRestore>>): ReturnType<typeof hostedRestore> {
1589 return hostedRestore(this.#restoreHost, ...args);
1592 /** The space options name: an agent's current space with `agent`, else the named draft, else shared. */
1593 #spaceFor(options: { draft?: string | null; agent?: string }): Space {
1594 if (options.agent !== undefined) {
1595 const agent = this.#agents.get(options.agent);
1596 if (!agent) throw new ProjectError("bad-request", `there is no agent ${JSON.stringify(options.agent)}`);
1597 return this.#spaceOf(agent);
1599 return this.#spaceNamed(options.draft ?? null);
1602 #spaceNamed(name: string | null): Space {
1603 const key = name === null ? SHARED : checkDraftName(name);
1604 const space = this.#spaces.get(key);
1605 if (!space) throw new ProjectError("bad-request", `there is no draft ${String(name)}`);
1606 return space;
1609 /**
1610 * The stored spelling a read means (#41, F7, the rule #49 set for writes):
1611 * the path itself, else the one file it matches by pathKey; failing that,
1612 * the one file ever in the view it matches, for a file since taken out.
1613 * A path that matches two files is answered exactly.
1614 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare1615 spellingIn(view: ReadView, path: string): string {
init0Start the project1616 if (view.hasFile(path)) return path;
1617 const key = pathKey(path);
1618 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
1619 if (live.length > 0) return live.length === 1 ? live[0]! : path;
1620 const known = view.knownPaths();
1621 if (known.includes(path)) return path;
1622 const gone = known.filter((p) => pathKey(p) === key);
1623 return gone.length === 1 ? gone[0]! : path;
1626 // Applying entries ------------------------------------------------------------
1628 #apply(entry: Entry): void {
infra-split37Comments and test names give each reason in plain words, without naming who raised it Notes like "(#37, Builder 5)" or "(AVCS - Security)" become "(#37)" or go, and a private commit hash after a name goes with it. Issue numbers and references such as git's CVE-2019-1353 stay. Only comments and test names change; no behavior changes.Compare1629 // Entries written before #41 have no time on these kinds; new ones do, so replay can place them.
init0Start the project1630 const kept =
1631 this.#loading || !UNTIMED.has(entry.type) || "time" in entry ? entry : ({ ...entry, time: Date.now() } as Entry);
1632 if (!this.#loading) this.#pending.push(kept);
1633 const at = this.#loading ? this.#stored : this.#stored + this.#pending.length - 1;
1634 // Positions by time (#41, the website): the newest time up to each position, as the log holds it.
1635 const keptTime =
1636 kept.type === "draft" ? kept.atom.time : "time" in kept && typeof kept.time === "number" ? kept.time : undefined;
1637 const prior = at > 0 ? this.#timeAt[at - 1]! : 0;
1638 this.#timeAt[at] = keptTime !== undefined && keptTime > prior ? keptTime : prior;
1639 const versionsBefore = this.#spaces.get(SHARED)?.versions.length ?? 0;
1640 try {
1641 this.#applyEntry(entry, at, keptTime);
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare1642 // Shared's closure, kept per version on disk (abso Capacity): after the entry, since its atoms join the graph after
1643 // its membership.
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare1644 if (this.#writerStorage && (this.#spaces.get(SHARED)?.versions.length ?? 0) > versionsBefore) {
1645 const shared = this.#spaces.get(SHARED)!;
1646 const storage = this.#writerStorage;
1647 indexClosure(storage, shared, this.#graph);
1648 // Each new version's changed files, from what it touched (version-files.ts): kept in the shapes table when
1649 // the host gives one, so the log, a path's history and the tree never lay versions out to find them.
1650 const host: VersionFilesHost = {
1651 storage,
1652 graph: this.#graph,
1653 at: (v) => this.#at(shared, v),
1654 viewAt: (v) => this.#viewAt(shared, v),
1655 empty: () => new View(this.#graph, []),
1656 closureChangedAt: (v) => closureChangedAt(storage, v),
1657 };
1658 for (let v = versionsBefore; v < shared.versions.length; v++) {
1659 const { files, exists } = keptVersionFiles(host, shared.versions[v]!);
1660 this.#paths.keep(shared, v, files, v === 0 ? host.empty() : host.viewAt(v - 1), host.viewAt(v), exists);
init0Start the project1663 } finally {
1664 // Positions by version: where each version of shared was made.
1665 const versionsAfter = this.#spaces.get(SHARED)?.versions.length ?? 0;
1666 for (let v = versionsBefore; v < versionsAfter; v++) this.#versionAt[v] = at;
1670 /**
1671 * The log position for a time or a version of shared (#41, the website):
1672 * for `time`, the position just after the last entry no later than it
1673 * (entries with no time take their predecessor's); for `version`, the
1674 * position just after the entry that made it. `end` is the log's length.
1675 */
1676 position(q: { time?: number; version?: number }): { position: number; end: number } {
1677 const end = this.#timeAt.length;
1678 if (q.version !== undefined) {
1679 if (!Number.isInteger(q.version) || q.version < 0 || q.version >= this.#versionAt.length)
1680 throw new ProjectError("not-found", `there is no version ${String(q.version)}`);
1681 return { position: this.#versionAt[q.version]! + 1, end };
1683 if (typeof q.time !== "number" || !Number.isFinite(q.time))
1684 throw new ProjectError("bad-request", "position needs ?time= or ?version=");
1685 // The newest time up to each position never goes down, so halve.
1686 let lo = 0;
1687 let hi = end;
1688 while (lo < hi) {
1689 const mid = (lo + hi) >> 1;
1690 if (this.#timeAt[mid]! <= q.time) lo = mid + 1;
1691 else hi = mid;
1693 return { position: lo, end };
1696 #applyEntry(entry: Entry, at: number, time: number | undefined): void {
1697 hostedApplyEntry(this.#applyEntryHost, entry, at, time);
1700 /** Apply entries and store them. */
1701 #commit(entries: Entry[]): void {
1702 for (const e of entries) this.#apply(e);
1703 this.#flush(entries);
1706 /** Store entries that are already applied. */
1707 #flush(_entries: readonly Entry[]): void {
1708 if (this.#pending.length === 0) return;
1709 const out = this.#pending;
1710 this.#store.append(out);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1711 this.#persistMutable();
init0Start the project1712 this.#pending = [];
1713 this.#stored += out.length;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1714 this.#writeCheckpoint();
init0Start the project1715 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1717 #writeCheckpoint(): void {
1718 this.#writerStorage?.write("project:meta", "checkpoint", {
1719 format: 1,
1720 logLength: this.#stored,
1721 atoms: this.#graph.size,
1722 version: this.version,
1723 });
1726 #persistMutable(): void {
1727 if (!this.#writerStorage) return;
1728 if (this.#agents instanceof WriterAgents) this.#agents.flush();
1729 this.#writerStorage.write("project:meta", "mods", this.#mods);
1730 this.#writerStorage.write("project:meta", "queue", this.#queue);
1731 this.#writerStorage.write(
1732 "project:meta",
1733 "tells",
1734 [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1735 );
init0Start the project1738 /**
1739 * The agent an entry names. Before every applied entry was stored, a call
1740 * that joined an agent and then threw could leave the join out of the log
1741 * while later entries named the agent. The lost join had the version the
1742 * project was at then, which is the version now, during replay.
1743 */
1744 #agentOf(name: string): AgentState {
1745 let agent = this.#agents.get(name);
1746 if (!agent) {
1747 this.#apply({ type: "join", agent: name, version: this.#shared.versions.length - 1 });
1748 agent = this.#agents.get(name)!;
1750 return agent;
1753 // Agents, spaces and views ----------------------------------------------------
1755 get #shared(): Space {
1756 return this.#spaces.get(SHARED)!;
1759 #needInit(): void {
1760 if (!this.initialized) throw new ProjectError("not-initialized", "the project has no files yet; init it first");
1763 #agent(name: string, entries: Entry[]): AgentState {
1764 this.#needInit();
1765 if (typeof name !== "string" || !NAME.test(name) || name === "init") {
1766 throw new ProjectError(
1767 "bad-agent",
1768 `bad agent name ${JSON.stringify(name)}: letters, digits, '.', '_' and '-', up to 64`,
1769 );
1771 let agent = this.#agents.get(name);
1772 if (!agent) {
1773 const join: Entry = { type: "join", agent: name, version: this.version };
1774 entries.push(join);
1775 this.#apply(join);
1776 agent = this.#agents.get(name)!;
1778 return agent;
1781 #spaceOf(agent: AgentState): Space {
1782 return this.#spaces.get(agent.space)!;
1785 #namedSpaceOf(agent: AgentState): Space {
1786 if (agent.space === SHARED) {
1787 throw new ProjectError("bad-request", `${agent.name} works in shared, not a named draft; switch to one first`);
1789 return this.#spaceOf(agent);
1792 // History reads (#41), in history.ts behind HistoryHost (#46, disk-first 1) ------------------------
1794 #host?: HistoryHost;
1795 /** The project as the history reads see it: the seam the derived tables plug into (abso issues 48, 79). */
1796 get #history(): HistoryHost {
1797 this.#host ??= {
1798 graph: this.#graph,
1799 agents: this.#agents,
1800 spaces: this.#spaces,
1801 needInit: () => this.#needInit(),
1802 spaceNamed: (name) => this.#spaceNamed(name),
1803 checkVersion: (space, version) => this.#checkVersion(space, version),
1804 viewAt: (space, version) => this.#viewAt(space, version),
capacity217tree lists a version's files from the kept shapes, as pathsAt does since 216 (disk-first 2; abso Capacity). The tree at a version laid out every file only to list them. Not for an agent's tree, whose view has its draft on top. On abso's export the tree at head went from over 60 s to 225 ms (replay takes 41 s), and the tree at 612 takes 156 ms, both matching Project.load. version-files.test.ts now also checks the tree at every version against the in-memory project. Named tests: version-files, files-reads, project, draft-reads-stored, named-drafts (38 of 38); tsc clean.Compare1805 keptPaths: (space, version) => this.#keptPaths(space, version),
capacity251Author totals: each shared file's lines by author and its size, kept as versions land, so tree with authors reads them instead of laying every file out (abso Capacity, issue 664; docs/disk-first-2.md; Security yes on ask 2096). version-files.ts keeps, beside the head line counts, each file's totals at the newest version (head-authors) and at every version that changed them (author-totals), from version 0 on and only while every version since has kept them. A version on the fast path adds each inserted visible line to its author and takes each deleted one off its writer's, with its UTF-8 bytes and newline (joinLines). A version with moves, drops or a closure change counts every touched file from its layout, so a line rewritten with the same text by someone else still moves its author. Shared only; a draft's view takes its base's totals for the files the draft doesn't touch (touchedBeyond) and lays out the rest, and a named draft never reads them. Kept in the writer's state, so whatever replaces or clears it (a new adoption, a restore, a live drop) takes them too. A writer adopted before this keeps none and lays out as before. On a fresh abso adoption (my machine): tree with authors at 1224 takes 333 ms first and 50 ms again (11 to 16 s and 1.8 to 2.4 s before); an agent's tree with authors 619 ms again (2 to 3.4 s). Adoption 7.2 min, the same as before. A full run matches 33 of 33 answers. Test: author-totals.test.ts, tree with authors at every version and in every agent's view, the stored writer against the in-memory project: moved lines, a rename by record and by move, a drop, a binary file, text beyond ASCII, drafts that edit, move lines or have nothing. With the path, move, drop, draft, adoption and version-files tests: 47 of 47.Compare1806 authorTotals: (space, version, agent) => this.#authorTotals(space, version, agent as AgentState | undefined),
capacity252Folder blame from author totals; an agent's tree compares only its draft's files; file lists without a full walk; one space object per stored row (abso Capacity, issue 664). - Folder blame counts each file's kept author totals where they answer (Project.authorTotalsFor: shared at a version, or an agent's view for the files its draft doesn't touch), and lays out the rest as before. - An agent's tree marked a file changed by comparing it in both views, which laid every file out twice (13 s of 14.6 s on abso). Only a file the draft touches can differ from its base (touchedBeyond, as the view's layout sharing uses), so only those are compared; a draft that moves lines compares every file as before. - View.paths: a draft's view over its base's takes the base's file list and checks only the files its draft touches; a published version's view answers from its kept file list. Both walked every file the graph ever had. - PathIndex.keptPathSet works an older version's file list back from the newest one (undoing each version's made and gone files), and keeps a few, instead of folding from version 0 again for every agent's base. - Membership's stored spaces decode to the same object for the same stored row. A space reads everything else through to storage; a new object on every read emptied every cache kept by space (the path index, versions' files and shapes, the kept file lists) on every call. On a fresh abso adoption (my machine): an agent's tree with authors 582 ms first and 762 ms again (12.5 s and 0.6 to 1.5 s before); folder blame for an agent 404 ms and 248 ms (1.8 s and 2.0 s); tree with authors at 1224 again 19 ms. A full run matches 33 of 33 answers; held heap at most 40.2 MB. Tests: author-totals now also compares folder blame at every version and in every agent's view, against the in-memory project. All of worker/project/test: 349 of 349 pass (one skipped).Compare1807 agentTouched: (agent) => this.#agentTouched(agent as AgentState),
init0Start the project1808 agentView: (agent) => this.#agentView(agent as AgentState),
1809 spellingIn: (view, asked) => this.spellingIn(view, asked),
1810 pathsOf: (space) => this.#paths.pathsOf(space),
1811 lastChange: (space, version) => this.#paths.lastChange(space, version),
1812 atOrBefore: (list, version) => PathIndex.atOrBefore(list, version),
1813 removedIn: (space, from, to, line) => this.#paths.removedIn(space, from, to, line),
1814 };
1815 return this.#host;
capacity217tree lists a version's files from the kept shapes, as pathsAt does since 216 (disk-first 2; abso Capacity). The tree at a version laid out every file only to list them. Not for an agent's tree, whose view has its draft on top. On abso's export the tree at head went from over 60 s to 225 ms (replay takes 41 s), and the tree at 612 takes 156 ms, both matching Project.load. version-files.test.ts now also checks the tree at every version against the in-memory project. Named tests: version-files, files-reads, project, draft-reads-stored, named-drafts (38 of 38); tsc clean.Compare1818 /** Shared's file list from kept shapes on a stored writer, where a version's layout reads its files from disk. */
1819 #keptPaths(space: Space, version: number): string[] | undefined {
1820 return this.#writerStorage && space.name === SHARED ? this.#paths.keptPaths(space, version) : undefined;
capacity251Author totals: each shared file's lines by author and its size, kept as versions land, so tree with authors reads them instead of laying every file out (abso Capacity, issue 664; docs/disk-first-2.md; Security yes on ask 2096). version-files.ts keeps, beside the head line counts, each file's totals at the newest version (head-authors) and at every version that changed them (author-totals), from version 0 on and only while every version since has kept them. A version on the fast path adds each inserted visible line to its author and takes each deleted one off its writer's, with its UTF-8 bytes and newline (joinLines). A version with moves, drops or a closure change counts every touched file from its layout, so a line rewritten with the same text by someone else still moves its author. Shared only; a draft's view takes its base's totals for the files the draft doesn't touch (touchedBeyond) and lays out the rest, and a named draft never reads them. Kept in the writer's state, so whatever replaces or clears it (a new adoption, a restore, a live drop) takes them too. A writer adopted before this keeps none and lays out as before. On a fresh abso adoption (my machine): tree with authors at 1224 takes 333 ms first and 50 ms again (11 to 16 s and 1.8 to 2.4 s before); an agent's tree with authors 619 ms again (2 to 3.4 s). Adoption 7.2 min, the same as before. A full run matches 33 of 33 answers. Test: author-totals.test.ts, tree with authors at every version and in every agent's view, the stored writer against the in-memory project: moved lines, a rename by record and by move, a drop, a binary file, text beyond ASCII, drafts that edit, move lines or have nothing. With the path, move, drop, draft, adoption and version-files tests: 47 of 47.Compare1822
1823 /**
1824 * Each file's kept author totals for tree with authors (version-files.ts), on a stored writer and for shared only. An
1825 * agent's view takes its base's totals for every file its draft doesn't touch, as its layout does (touchedBeyond),
1826 * and lays out the rest; a draft that moves lines lays out everything.
1827 */
1828 #authorTotals(
1829 space: Space,
1830 version: number,
1831 agent?: AgentState,
1832 ): ((path: string) => FileTotals | undefined) | undefined {
1833 const storage = this.#writerStorage;
1834 if (!storage || space.name !== SHARED || authoredVersion(storage) === undefined) return undefined;
capacity252Folder blame from author totals; an agent's tree compares only its draft's files; file lists without a full walk; one space object per stored row (abso Capacity, issue 664). - Folder blame counts each file's kept author totals where they answer (Project.authorTotalsFor: shared at a version, or an agent's view for the files its draft doesn't touch), and lays out the rest as before. - An agent's tree marked a file changed by comparing it in both views, which laid every file out twice (13 s of 14.6 s on abso). Only a file the draft touches can differ from its base (touchedBeyond, as the view's layout sharing uses), so only those are compared; a draft that moves lines compares every file as before. - View.paths: a draft's view over its base's takes the base's file list and checks only the files its draft touches; a published version's view answers from its kept file list. Both walked every file the graph ever had. - PathIndex.keptPathSet works an older version's file list back from the newest one (undoing each version's made and gone files), and keeps a few, instead of folding from version 0 again for every agent's base. - Membership's stored spaces decode to the same object for the same stored row. A space reads everything else through to storage; a new object on every read emptied every cache kept by space (the path index, versions' files and shapes, the kept file lists) on every call. On a fresh abso adoption (my machine): an agent's tree with authors 582 ms first and 762 ms again (12.5 s and 0.6 to 1.5 s before); folder blame for an agent 404 ms and 248 ms (1.8 s and 2.0 s); tree with authors at 1224 again 19 ms. A full run matches 33 of 33 answers; held heap at most 40.2 MB. Tests: author-totals now also compares folder blame at every version and in every agent's view, against the in-memory project. All of worker/project/test: 349 of 349 pass (one skipped).Compare1835 if (!agent) return (path) => authorTotalsAt(storage, path, version);
1836 const except = this.#agentTouched(agent);
capacity251Author totals: each shared file's lines by author and its size, kept as versions land, so tree with authors reads them instead of laying every file out (abso Capacity, issue 664; docs/disk-first-2.md; Security yes on ask 2096). version-files.ts keeps, beside the head line counts, each file's totals at the newest version (head-authors) and at every version that changed them (author-totals), from version 0 on and only while every version since has kept them. A version on the fast path adds each inserted visible line to its author and takes each deleted one off its writer's, with its UTF-8 bytes and newline (joinLines). A version with moves, drops or a closure change counts every touched file from its layout, so a line rewritten with the same text by someone else still moves its author. Shared only; a draft's view takes its base's totals for the files the draft doesn't touch (touchedBeyond) and lays out the rest, and a named draft never reads them. Kept in the writer's state, so whatever replaces or clears it (a new adoption, a restore, a live drop) takes them too. A writer adopted before this keeps none and lays out as before. On a fresh abso adoption (my machine): tree with authors at 1224 takes 333 ms first and 50 ms again (11 to 16 s and 1.8 to 2.4 s before); an agent's tree with authors 619 ms again (2 to 3.4 s). Adoption 7.2 min, the same as before. A full run matches 33 of 33 answers. Test: author-totals.test.ts, tree with authors at every version and in every agent's view, the stored writer against the in-memory project: moved lines, a rename by record and by move, a drop, a binary file, text beyond ASCII, drafts that edit, move lines or have nothing. With the path, move, drop, draft, adoption and version-files tests: 47 of 47.Compare1837 if (!except) return undefined;
1838 return (path) => (except.has(path) ? undefined : authorTotalsAt(storage, path, version));
capacity252Folder blame from author totals; an agent's tree compares only its draft's files; file lists without a full walk; one space object per stored row (abso Capacity, issue 664). - Folder blame counts each file's kept author totals where they answer (Project.authorTotalsFor: shared at a version, or an agent's view for the files its draft doesn't touch), and lays out the rest as before. - An agent's tree marked a file changed by comparing it in both views, which laid every file out twice (13 s of 14.6 s on abso). Only a file the draft touches can differ from its base (touchedBeyond, as the view's layout sharing uses), so only those are compared; a draft that moves lines compares every file as before. - View.paths: a draft's view over its base's takes the base's file list and checks only the files its draft touches; a published version's view answers from its kept file list. Both walked every file the graph ever had. - PathIndex.keptPathSet works an older version's file list back from the newest one (undoing each version's made and gone files), and keeps a few, instead of folding from version 0 again for every agent's base. - Membership's stored spaces decode to the same object for the same stored row. A space reads everything else through to storage; a new object on every read emptied every cache kept by space (the path index, versions' files and shapes, the kept file lists) on every call. On a fresh abso adoption (my machine): an agent's tree with authors 582 ms first and 762 ms again (12.5 s and 0.6 to 1.5 s before); folder blame for an agent 404 ms and 248 ms (1.8 s and 2.0 s); tree with authors at 1224 again 19 ms. A full run matches 33 of 33 answers; held heap at most 40.2 MB. Tests: author-totals now also compares folder blame at every version and in every agent's view, against the in-memory project. All of worker/project/test: 349 of 349 pass (one skipped).Compare1839 }
1841 /**
1842 * The files an agent's draft, and whatever it depends on beyond its base, can make differ from its base
1843 * (touchedBeyond); every other file is the same in both. Undefined when the draft moves lines.
1844 */
1845 #agentTouched(agent: AgentState): ReadonlySet<string> | undefined {
1846 if (agent.mine.length === 0) return new Set();
1847 const base = this.#viewAt(this.#spaceOf(agent), agent.base);
1848 return touchedBeyond(this.#graph, base.set, agent.mine, [base, this.#agentView(agent)]);
capacity251Author totals: each shared file's lines by author and its size, kept as versions land, so tree with authors reads them instead of laying every file out (abso Capacity, issue 664; docs/disk-first-2.md; Security yes on ask 2096). version-files.ts keeps, beside the head line counts, each file's totals at the newest version (head-authors) and at every version that changed them (author-totals), from version 0 on and only while every version since has kept them. A version on the fast path adds each inserted visible line to its author and takes each deleted one off its writer's, with its UTF-8 bytes and newline (joinLines). A version with moves, drops or a closure change counts every touched file from its layout, so a line rewritten with the same text by someone else still moves its author. Shared only; a draft's view takes its base's totals for the files the draft doesn't touch (touchedBeyond) and lays out the rest, and a named draft never reads them. Kept in the writer's state, so whatever replaces or clears it (a new adoption, a restore, a live drop) takes them too. A writer adopted before this keeps none and lays out as before. On a fresh abso adoption (my machine): tree with authors at 1224 takes 333 ms first and 50 ms again (11 to 16 s and 1.8 to 2.4 s before); an agent's tree with authors 619 ms again (2 to 3.4 s). Adoption 7.2 min, the same as before. A full run matches 33 of 33 answers. Test: author-totals.test.ts, tree with authors at every version and in every agent's view, the stored writer against the in-memory project: moved lines, a rename by record and by move, a drop, a binary file, text beyond ASCII, drafts that edit, move lines or have nothing. With the path, move, drop, draft, adoption and version-files tests: 47 of 47.Compare1849 }
capacity217tree lists a version's files from the kept shapes, as pathsAt does since 216 (disk-first 2; abso Capacity). The tree at a version laid out every file only to list them. Not for an agent's tree, whose view has its draft on top. On abso's export the tree at head went from over 60 s to 225 ms (replay takes 41 s), and the tree at 612 takes 156 ms, both matching Project.load. version-files.test.ts now also checks the tree at every version against the in-memory project. Named tests: version-files, files-reads, project, draft-reads-stored, named-drafts (38 of 38); tsc clean.Compare1850
capacity252Folder blame from author totals; an agent's tree compares only its draft's files; file lists without a full walk; one space object per stored row (abso Capacity, issue 664). - Folder blame counts each file's kept author totals where they answer (Project.authorTotalsFor: shared at a version, or an agent's view for the files its draft doesn't touch), and lays out the rest as before. - An agent's tree marked a file changed by comparing it in both views, which laid every file out twice (13 s of 14.6 s on abso). Only a file the draft touches can differ from its base (touchedBeyond, as the view's layout sharing uses), so only those are compared; a draft that moves lines compares every file as before. - View.paths: a draft's view over its base's takes the base's file list and checks only the files its draft touches; a published version's view answers from its kept file list. Both walked every file the graph ever had. - PathIndex.keptPathSet works an older version's file list back from the newest one (undoing each version's made and gone files), and keeps a few, instead of folding from version 0 again for every agent's base. - Membership's stored spaces decode to the same object for the same stored row. A space reads everything else through to storage; a new object on every read emptied every cache kept by space (the path index, versions' files and shapes, the kept file lists) on every call. On a fresh abso adoption (my machine): an agent's tree with authors 582 ms first and 762 ms again (12.5 s and 0.6 to 1.5 s before); folder blame for an agent 404 ms and 248 ms (1.8 s and 2.0 s); tree with authors at 1224 again 19 ms. A full run matches 33 of 33 answers; held heap at most 40.2 MB. Tests: author-totals now also compares folder blame at every version and in every agent's view, against the in-memory project. All of worker/project/test: 349 of 349 pass (one skipped).Compare1851 /**
1852 * Kept author totals for a folder's blame (blame.ts), where blame reads: shared at a version (the newest by default) or
1853 * an agent's view. A named draft has none. Undefined when none are kept.
1854 */
1855 authorTotalsFor(where: {
1856 version?: number;
1857 draft?: string;
1858 agent?: string;
1859 }): ((path: string) => FileTotals | undefined) | undefined {
1860 if (where.draft !== undefined) return undefined;
1861 if (where.agent !== undefined) {
1862 const agent = this.#agents.get(where.agent);
1863 return agent ? this.#authorTotals(this.#spaceOf(agent), agent.base, agent) : undefined;
1865 return this.#authorTotals(this.#shared, where.version ?? last(this.#shared));
init0Start the project1868 /** One folder at a version (history.ts). */
1869 tree(...args: Tail<Parameters<typeof historyTree>>): ReturnType<typeof historyTree> {
1870 return historyTree(this.#history, ...args);
1873 /** A path's life at a version (history.ts). */
1874 pathLife(...args: Tail<Parameters<typeof historyPathLife>>): ReturnType<typeof historyPathLife> {
1875 return historyPathLife(this.#history, ...args);
1878 /** Where lines went after a version (history.ts). */
1879 follow(...args: Tail<Parameters<typeof historyFollow>>): ReturnType<typeof historyFollow> {
1880 return historyFollow(this.#history, ...args);
1883 // The version list (log, ribbon, show), in version-log.ts behind LogHost ----------------------------
1885 #logs?: LogHost;
1886 get #logHost(): LogHost {
1887 this.#logs ??= {
1888 graph: this.#graph,
1889 paths: this.#paths,
1890 labels: this.#labels,
1891 shared: () => this.#shared,
1892 needInit: () => this.#needInit(),
1893 spaceFor: (options) => this.#spaceFor(options),
1894 checkVersion: (space, version) => this.#checkVersion(space, version),
1895 viewAt: (space, version) => this.#viewAt(space, version),
1896 view: (set) => this.#view(set),
1897 at: (space, version) => this.#at(space, version),
1898 spellingIn: (view, path) => this.spellingIn(view, path),
1899 versionChange: (space, version) =>
1900 this.#versionChange.get(`${space.name === SHARED ? "" : space.name} ${version}`),
1901 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1902 };
1903 return this.#logs;
1906 /** The versions of shared (or of a named draft), newest first (version-log.ts). */
1907 log(...args: Tail<Parameters<typeof versionLog>>): ReturnType<typeof versionLog> {
1908 return versionLog(this.#logHost, ...args);
1911 /** Shared's versions in one small answer, for the website's version ribbon (version-log.ts). */
1912 ribbon(): ReturnType<typeof versionRibbon> {
1913 return versionRibbon(this.#logHost);
1916 /** One version of shared (or of a named draft) and the files it changed (version-log.ts). */
1917 show(...args: Tail<Parameters<typeof versionShow>>): ReturnType<typeof versionShow> {
1918 return versionShow(this.#logHost, ...args);
1921 /** A file as it was at a version of shared (or a named draft) (version-log.ts). */
1922 fileAt(...args: Tail<Parameters<typeof versionFileAt>>): ReturnType<typeof versionFileAt> {
1923 return versionFileAt(this.#logHost, ...args);
1926 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
1927 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
1928 return versionCompare(this.#logHost, ...args);
capacity244compare keeps its own answer type; the summary is compareSummary (abso issue 680; abso Capacity). 243 gave compare one answer type for both shapes, full and summary. abso's own callers read compare(...).files as file changes (worker/src/engine-project.ts, scripts/versions-check.ts, test/versions.test.ts), and the union broke their types, which showed when I pinned 243 into abso. Core's own tests didn't catch it. - version-log.ts: compared() works out the files and both views; compare answers {from, to, files: FileChange[]} as before 243, and compareSummary answers {from, to, summary: true, files}. Project.compareSummary calls it. - server/src/engine-project.ts: compare(..., summary) calls compareSummary when summary is set. http.ts and ProjectHistory are unchanged from 243 (?summary=1, a fifth argument). - compare-summary.test.ts calls compareSummary. Answers are the same as 243's. Every engine test (292 of 292), every worker/project test (342 of 342); tsc (worker and server) and biome clean.Compare1929 }
1931 /** compare as each file's size and SHA-256, not its texts (version-log.ts, abso issue 680). */
1932 compareSummary(...args: Tail<Parameters<typeof versionCompareSummary>>): ReturnType<typeof versionCompareSummary> {
1933 return versionCompareSummary(this.#logHost, ...args);
candidates186Read a version of shared without some earlier versions: abso show <N> --without A,B shows what differs and abso export <dir> --version N --without A,B writes the files. The server's GET without?version=&versions= checks the set left exactly as asked: when a version it keeps builds on one left out, it refuses with that chain, the files and the wider set that works, and never widens it. Atoms keep their ids and authors; shared and its log don't change; the same ask gives the same tree hash.Compare1934 }
1936 /** A version of shared without some earlier versions, or the refusal naming what builds on them (without.ts). */
1937 without(version: number, versions: readonly number[]): ReturnType<typeof hostedWithout> {
1938 const host: WithoutHost = {
1939 graph: this.#graph,
1940 shared: () => this.#shared,
1941 needInit: () => this.#needInit(),
1942 checkVersion: (space, v) => this.#checkVersion(space, v),
1943 viewAt: (space, v) => this.#viewAt(space, v),
1944 at: (space, v) => this.#at(space, v),
1945 closed: (set) => this.#closed(set),
1946 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1947 };
1948 return hostedWithout(host, version, versions);
init0Start the project1949 }
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare1951 /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
init0Start the project1952 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
1953 return versionViewAt(this.#logHost, ...args);
1956 // Whether agents' drafts would collide, in draft-collisions.ts behind DraftCollisionHost -------------
1958 #draftCollisionHost?: DraftCollisionHost;
1959 get #draftCollisions(): DraftCollisionHost {
1960 this.#draftCollisionHost ??= {
1961 graph: this.#graph,
1962 agents: this.#agents,
1963 needInit: () => this.#needInit(),
1964 shared: () => this.#shared,
1965 sharedView: () => this.#sharedView(),
1966 definitionRule: () => this.#definitionRule,
1967 draft: (agent) => this.#draft(agent as AgentState),
1968 agentView: (agent) => this.#agentView(agent as AgentState),
capacity246Collisions step 2: shared with drafts on top is a kept view that borrows shared's layouts (abso Capacity, issue 664). Draft collisions asked for shared now with one agent's draft on top (and with two agents' for a name both define) as a fresh view each call, laid out from scratch. Project's draftsView keeps it under shared's version and the drafts' atoms, so it changes with any draft change, a dropped draft or shared moving. It is laid out as shared is for every file the drafts don't touch, as an agent's view is (shareFiles, touchedBeyond). One agent based on shared's newest version is just its own view. On the abso export (my machine): a warm collisions call takes 6.3 s instead of 7.7 s, with 45 layouts instead of 80. Same answer as replay. A full warm run's heap is 76.9 MB against 76.5 MB on 244, so borrowing adds nothing. test/collisions-kept-views.test.ts: a writer against the in-memory project, each answer asked twice, through drafts with definition and duplicate collisions, after a draft changes, after shared moves on and after a draft is dropped. The collision, path and move tests pass (35 of 35).Compare1969 draftsView: (agents) => this.#draftsView(agents as readonly AgentState[]),
init0Start the project1970 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
capacity249Collisions step 3: each draft's definition work kept between calls, under a hard 4 MB budget (abso Capacity, issue 664). KeptParts (kept-parts.ts) holds what draft collisions work out about each draft and each pair of drafts: the names a draft's new lines use, the definitions a draft's changes touch before and after (the changed-definition rule), and the names two drafts both define in a file. Each entry is weighed as the view cache weighs views (line ids, texts, names: view.ts's stringBytes) and the whole stays under 4 MB, oldest out first; an entry over the budget isn't kept. Keys name everything an entry depends on: shared's version, the draft's base and its atoms. Each collisions call drops every entry it didn't use, so a draft that changes, an agent that leaves or shared moving on drops theirs at once. On a stored writer only; the publish check (land.ts) and the in-memory project work as before. On the abso export (my machine): a warm collisions call takes 322 ms instead of 3.4 s, with the same answer as replay. A full warm run's held heap is at most 42.9 MB (41.7 MB without it), and all 33 answers match. Tests: kept-parts (new: the budget, oldest out first, an oversized entry never kept, a round dropping what it didn't use) and collisions-kept-views, which now runs through the kept parts on the writer (a draft changing, shared moving on, a draft dropped, each asked twice against the in-memory project). With the collision, definition, path and view tests: 47 of 47.Compare1971 // On a stored writer only, as a reader kept between calls is (abso Capacity).
1972 keptParts: () => (this.#writerStorage ? (this.#keptParts ??= new KeptParts()) : undefined),
1973 draftKey: (agent) => {
1974 const a = agent as AgentState;
1975 return `${last(this.#shared)} ${a.space}@${a.base} ${this.#draft(a).join(",")}`;
1976 },
init0Start the project1977 };
1978 return this.#draftCollisionHost;
capacity246Collisions step 2: shared with drafts on top is a kept view that borrows shared's layouts (abso Capacity, issue 664). Draft collisions asked for shared now with one agent's draft on top (and with two agents' for a name both define) as a fresh view each call, laid out from scratch. Project's draftsView keeps it under shared's version and the drafts' atoms, so it changes with any draft change, a dropped draft or shared moving. It is laid out as shared is for every file the drafts don't touch, as an agent's view is (shareFiles, touchedBeyond). One agent based on shared's newest version is just its own view. On the abso export (my machine): a warm collisions call takes 6.3 s instead of 7.7 s, with 45 layouts instead of 80. Same answer as replay. A full warm run's heap is 76.9 MB against 76.5 MB on 244, so borrowing adds nothing. test/collisions-kept-views.test.ts: a writer against the in-memory project, each answer asked twice, through drafts with definition and duplicate collisions, after a draft changes, after shared moves on and after a draft is dropped. The collision, path and move tests pass (35 of 35).Compare1979 }
1981 /**
1982 * Shared now with some agents' drafts on top, for draft collisions (abso Capacity). Kept under the drafts' atoms and
1983 * shared's version, so a second ask with nothing changed lays nothing out again, and laid out as shared is for every
1984 * file the drafts don't touch, as an agent's view is. One agent based on shared's newest version is its own view.
1985 */
1986 #draftsView(agents: readonly AgentState[]): ReadView {
1987 const shared = this.#shared;
1988 const version = last(shared);
1989 const only = agents.length === 1 ? agents[0]! : undefined;
1990 if (only && only.space === SHARED && only.base === version) return this.#agentView(only);
1991 const drafts = agents.map((agent) => this.#draft(agent));
1992 const mine = drafts.flat();
1993 const base = this.#sharedView();
1994 const view = this.#viewKeyed(`d ${SHARED}@${version}+${drafts.map((d) => d.join(",")).join("+")}`, () =>
1995 unionOverlay(base.set, mine),
1996 );
1997 if (this.#writerStorage && mine.length > 0 && view instanceof View && base instanceof View) {
1998 view.shareMoves(base);
1999 view.shareFiles(base, () => touchedBeyond(this.#graph, base.set, mine, [base, view]));
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare2001 return view;
init0Start the project2002 }
2004 /** Whether agents' unpublished changes would collide, by the publish rule (draft-collisions.ts). */
2005 collisions(...args: Tail<Parameters<typeof draftCollisions>>): ReturnType<typeof draftCollisions> {
2006 return draftCollisions(this.#draftCollisions, ...args);
2009 // An agent's unpublished changes, in draft-diff.ts behind DraftDiffHost -----------------------------
2011 #draftDiffHost?: DraftDiffHost;
2012 get #draftDiff(): DraftDiffHost {
2013 this.#draftDiffHost ??= {
2014 agents: this.#agents,
2015 needInit: () => this.#needInit(),
2016 draft: (agent) => this.#draft(agent as AgentState),
2017 agentView: (agent) => this.#agentView(agent as AgentState),
codex-capacity-chair163Integrate reviewed disk-backed operations, queue and bounded read cachesCompare2018 agentViewWithout: (agent, excluded) => {
2019 const state = agent as AgentState;
2020 return this.#agentView({ ...state, mine: state.mine.filter((id) => !excluded.has(id)) });
2021 },
init0Start the project2022 view: (set) => this.#view(set),
2023 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2024 };
2025 return this.#draftDiffHost;
2028 /** What the agent's unpublished changes do, file by file (draft-diff.ts). Creates the agent if needed. */
2029 diff(agentName: string): DiffAnswer {
2030 const entries: Entry[] = [];
2031 const answer = diffOfAgent(this.#draftDiff, this.#agent(agentName, entries));
2032 this.#flush(entries);
2033 return answer;
2036 /** An agent's draft diff for a reader: never creates the agent, never writes (draft-diff.ts). */
2037 diffOf(...args: Tail<Parameters<typeof draftDiffOf>>): ReturnType<typeof draftDiffOf> {
2038 return draftDiffOf(this.#draftDiff, ...args);
2041 // Unpublished deletes-and-writes of the same text become a move (express-moves.ts) -----------------
2043 #movesHost?: ExpressMovesHost;
2044 get #expressMovesHost(): ExpressMovesHost {
2045 this.#movesHost ??= {
2046 graph: this.#graph,
2047 draft: (agent) => this.#unqueuedDraft(agent),
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2048 beforeDraft: (agent, draft) => {
2049 const base = this.#at(this.#spaceOf(agent), agent.base);
2050 if (draft.some((id) => base.has(id)))
2051 return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));
2052 const removed = new Set(draft),
2053 kept = agent.mine.filter((id) => !removed.has(id));
2054 return kept.length === 0
2055 ? this.#viewAt(this.#spaceOf(agent), agent.base)
2056 : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept));
2057 },
init0Start the project2058 agentView: (agent) => this.#agentView(agent),
2059 view: (set) => this.#view(set),
2060 apply: (entry) => this.#apply(entry),
2061 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2062 recordFile: (agent, view, path, text, time, meta, entries, mode) =>
2063 this.#recordFile(agent, view, path, text, time, meta, entries, mode),
2064 };
2065 return this.#movesHost;
2068 // Files kept whole, in whole-files.ts behind WholeHost ----------------------------------------------
2070 #wholes?: WholeHost;
2071 get #wholeHost(): WholeHost {
2072 this.#wholes ??= {
2073 initialized: () => this.initialized,
2074 sharedView: () => this.#sharedView(),
2075 whole: this.#whole,
2076 };
2077 return this.#wholes;
2080 // Notes list and start notes, in notes.ts behind NoteHost -------------------------------------------
2082 #news?: NewsHost;
2083 get #newsHost(): NewsHost {
2084 this.#news ??= {
2085 graph: this.#graph,
2086 agents: this.#agents,
2087 draft: (agent) => this.#draft(agent),
2088 newerFor: (agent) => this.#newerFor(agent),
2089 spaceOf: (agent) => this.#spaceOf(agent),
2090 setOf: (space) => this.#setOf(space),
2091 viewAt: (space, version) => this.#viewAt(space, version),
2092 origin: (atom, spaceName) => this.#origin(atom, spaceName),
2093 collision: (agent, pair) => this.#collision(agent, pair),
2094 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2095 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2096 };
2097 return this.#news;
2100 #collisions?: CollisionHost;
2101 get #collisionHost(): CollisionHost {
2102 this.#collisions ??= {
2103 graph: this.#graph,
2104 spaces: this.#spaces,
2105 version: () => this.version,
2106 spaceOf: (agent) => this.#spaceOf(agent),
codex-capacity-chair142Avoid full-base membership copies during collision checksCompare2107 agentSet: (agent) => unionOverlay(this.#at(this.#spaceOf(agent), agent.base), agent.mine),
init0Start the project2108 draft: (agent) => this.#draft(agent),
2109 agentView: (agent) => this.#agentView(agent),
2110 at: (space, version) => this.#at(space, version),
2111 shared: () => this.#shared,
2112 };
2113 return this.#collisions;
2116 #markers?: MarkerHost;
2117 get #markerHost(): MarkerHost {
2118 this.#markers ??= {
2119 graph: this.#graph,
2120 agentView: (agent) => this.#agentView(agent),
2121 draft: (agent) => this.#draft(agent),
2122 draftFiles: (agent) => this.#draftFiles(agent),
2123 };
2124 return this.#markers;
2127 #noteWrites?: NoteWriteHost;
2128 get #noteWriteHost(): NoteWriteHost {
2129 this.#noteWrites ??= {
2130 notes: this.#notes,
2131 agents: this.#agents,
2132 changes: this.#changes,
2133 graph: this.#graph,
2134 lastNote: () => this.#lastNote,
2135 agentView: (agent) => this.#agentView(agent),
2136 viewAtVersion: (version) => this.viewAt(version),
2137 sharedView: () => this.#sharedView(),
2138 changeOfLines: (lines) => this.#changeOfLines(lines),
2139 apply: (entry) => this.#apply(entry),
2140 flush: (entries) => this.#flush(entries),
2141 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2142 noteAnswer: (n) => this.#noteAnswer(n),
2143 };
2144 return this.#noteWrites;
2147 #noteHost?: NoteHost;
2148 get #notesHost(): NoteHost {
2149 this.#noteHost ??= {
2150 graph: this.#graph,
2151 agents: this.#agents,
2152 spaces: this.#spaces,
2153 notes: this.#notes,
2154 initialized: () => this.initialized,
2155 shared: () => this.#shared,
2156 sharedView: () => this.#sharedView(),
2157 spellingIn: (view, path) => this.spellingIn(view, path),
2158 viewAt: (space, version) => this.#viewAt(space, version),
2159 agentView: (agent) => this.#agentView(agent),
2160 view: (set) => this.#view(set),
2161 at: (space, version) => this.#at(space, version),
2162 liveNote: (agent) => this.#liveNote(agent),
2163 };
2164 return this.#noteHost;
2167 #merges?: MergeHost;
2168 get #mergeHost(): MergeHost {
2169 this.#merges ??= {
2170 graph: this.#graph,
2171 openPairs: (agent) => this.#openPairs(agent),
2172 draft: (agent) => this.#unqueuedDraft(agent),
2173 origin: (atom, spaceName) => this.#origin(atom, spaceName),
2174 view: (set) => this.#view(set),
2175 viewAt: (space, version) => this.#viewAt(space, version),
2176 spaceOf: (agent) => this.#spaceOf(agent),
2177 apply: (entry) => this.#apply(entry),
2178 agentView: (agent) => this.#agentView(agent),
2179 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2180 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2181 };
2182 return this.#merges;
2185 #edits?: EditHost;
2186 get #editHost(): EditHost {
2187 this.#edits ??= {
2188 agents: this.#agents,
2189 whole: this.#whole,
2190 initialized: () => this.initialized,
2191 agentView: (agent) => this.#agentView(agent),
2192 sharedView: () => this.#sharedView(),
2193 isWhole: (path, length, view, rules) => this.#isWhole(path, length, view, rules),
2194 wholeRules: (config) => this.#wholeRules(config),
2195 record: (agentName, files, time, modes, blobs, meta) => this.record(agentName, files, time, modes, blobs, meta),
2196 agent: (name, entries) => this.#agent(name, entries),
2197 draftFiles: (agent) => this.#draftFiles(agent),
2198 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2199 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2200 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2201 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2202 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2203 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2204 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2205 flush: (entries) => this.#flush(entries),
2206 };
2207 return this.#edits;
2210 #announces?: AnnounceHost;
2211 get #announceHost(): AnnounceHost {
2212 this.#announces ??= {
2213 agents: this.#agents,
2214 announced: () => this.#announced,
2215 setAnnounced: (n) => {
2216 this.#announced = n;
2217 },
2218 agent: (name, entries) => this.#agent(name, entries),
2219 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2220 apply: (entry) => this.#apply(entry),
2221 flush: (entries) => this.#flush(entries),
2222 needInit: () => this.#needInit(),
2223 };
2224 return this.#announces;
2227 #publishers?: PublishHost;
2228 get #publishHost(): PublishHost {
2229 this.#publishers ??= {
2230 agents: this.#agents,
2231 nextAt: () => this.#nextAt,
2232 checkClash: (changes, ahead) => this.#checkClash(changes, ahead),
2233 queueOn: () => this.#queueOn(),
2234 queuedAtoms: (except) => this.#queuedAtoms(except),
2235 agent: (name, entries) => this.#agent(name, entries),
2236 draft: (agent) => this.#draft(agent),
2237 spaceOf: (agent) => this.#spaceOf(agent),
2238 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2239 setOf: (space) => this.#setOf(space),
2240 markedFiles: (agent) => this.#markedFiles(agent),
2241 agentView: (agent) => this.#agentView(agent),
2242 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2243 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2244 expressMoves: (agent, time, entries) => this.#expressMoves(agent, time, entries),
2245 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2246 collision: (agent, pair) => this.#collision(agent, pair),
2247 definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2248 duplicates: (agent) => this.#duplicates(agent),
speed160A held push keeps its message, and why tells every settle: the refusal stores the push's message; why on a line kept by abso settle --yours, --theirs or --both names the collision it was kept from, and both kinds of settle list the settler's held push with its reason; the settle's news and the change page carry it too, and a lone push's change now lists the refusals on its wayCompare2249 refuse: (agent, space, via, time, collisions, entries, message) =>
2250 this.#refuse(agent, space, via, time, collisions, entries, message),
init0Start the project2251 markerCollisions: (agent) => this.#markerCollisions(agent),
2252 enqueue: (agent, message, time, draft, resolves, entries) =>
2253 this.#enqueue(agent, message, time, draft, resolves, entries),
2254 view: (set) => this.#view(set),
2255 requireClosed: (tie, union) => this.#requireClosed(tie, union),
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2256 spaceOverlay: (space, atoms) =>
2257 this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () =>
2258 unionOverlay(this.#setOf(space), atoms),
2259 ),
init0Start the project2260 newerFor: (agent) => this.#newerFor(agent),
2261 currentChange: (agent, time) => this.#currentChange(agent, time),
2262 apply: (entry) => this.#apply(entry),
2263 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2264 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2265 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2266 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2267 flush: (entries) => this.#flush(entries),
2268 };
2269 return this.#publishers;
2272 #queues?: QueueHost;
2273 get #queueHost(): QueueHost {
2274 this.#queues ??= {
2275 graph: this.#graph,
2276 checkerReady: () => this.checkerReady,
2277 sharedView: () => this.#sharedView(),
codex-capacity-chair163Integrate reviewed disk-backed operations, queue and bounded read cachesCompare2278 sharedOverlay: (atoms) =>
2279 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2280 unionOverlay(this.#setOf(this.#shared), atoms),
2281 ),
2282 sharedAgentOverlay: (agent, atoms) => {
2283 const current = this.#setOf(this.#shared);
2284 const added = new Set([...atoms, ...agent.mine]);
2285 // Retain old-base atoms absent from current shared, without copying shared history.
2286 if (agent.base !== last(this.#shared))
2287 for (const id of this.#at(this.#spaceOf(agent), agent.base)) if (!current.has(id)) added.add(id);
2288 return this.#viewKeyed(`a @${last(this.#shared)}+${[...added].join(",")}`, () => unionOverlay(current, added));
2289 },
init0Start the project2290 queued: () => this.#queue,
2291 queuedId: () => this.#queuedId,
2292 checkingHas: (id) => this.#checking.has(id),
2293 replaceChecking: (ids) => {
2294 this.#checking = new Set(ids);
2295 },
2296 uncheck: (id) => {
2297 this.#checking.delete(id);
2298 },
2299 needInit: () => this.#needInit(),
2300 shared: () => this.#shared,
2301 setOf: (space) => this.#setOf(space),
2302 view: (set) => this.#view(set),
2303 agentSet: (agent) => this.#agentSet(agent),
2304 agentView: (agent) => this.#agentView(agent),
2305 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2306 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2307 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
speed160A held push keeps its message, and why tells every settle: the refusal stores the push's message; why on a line kept by abso settle --yours, --theirs or --both names the collision it was kept from, and both kinds of settle list the settler's held push with its reason; the settle's news and the change page carry it too, and a lone push's change now lists the refusals on its wayCompare2308 refuse: (agent, space, via, time, collisions, entries, message) =>
2309 this.#refuse(agent, space, via, time, collisions, entries, message),
init0Start the project2310 currentChange: (agent, time) => this.#currentChange(agent, time),
2311 nextAt: () => this.#nextAt,
2312 apply: (entry) => this.#apply(entry),
2313 agentOf: (name) => this.#agentOf(name),
2314 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2315 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2316 settledNews: (agent, version, settled, entries) => this.#settledNews(agent, version, settled, entries),
2317 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2318 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2319 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2320 flush: (entries) => this.#flush(entries),
2321 };
2322 return this.#queues;
2325 #applyEntries?: ApplyEntryHost;
2326 get #applyEntryHost(): ApplyEntryHost {
2327 this.#applyEntries ??= {
2328 graph: this.#graph,
2329 agents: this.#agents,
2330 atomAt: this.#atomAt,
2331 mods: this.#mods,
2332 notes: this.#notes,
2333 changes: this.#changes,
2334 labels: this.#labels,
2335 refusals: this.#refusals,
pinch31status lists the newest tells and who has heard each: every recipient, with the time its client handed the tell over (or not yet). It's read from the news and heard entries the log already keeps, so nothing new is recorded. Unlike announcements, which lists only what is still undelivered, a tell stays listed once heard, and two tells with the same words stay two. The last 50 are kept. A sync's reset hears no tell. Tests in worker/project/test/tells.test.ts.Compare2336 tells: this.#tells,
init0Start the project2337 uncheck: (id) => {
2338 this.#checking.delete(id);
2339 },
2340 stamp: (t) => {
2341 if (typeof t === "number" && t > this.#lastTime) this.#lastTime = t;
2342 },
2343 applyMembership: (entry, at) => this.#membership.apply(entry, at),
2344 agentOf: (name) => this.#agentOf(name),
2345 active: (agent, time) => this.#active(agent, time),
2346 joinChange: (agent, entry, at, draft, landed) => this.#joinChange(agent, entry, at, draft, landed),
2347 space: (name) => this.#spaces.get(name)!,
2348 queued: () => this.#queue,
2349 setQueued: (items) => {
2350 this.#queue = items;
2351 },
2352 setQueuedId: (id) => {
2353 this.#queuedId = id;
2354 },
2355 queuedId: () => this.#queuedId,
2356 setLastNote: (id) => {
2357 this.#lastNote = id;
2358 },
2359 lastNote: () => this.#lastNote,
2360 setAnnounced: (n) => {
2361 this.#announced = n;
2362 },
2363 announced: () => this.#announced,
2364 at: (space, version) => this.#at(space, version),
2365 spaceOf: (agent) => this.#spaceOf(agent),
2366 draft: (agent) => this.#draft(agent),
2367 currentChange: (agent, time) => this.#currentChange(agent, time),
2368 changeRecord: (id, agent, time) => this.#changeRecord(id, agent, time),
2369 };
2370 return this.#applyEntries;
2373 #landers?: LandHost;
2374 get #landHost(): LandHost {
2375 this.#landers ??= {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare2376 viewAt: (space, version, changes) =>
2377 changes?.length
2378 ? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(",")}`, () =>
2379 unionOverlay(this.#at(space, version), changes),
2381 : this.#viewAt(space, version),
init0Start the project2382 agents: this.#agents,
2383 graph: this.#graph,
2384 spaces: this.#spaces,
2385 version: () => this.version,
2386 nextAt: () => this.#nextAt,
2387 notQueuedYet: (what) => this.#notQueuedYet(what),
2388 checkClash: (changes) => this.#checkClash(changes),
2389 agent: (name, entries) => this.#agent(name, entries),
2390 namedSpaceOf: (agent) => this.#namedSpaceOf(agent),
2391 shared: () => this.#shared,
2392 setOf: (space) => this.#setOf(space),
2393 at: (space, version) => this.#at(space, version),
2394 view: (set) => this.#view(set),
2395 sharedView: () => this.#sharedView(),
2396 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
2397 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
2398 definitionRule: () => this.#definitionRule,
2399 refuse: (agent, space, via, time, collisions, entries) =>
2400 this.#refuse(agent, space, via, time, collisions, entries),
2401 requireClosed: (tie, union) => this.#requireClosed(tie, union),
2402 apply: (entry) => this.#apply(entry),
2403 newsForOthers: (publisher, space, version, entries) => this.#newsForOthers(publisher, space, version, entries),
2404 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2405 reviewNews: (agent, version, entries) => this.#reviewNews(agent, version, entries),
2406 flush: (entries) => this.#flush(entries),
2407 };
2408 return this.#landers;
2411 #records?: RecordHost;
2412 get #recordHost(): RecordHost {
2413 this.#records ??= {
2414 agents: this.#agents,
2415 whole: this.#whole,
2416 initialized: () => this.initialized,
2417 agentView: (agent) => this.#agentView(agent),
2418 sharedView: () => this.#sharedView(),
2419 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2420 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2421 agent: (name, entries) => this.#agent(name, entries),
2422 draftFiles: (agent) => this.#draftFiles(agent),
2423 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2424 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2425 overlapNews: (agent, before, entries) => this.#overlapNews(agent, before, entries),
2426 markedNews: (agent, files, entries) => this.#markedNews(agent, files, entries),
2427 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2428 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2429 flush: (entries) => this.#flush(entries),
2430 };
2431 return this.#records;
2434 #restores?: RestoreHost;
2435 get #restoreHost(): RestoreHost {
2436 this.#restores ??= {
2437 graph: this.#graph,
2438 agent: (name, entries) => this.#agent(name, entries),
2439 draft: (agent) => this.#unqueuedDraft(agent),
2440 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2441 apply: (entry) => this.#apply(entry),
2442 view: (set) => this.#view(set),
2443 agentSet: (agent) => this.#agentSet(agent),
2444 agentView: (agent) => this.#agentView(agent),
codex-capacity-chair163Integrate reviewed disk-backed operations, queue and bounded read cachesCompare2445 agentViewWithout: (agent, excluded) =>
2446 this.#agentView({ ...agent, mine: agent.mine.filter((id) => !excluded.has(id)) }),
init0Start the project2447 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2448 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2449 flush: (entries) => this.#flush(entries),
2450 };
2451 return this.#restores;
2454 #startings?: StartingHost;
2455 get #startingHost(): StartingHost {
2456 this.#startings ??= {
2457 agents: this.#agents,
2458 changes: this.#changes,
2459 agent: (name, entries) => this.#agent(name, entries),
2460 liveNote: (agent) => this.#liveNote(agent),
2461 apply: (entry) => this.#apply(entry),
2462 overlaps: (agent, patterns) => this.#overlaps(agent, patterns),
2463 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2464 flush: (entries) => this.#flush(entries),
2465 };
2466 return this.#startings;
2469 #syncs?: SyncHost;
2470 get #syncHost(): SyncHost {
2471 this.#syncs ??= {
2472 graph: this.#graph,
2473 labels: this.#labels,
2474 agent: (name, entries) => this.#agent(name, entries),
2475 spaceOf: (agent) => this.#spaceOf(agent),
2476 agentView: (agent) => this.#agentView(agent),
codex-capacity-chair163Integrate reviewed disk-backed operations, queue and bounded read cachesCompare2477 captureAgentView: (agent) => {
2478 const key = this.#agentViewKey(agent);
2479 const original = this.#agentView(agent);
2480 // Projected readers reopen the immutable key; only the in-memory fallback uses the original set.
2481 return () => this.#viewKeyed(key, () => original.set);
2482 },
init0Start the project2483 at: (space, version) => this.#at(space, version),
2484 draft: (agent) => this.#draft(agent),
2485 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2486 apply: (entry) => this.#apply(entry),
2487 flush: (entries) => this.#flush(entries),
2488 mergeIdentical: (agent, before, oldBase, oldVersion, time, entries) =>
2489 this.#mergeIdentical(agent, before, oldBase, oldVersion, time, entries),
2490 changesSince: (agent, before) => this.#changesSince(agent, before),
2491 };
2492 return this.#syncs;
2495 #moves?: MoveHost;
2496 get #moveHost(): MoveHost {
2497 this.#moves ??= {
2498 needInit: () => this.#needInit(),
2499 agents: this.#agents,
2500 agentView: (agent) => this.#agentView(agent),
2501 sharedView: () => this.#sharedView(),
2502 agent: (name, entries) => this.#agent(name, entries),
2503 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2504 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2505 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2506 newsAboutOwnDraft: (agent, entries) => this.#newsAboutOwnDraft(agent, entries),
2507 takeNews: (agent, entries) => this.#takeNews(agent, entries),
2508 flush: (entries) => this.#flush(entries),
2509 };
2510 return this.#moves;
2513 #switches?: SwitchHost;
2514 get #switchHost(): SwitchHost {
2515 this.#switches ??= {
2516 agent: (name, entries) => this.#agent(name, entries),
2517 flush: (entries) => this.#flush(entries),
2518 spaces: this.#spaces,
2519 agentView: (agent) => this.#agentView(agent),
2520 graph: this.#graph,
2521 version: () => this.version,
2522 apply: (entry) => this.#apply(entry),
2523 draft: (agent) => this.#draft(agent),
2524 setOf: (space) => this.#setOf(space),
2525 changesSince: (agent, before) => this.#changesSince(agent, before),
2526 };
2527 return this.#switches;
2530 #draftStates?: DraftStateHost;
2531 get #draftStateHost(): DraftStateHost {
2532 this.#draftStates ??= {
2533 needInit: () => this.#needInit(),
2534 spaceNamed: (name) => this.#spaceNamed(name),
2535 shared: () => this.#shared,
2536 graph: this.#graph,
2537 agents: this.#agents,
2538 draft: (agent) => this.#draft(agent),
2539 checkClash: (changes) => this.#checkClash(changes),
2540 landCollisions: (space, changes, pick) => this.#landCollisions(space, changes, pick),
2541 };
2542 return this.#draftStates;
2545 #checkClashes?: CheckClashHost;
2546 get #checkClashHost(): CheckClashHost {
2547 this.#checkClashes ??= {
2548 shared: () => this.#shared,
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare2549 setOf: (space) => this.#setOf(space),
init0Start the project2550 view: (set) => this.#view(set),
2551 sharedView: () => this.#sharedView(),
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2552 sharedOverlay: (atoms) =>
2553 this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2554 unionOverlay(this.#setOf(this.#shared), atoms),
2555 ),
init0Start the project2556 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2557 };
2558 return this.#checkClashes;
2561 #changesSinces?: ChangesSinceHost;
2562 get #changesSinceHost(): ChangesSinceHost {
2563 this.#changesSinces ??= {
2564 agentView: (agent) => this.#agentView(agent),
2565 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
2566 openPairs: (agent) => this.#openPairs(agent),
2567 collision: (agent, pair) => this.#collision(agent, pair),
2568 duplicates: (agent) => this.#duplicates(agent),
2569 markedCollisions: (agent) => this.#markedCollisions(agent),
2570 };
2571 return this.#changesSinces;
2574 #inits?: InitHost;
2575 get #initHost(): InitHost {
2576 this.#inits ??= {
2577 initialized: () => this.initialized,
2578 whole: this.#whole,
2579 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2580 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2581 commit: (entries) => this.#commit(entries),
2582 };
2583 return this.#inits;
2586 #amends?: AmendHost;
2587 get #amendHost(): AmendHost {
2588 this.#amends ??= {
2589 agent: (name, entries) => this.#agent(name, entries),
2590 spaceOf: (agent) => this.#spaceOf(agent),
2591 apply: (entry) => this.#apply(entry),
2592 flush: (entries) => this.#flush(entries),
2593 };
2594 return this.#amends;
2597 #labelHosts?: LabelHost;
2598 get #labelHost(): LabelHost {
2599 this.#labelHosts ??= {
2600 agent: (name, entries) => this.#agent(name, entries),
2601 version: () => this.version,
2602 labels: this.#labels,
2603 apply: (entry) => this.#apply(entry),
2604 flush: (entries) => this.#flush(entries),
2605 };
2606 return this.#labelHosts;
2609 #publishOfs?: PublishOfHost;
2610 get #publishOfHost(): PublishOfHost {
2611 this.#publishOfs ??= {
2612 shared: () => this.#shared,
2613 spaces: this.#spaces,
2614 };
2615 return this.#publishOfs;
2618 #versionMetas?: VersionMetaHost;
2619 get #versionMetaHost(): VersionMetaHost {
2620 this.#versionMetas ??= {
2621 needInit: () => this.#needInit(),
2622 spaceNamed: (name) => this.#spaceNamed(name),
2623 };
2624 return this.#versionMetas;
2627 #refuses?: RefuseHost;
2628 get #refuseHost(): RefuseHost {
2629 this.#refuses ??= {
2630 apply: (entry) => this.#apply(entry),
2631 refusals: this.#refusals,
2632 };
2633 return this.#refuses;
2636 #overlapsHost?: OverlapHost;
2637 get #overlapHost(): OverlapHost {
2638 this.#overlapsHost ??= {
2639 graph: this.#graph,
2640 agents: this.#agents,
2641 agentView: (agent) => this.#agentView(agent),
2642 draft: (agent) => this.#draft(agent),
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare2643 draftFiles: (agent) => this.#draftFiles(agent),
init0Start the project2644 liveNote: (agent) => this.#liveNote(agent),
2645 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2646 };
2647 return this.#overlapsHost;
2650 #recordFiles?: RecordFileHost;
2651 get #recordFileHost(): RecordFileHost {
2652 this.#recordFiles ??= {
2653 addDraft: (agent, view, input, time, meta, entries) => this.#addDraft(agent, view, input, time, meta, entries),
2654 };
2655 return this.#recordFiles;
2658 #addDrafts?: AddDraftHost;
2659 get #addDraftHost(): AddDraftHost {
2660 this.#addDrafts ??= {
2661 graph: this.#graph,
2662 openPairs: (agent) => this.#openPairs(agent),
2663 markersSettled: (agent, view, atom) => this.#markersSettled(agent, view, atom),
2664 apply: (entry) => this.#apply(entry),
2665 };
2666 return this.#addDrafts;
2669 #ingests?: IngestHost;
2670 get #ingestHost(): IngestHost {
2671 this.#ingests ??= {
2672 agents: this.#agents,
2673 spaces: this.#spaces,
2674 needInit: () => this.#needInit(),
2675 version: () => this.version,
2676 checkBlobs: (blobs, files) => this.#checkBlobs(blobs, files),
2677 apply: (entry) => this.#apply(entry),
2678 flush: (entries) => this.#flush(entries),
2679 wholeOut: (files, blobs, view, config) => this.#wholeOut(files, blobs, view, config),
2680 agentView: (agent) => this.#agentView(agent),
2681 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
2682 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
2683 publish: (agent, message, time, entries, asIs, direct) =>
2684 this.#publish(agent, message, time, entries, asIs, direct),
2685 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2686 };
2687 return this.#ingests;
2690 #plucks?: PluckHost;
2691 get #pluckHost(): PluckHost {
2692 this.#plucks ??= {
2693 graph: this.#graph,
2694 spaces: this.#spaces,
2695 agent: (name, entries) => this.#agent(name, entries),
2696 shared: () => this.#shared,
2697 notQueuedYet: (what) => this.#notQueuedYet(what),
2698 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
2699 checkClash: (changes) => this.#checkClash(changes),
2700 land: (agent, message, time, entries, pick) => this.#land(agent, message, time, entries, pick),
2701 flush: (entries) => this.#flush(entries),
2702 };
2703 return this.#plucks;
2706 #drops?: DropHost;
2707 get #dropHost(): DropHost {
2708 this.#drops ??= {
2709 graph: this.#graph,
2710 agents: this.#agents,
2711 spaces: this.#spaces,
2712 agent: (name, entries) => this.#agent(name, entries),
2713 shared: () => this.#shared,
2714 flush: (entries) => this.#flush(entries),
2715 apply: (entry) => this.#apply(entry),
2716 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
2717 addressedNews: (agent, version, entries) => this.#addressedNews(agent, version, entries),
2718 };
2719 return this.#drops;
2722 // Changes (#44), in change-records.ts behind ChangeHost ---------------------------------------------
2724 #changeRecords?: ChangeHost;
2725 get #changeHost(): ChangeHost {
2726 this.#changeRecords ??= {
2727 changes: this.#changes,
2728 agents: this.#agents,
2729 spaces: this.#spaces,
2730 notes: this.#notes,
2731 versionChange: this.#versionChange,
2732 paths: this.#paths,
2733 graph: this.#graph,
2734 stored: () => this.#stored,
2735 shared: () => this.#shared,
2736 queue: () => this.#queue,
2737 active: (agent, time) => this.#active(agent, time),
2738 currentChange: (agent, time) => this.#currentChange(agent, time),
2739 liveNote: (agent) => this.#liveNote(agent),
2740 noteAnswer: (n) => this.#noteAnswer(n),
2741 reviewersOf: (files, id) => this.#reviewersOf(files, id),
2742 };
2743 return this.#changeRecords;
2746 // What the project looks like now, in project-status.ts behind SnapshotHost -------------------------
2748 #snapshotHost?: SnapshotHost;
2749 get #snapshot(): SnapshotHost {
2750 this.#snapshotHost ??= {
2751 agents: this.#agents,
2752 spaces: this.#spaces,
2753 queue: () => this.#queue,
2754 refusals: this.#refusals,
2755 labels: this.#labels,
pinch31status lists the newest tells and who has heard each: every recipient, with the time its client handed the tell over (or not yet). It's read from the news and heard entries the log already keeps, so nothing new is recorded. Unlike announcements, which lists only what is still undelivered, a tell stays listed once heard, and two tells with the same words stay two. The last 50 are kept. A sync's reset hears no tell. Tests in worker/project/test/tells.test.ts.Compare2756 tells: this.#tells,
init0Start the project2757 needInit: () => this.#needInit(),
2758 shared: () => this.#shared,
2759 draft: (agent) => this.#draft(agent),
2760 draftFiles: (agent) => this.#draftFiles(agent),
2761 liveNote: (agent) => this.#liveNote(agent),
2762 openCollisions: (agent) => this.#openCollisions(agent),
2763 editsOf: (agent) => this.#editsOf(agent),
2764 setOf: (space) => this.#setOf(space),
2765 spaceNamed: (name) => this.#spaceNamed(name),
2766 checkVersion: (space, version) => this.#checkVersion(space, version),
2767 viewAt: (space, version) => this.#viewAt(space, version),
capacity217tree lists a version's files from the kept shapes, as pathsAt does since 216 (disk-first 2; abso Capacity). The tree at a version laid out every file only to list them. Not for an agent's tree, whose view has its draft on top. On abso's export the tree at head went from over 60 s to 225 ms (replay takes 41 s), and the tree at 612 takes 156 ms, both matching Project.load. version-files.test.ts now also checks the tree at every version against the in-memory project. Named tests: version-files, files-reads, project, draft-reads-stored, named-drafts (38 of 38); tsc clean.Compare2768 keptPaths: (space, version) => this.#keptPaths(space, version),
init0Start the project2769 agentView: (agent) => this.#agentView(agent),
2770 version: () => this.version,
engine25Read abso.json first, then avcs.json (abso 224, ask 238): one helper (projectFileIn) for the queue, files kept whole, reviewers and init; publish, init and git intake check both files the same way; when shared has both, abso.json counts and status says avcs.json is ignored (status answer projectFile, printed by abso status). .abso/ is kept out of projects like .avcs/. Old projects with only avcs.json work as before.Compare2771 projectFile: () => (this.initialized ? projectFileIn(this.#sharedView()) : undefined),
init0Start the project2772 };
2773 return this.#snapshotHost;
2776 /** The paths in an agent's view now (project-status.ts). */
2777 agentPaths(...args: Tail<Parameters<typeof snapshotAgentPaths>>): ReturnType<typeof snapshotAgentPaths> {
2778 return snapshotAgentPaths(this.#snapshot, ...args);
2781 /** The paths in shared, or a named draft, at a version (project-status.ts). */
2782 pathsAt(...args: Tail<Parameters<typeof snapshotPathsAt>>): ReturnType<typeof snapshotPathsAt> {
2783 return snapshotPathsAt(this.#snapshot, ...args);
2786 /** The paths in an agent's view now, for a reader (project-status.ts). */
2787 pathsOf(...args: Tail<Parameters<typeof snapshotPathsOf>>): ReturnType<typeof snapshotPathsOf> {
2788 return snapshotPathsOf(this.#snapshot, ...args);
2791 /** Every label, with the versions it marks, newest first (project-status.ts). */
2792 labels(): ReturnType<typeof snapshotLabels> {
2793 return snapshotLabels(this.#snapshot);
2796 /** Agents, drafts, refusals and waiting announcements (project-status.ts). */
2797 status(): ReturnType<typeof snapshotStatus> {
2798 return snapshotStatus(this.#snapshot);
codex-capacity-chair112Read one actor head without projecting every agent draftCompare2801 /** The operation fence needs one actor's heads, not every agent's file projection. */
2802 actorHead(name: string): { base: number; draftChanges: number; draft: string | null } | undefined {
2803 const agent = this.#agents.get(name);
2804 if (!agent) return undefined;
2805 const published = this.#setOf(this.#spaceOf(agent));
2806 let draftChanges = 0;
2807 for (const id of agent.mine) if (!published.has(id)) draftChanges++;
2808 return { base: agent.base, draftChanges, draft: agent.space === SHARED ? null : agent.space };
init0Start the project2811 /** A space's contents at one of its versions. */
2812 #at(space: Space, version: number): ReadonlySet<AtomId> {
2813 return this.#membership.at(space, version);
2816 /** A space's contents now. */
2817 #setOf(space: Space): ReadonlySet<AtomId> {
2818 return this.#at(space, last(space));
2821 #draft(agent: AgentState): AtomId[] {
2822 const set = this.#setOf(this.#spaceOf(agent));
2823 return agent.mine.filter((id) => !set.has(id));
2826 /**
2827 * The draft without the agent's publishes waiting in the queue (#39): what
2828 * moves, restore and sync's merge may drop and make again. A queued item's
2829 * atoms are no longer the draft's to remake; dropping them let the queue
2830 * land a tie that depends on discarded atoms (abso issue 135, item 4).
2831 * Undoing a queued publish is abso unqueue.
2832 */
2833 #unqueuedDraft(agent: AgentState): AtomId[] {
2834 const draft = this.#draft(agent);
2835 const held = this.#queuedAtoms();
2836 return held.size === 0 ? draft : draft.filter((id) => !held.has(id));
2839 #agentSet(agent: AgentState): Set<AtomId> {
2840 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2843 #agentView(agent: AgentState): ReadView {
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare2844 const view = this.#viewKeyed(this.#agentViewKey(agent), () => {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare2845 const base = this.#at(this.#spaceOf(agent), agent.base);
2846 return base instanceof StableSet
2847 ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2848 : new Set([...base, ...agent.mine]);
2849 });
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare2850 // A draft that moves nothing resolves its moves as its base does (abso Capacity): take them from the base's view.
2851 if (this.#writerStorage && agent.mine.length > 0 && view instanceof View) {
2852 const base = this.#viewAt(this.#spaceOf(agent), agent.base);
capacity235A draft's view takes its base view's layout of every file the draft doesn't touch (disk-first 2; abso Capacity). An agent's tree, files and folder blame lay out every file in the agent's view, and tree also lays out the base to see which files the draft changed. Each layout read the file's packed history again, though every file the draft doesn't touch lays out exactly as in the draft's base. - View.shareFiles(from, except): a view lays out a file by taking from's layout of it, unless the file is in except. except is worked out once, when a file is first needed. - Project.#agentView sets it for a draft's view over its base's when the draft moves nothing (its moves are then the base's, as shareMoves already relies on). The touched files are touchedFiles over the draft's atoms, in both views: the files they write, delete in, set attributes on, and, where moves count, the files their deleted lines and their runs' parents sit in. On abso adopted fresh, one kept writer: an agent's tree with authors 23.4 s to 12 to 14 s. It's still slow because a whole abso layout is bigger than the views' byte budget, so it isn't kept between calls. New test agent-views-shared: after a published move of a function into another file, drafts that edit a moved line, delete one, change another file, set an attribute, or move lines themselves each read every file (text, attributes, writers) as the in-memory project does, read twice; it fails when the touched files are taken from where lines were written only. Named tests: every engine test (288 of 288), every worker/project test (338 of 338); typescript-rs, all 27 answers match replay; tsc and biome clean.Compare2853 if (base instanceof View) {
2854 view.shareMoves(base);
capacity236Fix 235's wrong draft diff: a draft view's shared files count everything it holds beyond its base (disk-first 2; abso Capacity). Disk-first Testing found a wrong answer on typescript-rs with 235: diff for cloud-ts-01 showed lib.rs and passes.rs before cloud-ts-01's own version 326. The diff's before view is cloud-ts-01's base (293) plus three of its atoms that touch only reports/cloud-ts-01.md. A view's set is closed under dependencies, so it also holds atoms those three depend on that 293 lacks, including the ones that added passes.rs and rewrote lib.rs. 235 counted only the draft's own atoms as touched, so it took those two files from version 293. The files a draft's view can't take from its base are now worked out over everything the view holds beyond the base: the draft, plus whatever it depends on that the base lacks. Sharing is still off when any of those moves lines. Check: on typescript-rs adopted fresh, diff for cloud-ts-01 differs from replay on 235's code and matches with this. The unit tests do not reproduce this state; the export comparison does. Named tests: every worker/project test (338 of 338) and every engine test; tsc and biome clean.Compare2855 // And its layout of every file the draft doesn't touch, when the draft moves nothing (abso Capacity). What the
2856 // view holds beyond its base is the draft and whatever the draft depends on that the base lacks (the view's
2857 // set is closed): each of those can change a file, so all of them count.
capacity235A draft's view takes its base view's layout of every file the draft doesn't touch (disk-first 2; abso Capacity). An agent's tree, files and folder blame lay out every file in the agent's view, and tree also lays out the base to see which files the draft changed. Each layout read the file's packed history again, though every file the draft doesn't touch lays out exactly as in the draft's base. - View.shareFiles(from, except): a view lays out a file by taking from's layout of it, unless the file is in except. except is worked out once, when a file is first needed. - Project.#agentView sets it for a draft's view over its base's when the draft moves nothing (its moves are then the base's, as shareMoves already relies on). The touched files are touchedFiles over the draft's atoms, in both views: the files they write, delete in, set attributes on, and, where moves count, the files their deleted lines and their runs' parents sit in. On abso adopted fresh, one kept writer: an agent's tree with authors 23.4 s to 12 to 14 s. It's still slow because a whole abso layout is bigger than the views' byte budget, so it isn't kept between calls. New test agent-views-shared: after a published move of a function into another file, drafts that edit a moved line, delete one, change another file, set an attribute, or move lines themselves each read every file (text, attributes, writers) as the in-memory project does, read twice; it fails when the touched files are taken from where lines were written only. Named tests: every engine test (288 of 288), every worker/project test (338 of 338); typescript-rs, all 27 answers match replay; tsc and biome clean.Compare2858 const mine = agent.mine;
capacity237touchedBeyond, with named tests for 235's wrong draft diff (disk-first 2; abso Capacity). 236 fixed the wrong diff Disk-first Testing found on typescript-rs with 235 (cloud-ts-01's diff showed lib.rs and passes.rs from its older base). This moves that fix into a named function with its own tests, as Agent VCS asked. - collisions.ts touchedBeyond(graph, below, mine, views): the files a view over below plus mine can lay out differently from below, or undefined when any of it moves lines. It counts mine and whatever mine depends on that below lacks, since a view's set is closed. Project.#agentView's shareFiles uses it. - touched-beyond.test.ts: a publish's tie writes no files, but it depends on the published change. Counted from version 0 its files include the changed file, which 235's count (the atoms alone) missed. A move beyond the base turns sharing off. - agent-views-shared.test.ts adds a merge-queue landing with a move, then more drafting in the moved-to file. Checks: typescript-rs adopted fresh, diff for cloud-ts-01 matches replay (it differs on 235). Every worker/project test (341 of 341) and every engine test; tsc and biome clean.Compare2859 view.shareFiles(base, () => touchedBeyond(this.#graph, base.set, mine, [base, view]));
capacity235A draft's view takes its base view's layout of every file the draft doesn't touch (disk-first 2; abso Capacity). An agent's tree, files and folder blame lay out every file in the agent's view, and tree also lays out the base to see which files the draft changed. Each layout read the file's packed history again, though every file the draft doesn't touch lays out exactly as in the draft's base. - View.shareFiles(from, except): a view lays out a file by taking from's layout of it, unless the file is in except. except is worked out once, when a file is first needed. - Project.#agentView sets it for a draft's view over its base's when the draft moves nothing (its moves are then the base's, as shareMoves already relies on). The touched files are touchedFiles over the draft's atoms, in both views: the files they write, delete in, set attributes on, and, where moves count, the files their deleted lines and their runs' parents sit in. On abso adopted fresh, one kept writer: an agent's tree with authors 23.4 s to 12 to 14 s. It's still slow because a whole abso layout is bigger than the views' byte budget, so it isn't kept between calls. New test agent-views-shared: after a published move of a function into another file, drafts that edit a moved line, delete one, change another file, set an attribute, or move lines themselves each read every file (text, attributes, writers) as the in-memory project does, read twice; it fails when the touched files are taken from where lines were written only. Named tests: every engine test (288 of 288), every worker/project test (338 of 338); typescript-rs, all 27 answers match replay; tsc and biome clean.Compare2860 }
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export. - where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line. - Draft files (overlaps.ts) go by number the same way. - An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this). - Draft collisions: - build the union view only when two drafts share a file; - work out each agent's touched files and its "shared now plus draft" view once; - find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history; - have the definition rule keep a draft's uses, and the newer work's definitions, across partners. - A stored list read in order reads its length once, not before every element. draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail. On website's export (1,387 entries) the answers match Project.load: - status: 17 s to 4.5 s - where: over 60 s to 8.8 s - drafts: 14 s to 5.3 s - collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare2861 }
2862 return view;
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare2863 }
2865 /** 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. */
2866 #agentViewKey(agent: AgentState): string {
codex-capacity-chair114Reuse published projections for empty actor draftsCompare2867 // An empty draft is exactly its published base. Share its projection
2868 // with version readers instead of walking the same history twice.
2869 if (agent.mine.length === 0) return `v ${agent.space}@${agent.base}`;
engine55Issue 6: status no longer builds every agent's view. On abso's log (13,148 entries, 48 agents) status went from about 330 ms to 1 ms median (30 ms max) in Node. - markedCollisions skips the view when the agent has no marked files (most have none). This was most of the cost. - draftFiles skips the view when the draft is empty, and Project keeps each agent's draft files under their view key plus the draft, so they're worked out again only when either moves. Overlaps and overlap news use the kept ones too. - New test (draft-files-kept): status from a warm project equals a cold load after every step, in shared and with two agents in one named draft (Pinch's case). A weaker key fails it.Compare2870 return `a ${agent.space}@${agent.base}+${agent.mine.join(",")}`;
init0Start the project2871 }
2873 /** A space at a version: published versions never change, so the key is just their names (#46). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2874 #viewAt(space: Space, version: number): ReadView {
capacity245Collisions step 1: whether a file exists, without laying it out (abso Capacity, issue 664). A published version's view on a writer answers hasFile from the kept path list (PathIndex.keptPathSet, the set pathsAt already answers from), and a draft's view asks its base for every file the draft doesn't touch. Resolving an import tried up to seven file names in collisions, and each check laid the whole file out. On the abso export (collisions, my machine): the first call lays out 130 files instead of 407, 13.4 s instead of 15.2 s; a warm call 7.7 s instead of 8.3 s (step 2 is most of what's left). Same answer as replay. Heap after a full warm run: 76.9 MB against 76.5 MB on 244. test/known-paths.test.ts: every name at versions 0 to 2 and in four drafts, against the in-memory project, before and after every file is read: a version that deletes a file and renames one with record, one that moves lines into a new file, and drafts that delete, rename, move lines and add.Compare2875 const view = this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));
2876 // Which files it has from the kept path list (abso Capacity, View.knowPaths), as pathsAt answers.
2877 if (view instanceof View && this.#writerStorage && space.name === SHARED)
2878 view.knowPaths(() => this.#paths.keptPathSet(space, version));
2879 return view;
init0Start the project2880 }
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2882 #sharedView(): ReadView {
init0Start the project2883 return this.#viewAt(this.#shared, last(this.#shared));
capacity247A kept reader settles after each read; line texts weigh what V8 holds (abso Capacity, issue 664). What a kept reader held on abso, measured per question without the answer itself (heap snapshot after tree with authors, 56.9 MB held): the view cache 38.3 MB against its 24 MB budget, the agents read 6.5 to 7.7 MB, the move skeleton 2.4 MB, the state cache 2.3 MB; the rest is the engine's indexes. - Project.afterRead: the view cache trimmed to its budget (ViewCache.trim) and the agents the read decoded let go (WriterAgents.release). Views grow while a call lays files out and the cache weighed them only when asked for again; a read-only reader never flushed its agents, so it held every agent's news told. - View weight: a laid-out line's text counts a 16-byte header and a byte a character (two outside Latin-1), rounded to 8, as V8 holds it. It counted 8 and two a character, so abso's whole shared layout (22.7 MB held) weighed about 28 MB, over the budget alone: once trimmed, it was laid out again for every question (blame folder 2.5 s became 14.4 s). Full warm run on the abso export: held heap at most 41.7 MB (was 56.9), 24 to 29 MB between the big reads (was 32 to 37); every answer the same. Status and drafts take about 30 ms more (agents read again); blame folder 1.7 s instead of 2.5 s. Tests: view-cache (trim reweighs growth with no further hit), after-read (new: reads before and after it, and a write after it, against the in-memory project), and the collision, path and compare tests: 21 of 21.Compare2886 /**
2887 * After each read of a reader kept between calls, one that changed nothing (abso Capacity): the cached views back
2888 * under their budget, since views grow while a call lays files out and the cache weighs them only when they are
2889 * asked for again (on abso, a tree with authors left 38 MB of views held against the 24 MB budget), and the agents
2890 * the read decoded let go, read again from storage by the next call (7 MB on abso, every agent's news told).
2891 */
2892 afterRead(): void {
2893 this.#views.trim();
2894 if (this.#agents instanceof WriterAgents) this.#agents.release();
init0Start the project2897 /** A view of a set, cached by the set's exact contents (views.ts). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2898 #view(set: ReadonlySet<AtomId>): ReadView {
2899 this.#views.assertUnkeyedAllowed();
init0Start the project2900 return this.#views.view(this.#closed(set));
2903 /** A view cached under `key` (views.ts). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare2904 #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {
init0Start the project2905 return this.#views.keyed(key, () => this.#closed(set()));
2908 /**
2909 * A discarded atom that a later publish still depends on stays in the view
2910 * (abso issue 80). A closed set is unchanged.
2911 */
codex-capacity-chair115Preserve indexed membership when closing disk-first viewsCompare2912 #closed(set: Iterable<AtomId>): ReadonlySet<AtomId> {
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare2913 if (isClosedSet(set)) return set as ReadonlySet<AtomId>;
codex-capacity-chair115Preserve indexed membership when closing disk-first viewsCompare2914 if (set instanceof StableSet) {
2915 // Keep indexed membership external. Only dependencies absent from
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare2916 // that snapshot belong in the operation's closure overlay. Over a stored closed base (abso Capacity),
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare2917 // only the atoms outside it can reach outside it: unions are opened down to their closed parts.
2918 const walk: Iterable<AtomId>[] = [];
2919 const open = (part: ReadonlySet<AtomId>): void => {
2920 if (isClosedSet(part)) return;
2921 if (part instanceof StableUnionSet) {
2922 open(part.left);
2923 open(part.right);
2924 } else walk.push(part);
2925 };
2926 open(set);
codex-capacity-chair115Preserve indexed membership when closing disk-first viewsCompare2927 const missing = new Set<AtomId>();
2928 const visit = (id: AtomId) => {
2929 const stack = [id];
2930 while (stack.length) {
2931 for (const dependency of this.#graph.atom(stack.pop()!).deps) {
2932 if (!set.has(dependency) && !missing.has(dependency)) {
2933 missing.add(dependency);
2934 stack.push(dependency);
2938 };
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare2939 for (const part of walk) for (const id of part) visit(id);
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare2940 return markClosed(missing.size ? new StableUnionSet(set, new StableOverlaySet(missing)) : set);
codex-capacity-chair115Preserve indexed membership when closing disk-first viewsCompare2941 }
init0Start the project2942 return this.#graph.closureOf(set);
2945 /** A new publish or land must not depend on an atom outside the set (abso issue 80). */
2946 #requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void {
2947 const missing = tie.deps.filter((id) => !union.has(id));
2948 if (missing.length > 0)
2949 throw new ProjectError(
2950 "conflict",
rename100abso publish is now abso push, abso sync is now abso pull (abso 427) Commands, help, flags, messages, MCP tool names and descriptions, hook text, README, SKILL.md and tests say push and pull; "shared" stays the noun ("Pushed version N"). No aliases, no notices. A queued push that was "pulled" is now "turned back", so pull means one thing. push -f/--force/-u/--all/--tags and pull --rebase/--ff-only/--squash refuse with one plain line naming the abso way; push and pull take no remote or branch. Kept as stored: log entry kinds (publish, sync, pulled), HTTP route paths, the pipeline trigger on: publish, the yours (unpublished) marker, npm-publish.Compare2951 `this change depends on ${missing.join(", ")}, which is not in the set being pushed`,
init0Start the project2952 );
2955 /** The space's atoms published after the agent's base, by others. */
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare2956 #newerFor(agent: AgentState): ReadonlySet<AtomId> {
init0Start the project2957 const space = this.#spaceOf(agent);
2958 const base = this.#at(space, agent.base);
codex-capacity-chair141Avoid full shared-history scans when checking draft newsCompare2959 const current = this.#setOf(space);
2960 const newer =
2961 space.name === SHARED && space.membershipVersion
2962 ? new SharedAdditions(space, agent.base, base, current)
2963 : differenceSet(current, base);
2964 return differenceSet(newer, new StableOverlaySet(agent.mine));
init0Start the project2965 }
2967 /** The files whose text in the agent's view differs from `before`, and its open collisions. */
2968 #changesSince(...args: Tail<Parameters<typeof hostedChangesSince>>): ReturnType<typeof hostedChangesSince> {
2969 return hostedChangesSince(this.#changesSinceHost, ...args);
2972 /** Who published an atom, looking in the given space first and then in shared. */
2973 #origin(atom: AtomId, spaceName: string): Origin {
2974 return originOf(this.#collisionHost, atom, spaceName);
2977 // Drafting ----------------------------------------------------------------------
2979 /** Check a {path: sha256} map: hex hashes, no path also given as text, and bytes already uploaded. */
2980 #checkBlobs(blobs: unknown, files: object): Record<string, string> {
2981 if (typeof blobs !== "object" || blobs === null || Array.isArray(blobs))
2982 throw new ProjectError("bad-request", "blobs must be {path: sha256}");
2983 for (const [path, sha] of Object.entries(blobs as Record<string, unknown>)) {
2984 checkPath(path);
2985 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha))
2986 throw new ProjectError("bad-request", `${path}: a blob is the SHA-256 of the bytes, in lowercase hex`);
2987 if (Object.hasOwn(files, path)) throw new ProjectError("bad-request", `${path} is given as both text and a blob`);
2988 if (!this.#hasBlob(sha))
2989 throw new ProjectError("bad-request", `${path}: upload blob ${sha} first (PUT /p/:project/blobs/${sha})`);
2991 return blobs as Record<string, string>;
2994 /**
2995 * Make one file in the agent's view what the folder has, as one draft
2996 * change: `text` (null: the file is gone; "": an empty file; undefined:
2997 * leave its lines alone) and `mode` (only the fields given). Returns
2998 * whether anything changed.
2999 */
3000 #recordFile(...args: Tail<Parameters<typeof hostedRecordFile>>): ReturnType<typeof hostedRecordFile> {
3001 return hostedRecordFile(this.#recordFileHost, ...args);
3004 /**
3005 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
3006 * place and the same text that arrives somewhere else is the same line, in
3007 * either order (deleted then written, or written then deleted). Before a
3008 * publish, the draft's changes to the files involved are dropped (a discard
3009 * entry) and made again: one move per matched block, which keeps the
3010 * lines' ids, then a change per file to the draft's final text. The files
3011 * end up exactly as the draft had them. A matched block needs a line with
3012 * real content: blank lines and lone brackets only travel next to one.
3013 */
3014 #expressMoves(agent: AgentState, time: number, entries: Entry[]): void {
3015 hostedExpressMoves(this.#expressMovesHost, agent, time, entries);
3018 /**
3019 * Build a draft change against the agent's view. If it touches lines on
3020 * either side of a collision the agent has already seen, it settles that
3021 * collision (the engine's `resolves`).
3022 */
3023 #addDraft(...args: Tail<Parameters<typeof hostedAddDraft>>): ReturnType<typeof hostedAddDraft> {
3024 return hostedAddDraft(this.#addDraftHost, ...args);
3027 // Collisions and news -------------------------------------------------------------
3029 #pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[] {
3030 return pairsIn(this.#graph, draft, against, settled);
3033 /**
3034 * Collisions the agent has synced into and not settled: its draft against
3035 * its space at its base. In a named draft, also the draft's own changes
3036 * against shared work the draft was moved onto.
3037 */
3038 #openPairs(agent: AgentState): Pair[] {
3039 return hostedOpenPairs(this.#collisionHost, agent);
3042 /** After the agent's own change: news when its draft now collides with work published after its base. */
3043 #newsAboutOwnDraft(agent: AgentState, entries: Entry[]): void {
3044 hostedNewsAboutOwnDraft(this.#newsHost, agent, entries);
3047 /** After a publish or a landing: news for every other agent in that space whose draft collides with what just arrived. */
3048 #newsForOthers(publisher: AgentState, space: Space, version: number, entries: Entry[]): void {
3049 hostedNewsForOthers(this.#newsHost, publisher, space, version, entries);
3052 #queueNews(agent: AgentState, items: readonly { key: string; text: string }[], entries: Entry[]): void {
3053 const fresh = items.filter((p) => !agent.told.has(p.key));
3054 if (fresh.length === 0) return;
3055 const text = [...new Set(fresh.map((p) => p.text))];
3056 const entry: Entry = { type: "news", agent: agent.name, pairs: [...new Set(fresh.map((p) => p.key))], text };
3057 entries.push(entry);
3058 this.#apply(entry);
3061 #takeNews(agent: AgentState, entries: Entry[]): string[] {
3062 if (agent.news.length === 0) return [];
3063 const news = [...agent.news];
3064 const entry: Entry = { type: "heard", agent: agent.name };
3065 entries.push(entry);
3066 this.#apply(entry);
3067 return news;
3070 /** Describe a pair for the agent: its side in its own view, theirs in its space now. */
3071 #collision(agent: AgentState, pair: Pair): Collision {
3072 return this.#describe(
3073 pair,
3074 this.#agentView(agent),
3075 this.#viewAt(this.#spaceOf(agent), last(this.#spaceOf(agent))),
3076 agent.space,
3077 );
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare3080 #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {
init0Start the project3081 return describePair(
3082 this.#graph,
3083 (atom, space) => this.#origin(atom, space),
3084 pair,
3085 yoursView,
3086 theirsView,
3087 spaceName,
3088 );
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare3091 #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
init0Start the project3092 return touchedFiles(this.#graph, ids, views);
3095 // The changed-definition rule (#11) -------------------------------------------
3097 /** The rule for an agent's draft in its space. */
3098 #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
3099 const draft = new Set(this.#draft(agent));
3100 if (draft.size === 0 || newer.size === 0) return [];
3101 const space = this.#spaceOf(agent);
codex-capacity-chair141Avoid full shared-history scans when checking draft newsCompare3102 const at = this.#at(space, agent.base);
3103 const base = agent.mine.some((id) => at.has(id))
3104 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
3105 : this.#viewAt(space, agent.base);
init0Start the project3106 return this.#definitionRule.collisions(
3107 draft,
3108 this.#agentView(agent),
3109 base,
3110 this.#viewAt(space, last(space)),
3111 newer,
3112 space.name,
3113 );
3117export { EngineError };