{"version":203,"agent":"autosettle","message":"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.","time":1792028025572,"timeIso":"2026-10-15T01:33:45.572Z","changes":6,"change":3442,"files":["scripts/autosettle/jev.ts","scripts/autosettle/rules.ts","server/src/autosettle.ts","server/test/autosettle.test.ts","worker/project/autosettle.ts","worker/project/test/autosettle.test.ts"],"draft":null,"diff":[{"path":"scripts/autosettle/jev.ts","added":2,"removed":2,"diff":"--- a/scripts/autosettle/jev.ts\n+++ b/scripts/autosettle/jev.ts\n@@ -7,9 +7,9 @@\n // is never printed or written anywhere.\n \n import { execFileSync } from \"node:child_process\";\n-import { confidenceOf, SIGNS, systemOneBody } from \"../../server/src/autosettle.ts\";\n+import { confidenceOf, SIGNS, systemOneBody } from \"../../worker/project/autosettle.ts\";\n \n-// The questions are the open server's own (server/src/autosettle.ts), so Jev and Clef are asked alike.\n+// The questions are the tool's own (worker/project/autosettle.ts), so Jev and Clef are asked alike.\n export { systemOneBody };\n \n export const ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";"},{"path":"scripts/autosettle/rules.ts","added":2,"removed":2,"diff":"--- a/scripts/autosettle/rules.ts\n+++ b/scripts/autosettle/rules.ts\n@@ -1,3 +1,3 @@\n-// Checks in code around the model's pick (#19): the open server's own, so the scripts score what it runs.\n+// 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.\n \n-export { refused, ruled } from \"../../server/src/autosettle.ts\";\n+export { refused, ruled } from \"../../worker/project/autosettle.ts\";"},{"path":"server/src/autosettle.ts","added":3,"removed":358,"diff":"--- a/server/src/autosettle.ts\n+++ b/server/src/autosettle.ts\n@@ -1,359 +1,4 @@\n-// A first opinion on a held push (#19): for each collision, which of abso's\n-// settle choices fits, from Workers AI, with checks in code before and after.\n-// Off unless AUTOSETTLE is \"on\" and the Worker has an AI binding. The model\n-// picks one of four words; it never writes code.\n+// A first opinion on a held push (#19): the tool's own, in worker/project/autosettle.ts, so the platform's pin\n+// carries it too.\n \n-/** abso's settle choices, plus a hand edit by an agent. */\n-export type Pick = \"yours\" | \"theirs\" | \"both\" | \"agent\";\n-export const PICKS: readonly Pick[] = [\"yours\", \"theirs\", \"both\", \"agent\"];\n-export const MODEL = \"@cf/meta/llama-3.3-70b-instruct-fp8-fast\";\n-\n-/** One collision as the held agent sees it. */\n-export interface Hold {\n-\treadonly file: string;\n-\treadonly base: readonly string[];\n-\treadonly yours: readonly string[];\n-\treadonly theirs: readonly string[];\n-\treadonly before: readonly string[];\n-\treadonly after: readonly string[];\n-\t/** The held push's message: the settler's reason. */\n-\treadonly yourMessage?: string;\n-\treadonly yourAgent?: string;\n-\t/** The push that got there first: its reason. */\n-\treadonly theirMessage?: string;\n-\treadonly theirAgent?: string;\n-\treadonly issue?: string;\n-}\n-\n-export interface Advice {\n-\treadonly pick: Pick;\n-\t/** The share of samples that agree, or 1 for a pick code made. */\n-\treadonly confidence: number;\n-\treadonly reason: string;\n-\t/**\n-\t * rule: code decided without the model. turned down: the model's pick would break the file. unsure: the model\n-\t * leaned to a side under the threshold, so an agent settles.\n-\t */\n-\treadonly by: \"rule\" | \"model\" | \"turned down\" | \"unsure\";\n-\treadonly modelPick?: Pick;\n-\treadonly model?: string;\n-\treadonly ms: number;\n-}\n-\n-export interface Ai {\n-\trun(model: string, input: unknown): Promise<unknown>;\n-}\n-\n-const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));\n-\n-/** A pick code can make without the model, with why; undefined when it takes judgment. */\n-export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {\n-\tconst yours = solid(h.yours);\n-\tconst theirs = solid(h.theirs);\n-\tif (yours.join(\"\\n\") === theirs.join(\"\\n\")) return { pick: \"theirs\", reason: \"both sides wrote the same lines\" };\n-\tif (yours.length > 0 && yours.every((l) => theirs.includes(l)))\n-\t\treturn { pick: \"theirs\", reason: \"every line of yours is already in theirs\" };\n-\tif (theirs.length > 0 && theirs.every((l) => yours.includes(l)))\n-\t\treturn { pick: \"yours\", reason: \"every line of theirs is already in yours\" };\n-\treturn undefined;\n-}\n-\n-/** Why a model's pick can't be applied as it is, or undefined when it can. */\n-export function refused(h: Hold, pick: Pick): string | undefined {\n-\tif (pick !== \"both\") return undefined;\n-\tconst theirs = new Set(solid(h.theirs));\n-\tconst twice = solid(h.yours).filter((l) => theirs.has(l));\n-\tif (twice.length > 0)\n-\t\treturn `keeping both would repeat ${twice.length === 1 ? \"a line\" : `${twice.length} lines`}: ${twice[0]}`;\n-\t// The same key or name set on both sides: `timeoutMs:`, `limit =`.\n-\tconst key = (l: string) => /^([A-Za-z_$\"'][\\w$\"'-]*)\\s*[:=]/.exec(l)?.[1];\n-\tconst theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));\n-\tconst clash = solid(h.yours)\n-\t\t.map(key)\n-\t\t.find((k) => k && theirKeys.has(k));\n-\tif (clash) return `keeping both would set ${clash} twice`;\n-\t// Two versions of one statement, such as an import from the same module with a different list of names:\n-\t// most of the names on one side are on the other too.\n-\tconst names = (lines: readonly string[]) => new Set(lines.join(\" \").match(/[A-Za-z_$][\\w$]{2,}/g) ?? []);\n-\tconst a = names(h.yours);\n-\tconst b = names(h.theirs);\n-\tconst shared = [...a].filter((n) => b.has(n)).length;\n-\tconst share = shared / Math.max(1, Math.min(a.size, b.size));\n-\treturn share >= 0.5\n-\t\t? `keeping both would repeat one statement in two versions (${shared} names on both sides)`\n-\t\t: undefined;\n-}\n-\n-const SYSTEM = `You settle merge collisions in a version control system for coding agents.\n-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.\n-Pick exactly one:\n-- \"yours\": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.\n-- \"theirs\": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.\n-- \"both\": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.\n-- \"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.\n-Give \"confidence\" from 0 to 1: how likely your pick is the correct settle. Give \"reason\" as one plain sentence. Do not write code.`;\n-\n-const block = (lines: readonly string[]) => (lines.length === 0 ? \"(no lines)\" : lines.join(\"\\n\"));\n-\n-function prompt(h: Hold): string {\n-\treturn [\n-\t\t`FILE: ${h.file}`,\n-\t\t`YOUR PUSH (${h.yourAgent ?? \"you\"}): ${h.yourMessage ?? \"(no message)\"}`,\n-\t\t`THEIR PUSH (${h.theirAgent ?? \"the other agent\"}): ${h.theirMessage ?? \"(no message)\"}`,\n-\t\t...(h.issue ? [`ISSUE: ${h.issue}`] : []),\n-\t\t\"\",\n-\t\t\"LINES ABOVE:\",\n-\t\tblock(h.before),\n-\t\t\"\",\n-\t\t\"BEFORE (what both started from):\",\n-\t\th.base.length === 0 && h.before.length === 0 ? \"(not given)\" : block(h.base),\n-\t\t\"\",\n-\t\t\"YOURS:\",\n-\t\tblock(h.yours),\n-\t\t\"\",\n-\t\t\"THEIRS:\",\n-\t\tblock(h.theirs),\n-\t\t\"\",\n-\t\t\"LINES BELOW:\",\n-\t\tblock(h.after),\n-\t].join(\"\\n\");\n-}\n-\n-const SCHEMA = {\n-\ttype: \"object\",\n-\tproperties: {\n-\t\tpick: { type: \"string\", enum: PICKS },\n-\t\tconfidence: { type: \"number\", minimum: 0, maximum: 1 },\n-\t\treason: { type: \"string\" },\n-\t},\n-\trequired: [\"pick\", \"confidence\", \"reason\"],\n-};\n-\n-/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */\n-export async function modelPick(\n-\tai: Ai,\n-\th: Hold,\n-\topts: { model?: string; samples?: number } = {},\n-): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {\n-\tconst model = opts.model ?? MODEL;\n-\tconst samples = Math.min(9, Math.max(1, opts.samples ?? 5));\n-\tconst one = async () => {\n-\t\tconst out = (await ai.run(model, {\n-\t\t\tmessages: [\n-\t\t\t\t{ role: \"system\", content: SYSTEM },\n-\t\t\t\t{ role: \"user\", content: prompt(h) },\n-\t\t\t],\n-\t\t\tresponse_format: { type: \"json_schema\", json_schema: SCHEMA },\n-\t\t\ttemperature: samples > 1 ? 0.7 : 0,\n-\t\t\tmax_tokens: 200,\n-\t\t})) as { response: unknown; usage?: unknown };\n-\t\tconst answer = (typeof out.response === \"string\" ? JSON.parse(out.response) : out.response) as {\n-\t\t\tpick: string;\n-\t\t\tconfidence: number;\n-\t\t\treason: string;\n-\t\t};\n-\t\tif (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);\n-\t\treturn { ...answer, pick: answer.pick as Pick, usage: out.usage ?? null };\n-\t};\n-\tconst answers = await Promise.all(Array.from({ length: samples }, one));\n-\tconst votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<\n-\t\tPick,\n-\t\tnumber\n-\t>;\n-\tconst pick = PICKS.reduce((a, b) => (votes[b] > votes[a] ? b : a));\n-\tconst first = answers.find((a) => a.pick === pick)!;\n-\treturn {\n-\t\tpick,\n-\t\tconfidence: samples > 1 ? votes[pick] / samples : first.confidence,\n-\t\treason: first.reason,\n-\t\tselfReported: answers.map((a) => a.confidence),\n-\t\tusage: first.usage,\n-\t};\n-}\n-\n-const text = (lines: readonly string[]): string => (lines.length === 0 ? \"(no lines)\" : lines.join(\"\\n\"));\n-\n-/** A hold as a System One state: the content the questions point at by name. */\n-export function stateOf(h: Hold): Record<string, unknown> {\n-\treturn {\n-\t\tfile: h.file,\n-\t\tlines_above: text(h.before),\n-\t\tbefore_either_change: h.base.length === 0 && h.before.length === 0 ? \"(not given)\" : text(h.base),\n-\t\tyours: text(h.yours),\n-\t\ttheirs: text(h.theirs),\n-\t\tlines_below: text(h.after),\n-\t\tyour_push: { agent: h.yourAgent ?? \"you\", message: h.yourMessage ?? \"(no message)\" },\n-\t\ttheir_push: { agent: h.theirAgent ?? \"the other agent\", message: h.theirMessage ?? \"(no message)\" },\n-\t\t...(h.issue ? { issue: h.issue } : {}),\n-\t};\n-}\n-\n-const INSTRUCTIONS =\n-\t\"Two agents changed the same lines of `file`. Both started from `before_either_change`. \" +\n-\t\"`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. \" +\n-\t\"The region sits between `lines_above` and `lines_below`. \" +\n-\t\"Which result is correct code that does what both pushes meant?\";\n-\n-const CRITERIA: Record<Pick, string> = {\n-\tyours: \"Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.\",\n-\ttheirs: \"Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.\",\n-\tboth: \"Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.\",\n-\tagent:\n-\t\t\"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.\",\n-};\n-\n-const choice = (order: readonly Pick[]) => ({\n-\ttype: \"choice\",\n-\tinstructions: INSTRUCTIONS,\n-\tcriteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),\n-});\n-\n-/** Side questions asked with the choice, for the record (yes-probabilities). */\n-export const SIGNS: Record<string, string> = {\n-\tsame_setting_different_values:\n-\t\t\"Do `yours` and `theirs` set the same setting, constant or value to two different values?\",\n-\ttheirs_covers_yours: \"Does `theirs` already do everything `yours` was changed to do?\",\n-\tyours_covers_theirs: \"Does `yours` already do everything `theirs` was changed to do?\",\n-\tboth_unchanged_compiles:\n-\t\t\"If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?\",\n-};\n-\n-/**\n- * A System One request (TypeSafe's Jev and Cloudflare's Clef both take it): the choice in two option orders, since\n- * Jev's docs warn order can sway a Choice, and the side questions.\n- */\n-export function systemOneBody(h: Hold, model: string) {\n-\treturn {\n-\t\tmodel,\n-\t\tstate: stateOf(h),\n-\t\tquestions: {\n-\t\t\tsettle: choice(PICKS),\n-\t\t\tsettle_reversed: choice([...PICKS].reverse()),\n-\t\t\t...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: \"noul\", instructions: q }])),\n-\t\t},\n-\t};\n-}\n-\n-/** Choice confidence: how far the top probability sits above an even split, 0 to 1 (TypeSafe's formula). */\n-export function confidenceOf(p: Record<Pick, number>): number {\n-\tconst max = Math.max(...PICKS.map((k) => p[k]));\n-\tconst even = 1 / PICKS.length;\n-\treturn Math.max(0, (max - even) / (1 - even));\n-}\n-\n-/** Clef's pick: the two orders' probabilities averaged. */\n-export async function clefPick(\n-\tai: Ai,\n-\th: Hold,\n-\tmodel: string,\n-): Promise<{ pick: Pick; confidence: number; reason: string; probabilities: Record<Pick, number> }> {\n-\tconst out = (await ai.run(model === \"clef-flash\" ? \"@cf/cloudflare/clef-flash\" : \"@cf/cloudflare/clef\", {\n-\t\t...systemOneBody(h, model === \"clef-flash\" ? \"clef-flash\" : \"clef\"),\n-\t})) as { answers?: Record<string, { probabilities?: Record<string, number> }> };\n-\tconst orders = [\"settle\", \"settle_reversed\"].map((id) => out.answers?.[id]?.probabilities);\n-\tif (orders.some((p) => !p)) throw new Error(\"Clef answered without the settle choice\");\n-\tconst probabilities = Object.fromEntries(\n-\t\tPICKS.map((k) => [k, ((orders[0]![k] ?? 0) + (orders[1]![k] ?? 0)) / 2]),\n-\t) as Record<Pick, number>;\n-\tconst pick = PICKS.reduce((a, b) => (probabilities[b] > probabilities[a] ? b : a));\n-\tconst words: Record<Pick, string> = {\n-\t\tyours: \"keep yours\",\n-\t\ttheirs: \"keep theirs\",\n-\t\tboth: \"keep both\",\n-\t\tagent: \"an agent\",\n-\t};\n-\treturn {\n-\t\tpick,\n-\t\tconfidence: confidenceOf(probabilities),\n-\t\tprobabilities,\n-\t\treason: `Clef's probabilities: ${PICKS.map((k) => `${words[k]} ${probabilities[k].toFixed(2)}`).join(\", \")}`,\n-\t};\n-}\n-\n-/** Code's rules first, then the model, then code's check on what the model picked. */\n-export async function advise(\n-\tai: Ai,\n-\th: Hold,\n-\topts: { model?: string; samples?: number; at?: number } = {},\n-): Promise<Advice> {\n-\tconst started = Date.now();\n-\tconst rule = ruled(h);\n-\tif (rule) return { ...rule, confidence: 1, by: \"rule\", ms: 0 };\n-\t// Clef unless a text model is named: on project abso's 33 past holds it settled nothing wrong at 0.5 or more,\n-\t// where the text model was wrong once at 1.00 (#19).\n-\tconst clef = !opts.model || opts.model.startsWith(\"clef\");\n-\tconst m = clef ? await clefPick(ai, h, opts.model ?? \"clef\") : await modelPick(ai, h, opts);\n-\tconst model = clef ? `@cf/cloudflare/${opts.model ?? \"clef\"}` : (opts.model ?? MODEL);\n-\tconst at = opts.at ?? 0.5;\n-\tif (m.pick !== \"agent\" && m.confidence < at)\n-\t\treturn {\n-\t\t\tpick: \"agent\",\n-\t\t\tconfidence: m.confidence,\n-\t\t\treason: `${m.reason}; under ${at}, so an agent settles`,\n-\t\t\tby: \"unsure\",\n-\t\t\tmodelPick: m.pick,\n-\t\t\tmodel,\n-\t\t\tms: Date.now() - started,\n-\t\t};\n-\tconst no = refused(h, m.pick);\n-\treturn no\n-\t\t? {\n-\t\t\t\tpick: \"agent\",\n-\t\t\t\tconfidence: m.confidence,\n-\t\t\t\treason: no,\n-\t\t\t\tby: \"turned down\",\n-\t\t\t\tmodelPick: m.pick,\n-\t\t\t\tmodel,\n-\t\t\t\tms: Date.now() - started,\n-\t\t\t}\n-\t\t: { pick: m.pick, confidence: m.confidence, reason: m.reason, by: \"model\", model, ms: Date.now() - started };\n-}\n-\n-interface HeldCollision {\n-\treadonly kind: string;\n-\treadonly file: string;\n-\treadonly untouched?: true;\n-\treadonly marked?: true;\n-\treadonly yours: { readonly lines: [number, number]; readonly text: string };\n-\treadonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };\n-}\n-\n-/**\n- * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply\n- * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both\n- * started from, so the model goes without them.\n- */\n-export async function adviseHeld(\n-\tai: Ai,\n-\tcollisions: readonly HeldCollision[],\n-\theld: { agent: string; message: string },\n-\topts: { model?: string; at?: number } = {},\n-): Promise<(Advice | null)[]> {\n-\tconst lines = (text: string) => (text === \"\" ? [] : text.replace(/\\r?\\n$/, \"\").split(/\\r?\\n/));\n-\treturn Promise.all(\n-\t\tcollisions.map(async (c) => {\n-\t\t\tif (c.kind !== \"lines\" || c.untouched || c.marked) return null;\n-\t\t\ttry {\n-\t\t\t\treturn await advise(\n-\t\t\t\t\tai,\n-\t\t\t\t\t{\n-\t\t\t\t\t\tfile: c.file,\n-\t\t\t\t\t\tbase: [],\n-\t\t\t\t\t\tyours: lines(c.yours.text),\n-\t\t\t\t\t\ttheirs: lines(c.theirs.text),\n-\t\t\t\t\t\tbefore: [],\n-\t\t\t\t\t\tafter: [],\n-\t\t\t\t\t\tyourAgent: held.agent,\n-\t\t\t\t\t\tyourMessage: held.message,\n-\t\t\t\t\t\ttheirAgent: c.theirs.agent,\n-\t\t\t\t\t\ttheirMessage: c.theirs.message,\n-\t\t\t\t\t},\n-\t\t\t\t\topts,\n-\t\t\t\t);\n-\t\t\t} catch (e) {\n-\t\t\t\tconsole.error(`autosettle: ${c.file}: ${e instanceof Error ? e.message : String(e)}`);\n-\t\t\t\treturn null;\n-\t\t\t}\n-\t\t}),\n-\t);\n-}\n+export * from \"../../worker/project/autosettle.ts\";"},{"path":"worker/project/autosettle.ts","added":359,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/autosettle.ts\n@@ -0,0 +1,359 @@\n+// A first opinion on a held push (#19), shared by the open server and the platform: for each collision, which of abso's\n+// settle choices fits, from Workers AI, with checks in code before and after.\n+// Off unless AUTOSETTLE is \"on\" and the Worker has an AI binding. The model\n+// picks one of four words; it never writes code.\n+\n+/** abso's settle choices, plus a hand edit by an agent. */\n+export type Pick = \"yours\" | \"theirs\" | \"both\" | \"agent\";\n+export const PICKS: readonly Pick[] = [\"yours\", \"theirs\", \"both\", \"agent\"];\n+export const MODEL = \"@cf/meta/llama-3.3-70b-instruct-fp8-fast\";\n+\n+/** One collision as the held agent sees it. */\n+export interface Hold {\n+\treadonly file: string;\n+\treadonly base: readonly string[];\n+\treadonly yours: readonly string[];\n+\treadonly theirs: readonly string[];\n+\treadonly before: readonly string[];\n+\treadonly after: readonly string[];\n+\t/** The held push's message: the settler's reason. */\n+\treadonly yourMessage?: string;\n+\treadonly yourAgent?: string;\n+\t/** The push that got there first: its reason. */\n+\treadonly theirMessage?: string;\n+\treadonly theirAgent?: string;\n+\treadonly issue?: string;\n+}\n+\n+export interface Advice {\n+\treadonly pick: Pick;\n+\t/** The share of samples that agree, or 1 for a pick code made. */\n+\treadonly confidence: number;\n+\treadonly reason: string;\n+\t/**\n+\t * rule: code decided without the model. turned down: the model's pick would break the file. unsure: the model\n+\t * leaned to a side under the threshold, so an agent settles.\n+\t */\n+\treadonly by: \"rule\" | \"model\" | \"turned down\" | \"unsure\";\n+\treadonly modelPick?: Pick;\n+\treadonly model?: string;\n+\treadonly ms: number;\n+}\n+\n+export interface Ai {\n+\trun(model: string, input: unknown): Promise<unknown>;\n+}\n+\n+const solid = (lines: readonly string[]) => lines.map((l) => l.trim()).filter((l) => /[A-Za-z0-9]/.test(l));\n+\n+/** A pick code can make without the model, with why; undefined when it takes judgment. */\n+export function ruled(h: Hold): { pick: Pick; reason: string } | undefined {\n+\tconst yours = solid(h.yours);\n+\tconst theirs = solid(h.theirs);\n+\tif (yours.join(\"\\n\") === theirs.join(\"\\n\")) return { pick: \"theirs\", reason: \"both sides wrote the same lines\" };\n+\tif (yours.length > 0 && yours.every((l) => theirs.includes(l)))\n+\t\treturn { pick: \"theirs\", reason: \"every line of yours is already in theirs\" };\n+\tif (theirs.length > 0 && theirs.every((l) => yours.includes(l)))\n+\t\treturn { pick: \"yours\", reason: \"every line of theirs is already in yours\" };\n+\treturn undefined;\n+}\n+\n+/** Why a model's pick can't be applied as it is, or undefined when it can. */\n+export function refused(h: Hold, pick: Pick): string | undefined {\n+\tif (pick !== \"both\") return undefined;\n+\tconst theirs = new Set(solid(h.theirs));\n+\tconst twice = solid(h.yours).filter((l) => theirs.has(l));\n+\tif (twice.length > 0)\n+\t\treturn `keeping both would repeat ${twice.length === 1 ? \"a line\" : `${twice.length} lines`}: ${twice[0]}`;\n+\t// The same key or name set on both sides: `timeoutMs:`, `limit =`.\n+\tconst key = (l: string) => /^([A-Za-z_$\"'][\\w$\"'-]*)\\s*[:=]/.exec(l)?.[1];\n+\tconst theirKeys = new Set(solid(h.theirs).map(key).filter(Boolean));\n+\tconst clash = solid(h.yours)\n+\t\t.map(key)\n+\t\t.find((k) => k && theirKeys.has(k));\n+\tif (clash) return `keeping both would set ${clash} twice`;\n+\t// Two versions of one statement, such as an import from the same module with a different list of names:\n+\t// most of the names on one side are on the other too.\n+\tconst names = (lines: readonly string[]) => new Set(lines.join(\" \").match(/[A-Za-z_$][\\w$]{2,}/g) ?? []);\n+\tconst a = names(h.yours);\n+\tconst b = names(h.theirs);\n+\tconst shared = [...a].filter((n) => b.has(n)).length;\n+\tconst share = shared / Math.max(1, Math.min(a.size, b.size));\n+\treturn share >= 0.5\n+\t\t? `keeping both would repeat one statement in two versions (${shared} names on both sides)`\n+\t\t: undefined;\n+}\n+\n+const SYSTEM = `You settle merge collisions in a version control system for coding agents.\n+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.\n+Pick exactly one:\n+- \"yours\": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.\n+- \"theirs\": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.\n+- \"both\": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.\n+- \"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.\n+Give \"confidence\" from 0 to 1: how likely your pick is the correct settle. Give \"reason\" as one plain sentence. Do not write code.`;\n+\n+const block = (lines: readonly string[]) => (lines.length === 0 ? \"(no lines)\" : lines.join(\"\\n\"));\n+\n+function prompt(h: Hold): string {\n+\treturn [\n+\t\t`FILE: ${h.file}`,\n+\t\t`YOUR PUSH (${h.yourAgent ?? \"you\"}): ${h.yourMessage ?? \"(no message)\"}`,\n+\t\t`THEIR PUSH (${h.theirAgent ?? \"the other agent\"}): ${h.theirMessage ?? \"(no message)\"}`,\n+\t\t...(h.issue ? [`ISSUE: ${h.issue}`] : []),\n+\t\t\"\",\n+\t\t\"LINES ABOVE:\",\n+\t\tblock(h.before),\n+\t\t\"\",\n+\t\t\"BEFORE (what both started from):\",\n+\t\th.base.length === 0 && h.before.length === 0 ? \"(not given)\" : block(h.base),\n+\t\t\"\",\n+\t\t\"YOURS:\",\n+\t\tblock(h.yours),\n+\t\t\"\",\n+\t\t\"THEIRS:\",\n+\t\tblock(h.theirs),\n+\t\t\"\",\n+\t\t\"LINES BELOW:\",\n+\t\tblock(h.after),\n+\t].join(\"\\n\");\n+}\n+\n+const SCHEMA = {\n+\ttype: \"object\",\n+\tproperties: {\n+\t\tpick: { type: \"string\", enum: PICKS },\n+\t\tconfidence: { type: \"number\", minimum: 0, maximum: 1 },\n+\t\treason: { type: \"string\" },\n+\t},\n+\trequired: [\"pick\", \"confidence\", \"reason\"],\n+};\n+\n+/** The model's pick: several samples at once, the confidence being the share that agree with the most common pick. */\n+export async function modelPick(\n+\tai: Ai,\n+\th: Hold,\n+\topts: { model?: string; samples?: number } = {},\n+): Promise<{ pick: Pick; confidence: number; reason: string; selfReported: number[]; usage: unknown }> {\n+\tconst model = opts.model ?? MODEL;\n+\tconst samples = Math.min(9, Math.max(1, opts.samples ?? 5));\n+\tconst one = async () => {\n+\t\tconst out = (await ai.run(model, {\n+\t\t\tmessages: [\n+\t\t\t\t{ role: \"system\", content: SYSTEM },\n+\t\t\t\t{ role: \"user\", content: prompt(h) },\n+\t\t\t],\n+\t\t\tresponse_format: { type: \"json_schema\", json_schema: SCHEMA },\n+\t\t\ttemperature: samples > 1 ? 0.7 : 0,\n+\t\t\tmax_tokens: 200,\n+\t\t})) as { response: unknown; usage?: unknown };\n+\t\tconst answer = (typeof out.response === \"string\" ? JSON.parse(out.response) : out.response) as {\n+\t\t\tpick: string;\n+\t\t\tconfidence: number;\n+\t\t\treason: string;\n+\t\t};\n+\t\tif (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);\n+\t\treturn { ...answer, pick: answer.pick as Pick, usage: out.usage ?? null };\n+\t};\n+\tconst answers = await Promise.all(Array.from({ length: samples }, one));\n+\tconst votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length])) as Record<\n+\t\tPick,\n+\t\tnumber\n+\t>;\n+\tconst pick = PICKS.reduce((a, b) => (votes[b] > votes[a] ? b : a));\n+\tconst first = answers.find((a) => a.pick === pick)!;\n+\treturn {\n+\t\tpick,\n+\t\tconfidence: samples > 1 ? votes[pick] / samples : first.confidence,\n+\t\treason: first.reason,\n+\t\tselfReported: answers.map((a) => a.confidence),\n+\t\tusage: first.usage,\n+\t};\n+}\n+\n+const text = (lines: readonly string[]): string => (lines.length === 0 ? \"(no lines)\" : lines.join(\"\\n\"));\n+\n+/** A hold as a System One state: the content the questions point at by name. */\n+export function stateOf(h: Hold): Record<string, unknown> {\n+\treturn {\n+\t\tfile: h.file,\n+\t\tlines_above: text(h.before),\n+\t\tbefore_either_change: h.base.length === 0 && h.before.length === 0 ? \"(not given)\" : text(h.base),\n+\t\tyours: text(h.yours),\n+\t\ttheirs: text(h.theirs),\n+\t\tlines_below: text(h.after),\n+\t\tyour_push: { agent: h.yourAgent ?? \"you\", message: h.yourMessage ?? \"(no message)\" },\n+\t\ttheir_push: { agent: h.theirAgent ?? \"the other agent\", message: h.theirMessage ?? \"(no message)\" },\n+\t\t...(h.issue ? { issue: h.issue } : {}),\n+\t};\n+}\n+\n+const INSTRUCTIONS =\n+\t\"Two agents changed the same lines of `file`. Both started from `before_either_change`. \" +\n+\t\"`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. \" +\n+\t\"The region sits between `lines_above` and `lines_below`. \" +\n+\t\"Which result is correct code that does what both pushes meant?\";\n+\n+const CRITERIA: Record<Pick, string> = {\n+\tyours: \"Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.\",\n+\ttheirs: \"Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.\",\n+\tboth: \"Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.\",\n+\tagent:\n+\t\t\"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.\",\n+};\n+\n+const choice = (order: readonly Pick[]) => ({\n+\ttype: \"choice\",\n+\tinstructions: INSTRUCTIONS,\n+\tcriteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),\n+});\n+\n+/** Side questions asked with the choice, for the record (yes-probabilities). */\n+export const SIGNS: Record<string, string> = {\n+\tsame_setting_different_values:\n+\t\t\"Do `yours` and `theirs` set the same setting, constant or value to two different values?\",\n+\ttheirs_covers_yours: \"Does `theirs` already do everything `yours` was changed to do?\",\n+\tyours_covers_theirs: \"Does `yours` already do everything `theirs` was changed to do?\",\n+\tboth_unchanged_compiles:\n+\t\t\"If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?\",\n+};\n+\n+/**\n+ * A System One request (TypeSafe's Jev and Cloudflare's Clef both take it): the choice in two option orders, since\n+ * Jev's docs warn order can sway a Choice, and the side questions.\n+ */\n+export function systemOneBody(h: Hold, model: string) {\n+\treturn {\n+\t\tmodel,\n+\t\tstate: stateOf(h),\n+\t\tquestions: {\n+\t\t\tsettle: choice(PICKS),\n+\t\t\tsettle_reversed: choice([...PICKS].reverse()),\n+\t\t\t...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: \"noul\", instructions: q }])),\n+\t\t},\n+\t};\n+}\n+\n+/** Choice confidence: how far the top probability sits above an even split, 0 to 1 (TypeSafe's formula). */\n+export function confidenceOf(p: Record<Pick, number>): number {\n+\tconst max = Math.max(...PICKS.map((k) => p[k]));\n+\tconst even = 1 / PICKS.length;\n+\treturn Math.max(0, (max - even) / (1 - even));\n+}\n+\n+/** Clef's pick: the two orders' probabilities averaged. */\n+export async function clefPick(\n+\tai: Ai,\n+\th: Hold,\n+\tmodel: string,\n+): Promise<{ pick: Pick; confidence: number; reason: string; probabilities: Record<Pick, number> }> {\n+\tconst out = (await ai.run(model === \"clef-flash\" ? \"@cf/cloudflare/clef-flash\" : \"@cf/cloudflare/clef\", {\n+\t\t...systemOneBody(h, model === \"clef-flash\" ? \"clef-flash\" : \"clef\"),\n+\t})) as { answers?: Record<string, { probabilities?: Record<string, number> }> };\n+\tconst orders = [\"settle\", \"settle_reversed\"].map((id) => out.answers?.[id]?.probabilities);\n+\tif (orders.some((p) => !p)) throw new Error(\"Clef answered without the settle choice\");\n+\tconst probabilities = Object.fromEntries(\n+\t\tPICKS.map((k) => [k, ((orders[0]![k] ?? 0) + (orders[1]![k] ?? 0)) / 2]),\n+\t) as Record<Pick, number>;\n+\tconst pick = PICKS.reduce((a, b) => (probabilities[b] > probabilities[a] ? b : a));\n+\tconst words: Record<Pick, string> = {\n+\t\tyours: \"keep yours\",\n+\t\ttheirs: \"keep theirs\",\n+\t\tboth: \"keep both\",\n+\t\tagent: \"an agent\",\n+\t};\n+\treturn {\n+\t\tpick,\n+\t\tconfidence: confidenceOf(probabilities),\n+\t\tprobabilities,\n+\t\treason: `Clef's probabilities: ${PICKS.map((k) => `${words[k]} ${probabilities[k].toFixed(2)}`).join(\", \")}`,\n+\t};\n+}\n+\n+/** Code's rules first, then the model, then code's check on what the model picked. */\n+export async function advise(\n+\tai: Ai,\n+\th: Hold,\n+\topts: { model?: string; samples?: number; at?: number } = {},\n+): Promise<Advice> {\n+\tconst started = Date.now();\n+\tconst rule = ruled(h);\n+\tif (rule) return { ...rule, confidence: 1, by: \"rule\", ms: 0 };\n+\t// Clef unless a text model is named: on project abso's 33 past holds it settled nothing wrong at 0.5 or more,\n+\t// where the text model was wrong once at 1.00 (#19).\n+\tconst clef = !opts.model || opts.model.startsWith(\"clef\");\n+\tconst m = clef ? await clefPick(ai, h, opts.model ?? \"clef\") : await modelPick(ai, h, opts);\n+\tconst model = clef ? `@cf/cloudflare/${opts.model ?? \"clef\"}` : (opts.model ?? MODEL);\n+\tconst at = opts.at ?? 0.5;\n+\tif (m.pick !== \"agent\" && m.confidence < at)\n+\t\treturn {\n+\t\t\tpick: \"agent\",\n+\t\t\tconfidence: m.confidence,\n+\t\t\treason: `${m.reason}; under ${at}, so an agent settles`,\n+\t\t\tby: \"unsure\",\n+\t\t\tmodelPick: m.pick,\n+\t\t\tmodel,\n+\t\t\tms: Date.now() - started,\n+\t\t};\n+\tconst no = refused(h, m.pick);\n+\treturn no\n+\t\t? {\n+\t\t\t\tpick: \"agent\",\n+\t\t\t\tconfidence: m.confidence,\n+\t\t\t\treason: no,\n+\t\t\t\tby: \"turned down\",\n+\t\t\t\tmodelPick: m.pick,\n+\t\t\t\tmodel,\n+\t\t\t\tms: Date.now() - started,\n+\t\t\t}\n+\t\t: { pick: m.pick, confidence: m.confidence, reason: m.reason, by: \"model\", model, ms: Date.now() - started };\n+}\n+\n+interface HeldCollision {\n+\treadonly kind: string;\n+\treadonly file: string;\n+\treadonly untouched?: true;\n+\treadonly marked?: true;\n+\treadonly yours: { readonly lines: [number, number]; readonly text: string };\n+\treadonly theirs: { readonly agent: string; readonly message: string; readonly text: string; readonly file?: string };\n+}\n+\n+/**\n+ * Advice for each lines collision of a held push, in the order of `collisions`; null where it doesn't apply\n+ * (another kind, already in the agent's file) or the model failed. Collisions don't carry the lines both\n+ * started from, so the model goes without them.\n+ */\n+export async function adviseHeld(\n+\tai: Ai,\n+\tcollisions: readonly HeldCollision[],\n+\theld: { agent: string; message: string },\n+\topts: { model?: string; at?: number } = {},\n+): Promise<(Advice | null)[]> {\n+\tconst lines = (text: string) => (text === \"\" ? [] : text.replace(/\\r?\\n$/, \"\").split(/\\r?\\n/));\n+\treturn Promise.all(\n+\t\tcollisions.map(async (c) => {\n+\t\t\tif (c.kind !== \"lines\" || c.untouched || c.marked) return null;\n+\t\t\ttry {\n+\t\t\t\treturn await advise(\n+\t\t\t\t\tai,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tfile: c.file,\n+\t\t\t\t\t\tbase: [],\n+\t\t\t\t\t\tyours: lines(c.yours.text),\n+\t\t\t\t\t\ttheirs: lines(c.theirs.text),\n+\t\t\t\t\t\tbefore: [],\n+\t\t\t\t\t\tafter: [],\n+\t\t\t\t\t\tyourAgent: held.agent,\n+\t\t\t\t\t\tyourMessage: held.message,\n+\t\t\t\t\t\ttheirAgent: c.theirs.agent,\n+\t\t\t\t\t\ttheirMessage: c.theirs.message,\n+\t\t\t\t\t},\n+\t\t\t\t\topts,\n+\t\t\t\t);\n+\t\t\t} catch (e) {\n+\t\t\t\tconsole.error(`autosettle: ${c.file}: ${e instanceof Error ? e.message : String(e)}`);\n+\t\t\t\treturn null;\n+\t\t\t}\n+\t\t}),\n+\t);\n+}"},{"path":"worker/project/test/autosettle.test.ts","from":"server/test/autosettle.test.ts","similarity":98,"added":1,"removed":1,"diff":"similarity index 98%\nrename from server/test/autosettle.test.ts\nrename to worker/project/test/autosettle.test.ts\n--- a/server/test/autosettle.test.ts\n+++ b/worker/project/test/autosettle.test.ts\n@@ -1,6 +1,6 @@\n import assert from \"node:assert/strict\";\n import { test } from \"node:test\";\n-import { type Ai, adviseHeld, refused, ruled } from \"../src/autosettle.ts\";\n+import { type Ai, adviseHeld, refused, ruled } from \"../autosettle.ts\";\n \n /**\n  * A stand-in for Workers AI that always leans to `pick`: a System One answer for Clef (`top` on `pick`, the rest"}],"ci":null}