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/autosettle.ts?format=json
441 linesautosettle 100%Last change autosettle in version 211, 3 versions changed it
1// A first opinion on a held push (#19), shared by the open server and the platform: for each collision, which of abso's
2// settle choices fits, from Workers AI, with checks in code before and after.
3// Off unless AUTOSETTLE is "on" (advice) or "act" (the client settles) and the Worker has an AI binding. The model
4// picks one of four words; it never writes code.
5
6import type { AutoSettled } from "./project-types.ts";
7
8/** abso's settle choices, plus a hand edit by an agent. */
9export type Pick = "yours" | "theirs" | "both" | "agent";
10export const PICKS: readonly Pick[] = ["yours", "theirs", "both", "agent"];
11export const MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
13/** One collision as the held agent sees it. */
14export interface Hold {
15 readonly file: string;
16 readonly base: readonly string[];
17 readonly yours: readonly string[];
18 readonly theirs: readonly string[];
19 readonly before: readonly string[];
20 readonly after: readonly string[];
21 /** The held push's message: the settler's reason. */
22 readonly yourMessage?: string;
23 readonly yourAgent?: string;
24 /** The push that got there first: its reason. */
25 readonly theirMessage?: string;
26 readonly theirAgent?: string;
27 readonly issue?: string;
30export interface Advice {
31 readonly pick: Pick;
32 /** The share of samples that agree, or 1 for a pick code made. */
33 readonly confidence: number;
34 readonly reason: string;
35 /**
36 * rule: code decided without the model. turned down: the model's pick would break the file. unsure: the model
37 * leaned to a side under the threshold, so an agent settles.
38 */
39 readonly by: "rule" | "model" | "turned down" | "unsure";
40 readonly modelPick?: Pick;
41 readonly model?: string;
42 readonly ms: number;
45/**
46 * The heading a client puts over what it settled by itself, in the message of the push that follows (abso-core 19,
47 * 23). One line per file under it: `- <file>: kept <side>, confidence 0.81. <reason>` or `…, by a check in code. …`.
48 */
49export const AUTO_HEADING = "Settled automatically (abso 19):";
51/** The lines a client adds to its message for the files it settled by itself. */
52export function autoTrailer(
53 plan: Iterable<
54 readonly [
55 string,
56 { readonly pick: string; readonly by: string; readonly confidence: number; readonly reason: string },
57 ]
58 >,
59): string {
60 const lines = [...plan].map(([file, a]) => {
61 const how = a.by === "rule" ? "by a check in code" : `confidence ${a.confidence.toFixed(2)}`;
62 return `- ${file}: kept ${a.pick}, ${how}. ${a.reason.replace(/\s+/g, " ").trim()}`;
63 });
64 return [AUTO_HEADING, ...lines].join("\n");
67/** What a push's message says its abso settled by itself, by file; empty for a push that settled by hand. */
68export function autoSettledOf(message: string): Map<string, AutoSettled> {
69 const found = new Map<string, AutoSettled>();
70 const lines = message.split(/\r?\n/);
71 const at = lines.lastIndexOf(AUTO_HEADING);
72 if (at < 0) return found;
73 for (const line of lines.slice(at + 1)) {
74 const m = /^- (.+): kept (yours|theirs|both), (?:by a check in code|confidence ([01]\.\d\d))\. ?(.*)$/.exec(line);
75 if (!m) break;
76 found.set(m[1]!, {
77 pick: m[2] as AutoSettled["pick"],
78 by: m[3] === undefined ? "rule" : "model",
79 confidence: m[3] === undefined ? 1 : Number(m[3]),
80 reason: m[4] ?? "",
81 });
82 }
83 return found;
86export interface Ai {
87 run(model: string, input: unknown): Promise<unknown>;
90const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));
92/** A pick code can make without the model, with why; undefined when it takes judgment. */
93export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {
94 const yours = solid(h.yours);
95 const theirs = solid(h.theirs);
96 if (yours.join("\n") === theirs.join("\n")) return { pick: "theirs", reason: "both sides wrote the same lines" };
97 if (yours.length > 0 && yours.every((l) => theirs.includes(l)))
98 return { pick: "theirs", reason: "every line of yours is already in theirs" };
99 if (theirs.length > 0 && theirs.every((l) => yours.includes(l)))
100 return { pick: "yours", reason: "every line of theirs is already in yours" };
101 return undefined;
104/** Why a model's pick can't be applied as it is, or undefined when it can. */
105export function refused(h: Hold, pick: Pick): string | undefined {
106 if (pick !== "both") return undefined;
107 const theirs = new Set(solid(h.theirs));
108 const twice = solid(h.yours).filter((l) => theirs.has(l));
109 if (twice.length > 0)
110 return `keeping both would repeat ${twice.length === 1 ? "a line" : `${twice.length} lines`}: ${twice[0]}`;
111 // The same key or name set on both sides: `timeoutMs:`, `limit =`.
112 const key = (l: string) => /^([A-Za-z_$"'][\w$"'-]*)\s*[:=]/.exec(l)?.[1];
113 const theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));
114 const clash = solid(h.yours)
115 .map(key)
116 .find((k) => k && theirKeys.has(k));
117 if (clash) return `keeping both would set ${clash} twice`;
118 // Two versions of one statement, such as an import from the same module with a different list of names:
119 // most of the names on one side are on the other too.
120 const names = (lines: readonly string[]) => new Set(lines.join(" ").match(/[A-Za-z_$][\w$]{2,}/g) ?? []);
121 const a = names(h.yours);
122 const b = names(h.theirs);
123 const shared = [...a].filter((n) => b.has(n)).length;
124 const share = shared / Math.max(1, Math.min(a.size, b.size));
125 return share >= 0.5
126 ? `keeping both would repeat one statement in two versions (${shared} names on both sides)`
127 : undefined;
130const SYSTEM = `You settle merge collisions in a version control system for coding agents.
131Two agents changed the same lines of one file. Both started from BEFORE. YOURS is what the held agent wrote, for the reason in its push message; THEIRS was pushed first, for the reason in its push message.
132Pick exactly one:
133- "yours": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.
134- "theirs": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.
135- "both": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.
136- "agent": none of those is correct. The sides change the same thing in different ways (such as two different values for one setting), or keeping both would duplicate or contradict, so a correct result needs a hand edit.
137Give "confidence" from 0 to 1: how likely your pick is the correct settle. Give "reason" as one plain sentence. Do not write code.`;
139const block = (lines: readonly string[]) => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
141function prompt(h: Hold): string {
142 return [
143 `FILE: ${h.file}`,
144 `YOUR PUSH (${h.yourAgent ?? "you"}): ${h.yourMessage ?? "(no message)"}`,
145 `THEIR PUSH (${h.theirAgent ?? "the other agent"}): ${h.theirMessage ?? "(no message)"}`,
146 ...(h.issue ? [`ISSUE: ${h.issue}`] : []),
147 "",
148 "LINES ABOVE:",
149 block(h.before),
150 "",
151 "BEFORE (what both started from):",
152 h.base.length === 0 && h.before.length === 0 ? "(not given)" : block(h.base),
153 "",
154 "YOURS:",
155 block(h.yours),
156 "",
157 "THEIRS:",
158 block(h.theirs),
159 "",
160 "LINES BELOW:",
161 block(h.after),
162 ].join("\n");
165const SCHEMA = {
166 type: "object",
167 properties: {
168 pick: { type: "string", enum: PICKS },
169 confidence: { type: "number", minimum: 0, maximum: 1 },
170 reason: { type: "string" },
171 },
172 required: ["pick", "confidence", "reason"],
173};
175/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */
176export async function modelPick(
177 ai: Ai,
178 h: Hold,
179 opts: { model?: string; samples?: number } = {},
180): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {
181 const model = opts.model ?? MODEL;
182 const samples = Math.min(9, Math.max(1, opts.samples ?? 5));
183 const one = async () => {
184 const out = (await ai.run(model, {
185 messages: [
186 { role: "system", content: SYSTEM },
187 { role: "user", content: prompt(h) },
188 ],
189 response_format: { type: "json_schema", json_schema: SCHEMA },
190 temperature: samples > 1 ? 0.7 : 0,
191 max_tokens: 200,
192 })) as { response: unknown; usage?: unknown };
193 const answer = (typeof out.response === "string" ? JSON.parse(out.response) : out.response) as {
194 pick: string;
195 confidence: number;
196 reason: string;
197 };
198 if (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);
199 return { ...answer, pick: answer.pick as Pick, usage: out.usage ?? null };
200 };
201 const answers = await Promise.all(Array.from({ length: samples }, one));
202 const votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<
203 Pick,
204 number
205 >;
206 const pick = PICKS.reduce((a, b) => (votes[b] > votes[a] ? b : a));
207 const first = answers.find((a) => a.pick === pick)!;
208 return {
209 pick,
210 confidence: samples > 1 ? votes[pick] / samples : first.confidence,
211 reason: first.reason,
212 selfReported: answers.map((a) => a.confidence),
213 usage: first.usage,
214 };
217const text = (lines: readonly string[]): string => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
219/** A hold as a System One state: the content the questions point at by name. */
220export function stateOf(h: Hold): Record<string, unknown> {
221 return {
222 file: h.file,
223 lines_above: text(h.before),
224 before_either_change: h.base.length === 0 && h.before.length === 0 ? "(not given)" : text(h.base),
225 yours: text(h.yours),
226 theirs: text(h.theirs),
227 lines_below: text(h.after),
228 your_push: { agent: h.yourAgent ?? "you", message: h.yourMessage ?? "(no message)" },
229 their_push: { agent: h.theirAgent ?? "the other agent", message: h.theirMessage ?? "(no message)" },
230 ...(h.issue ? { issue: h.issue } : {}),
231 };
234const INSTRUCTIONS =
235 "Two agents changed the same lines of `file`. Both started from `before_either_change`. " +
236 "`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. " +
237 "The region sits between `lines_above` and `lines_below`. " +
238 "Which result is correct code that does what both pushes meant?";
240const CRITERIA: Record<Pick, string> = {
241 yours: "Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.",
242 theirs: "Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.",
243 both: "Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.",
244 agent:
245 "Neither side alone and not both unchanged: the sides change the same thing in different ways (such as two different values for one setting), or keeping both would duplicate or contradict, so a correct result needs a hand edit.",
246};
248const choice = (order: readonly Pick[]) => ({
249 type: "choice",
250 instructions: INSTRUCTIONS,
251 criteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),
252});
254/** Side questions asked with the choice, for the record (yes-probabilities). */
255export const SIGNS: Record<string, string> = {
256 same_setting_different_values:
257 "Do `yours` and `theirs` set the same setting, constant or value to two different values?",
258 theirs_covers_yours: "Does `theirs` already do everything `yours` was changed to do?",
259 yours_covers_theirs: "Does `yours` already do everything `theirs` was changed to do?",
260 both_unchanged_compiles:
261 "If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?",
262};
264/**
265 * A System One request (TypeSafe's Jev and Cloudflare's Clef both take it): the choice in two option orders, since
266 * Jev's docs warn order can sway a Choice, and the side questions.
267 */
268export function systemOneBody(h: Hold, model: string) {
269 return {
270 model,
271 state: stateOf(h),
272 questions: {
273 settle: choice(PICKS),
274 settle_reversed: choice([...PICKS].reverse()),
275 ...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: "noul", instructions: q }])),
276 },
277 };
280/** Choice confidence: how far the top probability sits above an even split, 0 to 1 (TypeSafe's formula). */
281export function confidenceOf(p: Record<Pick, number>): number {
282 const max = Math.max(...PICKS.map((k) => p[k]));
283 const even = 1 / PICKS.length;
284 return Math.max(0, (max - even) / (1 - even));
287/** Clef's pick: the two orders' probabilities averaged. */
288export async function clefPick(
289 ai: Ai,
290 h: Hold,
291 model: string,
292): Promise<{ pick: Pick; confidence: number; reason: string; probabilities: Record<Pick, number> }> {
293 const out = (await ai.run(model === "clef-flash" ? "@cf/cloudflare/clef-flash" : "@cf/cloudflare/clef", {
294 ...systemOneBody(h, model === "clef-flash" ? "clef-flash" : "clef"),
295 })) as { answers?: Record<string, { probabilities?: Record<string, number> }> };
296 const orders = ["settle", "settle_reversed"].map((id) => out.answers?.[id]?.probabilities);
297 if (orders.some((p) => !p)) throw new Error("Clef answered without the settle choice");
298 const probabilities = Object.fromEntries(
299 PICKS.map((k) => [k, ((orders[0]![k] ?? 0) + (orders[1]![k] ?? 0)) / 2]),
300 ) as Record<Pick, number>;
301 const pick = PICKS.reduce((a, b) => (probabilities[b] > probabilities[a] ? b : a));
302 const words: Record<Pick, string> = {
303 yours: "keep yours",
304 theirs: "keep theirs",
305 both: "keep both",
306 agent: "an agent",
307 };
308 return {
309 pick,
310 confidence: confidenceOf(probabilities),
311 probabilities,
312 reason: `Clef's probabilities: ${PICKS.map((k) => `${words[k]} ${probabilities[k].toFixed(2)}`).join(", ")}`,
313 };
316/** Code's rules first, then the model, then code's check on what the model picked. */
317export async function advise(
318 ai: Ai,
319 h: Hold,
320 opts: { model?: string; samples?: number; at?: number } = {},
321): Promise<Advice> {
322 const started = Date.now();
323 const rule = ruled(h);
324 if (rule) return { ...rule, confidence: 1, by: "rule", ms: 0 };
325 // Clef unless a text model is named: on project abso's 33 past holds it settled nothing wrong at 0.5 or more,
326 // where the text model was wrong once at 1.00 (#19).
327 const clef = !opts.model || opts.model.startsWith("clef");
328 const m = clef ? await clefPick(ai, h, opts.model ?? "clef") : await modelPick(ai, h, opts);
329 const model = clef ? `@cf/cloudflare/${opts.model ?? "clef"}` : (opts.model ?? MODEL);
330 const at = opts.at ?? 0.5;
331 if (m.pick !== "agent" && m.confidence < at)
332 return {
333 pick: "agent",
334 confidence: m.confidence,
335 reason: `${m.reason}; under ${at}, so an agent settles`,
336 by: "unsure",
337 modelPick: m.pick,
338 model,
339 ms: Date.now() - started,
340 };
341 const no = refused(h, m.pick);
342 return no
343 ? {
344 pick: "agent",
345 confidence: m.confidence,
346 reason: no,
347 by: "turned down",
348 modelPick: m.pick,
349 model,
350 ms: Date.now() - started,
351 }
352 : { pick: m.pick, confidence: m.confidence, reason: m.reason, by: "model", model, ms: Date.now() - started };
355interface HeldCollision {
356 readonly kind: string;
357 readonly file: string;
358 readonly untouched?: true;
359 readonly marked?: true;
360 readonly yours: { readonly lines: [number, number]; readonly text: string };
361 readonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };
364/**
365 * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply
366 * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both
367 * started from, so the model goes without them.
368 */
369export async function adviseHeld(
370 ai: Ai,
371 collisions: readonly HeldCollision[],
372 held: { agent: string; message: string },
373 opts: { model?: string; at?: number } = {},
374): Promise<(Advice | null)[]> {
375 const lines = (text: string) => (text === "" ? [] : text.replace(/\r?\n$/, "").split(/\r?\n/));
376 return Promise.all(
377 collisions.map(async (c) => {
378 if (c.kind !== "lines" || c.untouched || c.marked) return null;
379 try {
380 return await advise(
381 ai,
382 {
383 file: c.file,
384 base: [],
385 yours: lines(c.yours.text),
386 theirs: lines(c.theirs.text),
387 before: [],
388 after: [],
389 yourAgent: held.agent,
390 yourMessage: held.message,
391 theirAgent: c.theirs.agent,
392 theirMessage: c.theirs.message,
393 },
394 opts,
395 );
396 } catch (e) {
397 console.error(`autosettle: ${c.file}: ${e instanceof Error ? e.message : String(e)}`);
398 return null;
399 }
400 }),
401 );
404/** The switch as a Worker's env carries it: AUTOSETTLE "on" advises, "act" also has the client settle; else off. */
405export interface AutosettleEnv {
406 readonly AUTOSETTLE?: string;
407 readonly AUTOSETTLE_MODEL?: string;
408 readonly AUTOSETTLE_AT?: string | number;
409 readonly AI?: Ai;
412/**
413 * The one hook for a server (#19): a publish answer with the first opinion added when the push was held and the
414 * switch is on, or the answer as it was. Under "act" it also says `settle: true`, and the client settles the
415 * collisions advised to a side and pushes again; under "on" the client only shows the advice.
416 */
417export async function withAdvice(
418 env: AutosettleEnv,
419 op: string | undefined,
420 agent: string | undefined,
421 request: unknown,
422 answer: unknown,
423): Promise<unknown> {
424 const mode = env.AUTOSETTLE;
425 if (op !== "publish" || (mode !== "on" && mode !== "act") || !env.AI || !agent) return answer;
426 const held = answer as { ok?: boolean; collisions?: readonly HeldCollision[] } | null;
427 if (held?.ok !== false || !held.collisions || held.collisions.length === 0) return answer;
428 const message = String((request as { message?: unknown } | null | undefined)?.message ?? "");
429 const at = Number(env.AUTOSETTLE_AT);
430 const advice = await adviseHeld(
431 env.AI,
432 held.collisions,
433 { agent, message },
434 {
435 ...(env.AUTOSETTLE_MODEL ? { model: env.AUTOSETTLE_MODEL } : {}),
436 ...(at > 0 ? { at } : {}),
437 },
438 );
439 if (!advice.some((x) => x !== null)) return answer;
440 return { ...held, advice, ...(mode === "act" ? { settle: true } : {}) };