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
show on this site's /mcp
CLI
abso show 196 --json
JSON
/christopher/abso-core/versions/196?format=json

Auto-settle (#19), step 3 behind a switch: the open server gives a held push a first opinion. With AUTOSETTLE=on and an AI binding (both off unless set), a held push's answer carries advice for each lines collision: keep yours, theirs or both, or needs an agent, with how many of 5 Workers AI samples agree and one line why. Checks in code run first and after (server/src/autosettle.ts), and the scripts now use the same ones. The client prints the advice under the collisions; the agent still settles. A model that fails leaves no advice and never fails the push's answer. server/test/autosettle.test.ts covers it with a stand-in for Workers AI.

of shared·autosettle··Not checked

Auto-settle (#19), step 3 behind a switch: the open server gives a held push a first opinion. With AUTOSETTLE=on and an AI binding (both off unless set), a held push's answer carries advice for each lines collision: keep yours, theirs or both, or needs an agent, with how many of 5 Workers AI samples agree and one line why.

Checks in code run first and after (server/src/autosettle.ts), and the scripts now use the same ones. The client prints the advice under the collisions; the agent still settles. A model that fails leaves no advice and never fails the push's answer. server/test/autosettle.test.ts covers it with a stand-in for Workers AI.

Version 195 · Files at version 196

7 files, 359 lines added, 47 removed.

--- a/client/src/api-answers.ts
+++ b/client/src/api-answers.ts
@@ -88,7 +88,21 @@
8888 }
8989 /** With the merge queue on (#39): queued, not landed yet; `ahead` publishes wait in front of it. */
9090 | { ok: true; queued: number; position: number; ahead: number; changes: number; settled?: readonly Settled[] }
91− | { ok: false; collisions: readonly Collision[]; reason?: string };
91+ | { ok: false; collisions: readonly Collision[]; reason?: string; advice?: readonly (Advice | null)[] };
92+/**
93+ * A server's first opinion on one collision of a held push (#19), when it runs AUTOSETTLE: which settle fits,
94+ * how sure, and why. `by`: rule (code decided), model (Workers AI), or turned down (the model's pick would break
95+ * the file, so an agent settles).
96+ */
97+export interface Advice {
98+ readonly pick: "yours" | "theirs" | "both" | "agent";
99+ readonly confidence: number;
100+ readonly reason: string;
101+ readonly by: "rule" | "model" | "turned down";
102+ readonly modelPick?: string;
103+ readonly model?: string;
104+ readonly ms: number;
105+}
92106/** A note on lines (#44): where its lines are now, or null when they're all gone. */
93107export interface NoteAnswer {
94108 readonly id: number;
--- a/client/src/publish-commands.ts
+++ b/client/src/publish-commands.ts
@@ -2,7 +2,7 @@
22
33import { existsSync, readFileSync } from "node:fs";
44import { join } from "node:path";
5−import { type Api, ApiError, type Collision, type Settled } from "./api.ts";
5+import { type Advice, type Api, ApiError, type Collision, type Settled } from "./api.ts";
66import { bool, type Parsed, str, UsageError } from "./args.ts";
77import { boxOf, knownPrep, runRun, shellWord } from "./box-commands.ts";
88import { collisionsHeading, collisionText, mergedLinesText, mergedText } from "./collision-text.ts";
@@ -458,6 +458,8 @@
458458 const real = collisions.filter((c) => !isLocalOnly(c.file));
459459 const twice = real.filter((c) => c.kind === "duplicate");
460460 const newer = real.filter((c) => c.kind !== "duplicate");
461+ // The server's first opinion on each collision (#19), when it runs AUTOSETTLE. Advice only: the agent settles.
462+ const advice = answer.advice ?? [];
461463 return {
462464 exit: EXIT.refused,
463465 text: [
@@ -465,6 +467,12 @@
465467 // A name defined twice is already in your folder (sync listed it); the rest is newer work.
466468 `Not pushed: ${plural(collisions.length, "collision")}${newer.length > 0 ? " with work pushed since your last pull" : ""}.${answer.reason ? ` (${answer.reason})` : ""}`,
467469 ...real.map(collisionText),
470+ ...(advice.some((a) => a)
471+ ? [
472+ "First opinion (a model on the server, with checks in code; you still settle):",
473+ ...collisions.flatMap((c, i) => (advice[i] ? [` ${c.file}: ${adviceWords(advice[i]!)}`] : [])),
474+ ]
475+ : []),
468476 ...(local.length > 0
469477 ? [
470478 ` ${local.map((c) => c.file).join(", ")}: local files that should never have been shared. abso pull drops them from your draft and leaves your copy on disk.`,
@@ -481,10 +489,26 @@
481489 ? "Keep one definition of each name defined twice (delete yours, or theirs), then push again."
482490 : "Run abso pull, then push again.",
483491 ].join("\n"),
484− json: { collisions, recorded: recorded.sent, ...(answer.reason ? { reason: answer.reason } : {}) },
492+ json: {
493+ collisions,
494+ recorded: recorded.sent,
495+ ...(answer.reason ? { reason: answer.reason } : {}),
496+ ...(advice.length > 0 ? { advice } : {}),
497+ },
485498 };
486499}
487500
501+function adviceWords(a: Advice): string {
502+ const what = a.pick === "agent" ? "needs an agent" : `keep ${a.pick}`;
503+ const how =
504+ a.by === "rule"
505+ ? "by a check in code"
506+ : a.by === "turned down"
507+ ? `the model said keep ${a.modelPick}, turned down`
508+ : `${a.confidence.toFixed(2)} of samples agree`;
509+ return `${what} (${how}): ${a.reason}`;
510+}
488512export async function runSync(args: Parsed, env: Env): Promise<Output> {
489513 const { root, api } = open(env);
490514 const recorded = await recordFolder(root, api);
--- a/scripts/autosettle/rules.ts
+++ b/scripts/autosettle/rules.ts
@@ -1,45 +1,3 @@
1−// Checks in code around the model's pick (#19). What code can decide, code
2−// decides; what the model picks is turned down when it would plainly break
3−// the file. Both run before anything is settled automatically.
1+// Checks in code around the model's pick (#19): the open server's own, so the scripts score what it runs.
42
5−import type { Hold, Pick } from "./jev.ts";
6−
7−const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));
8−
9−/** A pick code can make without the model, with why; undefined when it takes judgment. */
10−export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {
11− const yours = solid(h.yours);
12− const theirs = solid(h.theirs);
13− if (yours.join("\n") === theirs.join("\n")) return { pick: "theirs", reason: "both sides wrote the same lines" };
14− if (yours.length > 0 && yours.every((l) => theirs.includes(l)))
15− return { pick: "theirs", reason: "every line of yours is already in theirs" };
16− if (theirs.length > 0 && theirs.every((l) => yours.includes(l)))
17− return { pick: "yours", reason: "every line of theirs is already in yours" };
18− return undefined;
19−}
20−
21−/** Why a model's pick can't be applied as it is, or undefined when it can. */
22−export function refused(h: Hold, pick: Pick): string | undefined {
23− if (pick !== "both") return undefined;
24− const theirs = new Set(solid(h.theirs));
25− const twice = solid(h.yours).filter((l) => theirs.has(l));
26− if (twice.length > 0)
27− return `keeping both would repeat ${twice.length === 1 ? "a line" : `${twice.length} lines`}: ${twice[0]}`;
28− // The same key or name set on both sides: `timeoutMs:`, `limit =`.
29− const key = (l: string) => /^([A-Za-z_$"'][\w$"'-]*)\s*[:=]/.exec(l)?.[1];
30− const theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));
31− const clash = solid(h.yours)
32− .map(key)
33− .find((k) => k && theirKeys.has(k));
34− if (clash) return `keeping both would set ${clash} twice`;
35− // Two versions of one statement, such as an import from the same module with a different list of names:
36− // most of the names on one side are on the other too.
37− const names = (lines: readonly string[]) => new Set(lines.join(" ").match(/[A-Za-z_$][\w$]{2,}/g) ?? []);
38− const a = names(h.yours);
39− const b = names(h.theirs);
40− const shared = [...a].filter((n) => b.has(n)).length;
41− const share = shared / Math.max(1, Math.min(a.size, b.size));
42− return share >= 0.5
43− ? `keeping both would repeat one statement in two versions (${shared} names on both sides)`
44− : undefined;
45−}
3+export { refused, ruled } from "../../server/src/autosettle.ts";
--- /dev/null
+++ b/server/src/autosettle.ts
@@ -0,0 +1,234 @@
1+// A first opinion on a held push (#19): 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" and the Worker has an AI binding. The model
4+// picks one of four words; it never writes code.
5+
6+/** abso's settle choices, plus a hand edit by an agent. */
7+export type Pick = "yours" | "theirs" | "both" | "agent";
8+export const PICKS: readonly Pick[] = ["yours", "theirs", "both", "agent"];
9+export const MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
11+/** One collision as the held agent sees it. */
12+export interface Hold {
13+ readonly file: string;
14+ readonly base: readonly string[];
15+ readonly yours: readonly string[];
16+ readonly theirs: readonly string[];
17+ readonly before: readonly string[];
18+ readonly after: readonly string[];
19+ /** The held push's message: the settler's reason. */
20+ readonly yourMessage?: string;
21+ readonly yourAgent?: string;
22+ /** The push that got there first: its reason. */
23+ readonly theirMessage?: string;
24+ readonly theirAgent?: string;
25+ readonly issue?: string;
26+}
28+export interface Advice {
29+ readonly pick: Pick;
30+ /** The share of samples that agree, or 1 for a pick code made. */
31+ readonly confidence: number;
32+ readonly reason: string;
33+ /** rule: code decided without the model. turned down: the model's pick would break the file. */
34+ readonly by: "rule" | "model" | "turned down";
35+ readonly modelPick?: Pick;
36+ readonly model?: string;
37+ readonly ms: number;
38+}
40+export interface Ai {
41+ run(model: string, input: unknown): Promise<unknown>;
42+}
44+const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));
46+/** A pick code can make without the model, with why; undefined when it takes judgment. */
47+export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {
48+ const yours = solid(h.yours);
49+ const theirs = solid(h.theirs);
50+ if (yours.join("\n") === theirs.join("\n")) return { pick: "theirs", reason: "both sides wrote the same lines" };
51+ if (yours.length > 0 && yours.every((l) => theirs.includes(l)))
52+ return { pick: "theirs", reason: "every line of yours is already in theirs" };
53+ if (theirs.length > 0 && theirs.every((l) => yours.includes(l)))
54+ return { pick: "yours", reason: "every line of theirs is already in yours" };
55+ return undefined;
56+}
58+/** Why a model's pick can't be applied as it is, or undefined when it can. */
59+export function refused(h: Hold, pick: Pick): string | undefined {
60+ if (pick !== "both") return undefined;
61+ const theirs = new Set(solid(h.theirs));
62+ const twice = solid(h.yours).filter((l) => theirs.has(l));
63+ if (twice.length > 0)
64+ return `keeping both would repeat ${twice.length === 1 ? "a line" : `${twice.length} lines`}: ${twice[0]}`;
65+ // The same key or name set on both sides: `timeoutMs:`, `limit =`.
66+ const key = (l: string) => /^([A-Za-z_$"'][\w$"'-]*)\s*[:=]/.exec(l)?.[1];
67+ const theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));
68+ const clash = solid(h.yours)
69+ .map(key)
70+ .find((k) => k && theirKeys.has(k));
71+ if (clash) return `keeping both would set ${clash} twice`;
72+ // Two versions of one statement, such as an import from the same module with a different list of names:
73+ // most of the names on one side are on the other too.
74+ const names = (lines: readonly string[]) => new Set(lines.join(" ").match(/[A-Za-z_$][\w$]{2,}/g) ?? []);
75+ const a = names(h.yours);
76+ const b = names(h.theirs);
77+ const shared = [...a].filter((n) => b.has(n)).length;
78+ const share = shared / Math.max(1, Math.min(a.size, b.size));
79+ return share >= 0.5
80+ ? `keeping both would repeat one statement in two versions (${shared} names on both sides)`
81+ : undefined;
82+}
84+const SYSTEM = `You settle merge collisions in a version control system for coding agents.
85+Two 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.
86+Pick exactly one:
87+- "yours": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.
88+- "theirs": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.
89+- "both": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.
90+- "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.
91+Give "confidence" from 0 to 1: how likely your pick is the correct settle. Give "reason" as one plain sentence. Do not write code.`;
93+const block = (lines: readonly string[]) => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
95+function prompt(h: Hold): string {
96+ return [
97+ `FILE: ${h.file}`,
98+ `YOUR PUSH (${h.yourAgent ?? "you"}): ${h.yourMessage ?? "(no message)"}`,
99+ `THEIR PUSH (${h.theirAgent ?? "the other agent"}): ${h.theirMessage ?? "(no message)"}`,
100+ ...(h.issue ? [`ISSUE: ${h.issue}`] : []),
101+ "",
102+ "LINES ABOVE:",
103+ block(h.before),
104+ "",
105+ "BEFORE (what both started from):",
106+ h.base.length === 0 && h.before.length === 0 ? "(not given)" : block(h.base),
107+ "",
108+ "YOURS:",
109+ block(h.yours),
110+ "",
111+ "THEIRS:",
112+ block(h.theirs),
113+ "",
114+ "LINES BELOW:",
115+ block(h.after),
116+ ].join("\n");
117+}
119+const SCHEMA = {
120+ type: "object",
121+ properties: {
122+ pick: { type: "string", enum: PICKS },
123+ confidence: { type: "number", minimum: 0, maximum: 1 },
124+ reason: { type: "string" },
125+ },
126+ required: ["pick", "confidence", "reason"],
127+};
129+/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */
130+export async function modelPick(
131+ ai: Ai,
132+ h: Hold,
133+ opts: { model?: string; samples?: number } = {},
134+): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {
135+ const model = opts.model ?? MODEL;
136+ const samples = Math.min(9, Math.max(1, opts.samples ?? 5));
137+ const one = async () => {
138+ const out = (await ai.run(model, {
139+ messages: [
140+ { role: "system", content: SYSTEM },
141+ { role: "user", content: prompt(h) },
142+ ],
143+ response_format: { type: "json_schema", json_schema: SCHEMA },
144+ temperature: samples > 1 ? 0.7 : 0,
145+ max_tokens: 200,
146+ })) as { response: unknown; usage?: unknown };
147+ const answer = (typeof out.response === "string" ? JSON.parse(out.response) : out.response) as {
148+ pick: string;
149+ confidence: number;
150+ reason: string;
151+ };
152+ if (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);
153+ return { ...answer, pick: answer.pick as Pick, usage: out.usage ?? null };
154+ };
155+ const answers = await Promise.all(Array.from({ length: samples }, one));
156+ const votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<
157+ Pick,
158+ number
159+ >;
160+ const pick = PICKS.reduce((a, b) => (votes[b] > votes[a] ? b : a));
161+ const first = answers.find((a) => a.pick === pick)!;
162+ return {
163+ pick,
164+ confidence: samples > 1 ? votes[pick] / samples : first.confidence,
165+ reason: first.reason,
166+ selfReported: answers.map((a) => a.confidence),
167+ usage: first.usage,
168+ };
169+}
171+/** Code's rules first, then the model, then code's check on what the model picked. */
172+export async function advise(ai: Ai, h: Hold, opts: { model?: string; samples?: number } = {}): Promise<Advice> {
173+ const started = Date.now();
174+ const rule = ruled(h);
175+ if (rule) return { ...rule, confidence: 1, by: "rule", ms: 0 };
176+ const m = await modelPick(ai, h, opts);
177+ const model = opts.model ?? MODEL;
178+ const no = refused(h, m.pick);
179+ return no
180+ ? {
181+ pick: "agent",
182+ confidence: m.confidence,
183+ reason: no,
184+ by: "turned down",
185+ modelPick: m.pick,
186+ model,
187+ ms: Date.now() - started,
188+ }
189+ : { pick: m.pick, confidence: m.confidence, reason: m.reason, by: "model", model, ms: Date.now() - started };
190+}
192+interface HeldCollision {
193+ readonly kind: string;
194+ readonly file: string;
195+ readonly untouched?: true;
196+ readonly marked?: true;
197+ readonly yours: { readonly lines: [number, number]; readonly text: string };
198+ readonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };
199+}
201+/**
202+ * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply
203+ * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both
204+ * started from, so the model goes without them.
205+ */
206+export async function adviseHeld(
207+ ai: Ai,
208+ collisions: readonly HeldCollision[],
209+ held: { agent: string; message: string },
210+): Promise<(Advice | null)[]> {
211+ const lines = (text: string) => (text === "" ? [] : text.replace(/\r?\n$/, "").split(/\r?\n/));
212+ return Promise.all(
213+ collisions.map(async (c) => {
214+ if (c.kind !== "lines" || c.untouched || c.marked) return null;
215+ try {
216+ return await advise(ai, {
217+ file: c.file,
218+ base: [],
219+ yours: lines(c.yours.text),
220+ theirs: lines(c.theirs.text),
221+ before: [],
222+ after: [],
223+ yourAgent: held.agent,
224+ yourMessage: held.message,
225+ theirAgent: c.theirs.agent,
226+ theirMessage: c.theirs.message,
227+ });
228+ } catch (e) {
229+ console.error(`autosettle: ${c.file}: ${e instanceof Error ? e.message : String(e)}`);
230+ return null;
231+ }
232+ }),
233+ );
234+}
--- a/server/src/env.ts
+++ b/server/src/env.ts
@@ -24,6 +24,10 @@
2424 /** Per-agent keys: "on" with KEY_HMAC_SECRET set. */
2525 AGENT_KEYS?: string;
2626 KEY_HMAC_SECRET?: string;
27+ /** "on" gives a held push a first opinion on each collision from Workers AI (#19); needs the AI binding. */
28+ AUTOSETTLE?: string;
29+ /** Workers AI, for AUTOSETTLE. Unbound unless wrangler.jsonc names it. */
30+ AI?: { run(model: string, input: unknown): Promise<unknown> };
2731}
2832
2933/** A secret by its abso name, or its avcs name from before the rename. Empty counts as unset. */
--- a/server/src/router.ts
+++ b/server/src/router.ts
@@ -18,6 +18,7 @@
1818// ABSO_TOKEN set, the server refuses every call.
1919
2020import { type Answer, validName } from "../../worker/project/http.ts";
21+import { adviseHeld } from "./autosettle.ts";
2122import { artifactsOf, type Env, secret } from "./env.ts";
2223import type { IssuesAuth, issuesFetch } from "./issues-entry.ts";
2324import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from "./keys.ts";
@@ -268,6 +269,15 @@
268269 keyForCall,
269270 request.headers.get("Idempotency-Key") ?? undefined,
270271 )) as unknown as Answer;
272+ // A held push gets a first opinion on each collision (#19), when the server is set up for it.
273+ if (op === "publish" && env.AUTOSETTLE === "on" && env.AI && agent) {
274+ const held = a.body as { ok?: boolean; collisions?: Parameters<typeof adviseHeld>[1] };
275+ if (held.ok === false && held.collisions && held.collisions.length > 0) {
276+ const message = String((body as { message?: unknown } | undefined)?.message ?? "");
277+ const advice = await adviseHeld(env.AI, held.collisions, { agent, message });
278+ if (advice.some((x) => x !== null)) return json(a.status, { ...held, advice });
279+ }
280+ }
271281 return json(a.status, a.body);
272282 } catch (e) {
273283 const error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;
--- /dev/null
+++ b/server/test/autosettle.test.ts
@@ -0,0 +1,68 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { type Ai, adviseHeld, refused, ruled } from "../src/autosettle.ts";
4+
5+/** A stand-in for Workers AI that always answers `pick`, and counts its calls. */
6+function fakeAi(pick: string): Ai & { calls: number } {
7+ const ai = {
8+ calls: 0,
9+ async run() {
10+ ai.calls++;
11+ return { response: { pick, confidence: 0.9, reason: "a fixed answer" }, usage: { prompt_tokens: 10 } };
12+ },
13+ };
14+ return ai;
15+}
17+const held = (yours: string, theirs: string, kind = "lines") => ({
18+ kind,
19+ file: "src/a.ts",
20+ yours: { lines: [3, 3] as [number, number], text: yours },
21+ theirs: { agent: "other", message: "their reason", text: theirs },
22+});
24+test("code settles when one side's lines are all in the other's, without asking the model", async () => {
25+ const ai = fakeAi("both");
26+ const [a] = await adviseHeld(ai, [held("\ttimeoutMs: 30000,\n", "\ttimeoutMs: 30000,\n\tretries: 2,\n")], {
27+ agent: "me",
28+ message: "my reason",
29+ });
30+ assert.equal(a?.pick, "theirs");
31+ assert.equal(a?.by, "rule");
32+ assert.equal(ai.calls, 0);
33+});
35+test("a keep-both that sets one key twice, or holds one import in two versions, goes to an agent", () => {
36+ const hold = (yours: string[], theirs: string[]) => ({ file: "a", base: [], yours, theirs, before: [], after: [] });
37+ assert.match(refused(hold(["\tmaxNesting: 64,"], ["\tmaxNesting: 1000,"]), "both") ?? "", /maxNesting twice/);
38+ assert.match(
39+ refused(hold(['import { a, b, c } from "./x.ts";'], ['import { a, b, d } from "./x.ts";']), "both") ?? "",
40+ /one statement in two versions/,
41+ );
42+ assert.equal(refused(hold(['\t"/blame": blame,'], ['\t"/search": search,']), "both"), undefined);
43+ assert.equal(ruled(hold(['\t"/blame": blame,'], ['\t"/search": search,'])), undefined);
44+});
46+test("the model's pick comes back with how many samples agree, and other kinds get no advice", async () => {
47+ const ai = fakeAi("both");
48+ const advice = await adviseHeld(
49+ ai,
50+ [held('\t"/blame": blame,\n', '\t"/search": search,\n'), held("x", "y", "definition")],
51+ { agent: "me", message: "my reason" },
52+ );
53+ assert.equal(advice[0]?.pick, "both");
54+ assert.equal(advice[0]?.by, "model");
55+ assert.equal(advice[0]?.confidence, 1);
56+ assert.equal(advice[1], null);
57+ assert.equal(ai.calls, 5);
58+});
60+test("a model that fails leaves no advice instead of failing the push's answer", async () => {
61+ const ai: Ai = {
62+ async run() {
63+ throw new Error("Workers AI is down");
64+ },
65+ };
66+ const [a] = await adviseHeld(ai, [held("a = 1", "b = 2")], { agent: "me", message: "m" });
67+ assert.equal(a, null);
68+});