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
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/worker/project/express-moves.ts?format=json
261 linesFirst import 74% · codex-capacity-chair 17% · capacity 10%Last change capacity in version 311, 6 versions changed it
1import { diffLineSymbols } from "../../src/engine/text.ts";
2import { recordFileChanges } from "./record-file.ts";
3// Moves (#28): within one agent's unpublished draft, a line that leaves one place and the same
4// text that arrives somewhere else is the same line. Before a publish, those matches become move
5// atoms so the lines keep their ids. Writes go through ExpressMovesHost; today the host is Project.
6
7import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, ReadView } from "../../src/engine/index.ts";
8import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts";
9import { MoveLineText } from "./move-line-text.ts";
10import type { AgentState, Entry, Meta, Mode } from "./project-types.ts";
12/** The most moved blocks one publish expresses: the longest ones, when there are more. */
13export const MOVE_LIMIT = 64;
14/** About how many lines one publish may lay out to express moves: each move lays out its files again. */
15export const MOVE_BUDGET = 200_000;
16/** The most places one deleted text is tried as the start of a moved stretch. */
17export const MATCH_STARTS = 256;
19/** What expressing moves needs from a project. */
20export interface ExpressMovesHost {
21 readonly graph: Graph;
22 draft(agent: AgentState): AtomId[];
23 agentView(agent: AgentState): ReadView;
24 beforeDraft?(agent: AgentState, draft: readonly AtomId[]): ReadView;
25 view(set: ReadonlySet<AtomId>): ReadView;
26 apply(entry: Entry): void;
27 addDraft(
28 agent: AgentState,
29 view: ReadView,
30 input: { edits: readonly EditInput[]; attrs?: readonly AttrSet[]; move?: MoveInput },
31 time: number,
32 meta: Meta,
33 entries: Entry[],
34 ): void;
35 recordFile(
36 agent: AgentState,
37 view: ReadView,
38 path: string,
39 text: string | null | undefined,
40 time: number,
41 meta: Meta,
42 entries: Entry[],
43 mode?: Mode,
44 ): boolean;
47/**
48 * Moves (#28). Within one agent's unpublished draft, a line that leaves one
49 * place and the same text that arrives somewhere else is the same line, in
50 * either order (deleted then written, or written then deleted). Before a
51 * publish, the draft's changes to the files involved are dropped (a discard
52 * entry) and made again: one move per matched block, which keeps the
53 * lines' ids, then a change per file to the draft's final text. The files
54 * end up exactly as the draft had them. A matched block needs a line with
55 * real content: blank lines and lone brackets only travel next to one.
56 * The agent's publishes waiting in the queue keep their changes: they count
57 * as already there, never dropped (abso issue 135, item 4).
58 */
59export function expressMoves(host: ExpressMovesHost, agent: AgentState, time: number, entries: Entry[]): void {
60 const draft = host.draft(agent);
61 if (draft.length === 0) return;
62 const g = host.graph;
63 const mine = new Set(draft);
64 const text = new MoveLineText(g);
65 // The draft's own lines first, before laying out any file (abso 714, piece 3): a move needs a written line with
66 // real content whose text the draft also deleted. An edit that only changes lines has none, and laying out its
67 // files (12k lines twice for one changed line of worker/src/index.ts) cost the whole publish.
68 const goneIds = new Set<LineId>();
69 const goneTexts = new Set<number>();
70 for (const id of draft)
71 for (const line of g.deletedLines(id)) {
72 goneIds.add(line);
73 goneTexts.add(text.intern(line));
74 }
75 if (goneTexts.size === 0) return;
76 let moved = false;
77 for (const id of draft) {
78 for (const line of g.eachInsertedLine(id)) {
79 const t = text.intern(line);
80 if (!text.plain[t] && goneTexts.has(t)) {
81 moved = true;
82 break;
83 }
84 }
85 if (moved) break;
86 }
87 if (!moved) return;
88 const after = host.agentView(agent);
89 const before = host.beforeDraft
90 ? host.beforeDraft(agent, draft)
91 : host.view(differenceSet(after.set, new StableOverlaySet(draft)));
92 const touched = new Set<string>();
93 for (const id of draft) for (const file of g.filesOf(id)) touched.add(file);
95 // Blocks of lines the draft deleted, and runs of lines it wrote, each consecutive.
96 interface Block {
97 readonly file: string;
98 readonly start: number;
99 readonly ids: LineId[];
100 readonly texts: number[];
101 }
102 const gone: Block[] = [];
103 const written: Block[] = [];
104 for (const file of [...touched].toSorted()) {
105 let cur: Block | undefined;
106 before.buildLines(file).forEach((l, i) => {
107 // Deleted by the draft: one of its atoms' deleted lines, with no lookup of each line's deleters.
108 if (goneIds.has(l.id)) {
109 if (!cur) gone.push((cur = { file, start: i, ids: [], texts: [] }));
110 cur.ids.push(l.id);
111 cur.texts.push(text.intern(l.id));
112 } else cur = undefined;
113 });
114 cur = undefined;
115 after.buildLines(file).forEach((l, i) => {
116 if (mine.has(l.atom)) {
117 if (!cur) written.push((cur = { file, start: i, ids: [], texts: [] }));
118 cur.ids.push(l.id);
119 cur.texts.push(text.intern(l.id));
120 } else cur = undefined;
121 });
122 }
123 if (gone.length === 0 || written.length === 0) return;
125 // Match: for each written run, the longest stretches that some deleted block has too.
126 interface Match {
127 readonly from: string;
128 readonly ids: LineId[];
129 readonly to: string;
130 /** Where the stretch starts in the draft's final text of `to`. */
131 readonly at: number;
132 }
133 const used = new Set<LineId>();
134 const matches: Match[] = [];
135 // Where each deleted text starts a candidate, in block and line order (abso issue 158): a stretch
136 // can only start where the texts are equal, so each written line looks only there, not at
137 // every deleted line. A text deleted more than MATCH_STARTS times keeps its first ones.
138 const starts = new Map<number, { block: Block; q: number }[]>();
139 for (const block of gone)
140 block.texts.forEach((t, q) => {
141 const list = starts.get(t);
142 if (!list) starts.set(t, [{ block, q }]);
143 else if (list.length < MATCH_STARTS) list.push({ block, q });
144 });
145 for (const run of written) {
146 let p = 0;
147 while (p < run.texts.length) {
148 let best: { block: Block; q: number; len: number } | undefined;
149 for (const { block, q } of starts.get(run.texts[p]!) ?? []) {
150 let len = 0;
151 while (
152 p + len < run.texts.length &&
153 q + len < block.texts.length &&
154 run.texts[p + len] === block.texts[q + len] &&
155 !used.has(block.ids[q + len]!)
156 ) {
157 len++;
158 }
159 if (len > 0 && (!best || len > best.len)) best = { block, q, len };
160 }
161 if (best?.block.texts.slice(best.q, best.q + best.len).some((t) => !text.plain[t])) {
162 const ids = best.block.ids.slice(best.q, best.q + best.len);
163 for (const id of ids) used.add(id);
164 matches.push({ from: best.block.file, ids, to: run.file, at: run.start + p });
165 p += best.len;
166 } else p++;
167 }
168 }
169 if (matches.length === 0) return;
170 // Each match lays its files out again, so the cost is matches times file length (abso issues 137,
171 // 142): a rewritten 23,572-line JSON file made 438 matches, 399 of them one line, and the publish
172 // passed Workers' CPU limit. So the longest blocks move first, up to MOVE_LIMIT of them and
173 // MOVE_BUDGET lines laid out in all; the rest are a delete and a fresh write, as an unmatched block
174 // always is.
175 const length = (path: string) => (after.hasFile(path) ? after.buildLines(path).length : 0);
176 const cost = (m: Match) => length(m.from) + (m.to === m.from ? 0 : length(m.to));
177 const keep = new Set<Match>();
178 let spent = 0;
179 for (const { m } of matches
180 .map((m, i) => ({ m, i }))
181 .toSorted((a, b) => b.m.ids.length - a.m.ids.length || a.i - b.i)) {
182 if (keep.size >= MOVE_LIMIT) break;
183 if (keep.size > 0 && spent + cost(m) > MOVE_BUDGET) continue;
184 spent += cost(m);
185 keep.add(m);
186 }
187 for (let i = matches.length - 1; i >= 0; i--) if (!keep.has(matches[i]!)) matches.splice(i, 1);
189 // Drop the draft's changes to the files involved, and whatever builds on them.
190 const involved = new Set<string>(matches.flatMap((m) => [m.from, m.to]));
191 const drop = new Set<AtomId>();
192 for (let grew = true; grew; ) {
193 grew = false;
194 for (const id of draft) {
195 if (drop.has(id)) continue;
196 const atom = g.atom(id);
197 if (g.filesOf(id).some((f) => involved.has(f)) || atom.deps.some((d) => drop.has(d))) {
198 drop.add(id);
199 for (const f of g.filesOf(id)) involved.add(f);
200 grew = true;
201 }
202 }
203 }
204 // Keep the intended membership, but reacquire its reader after each graph mutation.
205 const finalAgent = { ...agent, mine: [...agent.mine] };
206 const discard: Entry = { type: "discard", agent: agent.name, atoms: draft.filter((id) => drop.has(id)) };
207 entries.push(discard);
208 host.apply(discard);
210 for (const m of matches) {
211 const view = host.agentView(agent);
212 const start = view.lineNumber(m.from, m.ids[0]!);
213 if (start < 0 || m.ids.some((id, k) => view.lineNumber(m.from, id) !== start + k)) continue;
214 // Land after the nearest line above it in the final text that is already there.
215 const finalLines = host.agentView(finalAgent).buildLines(m.to);
216 let at = 0;
217 for (let i = m.at - 1; i >= 0; i--) {
218 const n = view.lineNumber(m.to, finalLines[i]!.id);
219 if (n >= 0) {
220 at = n + 1;
221 break;
222 }
223 }
224 if (m.to === m.from && at >= start && at <= start + m.ids.length) continue;
225 host.addDraft(
226 agent,
227 view,
228 { edits: [], move: { file: m.from, start, end: start + m.ids.length, to: m.to, at } },
229 time,
230 {},
231 entries,
232 );
233 }
234 for (const path of [...involved].toSorted()) {
235 const finalView = host.agentView(finalAgent);
236 const was = finalView.attrs(path);
237 const view = host.agentView(agent);
238 const target = finalView.buildLines(path);
239 const symbols = new MoveLineText(g);
240 const previous = view.buildLines(path).map((line) => symbols.intern(line.id));
241 const next = target.map((line) => symbols.intern(line.id));
242 const edits = diffLineSymbols(previous, next).map((hunk) => ({
243 file: path,
244 start: hunk.start,
245 end: hunk.end,
246 lines: hunk.lines.map((symbol) => symbols.text(symbol)),
247 }));
248 recordFileChanges(
249 host,
250 agent,
251 view,
252 path,
253 !finalView.hasFile(path) ? "missing" : target.length === 0 ? "empty" : "present",
254 edits,
255 time,
256 {},
257 entries,
258 { exec: was.exec, link: was.link },
259 );
260 }