// BudgetBench ORACLE: the gold of every case, computed from a household's truth/ledger.csv and truth/setup.json // alone, by the money definitions below. It never imports app code and never reads an answer. Extended from the // definitions of eval/reference.py and eval-chat/facts.mjs (the earlier evals' independent oracles). // // DEFINITIONS (the same for every system): // - A month is a calendar month; the running month ends today (setup.today). "all" is every month of the ledger. // - Spending: rows whose group is not Income, Transfers or Debt Payments. Per category AND per month the signed // amounts are summed and floored at zero (a refund lowers its own category, never another); a span is the sum of // its months. Pending rows count. A purchase its owner excluded in their app is not in the truth ledger at all. // - A shop's spending is the same computation over that shop's rows (purchases minus its refunds). // - Money in (income): the Income group (wages and card cashback). Money out: spending plus debt payments other than // card payments. Kept: money in minus spending (also accepted: money in minus money out; and either with the // refund credit, the part of a refund larger than its category's purchases, counted as money in: owner's ruling // 2026-10-04). // - A count is the number of purchases (rows with money out); the count with refund rows is also accepted. // - A new shop (measure new_merchants, 2026-10-22): a shop whose first purchase in the whole ledger falls in the // months asked; never asked of the ledger's first month, which has nothing before it. // - Each account has its own currency. No figure ever adds two currencies: every computation reads one currency // (the scope account's, else the meaning's `currency`, else the ledger's home currency). import fs from "node:fs"; import path from "node:path"; import {parseCsvLine} from "../households/csv.mjs"; const NOT_SPEND = new Set(["Income", "Transfers", "Debt Payments"]); export const r2 = (v) => Math.round(v * 100) / 100; const MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; export const monthLabel = (k) => `${MONTH_NAMES[Number(k.slice(5)) - 1]} ${k.slice(0, 4)}`; /** a household directory -> {dir, setup, rows, months, today, cur, home, merchants, aliases, categories, groups} */ export function loadHousehold(dir) { const lines = fs.readFileSync(path.join(dir, "truth/ledger.csv"), "utf8").replace(/\r/g, "").trim().split("\n"); const head = parseCsvLine(lines[0]); const rows = lines.slice(1).map((l) => { const v = parseCsvLine(l); const o = Object.fromEntries(head.map((h, i) => [h, v[i]])); return {...o, amount: Number(o.amount), month: o.date.slice(0, 7), pending: o.pending === "true"}; }); const setup = JSON.parse(fs.readFileSync(path.join(dir, "truth/setup.json"), "utf8")); let aliases = {}; try { aliases = JSON.parse(fs.readFileSync(path.join(dir, "truth/merchants.json"), "utf8")); } catch { /* none */ } const months = [...new Set(rows.map((r) => r.month))].sort(); return {dir, setup, rows, months, today: setup.today, cur: setup.today.slice(0, 7), home: setup.currency, merchants: [...new Set(rows.map((r) => r.merchant))].sort(), aliases, categories: [...new Set(rows.map((r) => r.category))].sort(), groups: [...new Set(rows.map((r) => r.group))].sort(), accounts: setup.accounts}; } const isSpend = (r) => !NOT_SPEND.has(r.group); /** the rows a meaning's scope selects (before the spend/income split), in one currency */ function scoped(hh, m, currency) { const ex = m.exclude ?? {}; const exM = new Set((ex.merchants ?? []).map((x) => x.toLowerCase())); const exC = new Set((ex.categories ?? []).map((x) => x.toLowerCase())); const exG = new Set((ex.groups ?? []).map((x) => x.toLowerCase())); return hh.rows.filter((r) => r.currency === currency && (m.merchant == null || r.merchant.toLowerCase() === m.merchant.toLowerCase()) && (m.category == null || r.category.toLowerCase() === m.category.toLowerCase()) && (m.group == null || r.group.toLowerCase() === m.group.toLowerCase()) && (m.account == null || r.account.toLowerCase() === m.account.toLowerCase()) && !exM.has(r.merchant.toLowerCase()) && !exC.has(r.category.toLowerCase()) && !exG.has(r.group.toLowerCase())); } export function currencyOf(hh, m) { if (m.currency) return m.currency; if (m.account) { const a = hh.accounts.find((x) => x.name.toLowerCase() === m.account.toLowerCase()); if (a?.currency) return a.currency; } if (m.merchant) { const r = hh.rows.find((x) => x.merchant.toLowerCase() === m.merchant.toLowerCase()); if (r) return r.currency; } return hh.home; } export const monthsOf = (hh, m) => (m.months == null || m.months === "all" ? [...hh.months] : m.months); /** spending of a set of rows over months: per category per month floored, summed */ export function spendOf(rows, months) { const cell = new Map(); for (const r of rows) { if (!isSpend(r) || !months.includes(r.month)) continue; const k = `${r.category}|${r.month}`; cell.set(k, (cell.get(k) ?? 0) + r.amount); } let t = 0; for (const v of cell.values()) t += Math.max(0, -v); return r2(t); } const refundCredit = (rows, months) => { const cell = new Map(); for (const r of rows) { if (!isSpend(r) || !months.includes(r.month)) continue; const k = `${r.category}|${r.month}`; cell.set(k, (cell.get(k) ?? 0) + r.amount); } let t = 0; for (const v of cell.values()) if (v > 0) t += v; return r2(t); }; const incomeOf = (rows, months) => r2(rows.filter((r) => r.group === "Income" && months.includes(r.month)).reduce((a, r) => a + r.amount, 0)); const loansOf = (rows, months) => r2(-rows.filter((r) => r.group === "Debt Payments" && r.category !== "Credit Card Payment" && months.includes(r.month)).reduce((a, r) => a + r.amount, 0)); /** * the gold of one turn's meaning: {gold, months, scope, measure, direction?, rank?, accept, currency}. * `alt_meanings` (a turn a careful person could read two ways, decided when the case was written): each other * reading's figure is accepted too, and a clarifying question is right (`accept: "clarify"` is implied). */ export function goldOf(hh, m) { const g = goldOne(hh, m); if (!Array.isArray(m.alt_meanings) || !m.alt_meanings.length) return g; const alts = []; for (const am of m.alt_meanings) { const a = goldOne(hh, {...m, alt_meanings: undefined, ...am}); if (a.gold.type !== g.gold.type || !["money", "count", "percent"].includes(a.gold.type)) throw new Error(`an alternative reading must have the same kind of answer (${g.gold.type} vs ${a.gold.type})`); alts.push(a.gold.value, ...(a.gold.alt ?? [])); if (Array.isArray(a.months) && Array.isArray(g.months)) g.months = [...new Set([...g.months, ...a.months])].sort(); } g.gold.alt = [...new Set([...(g.gold.alt ?? []), ...alts])].filter((v) => v !== g.gold.value); g.accept = "clarify"; return g; } function goldOne(hh, m) { const accept = m.accept ?? "answer"; const base = {measure: m.measure ?? m.act, accept, scope: [m.merchant, m.category, m.group, m.account].filter(Boolean)}; if (m.act === "decline") return {...base, gold: {type: "decline"}, months: null}; if (m.act === "cannot") return {...base, gold: {type: "cannot"}, months: null}; if (m.act === "howto") { if (!Array.isArray(m.concepts) || !m.concepts.length) throw new Error("howto needs concepts"); return {...base, gold: {type: "howto", concepts: m.concepts, forbid: m.forbid ?? []}, months: null}; } if (m.act === "clarify") return {...base, accept: "clarify", gold: {type: "clarify"}, months: m.months && m.months !== "all" ? m.months : null}; if (m.act !== "lookup") throw new Error(`unknown act ${m.act}`); const cur = currencyOf(hh, m); const months = monthsOf(hh, m); for (const k of months) if (!hh.months.includes(k)) throw new Error(`month ${k} is not in the ledger (${hh.months.join(", ")})`); // (a thing the ledger does not hold is an error in the case, unless the case says so: `absent` asks about a // category or shop with nothing in it, whose gold is "nothing") for (const [field, list] of [["merchant", hh.merchants], ["category", hh.categories], ["group", hh.groups]]) if (m[field] != null && !list.some((x) => x.toLowerCase() === m[field].toLowerCase())) { if (m.absent === true) return {...base, months: monthsOf(hh, m), currency: hh.home, gold: {type: "none"}}; throw new Error(`${field} "${m[field]}" is not in the ledger`); } if (m.account != null && !hh.accounts.some((a) => a.name.toLowerCase() === m.account.toLowerCase())) throw new Error(`account "${m.account}" is not in the ledger`); const rows = scoped(hh, m, cur); const all = scoped(hh, {exclude: m.exclude, account: m.account}, cur); const out = {...base, months, currency: cur}; const money = (v, alt = []) => ({type: "money", value: r2(v), ...(alt.filter((a) => Math.abs(a - v) >= 0.005).length ? {alt: [...new Set(alt.map(r2))].filter((a) => Math.abs(a - v) >= 0.005)} : {}), currency: cur}); switch (m.measure) { case "spend": { // (one figure per currency, never added: "how much did I spend in all" in a two-currency ledger) if (m.per_currency === true) { const curs = [...new Set(hh.rows.map((r) => r.currency))].sort((a, b) => (a === hh.home ? -1 : b === hh.home ? 1 : a.localeCompare(b))); const parts = curs.map((c) => [c, spendOf(scoped(hh, {...m, currency: undefined}, c), months)]).filter(([, v]) => v > 0.005); if (parts.length < 2) throw new Error("per_currency needs spending in two currencies"); return {...out, currency: null, gold: {type: "money_set", values: parts.map(([, v]) => v), currencies: parts.map(([c]) => c)}}; } const v = spendOf(rows, months); if (v === 0) return {...out, gold: {type: "none"}}; return {...out, gold: money(v)}; } case "income": { const v = incomeOf(rows, months); if (v === 0) return {...out, gold: {type: "none"}}; return {...out, gold: money(v)}; } case "money_out": return {...out, gold: money(r2(spendOf(rows, months) + loansOf(rows, months)))}; case "kept": { const inc = incomeOf(all, months), sp = spendOf(all, months), mo = r2(sp + loansOf(all, months)), cr = refundCredit(all, months); return {...out, gold: money(inc - sp, [inc - mo, inc + cr - sp, inc + cr - mo])}; } case "savings_rate": { const inc = incomeOf(all, months), sp = spendOf(all, months), mo = r2(sp + loansOf(all, months)), cr = refundCredit(all, months); if (inc === 0) throw new Error("savings rate with no income"); const pct = (x) => Math.round(1000 * x) / 10; const v = pct((inc - sp) / inc); return {...out, gold: {type: "percent", value: v, alt: [...new Set([pct((inc - mo) / inc), pct((inc + cr - sp) / (inc + cr))])].filter((a) => a !== v)}}; } case "count": { const inMonths = rows.filter((r) => isSpend(r) && months.includes(r.month)); const buys = inMonths.filter((r) => r.amount < 0).length; if (buys === 0) return {...out, gold: {type: "none"}}; const withRefunds = inMonths.length; return {...out, gold: {type: "count", value: buys, ...(withRefunds !== buys ? {alt: [withRefunds]} : {})}}; } case "average_month": { if (months.length < 2) throw new Error("an average needs two months or more"); return {...out, gold: money(spendOf(rows, months) / months.length)}; } case "largest_purchase": case "smallest_purchase": { const buys = rows.filter((r) => isSpend(r) && r.amount < 0 && months.includes(r.month)).sort((a, b) => a.amount - b.amount); if (!buys.length) return {...out, gold: {type: "none"}}; const pickRow = m.measure === "largest_purchase" ? buys[0] : buys[buys.length - 1]; const ties = buys.filter((r) => Math.abs(r.amount - pickRow.amount) < 0.005).map((r) => r.merchant); return {...out, gold: money(-pickRow.amount), detail: {merchant: [...new Set(ties)], date: pickRow.date}}; } case "top_category": case "top_merchant": case "top_month": { const rank = m.rank ?? 1; const smallest = m.smallest === true; let entries; if (m.measure === "top_month") entries = months.map((k) => [k, spendOf(rows, [k])]); else { const key = m.measure === "top_merchant" ? "merchant" : (m.level === "group" ? "group" : "category"); const names = [...new Set(rows.filter((r) => isSpend(r) && months.includes(r.month)).map((r) => r[key]))]; entries = names.map((n) => [n, spendOf(rows.filter((r) => r[key] === n), months)]); } entries = entries.filter(([, v]) => v > 0.005).sort((a, b) => (smallest ? a[1] - b[1] : b[1] - a[1]) || a[0].localeCompare(b[0])); if (entries.length < rank) throw new Error(`no entry at rank ${rank}`); const [name, v] = entries[rank - 1]; const tie = entries.some(([n, x], i) => i !== rank - 1 && Math.abs(x - v) < 0.005); if (tie) throw new Error(`a tie at rank ${rank}: ask another rank`); const names = m.measure === "top_month" ? [monthLabel(name), MONTH_NAMES[Number(name.slice(5)) - 1]] : m.measure === "top_merchant" ? (hh.aliases[name] ?? [name]) : [name]; return {...out, gold: {type: "names", all: [names], value_of: r2(v)}, rank, direction: smallest ? "smallest" : "biggest"}; } case "by_month": { const vals = months.map((k) => [k, spendOf(rows, [k])]).filter(([, v]) => v > 0.005); if (vals.length < 2) throw new Error("a table by month needs two months with spending"); return {...out, gold: {type: "money_set", values: vals.map(([, v]) => v), months: vals.map(([k]) => k), currency: cur}}; } case "difference": { if (!Array.isArray(m.versus) || !m.versus.length) throw new Error("difference needs versus months"); for (const k of m.versus) if (!hh.months.includes(k)) throw new Error(`month ${k} not in the ledger`); const a = spendOf(rows, months), b = spendOf(rows, m.versus); if (Math.abs(a - b) < 0.005) throw new Error("no difference"); const dir = months.length === 1 && m.versus.length === 1 ? (a > b ? {more: months[0], less: m.versus[0]} : {more: m.versus[0], less: months[0]}) : null; return {...out, months: [...months, ...m.versus], gold: money(Math.abs(a - b)), ...(dir ? {direction: dir} : {}), sides: {a, b}}; } case "latest_charge": case "yearly_cost": { if (m.merchant == null) throw new Error(`${m.measure} needs a merchant`); const charges = rows.filter((r) => isSpend(r) && r.amount < 0).sort((x, y) => x.date.localeCompare(y.date)); if (!charges.length) throw new Error("no charges"); const last = -charges[charges.length - 1].amount; return {...out, months: null, gold: money(m.measure === "latest_charge" ? last : last * 12)}; } case "new_merchants": { // (added 2026-10-22, before the sealed v3 writers; additive: no other measure changed) the shops whose FIRST // purchase in the whole ledger, in this scope and currency, falls in the months asked: "which shops did I // try for the first time in March". The ledger's first month has nothing before it, so it is never asked. if (m.months == null || m.months === "all") throw new Error("new_merchants needs months (never all)"); if (months.includes(hh.months[0])) throw new Error(`new_merchants: ${monthLabel(hh.months[0])} is the ledger's first month; nothing comes before it`); const first = new Map(); for (const r of rows) if (isSpend(r) && r.amount < 0 && !(first.get(r.merchant) <= r.date)) first.set(r.merchant, r.date); const fresh = [...first].filter(([, d]) => months.includes(d.slice(0, 7))).sort((a, b) => a[1].localeCompare(b[1]) || a[0].localeCompare(b[0])).map(([n]) => n); if (!fresh.length) return {...out, gold: {type: "none"}}; return {...out, gold: {type: "names", all: fresh.map((n) => hh.aliases[n] ?? [n])}}; } case "balance": { const a = hh.accounts.find((x) => x.name.toLowerCase() === String(m.account ?? "").toLowerCase()); if (a?.balance == null) throw new Error("balance needs an account with a balance"); return {...out, months: null, gold: money(a.balance)}; } case "share": { const whole = spendOf(scoped(hh, {exclude: m.exclude}, cur), months); const part = spendOf(rows, months); if (whole === 0 || part === 0) throw new Error("share of nothing"); const v = Math.round(1000 * part / whole) / 10; return {...out, gold: {type: "percent", value: v}}; } default: throw new Error(`unknown measure ${m.measure}`); } } /** a plain-English rendering of a meaning, for the review sheets (never shown to a system) */ export function describe(m) { if (m.act !== "lookup") return m.act; const scope = [m.merchant && `at ${m.merchant}`, m.category && `on ${m.category}`, m.group && `on group ${m.group}`, m.account && `on account ${m.account}`].filter(Boolean).join(" "); const ex = Object.values(m.exclude ?? {}).flat(); const when = m.months === "all" || m.months == null ? "all months" : m.months.map(monthLabel).join(" + "); return `${m.measure}${m.rank ? ` #${m.rank}` : ""}${m.smallest ? " (smallest first)" : ""}${m.level ? ` (${m.level} level)` : ""}${m.per_currency ? " (each currency apart)" : ""} ${scope} in ${when}${m.versus ? ` vs ${m.versus.map(monthLabel).join(" + ")}` : ""}${ex.length ? ` leaving out ${ex.join(", ")}` : ""}${m.currency ? ` (${m.currency})` : ""}`.replace(/\s+/g, " ").trim(); }