Files
threshing-atlas/core/graph.js
T
432e04c2c7 Refactor: lay the repo out by section (core, collection, analysis, planner, site) (#8)
Moves only; no behaviour changes. Every file now lives under the part of the project it
belongs to, each section has a README, and docs/PRIVACY.md collects the rules all parts follow.

  core/        engine.js, graph.js, solver.js, python/clean.py
  collection/  sources/ (form, register, PDF check, daily update), bot/ (importer)
  analysis/    stats/ (Python statistics), network/ (build-graph.js), reports/ (POLICY.md)
  planner/     build-policy.js, policy-report.js
  site/        atlas/ (the page), build.js, qa/
  tests/       core/ (unit), parity/ (JS vs Python), fixtures/

Checked against the previous layout: tests pass; coded runs, test outputs, graph.json and
policy.json are byte-identical; the built site differs only in comments that name file paths.
The published file names Ken's bot downloads (solver.js, graph.js, data/policy.json) are unchanged.

Also removes the undefined/ folder of QA screenshots committed by mistake (the QA scripts now
default to a temp folder) and test.txt, and drops the unused npm workspaces.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 19:46:33 +00:00

226 lines
11 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, ...). Bot trajectories are mapped onto it with CROSSWALK, so bot and
* form runs can be counted side by side, per source.
*
* 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 ---------- */
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"],
[/^head east toward the roar/, "direction", "East"],
[/^head west toward the scent/, "direction", "West"],
[/^head toward the center of the forest/, "direction", "Center"],
[/^keep walking the cadets are just as dangerous/, "scream", "Ignore the scream"],
[/^run and hope/, "sighting_action", "Retreat / run"],
[/hold still/, "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/, "sighting_action", "Hide"],
[/^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"],
[/^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"],
[/^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"]
];
/** Map one bot trajectory onto the form's decision variables. Unmapped choices are listed, not guessed. */
function trajectoryVariables(traj) {
const vars = {}, unmapped = [];
for (const s of 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 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, formRunVariables, VAR_STAGES, buildVariableGraph, buildSceneGraph, norm };
});