10 files, 340 lines added, 67 removed.
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -262,6 +262,7 @@
262262export type PackedDelete = [number, number]; 263263/** An attribute set on a file: [seq, name, value]. */ 264264export type PackedAttr = [number, string, string | null]; 265+const EMPTY_NUMBERS: readonly number[] = Object.freeze([]); 265266/** Lines longer than this aren't packed with their file; their text is read on its own. */ 266267const PACKED_TEXT = 4096; @@ -879,6 +880,16 @@
883+ /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */ 884+ *deletedNumbers(id: AtomId): IterableIterator<number> { 885+ const seq = this.#seq(id); 886+ if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) { 887+ yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)); 890+ yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS; 882893 /** How many lines an atom deletes, without reading its lists. */ 883894 deleteCount(id: AtomId): number { 884895 const seq = this.#seq(id); --- a/src/engine/state-source.ts
+++ b/src/engine/state-source.ts
@@ -594,16 +594,23 @@
594594 return count as number; 597+ const at = (index: number): T => { 598+ const raw = storage.read(name, String(index)); 599+ const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T); 600+ if (value === undefined) throw Error("missing stored list element"); 601+ return value && typeof value === "object" ? (Object.freeze(value) as T) : value; 603+ // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a 604+ // second disk read per element of a list too long for the cache. 605+ function* inOrder(): IterableIterator<T> { 606+ const count = length(); 607+ for (let index = 0; index < count; index++) yield at(index); 597609 return new Proxy([] as T[], { 598610 get(target, key, receiver) { 599611 if (key === "length") return length(); 600− if (indexKey(key)) {
601− if (Number(key) >= length()) return undefined;
602− const raw = storage.read(name, key);
603− const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
604− if (value === undefined) throw Error("missing stored list element");
605− return value && typeof value === "object" ? Object.freeze(value) : value;
606− }
612+ if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key)); 613+ if (key === Symbol.iterator || key === "values") return inOrder; 607614 return Reflect.get(target, key, receiver); 609616 has(target, key) { --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -10,7 +10,7 @@
1010// made when a caller asks for them, and the latest asked for is kept. 1212import type { Graph, RelocationInfo } from "./graph.ts"; 13−import { isStartNode } from "./keys.ts";
13+import { isStartNode, seqOf } from "./keys.ts"; 1414import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts"; 1515import { isClosedSet, StableSet } from "./state-source.ts"; 1616import { joinLines } from "./text.ts"; @@ -47,7 +47,10 @@
4949/** Structural read boundary shared by historical and transaction-bound projections. */ 50−export type ReadView = Omit<Pick<View, keyof View>, "sameText" | "visibleCount" | "shareMoves"> & {
50+export type ReadView = Omit< 51+ Pick<View, keyof View>, 52+ "sameText" | "visibleCount" | "shareMoves" | "fileOfNumber" | "lineNumberOf" | "visibleWriters" 5154 sameText(path: string, other: ReadView): boolean; @@ -280,13 +283,16 @@
280283 #fileOfShared: Map<number, string> | undefined; 283− * Take another view's resolved moves (abso Capacity). Only for a set that differs from that view's by atoms that
284− * move nothing, drop nothing and change no closure: its moves resolve the same, and every line it shares with that
285− * view sits where it sat there.
286+ * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the 287+ * moves then resolve the same, and every line sits where it sits there. Checked here, so any caller may ask. 287289 shareMoves(from: View): void { 288290 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves) return; 289− if (from.#scratchMoves()) return;
291+ if (this.#relocs || from.#scratchMoves()) return; 292+ for (const id of this.graph.movers()) { 293+ const seq = seqOf(id); 294+ if (this.#has(seq) !== from.#has(seq)) return; 290296 this.#relocs = from.#relocations(); 291297 this.#relocsN = from.#relocationsN(); 292298 this.#movesOnDisk = false; @@ -696,6 +702,11 @@
696702 return [...this.#known]; 705+ /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */ 706+ fileOfNumber(n: number): string { 707+ return this.#fileOfN(n); 699710 /** How many visible lines a file has. */ 700711 visibleCount(path: string): number { 701712 return this.#file(path).vis.length; @@ -849,14 +860,25 @@
850861 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */ 851862 lineNumber(path: string, line: LineId): number { 863+ return this.lineNumberOf(path, this.graph.lineN(line)); 866+ /** lineNumber by the line's number, with no lookup of its id. */ 867+ lineNumberOf(path: string, n: number): number { 852868 const f = this.#file(path); 853869 if (!f.visIndex) { 854870 f.visIndex = new Map(); 855871 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i); 857− return f.visIndex.get(this.graph.lineN(line)) ?? -1;
873+ return f.visIndex.get(n) ?? -1; 876+ /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */ 877+ visibleWriters(path: string): number[] { 878+ const graph = this.graph; 879+ return Array.from(this.#file(path).vis, (n) => graph.writerSeqOf(n)); 860882 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */ 861883 files(): Record<string, string> { 862884 const out: Record<string, string> = {}; --- a/worker/project/collisions.ts
+++ b/worker/project/collisions.ts
@@ -9,8 +9,10 @@
1416} from "../../src/engine/index.ts"; 1517import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts"; 1618import { definedTwice } from "./definitions.ts"; @@ -44,7 +46,20 @@
4446 against: ReadonlySet<AtomId>, 4547 settled: ReadonlySet<AtomId>, 47− const out: Pair[] = [];
49+ return pairsFrom(g, claimantsIn(g, draft, against), against, settled); 53+ * Each draft change's claimants in `against`, in seq order: the atoms whose claims meet its keys, before the 54+ * engine's rule is applied. A stored atom's keys are read from disk, so a caller checking one draft against many 55+ * (draft-collisions.ts) gathers once against all of them and filters with pairsFrom. 57+export function claimantsIn( 59+ draft: readonly AtomId[], 60+ against: ReadonlySet<AtomId>, 61+): ReadonlyMap<AtomId, readonly AtomId[]> { 62+ const out = new Map<AtomId, AtomId[]>(); 4863 for (const yours of draft) { 4964 const atom = g.atom(yours); 5065 const streams: IterableIterator<AtomId>[] = []; @@ -52,7 +67,62 @@
5267 streams.push(g.eachWriterOf(key), g.eachReaderOf(key), g.eachHolderOf(key)); 5469 for (const key of claimsOf(atom)) streams.push(g.eachWriterOf(key)); 55− for (const theirs of orderedClaimants(g, streams)) {
70+ const theirs: AtomId[] = []; 71+ for (const id of orderedClaimants(g, streams)) if (against.has(id)) theirs.push(id); 72+ out.set(yours, theirs); 78+ * claimantsIn for a few atoms against each other: each atom's claimants among `atoms`, in seq order, from their own 79+ * keys held in memory. Walking each key's history of claimants read four lists from disk per key, and a draft deleting 80+ * a big file has thousands of keys (abso Capacity). 82+export function claimantsAmong(g: Graph, atoms: readonly AtomId[]): ReadonlyMap<AtomId, readonly AtomId[]> { 83+ const claimers = new Map<Key, AtomId[]>(); 84+ const writers = new Map<Key, AtomId[]>(); 85+ const keys = new Map<AtomId, { writes: readonly Key[]; claims: readonly Key[] }>(); 86+ const add = (index: Map<Key, AtomId[]>, key: Key, id: AtomId) => { 87+ const list = index.get(key); 88+ if (list) list.push(id); 89+ else index.set(key, [id]); 91+ for (const id of atoms) { 92+ const atom = g.atom(id); 93+ const writes = [...atom.writes]; 94+ // claimsOf, with the writes already read. 95+ const claims = [...new Set([...writes, ...atom.reads, ...atom.holds])].sort(); 96+ keys.set(id, { writes, claims }); 97+ for (const key of writes) add(writers, key, id); 98+ for (const key of claims) add(claimers, key, id); 100+ const out = new Map<AtomId, AtomId[]>(); 101+ for (const id of atoms) { 102+ const own = keys.get(id)!; 103+ const found = new Set<AtomId>(); 104+ // As claimantsIn's streams: what claims a key it writes, and what writes a key it claims. 105+ for (const key of own.writes) for (const other of claimers.get(key) ?? []) found.add(other); 106+ for (const key of own.claims) for (const other of writers.get(key) ?? []) found.add(other); 110+ [...found].sort((a, b) => seqOf(a) - seqOf(b)), 116+/** The claimants in `against` that collide by the engine's rule and that no atom of `settled` resolves. */ 117+export function pairsFrom( 119+ claimants: ReadonlyMap<AtomId, readonly AtomId[]>, 120+ against: ReadonlySet<AtomId>, 121+ settled: ReadonlySet<AtomId>, 123+ const out: Pair[] = []; 124+ for (const [yours, theirsList] of claimants) { 125+ for (const theirs of theirsList) { 56126 if (!against.has(theirs)) continue; 57127 const [lo, hi] = g.atom(yours).seq < g.atom(theirs).seq ? [yours, theirs] : [theirs, yours]; 58128 const keys = conflictKeys(g.atom(lo), g.atom(hi), g.dependsOn(hi, lo)); --- a/worker/project/definition-rule.ts
+++ b/worker/project/definition-rule.ts
@@ -36,10 +36,23 @@
3636 readonly parent: string; 39+/** Definitions in the files newer work touched, before it and with it. */ 41+ readonly baseDefs: ReturnType<typeof definitionsIn>; 42+ readonly nowDefs: ReturnType<typeof definitionsIn>; 45+/** Names a draft's lines use that they don't declare, with where. */ 46+type Uses = ReadonlyMap<string, readonly { file: string; index: number }[]>; 3948export class DefinitionRule { 4049 readonly #graph: Graph; 4150 readonly #origin: (atom: AtomId, spaceName: string) => Origin; 4251 readonly #replacedCache = new Map<string, ReadonlySet<string>>(); 52+ /** A draft's uses, kept while it is asked about with the same views: draft collisions ask once per other agent. */ 53+ readonly #usesCache = new WeakMap<ReadonlySet<AtomId>, { view: ReadView; base: ReadView; uses: Uses }>(); 54+ /** The newer work's definitions before and after, kept while it is asked about with the same views. */ 55+ readonly #changedCache = new WeakMap<ReadonlySet<AtomId>, { base: ReadView; now: ReadView; defs: Changed }>(); 4457 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) { 4558 this.#graph = graph; @@ -93,47 +106,35 @@
93106 * draft declares itself is its own. A changed definition is any difference 94107 * in the text of the name's definitions (see definitions.ts), including one 95108 * that disappeared; a use that imports the name, or sits in a file that 96− * defines it, only counts that definition.
109+ * defines it, only counts that definition. `nowView` may be a function, called only when the draft uses a name. 99112 draft: ReadonlySet<AtomId>, 101114 baseView: ReadView, 102− nowView: ReadView,
115+ nowView: ReadView | (() => ReadView), 103116 newer: ReadonlySet<AtomId>, 104117 spaceName: string, 105118 ): DefinitionCollision[] { 106119 if (draft.size === 0 || newer.size === 0) return []; 107− const uses = new Map<string, { file: string; index: number }[]>();
108− const declared = new Set<string>();
109− const runsOf = new Map<AtomId, readonly RunEnd[]>();
110− // Only files the draft wrote lines in can hold its lines.
111− const draftFiles = touchedFiles(this.#graph, draft, [view]);
112− for (const file of [...draftFiles].sort()) {
113− if (holdsNoCode(file) || !view.hasFile(file)) continue;
114− const visible = view.lines(file);
115− if (!visible.some((l) => draft.has(l.atom))) continue;
116− const code = codeOfLines(visible.map((l) => l.text));
117− visible.forEach((line, i) => {
118− if (!draft.has(line.atom)) return;
119− for (const name of declaredIn(code[i]!)) declared.add(name);
120− // Only names the change added: a use already on the lines it replaced is not the draft's to answer for.
121− const before = this.#replacedNames(line.id, baseView, runsOf);
122− for (const name of usedNames(code[i]!)) {
123− if (before.has(name)) continue;
124− const list = uses.get(name);
125− if (list) list.push({ file, index: i });
126− else uses.set(name, [{ file, index: i }]);
127− }
128− });
120+ let kept = this.#usesCache.get(draft); 121+ if (!kept || kept.view !== view || kept.base !== baseView) { 122+ kept = { view, base: baseView, uses: this.#usesOf(draft, view, baseView) }; 123+ this.#usesCache.set(draft, kept); 130− for (const name of declared) uses.delete(name);
125+ const uses = kept.uses; 131126 if (uses.size === 0) return []; 127+ const now = typeof nowView === "function" ? nowView() : nowView; 133129 // A definition can only have changed in a file the newer work touched. 134− const touched = touchedFiles(this.#graph, newer, [baseView, nowView]);
135− const baseDefs = definitionsIn(baseView, touched);
136− const nowDefs = definitionsIn(nowView, touched);
130+ let changed = this.#changedCache.get(newer); 131+ if (!changed || changed.base !== baseView || changed.now !== now) { 132+ const touched = touchedFiles(this.#graph, newer, [baseView, now]); 133+ const defs = { baseDefs: definitionsIn(baseView, touched), nowDefs: definitionsIn(now, touched) }; 134+ changed = { base: baseView, now, defs }; 135+ this.#changedCache.set(newer, changed); 137+ const { baseDefs, nowDefs } = changed.defs; 137138 const out: DefinitionCollision[] = []; 138139 for (const [name, where] of [...uses].sort(([a], [b]) => (a < b ? -1 : 1))) { 139140 // Which definitions the uses mean: the file each use imports the name @@ -189,4 +190,33 @@
194+ /** The names the draft's lines use and don't declare, less those the lines they replaced already used. */ 195+ #usesOf(draft: ReadonlySet<AtomId>, view: ReadView, baseView: ReadView): Uses { 196+ const uses = new Map<string, { file: string; index: number }[]>(); 197+ const declared = new Set<string>(); 198+ const runsOf = new Map<AtomId, readonly RunEnd[]>(); 199+ // Only files the draft wrote lines in can hold its lines. 200+ const draftFiles = touchedFiles(this.#graph, draft, [view]); 201+ for (const file of [...draftFiles].sort()) { 202+ if (holdsNoCode(file) || !view.hasFile(file)) continue; 203+ const visible = view.lines(file); 204+ if (!visible.some((l) => draft.has(l.atom))) continue; 205+ const code = codeOfLines(visible.map((l) => l.text)); 206+ visible.forEach((line, i) => { 207+ if (!draft.has(line.atom)) return; 208+ for (const name of declaredIn(code[i]!)) declared.add(name); 209+ // Only names the change added: a use already on the lines it replaced is not the draft's to answer for. 210+ const before = this.#replacedNames(line.id, baseView, runsOf); 211+ for (const name of usedNames(code[i]!)) { 212+ if (before.has(name)) continue; 213+ const list = uses.get(name); 214+ if (list) list.push({ file, index: i }); 215+ else uses.set(name, [{ file, index: i }]); 219+ for (const name of declared) uses.delete(name); --- a/worker/project/draft-collisions.ts
+++ b/worker/project/draft-collisions.ts
@@ -2,7 +2,7 @@
22// is the project in memory. 44import { type AtomId, type Graph, parseKey, type ReadView } from "../../src/engine/index.ts"; 5−import { describeSide, fileOfKey, type Pair } from "./collisions.ts";
5+import { claimantsAmong, describeSide, fileOfKey, pairsFrom } from "./collisions.ts"; 66import type { DefinitionRule } from "./definition-rule.ts"; 77import { type Definition, definedTwice } from "./definitions.ts"; 88import { pathKey } from "./pathkey.ts"; @@ -25,7 +25,6 @@
2525 draft(agent: Agent): AtomId[]; 2626 agentView(agent: Agent): ReadView; 2727 view(set: ReadonlySet<AtomId>): ReadView; 28− pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];
2928 touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; @@ -54,6 +53,38 @@
5453 const sharedView = host.sharedView(); 5554 const out: DraftCollision[] = []; 5655 const side = (agent: string, file: string, s: CollisionSide) => ({ agent, file, lines: s.lines, text: s.text }); 56+ // Every draft change's claimants among all the drafts, found once (abso Capacity): a stored atom's keys are read 57+ // from disk, and a draft deleting a big file has thousands, read again for every other agent. 58+ let claimants: ReadonlyMap<AtomId, readonly AtomId[]> | undefined; 59+ const claimantsOf = (agent: Agent): ReadonlyMap<AtomId, readonly AtomId[]> => { 60+ claimants ??= claimantsAmong( 62+ working.flatMap((a) => host.draft(a)), 64+ const all = claimants; 65+ return new Map(host.draft(agent).map((id) => [id, all.get(id) ?? []])); 67+ // One set per draft, so the definition rule keeps what it worked out about it (abso Capacity). 68+ const draftSets = new Map<Agent, ReadonlySet<AtomId>>(); 69+ const draftSet = (agent: Agent) => { 70+ let set = draftSets.get(agent); 71+ if (!set) draftSets.set(agent, (set = new Set(host.draft(agent)))); 74+ // Shared now with each agent's draft on top, once per agent: the key of a view of a set lists every atom in it. 75+ const nowViews = new Map<Agent, ReadView>(); 76+ const nowViewOf = (agent: Agent) => { 77+ let view = nowViews.get(agent); 78+ if (!view) nowViews.set(agent, (view = host.view(new Set([...shared, ...host.draft(agent)])))); 81+ // Each agent's touched files once, not once per pair (abso Capacity). 82+ const touched = new Map<Agent, Set<string>>(); 83+ const touchedBy = (agent: Agent) => { 84+ let files = touched.get(agent); 85+ if (!files) touched.set(agent, (files = host.touchedFiles(host.draft(agent), [host.agentView(agent)]))); 5788 for (let i = 0; i < working.length; i++) { 5889 for (let j = 0; j < working.length; j++) { 5990 if (i === j) continue; @@ -61,14 +92,14 @@
6192 const b = working[j]!; 6293 const draftA = host.draft(a); 6394 const draftB = host.draft(b); 64− const newer = new Set(draftA);
95+ const newer = draftSet(a); 6596 const union = new Set([...shared, ...draftA, ...draftB]); 6697 const viewA = host.agentView(a); 6798 const viewB = host.agentView(b); 69100 // Lines and attributes: the same either way round, so once per pair. 70101 const paired = new Set<string>(); 71− for (const pair of host.pairs(draftB, newer, union)) {
102+ for (const pair of pairsFrom(host.graph, claimantsOf(b), newer, union)) { 72103 paired.add(`${pair.theirs} ${pair.yours}`); 73104 const file = fileOfKey(pair.keys[0]!.key, viewB); 74105 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, viewB) === file).map((k) => k.key); @@ -96,11 +127,14 @@
97128 // A name both define at the top level of one file: what the second meets once it syncs onto the 98129 // first's work, as the publish rule checks it then. Not when the two definitions are one lines collision. 99− const both = host.view(union);
130+ // The union's view only when the two share a file (abso Capacity): laying out shared plus both drafts 131+ // cost a few seconds a pair on a stored writer. 132+ let both: ReadView | undefined; 100133 const mineA = new Set(draftA); 101134 const mineB = new Set(draftB); 102− const filesA = host.touchedFiles(draftA, [viewA]);
103− for (const file of [...host.touchedFiles(draftB, [viewB])].filter((f) => filesA.has(f)).toSorted()) {
135+ const filesA = touchedBy(a); 136+ for (const file of [...touchedBy(b)].filter((f) => filesA.has(f)).toSorted()) { 137+ both ??= host.view(union); 104138 if (!both.hasFile(file)) continue; 105139 for (const [name, defs] of definedTwice(both, file)) { 106140 const by = (mine: Set<AtomId>) => defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom))); @@ -121,8 +155,8 @@
123157 // Definitions: b's new lines use a name whose definition a's changes change. 124− const nowView = host.view(new Set([...shared, ...draftA]));
125− for (const d of host.definitionRule().collisions(new Set(draftB), viewB, sharedView, nowView, newer, SHARED)) {
158+ const nowView = () => nowViewOf(a); 159+ for (const d of host.definitionRule().collisions(draftSet(b), viewB, sharedView, nowView, newer, SHARED)) { 126160 const c = d.collision; 128162 kind: "definition", --- a/worker/project/overlaps.ts
+++ b/worker/project/overlaps.ts
@@ -70,10 +70,13 @@
7070 // No draft, no view to build: most agents in a big project have nothing unpublished. 7171 if (draft.length === 0) return files; 7272 const view = host.agentView(agent); 73+ // By number where the view can (abso Capacity): a draft deleting a big generated file looked up each line's id. 74+ const byNumber = (view as { fileOfNumber?(n: number): string }).fileOfNumber?.bind(view); 7375 for (const id of draft) { 7476 const atom = host.graph.atom(id); 7577 for (const run of atom.inserts) files.add(isStartNode(run.parent) ? run.file : view.fileOf(run.parent)); 76− for (const line of atom.deletes) files.add(view.fileOf(line));
78+ if (byNumber) for (const n of host.graph.deletedNumbers(id)) files.add(byNumber(n)); 79+ else for (const line of atom.deletes) files.add(view.fileOf(line)); 7780 for (const m of atom.moves ?? []) files.add(view.fileOf(m.line)); --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -1874,7 +1874,6 @@
18741874 draft: (agent) => this.#draft(agent as AgentState), 18751875 agentView: (agent) => this.#agentView(agent as AgentState), 18761876 view: (set) => this.#view(set), 1877− pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
18781877 touchedFiles: (ids, views) => this.#touchedFiles(ids, views), 18801879 return this.#draftCollisionHost; @@ -2719,12 +2718,18 @@
27212720 #agentView(agent: AgentState): ReadView { 2722− return this.#viewKeyed(this.#agentViewKey(agent), () => {
2721+ const view = this.#viewKeyed(this.#agentViewKey(agent), () => { 27232722 const base = this.#at(this.#spaceOf(agent), agent.base); 27242723 return base instanceof StableSet 27252724 ? new StableUnionSet(base, new StableOverlaySet(agent.mine)) 27262725 : new Set([...base, ...agent.mine]); 2727+ // A draft that moves nothing resolves its moves as its base does (abso Capacity): take them from the base's view. 2728+ if (this.#writerStorage && agent.mine.length > 0 && view instanceof View) { 2729+ const base = this.#viewAt(this.#spaceOf(agent), agent.base); 2730+ if (base instanceof View) view.shareMoves(base); 27302735 /** 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. */ --- /dev/null
+++ b/worker/project/test/draft-reads-stored.test.ts
@@ -0,0 +1,54 @@
1+// Reads of agents' drafts on a writer-backed project (abso Capacity): where and draft collisions find files and 2+// lines by line number, take moves from the draft's base, and gather each draft's claimants once among all the 3+// drafts. They must answer as the in-memory project does: drafts that edit, delete a whole file, collide on a line, 4+// define the same name, and sit on bases before and after a move. 6+import assert from "node:assert/strict"; 7+import { test } from "node:test"; 8+import { storedArray } from "../../../src/engine/state-source.ts"; 9+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 10+import { MemoryStore, Project } from "../project.ts"; 11+import type { Entry, ProjectStore } from "../project-types.ts"; 12+import { where } from "../where.ts"; 15+ const storage = new SqlState(); 16+ const entries = storedArray<Entry>(storage, "canonical-log"); 17+ const store: ProjectStore = { 19+ for (const entry of batch) entries.push(entry); 22+ return new Project(store, { writerStorage: storage }); 25+const big = Array.from({ length: 300 }, (_, i) => `generated ${i}\n`).join(""); 27+function history(project: Project) { 29+ project.init({ "a.ts": "one\ntwo\nthree\nfour\n", "big.txt": big, "c.ts": "const x = 1;\n" }, t); 30+ // One agent's base is before a move, the others' after it. 32+ project.record("old", { "a.ts": "one\ntwo\nthree\nfour\nfive\n" }, ++t); 33+ project.move("mover", "c.ts", "d.ts", ++t); 34+ assert.equal(project.publish("mover", "Move c to d", ++t).ok, true); 35+ project.record("ann", { "a.ts": "one\nTWO\nthree\nfour\n", "d.ts": "const x = 2;\n" }, ++t); 36+ project.record("bob", { "a.ts": "one\nTwo\nthree\nfour\n", "big.txt": null }, ++t); 37+ project.record("cy", { "e.ts": "export function f() {}\n" }, ++t); 38+ project.record("dee", { "e.ts": "export function f() { return 1; }\n" }, ++t); 39+ project.sync("idle"); 42+test("where and draft collisions on a stored writer match the in-memory project's", () => { 43+ const oracle = new Project(new MemoryStore()); 44+ const project = writer(); 47+ const expected = where(oracle); 48+ assert.ok(expected.files["big.txt"], "bob's deleted file is listed"); 49+ assert.deepEqual(where(project), expected); 50+ const collisions = oracle.collisions(); 51+ assert.ok(collisions.collisions.length > 0, "ann and bob collide on a.ts"); 52+ assert.deepEqual(project.collisions(), collisions); 53+ assert.deepEqual(project.collisions({ file: "a.ts" }), oracle.collisions({ file: "a.ts" })); --- a/worker/project/where.ts
+++ b/worker/project/where.ts
@@ -3,11 +3,18 @@
33// two ways: in the agent's own view (what its folder shows), and in shared's 44// numbering (the shared lines it changes, or the shared line its new lines 55// follow), so agents can compare where they are against one common text. 6−import type { AtomId, LineId } from "../../src/engine/index.ts";
6+import { type AtomId, type LineId, type ReadView, seqOf } from "../../src/engine/index.ts"; 77import type { Project } from "./project.ts"; 99type Range = [number, number]; 11+/** A view's reads by line number (View has them; another ReadView may not). */ 12+type ByNumber = ReadView & { 13+ fileOfNumber?(n: number): string; 14+ lineNumberOf?(path: string, n: number): number; 15+ visibleWriters?(path: string): readonly number[]; 1118function ranges(ns: number[]): Range[] { 1219 const out: Range[] = []; 1320 for (const n of [...new Set(ns)].sort((a, b) => a - b)) { @@ -30,11 +37,18 @@
3138export function where(project: Project) { 3239 const graph = project.graph; 33− let shared: ReturnType<Project["sharedView"]> | undefined;
34− const sharedNumber = (file: string, id: LineId): number | undefined => {
35− shared ??= project.sharedView();
40+ let shared: ByNumber | undefined; 41+ // By the file's index of visible lines (abso Capacity): finding it in lines() built every line of the file again 42+ // whenever the file changed, per line asked. 43+ const sharedNumber = (file: string, line: LineId | number): number | undefined => { 44+ shared ??= project.sharedView() as ByNumber; 3645 if (!shared.hasFile(file)) return undefined; 37− const i = shared.lines(file).findIndex((l) => l.id === id);
47+ typeof line === "string" 48+ ? shared.lineNumber(file, line) 49+ : shared.lineNumberOf 50+ ? shared.lineNumberOf(file, line) 51+ : shared.lineNumber(file, graph.lineIdOf(line)); 3852 return i >= 0 ? i + 1 : undefined; 4054 const files: Record<string, Spot[]> = {}; @@ -42,6 +56,10 @@
4256 const draft = project.draftOf(agent); 4357 if (!draft || draft.atoms.length === 0) continue; 4458 const mine = new Set<AtomId>(draft.atoms); 59+ // Once per agent (abso Capacity): each read of draft.view asks the project's view cache, which weighs every 61+ const view = draft.view as ByNumber; 62+ const fileOfNumber = view.fileOfNumber?.bind(view); 4563 const perFile = new Map<string, { view: number[]; shared: number[]; changes: Set<AtomId>; last: number }>(); 4664 const at = (file: string) => { 4765 let s = perFile.get(file); @@ -52,7 +70,7 @@
5270 const atom = graph.atom(id); 5371 for (const run of atom.inserts) { 5472 // A line moved by someone (#28) is in the file the draft's view puts it in. 55− const file = run.parent.startsWith("^") ? run.file : draft.view.fileOf(run.parent);
73+ const file = run.parent.startsWith("^") ? run.file : view.fileOf(run.parent); 5876 s.last = Math.max(s.last, atom.time); @@ -60,10 +78,23 @@
6078 const anchor = run.parent.startsWith("^") ? 0 : sharedNumber(file, run.parent); 6179 if (anchor !== undefined) s.shared.push(Math.max(anchor, 1)); 81+ // By number where the view can (abso Capacity): a draft deleting a big generated file read every line's text 82+ // to check it exists, and looked up each line's id. 84+ for (const line of graph.deletedNumbers(id)) { 85+ const file = fileOfNumber(line); 88+ s.last = Math.max(s.last, atom.time); 89+ const n = sharedNumber(file, line); 90+ if (n !== undefined) s.shared.push(n); 6394 for (const lineId of atom.deletes) { 6495 const info = graph.line(lineId); 6596 if (!info) continue; 66− const file = draft.view.fileOf(lineId);
97+ const file = view.fileOf(lineId); 69100 s.last = Math.max(s.last, atom.time); @@ -72,10 +103,16 @@
74105 for (const [file, s] of perFile) { 75− if (draft.view.hasFile(file)) {
76− draft.view.lines(file).forEach((l, i) => {
77− if (mine.has(l.atom)) s.view.push(i + 1);
78− });
106+ if (view.hasFile(file)) { 107+ if (view.visibleWriters) { 108+ const seqs = new Set(draft.atoms.map(seqOf)); 109+ view.visibleWriters(file).forEach((seq, i) => { 110+ if (seqs.has(seq)) s.view.push(i + 1); 113+ view.lines(file).forEach((l, i) => { 114+ if (mine.has(l.atom)) s.view.push(i + 1); 80117 (files[file] ??= []).push({