- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/build.ts --json
- JSON
- /christopher/abso-core/blame/src/engine/build.ts?format=json
576 linesFirst import 85% · codex-capacity-chair 15%Last change codex-capacity-chair in version 175,
576 lines from 6 changes in 4 versions.
init0Start the project1// Building an atom from an edit against a view. Agents say "replace this exact
2// text with that text" (or "replace these visible lines with these lines");
3// the engine turns it into deletes, inserts, claim keys and derived deps.
5import { Graph } from "./graph.ts";
6import { attrKey, gapKey, isStartNode, lineKey, parseKey, posKey, startNode, writerOf } from "./keys.ts";
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare7import { diffChunkedLines, joinLines, normalizeText, splitLines } from "./text.ts";
9 ATTR_NAMES,
10 type Atom,
11 type AtomId,
12 type AttrSet,
13 EngineError,
14 type InsertRun,
15 type Key,
16 type LineId,
17 MODES,
18 type Mode,
19 type NodeId,
20 REASON_KINDS,
21 type Reason,
22 type Relocation,
23} from "./types.ts";
24import { View } from "./view.ts";
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare26/** Exact read surface used to build atoms; membership requires point lookup only. */
27export type AtomBuildView = Pick<View, "graph" | "lines" | "sequence" | "sequenceIndex" | "parentOf"> & {
28 readonly set: Pick<ReadonlySet<AtomId>, "has">;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare29 buildLines?: View["buildLines"];
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare30};
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare32function buildingLines(view: AtomBuildView, path: string) {
33 return view.buildLines ? view.buildLines(path) : view.lines(path);
34}
36/** Cache only within one immutable build; never retain handles across writes. */
37function cachedBuildView(view: AtomBuildView): AtomBuildView {
38 const files = new Map<string, ReturnType<View["lines"]>>();
39 return {
40 graph: view.graph,
41 set: view.set,
42 lines(path) {
43 let lines = files.get(path);
44 if (!lines) {
45 lines = buildingLines(view, path);
46 files.set(path, lines);
47 }
48 return lines;
49 },
50 sequence: (path) => view.sequence(path),
51 sequenceIndex: (path, line) => view.sequenceIndex(path, line),
52 parentOf: (line) => view.parentOf(line),
53 };
54}
57export interface TextEdit {
58 readonly file: string;
59 readonly old: string;
60 readonly new: string;
61 readonly mode?: Mode;
62}
64/**
65 * Replace visible lines [start, end) of `file` (0-based) with `lines`. With
66 * start === end it is a pure insertion before line `start`. This is the form
67 * a git hunk maps onto.
68 */
69export interface SpliceEdit {
70 readonly file: string;
71 readonly start: number;
72 readonly end: number;
73 readonly lines: readonly string[];
74 readonly mode?: Mode;
75}
77export type EditInput = TextEdit | SpliceEdit;
79/** Visible lines [start, end) of a file, 0-based, end exclusive, non-empty. */
80export interface LineRange {
81 readonly file: string;
82 readonly start: number;
83 readonly end: number;
84}
86/**
87 * Move visible lines [start, end) of `file` (0-based, non-empty) so they sit
88 * just before visible line `at` of `to` (at === its line count: the end).
89 * `to` may be the same file, with `at` outside [start, end]. The lines keep
90 * their ids, so edits to them, made before or after, follow them (#28).
91 */
92export interface MoveInput {
93 readonly file: string;
94 readonly start: number;
95 readonly end: number;
96 readonly to: string;
97 readonly at: number;
98}
100export interface AtomInput {
101 readonly author: string;
102 /** The why. */
103 readonly message: string;
104 /** Milliseconds since the epoch. Defaults to 0; the engine never reads a clock. */
105 readonly time?: number;
106 /** Edits, all matched against the same view; their line spans may not overlap. */
107 readonly edits?: readonly EditInput[];
108 /**
109 * "My change relies on these lines staying as they are": holds each line and
110 * the gaps between them, so an edit landing anywhere in the range trips it.
111 */
112 readonly reliesOn?: readonly LineRange[];
113 /** Claim spans: hold these lines and the gaps between them (what a claim-only atom is made of). */
114 readonly spans?: readonly LineRange[];
115 /** Explicit dependencies. */
116 readonly needs?: readonly AtomId[];
117 /** Atoms whose conflict this atom settles. Implies needs. */
118 readonly resolves?: readonly AtomId[];
119 readonly reasons?: readonly Reason[];
120 /** File attributes to set: an empty file's existence, the executable bit, a link target. */
121 readonly attrs?: readonly AttrSet[];
122 /** One block of lines to move. Not together with edits. */
123 readonly move?: MoveInput;
124}
126/** An edit after matching: visible lines [start, end) of `file` become `lines`. */
127interface Region {
128 readonly file: string;
129 readonly start: number;
130 readonly end: number;
131 readonly lines: readonly string[];
132 readonly mode: Mode;
133 readonly order: number;
134}
136/**
137 * Build (but do not accept) an atom from edits against a view. The atom gets
138 * the graph's next id; accept it with `graph.add(atom)` and put it in a set.
139 * Its dependencies are derived from what it touched in the view (see deriveDeps).
140 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare141export function buildAtom(view: AtomBuildView, input: AtomInput): Atom {
143}
145/** The starting snapshot: a0, inserting every line of every file. Empty files are skipped. */
146export function buildBase(
147 files: Readonly<Record<string, string>>,
148 meta: { author: string; message: string; time?: number },
149 attrs: readonly AttrSet[] = [],
150): Atom {
151 const view = new View(new Graph(), []);
152 const edits: TextEdit[] = Object.keys(files)
153 .sort()
154 .filter((file) => files[file] !== "")
155 .map((file) => ({ file, old: "", new: files[file]! }));
156 return build(view, { ...meta, edits, attrs }, true);
157}
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare159function build(view: AtomBuildView, input: AtomInput, allowEmpty: boolean): Atom {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare160 view = cachedBuildView(view);
162 const id = graph.nextId();
163 if (typeof input.author !== "string" || typeof input.message !== "string") {
164 throw new EngineError("bad-edit", "an atom needs an author and a message");
165 }
166 const time = input.time ?? 0;
167 if (!Number.isFinite(time)) throw new EngineError("bad-edit", "time must be a finite number");
169 const regions = resolveRegions(view, input.edits ?? []);
170 if (input.move !== undefined && regions.length > 0)
171 throw new EngineError("bad-edit", "a move goes in an atom of its own, without edits");
173 const inserts: InsertRun[] = [];
174 const deletes: LineId[] = [];
175 const writes = new Set<Key>();
176 const reads = new Set<Key>();
177 const holds = new Set<Key>();
178 const emptiedBy = new Set<AtomId>();
180 for (const region of regions) {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare181 const visible = buildingLines(view, region.file);
182 function* oldLines() {
183 for (let i = region.start; i < region.end; i++) {
184 const line = visible[i]!;
185 yield () => (line.textChunks ? line.textChunks() : [line.text]);
186 }
187 }
188 for (const hunk of diffChunkedLines(oldLines(), region.lines)) {
190 const end = region.start + hunk.end;
191 let parent: NodeId;
192 if (end > start) {
193 // Replacement: delete the old lines; new lines hang off the last deleted one.
194 for (let i = start; i < end; i++) {
195 const line = visible[i]!.id;
196 deletes.push(line);
197 writes.add(lineKey(line));
198 }
199 parent = visible[end - 1]!.id;
200 } else {
201 // Pure insertion between X (above, or the start node) and Y (below, or end of file).
202 const above = start > 0 ? visible[start - 1]!.id : undefined;
203 const below = start < visible.length ? visible[start]!.id : undefined;
204 parent = above ?? startNode(region.file);
205 writes.add(gapKey(parent));
206 // after reads only X and before only Y; at the edge of a file each
207 // reads the neighbour there is, so an insertion into a non-empty file
208 // always claims a line of it.
209 if (above !== undefined && (region.mode !== "before" || below === undefined)) reads.add(lineKey(above));
210 if (below !== undefined && (region.mode !== "after" || above === undefined)) reads.add(lineKey(below));
211 // Creating a file over a deleted one relies on it being empty.
212 if (visible.length === 0) {
213 for (const line of view.sequence(region.file)) for (const d of line.deletedBy) emptiedBy.add(d);
214 }
215 }
216 if (hunk.lines.length > 0) inserts.push({ file: region.file, parent, lines: [...hunk.lines] });
217 }
218 if (region.mode === "wide")
219 holdSpan(
220 visible.slice(region.start, region.end).map((l) => l.id),
221 holds,
222 );
223 }
225 const moves = input.move !== undefined ? planMove(view, input.move, writes, reads) : [];
227 const attrs: AttrSet[] = [];
228 for (const a of input.attrs ?? []) {
229 if (typeof a?.file !== "string" || a.file === "" || /[\n\r]/.test(a.file) || !ATTR_NAMES.includes(a.name)) {
230 throw new EngineError("bad-edit", `an attribute needs a file and one of ${ATTR_NAMES.join(", ")}`);
231 }
232 if (a.value !== null && typeof a.value !== "string")
233 throw new EngineError("bad-edit", "an attribute value is a string or null");
234 if (attrs.some((x) => x.file === a.file && x.name === a.name))
235 throw new EngineError("bad-edit", `${a.name} of ${a.file} set twice`);
236 attrs.push({ file: a.file, name: a.name, value: a.value });
237 writes.add(attrKey(a.file, a.name));
238 }
240 for (const range of input.reliesOn ?? []) holdSpan(rangeLines(view, range), holds);
241 for (const range of input.spans ?? []) holdSpan(rangeLines(view, range), holds);
243 const needs = uniqueAtoms(view, input.needs ?? [], "needs");
244 const resolves = uniqueAtoms(view, input.resolves ?? [], "resolves");
245 const reasons = (input.reasons ?? []).map((r) => {
246 if (!REASON_KINDS.includes(r.kind)) {
247 throw new EngineError("bad-edit", `reason kind must be one of ${REASON_KINDS.join(", ")}, not ${String(r.kind)}`);
248 }
249 if (!graph.has(r.to)) throw new EngineError("unknown-atom", `reason points at unknown atom ${r.to}`);
250 if (typeof r.text !== "string") throw new EngineError("bad-edit", "a reason needs text");
251 return { to: r.to, kind: r.kind, text: r.text };
252 });
254 const nothing =
255 inserts.length === 0 &&
256 deletes.length === 0 &&
257 holds.size === 0 &&
258 needs.length === 0 &&
259 resolves.length === 0 &&
260 reasons.length === 0 &&
261 attrs.length === 0 &&
262 moves.length === 0;
263 if (nothing && !allowEmpty) {
264 throw new EngineError("empty-atom", "the edit changes nothing and claims nothing");
265 }
267 const sortedWrites = [...writes].sort();
268 const sortedReads = [...reads].sort();
269 const sortedHolds = [...holds].sort();
270 const deps = deriveDeps(view, {
271 writes: sortedWrites,
272 reads: sortedReads,
273 holds: sortedHolds,
274 emptiedBy,
275 needs,
276 resolves,
277 });
279 return {
280 id,
281 seq: graph.size,
282 author: input.author,
283 message: input.message,
284 time,
285 inserts,
286 deletes,
287 writes: sortedWrites,
288 reads: sortedReads,
289 holds: sortedHolds,
290 needs,
291 resolves,
292 reasons,
293 deps,
294 ...(attrs.length > 0 ? { attrs } : {}),
295 ...(moves.length > 0 ? { moves } : {}),
296 };
297}
299/**
300 * The relocations that move a block. In the file's full sequence (tombstones
301 * included), the block runs from its first line to its last. Afterwards the
302 * block must sit right after D (the visible line before `at`, or the start
303 * node), and everything else must keep its order. So:
304 * - the block's first line moves to D;
305 * - a later block line whose parent is outside the block moves to the block
306 * line before it (which has no children, the walk being depth-first);
307 * - a line after the block whose parent is inside it moves to the line before
308 * it once the block is gone (the line before the block, for the first).
309 * It writes P: of every block line and of every line it relocates, and G: of
310 * every new parent. It reads P:D, so two moves made apart that would loop
311 * lines into each other collide in all but the rarest cases (the view breaks
312 * any loop that is left).
313 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare314function planMove(view: AtomBuildView, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] {
316 if (typeof path !== "string" || path === "" || /[\n\r]/.test(path))
317 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(path)}`);
318 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare319 const visible = buildingLines(view, move.file);
321 if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end > visible.length || start >= end) {
322 throw new EngineError(
323 "bad-range",
324 `${move.file} lines [${start}, ${end}) are not a non-empty range of its ${visible.length} visible lines`,
325 );
326 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare327 const dest = buildingLines(view, move.to);
329 throw new EngineError("bad-range", `${move.to} has no place ${at} (it has ${dest.length} visible lines)`);
330 }
331 if (move.to === move.file && at >= start && at <= end)
332 throw new EngineError("bad-range", "the lines are already there");
333 const sequence = view.sequence(move.file);
334 const i = view.sequenceIndex(move.file, visible[start]!.id);
335 const j = view.sequenceIndex(move.file, visible[end - 1]!.id);
336 const block = sequence.slice(i, j + 1).map((l) => l.id);
337 const inBlock = new Set(block);
338 const target: NodeId = at > 0 ? dest[at - 1]!.id : startNode(move.to);
340 const out: Relocation[] = [{ line: block[0]!, parent: target }];
341 for (let k = 1; k < block.length; k++) {
342 if (!inBlock.has(view.parentOf(block[k]!))) out.push({ line: block[k]!, parent: block[k - 1]! });
343 }
344 for (let m = j + 1; m < sequence.length; m++) {
345 const line = sequence[m]!.id;
346 if (!inBlock.has(view.parentOf(line))) continue;
347 const parent = m === j + 1 ? (i > 0 ? sequence[i - 1]!.id : startNode(move.file)) : sequence[m - 1]!.id;
348 out.push({ line, parent });
349 }
350 for (const line of block) writes.add(posKey(line));
351 for (const r of out) {
352 writes.add(posKey(r.line));
353 writes.add(gapKey(r.parent));
354 }
355 if (!isStartNode(target)) reads.add(posKey(target));
356 return out;
357}
359/**
360 * Derived dependencies of a new atom against its view (docs/prototype.md,
361 * "Dependencies"):
362 * - blame: the writers of every line its keys name (a G: key names the line
363 * the gap follows);
364 * - gap rule: atoms in the view that wrote a gap it inserts into or holds.
365 * Their lines hang off the same line, so the new run outranks all of them
366 * and lands directly after its parent;
367 * - implicit-read rule: atoms in the view whose implicit reads include a key
368 * it writes (it saw that insert and changed its neighbour);
369 * - creating a file over a deleted one: the atoms that deleted its lines;
370 * - needs and resolves.
371 * Nothing else from the view: not the line below an insertion, not the
codex-capacity-chair124Reduce implicit dependencies to their maximal frontierCompare372 * tombstones around it. New atoms encode implicit dependencies as maximal
373 * tips: ancestors reachable through another tip are omitted from direct deps.
374 * Explicit needs/resolves always remain direct. Existing atoms are not rewritten.
375 * Direct-edge diagnostics (including why/Deps trailers and missingDeps) therefore
376 * show fewer redundant edges; transitive closure and dependency ordering remain
377 * the semantic contract. A missing tip still implies its required ancestors.
379function deriveDeps(
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare380 view: AtomBuildView,
382 writes: readonly Key[];
383 reads: readonly Key[];
384 holds: readonly Key[];
385 emptiedBy: ReadonlySet<AtomId>;
386 needs: readonly AtomId[];
387 resolves: readonly AtomId[];
388 },
389): AtomId[] {
390 const graph = view.graph;
codex-capacity-chair124Reduce implicit dependencies to their maximal frontierCompare391 // New atoms retain maximal implicit dependencies. Their transitive closure is
392 // unchanged; explicit needs/resolves remain direct edges below.
393 const deps = new Set<AtomId>();
394 const addImplicit = (candidate: AtomId): void => {
395 if (deps.has(candidate)) return;
396 const candidateClock = graph.lamport(candidate);
397 for (const previous of deps) {
398 const previousClock = graph.lamport(previous);
399 // Equal Lamport clocks cannot reach each other; check only the possible direction.
400 if (previousClock > candidateClock && graph.dependsOn(previous, candidate)) return;
401 if (candidateClock > previousClock && graph.dependsOn(candidate, previous)) deps.delete(previous);
402 }
403 deps.add(candidate);
404 };
405 for (const id of parts.emptiedBy) addImplicit(id);
407 const { kind, node } = parseKey(key);
408 // An attribute builds on whoever set it last in the view, the way an insertion builds on a gap's writers;
409 // a move builds on the earlier moves of its lines.
codex-capacity-chair124Reduce implicit dependencies to their maximal frontierCompare410 if (kind !== "attr" && !isStartNode(node)) addImplicit(writerOf(node));
411 if (kind !== "line") for (const writer of graph.eachWriterOf(key)) if (view.set.has(writer)) addImplicit(writer);
413 for (const key of parts.writes) {
codex-capacity-chair124Reduce implicit dependencies to their maximal frontierCompare414 for (const reader of graph.eachReaderOf(key)) if (view.set.has(reader)) addImplicit(reader);
416 for (const id of parts.needs) deps.add(id);
417 for (const id of parts.resolves) deps.add(id);
418 return [...deps].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq);
419}
421/** Hold every line of a span and every gap between consecutive lines of it. */
422function holdSpan(lines: readonly LineId[], holds: Set<Key>): void {
423 lines.forEach((line, i) => {
424 holds.add(lineKey(line));
425 if (i + 1 < lines.length) holds.add(gapKey(line));
426 });
427}
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare429function rangeLines(view: AtomBuildView, range: LineRange): LineId[] {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare430 const visible = buildingLines(view, range.file);
432 !Number.isInteger(range.start) ||
433 !Number.isInteger(range.end) ||
434 range.start < 0 ||
435 range.end > visible.length ||
436 range.start >= range.end
437 ) {
438 throw new EngineError(
439 "bad-range",
440 `${range.file} lines [${range.start}, ${range.end}) are not a non-empty range of its ${visible.length} visible lines`,
441 );
442 }
443 return visible.slice(range.start, range.end).map((l) => l.id);
444}
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare446function uniqueAtoms(view: AtomBuildView, ids: readonly AtomId[], what: string): AtomId[] {
448 for (const id of ids) {
449 if (!view.graph.has(id)) throw new EngineError("unknown-atom", `${what} names unknown atom ${id}`);
450 if (!view.set.has(id)) throw new EngineError("not-in-view", `${what} names ${id}, which is not in the view`);
451 if (!out.includes(id)) out.push(id);
452 }
453 return out.sort((a, b) => view.graph.atom(a).seq - view.graph.atom(b).seq);
454}
456// Matching edits ---------------------------------------------------------------
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare458function resolveRegions(view: AtomBuildView, edits: readonly EditInput[]): Region[] {
460 const mode = edit.mode ?? "both";
461 if (!MODES.includes(mode)) throw new EngineError("bad-edit", `mode must be one of ${MODES.join(", ")}`);
462 // A path may start with '^' (a start node is '^' + path, so '^^x' stays unambiguous).
463 if (typeof edit.file !== "string" || edit.file === "" || /[\n\r]/.test(edit.file)) {
464 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(edit.file)}`);
465 }
466 return "old" in edit ? matchText(view, edit, mode, order) : matchSplice(view, edit, mode, order);
467 });
469 // Files in order of first appearance; within a file, regions in position order.
470 const fileOrder = new Map<string, number>();
471 for (const r of regions) if (!fileOrder.has(r.file)) fileOrder.set(r.file, fileOrder.size);
472 regions.sort(
473 (a, b) =>
474 fileOrder.get(a.file)! - fileOrder.get(b.file)! || a.start - b.start || a.end - b.end || a.order - b.order,
475 );
476 for (let i = 1; i < regions.length; i++) {
477 const prev = regions[i - 1]!;
478 const cur = regions[i]!;
479 if (prev.file === cur.file && prev.end > cur.start) {
480 throw new EngineError(
481 "overlapping-edits",
482 `two edits to ${cur.file} overlap (lines ${prev.start + 1}-${prev.end} and ${cur.start + 1}-${cur.end})`,
483 );
484 }
485 }
486 return regions;
487}
489/**
490 * Find `old` (exactly once) in the file's visible text and widen the match to
491 * whole lines. If the replacement would leave a line without its newline, the
492 * next line joins the region (that is what the plain-text edit does).
493 */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare494function matchText(view: AtomBuildView, edit: TextEdit, mode: Mode, order: number): Region {
496 throw new EngineError("bad-edit", "a text edit needs old and new strings");
497 }
498 const file = edit.file;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare499 const visible = buildingLines(view, file);
501 const newText = normalizeText(edit.new);
502 if (oldText === "") {
503 if (visible.length > 0) {
504 throw new EngineError(
505 "ambiguous-match",
506 `empty old text matches everywhere in ${file}; an empty old text only creates a file`,
507 );
508 }
509 return { file, start: 0, end: 0, lines: splitLines(newText), mode, order };
510 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare511 const texts = visible.map((line) => line.text);
512 const text = joinLines(texts);
514 if (at < 0) throw new EngineError("no-match", `old text not found in ${file}`);
515 if (text.indexOf(oldText, at + 1) >= 0) {
516 throw new EngineError(
517 "ambiguous-match",
518 `old text matches more than once in ${file}; add context to make it unique`,
519 );
520 }
521 const starts: number[] = [];
522 let pos = 0;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare523 for (const text of texts) {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare525 pos += text.length + 1;
527 const lineAt = (offset: number): number => {
528 let lo = 0;
529 let hi = starts.length - 1;
530 while (lo < hi) {
531 const mid = (lo + hi + 1) >> 1;
532 if (starts[mid]! <= offset) lo = mid;
533 else hi = mid - 1;
534 }
535 return lo;
536 };
537 const end = at + oldText.length;
538 const startLine = lineAt(at);
539 let endLine = lineAt(end - 1);
540 const lineStart = starts[startLine]!;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare541 const lineEnd = starts[endLine]! + texts[endLine]!.length + 1;
init0Start the project542 let replacement = text.slice(lineStart, at) + newText + text.slice(end, lineEnd);
543 if (replacement !== "" && !replacement.endsWith("\n")) {
544 if (endLine + 1 < visible.length) {
545 endLine++;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare546 replacement += `${texts[endLine]}\n`;
548 replacement += "\n";
549 }
550 }
551 return { file, start: startLine, end: endLine + 1, lines: splitLines(replacement), mode, order };
552}
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare554function matchSplice(view: AtomBuildView, edit: SpliceEdit, mode: Mode, order: number): Region {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare555 const count = buildingLines(view, edit.file).length;
557 !Number.isInteger(edit.start) ||
558 !Number.isInteger(edit.end) ||
559 edit.start < 0 ||
560 edit.start > edit.end ||
561 edit.end > count
562 ) {
563 throw new EngineError(
564 "bad-range",
565 `${edit.file} lines [${edit.start}, ${edit.end}) are outside its ${count} visible lines`,
566 );
567 }
568 if (!Array.isArray(edit.lines)) throw new EngineError("bad-edit", "a splice edit needs lines");
569 const lines = edit.lines.map((line) => {
570 if (typeof line !== "string" || /[\n\r]/.test(line)) {
571 throw new EngineError("bad-edit", "splice lines must be strings without line breaks");
572 }
573 return line;
574 });
575 return { file: edit.file, start: edit.start, end: edit.end, lines, mode, order };
576}