- MCP
- show on this site's /mcp
- CLI
- abso show 203 --json
- JSON
- /christopher/abso-core/versions/203?format=json
Auto-settle (#19): the advice code moves into the tool, worker/project/autosettle.ts with its test, so the platform's pin carries it. server/src/autosettle.ts re-exports it for the open server; the scripts import it from there. No change in behavior.
of shared·autosettle··Not checked
Version 202 · Files at version 203
5 files (1 renamed), 367 lines added, 363 removed.
--- a/scripts/autosettle/jev.ts
+++ b/scripts/autosettle/jev.ts
@@ -7,9 +7,9 @@
88
10−import { confidenceOf, SIGNS, systemOneBody } from "../../server/src/autosettle.ts";
1111
12−// The questions are the open server's own (server/src/autosettle.ts), so Jev and Clef are asked alike.
12+// The questions are the tool's own (worker/project/autosettle.ts), so Jev and Clef are asked alike.
1414
--- a/scripts/autosettle/rules.ts
+++ b/scripts/autosettle/rules.ts
@@ -1,3 +1,3 @@
1−// Checks in code around the model's pick (#19): the open server's own, so the scripts score what it runs.
1+// Checks in code around the model's pick (#19): the tool's own (worker/project/autosettle.ts), so the scripts score what the servers run.
22
3−export { refused, ruled } from "../../server/src/autosettle.ts";
--- a/server/src/autosettle.ts
+++ b/server/src/autosettle.ts
@@ -1,359 +1,4 @@
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.
1+// A first opinion on a held push (#19): the tool's own, in worker/project/autosettle.ts, so the platform's pin
53
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";
10−
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−}
27−
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− /**
34− * rule: code decided without the model. turned down: the model's pick would break the file. unsure: the model
35− * leaned to a side under the threshold, so an agent settles.
36− */
37− readonly by: "rule" | "model" | "turned down" | "unsure";
38− readonly modelPick?: Pick;
39− readonly model?: string;
40− readonly ms: number;
41−}
42−
43−export interface Ai {
44− run(model: string, input: unknown): Promise<unknown>;
45−}
46−
47−const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));
48−
49−/** A pick code can make without the model, with why; undefined when it takes judgment. */
50−export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {
51− const yours = solid(h.yours);
52− const theirs = solid(h.theirs);
53− if (yours.join("\n") === theirs.join("\n")) return { pick: "theirs", reason: "both sides wrote the same lines" };
54− if (yours.length > 0 && yours.every((l) => theirs.includes(l)))
55− return { pick: "theirs", reason: "every line of yours is already in theirs" };
56− if (theirs.length > 0 && theirs.every((l) => yours.includes(l)))
57− return { pick: "yours", reason: "every line of theirs is already in yours" };
58− return undefined;
59−}
60−
61−/** Why a model's pick can't be applied as it is, or undefined when it can. */
62−export function refused(h: Hold, pick: Pick): string | undefined {
63− if (pick !== "both") return undefined;
64− const theirs = new Set(solid(h.theirs));
65− const twice = solid(h.yours).filter((l) => theirs.has(l));
66− if (twice.length > 0)
67− return `keeping both would repeat ${twice.length === 1 ? "a line" : `${twice.length} lines`}: ${twice[0]}`;
68− // The same key or name set on both sides: `timeoutMs:`, `limit =`.
69− const key = (l: string) => /^([A-Za-z_$"'][\w$"'-]*)\s*[:=]/.exec(l)?.[1];
70− const theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));
71− const clash = solid(h.yours)
72− .map(key)
73− .find((k) => k && theirKeys.has(k));
74− if (clash) return `keeping both would set ${clash} twice`;
75− // Two versions of one statement, such as an import from the same module with a different list of names:
76− // most of the names on one side are on the other too.
77− const names = (lines: readonly string[]) => new Set(lines.join(" ").match(/[A-Za-z_$][\w$]{2,}/g) ?? []);
78− const a = names(h.yours);
79− const b = names(h.theirs);
80− const shared = [...a].filter((n) => b.has(n)).length;
81− const share = shared / Math.max(1, Math.min(a.size, b.size));
82− return share >= 0.5
83− ? `keeping both would repeat one statement in two versions (${shared} names on both sides)`
84− : undefined;
85−}
86−
87−const SYSTEM = `You settle merge collisions in a version control system for coding agents.
88−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.
89−Pick exactly one:
90−- "yours": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.
91−- "theirs": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.
92−- "both": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.
93−- "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.
94−Give "confidence" from 0 to 1: how likely your pick is the correct settle. Give "reason" as one plain sentence. Do not write code.`;
95−
96−const block = (lines: readonly string[]) => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
97−
98−function prompt(h: Hold): string {
99− return [
100− `FILE: ${h.file}`,
101− `YOUR PUSH (${h.yourAgent ?? "you"}): ${h.yourMessage ?? "(no message)"}`,
102− `THEIR PUSH (${h.theirAgent ?? "the other agent"}): ${h.theirMessage ?? "(no message)"}`,
103− ...(h.issue ? [`ISSUE: ${h.issue}`] : []),
104− "",
105− "LINES ABOVE:",
106− block(h.before),
107− "",
108− "BEFORE (what both started from):",
109− h.base.length === 0 && h.before.length === 0 ? "(not given)" : block(h.base),
110− "",
111− "YOURS:",
112− block(h.yours),
113− "",
114− "THEIRS:",
115− block(h.theirs),
116− "",
117− "LINES BELOW:",
118− block(h.after),
119− ].join("\n");
120−}
121−
122−const SCHEMA = {
123− type: "object",
124− properties: {
125− pick: { type: "string", enum: PICKS },
126− confidence: { type: "number", minimum: 0, maximum: 1 },
127− reason: { type: "string" },
128− },
129− required: ["pick", "confidence", "reason"],
130−};
131−
132−/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */
133−export async function modelPick(
134− ai: Ai,
135− h: Hold,
136− opts: { model?: string; samples?: number } = {},
137−): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {
138− const model = opts.model ?? MODEL;
139− const samples = Math.min(9, Math.max(1, opts.samples ?? 5));
140− const one = async () => {
141− const out = (await ai.run(model, {
142− messages: [
143− { role: "system", content: SYSTEM },
144− { role: "user", content: prompt(h) },
145− ],
146− response_format: { type: "json_schema", json_schema: SCHEMA },
147− temperature: samples > 1 ? 0.7 : 0,
148− max_tokens: 200,
149− })) as { response: unknown; usage?: unknown };
150− const answer = (typeof out.response === "string" ? JSON.parse(out.response) : out.response) as {
151− pick: string;
152− confidence: number;
153− reason: string;
154− };
155− if (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);
156− return { ...answer, pick: answer.pick as Pick, usage: out.usage ?? null };
157− };
158− const answers = await Promise.all(Array.from({ length: samples }, one));
159− const votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<
160− Pick,
161− number
162− >;
163− const pick = PICKS.reduce((a, b) => (votes[b] > votes[a] ? b : a));
164− const first = answers.find((a) => a.pick === pick)!;
165− return {
166− pick,
167− confidence: samples > 1 ? votes[pick] / samples : first.confidence,
168− reason: first.reason,
169− selfReported: answers.map((a) => a.confidence),
170− usage: first.usage,
171− };
172−}
173−
174−const text = (lines: readonly string[]): string => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
175−
176−/** A hold as a System One state: the content the questions point at by name. */
177−export function stateOf(h: Hold): Record<string, unknown> {
178− return {
179− file: h.file,
180− lines_above: text(h.before),
181− before_either_change: h.base.length === 0 && h.before.length === 0 ? "(not given)" : text(h.base),
182− yours: text(h.yours),
183− theirs: text(h.theirs),
184− lines_below: text(h.after),
185− your_push: { agent: h.yourAgent ?? "you", message: h.yourMessage ?? "(no message)" },
186− their_push: { agent: h.theirAgent ?? "the other agent", message: h.theirMessage ?? "(no message)" },
187− ...(h.issue ? { issue: h.issue } : {}),
188− };
189−}
190−
191−const INSTRUCTIONS =
192− "Two agents changed the same lines of `file`. Both started from `before_either_change`. " +
193− "`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. " +
194− "The region sits between `lines_above` and `lines_below`. " +
195− "Which result is correct code that does what both pushes meant?";
196−
197−const CRITERIA: Record<Pick, string> = {
198− yours: "Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.",
199− theirs: "Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.",
200− both: "Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.",
201− agent:
202− "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.",
203−};
204−
205−const choice = (order: readonly Pick[]) => ({
206− type: "choice",
207− instructions: INSTRUCTIONS,
208− criteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),
209−});
210−
211−/** Side questions asked with the choice, for the record (yes-probabilities). */
212−export const SIGNS: Record<string, string> = {
213− same_setting_different_values:
214− "Do `yours` and `theirs` set the same setting, constant or value to two different values?",
215− theirs_covers_yours: "Does `theirs` already do everything `yours` was changed to do?",
216− yours_covers_theirs: "Does `yours` already do everything `theirs` was changed to do?",
217− both_unchanged_compiles:
218− "If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?",
219−};
220−
221−/**
222− * A System One request (TypeSafe's Jev and Cloudflare's Clef both take it): the choice in two option orders, since
223− * Jev's docs warn order can sway a Choice, and the side questions.
224− */
225−export function systemOneBody(h: Hold, model: string) {
226− return {
227− model,
228− state: stateOf(h),
229− questions: {
230− settle: choice(PICKS),
231− settle_reversed: choice([...PICKS].reverse()),
232− ...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: "noul", instructions: q }])),
233− },
234− };
235−}
236−
237−/** Choice confidence: how far the top probability sits above an even split, 0 to 1 (TypeSafe's formula). */
238−export function confidenceOf(p: Record<Pick, number>): number {
239− const max = Math.max(...PICKS.map((k) => p[k]));
240− const even = 1 / PICKS.length;
241− return Math.max(0, (max - even) / (1 - even));
242−}
243−
244−/** Clef's pick: the two orders' probabilities averaged. */
245−export async function clefPick(
246− ai: Ai,
247− h: Hold,
248− model: string,
249−): Promise<{ pick: Pick; confidence: number; reason: string; probabilities: Record<Pick, number> }> {
250− const out = (await ai.run(model === "clef-flash" ? "@cf/cloudflare/clef-flash" : "@cf/cloudflare/clef", {
251− ...systemOneBody(h, model === "clef-flash" ? "clef-flash" : "clef"),
252− })) as { answers?: Record<string, { probabilities?: Record<string, number> }> };
253− const orders = ["settle", "settle_reversed"].map((id) => out.answers?.[id]?.probabilities);
254− if (orders.some((p) => !p)) throw new Error("Clef answered without the settle choice");
255− const probabilities = Object.fromEntries(
256− PICKS.map((k) => [k, ((orders[0]![k] ?? 0) + (orders[1]![k] ?? 0)) / 2]),
257− ) as Record<Pick, number>;
258− const pick = PICKS.reduce((a, b) => (probabilities[b] > probabilities[a] ? b : a));
259− const words: Record<Pick, string> = {
260− yours: "keep yours",
261− theirs: "keep theirs",
262− both: "keep both",
263− agent: "an agent",
264− };
265− return {
266− pick,
267− confidence: confidenceOf(probabilities),
268− probabilities,
269− reason: `Clef's probabilities: ${PICKS.map((k) => `${words[k]} ${probabilities[k].toFixed(2)}`).join(", ")}`,
270− };
271−}
272−
273−/** Code's rules first, then the model, then code's check on what the model picked. */
274−export async function advise(
275− ai: Ai,
276− h: Hold,
277− opts: { model?: string; samples?: number; at?: number } = {},
278−): Promise<Advice> {
279− const started = Date.now();
280− const rule = ruled(h);
281− if (rule) return { ...rule, confidence: 1, by: "rule", ms: 0 };
282− // Clef unless a text model is named: on project abso's 33 past holds it settled nothing wrong at 0.5 or more,
283− // where the text model was wrong once at 1.00 (#19).
284− const clef = !opts.model || opts.model.startsWith("clef");
285− const m = clef ? await clefPick(ai, h, opts.model ?? "clef") : await modelPick(ai, h, opts);
286− const model = clef ? `@cf/cloudflare/${opts.model ?? "clef"}` : (opts.model ?? MODEL);
287− const at = opts.at ?? 0.5;
288− if (m.pick !== "agent" && m.confidence < at)
289− return {
290− pick: "agent",
291− confidence: m.confidence,
292− reason: `${m.reason}; under ${at}, so an agent settles`,
293− by: "unsure",
294− modelPick: m.pick,
295− model,
296− ms: Date.now() - started,
297− };
298− const no = refused(h, m.pick);
299− return no
300− ? {
301− pick: "agent",
302− confidence: m.confidence,
303− reason: no,
304− by: "turned down",
305− modelPick: m.pick,
306− model,
307− ms: Date.now() - started,
308− }
309− : { pick: m.pick, confidence: m.confidence, reason: m.reason, by: "model", model, ms: Date.now() - started };
310−}
311−
312−interface HeldCollision {
313− readonly kind: string;
314− readonly file: string;
315− readonly untouched?: true;
316− readonly marked?: true;
317− readonly yours: { readonly lines: [number, number]; readonly text: string };
318− readonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };
319−}
320−
321−/**
322− * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply
323− * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both
324− * started from, so the model goes without them.
325− */
326−export async function adviseHeld(
327− ai: Ai,
328− collisions: readonly HeldCollision[],
329− held: { agent: string; message: string },
330− opts: { model?: string; at?: number } = {},
331−): Promise<(Advice | null)[]> {
332− const lines = (text: string) => (text === "" ? [] : text.replace(/\r?\n$/, "").split(/\r?\n/));
333− return Promise.all(
334− collisions.map(async (c) => {
335− if (c.kind !== "lines" || c.untouched || c.marked) return null;
336− try {
337− return await advise(
338− ai,
339− {
340− file: c.file,
341− base: [],
342− yours: lines(c.yours.text),
343− theirs: lines(c.theirs.text),
344− before: [],
345− after: [],
346− yourAgent: held.agent,
347− yourMessage: held.message,
348− theirAgent: c.theirs.agent,
349− theirMessage: c.theirs.message,
350− },
351− opts,
352− );
353− } catch (e) {
354− console.error(`autosettle: ${c.file}: ${e instanceof Error ? e.message : String(e)}`);
355− return null;
356− }
357− }),
358− );
359−}
--- /dev/null
+++ b/worker/project/autosettle.ts
@@ -0,0 +1,359 @@
1+// A first opinion on a held push (#19), shared by the open server and the platform: for each collision, which of abso's
5+
10+
27+
34+ * rule: code decided without the model. turned down: the model's pick would break the file. unsure: the model
42+
46+
47+const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));
48+
53+ if (yours.join("\n") === theirs.join("\n")) return { pick: "theirs", reason: "both sides wrote the same lines" };
60+
67+ return `keeping both would repeat ${twice.length === 1 ? "a line" : `${twice.length} lines`}: ${twice[0]}`;
75+ // Two versions of one statement, such as an import from the same module with a different list of names:
77+ const names = (lines: readonly string[]) => new Set(lines.join(" ").match(/[A-Za-z_$][\w$]{2,}/g) ?? []);
86+
88+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.
90+- "yours": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.
91+- "theirs": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.
92+- "both": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.
93+- "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.
94+Give "confidence" from 0 to 1: how likely your pick is the correct settle. Give "reason" as one plain sentence. Do not write code.`;
95+
96+const block = (lines: readonly string[]) => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
97+
121+
131+
132+/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */
137+): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {
150+ const answer = (typeof out.response === "string" ? JSON.parse(out.response) : out.response) as {
155+ if (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);
159+ const votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<
173+
174+const text = (lines: readonly string[]): string => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
175+
181+ before_either_change: h.base.length === 0 && h.before.length === 0 ? "(not given)" : text(h.base),
186+ their_push: { agent: h.theirAgent ?? "the other agent", message: h.theirMessage ?? "(no message)" },
190+
193+ "`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. " +
196+
198+ yours: "Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.",
199+ theirs: "Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.",
200+ both: "Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.",
202+ "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.",
204+
210+
218+ "If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?",
220+
222+ * A System One request (TypeSafe's Jev and Cloudflare's Clef both take it): the choice in two option orders, since
232+ ...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: "noul", instructions: q }])),
236+
237+/** Choice confidence: how far the top probability sits above an even split, 0 to 1 (TypeSafe's formula). */
243+
249+): Promise<{ pick: Pick; confidence: number; reason: string; probabilities: Record<Pick, number> }> {
250+ const out = (await ai.run(model === "clef-flash" ? "@cf/cloudflare/clef-flash" : "@cf/cloudflare/clef", {
269+ reason: `Clef's probabilities: ${PICKS.map((k) => `${words[k]} ${probabilities[k].toFixed(2)}`).join(", ")}`,
272+
282+ // Clef unless a text model is named: on project abso's 33 past holds it settled nothing wrong at 0.5 or more,
309+ : { pick: m.pick, confidence: m.confidence, reason: m.reason, by: "model", model, ms: Date.now() - started };
311+
318+ readonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };
320+
322+ * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply
323+ * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both
332+ const lines = (text: string) => (text === "" ? [] : text.replace(/\r?\n$/, "").split(/\r?\n/));
worker/project/test/autosettle.test.tsrenamed from server/test/autosettle.test.ts, 98% the same+1 −1Blame
similarity index 98%
rename from server/test/autosettle.test.ts
rename to worker/project/test/autosettle.test.ts
--- a/server/test/autosettle.test.ts
+++ b/worker/project/test/autosettle.test.ts
@@ -1,6 +1,6 @@
3−import { type Ai, adviseHeld, refused, ruled } from "../src/autosettle.ts";
44
66 * A stand-in for Workers AI that always leans to `pick`: a System One answer for Clef (`top` on `pick`, the rest