Files
threshing-atlas/core/solver.js
T
11b4a0398e Core: a small JS advisor reads the game from policy.json; engine.js is gone (#13)
Step 4b of the Python-first core.

- core/solver.js is now a 250-line advisor (was 900 lines): it reads the game (core/spec/game.yaml,
  published inside policy.json as model.game) and the count tables, and re-solves from any point in
  a run with the same interpreter as the Python model. Same API for the site and Ken's bot
  (advisor, recommendOption, solverHistory). The bot's on-screen text for each option moves to
  game.yaml (bot_text); the deadly rolls carry their risk labels there too.
- tests/core/advisor.test.js: the advisor gives exactly the Python model's values and choices for
  every colour and goal (to 1e-12, every decision on every published route), walks a run in the
  game's order, and maps advice onto the bot's screen.
- Removed core/engine.js and everything that only compared it with Python (tests/parity/run_engine,
  compare_runs, compare_results, compare_routes, compare_solver, compare_stats, analysis/stats/
  analyze.py). In their place: tests/core/test_stats.py checks the statistics against known answers,
  test_solver.py checks the route model on a synthetic world (tests/fixtures/synthetic_policy.py).
- analysis/network/build-graph.js reads the Python-coded runs; graph.json is byte-identical.
- docs/BOT_INTEGRATION.md: what changed for the bot (history keys, new choices, re-sync all three files).


Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:01:32 +00:00

273 lines
15 KiB
JavaScript

/*
* solver.js: the route advisor for the site and the DragonKind bot.
*
* The route model is built in Python (core/atlas/solver.py) from the game in core/spec/game.yaml and published as
* data/policy.json. Each sample in it carries the game itself (model.game) and the count tables behind every roll
* (model.tables, model.alphas). This file reads both and re-solves the game from any point in a run, including
* points off the recommended route, so a rider (or the bot) always gets the best next choice. It is the same
* interpreter as the Python one, kept small: a walk of the game's steps, posterior-mean odds with hierarchical
* back-off, backward induction, and Dinkelbach iteration for the "eventually" goal.
* tests/core/advisor.test.js checks it gives exactly the Python model's values.
*
* Public API (unchanged for the bot): advisor(sample, colour, objective, { only }), recommendOption(adv, h, texts),
* solverHistory(formVars, seen), makeParams(tables, { alphas, game }), ENCOUNTERS (set from the first sample).
* UMD: window.ThreshSolver in the browser, module.exports in Node. No dependencies.
*/
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.ThreshSolver = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const ALPHA = 20;
const ZERO = { x: 0, o: 0, r: 0 }, REACHED = { x: 0, o: 0, r: 1 };
const canon = (s) => JSON.stringify(Object.keys(s).sort().map((k) => [k, s[k]]));
const encColour = (ctx) => (ctx === "tree-Greens" ? "Green" : ctx.split("-")[1]);
const api = {};
/* ---------- the odds: posterior means with hierarchical back-off (as in core/atlas/model.py) ---------- */
function makeParams(T, { alphas = {}, game }) {
const memo = new Map();
const ctxKey = (s, names) => names.map((k) => (s[k] == null ? "?" : s[k])).join("|");
function chance(node, state) {
const sp = game.chance[node], cats = sp.outcomes;
let p = null;
for (let L = 0; L <= sp.context.length; L++) {
const names = sp.context.slice(0, L);
if (names.some((k) => state[k] == null)) break;
const key = L + ":" + ctxKey(state, names), mk = node + "#" + key;
if (memo.has(mk)) { p = memo.get(mk); continue; }
const c = T[node][key] || {}, al = alphas[node] || ALPHA;
const a = cats.map((k, i) => (c[k] || 0) + (p ? al * p[i] : 0.5));
let sum = 0; for (const x of a) sum += x;
p = a.map((x) => x / sum);
memo.set(mk, p);
}
return Object.fromEntries(cats.map((k, i) => [k, p[i]]));
}
function encounter(ctx) {
const mk = "enc#" + ctx;
if (!memo.has(mk)) {
const e = T.encounter[ctx] || { outcomes: {}, seen: {} };
const cats = game.encounter_outcomes.filter((k) => k === "burn" || e.seen[k] || (e.outcomes[k] || 0) > 0 || k === encColour(ctx));
const a = cats.map((k) => (e.outcomes[k] || 0) + 0.5);
let sum = 0; for (const x of a) sum += x;
memo.set(mk, Object.fromEntries(cats.map((k, i) => [k, a[i] / sum])));
}
return memo.get(mk);
}
return { chance, encounter };
}
/* ---------- one walk of the game, used to solve (as Walker in core/atlas/solver.py) ---------- */
function apply(then, state, value) {
const s = then.keep ? Object.fromEntries(then.keep.filter((k) => k in state).map((k) => [k, state[k]])) : { ...state };
for (const k of then.drop || []) delete s[k];
for (const [k, v] of Object.entries(then.set || {})) s[k] = v === "$" ? value : v;
return s;
}
function walker(game, support, only, hooks) {
const options = (name, state) => {
const by = game.decisions[name].support_by;
return by ? support[`${name}:${state[by]}`] || game.decisions[name].options : support[name];
};
function follow(then, value, state) {
const t = then[value] || then.default;
if (t.end) return hooks.end(t.end);
const s = apply(t, state, value);
if (t.encounter) {
const ctx = t.encounter.replace("$", value);
const opts = only && !only.includes(ctx) ? ["Die on purpose"] : support.encounter;
return hooks.decision("encounter", { ...s, enc: ctx }, opts, (o) => (o === "Die on purpose" ? hooks.dieOnPurpose() : hooks.attempt(ctx)));
}
return run(t.go, s);
}
function run(id, state) {
const st = game.steps[id];
if (st.decision) return hooks.decision(st.decision, state, options(st.decision, state), (o) => follow(st.then, o, state));
return hooks.chance(st.chance, state, (k) => follow(st.then, k, state));
}
return { root: () => run(game.start, {}) };
}
/** Backward induction for colour X: score = (1 - lam) P(X) - lam P(other), ties to the higher P(X). */
function solve(params, game, support, X, lam = 0, only = null) {
const memo = new Map(), choices = new Map(), optVals = new Map();
const score = (v) => (1 - lam) * v.x - lam * v.o + 1e-9 * v.x - 1e-12 * v.o;
const w = walker(game, support, only, {
decision(name, state, opts, cont) {
const key = name + "@" + canon(state);
if (memo.has(key)) return memo.get(key);
let top = null, arg = null;
const vals = {};
for (const o of opts) {
const v = cont(o);
vals[o] = v;
if (!top || score(v) > score(top)) { top = v; arg = o; }
}
memo.set(key, top); choices.set(key, arg); optVals.set(key, vals);
return top;
},
chance(node, state, cont) {
let acc = ZERO;
for (const [k, p] of Object.entries(params.chance(node, state))) {
if (!p) continue;
const v = cont(k);
acc = { x: acc.x + p * v.x, o: acc.o + p * v.o, r: acc.r + p * v.r };
}
return acc;
},
end: () => ZERO,
dieOnPurpose: () => REACHED,
attempt(ctx) {
let x = 0, o = 0;
for (const [k, p] of Object.entries(params.encounter(ctx))) if (k !== "burn") { if (k === X) x += p; else o += p; }
return { x, o, r: 1 };
},
});
return { value: w.root(), choices, optVals };
}
function solveRatio(params, game, support, X, only) {
let lam = 0, s = solve(params, game, support, X, 0, only);
for (let i = 0; i < 30; i++) {
const v = s.value, r = v.x + v.o > 0 ? v.x / (v.x + v.o) : 0;
if (Math.abs(r - lam) < 1e-10) break;
lam = r;
s = solve(params, game, support, X, lam, only);
}
return { ...s, lam };
}
/* ---------- the advisor ---------- */
/**
* advisor(sample, X, objective, { only }): sample is policy.samples.all (or .lowBias); X a colour; objective
* "eventually" (default) or "thisAttempt"; only: bond only at these encounters, die on purpose elsewhere.
* Returns { value, step(h), next(h), attempts(ctx), params, game }.
*
* h is a run so far, keyed by the game's step names: decisions (company, leave, direction, react, scream,
* clearing, fight, dagger, fate, wounded, post, hour, descend, red, valley, encounter) and rolls (fs, shadow,
* shadowColour, meadow). A rider asking for advice survived every deadly roll so far; step() reports the risk of
* the deadly roll just passed on the step after it. When h already has a later step but skips an earlier
* decision (an older form record, say), the recommended option is assumed for the skipped one.
*/
function advisor(sample, X, objective = "eventually", { only = null } = {}) {
const m = sample.model, game = m.game;
api.game = game; api.ENCOUNTERS = game.by_colour;
const params = makeParams(m.tables, { alphas: m.alphas, game });
const sol = objective === "eventually" ? solveRatio(params, game, m.support, X, only) : solve(params, game, m.support, X, 0, only);
const VARS = new Set([...Object.keys(game.decisions), ...Object.keys(game.chance), "encounter"]);
const fmt = (v) => ({ pX: v.x, pOther: v.o, pReach: v.r });
const label = (k) => (game.decisions[k] || game.chance[k]).label;
const decisionAt = (name, key, extra) => {
const vals = sol.optVals.get(key) || {};
return { kind: "decision", var: name, label: label(name), choice: sol.choices.get(key),
options: Object.fromEntries(Object.entries(vals).map(([o, v]) => [o, fmt(v)])), ...extra };
};
/** The next thing that happens after history h: a decision, a roll, or the end of the run. */
function step(h) {
const used = new Set();
const later = () => Object.keys(h).some((k) => VARS.has(k) && h[k] != null && !used.has(k));
let id = game.start, state = {}, risk = null;
for (let guard = 0; guard < 100; guard++) {
const st = game.steps[id];
let value;
if (st.decision) {
const name = st.decision, key = name + "@" + canon(state);
if (h[name] != null) { value = h[name]; used.add(name); }
else if (later()) value = sol.choices.get(key);
else return decisionAt(name, key, risk ? { risk } : {});
risk = null;
} else {
const node = st.chance, probs = params.chance(node, state), sp = game.chance[node];
if (sp.risk_label) { risk = { label: sp.risk_label, p: probs.die }; value = "live"; }
else if (h[node] != null) { value = h[node]; used.add(node); risk = null; }
else return { kind: "chance", var: node, label: label(node), probs, ...(risk ? { risk } : {}) };
}
const t = st.then[value] || st.then.default;
if (!t) return { kind: "end", invalid: `${st.decision || st.chance} = ${value}` };
if (t.end) return { kind: "end", what: t.end };
const s = apply(t, state, value);
if (t.encounter) {
const ctx = t.encounter.replace("$", value);
if (h.encounter == null) return decisionAt("encounter", "encounter@" + canon({ ...s, enc: ctx }), { encounter: ctx, ...(risk ? { risk } : {}) });
return { kind: "end", encounter: ctx, action: h.encounter, outcomes: h.encounter === "Die on purpose" ? { burn: 1 } : params.encounter(ctx) };
}
id = t.go; state = s;
}
throw new Error("the game has no end");
}
return {
colour: X, objective, only, value: sol.value, step, params, game,
/** attempts recorded at an encounter (genuine attempts only), to show how much data a bond chance rests on */
attempts: (ctx) => Object.values(((m.tables.encounter || {})[ctx] || { outcomes: {} }).outcomes).reduce((a, b) => a + b, 0),
/** the next decision only (null when the next step is a roll or the run is over) */
next(h) {
const s = step(h);
return s.kind === "decision" ? { decision: s.var, label: s.label, choice: s.choice, options: s.options } : null;
},
};
}
/* ---------- the bot ---------- */
const norm = (t) => String(t || "").toLowerCase().replace(/[‘’‛`']/g, "'").replace(/[–—-]/g, " ").replace(/[^a-z0-9'\s]/g, " ").replace(/\s+/g, " ").trim();
/**
* Which of the options on the bot's screen to pick: { index, decision, choice, margin, options, reason }.
* index is null when there is no advice for this screen (use the bot's own rules). The encounter decision
* ("Attempt the bond" / "Die on purpose") is returned without an index: the bot knows which option is which.
* The on-screen text of each option is in game.yaml (bot_text).
*/
function recommendOption(adv, h, offered) {
const rec = adv.next(h);
if (!rec) return null;
const pat = ((adv.game.bot_text || {})[rec.decision] || {})[rec.choice];
const idx = pat ? offered.map(norm).findIndex((t) => new RegExp(pat).test(t)) : -1;
const values = Object.values(rec.options).map((v) => v.pX).sort((a, b) => b - a);
return { index: idx < 0 ? null : idx, decision: rec.decision, choice: rec.choice, margin: values.length > 1 ? values[0] - values[1] : null,
options: rec.options,
reason: idx < 0 && rec.decision !== "encounter" ? "the recommended choice is not on this screen; use the bot's own rules" : `${rec.label}: ${rec.choice}` };
}
/**
* The community form's variables for a run so far (graph.trajectoryVariables(t).vars, or a coded form run) as a
* history for advisor().step(), keyed by the game's step names. seen: what the bot saw on screen that the form does
* not ask: { shadow: "yes"|"no", shadowColour, meadow }. Uses the game of the last advisor made (or pass one).
*/
function solverHistory(vars, seen = {}, game = api.game) {
const D = game.decisions, F = game.from_form, h = {};
const has = (k, v) => D[k].options.includes(v);
if (has("company", vars.company)) h.company = vars.company;
const lf = vars.left_squadmates;
if (h.company && h.company !== "Alone" && lf != null && lf !== "") h.leave = String(lf).toLowerCase() === "true" ? "Leave them" : "Stay together";
if (has("direction", vars.direction)) h.direction = vars.direction;
if (["Red", "Brown", "Green", "Orange"].includes(vars.first_sighting)) h.fs = vars.first_sighting;
if (has("react", vars.sighting_action)) h.react = vars.sighting_action;
if (vars.scream === "Ignore the scream") h.scream = "Keep walking";
else if (vars.scream === "Investigate & help" || vars.scream === "Investigate & leave" || vars.scream_investigate) h.scream = "Investigate the scream";
if (vars.scream === "Investigate & help") h.clearing = "Help your squadmate";
if (vars.scream === "Investigate & leave") h.clearing = "Walk away";
if (F.fight[vars.combat_first]) h.fight = F.fight[vars.combat_first];
if (F.dagger[vars.combat_second]) h.dagger = F.dagger[vars.combat_second];
if (F.helped.includes(vars.resolution)) h.fate = vars.resolution;
if (F.ignored.includes(vars.resolution)) h.wounded = vars.resolution;
if (has("post", vars.post_path)) h.post = vars.post_path;
if (has("hour", vars.hour)) h.hour = vars.hour;
if (vars.branch === "Descend quickly: Red" || vars.branch === "Descend quickly: let the Red pass") h.descend = "Quickly (Red)";
if (vars.branch === "Descend quickly: let the Red pass") h.red = "Let it pass (two Greens)";
if (has("red", vars.red)) h.red = vars.red;
if (vars.branch === "Descend slowly: two Greens") h.descend = "Slowly (two Greens)";
if (vars.branch === "Valley Red") h.valley = "Face the Red";
if (vars.branch === "Passed the Red: meadow") h.valley = "Pass the Red (meadow)";
for (const k of ["meadow", "shadow", "shadowColour"]) if (seen[k]) h[k] = seen[k];
if (h.hour === "Tree" && h.descend && !h.shadow) h.shadow = "no";
return h;
}
return Object.assign(api, {
advisor, recommendOption, solverHistory, norm,
makeParams: (T, { alphas, game } = {}) => makeParams(T, { alphas, game: game || api.game }),
/** remember the game of a policy sample (sets ENCOUNTERS) without solving anything */
useGame(sample) { api.game = sample.model.game; api.ENCOUNTERS = api.game.by_colour; return api.game; },
ENCOUNTERS: null, game: null,
});
});