Files
ekcSchianoandClaude Fable 5.2 f8e4f575f4
CI / test (pull_request) Canceled after 0s
Screen tree, register rows in the master list, and bot runs coded from the picks that were played
- analysis/tree/build_tree.py -> data/public/tree.json, analysis/reports/TREE.md: every screen the bot has seen,
  every option, where each led (fixed or dice, with ranges), best known picks per colour chosen cautiously, where
  any picks end, and the untested options. solver.js screenPick(): least-tried and Thompson picks from the tree.
- The bot logs a pick it then overrode as a step: 37 runs were coded with choices they never made. Importer and
  graph.js now use the played steps only.
- runs_clean.csv: the Unofficial Dragon Register's 288 bonded dragons are in the master list as outcome-only
  rows, flagged (no analysis uses them).
- Cycle, refresh and the bot kit rebuild and carry the tree; tests check every generated report is current.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014jqCC2LZ4x1WHQ1V57nTsv
2026-11-16 15:50:12 +00:00

246 lines
12 KiB
JavaScript

/*
* graph.js: the route graph shared by every data source.
*
* Two levels:
* 1. Scene graph (bot data): nodes are exact game scenes (fingerprints), edges are (scene, option) -> next scene
* or a terminal (BURNED, BONDED:<colour>). Chance shows up as one option leading to several scenes,
* e.g. "head toward the centre" -> a Red OR a Brown first sighting.
* 2. Decision-variable graph (all sources): the coarse variables the community form asks about
* (company, direction, first sighting, ...). trajectoryVariables() maps a bot trajectory onto it with CROSSWALK
* (written from collection/specs/bot.yaml; the Python importer uses the same file), for the bot's advisor.
*
* Trajectories keep the full ordered history of each attempt, so history-dependent (non-Markov) models can be fitted
* later without changing the data format.
*
* UMD: window.ThreshGraph in the browser, module.exports in Node. No dependencies.
*/
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.ThreshGraph = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const norm = (t) => String(t || "").toLowerCase()
.replace(/[‘’‛`']/g, "'").replace(/[–—-]/g, " ")
.replace(/[^a-z0-9'\s]/g, " ").replace(/\s+/g, " ").trim();
const cap = (s) => (s ? s[0].toUpperCase() + s.slice(1).toLowerCase() : s);
/* ---------- Beta posterior and credible interval ---------- */
function logGamma(x) {
const c = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
let y = x, tmp = x + 5.5, ser = 1.000000000190015;
tmp -= (x + 0.5) * Math.log(tmp);
for (const v of c) ser += v / ++y;
return -tmp + Math.log(2.5066282746310005 * ser / x);
}
function betacf(a, b, x) {
const MAXIT = 300, EPS = 3e-14, FPMIN = 1e-300;
let qab = a + b, qap = a + 1, qam = a - 1, c = 1, d = 1 - qab * x / qap;
if (Math.abs(d) < FPMIN) d = FPMIN;
d = 1 / d; let h = d;
for (let m = 1; m <= MAXIT; m++) {
const m2 = 2 * m;
let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1 / d; h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1 + aa * d; if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1 + aa / c; if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1 / d; const del = d * c; h *= del;
if (Math.abs(del - 1) < EPS) break;
}
return h;
}
/** Regularised incomplete beta I_x(a, b). */
function ibeta(x, a, b) {
if (x <= 0) return 0;
if (x >= 1) return 1;
const bt = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x));
return x < (a + 1) / (a + b + 2) ? bt * betacf(a, b, x) / a : 1 - bt * betacf(b, a, 1 - x) / b;
}
function betaQuantile(p, a, b) {
let lo = 0, hi = 1;
for (let i = 0; i < 80; i++) {
const mid = (lo + hi) / 2;
if (ibeta(mid, a, b) < p) lo = mid; else hi = mid;
}
return (lo + hi) / 2;
}
/**
* Posterior for a proportion with k successes in n trials under a Beta(a0, b0) prior
* (default Jeffreys, a0 = b0 = 0.5). Returns the mean and the equal-tailed 95% credible interval.
*/
function betaPosterior(k, n, a0 = 0.5, b0 = 0.5) {
const a = a0 + k, b = b0 + n - k;
return { k, n, mean: a / (a + b), lo: betaQuantile(0.025, a, b), hi: betaQuantile(0.975, a, b) };
}
/* ---------- Crosswalk: bot option text -> community form variables ---------- */
// BEGIN CROSSWALK: written by `python -m collection build` from collection/specs/bot.yaml (edit that file)
const CROSSWALK = [
[/^enter the valley alone/, "company", "Alone"],
[/^enter the valley with one of your squadmates/, "company", "1 Squadmate"],
[/^enter the valley with two of your squadmates/, "company", "2 Squadmates"],
[/^leave your squadmates?$/, "left_squadmates", true],
[/^head east toward the roar/, "direction", "East"],
[/^head west toward the scent/, "direction", "West"],
[/^head toward the center of the forest/, "direction", "Center"],
[/^go east with your squad|^convince them to head east/, "direction", "East"],
[/^go west with your squad|^convince them to head west/, "direction", "West"],
[/^keep walking the cadets are just as dangerous/, "scream", "Ignore the scream"],
[/^run and hope/, "sighting_action", "Retreat / run"],
[/hold still|hold your ground/, "sighting_action", "Hold still"],
[/lower your eyes in respect|lower your eyes and turn to face it/, "sighting_action", "Respect / face it"],
[/meeting its gaze/, "sighting_action", "Meet its gaze"],
[/^hide behind a tree|^duck behind a boulder/, "sighting_action", "Hide"],
[/^approach with confidence|^approach from the left/, "sighting_action", "Approach"],
[/^investigate the scream/, "scream_investigate", true],
[/^help your squadmate/, "scream", "Investigate & help"],
[/^play it safe and leave them/, "scream", "Investigate & leave"],
[/^pause to assess the situation/, "combat_first", "Assess the situation"],
[/^charge the other cadet/, "combat_first", "Even the numbers (smaller cadet)"],
[/^unsheathe your weapon and charge between/, "combat_first", "Put yourself in the middle (bigger cadet)"],
[/^engage the smaller cadet/, "combat_second", "Engage the smaller cadet"],
[/^daggers or not/, "combat_second", "Daggers or not (protect squadmate)"],
[/^end the lives of the bullies/, "resolution", "Killed the bullies yourself"],
[/^allow your squadmate to exact/, "resolution", "Squadmate's revenge"],
[/^leave the bullies alive/, "resolution", "Left bullies to the dragons"],
[/tourniquet/, "resolution", "Tourniquet"],
[/leave (them|him|her) to die|^keep going clearly they've been found lacking/, "resolution", "Left injured cadet"],
[/take (their|his|her|the cadet's) weapons?/, "resolution", "Took their weapons"],
[/^walk toward the east/, "post_path", "East"],
[/^walk toward the west/, "post_path", "West"],
[/^walk farther into the forest/, "post_path", "Forest"],
[/^continue toward the center of the valley/, "hour", "Valley"],
[/^find the tallest tree/, "hour", "Tree"],
[/^there's no way this is your dragon/, "branch", "Passed the Red: meadow"],
[/^this is your dragon and it's time to start bonding/, "branch", "Valley Red"],
[/^descend quickly/, "branch", "Descend quickly: Red"],
[/^climb down slowly to pursue the green/, "branch", "Descend slowly: two Greens"],
[/^reds are too hot tempered/, "red", "Let it pass (two Greens)"],
[/^jump (now|in a few seconds)/, "red", "Jump onto the Red"]
];
// END CROSSWALK
/** Map one bot trajectory onto the form's decision variables. Unmapped choices are listed, not guessed. */
/**
* The steps that were actually played. The bot logs a pick it then overrode (its own rules against the atlas's
* advice) as a step whose `to` is not where the run went, followed by the pick it made on the same screen. Those
* superseded picks are dropped. A step without `to` (a run in progress) is kept unless the next step is on the
* same screen.
*/
function playedSteps(steps) {
return (steps || []).filter((s, i) => !(i + 1 < steps.length && steps[i + 1].scene != null && steps[i + 1].scene === s.scene && s.to !== steps[i + 1].scene));
}
function trajectoryVariables(traj) {
const vars = {}, unmapped = [];
for (const s of playedSteps(traj.steps)) {
const t = norm(s.optionText);
const hit = CROSSWALK.find(([re]) => re.test(t));
if (hit) { if (!(hit[1] in vars)) vars[hit[1]] = hit[2]; }
else unmapped.push(s.optionText);
// first sighting = the first tinted scene after the direction choice
if (vars.direction && !vars.first_sighting && s.tint) vars.first_sighting = cap(s.tint);
}
const o = traj.outcome || {};
vars.outcome = o.type === "BONDED" ? "Bonded" : o.type === "BURNED" ? "Incinerated" : "No outcome recorded";
vars.outcome_color = o.type === "BONDED" && o.colour ? cap(o.colour) : null;
return { vars, unmapped };
}
/** A coded community-form run (engine.codeRow output) in the same shape. */
function formRunVariables(run) {
const keep = ["company", "left_squadmates", "direction", "first_sighting", "sighting_action", "scream", "combat_first", "combat_second", "resolution", "post_path", "hour", "branch", "outcome", "outcome_color"];
const vars = {};
for (const k of keep) vars[k] = run[k] == null ? null : run[k];
return vars;
}
/* ---------- Decision-variable graph (all sources) ---------- */
const VAR_STAGES = ["company", "direction", "first_sighting", "scream", "resolution", "post_path", "hour", "branch"];
// "(no fork)" is a real state (that path has no fork), but it is not a choice node, so it is skipped too
const MISSING = new Set([null, undefined, "", "Unknown", "Unsure", "Unsure/unknown", "Multiple", "(no fork)", "(not recorded)", "(not asked)", "(not asked/blank)", "Unknown/lost count"]);
function endLabel(v) {
if (v.outcome === "Bonded") return v.outcome_color ? `Bonded ${v.outcome_color}` : "Bonded (colour unknown)";
if (v.outcome === "Incinerated" || v.outcome === "Died before the hour") return "Incinerated";
return null;
}
/**
* records: [{ source, vars }]. Returns nodes keyed "stage=value" and edges between consecutive KNOWN stages,
* each with total and per-source counts, plus P(next | this) with a Beta credible interval.
*/
function buildVariableGraph(records, stages = VAR_STAGES) {
const nodes = {}, edges = {};
const bump = (obj, key, src, init) => {
const x = obj[key] || (obj[key] = Object.assign({ n: 0, bySource: {} }, init));
x.n++; x.bySource[src] = (x.bySource[src] || 0) + 1;
return x;
};
for (const { source, vars } of records) {
const path = [];
for (const st of stages) if (!MISSING.has(vars[st])) path.push(`${st}=${vars[st]}`);
const end = endLabel(vars);
if (end) path.push(`end=${end}`);
path.forEach((id, i) => {
const [stage, value] = id.split("=");
bump(nodes, id, source, { stage, value });
if (i) bump(edges, `${path[i - 1]}>${id}`, source, { from: path[i - 1], to: id });
});
}
const out = {};
for (const e of Object.values(edges)) (out[e.from] = out[e.from] || []).push(e);
for (const [from, list] of Object.entries(out)) {
const tot = list.reduce((s, e) => s + e.n, 0);
for (const e of list) e.p = betaPosterior(e.n, tot);
nodes[from].out = tot;
}
return { stages: stages.concat("end"), nodes, edges: Object.values(edges) };
}
/* ---------- Scene graph (bot) ---------- */
/**
* scenes: catalogue { id: { stage, tint, label, options: [{ id, text }] } }; trajs: bot trajectories.
* For every scene option: how often it was taken, where it led, P(incinerated) and P(survived) with
* credible intervals. Options never taken are kept and marked untested.
*/
function buildSceneGraph(scenes, trajs) {
const g = {};
for (const [id, s] of Object.entries(scenes)) {
g[id] = { id, stage: s.stage, tint: s.tint, label: s.label, visits: 0, options: {} };
for (const o of s.options) g[id].options[o.id] = { id: o.id, text: o.text, n: 0, to: {}, bySource: {}, intentionalBurns: 0 };
}
for (const t of trajs) {
for (const s of playedSteps(t.steps)) {
const node = g[s.scene] || (g[s.scene] = { id: s.scene, stage: s.stage, tint: s.tint, label: s.stage, visits: 0, options: {} });
node.visits++;
const o = node.options[s.option] || (node.options[s.option] = { id: s.option, text: s.optionText, n: 0, to: {}, bySource: {}, intentionalBurns: 0 });
o.n++;
o.bySource[t.source] = (o.bySource[t.source] || 0) + 1;
const to = s.to || "UNKNOWN";
o.to[to] = (o.to[to] || 0) + 1;
if (to === "BURNED" && t.outcome && t.outcome.intentional) o.intentionalBurns++;
}
}
for (const node of Object.values(g)) {
for (const o of Object.values(node.options)) {
const burns = o.to.BURNED || 0;
const known = o.n - (o.to.UNKNOWN || 0);
o.untested = o.n === 0;
o.pBurn = known ? betaPosterior(burns, known) : null;
o.chance = Object.keys(o.to).filter((k) => k !== "BURNED" && k !== "UNKNOWN").length > 1;
}
}
return g;
}
return { betaPosterior, betaQuantile, ibeta, CROSSWALK, trajectoryVariables, playedSteps, formRunVariables, VAR_STAGES, buildVariableGraph, buildSceneGraph, norm };
});