Jev auto-settle prototype, step 1 (#19): scripts/autosettle asks Jev to pick keep yours, theirs, both, or needs an agent for each marker block, and scores it against past settles. Local scripts only; reads JEV_API_KEY, never prints it. Version 189 of shared· autosettle· Oct 14 (2026-10-14 22:31 UTC) · Not checked
Version 188 · Files at version 189
3 files, 365 lines added, 0 removed.
--- /dev/null
+++ b/scripts/autosettle/jev.ts
@@ -0,0 +1,176 @@
1 + // Ask Jev (TypeSafe's System One model) how a held push's collision should be 2 + // settled (#19). Jev answers a Choice with a probability per option, so it can 3 + // pick among abso's own settle choices but can't write code. 5 + // API: POST https://api.typesafe.ai/v1/systemone, per https://docs.typesafe.ai/api.md. 6 + // The key comes from JEV_API_KEY (or TYPESAFE_API_KEY, the SDK's own name) and 7 + // is never printed or written anywhere. 9 + import { execFileSync } from "node:child_process"; 11 + export const ENDPOINT = "https://api.typesafe.ai/v1/systemone"; 13 + /** abso's settle choices, plus a hand edit by an agent. */ 14 + export type Pick = "yours" | "theirs" | "both" | "agent"; 15 + export const PICKS: readonly Pick[] = ["yours", "theirs", "both", "agent"]; 17 + /** One collision as the held agent sees it: a marker block and what's around it. */ 18 + export interface Hold { 19 + readonly file: string; 20 + readonly base: readonly string[]; 21 + readonly yours: readonly string[]; 22 + readonly theirs: readonly string[]; 23 + readonly before: readonly string[]; 24 + readonly after: readonly string[]; 25 + /** The held push's message: the settler's reason. */ 26 + readonly yourMessage?: string; 27 + readonly yourAgent?: string; 28 + /** The push that got there first: its reason. */ 29 + readonly theirMessage?: string; 30 + readonly theirAgent?: string; 31 + readonly issue?: string; 34 + export interface Verdict { 36 + /** Averaged over both option orders. */ 37 + readonly probabilities: Record<Pick, number>; 38 + /** Choice confidence on the averaged probabilities: 0 at an even split, 1 when certain. */ 39 + readonly confidence: number; 40 + /** Each order's own answer, to see whether the order moved it. */ 41 + readonly orders: readonly { pick: Pick; probabilities: Record<Pick, number>; confidence: number }[]; 42 + /** Yes-probabilities of the side questions. */ 43 + readonly signs: Record<string, number>; 44 + readonly model: string; 46 + readonly inputTokens: number; 49 + export function apiKey(): string { 50 + const key = process.env.JEV_API_KEY ?? process.env.TYPESAFE_API_KEY ?? userVariable("JEV_API_KEY"); 51 + if (!key) throw new Error("No Jev key: set JEV_API_KEY in the environment."); 55 + /** On Windows, a user variable set after this shell started (setx, or the Environment Variables dialog). */ 56 + function userVariable(name: string): string | undefined { 57 + if (process.platform !== "win32") return undefined; 59 + const out = execFileSync( 61 + ["-NoProfile", "-Command", `[Environment]::GetEnvironmentVariable('${name}','User')`], 62 + { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, 64 + return out || undefined; 70 + const text = (lines: readonly string[]): string => (lines.length === 0 ? "(no lines)" : lines.join("\n")); 72 + function stateOf(h: Hold): Record<string, unknown> { 75 + lines_above: text(h.before), 76 + before_either_change: text(h.base), 77 + yours: text(h.yours), 78 + theirs: text(h.theirs), 79 + lines_below: text(h.after), 80 + your_push: { agent: h.yourAgent ?? "you", message: h.yourMessage ?? "(no message)" }, 81 + their_push: { agent: h.theirAgent ?? "the other agent", message: h.theirMessage ?? "(no message)" }, 82 + ...(h.issue ? { issue: h.issue } : {}), 87 + "Two agents changed the same lines of `file`. Both started from `before_either_change`. " + 88 + "`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. " + 89 + "The region sits between `lines_above` and `lines_below`. " + 90 + "Which result is correct code that does what both pushes meant?"; 92 + const CRITERIA: Record<Pick, string> = { 93 + yours: "Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.", 94 + theirs: "Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.", 95 + both: "Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.", 97 + "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.", 100 + function choice(order: readonly Pick[]) { 103 + instructions: INSTRUCTIONS, 104 + criteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])), 108 + const SIGNS: Record<string, string> = { 109 + same_setting_different_values: 110 + "Do `yours` and `theirs` set the same setting, constant or value to two different values?", 111 + theirs_covers_yours: "Does `theirs` already do everything `yours` was changed to do?", 112 + yours_covers_theirs: "Does `yours` already do everything `theirs` was changed to do?", 113 + both_unchanged_compiles: 114 + "If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?", 117 + function confidenceOf(p: Record<Pick, number>): number { 118 + const max = Math.max(...PICKS.map((k) => p[k])); 119 + const even = 1 / PICKS.length; 120 + return Math.max(0, (max - even) / (1 - even)); 123 + function top(p: Record<Pick, number>): Pick { 124 + return PICKS.reduce((a, b) => (p[b] > p[a] ? b : a)); 127 + /** Ask Jev once, with the choice in two option orders (Jev's docs warn order can sway a Choice) and the side questions. */ 128 + export async function ask(h: Hold, opts: { model?: string; key?: string } = {}): Promise<Verdict> { 129 + const forward = PICKS; 130 + const backward = [...PICKS].reverse(); 132 + model: opts.model ?? "jev-latest", 135 + settle: choice(forward), 136 + settle_reversed: choice(backward), 137 + ...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: "noul", instructions: q }])), 140 + const started = performance.now(); 141 + const res = await fetch(ENDPOINT, { 143 + headers: { authorization: `Bearer ${opts.key ?? apiKey()}`, "content-type": "application/json" }, 144 + body: JSON.stringify(body), 146 + const ms = performance.now() - started; 147 + if (!res.ok) throw new Error(`Jev answered ${res.status}: ${(await res.text()).slice(0, 500)}`); 148 + const out = (await res.json()) as { 150 + answers: Record<string, { type: string; probabilities?: Record<string, number>; noul?: number; choice?: string }>; 151 + usage: { input_tokens: number }; 153 + const orders = ["settle", "settle_reversed"].map((id) => { 154 + const probabilities = Object.fromEntries(PICKS.map((k) => [k, out.answers[id]!.probabilities![k] ?? 0])) as Record< 158 + return { pick: top(probabilities), probabilities, confidence: confidenceOf(probabilities) }; 160 + const probabilities = Object.fromEntries( 161 + PICKS.map((k) => [k, (orders[0]!.probabilities[k] + orders[1]!.probabilities[k]) / 2]), 162 + ) as Record<Pick, number>; 164 + pick: top(probabilities), 166 + confidence: confidenceOf(probabilities), 168 + signs: Object.fromEntries(Object.keys(SIGNS).map((id) => [id, out.answers[id]?.noul ?? Number.NaN])), 171 + inputTokens: out.usage.input_tokens, 175 + /** Dollars for one call: Jev charges $0.042 per million input tokens, output free (docs.typesafe.ai/models). */ 176 + export const dollars = (inputTokens: number): number => (inputTokens * 0.042) / 1e6; --- /dev/null
+++ b/scripts/autosettle/score.ts
@@ -0,0 +1,108 @@
1 + // Score Jev against how agents really settled past holds (#19). 3 + // node scripts/autosettle/score.ts <cases.json> [--out <report.json>] [--model jev-latest] 5 + // A case is one settled collision: base, yours, theirsLines, context, both 6 + // pushes' messages, and `kept` from the server's settled record (yours, theirs, 7 + // both, or rewrote, which counts as "agent": a hand edit). Needs JEV_API_KEY. 9 + import { readFileSync, writeFileSync } from "node:fs"; 10 + import { ask, dollars, type Hold, PICKS, type Pick, type Verdict } from "./jev.ts"; 16 + settler: { agent: string; heldMessage?: string; settleMessage?: string }; 17 + theirs: { agent: string; version: number; message?: string }; 18 + base: string[] | null; 19 + yours: string[] | null; 20 + theirsLines: string[] | null; 21 + context?: { before?: string[]; after?: string[] }; 22 + kept: "yours" | "theirs" | "both" | "rewrote"; 23 + issue?: string | null; 26 + const truth = (kept: Case["kept"]): Pick => (kept === "rewrote" ? "agent" : kept); 28 + function holdOf(c: Case): Hold { 32 + yours: c.yours ?? [], 33 + theirs: c.theirsLines ?? [], 34 + before: c.context?.before ?? [], 35 + after: c.context?.after ?? [], 36 + yourAgent: c.settler.agent, 37 + ...(c.settler.heldMessage ? { yourMessage: c.settler.heldMessage } : {}), 38 + theirAgent: c.theirs.agent, 39 + ...(c.theirs.message ? { theirMessage: c.theirs.message } : {}), 40 + ...(c.issue ? { issue: c.issue } : {}), 44 + function flag(args: string[], name: string): string | undefined { 45 + const i = args.indexOf(name); 46 + return i === -1 ? undefined : args[i + 1]; 49 + const args = process.argv.slice(2); 50 + const cases = (JSON.parse(readFileSync(args[0]!, "utf8")) as Case[]).filter( 51 + (c) => c.yours !== null && c.theirsLines !== null, 53 + const rows: { id: string; truth: Pick; verdict: Verdict; right: boolean }[] = []; 54 + for (const c of cases) { 56 + const verdict = await ask(holdOf(c), { ...(flag(args, "--model") ? { model: flag(args, "--model") } : {}) }); 57 + const t = truth(c.kept); 58 + rows.push({ id: c.id, truth: t, verdict, right: verdict.pick === t }); 60 + `${verdict.pick === t ? "agree" : "DIFFER"} ${c.id}: agent ${t}, Jev ${verdict.pick} ${verdict.confidence.toFixed(2)} (${verdict.ms.toFixed(0)} ms)`, 63 + console.log(`error ${c.id}: ${(e as Error).message}`); 67 + const mean = (xs: number[]) => (xs.length === 0 ? Number.NaN : xs.reduce((a, b) => a + b, 0) / xs.length); 68 + const right = rows.filter((r) => r.right); 69 + const wrong = rows.filter((r) => !r.right); 70 + const ms = rows.map((r) => r.verdict.ms).sort((a, b) => a - b); 71 + const tokens = rows.map((r) => r.verdict.inputTokens); 72 + const at = (threshold: number) => { 73 + const sure = rows.filter((r) => r.verdict.confidence >= threshold); 74 + return { threshold, settled: sure.length, agreed: sure.filter((r) => r.right).length }; 77 + model: rows[0]?.verdict.model, 79 + skipped: cases.length - rows.length, 80 + agreed: right.length, 81 + confidenceWhenRight: mean(right.map((r) => r.verdict.confidence)), 82 + confidenceWhenWrong: mean(wrong.map((r) => r.verdict.confidence)), 83 + thresholds: [0.3, 0.5, 0.6, 0.7, 0.8, 0.9].map(at), 84 + confusion: Object.fromEntries( 87 + Object.fromEntries(PICKS.map((p) => [p, rows.filter((r) => r.truth === t && r.verdict.pick === p).length])), 90 + ordersDisagreed: rows.filter((r) => r.verdict.orders[0]!.pick !== r.verdict.orders[1]!.pick).length, 91 + latencyMs: { median: ms[Math.floor(ms.length / 2)], max: ms[ms.length - 1], mean: mean(ms) }, 92 + inputTokensMean: mean(tokens), 93 + dollarsPerCall: dollars(mean(tokens)), 94 + rows: rows.map((r) => ({ 98 + confidence: r.verdict.confidence, 99 + probabilities: r.verdict.probabilities, 100 + orders: r.verdict.orders.map((o) => o.pick), 101 + signs: r.verdict.signs, 102 + ms: Math.round(r.verdict.ms), 105 + const out = flag(args, "--out"); 106 + if (out) writeFileSync(out, JSON.stringify(report, null, "\t")); 107 + const { rows: _, ...summary } = report; 108 + console.log(JSON.stringify(summary, null, "\t")); --- /dev/null
+++ b/scripts/autosettle/settle-one.ts
@@ -0,0 +1,81 @@
1 + // Ask Jev how to settle each marker block in one file (#19), the way abso pull 2 + // leaves a held push's file. Prints Jev's pick and its probabilities; changes nothing. 4 + // node scripts/autosettle/settle-one.ts <file> [--message "<your held push's message>"] [--issue "..."] [--name <path in the project>] [--json] 6 + // Needs JEV_API_KEY in the environment. 8 + import { readFileSync } from "node:fs"; 9 + import { findBlocks } from "../../client/src/settle.ts"; 10 + import { ask, dollars, type Hold, PICKS } from "./jev.ts"; 13 + const CLOSE = /^>>>>>>> theirs: (.*?), version (\d+) "(.*)"$/; 15 + /** Each marker block in a file's text as a Hold. */ 16 + export function holdsIn( 19 + extra: { yourMessage?: string; yourAgent?: string; issue?: string } = {}, 21 + const lines = text.split(/\r?\n/); 22 + return findBlocks(lines).map((b) => { 23 + const close = CLOSE.exec(lines[b.end]!); 29 + before: lines.slice(Math.max(0, b.start - CONTEXT), b.start), 30 + after: lines.slice(b.end + 1, b.end + 1 + CONTEXT), 31 + ...(close ? { theirAgent: close[1], theirMessage: close[3] } : {}), 37 + function flag(args: string[], name: string): string | undefined { 38 + const i = args.indexOf(name); 39 + return i === -1 ? undefined : args[i + 1]; 42 + async function main(): Promise<void> { 43 + const args = process.argv.slice(2); 44 + const path = args[0]; 45 + if (!path || path.startsWith("--")) { 47 + 'usage: node scripts/autosettle/settle-one.ts <file> [--message "..."] [--issue "..."] [--name <path>] [--json]', 51 + const holds = holdsIn(readFileSync(path, "utf8"), flag(args, "--name") ?? path, { 52 + ...(flag(args, "--message") ? { yourMessage: flag(args, "--message") } : {}), 53 + ...(flag(args, "--issue") ? { issue: flag(args, "--issue") } : {}), 55 + if (holds.length === 0) { 56 + console.error(`${path} has no marker blocks.`); 60 + for (const [i, h] of holds.entries()) { 61 + const v = await ask(h); 62 + results.push({ block: i + 1, ...v }); 63 + if (args.includes("--json")) continue; 64 + const pct = (x: number) => `${(x * 100).toFixed(0)}%`; 65 + console.log(`Block ${i + 1} of ${holds.length} in ${h.file}: ${v.pick}, confidence ${v.confidence.toFixed(2)}`); 66 + console.log(` probabilities: ${PICKS.map((k) => `${k} ${pct(v.probabilities[k])}`).join(", ")}`); 68 + ` each order: ${v.orders.map((o) => `${o.pick} ${o.confidence.toFixed(2)}`).join(" / ")}; side questions: ${Object.entries( 71 + .map(([k, p]) => `${k} ${pct(p)}`) 75 + ` ${v.model}, ${v.ms.toFixed(0)} ms, ${v.inputTokens} input tokens ($${dollars(v.inputTokens).toFixed(6)})`, 78 + if (args.includes("--json")) console.log(JSON.stringify(results, null, "\t")); 81 + if (process.argv[1]?.endsWith("settle-one.ts")) await main();