{"version":189,"agent":"autosettle","message":"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.","time":1792017105757,"timeIso":"2026-10-14T22:31:45.757Z","changes":8,"change":3146,"files":["scripts/autosettle/jev.ts","scripts/autosettle/score.ts","scripts/autosettle/settle-one.ts"],"draft":null,"diff":[{"path":"scripts/autosettle/jev.ts","added":176,"removed":0,"diff":"--- /dev/null\n+++ b/scripts/autosettle/jev.ts\n@@ -0,0 +1,176 @@\n+// Ask Jev (TypeSafe's System One model) how a held push's collision should be\n+// settled (#19). Jev answers a Choice with a probability per option, so it can\n+// pick among abso's own settle choices but can't write code.\n+//\n+// API: POST https://api.typesafe.ai/v1/systemone, per https://docs.typesafe.ai/api.md.\n+// The key comes from JEV_API_KEY (or TYPESAFE_API_KEY, the SDK's own name) and\n+// is never printed or written anywhere.\n+\n+import { execFileSync } from \"node:child_process\";\n+\n+export const ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";\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+\n+/** One collision as the held agent sees it: a marker block and what's around 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 Verdict {\n+\treadonly pick: Pick;\n+\t/** Averaged over both option orders. */\n+\treadonly probabilities: Record<Pick, number>;\n+\t/** Choice confidence on the averaged probabilities: 0 at an even split, 1 when certain. */\n+\treadonly confidence: number;\n+\t/** Each order's own answer, to see whether the order moved it. */\n+\treadonly orders: readonly { pick: Pick; probabilities: Record<Pick, number>; confidence: number }[];\n+\t/** Yes-probabilities of the side questions. */\n+\treadonly signs: Record<string, number>;\n+\treadonly model: string;\n+\treadonly ms: number;\n+\treadonly inputTokens: number;\n+}\n+\n+export function apiKey(): string {\n+\tconst key = process.env.JEV_API_KEY ?? process.env.TYPESAFE_API_KEY ?? userVariable(\"JEV_API_KEY\");\n+\tif (!key) throw new Error(\"No Jev key: set JEV_API_KEY in the environment.\");\n+\treturn key;\n+}\n+\n+/** On Windows, a user variable set after this shell started (setx, or the Environment Variables dialog). */\n+function userVariable(name: string): string | undefined {\n+\tif (process.platform !== \"win32\") return undefined;\n+\ttry {\n+\t\tconst out = execFileSync(\n+\t\t\t\"powershell.exe\",\n+\t\t\t[\"-NoProfile\", \"-Command\", `[Environment]::GetEnvironmentVariable('${name}','User')`],\n+\t\t\t{ encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n+\t\t).trim();\n+\t\treturn out || undefined;\n+\t} catch {\n+\t\treturn undefined;\n+\t}\n+}\n+\n+const text = (lines: readonly string[]): string => (lines.length === 0 ? \"(no lines)\" : lines.join(\"\\n\"));\n+\n+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: 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+function choice(order: readonly Pick[]) {\n+\treturn {\n+\t\ttype: \"choice\",\n+\t\tinstructions: INSTRUCTIONS,\n+\t\tcriteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),\n+\t};\n+}\n+\n+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+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+function top(p: Record<Pick, number>): Pick {\n+\treturn PICKS.reduce((a, b) => (p[b] > p[a] ? b : a));\n+}\n+\n+/** Ask Jev once, with the choice in two option orders (Jev's docs warn order can sway a Choice) and the side questions. */\n+export async function ask(h: Hold, opts: { model?: string; key?: string } = {}): Promise<Verdict> {\n+\tconst forward = PICKS;\n+\tconst backward = [...PICKS].reverse();\n+\tconst body = {\n+\t\tmodel: opts.model ?? \"jev-latest\",\n+\t\tstate: stateOf(h),\n+\t\tquestions: {\n+\t\t\tsettle: choice(forward),\n+\t\t\tsettle_reversed: choice(backward),\n+\t\t\t...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: \"noul\", instructions: q }])),\n+\t\t},\n+\t};\n+\tconst started = performance.now();\n+\tconst res = await fetch(ENDPOINT, {\n+\t\tmethod: \"POST\",\n+\t\theaders: { authorization: `Bearer ${opts.key ?? apiKey()}`, \"content-type\": \"application/json\" },\n+\t\tbody: JSON.stringify(body),\n+\t});\n+\tconst ms = performance.now() - started;\n+\tif (!res.ok) throw new Error(`Jev answered ${res.status}: ${(await res.text()).slice(0, 500)}`);\n+\tconst out = (await res.json()) as {\n+\t\tmodel: string;\n+\t\tanswers: Record<string, { type: string; probabilities?: Record<string, number>; noul?: number; choice?: string }>;\n+\t\tusage: { input_tokens: number };\n+\t};\n+\tconst orders = [\"settle\", \"settle_reversed\"].map((id) => {\n+\t\tconst probabilities = Object.fromEntries(PICKS.map((k) => [k, out.answers[id]!.probabilities![k] ?? 0])) as Record<\n+\t\t\tPick,\n+\t\t\tnumber\n+\t\t>;\n+\t\treturn { pick: top(probabilities), probabilities, confidence: confidenceOf(probabilities) };\n+\t});\n+\tconst probabilities = Object.fromEntries(\n+\t\tPICKS.map((k) => [k, (orders[0]!.probabilities[k] + orders[1]!.probabilities[k]) / 2]),\n+\t) as Record<Pick, number>;\n+\treturn {\n+\t\tpick: top(probabilities),\n+\t\tprobabilities,\n+\t\tconfidence: confidenceOf(probabilities),\n+\t\torders,\n+\t\tsigns: Object.fromEntries(Object.keys(SIGNS).map((id) => [id, out.answers[id]?.noul ?? Number.NaN])),\n+\t\tmodel: out.model,\n+\t\tms,\n+\t\tinputTokens: out.usage.input_tokens,\n+\t};\n+}\n+\n+/** Dollars for one call: Jev charges $0.042 per million input tokens, output free (docs.typesafe.ai/models). */\n+export const dollars = (inputTokens: number): number => (inputTokens * 0.042) / 1e6;"},{"path":"scripts/autosettle/score.ts","added":108,"removed":0,"diff":"--- /dev/null\n+++ b/scripts/autosettle/score.ts\n@@ -0,0 +1,108 @@\n+// Score Jev against how agents really settled past holds (#19).\n+//\n+//   node scripts/autosettle/score.ts <cases.json> [--out <report.json>] [--model jev-latest]\n+//\n+// A case is one settled collision: base, yours, theirsLines, context, both\n+// pushes' messages, and `kept` from the server's settled record (yours, theirs,\n+// both, or rewrote, which counts as \"agent\": a hand edit). Needs JEV_API_KEY.\n+\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { ask, dollars, type Hold, PICKS, type Pick, type Verdict } from \"./jev.ts\";\n+\n+interface Case {\n+\tid: string;\n+\tfile: string;\n+\tkind?: string;\n+\tsettler: { agent: string; heldMessage?: string; settleMessage?: string };\n+\ttheirs: { agent: string; version: number; message?: string };\n+\tbase: string[] | null;\n+\tyours: string[] | null;\n+\ttheirsLines: string[] | null;\n+\tcontext?: { before?: string[]; after?: string[] };\n+\tkept: \"yours\" | \"theirs\" | \"both\" | \"rewrote\";\n+\tissue?: string | null;\n+}\n+\n+const truth = (kept: Case[\"kept\"]): Pick => (kept === \"rewrote\" ? \"agent\" : kept);\n+\n+function holdOf(c: Case): Hold {\n+\treturn {\n+\t\tfile: c.file,\n+\t\tbase: c.base ?? [],\n+\t\tyours: c.yours ?? [],\n+\t\ttheirs: c.theirsLines ?? [],\n+\t\tbefore: c.context?.before ?? [],\n+\t\tafter: c.context?.after ?? [],\n+\t\tyourAgent: c.settler.agent,\n+\t\t...(c.settler.heldMessage ? { yourMessage: c.settler.heldMessage } : {}),\n+\t\ttheirAgent: c.theirs.agent,\n+\t\t...(c.theirs.message ? { theirMessage: c.theirs.message } : {}),\n+\t\t...(c.issue ? { issue: c.issue } : {}),\n+\t};\n+}\n+\n+function flag(args: string[], name: string): string | undefined {\n+\tconst i = args.indexOf(name);\n+\treturn i === -1 ? undefined : args[i + 1];\n+}\n+\n+const args = process.argv.slice(2);\n+const cases = (JSON.parse(readFileSync(args[0]!, \"utf8\")) as Case[]).filter(\n+\t(c) => c.yours !== null && c.theirsLines !== null,\n+);\n+const rows: { id: string; truth: Pick; verdict: Verdict; right: boolean }[] = [];\n+for (const c of cases) {\n+\ttry {\n+\t\tconst verdict = await ask(holdOf(c), { ...(flag(args, \"--model\") ? { model: flag(args, \"--model\") } : {}) });\n+\t\tconst t = truth(c.kept);\n+\t\trows.push({ id: c.id, truth: t, verdict, right: verdict.pick === t });\n+\t\tconsole.log(\n+\t\t\t`${verdict.pick === t ? \"agree\" : \"DIFFER\"}  ${c.id}: agent ${t}, Jev ${verdict.pick} ${verdict.confidence.toFixed(2)} (${verdict.ms.toFixed(0)} ms)`,\n+\t\t);\n+\t} catch (e) {\n+\t\tconsole.log(`error   ${c.id}: ${(e as Error).message}`);\n+\t}\n+}\n+\n+const mean = (xs: number[]) => (xs.length === 0 ? Number.NaN : xs.reduce((a, b) => a + b, 0) / xs.length);\n+const right = rows.filter((r) => r.right);\n+const wrong = rows.filter((r) => !r.right);\n+const ms = rows.map((r) => r.verdict.ms).sort((a, b) => a - b);\n+const tokens = rows.map((r) => r.verdict.inputTokens);\n+const at = (threshold: number) => {\n+\tconst sure = rows.filter((r) => r.verdict.confidence >= threshold);\n+\treturn { threshold, settled: sure.length, agreed: sure.filter((r) => r.right).length };\n+};\n+const report = {\n+\tmodel: rows[0]?.verdict.model,\n+\tcases: rows.length,\n+\tskipped: cases.length - rows.length,\n+\tagreed: right.length,\n+\tconfidenceWhenRight: mean(right.map((r) => r.verdict.confidence)),\n+\tconfidenceWhenWrong: mean(wrong.map((r) => r.verdict.confidence)),\n+\tthresholds: [0.3, 0.5, 0.6, 0.7, 0.8, 0.9].map(at),\n+\tconfusion: Object.fromEntries(\n+\t\tPICKS.map((t) => [\n+\t\t\tt,\n+\t\t\tObject.fromEntries(PICKS.map((p) => [p, rows.filter((r) => r.truth === t && r.verdict.pick === p).length])),\n+\t\t]),\n+\t),\n+\tordersDisagreed: rows.filter((r) => r.verdict.orders[0]!.pick !== r.verdict.orders[1]!.pick).length,\n+\tlatencyMs: { median: ms[Math.floor(ms.length / 2)], max: ms[ms.length - 1], mean: mean(ms) },\n+\tinputTokensMean: mean(tokens),\n+\tdollarsPerCall: dollars(mean(tokens)),\n+\trows: rows.map((r) => ({\n+\t\tid: r.id,\n+\t\tagent: r.truth,\n+\t\tjev: r.verdict.pick,\n+\t\tconfidence: r.verdict.confidence,\n+\t\tprobabilities: r.verdict.probabilities,\n+\t\torders: r.verdict.orders.map((o) => o.pick),\n+\t\tsigns: r.verdict.signs,\n+\t\tms: Math.round(r.verdict.ms),\n+\t})),\n+};\n+const out = flag(args, \"--out\");\n+if (out) writeFileSync(out, JSON.stringify(report, null, \"\\t\"));\n+const { rows: _, ...summary } = report;\n+console.log(JSON.stringify(summary, null, \"\\t\"));"},{"path":"scripts/autosettle/settle-one.ts","added":81,"removed":0,"diff":"--- /dev/null\n+++ b/scripts/autosettle/settle-one.ts\n@@ -0,0 +1,81 @@\n+// Ask Jev how to settle each marker block in one file (#19), the way abso pull\n+// leaves a held push's file. Prints Jev's pick and its probabilities; changes nothing.\n+//\n+//   node scripts/autosettle/settle-one.ts <file> [--message \"<your held push's message>\"] [--issue \"...\"] [--name <path in the project>] [--json]\n+//\n+// Needs JEV_API_KEY in the environment.\n+\n+import { readFileSync } from \"node:fs\";\n+import { findBlocks } from \"../../client/src/settle.ts\";\n+import { ask, dollars, type Hold, PICKS } from \"./jev.ts\";\n+\n+const CONTEXT = 15;\n+const CLOSE = /^>>>>>>> theirs: (.*?), version (\\d+) \"(.*)\"$/;\n+\n+/** Each marker block in a file's text as a Hold. */\n+export function holdsIn(\n+\ttext: string,\n+\tfile: string,\n+\textra: { yourMessage?: string; yourAgent?: string; issue?: string } = {},\n+): Hold[] {\n+\tconst lines = text.split(/\\r?\\n/);\n+\treturn findBlocks(lines).map((b) => {\n+\t\tconst close = CLOSE.exec(lines[b.end]!);\n+\t\treturn {\n+\t\t\tfile,\n+\t\t\tbase: b.base,\n+\t\t\tyours: b.yours,\n+\t\t\ttheirs: b.theirs,\n+\t\t\tbefore: lines.slice(Math.max(0, b.start - CONTEXT), b.start),\n+\t\t\tafter: lines.slice(b.end + 1, b.end + 1 + CONTEXT),\n+\t\t\t...(close ? { theirAgent: close[1], theirMessage: close[3] } : {}),\n+\t\t\t...extra,\n+\t\t};\n+\t});\n+}\n+\n+function flag(args: string[], name: string): string | undefined {\n+\tconst i = args.indexOf(name);\n+\treturn i === -1 ? undefined : args[i + 1];\n+}\n+\n+async function main(): Promise<void> {\n+\tconst args = process.argv.slice(2);\n+\tconst path = args[0];\n+\tif (!path || path.startsWith(\"--\")) {\n+\t\tconsole.error(\n+\t\t\t'usage: node scripts/autosettle/settle-one.ts <file> [--message \"...\"] [--issue \"...\"] [--name <path>] [--json]',\n+\t\t);\n+\t\tprocess.exit(2);\n+\t}\n+\tconst holds = holdsIn(readFileSync(path, \"utf8\"), flag(args, \"--name\") ?? path, {\n+\t\t...(flag(args, \"--message\") ? { yourMessage: flag(args, \"--message\") } : {}),\n+\t\t...(flag(args, \"--issue\") ? { issue: flag(args, \"--issue\") } : {}),\n+\t});\n+\tif (holds.length === 0) {\n+\t\tconsole.error(`${path} has no marker blocks.`);\n+\t\tprocess.exit(1);\n+\t}\n+\tconst results = [];\n+\tfor (const [i, h] of holds.entries()) {\n+\t\tconst v = await ask(h);\n+\t\tresults.push({ block: i + 1, ...v });\n+\t\tif (args.includes(\"--json\")) continue;\n+\t\tconst pct = (x: number) => `${(x * 100).toFixed(0)}%`;\n+\t\tconsole.log(`Block ${i + 1} of ${holds.length} in ${h.file}: ${v.pick}, confidence ${v.confidence.toFixed(2)}`);\n+\t\tconsole.log(`  probabilities: ${PICKS.map((k) => `${k} ${pct(v.probabilities[k])}`).join(\", \")}`);\n+\t\tconsole.log(\n+\t\t\t`  each order: ${v.orders.map((o) => `${o.pick} ${o.confidence.toFixed(2)}`).join(\" / \")}; side questions: ${Object.entries(\n+\t\t\t\tv.signs,\n+\t\t\t)\n+\t\t\t\t.map(([k, p]) => `${k} ${pct(p)}`)\n+\t\t\t\t.join(\", \")}`,\n+\t\t);\n+\t\tconsole.log(\n+\t\t\t`  ${v.model}, ${v.ms.toFixed(0)} ms, ${v.inputTokens} input tokens ($${dollars(v.inputTokens).toFixed(6)})`,\n+\t\t);\n+\t}\n+\tif (args.includes(\"--json\")) console.log(JSON.stringify(results, null, \"\\t\"));\n+}\n+\n+if (process.argv[1]?.endsWith(\"settle-one.ts\")) await main();"}],"ci":null}