Threshing Atlas: monorepo, route graph, bot importer, daily source checks

- apps/atlas: the web page (valley map, route flow, Dragon Register)
- packages/core: coding rules and statistics (engine.js) and the shared route
  graph (graph.js): scene graph, decision-variable graph, bot-to-form crosswalk,
  Beta credible intervals
- packages/ingest: DragonKind bot importer to anonymised trajectories (no prose,
  no account identifiers); data/bot holds Ken's sample
- research/python: independent reference implementation + update_sources.py
- tests: JS/Python parity checks and graph/importer unit tests
- CI, GitHub Pages deploy, daily check of the community sheets and route PDF
- Email addresses in free-text form answers are redacted; the raw spreadsheet
  is not committed
- MIT code licence, CC BY 4.0 data licence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ
This commit is contained in:
ekcSchiano
2026-11-01 21:54:54 +00:00
co-authored by Claude Opus 5.5
parent 0052d1a5fd
commit c3d067b88c
48 changed files with 8334 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r research/python/requirements.txt
- run: npm test
- name: graph.json is up to date
run: node scripts/build-graph.js && git diff --exit-code data/public/graph.json
- run: npm run build
+30
View File
@@ -0,0 +1,30 @@
name: Deploy Atlas to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: true
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm run build
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
path: dist
- id: deployment
uses: actions/deploy-pages@v4
+46
View File
@@ -0,0 +1,46 @@
name: Check sources for new data
on:
schedule:
- cron: "23 10 * * *" # daily
workflow_dispatch:
permissions:
contents: write
pull-requests: write
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r research/python/requirements.txt
- id: check
run: python research/python/update_sources.py --report "$RUNNER_TEMP/report.md"
- name: Rebuild graph and run tests
if: steps.check.outputs.changed == 'true'
run: |
node scripts/build-graph.js
npm test
- name: Open a pull request with the new data
if: steps.check.outputs.changed == 'true'
uses: peter-evans/create-pull-request@v6
with:
branch: data/source-update
delete-branch: true
commit-message: "data: update from community sources"
title: "New data from the community sources"
body-path: ${{ runner.temp }}/report.md
labels: data
- name: Report a broken source link
if: steps.check.outputs.failed != ''
env:
GH_TOKEN: ${{ github.token }}
run: |
title="Source check failed: ${{ steps.check.outputs.failed }}"
if ! gh issue list --state open --search "$title in:title" --json number --jq '.[0].number' | grep -q .; then
gh issue create --title "$title" --body-file "$RUNNER_TEMP/report.md"
fi
+14
View File
@@ -218,3 +218,17 @@ __marimo__/
# Streamlit
.streamlit/secrets.toml
# --- Threshing Atlas ---
node_modules/
dist/
tests/out/
__pycache__/
*.pyc
.env
.DS_Store
# Raw register export contains rider names: keep it local, publish only data/public/register.json
data/raw/register/
# Third-party guide PDF: link to it, do not redistribute
*.pdf
data/raw/form/*.xlsx
+21
View File
@@ -0,0 +1,21 @@
# Data licence
The data this project produces (coded runs in `data/derived/`, the route graph, `policy.json`,
`experiments.json`, and bot exports in `data/bot/`) are licensed under
**Creative Commons Attribution 4.0 International (CC BY 4.0)**:
https://creativecommons.org/licenses/by/4.0/
Credit: "Threshing Atlas contributors", with a link to this repository.
## Third-party sources
Some inputs belong to others. They keep their own terms, and CC BY 4.0 does not apply to them:
- `data/raw/form/` and `data/public/form_responses.json`: responses to the community
"Threshing Routes" Google Form compiled by u/ClumsyBadger. Included unmodified so results can be
reproduced. Credit the form and its respondents.
- `data/public/register.json`: derived from the community "Unofficial Dragon Register". Rider names
and photos are removed. The raw export is not committed.
- The community route PDF is not redistributed. See `data/SOURCES.md` for where to find it.
Dragonkind and Fourth Wing belong to their respective owners. This is an unofficial fan project.
+94
View File
@@ -0,0 +1,94 @@
# Threshing Atlas
Route probabilities and path finding for the Dragonkind threshing: which choices lead to which
dragon, how often, how sure we can be, and (in progress) the best route to each colour.
Unofficial fan project. Not affiliated with Dragonkind or the Fourth Wing publishers.
## Layout
```
apps/atlas/ the web page: valley map, route flow, charts, Dragon Register, Reddit post generator
packages/core/ @threshing-atlas/core, no dependencies, runs in Node and the browser:
src/engine.js coding rules and statistics for the community form
src/graph.js the shared route graph: scene graph, decision-variable graph,
bot-to-form crosswalk, Beta credible intervals
packages/ingest/ @threshing-atlas/ingest: DragonKind bot importer (fingerprints and choice text only)
research/python/ independent Python implementation of the coding rules and statistics
tests/ JS/Python parity tests (they fail loudly if the two disagree)
scripts/build-site.js assembles the static site into dist/
scripts/build-graph.js combines every source into data/public/graph.json
data/raw/ source exports (form .xlsx; the register export stays local, git-ignored)
data/public/ what the page loads: form_responses.json, register.json, graph.json
data/sources.json where the community spreadsheets and the PDF are downloaded from
data/derived/ coded runs (runs_clean.csv)
data/bot/ anonymised DragonKind bot runs, added by pull request
docs/ ROADMAP.md, BOT_DATA_PROTOCOL.md, REDDIT_POST.md
```
## Run it locally
Requirements: Node 18+, Python 3.9+ (`pip install -r research/python/requirements.txt`).
```
npm run dev # builds dist/ and serves it at http://localhost:8000
npm test # JS engine + Python reference + parity checks
```
## New data from the community sources
A GitHub Action (`.github/workflows/update-sources.yml`) runs every day. It downloads the Threshing Routes
responses, the Dragon Register and the route PDF, and if anything changed it rebuilds the data, runs the
tests and opens a pull request that says what changed: new responses, new or renamed questions, and for
the PDF the pages and lines that are new. The PDF itself is never committed, only a fingerprint
(`data/derived/pdf_fingerprint.json`). If a link stops working, the Action opens an issue. You can also
run it by hand from the Actions tab, or locally with `npm run check-sources`.
## Bot data
The private DragonKind bot's files are converted locally, and only the anonymised result is committed:
```
DK_ACCOUNT_SALT=... npm run import-bot -- --bot /path/to/DragonKind --tag 2026-11-01
npm run graph
```
This writes `data/bot/scenes.json` and `data/bot/trajectories-<tag>.jsonl`: scene fingerprints, short labels,
choice text and outcomes, with no game prose and no account names. The importer refuses to write anything that
looks like prose. See `docs/BOT_DATA_PROTOCOL.md` for what the bot should log.
## Updating with new form data by hand
In the browser: open the page and use **Load a newer export** with the responses spreadsheet
(Google Sheets → File → Download → Microsoft Excel). Everything recomputes. Questions are matched by
wording; a renamed question is listed as "not found", and then `COLUMN_KEYS` in
`packages/core/src/engine.js` and `research/python/clean.py` need updating.
To update the bundled snapshot, put the new export in `data/raw/form/`, then:
```
cd research/python
python export_raw.py ../../data/raw/form/NEW_EXPORT.xlsx ../../data/public/form_responses.json
python clean.py ../../data/raw/form/NEW_EXPORT.xlsx
cd ../..
npm test
```
## Changing a coding rule
Every rule lives in `codeRow()` in `packages/core/src/engine.js` and `code_row()` in
`research/python/clean.py`. Change both and run `npm test`.
## Statistics in one paragraph
Rates use 95% Wilson score intervals. Each answer is compared with the other answers to the same
question by odds ratio (Woolf CI, +0.5 Haldane correction for zero cells) and Fisher's exact test, with
Benjamini–Hochberg q-values. Because Blue- and Black-chasers report rare sightings far more often than
players who log every run, key outcomes are also modelled with ridge-penalised logistic regression
(λ = 1) that includes data source and chase goal, and route rankings use a Mantel–Haenszel odds ratio
stratified by the same factors. The page's Methods section has the details.
## Licences
Code: MIT (`LICENSE`). Data produced by this project: CC BY 4.0 (`DATA_LICENSE.md`), which also lists
third-party sources that keep their own terms.
+701
View File
@@ -0,0 +1,701 @@
/* app.js — renders the Threshing Route Atlas from engine.js results. All numbers come from ThreshEngine. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const NS = "http://www.w3.org/2000/svg";
const state = {
raw: null, bundled: null, allRuns: [], runs: [], res: null, missing: [],
filters: { source: "all", goal: "all", excludeFlagged: false },
target: "bond_Blue", widthMode: "traffic", minN: 10, conds: {},
fxOutcome: "blue_meadow", fxFactor: "resolution", rtTarget: "see_Blue", rtMin: 10,
};
// ------------------------------------------------------------ formatting
const pct = (p, d = 1) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(p > 0 && p < 0.001 ? 2 : d) + "%");
const ci = (w, d = 1) => (w && w.n ? `${pct(w.lo, d)}–${pct(w.hi, d)}` : "–");
const fmtOR = (x) => (x === null || x === undefined || !isFinite(x) ? "–" : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2));
const fmtP = (p) => (p === null || p === undefined ? "–" : p < 0.0001 ? "<0.0001" : p < 0.001 ? p.toExponential(1) : p.toFixed(p < 0.01 ? 3 : 2));
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const kn = (w) => (w ? `${w.k}/${w.n}` : "–");
const rateTxt = (w, d = 1) => (w && w.n ? `${pct(w.p, d)} (${kn(w)}; 95% CI ${ci(w, d)})` : "no data");
function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
function rgb(c) {
c = c.trim();
if (c.startsWith("#")) {
const h = c.length === 4 ? c.slice(1).split("").map((x) => x + x).join("") : c.slice(1);
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
}
const m = c.match(/\d+(\.\d+)?/g);
return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
function mix(a, b, t) {
const A = rgb(a), B = rgb(b);
return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`;
}
const DRAGON_VAR = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const dragonColor = (c) => cssVar(DRAGON_VAR[c] || "--dr-any");
const targetColor = (t) => dragonColor(E.TARGETS[t].color);
function svgEl(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function toast(msg) {
const t = document.createElement("div");
t.className = "toast"; t.textContent = msg; document.body.appendChild(t);
setTimeout(() => t.remove(), 2200);
}
async function copyText(text, label) {
try { await navigator.clipboard.writeText(text); toast(`Copied ${label}`); }
catch (e) {
const ta = document.createElement("textarea");
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select();
let ok = false; try { ok = document.execCommand("copy"); } catch (_) { /* ignore */ }
ta.remove(); toast(ok ? `Copied ${label}` : "Copy was blocked here. Select the text manually instead.");
}
}
// ------------------------------------------------------------ tooltip
const tip = $("#tip");
function showTip(evt, html) {
tip.innerHTML = html; tip.hidden = false;
const x = evt.clientX ?? (evt.touches && evt.touches[0].clientX) ?? 0, y = evt.clientY ?? 0;
const r = tip.getBoundingClientRect();
tip.style.left = Math.min(window.innerWidth - r.width - 8, x + 14) + "px";
tip.style.top = Math.min(window.innerHeight - r.height - 8, y + 14) + "px";
}
const hideTip = () => (tip.hidden = true);
// ------------------------------------------------------------ data loading
async function loadBundled() {
const resp = await fetch("data/form_responses.json");
const raw = await resp.json();
state.bundled = raw;
useRaw(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`);
}
function useRaw(raw, label) {
const { runs, missing } = E.codeRows(raw.rows, raw.headers);
state.raw = raw; state.allRuns = runs; state.missing = missing; state.dataLabel = label;
state.conds = {};
recompute();
}
$("#upload").addEventListener("change", async (e) => {
const f = e.target.files[0];
if (!f) return;
try {
const buf = await f.arrayBuffer();
const wb = XLSX.read(buf, { type: "array", cellDates: true });
const name = wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0];
const ws = wb.Sheets[name];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
useRaw({ rows, headers, source_file: f.name, exported: new Date().toISOString().slice(0, 10) }, `uploaded file ${f.name} (sheet "${name}")`);
$("#btn-reset-data").hidden = false;
toast(`Loaded ${rows.length} rows from ${f.name}`);
} catch (err) {
toast("That file could not be read. Export the responses sheet as .xlsx or .csv and try again.");
console.error(err);
}
e.target.value = "";
});
$("#btn-reset-data").addEventListener("click", () => { useRaw(state.bundled, `bundled snapshot (${state.bundled.source_file}, exported ${state.bundled.exported})`); $("#btn-reset-data").hidden = true; });
function recompute() {
state.runs = E.applyFilters(state.allRuns, state.filters);
state.res = E.analyse(state.allRuns, state.filters);
renderAll();
}
// ------------------------------------------------------------ header
function renderStatus() {
const m = state.res.meta;
const src = Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v.toLocaleString()}`).join(" · ");
const filt = [];
if (state.filters.source !== "all") filt.push(state.filters.source === "form" ? "form submissions only" : "bulk logs only");
if (state.filters.goal !== "all") filt.push(state.filters.goal === "exclude_rare" ? "not chasing Blue/Black" : "chasing Blue/Black");
if (state.filters.excludeFlagged) filt.push("flagged rows dropped");
$("#data-status").innerHTML = `
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.toLocaleString()}` : ""}</span>
<span>${esc(src)}</span>
<span>Form dates ${m.date_min || "?"} → ${m.date_max || "?"}</span>
<span class="pill">${esc(state.dataLabel)}</span>
${filt.length ? `<span class="pill warn">Filtered: ${esc(filt.join(", "))}</span>` : ""}
${state.missing.length ? `<span class="pill warn">Questions not found in this file: ${esc(state.missing.join(", "))}</span>` : ""}`;
}
// ------------------------------------------------------------ findings
function stratumRate(chance, keyPart) {
const e = Object.entries(chance.by_stratum).find(([k]) => k.startsWith(keyPart));
return e ? e[1] : null;
}
const ROUTE_FACTORS = ["direction", "first_sighting", "resolution", "company"];
const NOT_A_CHOICE = /^(Unsure|Unknown|Multiple|\(not recorded\)|Unknown\/lost count|Unsure\/unknown)/;
function buildFindings() {
const r = state.res, out = [];
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), otherB = stratumRate(cb, "Form: other");
const encBlue = r.encounters.find((e) => e.context === "Blue (meadow)");
const encBlack = r.encounters.find((e) => e.context === "Black (shadow)");
if (cb.overall.n) {
const biasShown = chaseB && bulkB && chaseB.n >= 20 && bulkB.n >= 20 && chaseB.lo > bulkB.hi;
let t;
if (biasShown) {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits, but that figure is inflated.</b> Players chasing a Blue report it in ${pct(chaseB.p)} of their visits. Bulk logs, which record every run, show ${rateTxt(bulkB)}. The game cannot see what you are chasing, so that gap comes from which runs get reported.</p>`;
t += `<p>A realistic expectation is nearer the bulk-log rate, about one meadow visit in ${Math.round(1 / Math.max(bulkB.p, 0.001))}, than the headline figure.${otherB ? ` Form players who were not chasing a Blue report ${pct(otherB.p)}, which still carries some selective reporting.` : ""}</p>`;
} else {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits in the current selection.</b> Compare the data-source filter settings to see how much this depends on who logged the runs.</p>`;
}
out.push(["bias", "Reporting bias", t]);
}
const mb = r.models.blue_meadow;
if (mb) {
const sig = mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level));
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q !== undefined && x.mh_q < 0.05);
let t = sig.length
? `<p><b>After adjusting for reporting bias, ${sig.length === 1 ? "one recorded choice was" : sig.length + " recorded choices were"} linked to the Blue appearing:</b> ${sig.map((s) => `${esc(s.term)} (OR ${fmtOR(s.or)}, 95% CI ${fmtOR(s.lo)}–${fmtOR(s.hi)}, p = ${fmtP(s.p)})`).join("; ")}.</p>`
: `<p><b>No recorded route choice changed the chance of the Blue appearing once reporting bias is held fixed.</b> Direction, first sighting, how you handled the cadet and who you entered with all have adjusted odds ratios whose 95% intervals include 1 (n = ${mb.n} meadow visits).</p>`;
t += `<p>Of ${rk.n_routes_tested} full routes with at least ${state.rtMin} meadow visits, ${adjSig.length} beat the others after adjustment and correction for multiple testing. The "precise pathways" shared on Reddit may still matter through choices the form does not record, such as how you react to the first dragon.</p>`;
out.push(["blue", "Blue", t]);
}
if (encBlue && encBlue.overall.n) {
out.push(["blue", "Blue", `<p><b>Reaching the Blue is not enough. Only ${rateTxt(encBlue.overall)} of Blue attempts ended in a bond</b> (${pct(encBlue.intent_matched.p)} when the player wanted a Blue). The community PDF's step-by-step survival rates multiply out to about 25% for the standard answers. Expect several Blue encounters per bond, and do not treat one death as proof that an answer is wrong.</p>`]);
}
if (cs.overall.n) {
const bulkS = stratumRate(cs, "Bulk"), formS = Object.entries(cs.by_stratum).filter(([k]) => k.startsWith("Form"));
const fk = formS.reduce((a, [, w]) => a + w.k, 0), fn = formS.reduce((a, [, w]) => a + w.n, 0);
const fw = E.wilson(fk, fn);
let t = `<p><b>The tree shadow showed up in ${rateTxt(cs.overall)} of logged tree climbs.</b>${fn ? ` Form submissions: ${rateTxt(fw)}.` : ""}`;
if (bulkS && bulkS.n >= 30 && fn >= 30 && fw.lo > bulkS.hi) t += ` Bulk logs: ${rateTxt(bulkS)}. Those two cannot both be the true rate for the same game. The form figure is the one exposed to selective reporting, so the true rate is probably nearer the bulk logs, whose 95% upper bound is ${pct(bulkS.hi)} per climb.`;
t += `</p>`;
if (encBlack && encBlack.overall.n) t += `<p>Once the Black appears it is the easiest dragon to bond: ${rateTxt(encBlack.overall)}.</p>`;
out.push(["black", "Black", t]);
}
// leads: unadjusted factor rows with q < 0.05 on route-type factors, for the shadow
const leadF = ["post_path", "attempt_group", "direction", "first_sighting", "resolution", "company", "combat_first"];
const sh = r.factors.shadow.rows.filter((x) => leadF.includes(x.factor) && x.q !== undefined && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
if (sh.length) {
const ms = r.models.shadow;
let t = `<p><b>Shadow leads to test, not established:</b> ${sh.map((x) => `<i>${esc(labelFactor(x.factor))}: ${esc(x.level)}</i> had the shadow in ${rateTxt(x)} vs the rest (OR ${fmtOR(x.or)}, q = ${fmtP(x.q)})`).join("; ")}.</p>`;
const att = ms && ms.terms.find((tm) => tm.factor === "attempt" && tm.level === "First attempt");
if (att) t += `<p>The first-attempt pattern survives adjustment for source, goal, direction and date (OR ${fmtOR(att.or)}, 95% CI ${fmtOR(att.lo)}–${fmtOR(att.hi)}). That matches a theory on Reddit that a fresh account rolls the shadow more often, but players who strike lucky on a first run may also be more likely to submit the form.</p>`;
t += `<p>The cheapest test is a bulk log that records every tree climb, including the dull ones, with these choices noted.</p>`;
out.push(["lead", "Lead", t]);
}
// common dragons
const common = r.encounters.filter((e) => ["Red (valley)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Red (tree, descend quickly)"].includes(e.context) && e.intent_matched.n >= 10);
if (common.length) {
out.push(["", "Common", `<p><b>For the common colours, intent matters more than route.</b> Among players who wanted that colour: ${common.map((e) => `${esc(e.context)} ${pct(e.intent_matched.p, 0)} (${kn(e.intent_matched)})`).join(", ")}. The tree Red is the hardest bond in the game.</p>`]);
}
return out;
}
function renderFindings() {
$("#findings-list").innerHTML = buildFindings().map(([cls, tag, html], i) =>
`<div class="finding ${cls}"><span class="mark">${i + 1}</span><div><span class="tag">${esc(tag)}</span>${html}</div></div>`).join("");
}
const FACTOR_LABEL = { company: "Company", direction: "Direction", first_sighting: "First sighting", scream: "Scream choice", resolution: "Cadet encounter",
combat_first: "First combat move", post_path: "Fork in the road", hour: "After an hour", wing: "Wing", squad: "Squad",
attempt_group: "Attempt", source: "Data source", goal: "Chasing", attempt: "Attempt", period: "Date", };
const labelFactor = (f) => FACTOR_LABEL[f] || f;
// ------------------------------------------------------------ route map
const RARE_T = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow"];
const OTHER_T = ["bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
function renderTargets() {
const chip = (t, featured) => {
const c = E.TARGETS[t].color ? DRAGON_VAR[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${featured ? " featured" : ""}" data-t="${t}" aria-pressed="${state.target === t}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
};
$("#targets-rare").innerHTML = RARE_T.map((t) => chip(t, t.startsWith("bond"))).join("");
$("#targets-other").innerHTML = OTHER_T.map((t) => chip(t, false)).join("");
$$(".tchip").forEach((b) => b.addEventListener("click", () => { state.target = b.dataset.t; $("#best-routes").innerHTML = ""; renderTargets(); renderMap(); }));
}
const ORDER = {
company: ["Alone", "1 Squadmate", "2 Squadmates", "Unknown"],
direction: ["East", "Center", "West", "Multiple", "Unknown"],
first_sighting: ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"],
post_path: ["Forest", "West", "East", "(no fork)", "Unknown"],
hour: ["Climb the tree", "Valley centre"],
encounter: ["Tree: Red below", "Tree: two Greens", "Tree: shadow → Blue/Black", "Valley: bond the Red", "Meadow: Orange", "Meadow: Brown", "Meadow: Orange/Brown", "Meadow: Blue", "Meadow (no attempt recorded)"],
end: ["Bonded Red", "Bonded Green", "Bonded Orange", "Bonded Brown", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour"],
};
const SHORT = {
"Help → Killed the bullies yourself": "Help · killed bullies", "Help → Squadmate's revenge": "Help · squadmate's revenge",
"Help → Left bullies to the dragons": "Help · left to dragons", "Help → DIED in combat": "Help · died in combat", "Help → Unknown": "Help · unknown",
"Ignore the scream → Tourniquet": "Ignore · tourniquet", "Ignore the scream → Left injured cadet": "Ignore · left cadet",
"Ignore the scream → Took their weapons": "Ignore · took weapons", "Investigate & leave → Left them to it": "Investigate · walked away",
"Tree: shadow → Blue/Black": "Tree: shadow (Blue→Black)", "Meadow (no attempt recorded)": "Meadow: none recorded", "Unknown → Unknown": "Unknown",
};
const short = (v) => SHORT[v] || v;
const condSets = () => Object.fromEntries(Object.entries(state.conds).map(([k, v]) => [k, new Set(v)]));
function renderMap() {
const svg = $("#map");
svg.innerHTML = "";
const runs = state.runs;
const base = E.buildGraph(runs, state.target, {});
const sel = E.buildGraph(runs, state.target, condSets());
const hasSel = Object.values(state.conds).some((v) => v.length);
const selNode = new Map(sel.nodes.map((n) => [n.id, n]));
const minN = state.minN;
const tcol = targetColor(state.target), low = cssVar("--link-low"), surface = cssVar("--raised");
const shell = $(".map-scroll");
const W = Math.max(1440, shell.clientWidth || 1440), H = 660, top = 40, bottom = 16, left = 10, right = 168, nodeW = 12;
svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const S = E.STAGES.length;
const colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
const cols = E.STAGES.map((s, i) => {
const ns = base.nodes.filter((n) => n.stage === i);
const ord = ORDER[s.key];
ns.sort((a, b) => {
const ia = ord ? ord.indexOf(a.value) : -1, ib = ord ? ord.indexOf(b.value) : -1;
if (ia !== -1 || ib !== -1) return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
return b.n - a.n;
});
return ns;
});
const pad = 7;
const maxTotal = Math.max(...cols.map((c) => c.reduce((s, n) => s + n.n, 0)));
const maxCount = Math.max(...cols.map((c) => c.length));
const scale = (H - top - bottom - pad * (maxCount - 1)) / maxTotal;
const pos = new Map();
cols.forEach((ns, i) => {
const hTot = ns.reduce((s, n) => s + Math.max(2, n.n * scale), 0) + pad * (ns.length - 1);
let y = top + (H - top - bottom - hTot) / 2;
ns.forEach((n) => { const h = Math.max(2, n.n * scale); pos.set(n.id, { x: colX(i), y, h, n }); y += h + pad; });
});
// colour scale: anchored on the route steps, not on the outcome column (where the target node is 100% by definition)
const lastStage = S - 1;
const stageOf = (id) => +id.split("|")[0];
const eligible = sel.links.filter((l) => l.n >= minN && stageOf(l.target) < lastStage);
const pmax = Math.max(0.005, ...eligible.map((l) => l.p), ...sel.nodes.filter((n) => n.n >= minN && n.stage < lastStage).map((n) => n.p));
const colorFor = (o) => (o.n < minN ? low : mix(low, tcol, Math.pow(Math.min(1, o.p / pmax), 0.75)));
// stage headers
E.STAGES.forEach((s, i) => {
const chance = s.key === "first_sighting" || s.key === "encounter";
const t = svgEl("text", { x: colX(i), y: 18, class: "stage-label" + (chance ? " stage-chance" : "") }, svg);
t.textContent = s.label;
if (chance) { const r = svgEl("text", { x: colX(i), y: 31, class: "stage-label stage-chance" }, svg); r.textContent = "game roll"; }
});
// links
const gLinks = svgEl("g", {}, svg);
const outOff = new Map(), inOff = new Map();
const linksSorted = sel.links.slice().sort((a, b) => pos.get(a.source).y - pos.get(b.source).y || pos.get(a.target).y - pos.get(b.target).y);
// order out-links by target y and in-links by source y for clean stacking
const byOut = {}, byIn = {};
linksSorted.forEach((l) => { (byOut[l.source] = byOut[l.source] || []).push(l); (byIn[l.target] = byIn[l.target] || []).push(l); });
Object.values(byOut).forEach((ls) => ls.sort((a, b) => pos.get(a.target).y - pos.get(b.target).y));
Object.values(byIn).forEach((ls) => ls.sort((a, b) => pos.get(a.source).y - pos.get(b.source).y));
const offOut = {}, offIn = {};
Object.entries(byOut).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offOut[l.id] = o; o += l.n * scale; }); });
Object.entries(byIn).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offIn[l.id] = o; o += l.n * scale; }); });
const drawOrder = state.widthMode === "prob" ? sel.links.slice().sort((a, b) => (a.n >= minN) - (b.n >= minN) || a.p - b.p) : linksSorted;
drawOrder.forEach((l) => {
const s = pos.get(l.source), t = pos.get(l.target);
if (!s || !t) return;
const x0 = s.x + nodeW, x1 = t.x, xm = (x0 + x1) / 2;
let el;
if (state.widthMode === "traffic") {
const w = Math.max(0.6, l.n * scale);
const y0 = s.y + offOut[l.id], y1 = t.y + offIn[l.id];
el = svgEl("path", {
d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}L${x1},${y1 + w}C${xm},${y1 + w} ${xm},${y0 + w} ${x0},${y0 + w}Z`,
fill: colorFor(l), "fill-opacity": l.n >= minN ? 0.62 : 0.3, class: "link",
}, gLinks);
} else {
const y0 = s.y + s.h / 2, y1 = t.y + t.h / 2;
const w = l.n >= minN ? 1.2 + 18 * (l.p / pmax) : 1;
el = svgEl("path", { d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}`, fill: "none", stroke: colorFor(l), "stroke-width": w, "stroke-opacity": l.n >= minN ? 0.8 : 0.3, "stroke-linecap": "round", class: "link" }, gLinks);
}
const sv = pos.get(l.source).n.value, tv = pos.get(l.target).n.value;
el.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${esc(sv)} → ${esc(tv)}</div>${l.n} runs${hasSel ? " (in your selection)" : ""}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(l.p)}</b> (${kn(l)})<br>95% CI ${ci(l)}${l.n < minN ? "<br><i>Too few runs to read</i>" : ""}`));
el.addEventListener("mouseleave", hideTip);
});
// nodes
const gNodes = svgEl("g", {}, svg);
cols.forEach((ns, i) => {
let lastLabelBottom = -1e9;
ns.forEach((bn) => {
const p = pos.get(bn.id), sn = selNode.get(bn.id);
const isSel = (state.conds[E.STAGES[i].key] || []).includes(bn.value);
const g = svgEl("g", { class: "node" + (isSel ? " sel" : "") + (hasSel && !sn ? " dim" : ""), tabindex: 0, role: "button", "aria-label": `${E.STAGES[i].label}: ${bn.value}, ${bn.n} runs` }, gNodes);
const shown = sn || { n: 0, k: 0, p: null };
svgEl("rect", { x: p.x, y: p.y, width: nodeW, height: p.h, rx: 2, fill: sn ? colorFor(sn) : low }, g);
const lx = p.x + nodeW + 5, ly = p.y + p.h / 2 + 4;
if (ly - 11 > lastLabelBottom || isSel) {
const t = svgEl("text", { x: lx, y: ly, "paint-order": "stroke", stroke: surface, "stroke-width": 3, "stroke-linejoin": "round" }, g);
const lab = short(bn.value), maxC = i === S - 1 ? 30 : Math.floor((colX(1) - colX(0) - nodeW - 36) / 5.8);
t.textContent = lab.length > maxC ? lab.slice(0, maxC - 1) + "…" : lab;
const t2 = svgEl("tspan", { fill: cssVar("--muted"), dx: 4 }, t);
t2.textContent = sn && sn.n >= minN ? pct(sn.p, 0) : sn ? `n=${sn.n}` : "";
lastLabelBottom = ly;
}
const html = () => `<div class="t">${esc(E.STAGES[i].label)}: ${esc(bn.value)}</div>${hasSel ? `${shown.n} of ${bn.n} runs in your selection` : `${bn.n} runs`}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(shown.p)}</b> (${shown.k}/${shown.n})<br>95% CI ${ci(sn)}<br><span class="muted">Click to ${isSel ? "remove from" : "add to"} the selection</span>`;
g.addEventListener("mousemove", (e) => showTip(e, html()));
g.addEventListener("mouseleave", hideTip);
const toggle = () => {
const k = E.STAGES[i].key, cur = new Set(state.conds[k] || []);
cur.has(bn.value) ? cur.delete(bn.value) : cur.add(bn.value);
state.conds[k] = [...cur];
if (!state.conds[k].length) delete state.conds[k];
hideTip(); renderMap();
};
g.addEventListener("click", toggle);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggle(); } });
});
});
renderCondChips(); renderSelSummary(sel); renderLegend(pmax, tcol, low);
}
function renderCondChips() {
const entries = Object.entries(state.conds).filter(([, v]) => v.length);
$("#cond-chips").innerHTML = entries.length
? entries.map(([k, vals]) => vals.map((v) => `<span class="cchip">${esc(E.STAGES.find((s) => s.key === k).label)}: ${esc(v)}<button type="button" aria-label="Remove ${esc(v)}" data-k="${esc(k)}" data-v="${esc(v)}">×</button></span>`).join("")).join("")
: `<span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span>`;
$$("#cond-chips button").forEach((b) => b.addEventListener("click", () => {
state.conds[b.dataset.k] = (state.conds[b.dataset.k] || []).filter((v) => v !== b.dataset.v);
if (!state.conds[b.dataset.k].length) delete state.conds[b.dataset.k];
renderMap();
}));
}
function renderSelSummary(sel) {
const T = E.TARGETS[state.target];
const cs = condSets();
const inSel = (r) => Object.entries(cs).every(([k, set]) => !set.size || set.has(E.stageValue(r, k)));
const pool = state.runs.filter(T.pool);
const A = pool.filter(inSel), B = pool.filter((r) => !inSel(r));
const wa = E.wilson(A.filter(T.fn).length, A.length), wb = E.wilson(B.filter(T.fn).length, B.length);
const hasSel = Object.keys(state.conds).length > 0;
let cmp = "";
if (hasSel && A.length && B.length) {
const o = E.oddsRatio(wa.k, wa.n - wa.k, wb.k, wb.n - wb.k);
cmp = `<div>Everyone else: ${pct(wb.p)} (${kn(wb)}). Odds ratio ${fmtOR(o.or)} (95% CI ${fmtOR(o.or_lo)}–${fmtOR(o.or_hi)}), Fisher p = ${fmtP(o.fisher_p)}. This is unadjusted: if your selection mixes in a lot of Blue-chasers, expect it to look better than it is.</div>`;
}
$("#sel-summary").innerHTML = `
<span class="eyebrow">${hasSel ? "Your selection" : "All runs"} · ${esc(T.label)}</span>
<div><span class="big">${pct(wa.p)}</span> <span class="muted">${kn(wa)} runs that could reach it · 95% CI ${ci(wa)}</span></div>
${cmp}`;
}
function renderLegend(pmax, tcol, low) {
$("#legend").innerHTML = `
<span>${state.widthMode === "traffic" ? "Band width = number of runs" : "Line width = chance of the outcome"}</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${low}, ${tcol})"></span> ${pct(pmax, 0)}</span>
<span>Grey = fewer than ${state.minN} runs</span>
<span><span style="color:var(--accent)">Gold headings</span> = steps the game rolls, not you</span>`;
}
function renderBestRoutes() {
const rk = E.rankRoutes(state.runs, state.target, state.minN);
const rows = rk.rows.slice(0, 8);
const sigN = rk.rows.filter((r) => r.mh_q !== undefined && r.mh_q < 0.05 && r.mh_or > 1).length;
$("#best-routes").innerHTML = `<div class="panel">
<h3>Top routes for "${esc(E.TARGETS[state.target].label)}" <span class="small muted">routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval</span></h3>
<p class="small">${rows.length ? `Overall rate in the comparison group: ${rateTxt(rk.overall)}. <b>${sigN} of ${rk.n_routes_tested} routes are better than the rest after adjusting for reporting bias and multiple testing.</b> ${sigN === 0 ? "Treat the ordering below as noise unless a newer export changes this." : ""}` : "No route has enough runs at this threshold. Lower the minimum."}</p>
${rows.length ? `<div class="tbl-wrap"><table><thead><tr><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">Adj. OR</th><th class="num">Adj. q</th><th></th></tr></thead><tbody>
${rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}"><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td><td><button type="button" data-i="${i}">Follow</button></td></tr>`).join("")}
</tbody></table></div>` : ""}</div>`;
$$("#best-routes button[data-i]").forEach((b) => b.addEventListener("click", () => {
const r = rows[+b.dataset.i];
state.conds = {};
E.STAGES.slice(0, 6).forEach((s, i) => { if (r.values[i]) state.conds[s.key] = [r.values[i]]; });
renderMap();
$("#map-sec").scrollIntoView({ behavior: "smooth" });
}));
}
// ------------------------------------------------------------ small charts
// Horizontal rate bars with 95% CI whiskers.
function ciBars(el, rows, opts = {}) {
const W = 640, rowH = opts.rowH || 26, lw = opts.labelW || 190, top = 8, bottom = 26;
const H = top + bottom + rows.length * rowH;
const xmax = opts.max || Math.min(1, Math.max(0.05, ...rows.map((r) => r.hi || 0)) * 1.08);
const x = (v) => lw + (v / xmax) * (W - lw - 120);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ticks = niceTicks(xmax);
const ga = svgEl("g", { class: "axis" }, svg);
ticks.forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 8, "text-anchor": "middle" }, ga); tx.textContent = pct(t, 0);
});
rows.forEach((r, i) => {
const y = top + i * rowH + rowH / 2;
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg); lab.textContent = r.label;
if (r.indent) lab.setAttribute("fill", cssVar("--muted"));
if (!r.n) { const t = svgEl("text", { x: lw, y: y + 4, fill: cssVar("--faint") }, svg); t.textContent = "no runs"; return; }
const col = r.color || cssVar("--muted");
svgEl("rect", { x: lw, y: y - 7, width: Math.max(1, x(r.p) - lw), height: 14, fill: col, "fill-opacity": 0.28, rx: 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.lo), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.hi), x2: x(r.hi), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("circle", { cx: x(r.p), cy: y, r: 4, fill: col }, svg);
const v = svgEl("text", { x: x(r.hi) + 6, y: y + 4, "font-family": "var(--font-data)" }, svg);
v.textContent = `${pct(r.p)} · ${r.k}/${r.n}`;
});
el.innerHTML = ""; el.appendChild(svg);
}
function niceTicks(max) {
const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.25];
const step = steps.find((s) => max / s <= 6) || 0.25;
const out = []; for (let v = 0; v <= max + 1e-9; v += step) out.push(+v.toFixed(4)); return out;
}
// Forest plot of odds ratios on a log axis.
function forest(el, terms, opts = {}) {
const W = 640, rowH = 22, lw = opts.labelW || 290, top = 8, bottom = 28;
const H = top + bottom + Math.max(1, terms.length) * rowH;
const lo = 0.05, hi = 20;
const x = (v) => lw + ((Math.log(Math.min(hi, Math.max(lo, v))) - Math.log(lo)) / (Math.log(hi) - Math.log(lo))) * (W - lw - 60);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ga = svgEl("g", { class: "axis" }, svg);
[0.1, 0.25, 0.5, 1, 2, 4, 10].forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4, "stroke-dasharray": t === 1 ? "" : "2 3", "stroke-width": t === 1 ? 1.5 : 1 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 10, "text-anchor": "middle" }, ga); tx.textContent = t;
});
terms.forEach((t, i) => {
const y = top + i * rowH + rowH / 2;
const sig = t.p !== undefined ? t.p < 0.05 : t.q < 0.05;
const col = sig ? cssVar("--accent") : cssVar("--muted");
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg);
lab.textContent = (t.label.length > 40 ? t.label.slice(0, 39) + "…" : t.label) + (t.n !== undefined ? ` (n=${t.n})` : "");
svgEl("line", { x1: x(t.lo), x2: x(t.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("rect", { x: x(t.or) - 4, y: y - 4, width: 8, height: 8, fill: col }, svg);
const v = svgEl("text", { x: W - 4, y: y + 4, "text-anchor": "end", "font-family": "var(--font-data)", fill: cssVar("--muted") }, svg);
v.textContent = fmtOR(t.or);
});
el.innerHTML = ""; el.appendChild(svg);
}
// ------------------------------------------------------------ rare section
const STRATUM_ORDER = ["Bulk logs (imports)", "Form: other/blank goal", "Form: chasing Black", "Form: chasing Blue"];
function renderRare() {
const r = state.res;
const blueCol = dragonColor("Blue"), blackCol = dragonColor("Black");
const strataRows = (c, col) => [{ label: "All rows", ...c.overall, color: cssVar("--ink") }].concat(
STRATUM_ORDER.filter((s) => c.by_stratum[s]).map((s) => ({ label: s, ...c.by_stratum[s], color: col })),
Object.entries(c.by_attempt).filter(([k]) => k !== "Unknown/lost count").map(([k, w]) => ({ label: k, ...w, color: cssVar("--accent") })));
ciBars($("#ch-blue-strata"), strataRows(r.chance.blue_meadow, blueCol), { labelW: 180 });
ciBars($("#ch-shadow-strata"), strataRows(r.chance.shadow, blackCol), { labelW: 180 });
const termsOf = (m, skip = []) => (m ? m.terms.filter((t) => t.n >= 5 && !skip.includes(t.factor)).map((t) => ({ label: `${labelFactor(t.factor)}: ${t.level}`, or: t.or, lo: t.lo, hi: t.hi, p: t.p, n: t.n })) : []);
const mb = r.models.blue_meadow, ms = r.models.shadow;
forest($("#ch-model-blue"), termsOf(mb));
forest($("#ch-model-shadow"), termsOf(ms));
const refTxt = (m) => (m ? `Reference answers: ${Object.entries(m.refs).map(([f, v]) => `${labelFactor(f)} = ${v}`).join(", ")}. n = ${m.n}, events = ${m.events}. Gold = p < 0.05 (not corrected for the number of terms).` : "Not enough data.");
$("#model-blue-note").textContent = refTxt(mb);
$("#model-shadow-note").textContent = refTxt(ms);
renderDaily();
const enc = r.encounters.filter((e) => ["Blue (meadow)", "Blue (shadow)", "Black (shadow)"].includes(e.context));
ciBars($("#ch-rare-bond"), enc.flatMap((e) => [
{ label: e.context, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]), { labelW: 200, max: 1 });
renderPdfSteps();
}
function renderDaily() {
const d = state.res.daily.filter((x) => x.meadow_n + x.tree_n > 0);
const el = $("#ch-daily");
if (!d.length) { el.textContent = "No dated runs in the current filter."; return; }
const W = 640, H = 250, l = 44, rgt = 24, top = 16, mid = 125, bottom = 30;
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const x = (i) => l + (d.length === 1 ? (W - l - rgt) / 2 : (i * (W - l - rgt)) / (d.length - 1));
const panels = [
{ y0: top, y1: mid - 14, k: "blue_k", n: "meadow_n", col: dragonColor("Blue"), name: "Blue in meadow" },
{ y0: mid + 6, y1: H - bottom, k: "shadow_k", n: "tree_n", col: dragonColor("Black"), name: "Shadow at tree" },
];
panels.forEach((P) => {
const vals = d.map((r) => E.wilson(r[P.k], r[P.n]));
const ymax = Math.min(1, Math.max(0.05, ...vals.filter((v) => v.n >= 5).map((v) => v.hi)));
const y = (v) => P.y1 - (v / ymax) * (P.y1 - P.y0);
const ga = svgEl("g", { class: "axis" }, svg);
[0, ymax / 2, ymax].forEach((t) => { svgEl("line", { x1: l, x2: W - rgt, y1: y(t), y2: y(t) }, ga); const tx = svgEl("text", { x: l - 6, y: y(t) + 3, "text-anchor": "end" }, ga); tx.textContent = pct(t, 0); });
const nm = svgEl("text", { x: l + 4, y: P.y0 + 10, fill: P.col, "font-weight": 600 }, svg); nm.textContent = P.name;
const yc = (v) => y(Math.min(ymax, v));
vals.forEach((v, i) => {
if (v.n < 3) return;
svgEl("line", { x1: x(i), x2: x(i), y1: yc(v.lo), y2: yc(v.hi), stroke: P.col, "stroke-opacity": 0.45, "stroke-width": 1.5 }, svg);
const c = svgEl("circle", { cx: x(i), cy: yc(v.p), r: 2 + Math.sqrt(v.n) / 2.2, fill: P.col, "fill-opacity": 0.85 }, svg);
c.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${d[i].date} · ${P.name}</div>${pct(v.p)} (${kn(v)})<br>95% CI ${ci(v)}`));
c.addEventListener("mouseleave", hideTip);
});
});
const ga = svgEl("g", { class: "axis" }, svg);
d.forEach((r, i) => { if (i % Math.ceil(d.length / 8) === 0 || i === d.length - 1) { const t = svgEl("text", { x: x(i), y: H - 10, "text-anchor": "middle" }, ga); t.textContent = r.date.slice(5); } });
el.innerHTML = ""; el.appendChild(svg);
}
function renderPdfSteps() {
const blue = [["Approach the Blue: “Absolutely…”", "90%"], ["Hold the Blue's glare and advance", "80%"], ["Do nothing (it seizes the other cadet)", "82%"], ["Hold glare and watch", "84%"], ["Straighten your spine", "83%"], ["Launch yourself right (boulder)", "93%"], ["“Bring down an empire”", "81%"], ["Move slowly forward, wait for an invitation", "81%"]];
const prod = [0.9, 0.8, 0.82, 0.84, 0.83, 0.93, 0.81, 0.81].reduce((a, b) => a * b, 1);
$("#pdf-steps").innerHTML = `<p class="small muted">As published in the community PDF (u/ClumsyBadger, u/Old_Regular3018). These come from hand-coded free-text answers. The underlying counts are not shown there, and many cells rest on fewer than 10 runs.</p>
<div class="tbl-wrap"><table><thead><tr><th>Meadow Blue, standard answers</th><th class="num">Survived step</th></tr></thead><tbody>${blue.map(([a, b]) => `<tr><td>${a}</td><td class="num">${b}</td></tr>`).join("")}
<tr><td><b>All eight steps (product)</b></td><td class="num"><b>${pct(prod, 0)}</b></td></tr></tbody></table></div>
<p class="small">The product, about ${pct(prod, 0)}, agrees with the form's own Blue bond rate (${rateTxt(state.res.encounters.find((e) => e.context === "Blue (meadow)").overall)}), which is a useful cross-check.</p>
<div class="tbl-wrap"><table><thead><tr><th>Black (after the shadow and the tree Blue)</th><th class="num">PDF outcome</th></tr></thead><tbody>
<tr><td>Turn to face the threat → hold its gaze</td><td class="num">66% bonded · 33% incinerated</td></tr>
<tr><td>Turn to face the threat → lower your eyes → try to mount → meet its gaze</td><td class="num">100% bonded (very few runs)</td></tr></tbody></table></div>`;
}
// ------------------------------------------------------------ every dragon
function renderDragons() {
const r = state.res;
const order = ["Red (valley)", "Red (tree, descend quickly)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Blue (meadow)", "Blue (shadow)", "Black (shadow)"];
const rows = order.map((c) => r.encounters.find((e) => e.context === c)).filter(Boolean).flatMap((e) => [
{ label: `${e.context}`, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]);
const box = $("#ch-encounters");
box.innerHTML = `<h3>Bond rate once the encounter starts</h3><div class="chart" id="ch-enc-inner"></div>`;
ciBars($("#ch-enc-inner"), rows, { labelW: 220, max: 1, rowH: 22 });
const g = r.green_rescue;
const parts = [["Bonded a Green", g.bonded_green, dragonColor("Green")], ["Rescued, bonded the Orange", g.rescued_orange, dragonColor("Orange")], ["Rescued, bonded the Brown", g.rescued_brown, dragonColor("Brown")], ["Incinerated", g.incinerated, cssVar("--faint")], ["No outcome recorded", g.green_encounters - g.bonded_green - g.rescued_orange - g.rescued_brown - g.incinerated, cssVar("--line")]];
const tot = g.green_encounters || 1;
$("#green-rescue").innerHTML = `<p class="small muted">${g.green_encounters} tree runs that descended slowly to the two Greens. A wrong answer sometimes brings an Orange or Brown swooping in to bond you instead.</p>
<div style="display:flex;height:16px;border-radius:3px;overflow:hidden;border:1px solid var(--line)">${parts.map(([, n, c]) => `<span style="width:${(100 * n) / tot}%;background:${c}"></span>`).join("")}</div>
<div class="tbl-wrap"><table><tbody>${parts.map(([l, n, c]) => { const w = E.wilson(n, g.green_encounters); return `<tr><td><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:${c};margin-right:6px"></span>${l}</td><td class="num">${n}</td><td class="num">${pct(w.p)}</td><td class="num">${ci(w)}</td></tr>`; }).join("")}</tbody></table></div>`;
const cols = ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"];
const POOL = { "Alone|East": ["Red", "Orange"], "Alone|West": ["Red", "Brown", "Green"], "Alone|Center": ["Red", "Brown"], "1 Squadmate|East": ["Green", "Orange", "Red"], "1 Squadmate|West": ["Red", "Brown", "Green"], "1 Squadmate|Center": ["Red", "Brown"], "2 Squadmates|East": ["Red", "Orange"], "2 Squadmates|West": ["Green", "Brown", "Red"], "2 Squadmates|Center": ["Red", "Brown"] };
$("#tbl-first").innerHTML = `<table><thead><tr><th>Company · direction</th>${cols.map((c) => `<th class="num">${c}</th>`).join("")}<th class="num">Runs</th></tr></thead><tbody>${r.first_sighting.filter((x) => x.n >= 3).map((x) => `<tr><td>${esc(x.key.replace("|", " · "))}</td>${cols.map((c) => { const n = x.colors[c] || 0; const off = n && POOL[x.key] && !["Unsure", "Unknown"].includes(c) && !POOL[x.key].includes(c); return `<td class="num" style="${off ? "color:var(--warn);font-weight:600" : n ? "" : "color:var(--faint)"}" title="${off ? "Outside the documented pool" : ""}">${n ? `${n}<span class="muted"> · ${pct(n / x.n, 0)}</span>` : "·"}</td>`; }).join("")}<td class="num">${x.n}</td></tr>`).join("")}</tbody></table>`;
}
// ------------------------------------------------------------ route table
function renderRouteTable() {
const sel = $("#rt-target");
if (!sel.options.length) {
sel.innerHTML = Object.entries(E.TARGETS).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join("");
sel.value = state.rtTarget;
sel.addEventListener("change", () => { state.rtTarget = sel.value; renderRouteTable(); });
$("#rt-min").addEventListener("change", (e) => { state.rtMin = Math.max(1, +e.target.value || 10); renderRouteTable(); renderFindings(); });
}
const rk = E.rankRoutes(state.runs, state.rtTarget, state.rtMin);
const sig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
$("#rt-note").innerHTML = `${rk.n_routes_tested} routes tested · comparison group ${rateTxt(rk.overall)} · <b>${sig}</b> clearly better after adjustment`;
const bar = (w) => `<span class="cibar" aria-hidden="true"><i style="left:${w.lo * 90}px;width:${Math.max(1, (w.hi - w.lo) * 90)}px"></i><b style="left:${w.p * 90 - 1}px"></b></span>`;
$("#tbl-routes").innerHTML = rk.rows.length ? `<table><thead><tr><th>#</th><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Hits</th><th class="num">Rate</th><th class="num">95% CI</th><th></th><th class="num">Crude OR</th><th class="num">q</th><th class="num">Adj. OR</th><th class="num">Adj. q</th></tr></thead><tbody>
${rk.rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}${r.n < 20 ? " thin" : ""}"><td class="num">${i + 1}</td><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${r.k}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td>${bar(r)}</td><td class="num">${fmtOR(r.or)}</td><td class="num">${fmtP(r.q)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td></tr>`).join("")}
</tbody></table>` : `<p class="small muted" style="padding:12px">No routes reach the minimum. Lower it.</p>`;
}
// ------------------------------------------------------------ factor explorer
function renderFactors() {
const so = $("#fx-outcome"), sf = $("#fx-factor");
if (!so.options.length) {
so.innerHTML = Object.entries(E.OUTCOMES).map(([k, o]) => `<option value="${k}">${esc(o.label)}</option>`).join("");
sf.innerHTML = E.FACTORS.map((f) => `<option value="${f}">${esc(labelFactor(f))}</option>`).join("");
so.value = state.fxOutcome; sf.value = state.fxFactor;
so.addEventListener("change", () => { state.fxOutcome = so.value; renderFactors(); });
sf.addEventListener("change", () => { state.fxFactor = sf.value; renderFactors(); });
}
const ft = state.res.factors[state.fxOutcome];
const rows = ft.rows.filter((r) => r.factor === state.fxFactor);
$("#tbl-factors").innerHTML = `<table><thead><tr><th>${esc(labelFactor(state.fxFactor))}</th><th class="num">Hits/runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">OR vs rest</th><th class="num">p</th><th class="num">q</th></tr></thead><tbody>
<tr><td><i>All</i></td><td class="num">${kn(ft.overall)}</td><td class="num">${pct(ft.overall.p)}</td><td class="num">${ci(ft.overall)}</td><td></td><td></td><td></td></tr>
${rows.map((r) => `<tr class="${r.q < 0.05 ? "sig" : ""}${r.or === undefined ? " thin" : ""}"><td>${esc(r.level)}</td><td class="num">${kn(r)}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${r.or !== undefined ? `${fmtOR(r.or)} <span class="muted">(${fmtOR(r.or_lo)}–${fmtOR(r.or_hi)})</span>` : "too few"}</td><td class="num">${fmtP(r.fisher_p)}</td><td class="num">${r.q !== undefined ? `<span class="qbadge${r.q < 0.05 ? " s" : ""}">${fmtP(r.q)}</span>` : ""}</td></tr>`).join("")}
</tbody></table>`;
forest($("#ch-factor"), rows.filter((r) => r.or !== undefined).map((r) => ({ label: r.level, or: r.or, lo: r.or_lo, hi: r.or_hi, q: r.q, p: undefined, n: r.n })), { labelW: 220 });
}
// ------------------------------------------------------------ quality
function renderQuality() {
const r = state.res, m = r.meta;
const flags = Object.entries(m.flag_counts).sort((a, b) => b[1] - a[1]);
const outs = Object.entries(m.outcomes).sort((a, b) => b[1] - a[1]);
$("#quality-panels").innerHTML = `
<div class="panel"><h3>Who logged the runs</h3><div class="tbl-wrap"><table><thead><tr><th>Source</th><th class="num">Runs</th><th class="num">Blue in meadow</th><th class="num">Shadow at tree</th></tr></thead><tbody>
${Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([s, n]) => { const b = sourceRate("blue_meadow", s), t = sourceRate("shadow", s); return `<tr><td>${esc(s)}</td><td class="num">${n}</td><td class="num">${pct(b.p)} <span class="muted">${kn(b)}</span></td><td class="num">${pct(t.p)} <span class="muted">${kn(t)}</span></td></tr>`; }).join("")}
</tbody></table></div><p class="small">Bulk logs come from players who recorded every run, so they are the least selective rows. Their rare-dragon rates are several times lower than the form's, which is the strongest sign of reporting bias in this data.</p></div>
<div class="panel"><h3>Rows flagged for contradictions</h3><p class="small muted">${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you drop them above.</p><div class="tbl-wrap"><table><tbody>${flags.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td></tr>`).join("") || `<tr><td>None</td></tr>`}</tbody></table></div></div>
<div class="panel"><h3>How runs ended</h3><div class="tbl-wrap"><table><tbody>${outs.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td><td class="num">${pct(n / r.n)}</td></tr>`).join("")}</tbody></table></div><p class="small muted">"No outcome recorded" rows reached the hour but the form shows no Bonded or Incinerated. They count toward reaching a branch but not toward bond rates.</p></div>
<div class="panel"><h3>Independence</h3><p class="small">The form has no player ID. One player's 50 runs count as 50 independent runs, so intervals are somewhat narrower than they should be. ${pct((r.n - (m.sources["Form"] || 0)) / r.n, 0)} of rows arrived as bulk imports, each probably one player's or one group's log.</p></div>
<div class="panel"><h3>What the form does not ask</h3><p class="small">How you reacted to the first dragon, whether you assessed or charged the bullies (asked only on later forms: ${r.factors.reach_hour.rows.filter((x) => x.factor === "combat_first" && x.level !== "(not recorded)").reduce((a, x) => a + x.n, 0)} rows), and most choices inside encounters. Theories that rely on those choices cannot be confirmed or refuted here.</p></div>`;
}
function sourceRate(outKey, source) {
const O = E.OUTCOMES[outKey];
const D = state.runs.filter((r) => r.source === source).filter(O.denom);
return E.wilson(D.filter(O.event).length, D.length);
}
// ------------------------------------------------------------ share
function redditPost() {
const r = state.res, cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), bulkS = stratumRate(cs, "Bulk");
const encB = r.encounters.find((e) => e.context === "Blue (meadow)"), encK = r.encounters.find((e) => e.context === "Black (shadow)");
const mb = r.models.blue_meadow;
const sigRoute = mb ? mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level)) : [];
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
const leads = r.factors.shadow.rows.filter((x) => ["post_path", "attempt_group"].includes(x.factor) && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
const L = [];
L.push(`# I ran the numbers on ${r.n.toLocaleString()} logged threshing runs. Here's what holds up (and what doesn't)`);
L.push("");
L.push(`*Per the megathread rules, anything that names a specific route is behind spoiler tags.*`);
L.push("");
L.push(`Data: the community Threshing Routes form/spreadsheet (thanks u/ClumsyBadger, u/Old_Regular3018, u/Smart_Trifle_2099 and everyone who logged runs). ${Object.entries(r.meta.sources).map(([k, v]) => `${v} ${k === "Form" ? "form submissions" : k}`).join(", ")}; form dates ${r.meta.date_min} to ${r.meta.date_max}. Every rate below has a 95% confidence interval.`);
L.push("");
L.push(`**TL;DR**`);
L.push("");
L.push(`* **The meadow Blue shows up a lot less than the spreadsheet suggests.** Runs logged by Blue-chasers show it ${pct(chaseB && chaseB.p)} of the time, but bulk logs (people who recorded *every* run) show ${bulkB ? `${pct(bulkB.p)} (${kn(bulkB)})` : "n/a"}. The game can't know what you're chasing, so that gap is reporting bias. Expect something closer to the bulk-log number.`);
L.push(`* **${sigRoute.length ? "Only these route choices mattered for the Blue appearing" : "No recorded route choice changed the Blue's odds"}** once you account for that bias${sigRoute.length ? `: ${sigRoute.map((s) => s.term).join("; ")}` : ""} (direction, first dragon, how you handled the cadet, company). ${adjSig} of ${rk.n_routes_tested} full routes beat the rest after correcting for multiple testing. The "precise pathways" might still matter through choices the form doesn't record (like how you react to the first dragon), but the form can't confirm them.`);
L.push(`* **Getting the Blue to show up is only half of it.** Only ${encB ? `${pct(encB.overall.p)} (${kn(encB.overall)})` : "n/a"} of Blue attempts bonded, which matches the PDF's step-by-step numbers (~25%). Dying with the "right" answer is normal.`);
L.push(`* **The tree shadow (→ Black) is rarer than the spreadsheet suggests.** All rows: ${pct(cs.overall.p)} (${kn(cs.overall)}), but bulk logs show ${bulkS ? `${kn(bulkS)} (upper 95% bound ${pct(bulkS.hi)})` : "n/a"}. ${bulkS && bulkS.n ? `Plan on roughly 1 in ${Math.round(1 / Math.max(bulkS.hi, 0.001) / 10) * 10} climbs at best.` : ""} Once you get the Black, it bonds ${encK ? `${pct(encK.overall.p)} (${kn(encK.overall)})` : "n/a"} of the time.`);
if (leads.length) L.push(`* **Leads worth testing (not proven):** >!${leads.map((x) => `${labelFactor(x.factor)} = ${x.level}: shadow in ${pct(x.p)} (${kn(x)}) vs the rest`).join("; ")}!<. If you bulk-log your tree climbs *including the boring ones*, we can settle this.`);
L.push("");
L.push(`**How to help:** log every run in the form, including the ones where nothing rare happened. Those dull runs are what make the rates trustworthy.`);
L.push("");
L.push(`Interactive route map, full methods, and code to reproduce every number: [Threshing Route Atlas](LINK)`);
L.push("");
L.push(`*Caveats: self-reported data, no player IDs (so runs from one person aren't independent), and the form doesn't record every in-game choice. The author has said there's a ~10% chaos roll, so nothing is guaranteed.*`);
return L.join("\n");
}
function runsCSV() {
const cols = Object.keys(state.runs[0] || {});
const q = (v) => { if (v === null || v === undefined) return ""; const s = String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...state.runs.map((r) => cols.map((c) => q(r[c])).join(","))].join("\n");
}
$("#cp-reddit").addEventListener("click", () => copyText(redditPost(), "Reddit post"));
$("#cp-csv").addEventListener("click", () => copyText(runsCSV(), `${state.runs.length} coded runs`));
$("#cp-json").addEventListener("click", () => copyText(JSON.stringify(state.res, null, 1), "results JSON"));
$$("button[data-src]").forEach((b) => b.addEventListener("click", async () => {
const pre = $("#srcview");
try { const t = await (await fetch(b.dataset.src)).text(); pre.textContent = t; pre.hidden = false; pre.scrollTop = 0; }
catch (e) { pre.textContent = "Could not load " + b.dataset.src; pre.hidden = false; }
}));
// ------------------------------------------------------------ controls
$$("#width-mode button").forEach((b) => b.addEventListener("click", () => {
state.widthMode = b.dataset.v;
$$("#width-mode button").forEach((x) => x.setAttribute("aria-pressed", x === b));
renderMap();
}));
$("#minn").addEventListener("change", (e) => { state.minN = Math.max(1, +e.target.value || 10); renderMap(); });
$("#f-source").addEventListener("change", (e) => { state.filters.source = e.target.value; recompute(); });
$("#f-goal").addEventListener("change", (e) => { state.filters.goal = e.target.value; recompute(); });
$("#f-flag").addEventListener("change", (e) => { state.filters.excludeFlagged = e.target.checked; recompute(); });
$("#btn-clear").addEventListener("click", () => { state.conds = {}; renderMap(); $("#best-routes").innerHTML = ""; });
$("#btn-best").addEventListener("click", renderBestRoutes);
function renderAll() {
renderStatus(); renderFindings(); renderTargets(); renderMap(); renderRare(); renderDragons(); renderRouteTable(); renderFactors(); renderQuality();
if ($("#best-routes").innerHTML) renderBestRoutes();
if (window.AtlasUI) window.AtlasUI.render(state);
}
// re-colour when the theme changes
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const rerender = () => state.res && renderAll();
mq.addEventListener && mq.addEventListener("change", rerender);
new MutationObserver(rerender).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
let rz; window.addEventListener("resize", () => { clearTimeout(rz); rz = setTimeout(() => state.res && renderMap(), 200); });
window.ThreshAtlas = { state, redditPost, runsCSV };
if (window.DragonRegister) window.DragonRegister.mount({ copy: copyText, toast });
loadBundled().catch((e) => { $("#data-status").innerHTML = `<span class="pill warn">The bundled data could not load (${esc(e.message)}). Use "Load a newer export" to load the responses file.</span>`; console.error(e); });
})();
+592
View File
@@ -0,0 +1,592 @@
<title>Threshing Route Atlas</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Marcellus&family=Josefin+Sans:wght@400;600&family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
/* Layout: a field atlas — one wide route chart flanked by narrow reading columns; numbers set in mono, dragons carry their own colours. */
/* Layout: a dusk-lit field atlas — arched, deco-framed panels on deep plum; gold line work; each dragon tints its own frame; deaths turn steel and ember. Single dark world by design. */
:root {
color-scheme: dark;
--bg: #170911; --surface: #210f19; --raised: #2a1420; --ink: #f6e8d6; --muted: #cba890; --faint: #8e7069; --line: #4b2a36;
--accent: #e8b483; --accent-ink: #1d0a12; --good: #8fc98a; --warn: #f0a55a; --bad: #ef6b6b;
--dr-red: #e4566d; --dr-green: #84c27c; --dr-orange: #f29a4c; --dr-brown: #c8976b; --dr-blue: #82a8f2; --dr-black: #b9abd3; --dr-any: #e0a9c6;
--link-low: #4f2f3c; --death: #9fb6c3; --ember: #e3692f; --death-bg: #1b0811; --frame: var(--accent);
--font-display: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-crest: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-label: "Josefin Sans", "Gill Sans", "Trebuchet MS", sans-serif;
--font-body: "Alegreya Sans", "Segoe UI", system-ui, sans-serif;
--font-data: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
--hero-bg: #1a0912; --hero-bg2: #3a1526; --hero-ink: #f6e8d6; --hero-muted: #d2b096; --hero-line: #6b4148;
--map-ground: #2a1420; --map-ground2: #34192a; --map-forest: #4b2b3b; --map-forest2: #3b2030; --map-rock: #5e3d4a; --map-water: #6f90a5; --map-path: #e8b483; --map-label: #f6e8d6; --map-halo: #1c0a13;
--step--1: 0.84rem; --step-0: 1rem; --step-1: 1.18rem; --step-2: 1.6rem; --step-3: 2.3rem; --radius: 10px;
}
* { box-sizing: border-box; }
body { background: var(--bg); color: var(--ink); font-family: var(--font-body); font-size: var(--step-0); line-height: 1.55; }
.wrap { max-width: 1260px; margin: 0 auto; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); padding-block: 0; }
h1, h2, h3 { font-family: var(--font-display); font-weight: 650; line-height: 1.15; text-wrap: balance; margin: 0; }
h1 { font-size: var(--step-3); letter-spacing: -0.01em; }
h2 { font-size: var(--step-2); }
h3 { font-size: var(--step-1); font-family: var(--font-body); font-weight: 600; }
p { margin: 0; max-width: 68ch; }
a { color: var(--accent); }
code, .num, .mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; }
.eyebrow { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
.muted { color: var(--muted); }
.small { font-size: var(--step--1); }
header.top { border-bottom: 1px solid var(--line); background: var(--surface); }
header.top .wrap { display: grid; gap: 14px; padding-block: 28px 22px; }
.title-row { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; }
.lede { color: var(--muted); max-width: 72ch; }
.data-status { display: flex; flex-wrap: wrap; gap: 8px 18px; font-size: var(--step--1); color: var(--muted); align-items: center; }
.data-status b { color: var(--ink); font-weight: 600; }
.pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); white-space: nowrap; }
.data-status .pill { white-space: normal; overflow-wrap: anywhere; max-width: 100%; }
.data-status > span { min-width: 0; overflow-wrap: anywhere; }
.pill.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); color: var(--warn); }
nav.toc { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: var(--step--1); }
nav.toc a { color: var(--muted); text-decoration: none; border-bottom: 1px solid transparent; }
nav.toc a:hover, nav.toc a:focus-visible { color: var(--ink); border-bottom-color: var(--accent); }
main { display: grid; gap: 44px; padding-block: 30px 60px; }
section { display: grid; gap: 16px; scroll-margin-top: 16px; }
.section-head { display: grid; gap: 6px; }
/* controls */
.controls { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: end; padding: 14px 16px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.ctl { display: grid; gap: 4px; min-width: 0; }
.ctl label, .ctl .lbl { font-size: var(--step--1); color: var(--muted); }
select, input[type="number"], button, .filebtn { font: inherit; font-size: var(--step--1); color: var(--ink); background: var(--raised); border: 1px solid var(--line); border-radius: 5px; padding: 6px 10px; }
input[type="number"] { width: 5.5em; }
button, .filebtn { cursor: pointer; }
button:hover, .filebtn:hover { border-color: var(--accent); }
button:focus-visible, select:focus-visible, input:focus-visible, .filebtn:focus-within, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
.seg button { border: 0; border-radius: 0; border-right: 1px solid var(--line); }
.seg button:last-child { border-right: 0; }
.seg button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
.check { display: inline-flex; gap: 6px; align-items: center; font-size: var(--step--1); }
.targets { display: flex; flex-wrap: wrap; gap: 8px; }
.tchip { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); cursor: pointer; }
.tchip .sw { width: 11px; height: 11px; border-radius: 50%; background: var(--c, var(--faint)); box-shadow: 0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent); }
.tchip[aria-pressed="true"] { border-color: var(--c, var(--ink)); box-shadow: inset 0 0 0 1px var(--c, var(--ink)); font-weight: 600; }
.tchip.featured { padding: 7px 14px; font-size: var(--step-0); }
.target-group { display: grid; gap: 6px; }
/* map */
.map-shell { border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); overflow: hidden; }
.map-top { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid var(--line); background: var(--surface); }
.cond-chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
.cchip { display: inline-flex; gap: 6px; align-items: center; padding: 2px 4px 2px 9px; border: 1px solid var(--accent); color: var(--ink); border-radius: 999px; font-size: var(--step--1); background: color-mix(in srgb, var(--accent) 10%, var(--raised)); }
.cchip button { border: 0; background: transparent; padding: 0 6px; line-height: 1; font-size: 1rem; color: var(--muted); }
.map-scroll { overflow-x: auto; }
#map { display: block; }
#map text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
#map .stage-label { font-family: var(--font-data); font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--muted); }
#map .stage-chance { fill: var(--accent); }
#map .node rect { stroke: color-mix(in srgb, var(--ink) 40%, transparent); stroke-width: 0.6; cursor: pointer; }
#map .node.sel rect { stroke: var(--accent); stroke-width: 2.4; }
#map .node.dim { opacity: 0.35; }
#map .link { mix-blend-mode: normal; }
#map .link:hover { opacity: 1 !important; }
#map .node:focus-visible rect { stroke: var(--accent); stroke-width: 3; }
.map-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .map-foot { grid-template-columns: minmax(0, 1fr); } }
.legend { display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: center; font-size: var(--step--1); color: var(--muted); }
.ramp { width: 150px; height: 10px; border-radius: 3px; border: 1px solid var(--line); }
.sel-summary { display: grid; gap: 6px; font-size: var(--step--1); }
.sel-summary .big { font-family: var(--font-data); font-size: var(--step-2); color: var(--ink); }
#tip { position: fixed; z-index: 50; pointer-events: none; background: var(--raised); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; font-size: var(--step--1); box-shadow: 0 6px 20px rgba(0,0,0,0.18); max-width: 300px; }
#tip .t { font-weight: 600; }
/* cards & grids */
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 18px; }
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 18px; }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px; display: grid; gap: 10px; min-width: 0; align-content: start; }
.panel h3 { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
.chart { width: 100%; overflow-x: auto; }
.chart svg { display: block; width: 100%; max-width: 760px; min-width: 540px; height: auto; }
.chart svg text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
.chart svg .axis text { fill: var(--muted); font-family: var(--font-data); font-size: 10px; }
.chart svg .axis line, .chart svg .grid line { stroke: var(--line); }
.findings { display: grid; gap: 12px; counter-reset: f; }
.finding { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 10px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.finding .mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-family: var(--font-data); font-size: 11px; color: var(--accent-ink); background: var(--muted); }
.finding.blue .mark { background: var(--dr-blue); color: #fff; }
.finding.black .mark { background: var(--dr-black); color: var(--bg); }
.finding.bias .mark { background: var(--warn); color: #fff; }
.finding.lead .mark { background: var(--accent); }
.finding p + p { margin-top: 4px; }
.finding .tag { font-family: var(--font-data); font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
/* tables */
.tbl-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); }
table { border-collapse: collapse; width: 100%; font-size: var(--step--1); }
th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--line); vertical-align: top; }
th { font-weight: 600; color: var(--muted); background: var(--surface); position: sticky; top: 0; white-space: nowrap; }
th[data-sort] { cursor: pointer; }
th[data-sort]:hover { color: var(--ink); }
td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-numeric: tabular-nums; white-space: nowrap; }
tr.sig td { background: color-mix(in srgb, var(--accent) 9%, transparent); }
tr.thin td { color: var(--faint); }
.route-cell { min-width: 280px; }
.cibar { display: inline-block; position: relative; width: 90px; height: 10px; vertical-align: middle; }
.cibar i { position: absolute; top: 4px; height: 2px; background: var(--muted); }
.cibar b { position: absolute; top: 1px; width: 2px; height: 8px; background: var(--ink); }
.qbadge { font-family: var(--font-data); font-size: 10.5px; padding: 1px 6px; border-radius: 4px; border: 1px solid var(--line); }
.qbadge.s { border-color: var(--accent); color: var(--accent); }
.method { display: grid; gap: 14px; }
.method p, .method li { max-width: 74ch; }
.method ul, .method ol { margin: 0; padding-left: 1.2em; display: grid; gap: 4px; }
.formula { font-family: var(--font-data); font-size: var(--step--1); background: var(--surface); border: 1px solid var(--line); border-left: 3px solid var(--accent); padding: 10px 12px; border-radius: 4px; overflow-x: auto; white-space: pre; }
details.fold { border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
details.fold > summary { cursor: pointer; padding: 10px 14px; font-weight: 600; }
details.fold > div { padding: 0 14px 14px; display: grid; gap: 10px; }
.btnrow { display: flex; flex-wrap: wrap; gap: 8px; }
#srcview { white-space: pre; overflow: auto; max-height: 420px; font-family: var(--font-data); font-size: 12px; background: var(--raised); border: 1px solid var(--line); border-radius: 4px; padding: 10px; }
.toast { position: fixed; bottom: calc(16px + env(safe-area-inset-bottom, 0px)); left: 50%; transform: translateX(-50%); background: var(--ink); color: var(--bg); padding: 8px 14px; border-radius: 6px; font-size: var(--step--1); z-index: 60; }
.loading { padding: 40px 0; color: var(--muted); }
footer { border-top: 1px solid var(--line); padding-block: 22px 40px; color: var(--muted); font-size: var(--step--1); }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
/* ---------- hero, tabs, overview, valley map, gallery ---------- */
body::before { content: ""; position: fixed; inset: 0 0 auto; height: env(safe-area-inset-top, 0px); z-index: 10; background: var(--hero-bg); }
.hero { background: radial-gradient(120% 140% at 70% 0%, var(--hero-bg2), var(--hero-bg) 60%); color: var(--hero-ink); position: relative; overflow: hidden; }
.hero .wrap { position: relative; z-index: 1; display: grid; gap: 14px; padding-block: 34px 0; }
.hero-art { position: absolute; inset: auto 0 0 0; height: 100%; width: 100%; z-index: 0; pointer-events: none; }
.hero h1 { font-family: var(--font-crest); font-weight: 700; font-size: clamp(1.9rem, 4.6vw, 3.1rem); letter-spacing: 0.04em; color: var(--hero-ink); }
.hero .kicker { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.14em; text-transform: uppercase; color: var(--hero-muted); }
.hero .tagline { color: var(--hero-muted); max-width: 60ch; font-size: var(--step-1); }
.hero .unofficial { display: inline-block; font-size: var(--step--1); color: var(--hero-muted); border: 1px solid var(--hero-line); border-radius: 999px; padding: 2px 10px; width: fit-content; }
.tabs { display: flex; gap: 2px; overflow-x: auto; margin-top: 18px; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab { font-family: var(--font-crest); font-weight: 700; letter-spacing: 0.06em; font-size: 0.9rem; color: var(--hero-muted); background: transparent; border: 0; border-radius: 8px 8px 0 0; padding: 12px 16px 11px; white-space: nowrap; cursor: pointer; border-top: 2px solid transparent; }
.tab:hover { color: var(--hero-ink); }
.tab[aria-selected="true"] { background: var(--bg); color: var(--ink); border-top-color: var(--accent); }
.tab:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.tabpanel { display: grid; gap: 44px; }
.tabpanel[hidden] { display: none !important; }
section h2 { font-family: var(--font-crest); letter-spacing: 0.03em; }
.odds { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr)); gap: 16px; }
.odd { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 10px; align-content: start; position: relative; overflow: hidden; }
.odd .big { font-family: var(--font-crest); font-weight: 700; font-size: 2.1rem; line-height: 1; color: var(--c, var(--ink)); }
.odd .what { font-weight: 600; }
.odd .how { font-size: var(--step--1); color: var(--muted); }
.odd svg { display: block; width: 100%; max-width: 220px; height: auto; }
.odd::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 4px; background: var(--c, var(--line)); }
.combo { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 16px; }
.combo .odd { grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 14px; }
.journey { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 0; counter-reset: st; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--surface); }
.stop { padding: 14px; display: grid; gap: 6px; align-content: start; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.stop .n { font-family: var(--font-crest); font-weight: 700; color: var(--accent); font-size: 1.3rem; }
.stop .t { font-weight: 600; }
.stop .d { font-size: var(--step--1); color: var(--muted); }
.stop .verdict { font-size: var(--step--1); border-top: 1px dashed var(--line); padding-top: 6px; }
.stop.roll .n::after { content: " · roll"; font-family: var(--font-data); font-size: 10px; letter-spacing: 0.1em; color: var(--muted); }
.truths { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 16px; }
.truth { padding: 18px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); display: grid; gap: 8px; align-content: start; }
.truth h3 { font-family: var(--font-crest); font-size: 1.05rem; letter-spacing: 0.02em; }
.cta { display: flex; flex-wrap: wrap; gap: 10px; }
.cta button { font-size: var(--step-0); padding: 9px 16px; }
.lore { border-left: 3px solid var(--accent); padding: 4px 0 4px 14px; color: var(--muted); font-size: var(--step--1); max-width: 70ch; }
.valley-shell { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--map-ground); }
.valley-wrap { overflow-x: auto; }
#valley { display: block; width: 100%; min-width: 820px; height: auto; background: #d9b07a; }
#valley .loc { cursor: pointer; }
#valley .loc:focus-visible circle.ring { stroke: var(--accent); stroke-width: 4; }
#valley text { font-family: var(--font-body); }
#valley .place { font-family: var(--font-crest); font-weight: 700; font-size: 15px; letter-spacing: 0.04em; fill: var(--map-label); paint-order: stroke; stroke: var(--map-halo); stroke-width: 4px; stroke-linejoin: round; }
#valley .sub { font-size: 12px; fill: var(--map-label); opacity: 0.85; paint-order: stroke; stroke: var(--map-halo); stroke-width: 3px; }
#valley .trail { fill: none; stroke-linecap: round; }
#valley .flow { fill: none; stroke-linecap: round; stroke-dasharray: 2 14; animation: march 1.6s linear infinite; }
@keyframes march { to { stroke-dashoffset: -32; } }
@media (prefers-reduced-motion: reduce) { #valley .flow { animation: none; } }
.valley-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .valley-foot { grid-template-columns: minmax(0, 1fr); } }
.loc-card { display: grid; gap: 6px; font-size: var(--step--1); }
.loc-card h3 { font-family: var(--font-crest); font-size: 1.1rem; }
.bars { display: grid; gap: 4px; }
.bar { display: grid; grid-template-columns: 120px minmax(0, 1fr) 96px; gap: 8px; align-items: center; font-size: var(--step--1); }
.bar i { display: block; height: 10px; border-radius: 3px; background: var(--c, var(--muted)); min-width: 2px; }
.bar span:last-child { text-align: right; font-family: var(--font-data); white-space: nowrap; }
.gallery { display: grid; gap: 22px; }
.gal-group { display: grid; gap: 10px; }
.gal-group h3 { font-family: var(--font-crest); display: flex; gap: 10px; align-items: center; font-size: 1.15rem; }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 168px), 1fr)); gap: 10px; }
.dcard { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px; display: grid; gap: 6px; justify-items: center; text-align: center; position: relative; }
.dcard svg { width: 64px; height: 64px; }
.dcard .nm { font-family: var(--font-crest); font-weight: 700; font-size: 1rem; letter-spacing: 0.03em; overflow-wrap: anywhere; }
.dcard .meta { font-size: 12px; color: var(--muted); line-height: 1.35; }
.dcard .age { position: absolute; top: 8px; right: 10px; font-family: var(--font-data); font-size: 11px; color: var(--muted); }
.viewtoggle { display: inline-flex; }
/* ---------- dusk & gold theme layer ---------- */
body { background: radial-gradient(140% 90% at 50% -10%, #2b0f1f 0%, var(--bg) 55%) fixed, var(--bg); }
.eyebrow, .kicker, .lbl, .tab, .tchip, button, .filebtn, th, .stage-label { font-family: var(--font-label); letter-spacing: 0.12em; text-transform: uppercase; }
.eyebrow { font-size: 0.72rem; color: var(--accent); }
h1, h2, h3 { font-family: var(--font-display); font-weight: 400; }
h2 { font-size: var(--step-2); letter-spacing: 0.04em; }
.panel h3, .truth h3, .gal-group h3, .loc-card h3 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.03em; }
button, .filebtn { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); background: color-mix(in srgb, var(--raised) 80%, #000); color: var(--ink); font-size: 0.74rem; padding: 8px 16px; box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 12px rgba(232,180,131,0.08); }
button:hover, .filebtn:hover { border-color: var(--accent); box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 14px rgba(232,180,131,0.25); }
button.primary { background: var(--accent); color: var(--accent-ink); }
select, input[type="number"], input[type="search"] { background: var(--raised) !important; color: var(--ink) !important; border: 1px solid var(--line) !important; border-radius: 8px !important; }
.seg { border-radius: 999px; border-color: color-mix(in srgb, var(--accent) 60%, transparent); }
.seg button { border-radius: 0; box-shadow: none; }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
.tchip { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--c, var(--accent)) 55%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); font-size: 0.72rem; padding: 7px 14px; }
.tchip[aria-pressed="true"] { background: color-mix(in srgb, var(--c, var(--accent)) 22%, var(--raised)); box-shadow: 0 0 14px color-mix(in srgb, var(--c, var(--accent)) 35%, transparent), inset 0 0 0 1px var(--c, var(--accent)); }
.tchip.featured { font-size: 0.8rem; }
/* deco frame: double line + sunburst corners, tinted by --frame */
.deco { position: relative; border: 1px solid color-mix(in srgb, var(--frame) 75%, transparent); box-shadow: inset 0 0 0 4px var(--surface), inset 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent); }
.deco::before, .deco::after { content: ""; position: absolute; width: 46px; height: 46px; pointer-events: none; background: var(--frame); opacity: 0.55;
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat; }
.deco::before { top: 6px; left: 6px; }
.deco::after { bottom: 6px; right: 6px; transform: rotate(180deg); }
.panel, .odd, .truth, .finding, .controls, .map-shell, .valley-shell, .journey, .dcard, .tbl-wrap { border-color: color-mix(in srgb, var(--frame) 30%, var(--line)); }
.panel, .odd, .truth { background: linear-gradient(180deg, color-mix(in srgb, var(--surface) 92%, var(--frame) 8%), var(--surface)); }
.controls { background: color-mix(in srgb, var(--surface) 80%, #000); }
.odd::before { display: none; }
.odd { border-radius: 120px 120px 14px 14px / 60px 60px 14px 14px; padding-top: 26px; text-align: center; justify-items: center; }
.odd .big { font-family: var(--font-display); font-weight: 400; text-shadow: 0 0 18px color-mix(in srgb, var(--c) 45%, transparent); }
.combo .odd { border-radius: 14px; text-align: left; justify-items: start; }
.truth { border-radius: 14px; }
table { background: transparent; }
th { background: color-mix(in srgb, var(--surface) 70%, #000); color: var(--accent); font-size: 0.7rem; }
td { border-bottom-color: color-mix(in srgb, var(--line) 70%, transparent); }
.tbl-wrap { background: color-mix(in srgb, var(--raised) 60%, var(--bg)); }
.formula { background: var(--death-bg); border-left-color: var(--accent); }
#tip { background: #2a1420; border-color: var(--accent); box-shadow: 0 6px 24px rgba(0,0,0,0.5), 0 0 12px rgba(232,180,131,0.15); }
.toast { background: var(--accent); color: var(--accent-ink); }
.pill { background: color-mix(in srgb, var(--raised) 70%, #000); }
.lore { border-left-color: var(--accent); font-style: italic; }
/* hero: arched title card over a dusk forest */
.hero { background: radial-gradient(90% 120% at 50% 0%, var(--hero-bg2), var(--hero-bg) 70%); }
.hero .wrap { justify-items: center; text-align: center; padding-block: 28px 0; }
.arch { --frame: var(--accent); position: relative; padding: 34px clamp(18px, 5vw, 64px) 26px; border-radius: 260px 260px 18px 18px / 150px 150px 18px 18px; border: 1px solid color-mix(in srgb, var(--accent) 80%, transparent);
box-shadow: inset 0 0 0 5px rgba(26,9,18,0.9), inset 0 0 0 6px color-mix(in srgb, var(--accent) 45%, transparent), 0 0 40px rgba(0,0,0,0.45);
background: radial-gradient(70% 80% at 50% 40%, rgba(40,10,26,0.92), rgba(22,7,15,0.95)); display: grid; gap: 10px; justify-items: center; max-width: 760px; width: 100%; }
.arch .crest { width: 120px; height: 34px; margin-top: -8px; }
.hero h1 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.08em; text-transform: uppercase; font-size: clamp(1.7rem, 5vw, 3rem); text-shadow: 0 0 22px rgba(232,180,131,0.25); }
.hero .kicker { font-family: var(--font-label); color: var(--accent); letter-spacing: 0.22em; font-size: 0.7rem; }
.hero .tagline { color: var(--hero-muted); font-size: var(--step-1); }
.hero .unofficial { border-color: var(--hero-line); color: var(--hero-muted); }
.tabs { justify-content: flex-start; gap: 6px; margin-top: 22px; padding-bottom: 14px; flex-wrap: nowrap; width: fit-content; max-width: 100%; }
.tab { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent); padding: 9px 16px; font-size: 0.7rem; color: var(--hero-muted); background: rgba(20,6,13,0.6); border-top-width: 1px; }
.tab[aria-selected="true"] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); box-shadow: 0 0 16px rgba(232,180,131,0.35); }
.embers { position: absolute; inset: 0; pointer-events: none; z-index: 0; overflow: hidden; }
.embers i { position: absolute; bottom: -10px; width: 4px; height: 4px; border-radius: 50%; background: var(--ember); box-shadow: 0 0 8px var(--ember); opacity: 0; animation: rise linear infinite; }
@keyframes rise { 0% { transform: translateY(0); opacity: 0; } 10% { opacity: 0.9; } 100% { transform: translateY(-340px) translateX(20px); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .embers i { animation: none; opacity: 0.5; bottom: auto; } }
/* death palette: steel frame, ember glow */
.death { --frame: var(--death); background: radial-gradient(80% 90% at 50% 30%, #2a0b19, var(--death-bg)) !important; color: #efe6f2; }
.death .big { color: #efe6f2 !important; text-shadow: 0 0 22px rgba(227,105,47,0.45), 0 0 4px rgba(255,255,255,0.4) !important; font-family: var(--font-display); text-transform: uppercase; letter-spacing: 0.04em; }
.death .how, .death p { color: #c8bcc9; }
.arch::before { top: auto; bottom: 6px; left: 6px; transform: rotate(270deg); }
.odds { grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); }
@media (max-width: 600px) { .hero .tagline { font-size: var(--step-0); } }
/* dragon-tinted frames */
.dcard { --frame: var(--dc, var(--accent)); border-radius: 60px 60px 12px 12px / 34px 34px 12px 12px; border: 1px solid color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: inset 0 0 0 3px var(--surface), inset 0 0 0 4px color-mix(in srgb, var(--frame) 30%, transparent); padding-top: 16px; }
.dcard .nm { font-family: var(--font-display); font-weight: 400; }
.gal-group h3 { color: var(--ink); }
.loc-card { --frame: var(--lc, var(--accent)); }
.valley-shell { --frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent), 0 0 30px color-mix(in srgb, var(--frame) 15%, transparent); }
#panel-rare .panel:nth-child(odd) { --frame: var(--dr-blue); }
#panel-rare .panel:nth-child(even) { --frame: var(--dr-black); }
.stop .n { font-family: var(--font-display); font-weight: 400; color: var(--accent); }
.journey { background: color-mix(in srgb, var(--surface) 85%, #000); }
footer { border-top-color: var(--line); }
</style>
<header class="hero">
<svg class="hero-art" id="hero-art" viewBox="0 0 1200 420" preserveAspectRatio="xMidYMax slice" aria-hidden="true"></svg>
<div class="embers" id="embers" aria-hidden="true"></div>
<div class="wrap">
<div class="arch deco">
<svg class="crest" viewBox="0 0 120 34" aria-hidden="true"><g fill="none" stroke="#e8b483" stroke-width="1.1"><path d="M4 20 H44 M76 20 H116"/><path d="M60 4 L68 17 L60 30 L52 17 Z"/><path d="M60 10 L64 17 L60 24 L56 17 Z" fill="#e8b483"/><path d="M44 20 C50 12, 54 12, 52 17 M76 20 C70 12, 66 12, 68 17"/><circle cx="4" cy="20" r="2" fill="#e8b483"/><circle cx="116" cy="20" r="2" fill="#e8b483"/></g></svg>
<span class="kicker">Basgiath · Riders Quadrant · Threshing</span>
<h1>Threshing Route Atlas</h1>
<p class="tagline" id="hero-tagline">Every path through the valley, mapped from the runs riders logged.</p>
<span class="unofficial">Unofficial fan atlas for readers of Rebecca Yarros's <i>Fourth Wing</i> · not affiliated with Dragonkind</span>
</div>
<nav class="tabs" role="tablist" aria-label="Atlas pages">
<button class="tab" role="tab" id="tab-overview" aria-controls="panel-overview" aria-selected="true">The Threshing</button>
<button class="tab" role="tab" id="tab-valley" aria-controls="panel-valley" aria-selected="false">Valley Map</button>
<button class="tab" role="tab" id="tab-flow" aria-controls="panel-flow" aria-selected="false">Route Flow</button>
<button class="tab" role="tab" id="tab-rare" aria-controls="panel-rare" aria-selected="false">Blue &amp; Black</button>
<button class="tab" role="tab" id="tab-dragons" aria-controls="panel-dragons" aria-selected="false">The Dragons</button>
<button class="tab" role="tab" id="tab-deep" aria-controls="panel-deep" aria-selected="false">Deep Dive</button>
<button class="tab" role="tab" id="tab-share" aria-controls="panel-share" aria-selected="false">Data &amp; Share</button>
</nav>
</div>
</header>
<div class="wrap">
<main>
<div class="tabpanel" id="panel-overview" role="tabpanel" aria-labelledby="tab-overview">
<section id="overview" aria-labelledby="h-odds">
<div class="section-head">
<span class="eyebrow">Before you walk into the valley</span>
<h2 id="h-odds">Your odds, honestly</h2>
<p class="muted small">Each grid of dots is 100 runs. These numbers lean on the riders who logged <i>every</i> run, including the dull ones, because people mostly share their lucky runs.</p>
</div>
<div class="odds" id="odds"></div>
<div class="combo" id="combo"></div>
</section>
<section aria-labelledby="h-journey">
<div class="section-head">
<span class="eyebrow">Seven steps, two of them pure luck</span>
<h2 id="h-journey">How a run unfolds</h2>
</div>
<div class="journey" id="journey"></div>
<p class="lore">In the books, first-years who survive to Threshing walk into a valley of unbonded dragons, and the dragons do the choosing. The Dragonkind site recreates that: every choice can end with you incinerated, and the author has said there is a 10% chance of that no matter what you pick.</p>
</section>
<section aria-labelledby="h-truths">
<div class="section-head"><span class="eyebrow">What 2,500 runs say</span><h2 id="h-truths">Three things worth knowing</h2></div>
<div class="truths" id="truths"></div>
<div class="cta"><button type="button" class="primary" data-go="valley">Walk the valley map</button><button type="button" data-go="rare">Chasing a Blue or Black?</button><button type="button" data-go="dragons">Meet the bonded dragons</button></div>
</section>
</div>
<div class="tabpanel" id="panel-valley" role="tabpanel" aria-labelledby="tab-valley" hidden>
<section id="valley-sec" aria-labelledby="h-valley">
<div class="section-head">
<span class="eyebrow">Interactive · drawn from the in-game descriptions, not an official map</span>
<h2 id="h-valley">The valley</h2>
<p class="muted small">Trails are as thick as the number of riders who walked them. Their colour shows how often walking that way ended with the dragon you pick below. Tap a place for what happened there.</p>
</div>
<div class="controls"><div class="target-group"><span class="lbl small muted">Colour the trails by</span><div class="targets" id="valley-targets"></div></div></div>
<div class="valley-shell deco">
<div class="valley-wrap"><svg id="valley" viewBox="0 0 1000 780" role="img" aria-label="Illustrated map of the threshing valley with trails"></svg></div>
<div class="valley-foot"><div class="loc-card" id="loc-card"></div><div class="legend" id="valley-legend"></div></div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-flow" role="tabpanel" aria-labelledby="tab-flow" hidden>
<section id="map-sec" aria-labelledby="h-map">
<div class="section-head">
<span class="eyebrow">Interactive</span>
<h2 id="h-map">Route map</h2>
<p class="muted small">Pick an outcome. Click any box to keep only the runs that passed through it, and click more boxes to narrow further. Hover or tap a box or band for its numbers.</p>
</div>
<div class="controls" id="map-controls">
<div class="target-group">
<span class="lbl small muted">Rare dragons</span>
<div class="targets" id="targets-rare"></div>
</div>
<div class="target-group">
<span class="lbl small muted">Other outcomes</span>
<div class="targets" id="targets-other"></div>
</div>
</div>
<div class="controls">
<div class="ctl"><span class="lbl">Band width shows</span>
<div class="seg" id="width-mode"><button type="button" data-v="traffic" aria-pressed="true">How many runs</button><button type="button" data-v="prob" aria-pressed="false">Chance of outcome</button></div></div>
<div class="ctl"><label for="minn">Grey out steps with fewer runs than</label><input id="minn" type="number" min="1" max="200" value="10"></div>
<div class="ctl"><label for="f-source">Data source</label>
<select id="f-source"><option value="all">All rows</option><option value="form">Form submissions only</option><option value="bulk">Bulk logs only (imports)</option></select></div>
<div class="ctl"><label for="f-goal">Players chasing</label>
<select id="f-goal"><option value="all">Any goal</option><option value="exclude_rare">Not chasing Blue/Black</option><option value="only_rare">Chasing Blue/Black</option></select></div>
<label class="check" for="f-flag"><input id="f-flag" type="checkbox"> Drop rows with data-quality flags</label>
</div>
<div class="map-shell deco">
<div class="map-top">
<div class="cond-chips" id="cond-chips"><span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span></div>
<div class="btnrow"><button type="button" id="btn-best">Show top routes for this outcome</button><button type="button" id="btn-clear">Clear selection</button></div>
</div>
<div class="map-scroll"><svg id="map" role="img" aria-label="Route map"></svg></div>
<div class="map-foot">
<div class="sel-summary" id="sel-summary"></div>
<div class="legend" id="legend"></div>
</div>
</div>
<div id="best-routes"></div>
</section>
</div>
<div class="tabpanel" id="panel-rare" role="tabpanel" aria-labelledby="tab-rare" hidden>
<section id="rare" aria-labelledby="h-rare">
<div class="section-head">
<span class="eyebrow">Blue &amp; Black</span>
<h2 id="h-rare">The rare dragons</h2>
<p class="muted small">Two separate rolls. The meadow Blue can join the Orange and Brown after you turn down the valley Red. The tree's shadow option leads to a Blue and then a Black.</p>
</div>
<div class="grid2">
<div class="panel"><h3>Does the Blue show up in the meadow?</h3><p class="small muted">Share of meadow visits where a Blue was attempted, by who logged the run. The game cannot know which dragon a player is chasing, so gaps between these bars come from how people report, not from the game.</p><div class="chart" id="ch-blue-strata"></div></div>
<div class="panel"><h3>Does the shadow show up at the tree?</h3><p class="small muted">Share of tree climbs where the shadow option led to a Blue and/or Black.</p><div class="chart" id="ch-shadow-strata"></div></div>
</div>
<div class="grid2">
<div class="panel"><h3>What changes the Blue's appearance, once reporting bias is held fixed?</h3><p class="small muted">Adjusted odds ratios from one logistic model: route choices plus data source and chase goal. Bars that cross 1 mean no detectable effect.</p><div class="chart" id="ch-model-blue"></div><p class="small muted" id="model-blue-note"></p></div>
<div class="panel"><h3>What changes the shadow's appearance?</h3><p class="small muted">Same approach for the shadow. With so few shadows, intervals are wide.</p><div class="chart" id="ch-model-shadow"></div><p class="small muted" id="model-shadow-note"></p></div>
</div>
<div class="grid2">
<div class="panel"><h3>Day by day (form submissions)</h3><p class="small muted">Bulk imports carry no dates, so they are left out here. Dots are sized by the number of runs, and whiskers show 95% intervals.</p><div class="chart" id="ch-daily"></div></div>
<div class="panel"><h3>Bonding once you reach them</h3><div class="chart" id="ch-rare-bond"></div>
<details class="fold"><summary>Step-by-step survival inside the encounter (from the community PDF)</summary><div id="pdf-steps"></div></details>
</div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-dragons" role="tabpanel" aria-labelledby="tab-dragons" hidden>
<section id="register" aria-labelledby="h-register">
<div class="section-head">
<span class="eyebrow">Bonded dragons, as riders registered them</span>
<h2 id="h-register">The bonded dragons</h2>
<p class="muted small">Every bonded dragon we could collect, sorted by colour, then tail, then lineage, then oldest first. Most come from ClumsyBadger's Unofficial Dragon Register form, and the rest from dragonkind.com result pages linked in the megathreads. Rider names and photos are left out. Misspelled lineages are corrected when they are within two letters of a lineage seen at least three times for the same colour. The original spelling is kept in the notes.</p>
</div>
<div class="data-status" id="reg-status"></div>
<div class="grid2">
<div class="panel"><h3>Colour × tail</h3><div class="tbl-wrap" id="reg-matrix"></div></div>
<div class="panel"><h3>Lineages</h3><div class="tbl-wrap" id="reg-lineages" style="max-height:340px"></div></div>
</div>
<div class="controls">
<div class="ctl"><label for="reg-colour">Colour</label><select id="reg-colour"></select></div>
<div class="ctl"><label for="reg-tail">Tail</label><select id="reg-tail"></select></div>
<div class="ctl"><label for="reg-lineage">Lineage</label><select id="reg-lineage"></select></div>
<div class="ctl"><label for="reg-sex">Sex</label><select id="reg-sex"></select></div>
<div class="ctl"><label for="reg-q">Search names</label><input id="reg-q" type="search" placeholder="Dragon or lineage" style="font:inherit;font-size:var(--step--1);padding:6px 10px;border:1px solid var(--line);border-radius:5px;background:var(--raised);color:var(--ink)"></div>
<div class="ctl"><span class="lbl">View</span><div class="seg" id="reg-view"><button type="button" data-v="cards" aria-pressed="true">Cards</button><button type="button" data-v="table" aria-pressed="false">Table</button></div></div>
<div class="btnrow" style="align-self:end"><button type="button" id="reg-copy">Copy as CSV</button><label class="filebtn" for="reg-upload">Load a newer register export…<input id="reg-upload" type="file" accept=".xlsx,.csv" hidden></label></div>
<span class="small muted" id="reg-count" style="align-self:center"></span>
</div>
<div class="gallery" id="reg-gallery"></div>
<div class="tbl-wrap" id="reg-table" style="max-height:640px" hidden></div>
</section>
<section id="bondrates" aria-labelledby="h-dragons">
<div class="section-head">
<span class="eyebrow">All six colours</span>
<h2 id="h-dragons">Every dragon: how often the attempt ends in a bond</h2>
<p class="muted small">A run counts here when the player reached that dragon's bonding encounter and the form shows Bonded or Incinerated. Many players die on purpose to reroll, which drags the raw rate down. "Wanted it" keeps only runs where the player said they were after that colour, or any dragon.</p>
</div>
<div class="chart panel" id="ch-encounters"></div>
<div class="grid2">
<div class="panel"><h3>The two Greens</h3><div id="green-rescue"></div></div>
<div class="panel"><h3>First sighting: what the game rolls</h3><p class="small muted">Which dragon met the cadet first, by company and direction. Pools come from the community PDF, and cells outside them are counted as data-quality flags.</p><div class="tbl-wrap" id="tbl-first"></div></div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-deep" role="tabpanel" aria-labelledby="tab-deep" hidden>
<section id="findings" aria-labelledby="h-findings">
<div class="section-head">
<span class="eyebrow">What the data supports</span>
<h2 id="h-findings">Findings</h2>
<p class="muted small">These sentences are generated from the current data and filters, so they update when the data does. "Lead" means a pattern worth testing that is not yet established.</p>
</div>
<div class="findings" id="findings-list"></div>
</section>
<section id="routes" aria-labelledby="h-routes">
<div class="section-head">
<span class="eyebrow">Ranked</span>
<h2 id="h-routes">Route table</h2>
<p class="muted small">A route here means every choice up to the hour. Routes are ranked by the lower end of their 95% interval, so a route needs both a high rate and enough runs to rank high. Each route is compared with every other route that could reach the same outcome. "Adjusted" holds data source and chase goal fixed (Mantel–Haenszel). q-values correct for testing many routes at once.</p>
</div>
<div class="controls"><div class="ctl"><label for="rt-target">Outcome</label><select id="rt-target"></select></div><div class="ctl"><label for="rt-min">Minimum runs per route</label><input id="rt-min" type="number" min="1" max="200" value="10"></div><p class="small muted" id="rt-note" style="align-self:center"></p></div>
<div class="tbl-wrap" id="tbl-routes"></div>
</section>
<section id="factors" aria-labelledby="h-factors">
<div class="section-head">
<span class="eyebrow">One choice at a time</span>
<h2 id="h-factors">Factor explorer</h2>
<p class="muted small">Each row compares runs with that answer against runs with any other answer to the same question, using Fisher's exact test. These comparisons are unadjusted, so check the adjusted models above before trusting a difference. Shaded rows have q &lt; 0.05 after correcting for every comparison in this table.</p>
</div>
<div class="controls"><div class="ctl"><label for="fx-outcome">Outcome</label><select id="fx-outcome"></select></div><div class="ctl"><label for="fx-factor">Question</label><select id="fx-factor"></select></div></div>
<div class="grid2"><div class="tbl-wrap" id="tbl-factors"></div><div class="panel"><h3>Odds ratios</h3><div class="chart" id="ch-factor"></div></div></div>
</section>
<section id="quality" aria-labelledby="h-quality">
<div class="section-head">
<span class="eyebrow">Read this before quoting a number</span>
<h2 id="h-quality">Data quality and bias</h2>
</div>
<div class="grid3" id="quality-panels"></div>
</section>
<section id="methods" aria-labelledby="h-methods" class="method">
<div class="section-head"><span class="eyebrow">How every number is made</span><h2 id="h-methods">Methods</h2></div>
<div class="grid2">
<div class="method">
<h3>1. From form answers to runs</h3>
<p>Each row of the "Threshing Routes" form (and each row pasted in from players' own logs) is one threshing run. The page reads the raw export and codes every row with the same fixed rules, which are visible in <code>engine.js</code>:</p>
<ul>
<li><b>Source.</b> Rows with a real timestamp are form submissions. Rows labelled "Data Import", "Manual Upload" or "Historical import" were bulk-pasted from players' own run logs and are called <i>bulk logs</i> here.</li>
<li><b>Cadet encounter.</b> Split into the scream choice (help, investigate and leave, or ignore) and its resolution (killed the bullies, squadmate's revenge, left them to the dragons, tourniquet, left the cadet, took their weapons). The fork in the road only exists after helping, so other branches are coded "(no fork)".</li>
<li><b>Encounter branch.</b> A tree run with a Blue or Black recorded took the shadow. A tree run with Greens recorded descended slowly, and one with only a Red descended quickly. A valley run with an Orange, Brown or Blue recorded (or a Red marked "Changed my mind") passed the Red and reached the meadow.</li>
<li><b>Outcome.</b> Bonded to the one dragon marked "Bonded!". Otherwise incinerated by the last dragon marked "Incinerated" in encounter order, or died before the hour. "Saved by another" on the Greens plus a bonded Orange or Brown counts as a rescue bond.</li>
<li><b>Flags.</b> Rows are flagged, not deleted, when answers contradict each other: several directions or wings, Greens in the valley, two bonds, or a first sighting outside the documented pool. You can drop flagged rows with the checkbox above the map.</li>
</ul>
<h3>2. Rates and their uncertainty</h3>
<p>A rate is k events out of n runs that could have had that event. The denominator matters. The meadow Blue rate divides by runs that reached the meadow, not by all runs. Intervals are 95% Wilson score intervals, which behave well for small n and for rates near 0%:</p>
<div class="formula">p̂ = k / n, z = 1.96
centre = (p̂ + z²/2n) / (1 + z²/n)
half = z·√(p̂(1−p̂)/n + z²/4n²) / (1 + z²/n)
CI = centre ± half</div>
<p>With 0 events in n runs, the upper end is still informative. For example, 0 shadows in 367 bulk-log tree climbs gives an upper bound near 1.0%.</p>
</div>
<div class="method">
<h3>3. Comparing choices</h3>
<p>For one answer against the rest, the 2×2 table is [a b; c d] = [event, no event] × [this answer, other answers].</p>
<div class="formula">OR = (a·d) / (b·c)
95% CI = exp( ln OR ± 1.96·√(1/a + 1/b + 1/c + 1/d) )
(0.5 is added to every cell when any cell is 0)
p = Fisher's exact test, two-sided
q = Benjamini–Hochberg: sort p, q(i) = min over j≥i of p(j)·m/j</div>
<p>An odds ratio of 2 means the odds of the outcome are twice as high with that answer. q-values control the false-discovery rate. With dozens of comparisons, some p &lt; 0.05 results are expected by chance, so a "real" difference needs q &lt; 0.05.</p>
<h3>4. Adjusting for who reports what</h3>
<p>Players chasing a Blue log runs where they saw a Blue far more often than other players do. Bulk loggers record every run, including dull ones. To separate route effects from reporting effects, the page fits a logistic regression with every route choice plus data source and chase goal:</p>
<div class="formula">logit P(event) = β₀ + Σ βⱼ·xⱼ (x = 0/1 indicators; reference = most common answer)
fitted by Newton–Raphson with a small ridge penalty λ = 1 on the slopes
adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ)</div>
<p>The ridge penalty keeps estimates finite when an answer has 0 events. It shrinks extreme odds ratios slightly toward 1, which makes the model more cautious. Route rankings use the Mantel–Haenszel odds ratio across four strata (bulk logs, form runs chasing Blue, chasing Black, everything else) for the same reason.</p>
<h3>5. What this data cannot tell you</h3>
<ul>
<li>It is self-reported and self-selected. Runs worth bragging about are over-represented, and that inflates every rare-dragon rate. Bulk logs are the least selected rows.</li>
<li>Runs are not independent. One player may log dozens of runs, and the form has no player ID, so intervals are somewhat too narrow.</li>
<li>The form records only stage-level choices. It does not record how you reacted to the first dragon (lower eyes, hold still…) or most choices inside an encounter, so route claims that depend on those cannot be tested here.</li>
<li>The form records dragons you <i>attempted</i>. A player who saw the Blue but chose the Orange would not record the Blue, so Blue sightings are slightly undercounted.</li>
<li>Step-by-step survival inside an encounter comes from the community PDF, which coded the free-text answers by hand. It is shown as published and cannot be recomputed here.</li>
</ul>
</div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-share" role="tabpanel" aria-labelledby="tab-share" hidden>
<section id="data-sec" aria-labelledby="h-data">
<div class="section-head"><span class="eyebrow">Where the numbers come from</span><h2 id="h-data">Data</h2></div>
<div class="data-status" id="data-status"><span class="loading">Loading data…</span></div>
<div class="btnrow"><label class="filebtn" for="upload">Load a newer route export…<input id="upload" type="file" accept=".xlsx,.csv" hidden></label><button id="btn-reset-data" type="button" hidden>Back to bundled data</button></div>
</section>
<section id="share" aria-labelledby="h-share">
<div class="section-head"><span class="eyebrow">Open by design</span><h2 id="h-share">Share &amp; reproduce</h2>
<p class="muted small">Everything on this page is recomputed in your browser from the raw form export. To update it, download the latest responses sheet (File → Download → Microsoft Excel) and load it with "Load a newer export" at the top. Column order does not matter, because questions are matched by their wording.</p></div>
<div class="grid2">
<div class="panel"><h3>Copy the outputs</h3>
<div class="btnrow"><button type="button" id="cp-reddit" class="primary">Copy Reddit post (Markdown)</button><button type="button" id="cp-csv">Copy coded runs (CSV)</button><button type="button" id="cp-json">Copy all results (JSON)</button></div>
<p class="small muted">The Reddit post is written from the current numbers and filters.</p></div>
<div class="panel"><h3>Read the code</h3>
<div class="btnrow"><button type="button" data-src="engine.js">engine.js (all rules and statistics)</button><button type="button" data-src="app.js">app.js (this page)</button><button type="button" data-src="python/clean.py">clean.py</button><button type="button" data-src="python/analyze.py">analyze.py</button><button type="button" data-src="python/stats_core.py">stats_core.py</button><button type="button" data-src="register.js">register.js</button><button type="button" data-src="README.md">README</button></div>
<p class="small muted">The Python files are an independent second implementation. The test scripts confirm that both produce identical coded runs and identical odds ratios, p-values and model estimates.</p>
<pre id="srcview" hidden></pre></div>
</div>
</section>
</div>
</main>
</div>
<footer><div class="wrap"><p>Data: the community "Threshing Routes" Google Form and spreadsheet compiled by u/ClumsyBadger, with percentages in the route PDF by u/ClumsyBadger, u/Old_Regular3018 and u/Smart_Trifle_2099. This is an unofficial fan analysis, not affiliated with the Dragonkind site or its authors. A 10% "chaos" chance of incineration on any choice has been described by the author, so no route guarantees a bond.</p></div></footer>
<div id="tip" hidden></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="engine.js"></script>
<script src="register.js"></script>
<script src="app.js"></script>
<script src="valley.js"></script>
<script src="ui.js"></script>
+204
View File
@@ -0,0 +1,204 @@
/* register.js — the Dragon Register section: clean, merge, sort and display bonded dragons.
* Works in the browser (window.DragonRegister) and in Node (module.exports) for testing. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonRegister = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const COLOUR_ORDER = ["Red", "Orange", "Brown", "Green", "Blue", "Black"];
const TAILS = ["Clubtail", "Daggertail", "Morningstartail", "Scorpiontail", "Swordtail"];
const KEYS = {
timestamp: ["timestamp"], cadet: ["cadet name"], wing: ["assignment - wing"], section: ["assignment - section"],
squad: ["assignment - squad"], name: ["dragon", "name"], lineage: ["lineage"], colour: ["colour"], tail: ["tail"],
sex: ["sex"], age: [/\bage\b/],
};
const str = (v) => (v === null || v === undefined ? null : String(v).trim() || null);
const title = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1).toLowerCase() : s);
function findCols(headers) {
const C = {};
for (const [k, words] of Object.entries(KEYS)) {
const h = headers.find((x) => words.every((w) => (w instanceof RegExp ? w.test(String(x).toLowerCase()) : String(x).toLowerCase().includes(w))) && !(k === "name" && /cadet/i.test(x)));
if (h) C[k] = h;
}
return C;
}
function tailOf(v) {
const t = (str(v) || "").toLowerCase().replace(/[^a-z]/g, "");
return TAILS.find((x) => x.toLowerCase() === t || x.toLowerCase().replace("tail", "") === t) || (t ? title(t) : "Unknown");
}
function lev(a, b) {
const m = a.length, n = b.length, d = Array.from({ length: m + 1 }, (_, i) => [i, ...new Array(n).fill(0)]);
for (let j = 1; j <= n; j++) d[0][j] = j;
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
return d[m][n];
}
const lkey = (s) => (str(s) || "").toLowerCase().replace(/[^a-z]/g, "");
// rows: raw register form rows; extra: dragons from other sources (already structured)
function build(raw) {
const C = findCols(raw.headers || Object.keys(raw.rows[0] || {}));
const items = raw.rows.map((r, i) => ({
source: "Register form", source_url: null, submitted: str(r[C.timestamp]),
cadet: str(r[C.cadet]), wing: str(r[C.wing]), section: str(r[C.section]), squad: str(r[C.squad]),
name: str(r[C.name]), lineage_raw: str(r[C.lineage]), colour: title(str(r[C.colour])), tail: tailOf(r[C.tail]),
sex: title(str(r[C.sex])), age: parseInt(r[C.age], 10), flags: [],
}));
(raw.extra || []).forEach((e) => items.push({
source: "Reddit (dragonkind.com result page)", source_url: e.url, submitted: null, cadet: null, wing: null, section: null, squad: null,
name: str(e.name), lineage_raw: str(e.lineage), colour: title(e.colour), tail: tailOf(e.tail), sex: title(e.sex), age: parseInt(e.age, 10), flags: [],
}));
// lineage spelling: spellings used 3+ times are canonical; others snap to a canonical of the same colour within 2 edits
const counts = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (k) counts[k] = (counts[k] || 0) + 1; });
// spellings confirmed by an official dragonkind.com result page also count as canonical
const official = new Set(items.filter((it) => it.source_url).map((it) => lkey(it.lineage_raw)));
const canon = Object.keys(counts).filter((k) => counts[k] >= 3 || official.has(k));
const colourOfKey = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (canon.includes(k)) (colourOfKey[k] = colourOfKey[k] || new Set()).add(it.colour); });
items.forEach((it) => {
let k = lkey(it.lineage_raw);
if (k && !canon.includes(k)) {
const best = canon.filter((c) => colourOfKey[c] && colourOfKey[c].has(it.colour)).map((c) => [c, lev(k, c)]).sort((a, b) => a[1] - b[1])[0];
if (best && best[1] <= 2) { it.flags.push(`lineage spelled "${it.lineage_raw}"`); k = best[0]; }
else it.flags.push("lineage seen fewer than 3 times");
}
it.lineage = k ? title(k) : "Unknown";
if (!Number.isFinite(it.age)) { it.age = null; it.flags.push("age missing"); }
if (!COLOUR_ORDER.includes(it.colour)) it.flags.push("unrecognised colour");
});
// a lineage should belong to one colour
const lc = {};
items.forEach((it) => (lc[it.lineage] = lc[it.lineage] || new Set()).add(it.colour));
items.forEach((it) => { if (lc[it.lineage].size > 1) it.flags.push(`lineage also recorded under ${[...lc[it.lineage]].filter((c) => c !== it.colour).join("/")}`); });
// duplicates: same dragon name + colour + tail + sex + age + lineage
const seen = new Map(), out = [];
items.forEach((it) => {
const key = [it.name && it.name.toLowerCase(), it.colour, it.tail, it.sex, it.age, it.lineage].join("|");
if (seen.has(key)) {
const first = seen.get(key);
first.duplicates = (first.duplicates || 0) + 1;
if (!first.also.includes(it.source) && it.source !== first.source) first.also.push(it.source);
if (it.source_url && !first.source_url) first.source_url = it.source_url;
return;
}
it.also = []; seen.set(key, it); out.push(it);
});
out.sort(compare);
return out;
}
function compare(a, b) {
const ci = (c) => (COLOUR_ORDER.indexOf(c) + 1 || 99);
return ci(a.colour) - ci(b.colour) || a.tail.localeCompare(b.tail) || a.lineage.localeCompare(b.lineage) ||
(b.age ?? -1) - (a.age ?? -1) || (a.name || "").localeCompare(b.name || "");
}
// ---------------------------------------------------------------- browser UI
function mount(opts) {
const $ = (q) => document.querySelector(q);
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const st = { all: [], label: "", f: { colour: "", tail: "", lineage: "", sex: "", q: "" }, bundled: null };
function load(raw, label) { st.all = build(raw); st.label = label; st.f = { colour: "", tail: "", lineage: "", sex: "", q: "" }; ["reg-colour", "reg-tail", "reg-lineage", "reg-sex", "reg-q"].forEach((id) => ($("#" + id).value = "")); render(); }
const filtered = () => st.all.filter((d) => (!st.f.colour || d.colour === st.f.colour) && (!st.f.tail || d.tail === st.f.tail) &&
(!st.f.lineage || d.lineage === st.f.lineage) && (!st.f.sex || d.sex === st.f.sex) &&
(!st.f.q || [d.name, d.lineage].join(" ").toLowerCase().includes(st.f.q.toLowerCase())));
const sw = (c) => `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:var(${DV[c] || "--faint"});margin-right:6px;vertical-align:-1px;box-shadow:0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent)"></span>`;
const median = (a) => { const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : null; };
function fillSelect(id, values, label) {
const el = $("#" + id), cur = el.value;
el.innerHTML = `<option value="">${label}</option>` + values.map((v) => `<option>${esc(v)}</option>`).join("");
el.value = values.includes(cur) ? cur : "";
}
function render() {
const all = st.all, rows = filtered();
const colours = COLOUR_ORDER.filter((c) => all.some((d) => d.colour === c));
fillSelect("reg-colour", colours, "All colours");
fillSelect("reg-tail", TAILS.filter((t) => all.some((d) => d.tail === t)), "All tails");
fillSelect("reg-lineage", [...new Set(all.filter((d) => !st.f.colour || d.colour === st.f.colour).map((d) => d.lineage))].sort(), "All lineages");
fillSelect("reg-sex", [...new Set(all.map((d) => d.sex).filter(Boolean))].sort(), "Any sex");
const src = {}; all.forEach((d) => (src[d.source] = (src[d.source] || 0) + 1));
$("#reg-status").innerHTML = `<b>${all.length}</b> bonded dragons · ${Object.entries(src).map(([k, v]) => `${esc(k)} ${v}`).join(" · ")} · <span class="pill">${esc(st.label)}</span>`;
// colour x tail matrix
$("#reg-matrix").innerHTML = `<table><thead><tr><th>Colour</th>${TAILS.map((t) => `<th class="num">${t.replace("tail", "")}</th>`).join("")}<th class="num">Total</th></tr></thead><tbody>${colours.map((c) => {
const cs = rows.filter((d) => d.colour === c);
return `<tr><td>${sw(c)}${c}</td>${TAILS.map((t) => { const n = cs.filter((d) => d.tail === t).length; return `<td class="num"${n ? "" : ' style="color:var(--faint)"'}>${n || "·"}</td>`; }).join("")}<td class="num"><b>${cs.length}</b></td></tr>`;
}).join("")}</tbody></table>`;
// lineages
const lin = {};
rows.forEach((d) => { const k = d.colour + "|" + d.lineage; (lin[k] = lin[k] || []).push(d); });
$("#reg-lineages").innerHTML = `<table><thead><tr><th>Colour</th><th>Lineage</th><th class="num">Dragons</th><th class="num">Ages</th><th class="num">Median</th><th class="num">F / M</th></tr></thead><tbody>${Object.keys(lin).sort((a, b) => COLOUR_ORDER.indexOf(a.split("|")[0]) - COLOUR_ORDER.indexOf(b.split("|")[0]) || a.localeCompare(b)).map((k) => {
const g = lin[k], ages = g.map((d) => d.age).filter(Number.isFinite), [c, l] = k.split("|");
return `<tr><td>${sw(c)}${c}</td><td>${esc(l)}</td><td class="num">${g.length}</td><td class="num">${ages.length ? Math.min(...ages) + "–" + Math.max(...ages) : "–"}</td><td class="num">${ages.length ? median(ages) : "–"}</td><td class="num">${g.filter((d) => d.sex === "Female").length} / ${g.filter((d) => d.sex === "Male").length}</td></tr>`;
}).join("")}</tbody></table>`;
// main table, grouped by colour then tail
let lastGroup = "";
$("#reg-table").innerHTML = rows.length ? `<table><thead><tr><th>Colour</th><th>Tail</th><th>Lineage</th><th class="num">Age</th><th>Sex</th><th>Dragon</th><th>Rider's assignment</th><th>Source</th><th>Notes</th></tr></thead><tbody>${rows.map((d) => {
const g = d.colour + "|" + d.tail, head = g !== lastGroup; lastGroup = g;
return `<tr${head ? ' style="border-top:2px solid var(--line)"' : ""}><td>${sw(d.colour)}${esc(d.colour)}</td><td>${esc(d.tail)}</td><td>${esc(d.lineage)}</td><td class="num">${d.age ?? "–"}</td><td>${esc(d.sex)}</td><td><b>${esc(d.name)}</b></td><td class="small">${[d.wing, d.section, d.squad].filter(Boolean).map(esc).join(" · ") || "–"}</td><td class="small">${[d.source === "Register form" || d.also.includes("Register form") ? "form" : null, d.source_url ? `<a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : null].filter(Boolean).join(" + ")}${d.duplicates ? ` <span class="muted">(${d.duplicates + 1} entries merged)</span>` : ""}</td><td class="small muted">${esc(d.flags.join("; "))}</td></tr>`;
}).join("")}</tbody></table>` : `<p class="small muted" style="padding:12px">No dragons match these filters.</p>`;
$("#reg-count").textContent = `${rows.length} shown`;
renderGallery(rows);
}
// tail glyphs (24-unit box), drawn as simple original marks
const TAIL_GLYPH = {
Clubtail: '<path d="M5 19 L14 10" stroke-width="2.4"/><circle cx="16" cy="8" r="3.6" stroke="none" fill="currentColor"/>',
Daggertail: '<path d="M5 19 L8.5 15.5" stroke-width="2.4"/><path d="M7 14 L10 17" stroke-width="1.8"/><path d="M8.5 15.5 L19 5 L13.5 15.5 Z" fill="currentColor" stroke="none"/>',
Morningstartail: '<path d="M5 19 L11 13" stroke-width="2.4"/><circle cx="14.5" cy="9.5" r="3.4" fill="currentColor" stroke="none"/><path d="M14.5 3.5v2.5M14.5 13v2.5M8.5 9.5h2.5M18 9.5h2.5M10.3 5.3l1.8 1.8M16.9 11.9l1.8 1.8M18.7 5.3l-1.8 1.8M12.1 11.9l-1.8 1.8" stroke-width="1.6"/>',
Scorpiontail: '<path d="M5 19 C5 10 11 5.5 17 6.5 C20.5 7.2 20.5 11.5 17.5 12.5" stroke-width="2.2"/><path d="M17.5 12.5 L14.5 11 L16.2 15 Z" fill="currentColor" stroke="none"/>',
Swordtail: '<path d="M5 19 L19 5" stroke-width="2.6"/><path d="M6.5 13.5 L10.5 17.5" stroke-width="2"/><path d="M19 5 L16 6 L18 8 Z" fill="currentColor" stroke="none"/>',
};
function emblem(d) {
const col = cssVar(DV[d.colour] || "--faint");
const rgbv = (col.match(/[0-9a-f]{2}/gi) || ["80", "80", "80"]).slice(0, 3).map((h) => parseInt(h, 16));
const lum = col.startsWith("#") ? (0.299 * rgbv[0] + 0.587 * rgbv[1] + 0.114 * rgbv[2]) / 255 : 0.4;
const ink = lum > 0.6 ? "#14181d" : "#f4f1ea";
return `<svg viewBox="0 0 64 64" aria-hidden="true"><defs><radialGradient id="g${d.colour}" cx="35%" cy="30%" r="80%"><stop offset="0" stop-color="${col}" stop-opacity="0.85"/><stop offset="1" stop-color="${col}"/></radialGradient></defs>
<path d="M32 3 L57 17 L57 47 L32 61 L7 47 L7 17 Z" fill="url(#g${d.colour})" stroke="var(--ink)" stroke-opacity="0.25"/>
<path d="M32 9 L52 20 L52 44 L32 55 L12 44 L12 20 Z" fill="none" stroke="${ink}" stroke-opacity="0.35"/>
<g transform="translate(16 16) scale(1.35)" stroke="${ink}" fill="none" stroke-linecap="round" style="color:${ink}">${TAIL_GLYPH[d.tail] || ""}</g></svg>`;
}
function renderGallery(rows) {
const g = $("#reg-gallery");
if (!g) return;
const byC = {};
rows.forEach((d) => (byC[d.colour] = byC[d.colour] || []).push(d));
g.innerHTML = Object.keys(byC).sort((a, b) => COLOUR_ORDER.indexOf(a) - COLOUR_ORDER.indexOf(b)).map((c) => `
<div class="gal-group"><h3>${sw(c)}${esc(c)} dragons <span class="small muted" style="font-family:var(--font-body);letter-spacing:0">${byC[c].length}</span></h3>
<div class="cards">${byC[c].map((d) => `<div class="dcard" style="--dc: var(${DV[d.colour] || "--accent"})" title="${esc(d.flags.join("; "))}"><span class="age">${d.age ?? "?"} yrs</span>${emblem(d)}<span class="nm">${esc(d.name)}</span><span class="meta">${esc(d.sex || "")} ${esc(d.tail)}<br>${esc(d.lineage)} lineage${d.source_url ? `<br><a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : ""}</span></div>`).join("")}</div></div>`).join("") || `<p class="small muted">No dragons match these filters.</p>`;
}
document.querySelectorAll("#reg-view button").forEach((b) => b.addEventListener("click", () => {
document.querySelectorAll("#reg-view button").forEach((x) => x.setAttribute("aria-pressed", x === b));
$("#reg-gallery").hidden = b.dataset.v !== "cards";
$("#reg-table").hidden = b.dataset.v !== "table";
}));
function csv() {
const cols = ["colour", "tail", "lineage", "age", "sex", "name", "wing", "section", "squad", "source", "source_url", "lineage_raw", "flags"];
const q = (v) => { if (v === null || v === undefined) return ""; const s = Array.isArray(v) ? v.join("; ") : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...filtered().map((d) => cols.map((c) => q(d[c])).join(","))].join("\n");
}
[["reg-colour", "colour"], ["reg-tail", "tail"], ["reg-lineage", "lineage"], ["reg-sex", "sex"]].forEach(([id, k]) =>
$("#" + id).addEventListener("change", (e) => { st.f[k] = e.target.value; if (k === "colour") st.f.lineage = ""; render(); }));
$("#reg-q").addEventListener("input", (e) => { st.f.q = e.target.value.trim(); render(); });
$("#reg-copy").addEventListener("click", () => opts.copy(csv(), "register CSV"));
$("#reg-upload").addEventListener("change", async (e) => {
const f = e.target.files[0]; if (!f) return;
try {
const wb = XLSX.read(await f.arrayBuffer(), { type: "array", cellDates: true });
const ws = wb.Sheets[wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0]];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
load({ headers, rows, extra: st.bundled.extra }, `uploaded ${f.name} + Reddit result pages`);
opts.toast(`Loaded ${rows.length} register rows`);
} catch (err) { opts.toast("That file could not be read. Export the register sheet as .xlsx or .csv."); console.error(err); }
e.target.value = "";
});
fetch("data/register.json").then((r) => r.json()).then((raw) => { st.bundled = raw; load(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`); })
.catch((e) => ($("#reg-status").textContent = "The register data could not load."));
}
return { build, compare, mount, COLOUR_ORDER, TAILS, lev };
});
+194
View File
@@ -0,0 +1,194 @@
/* ui.js — tabs, hero art, the plain-language overview and the illustrated valley map.
* Reads the same coded runs and results as the rest of the page (window.ThreshAtlas.state). */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p, d = 0) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(d) + "%");
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const oneIn = (p) => (p > 0 ? Math.max(1, Math.round(1 / p)) : null);
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function rgb(c) {
c = (c || "").trim();
if (c.startsWith("#")) { const h = c.length === 4 ? [...c.slice(1)].map((x) => x + x).join("") : c.slice(1); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
const m = c.match(/\d+(\.\d+)?/g); return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
const mix = (a, b, t) => { const A = rgb(a), B = rgb(b); return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`; };
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ tabs
const TABS = ["overview", "valley", "flow", "rare", "dragons", "deep", "share"];
function showTab(name, focus) {
if (!TABS.includes(name)) name = "overview";
TABS.forEach((t) => {
const on = t === name;
$("#tab-" + t).setAttribute("aria-selected", on);
$("#tab-" + t).tabIndex = on ? 0 : -1;
$("#panel-" + t).hidden = !on;
});
if (focus) $("#tab-" + name).focus();
try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ }
try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ }
if (name === "flow" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize"));
}
TABS.forEach((t, i) => {
const b = $("#tab-" + t);
b.addEventListener("click", () => showTab(t));
b.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
const j = (i + (e.key === "ArrowRight" ? 1 : TABS.length - 1)) % TABS.length;
showTab(TABS[j], true); e.preventDefault();
}
});
});
$$("[data-go]").forEach((b) => b.addEventListener("click", () => { showTab(b.dataset.go); window.scrollTo({ top: 0, behavior: "smooth" }); }));
// in-page links that point at sections inside other tabs
document.addEventListener("click", (e) => {
const a = e.target.closest('a[href^="#"]');
if (!a) return;
const id = a.getAttribute("href").slice(1);
if (TABS.includes(id)) { e.preventDefault(); showTab(id); return; }
const target = document.getElementById(id);
const panel = target && target.closest(".tabpanel");
if (panel && panel.hidden) { e.preventDefault(); showTab(panel.id.replace("panel-", "")); target.scrollIntoView({ behavior: "smooth" }); }
});
window.addEventListener("hashchange", () => { const h = location.hash.slice(1); if (TABS.includes(h)) showTab(h); });
const initial = (location.hash || "").slice(1);
showTab(TABS.includes(initial) ? initial : "overview");
// ------------------------------------------------------------ hero art (original, generic silhouettes)
function drawHero() {
const svg = $("#hero-art");
svg.innerHTML = "";
const g = el("g", {}, svg);
el("path", { d: "M0 330 L120 250 L210 290 L330 200 L430 270 L560 180 L690 260 L800 210 L930 280 L1040 220 L1200 290 L1200 420 L0 420 Z", fill: "#2c1120" }, g);
el("path", { d: "M0 360 L160 300 L300 330 L470 270 L620 330 L780 285 L960 335 L1100 300 L1200 330 L1200 420 L0 420 Z", fill: "#220a17" }, g);
// tree line
const R = rng(3); let tl = "M0 420 L0 380";
for (let x = 0; x <= 1200; x += 14) { const h = 18 + R() * 30; tl += ` L${x + 7} ${392 - h} L${x + 14} ${392 - R() * 6}`; }
el("path", { d: tl + " L1200 420 Z", fill: "#16060e" }, g);
// a generic cliff-top keep, right side
const keep = el("g", { fill: "#1a0812", transform: "translate(0 40)" }, g);
el("path", { d: "M930 360 L930 250 L960 240 L990 250 L1010 236 L1040 250 L1070 232 L1100 250 L1130 245 L1150 360 Z" }, keep);
[[952, 196, 20, 58], [1000, 180, 22, 70], [1058, 190, 18, 60], [1098, 205, 16, 46]].forEach(([x, y, w, h]) => {
el("rect", { x, y, width: w, height: h }, keep);
el("path", { d: `M${x - 3} ${y} L${x + w / 2} ${y - 18} L${x + w + 3} ${y} Z` }, keep);
});
// distant riders: simple winged silhouettes
const shape = "M50 30 L18 6 L27 21 L3 16 L25 32 Z M50 30 L82 6 L73 21 L97 16 L75 32 Z M37 30 Q50 23 63 30 Q50 37 37 30 Z M63 30 L76 26 L80 28 L73 31 Z M37 30 Q24 37 10 34 Q22 33 36 31 Z";
[[700, 70, 0.9, 0.9], [560, 120, 0.55, 0.7], [820, 130, 0.42, 0.55], [380, 95, 0.32, 0.45]].forEach(([x, y, s, o]) =>
el("path", { d: shape, transform: `translate(${x} ${y}) scale(${s})`, fill: "#0f040a", "fill-opacity": o }, g));
const em = $("#embers");
if (em && !em.childElementCount) {
const R2 = rng(11);
for (let i = 0; i < 26; i++) {
const e = document.createElement("i");
e.style.left = (R2() * 100).toFixed(1) + "%";
e.style.animationDuration = (6 + R2() * 7).toFixed(1) + "s";
e.style.animationDelay = (-R2() * 12).toFixed(1) + "s";
const sz = (2 + R2() * 3).toFixed(1); e.style.width = e.style.height = sz + "px";
if (matchMedia("(prefers-reduced-motion: reduce)").matches) e.style.top = (10 + R2() * 80).toFixed(1) + "%";
em.appendChild(e);
}
}
}
drawHero();
// ------------------------------------------------------------ overview
function stratum(c, prefix) { const e = Object.entries(c.by_stratum).find(([k]) => k.startsWith(prefix)); return e ? e[1] : null; }
function dots(k, n, color, total = 100) {
const p = n ? k / n : 0, filled = p * total;
const cols = 20, r = 4, gap = 11, rows = Math.ceil(total / cols);
const svg = el("svg", { viewBox: `0 0 ${cols * gap} ${rows * gap}`, role: "img", "aria-label": `${pct(p, 1)} shown as ${total} dots` });
for (let i = 0; i < total; i++) {
const x = (i % cols) * gap + gap / 2, y = Math.floor(i / cols) * gap + gap / 2;
const on = i < Math.floor(filled), part = i === Math.floor(filled) && filled % 1 > 0.05;
el("circle", { cx: x, cy: y, r, fill: on ? color : "none", stroke: on || part ? color : cssVar("--line"), "stroke-width": 1.2, "fill-opacity": part ? 0.35 : 1 }, svg);
if (part) el("circle", { cx: x, cy: y, r: r * Math.sqrt(filled % 1), fill: color }, svg);
}
return svg.outerHTML;
}
function renderOverview(state) {
const r = state.res;
const reach = r.factors.reach_hour.overall;
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratum(cb, "Bulk"), bulkS = stratum(cs, "Bulk");
const blueSeen = bulkB && bulkB.n >= 30 ? bulkB : cb.overall;
const shadow = bulkS && bulkS.n >= 30 ? bulkS : cs.overall;
const encB = r.encounters.find((e) => e.context === "Blue (meadow)").overall;
const encK = r.encounters.find((e) => e.context === "Black (shadow)").overall;
const shadowP = shadow.k === 0 ? shadow.hi : shadow.p;
const tag = (txt) => `<span class="how">${txt}</span>`;
const cards = [
{ c: "--accent", big: pct(reach.p), what: "reach the hour alive", how: `${reach.k.toLocaleString()} of ${reach.n.toLocaleString()} logged runs made it past the cadets to the tree-or-valley choice.`, w: reach },
{ c: DV.Blue, big: `1 in ${oneIn(blueSeen.p)}`, what: "meadow visits has a Blue", how: blueSeen === bulkB ? `From riders who logged every run (${blueSeen.k}/${blueSeen.n}). The spreadsheet's headline says ${pct(cb.overall.p)}, inflated by lucky runs being shared more.` : `${blueSeen.k}/${blueSeen.n} meadow visits.`, w: blueSeen },
{ c: DV.Blue, big: pct(encB.p), what: "of Blue attempts end in a bond", how: `${encB.k} of ${encB.n}. Riders who reached a Blue were usually burned, even with the community's best answers.`, w: encB },
{ c: DV.Black, big: shadow.k === 0 ? `< ${pct(shadow.hi, 0)}` : `1 in ${oneIn(shadow.p)}`, what: "of tree climbs show the shadow", how: shadow === bulkS ? `Riders who logged every climb saw it ${shadow.k} times in ${shadow.n}. Form posts show more (${pct(cs.overall.p, 1)}), again because lucky runs get shared.` : `${shadow.k}/${shadow.n} tree climbs.`, w: shadow, scale: 1000 },
{ c: DV.Black, big: pct(encK.p), what: "of riders who meet the Black bond it", how: `${encK.k} of ${encK.n}. Getting there is the hard part.`, w: encK },
];
const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0);
cards.push({ c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / r.n)} of logged runs ended in fire or worse. Most were riders dying on purpose to try again.`, w: { k: dead, n: r.n }, death: true });
$("#odds").innerHTML = cards.map((c) => `<div class="odd${c.death ? " death deco" : ""}" style="--c: var(${c.c})"><span class="big">${esc(c.big)}</span><span class="what">${esc(c.what)}</span>${c.scale ? "" : dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
const pBlueRun = blueSeen.p * encB.p, pBlackRun = shadowP * encK.p;
$("#combo").innerHTML = `
<div class="odd" style="--c: var(${DV.Blue})"><span class="big">≈ 1 in ${oneIn(pBlueRun)}</span><div><div class="what">valley runs ends bonded to a Blue</div>${tag(`A Blue has to show up (about ${pct(blueSeen.p)}) and then accept you (about ${pct(encB.p)}).`)}</div></div>
<div class="odd" style="--c: var(${DV.Black})"><span class="big">${shadow.k === 0 ? "<" : "≈"} 1 in ${oneIn(pBlackRun)}</span><div><div class="what">tree climbs ends bonded to a Black</div>${tag(`The shadow has to appear (${shadow.k === 0 ? "under " + pct(shadow.hi, 1) : "about " + pct(shadow.p, 1)}) and the Black has to accept you (about ${pct(encK.p)}).`)}</div></div>`;
// journey
const fr = r.factors.reach_hour.rows;
const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l);
const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates");
const helpK = lvl("resolution", "DIED in combat");
const mb = r.models.blue_meadow;
const routeSig = mb ? mb.terms.filter((t) => ["direction", "first_sighting", "resolution", "company"].includes(t.factor) && t.p < 0.05 && !/Unsure|Unknown|Multiple/.test(t.level)) : [];
const fork = r.factors.shadow.rows.find((x) => x.factor === "post_path" && x.level === "Forest");
const rest = r.factors.shadow.rows.filter((x) => x.factor === "post_path" && x.level !== "Forest");
const restK = rest.reduce((a, x) => a + x.k, 0), restN = rest.reduce((a, x) => a + x.n, 0);
const greens = r.green_rescue;
const stops = [
{ t: "Choose company", d: "Go in alone, or with one or two squadmates.", v: alone && two ? `Alone, ${pct(alone.p)} reached the hour. With two squadmates, ${pct(two.p)} did.` : "" },
{ t: "Pick a direction", d: "East toward the roar, west toward the scent, or the forest centre.", v: routeSig.some((x) => x.factor === "direction") ? "Direction shows some link to the Blue." : "No sign that direction changes your Blue odds." },
{ t: "The first dragon", d: "A dragon finds you. Which colour is the game's roll, not yours.", v: "Keep your eyes down. This one is about surviving, not bonding.", roll: true },
{ t: "The scream", d: "Help the squadmate fighting two cadets, walk away, or ignore it and find a wounded cadet.", v: helpK ? `${helpK.n} logged runs died in the fight.` : "" },
{ t: "Fork in the road", d: "After the fight: west, deeper into the forest, or east.", v: fork && restN ? `Shadows came from "deeper" ${pct(fork.p, 1)} of the time, vs ${pct(restK / restN, 1)} otherwise. A lead, not proof.` : "" },
{ t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds Reds, Greens and the rare shadow. The valley holds Red, Orange, Brown and the meadow Blue." },
{ t: "The bonding", d: "Who is waiting is partly luck. Then every answer is a test.", v: greens.green_encounters ? `At the two Greens, ${pct((greens.rescued_orange + greens.rescued_brown) / greens.green_encounters)} were rescued by an Orange or Brown.` : "", roll: true },
];
$("#journey").innerHTML = stops.map((s, i) => `<div class="stop${s.roll ? " roll" : ""}"><span class="n">${["I", "II", "III", "IV", "V", "VI", "VII"][i]}</span><span class="t">${esc(s.t)}</span><span class="d">${esc(s.d)}</span>${s.v ? `<span class="verdict">${esc(s.v)}</span>` : ""}</div>`).join("");
const chase = stratum(cb, "Form: chasing Blue");
$("#truths").innerHTML = `
<div class="truth"><h3>Lucky runs get shared</h3><p class="small">Riders hunting a Blue logged one in ${pct(chase ? chase.p : null)} of their meadow visits. Riders who logged every run saw it in ${pct(bulkB ? bulkB.p : null)}. The game can't know what you're chasing, so the difference is who chose to write in.</p></div>
<div class="truth"><h3>No secret route to the Blue, so far</h3><p class="small">${routeSig.length ? `A few recorded choices showed a link: ${esc(routeSig.map((t) => t.term).join(", "))}.` : "Once that reporting bias is accounted for, none of the recorded choices (direction, first dragon, the cadets, company) changed how often the Blue appeared."} Choices the form doesn't record might still matter.</p></div>
<div class="truth"><h3>The right answer can still burn</h3><p class="small">Only ${pct(encB.p)} of Blue attempts bonded, about what the community's step-by-step odds predict. One death with the "right" answer doesn't mean the answer was wrong. Try again in four hours.</p></div>`;
$("#hero-tagline").textContent = `Every path through the valley, mapped from ${r.n.toLocaleString()} runs riders logged.`;
}
// tooltip shared with app.js
const tipEl = $("#tip");
function tip(e, html) {
tipEl.innerHTML = html; tipEl.hidden = false;
const r = tipEl.getBoundingClientRect();
tipEl.style.left = Math.min(window.innerWidth - r.width - 8, e.clientX + 14) + "px";
tipEl.style.top = Math.min(window.innerHeight - r.height - 8, e.clientY + 14) + "px";
}
const hideTip = () => (tipEl.hidden = true);
window.AtlasUI = {
render(state) {
renderOverview(state);
if (window.ValleyMap) window.ValleyMap.render(state);
},
showTab,
};
if (window.ThreshAtlas && window.ThreshAtlas.state && window.ThreshAtlas.state.res) window.AtlasUI.render(window.ThreshAtlas.state);
})();
+387
View File
@@ -0,0 +1,387 @@
/* valley.js — the watercolour valley map.
* Every place on the map is a step in a run. Trails are drawn from the coded runs (engine.js):
* thickness = riders who walked it, colour = share of those riders who reached the chosen outcome.
* Dashed trails are routes the community has described but the form does not record. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p, d = 0) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(d) + "%");
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
// painted-map dragon inks (darker than the UI tones so they read on gold paper)
const INK = { Red: "#b8293f", Green: "#3f7a3a", Orange: "#d06a1c", Brown: "#7a4e2e", Blue: "#2f5fb8", Black: "#2a2230" };
const PAPER = { ink: "#3b2416", halo: "#f6e6c4", trailLow: "#8a6446", death: "#c4471c" };
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function rgb(c) {
c = (c || "").trim();
if (c.startsWith("#")) { const h = c.length === 4 ? [...c.slice(1)].map((x) => x + x).join("") : c.slice(1); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
const m = c.match(/\d+(\.\d+)?/g); return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
const mix = (a, b, t) => { const A = rgb(a), B = rgb(b); return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`; };
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ places
// kind: start | way (a choice point) | dragon (a dragon is met here) | small (a choice made here)
const L = {
"comp:Alone": { x: 500, y: 736, name: "Alone", kind: "start", lab: "below", desc: "Enter the valley alone. The most common start, and the one that survives most often." },
"comp:1 Squadmate": { x: 380, y: 740, name: "One squadmate", kind: "start", lab: "below", desc: "Enter with one squadmate. You can later leave them and go on alone." },
"comp:2 Squadmates": { x: 620, y: 740, name: "Two squadmates", kind: "start", lab: "below", desc: "Enter with two squadmates. The first dragon is often deadlier for a group." },
"dir:West": { x: 190, y: 662, name: "West", sub: "toward the scent", kind: "way", lab: "left", desc: "Follow a scent west. A Brown, Green or Red finds you first." },
"dir:Center": { x: 500, y: 668, name: "Forest centre", kind: "way", lab: "right", desc: "Straight into the forest. Alone, a Red or a Brown finds you first." },
"dir:East": { x: 810, y: 662, name: "East", sub: "toward the roar", kind: "way", lab: "right", desc: "Toward the roar. Alone, a Red or an Orange finds you first. With one squadmate, a Green or an Orange." },
// first sightings (game roll)
"see:West:Red": { x: 110, y: 598, colour: "Red", kind: "dragon", first: true },
"see:West:Brown": { x: 185, y: 584, colour: "Brown", kind: "dragon", first: true },
"see:West:Green": { x: 262, y: 598, colour: "Green", kind: "dragon", first: true },
"see:Center:Red": { x: 448, y: 600, colour: "Red", kind: "dragon", first: true },
"see:Center:Brown": { x: 552, y: 600, colour: "Brown", kind: "dragon", first: true },
"see:East:Red": { x: 738, y: 598, colour: "Red", kind: "dragon", first: true },
"see:East:Orange": { x: 815, y: 584, colour: "Orange", kind: "dragon", first: true },
"see:East:Green": { x: 892, y: 598, colour: "Green", kind: "dragon", first: true },
scream: { x: 500, y: 512, name: "The scream", kind: "way", lab: "right", desc: "A scream in the trees. Help the squadmate fighting two cadets, walk away, or ignore it." },
bully: { x: 318, y: 462, name: "The bully fight", kind: "way", lab: "left", desc: "A squadmate is cornered by two cadets. Assess, even the numbers, or put yourself in the middle." },
"res:Killed the bullies yourself": { x: 222, y: 410, name: "Kill them", kind: "small", lab: "left", desc: "End the bullies yourself." },
"res:Squadmate's revenge": { x: 312, y: 398, name: "Squadmate's revenge", kind: "small", lab: "above", desc: "Let your squadmate take revenge." },
"res:Left bullies to the dragons": { x: 404, y: 410, name: "Dragons decide", kind: "small", lab: "right", desc: "Leave the bullies to the dragons." },
away: { x: 500, y: 440, name: "Walked away", kind: "small", lab: "right", desc: "Investigated the scream, then left them to it." },
wounded: { x: 684, y: 462, name: "The wounded cadet", kind: "way", lab: "right", desc: "Ignore the scream and you trip over a cadet missing a leg." },
"res:Tourniquet": { x: 600, y: 410, name: "Tourniquet", kind: "small", lab: "left", desc: "Use their belt as a tourniquet." },
"res:Left injured cadet": { x: 690, y: 398, name: "Leave them", kind: "small", lab: "above", desc: "Leave them to die." },
"res:Took their weapons": { x: 780, y: 410, name: "Take their weapons", kind: "small", lab: "right", desc: "Take their weapons and go." },
"fork:West": { x: 196, y: 336, name: "West fork", kind: "way", lab: "left", desc: "After the fight, the path splits: west." },
"fork:Forest": { x: 318, y: 318, name: "Deeper in", kind: "way", lab: "above", desc: "After the fight: deeper into the forest. Most recorded shadows came after this choice." },
"fork:East": { x: 432, y: 336, name: "East fork", kind: "way", lab: "right", desc: "After the fight, the path splits: east." },
hour: { x: 520, y: 272, name: "An hour's walk", sub: "the thorn", kind: "way", lab: "right", desc: "An hour of walking, and a thorn draws blood. No dragon bonds before this point." },
tree: { x: 316, y: 204, name: "The tallest tree", kind: "way", lab: "right", desc: "Climb for a view: a Red below, two Greens in a clearing and, very rarely, a shadow moving west." },
valley: { x: 694, y: 204, name: "Valley centre", kind: "way", lab: "left", desc: "Walk on to the valley centre." },
treeRed: { x: 168, y: 250, name: "The Red below", colour: "Red", kind: "dragon", lab: "left", desc: "Descend quickly onto a Red prowling under the tree. The hardest bond in the game." },
greens: { x: 124, y: 140, name: "Two Greens", colour: "Green", kind: "dragon", lab: "below", desc: "Two Greens in a clearing test you. A wrong answer sometimes brings an Orange or Brown to the rescue." },
stream: { x: 372, y: 142, name: "The shadow", sub: "a stream, a claw print", kind: "way", lab: "right", desc: "The rare third option at the tree. Follow the shadow west, past a stream and a claw print." },
redwood: { x: 452, y: 84, name: "Blue at the redwood", colour: "Blue", kind: "dragon", lab: "above", desc: "A Blue coiled around a redwood. Hold still and let it pass to reach the Black." },
black: { x: 262, y: 70, name: "Behind you", colour: "Black", kind: "dragon", lab: "left", desc: "A branch snaps behind you. Turn to face the threat." },
valleyRed: { x: 846, y: 250, name: "The valley Red", colour: "Red", kind: "dragon", lab: "below", desc: "A Red that has just incinerated another cadet. Most who choose to bond it succeed. Say it isn't your dragon to walk on to the meadow." },
meadow: { x: 742, y: 146, name: "The meadow", kind: "way", lab: "below", desc: "A meadow where an Orange and a Brown wait. Sometimes a Blue joins them." },
"meadow:Orange": { x: 652, y: 100, name: "Orange", colour: "Orange", kind: "dragon", lab: "left", desc: "The meadow Orange." },
"meadow:Brown": { x: 744, y: 80, name: "Brown", colour: "Brown", kind: "dragon", lab: "above", desc: "The meadow Brown." },
"meadow:Blue": { x: 836, y: 100, name: "Meadow Blue", colour: "Blue", kind: "dragon", lab: "right", desc: "The rare meadow Blue. Most riders who approach it are burned, even with the community's best answers." },
};
// routes described by the community that the form does not record
const KNOWN = [
["treeRed", "greens", "Wait and pursue the Green"],
["redwood", "greens", "Retreat, then find the Green"],
["redwood", "valley", "Retreat toward the valley"],
["comp:1 Squadmate", "comp:Alone", "Leave your squadmate"],
["comp:2 Squadmates", "comp:Alone", "Leave your squadmates"],
];
const SIGHT_NODES = new Set(Object.keys(L).filter((k) => k.startsWith("see:")));
function path(r) {
const s = [];
if (L["comp:" + r.company]) s.push("comp:" + r.company);
if (!["East", "West", "Center"].includes(r.direction)) return s;
s.push("dir:" + r.direction);
const sight = `see:${r.direction}:${r.first_sighting}`;
if (SIGHT_NODES.has(sight)) s.push(sight);
if (r.scream === "DIED at first sighting" || r.scream === "Unknown") return s;
s.push("scream");
if (r.scream === "Investigate & help") {
s.push("bully");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
if (r.resolution.startsWith("DIED")) return s;
if (["Forest", "West", "East"].includes(r.post_path)) s.push("fork:" + r.post_path);
} else if (r.scream === "Ignore the scream") {
s.push("wounded");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
} else if (r.scream === "Investigate & leave") s.push("away");
if (r.hour !== "Tree" && r.hour !== "Valley") return s;
s.push("hour");
if (r.hour === "Tree") {
s.push("tree");
if (r.branch === "Descend quickly: Red") s.push("treeRed");
else if (r.branch === "Descend slowly: two Greens") s.push("greens");
else if (r.branch === "Shadow (rare)") { s.push("stream"); if (r.enc_Blue || r.enc_Black) s.push("redwood"); if (r.enc_Black) s.push("black"); }
} else {
s.push("valley");
if (r.branch === "Valley Red") s.push("valleyRed");
else if (r.branch === "Passed the Red: meadow") {
s.push("meadow");
const tried = r.enc_Blue ? "Blue" : (r.outcome_color === "Orange" || r.outcome_color === "Brown") ? r.outcome_color : r.enc_Orange ? "Orange" : r.enc_Brown ? "Brown" : null;
if (tried) s.push("meadow:" + tried);
}
}
return s;
}
// ------------------------------------------------------------ painting
function defs(svg) {
const d = el("defs", {}, svg);
d.innerHTML = `
<linearGradient id="vm-sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#f3d69c"/><stop offset="0.35" stop-color="#e9c88f"/><stop offset="0.7" stop-color="#d9b07a"/><stop offset="1" stop-color="#c8955f"/>
</linearGradient>
<radialGradient id="vm-sun" cx="0.62" cy="0.12" r="0.55"><stop offset="0" stop-color="#fff3d1" stop-opacity="0.9"/><stop offset="1" stop-color="#fff3d1" stop-opacity="0"/></radialGradient>
<radialGradient id="vm-vignette" cx="0.5" cy="0.5" r="0.72"><stop offset="0.6" stop-color="#2a0f1c" stop-opacity="0"/><stop offset="1" stop-color="#2a0f1c" stop-opacity="0.55"/></radialGradient>
<filter id="vm-wash" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.022" numOctaves="3" seed="4" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="16" xChannelSelector="R" yChannelSelector="G" result="d"/>
<feGaussianBlur in="d" stdDeviation="0.7"/>
</filter>
<filter id="vm-wash2" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.05" numOctaves="2" seed="9" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="8" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-brush" x="-5%" y="-5%" width="110%" height="110%">
<feTurbulence type="fractalNoise" baseFrequency="0.09" numOctaves="2" seed="3" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="4" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-paper" x="0" y="0" width="100%" height="100%">
<feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="1" result="g"/>
<feColorMatrix in="g" type="matrix" values="0 0 0 0 0.36 0 0 0 0 0.24 0 0 0 0 0.14 0 0 0 0.55 -0.18"/>
</filter>
<filter id="vm-haze"><feGaussianBlur stdDeviation="10"/></filter>`;
}
function blob(g, x, y, r, fill, op, R) {
// irregular canopy blob from a few overlapping circles
for (let i = 0; i < 3; i++) el("circle", { cx: x + (R() - 0.5) * r * 0.9, cy: y + (R() - 0.5) * r * 0.6, r: r * (0.6 + R() * 0.45), fill, "fill-opacity": op }, g);
}
function paint(svg) {
const R = rng(21);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sky)" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sun)" }, svg);
// far ridge and hazy hills
const far = el("g", { filter: "url(#vm-wash)" }, svg);
let d = "M-20 120";
for (let x = -20; x <= 1020; x += 60) d += ` Q${x + 30} ${40 + R() * 40} ${x + 60} ${90 + R() * 40}`;
el("path", { d: d + " L1020 -10 L-20 -10 Z", fill: "#c99a72", "fill-opacity": 0.55 }, far);
el("path", { d: "M-20 150 Q200 90 420 140 T820 120 T1020 150 L1020 200 L-20 200 Z", fill: "#d4a677", "fill-opacity": 0.45 }, far);
// forest: three depth tiers of canopy washes, kept out of the clearings
const clear = [[742, 100, 150, 85], [124, 140, 92, 58], [694, 205, 80, 44], [520, 272, 70, 32], [846, 250, 70, 40], [500, 740, 190, 46], [318, 455, 120, 60], [684, 455, 120, 60], [500, 660, 80, 30]];
const inClear = (x, y) => clear.some(([cx, cy, rx, ry]) => ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 < 1);
const tiers = [
{ y0: 120, y1: 330, n: 150, r: [10, 20], cols: ["#b39a63", "#a99158"], op: 0.32 },
{ y0: 300, y1: 560, n: 170, r: [12, 24], cols: ["#8e8a54", "#7f7e4b"], op: 0.4 },
{ y0: 520, y1: 780, n: 170, r: [14, 30], cols: ["#6c6b40", "#5b5c37", "#6b5a35"], op: 0.45 },
];
tiers.forEach((t, ti) => {
const g = el("g", { filter: "url(#vm-wash)" }, svg);
// tall pale trunks, like a sunlit wood
for (let i = 0; i < t.n * 0.25; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
el("rect", { x, y: y - 50 - ti * 10, width: 2 + ti * 1.5, height: 60 + ti * 14, fill: "#7a5c3c", "fill-opacity": 0.18 + ti * 0.07 }, g);
}
for (let i = 0; i < t.n; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
blob(g, x, y, t.r[0] + R() * (t.r[1] - t.r[0]), t.cols[Math.floor(R() * t.cols.length)], t.op, R);
}
});
// clearings: warm ochre light
const cg = el("g", { filter: "url(#vm-wash)" }, svg);
clear.forEach(([cx, cy, rx, ry]) => el("ellipse", { cx, cy, rx: rx * 0.85, ry: ry * 0.8, fill: "#f0cf93", "fill-opacity": 0.55 }, cg));
// mist bands
const mg = el("g", { filter: "url(#vm-haze)" }, svg);
[[230, 0.35], [380, 0.2], [560, 0.18]].forEach(([y, o]) => el("rect", { x: -40, y, width: 1080, height: 26, fill: "#fbe9c4", "fill-opacity": o }, mg));
// the stream
const sg = el("g", { filter: "url(#vm-wash2)" }, svg);
const stream = "M560 -10 C 520 40, 470 70, 420 112 S 330 170, 270 150 S 170 120, 110 220 S 40 320, -10 350";
el("path", { d: stream, fill: "none", stroke: "#7fa3a6", "stroke-width": 13, "stroke-opacity": 0.65, "stroke-linecap": "round" }, sg);
el("path", { d: stream, fill: "none", stroke: "#cfe1dc", "stroke-width": 3, "stroke-opacity": 0.6, "stroke-linecap": "round" }, sg);
// rock outcrop for the valley Red, standing stones by the meadow
const rk = el("g", { filter: "url(#vm-wash2)" }, svg);
el("path", { d: "M800 272 L826 236 L862 230 L892 262 L880 284 L812 288 Z", fill: "#6e5c63", "fill-opacity": 0.75 }, rk);
el("path", { d: "M826 236 L862 230 L870 246 L834 252 Z", fill: "#9b8790", "fill-opacity": 0.6 }, rk);
// the tallest tree and the redwood
const big = el("g", { filter: "url(#vm-wash2)" }, svg);
el("rect", { x: 312, y: 150, width: 9, height: 70, fill: "#5a3f28", "fill-opacity": 0.85 }, big);
[[316, 150, 30], [302, 172, 22], [332, 168, 22], [316, 124, 22]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#46502e", "fill-opacity": 0.75 }, big));
el("rect", { x: 446, y: 40, width: 11, height: 56, fill: "#8a4430", "fill-opacity": 0.85 }, big);
[[452, 40, 20], [440, 54, 14], [464, 54, 14]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#3f4a2b", "fill-opacity": 0.7 }, big));
}
function overlay(svg) {
el("rect", { x: 0, y: 0, width: 1000, height: 780, filter: "url(#vm-paper)", opacity: 0.45, style: "mix-blend-mode:multiply", "pointer-events": "none" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-vignette)", "pointer-events": "none" }, svg);
}
// tiny original winged glyph for dragon places
const WING = "M50 30 L18 6 L27 21 L3 16 L25 32 Z M50 30 L82 6 L73 21 L97 16 L75 32 Z M37 30 Q50 23 63 30 Q50 37 37 30 Z M63 30 L76 26 L80 28 L73 31 Z M37 30 Q24 37 10 34 Q22 33 36 31 Z";
// ------------------------------------------------------------ rendering
let target = "bond_Blue", selected = "meadow:Blue", lastState = null, tipEl = null;
const TGT = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow", "bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
function tip(e, html) {
tipEl = tipEl || $("#tip");
tipEl.innerHTML = html; tipEl.hidden = false;
const r = tipEl.getBoundingClientRect();
tipEl.style.left = Math.min(window.innerWidth - r.width - 8, e.clientX + 14) + "px";
tipEl.style.top = Math.min(window.innerHeight - r.height - 8, e.clientY + 14) + "px";
}
const hideTip = () => { if (tipEl) tipEl.hidden = true; };
function renderTargets() {
$("#valley-targets").innerHTML = TGT.map((t) => {
const c = E.TARGETS[t].color ? DV[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${t.startsWith("bond_B") ? " featured" : ""}" data-vt="${t}" aria-pressed="${t === target}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
}).join("");
$$("#valley-targets .tchip").forEach((b) => b.addEventListener("click", () => { target = b.dataset.vt; render(lastState); }));
}
function curve(A, B, bend) {
const mx = (A.x + B.x) / 2, my = (A.y + B.y) / 2, dx = B.x - A.x, dy = B.y - A.y;
return `M${A.x} ${A.y} Q${mx - dy * bend} ${my + dx * bend} ${B.x} ${B.y}`;
}
const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour";
function render(state) {
if (!state || !state.res) return;
lastState = state;
renderTargets();
const svg = $("#valley");
svg.setAttribute("viewBox", "0 0 1000 790");
svg.innerHTML = "";
defs(svg); paint(svg);
const T = E.TARGETS[target].fn;
const nodes = new Map(), edges = new Map();
state.runs.forEach((r) => {
const seq = path(r), hit = T(r) ? 1 : 0;
seq.forEach((id, i) => {
const n = nodes.get(id) || { id, n: 0, k: 0, runs: [], endDeaths: 0 };
n.n++; n.k += hit; n.runs.push(r);
if (i === seq.length - 1 && isDeath(r)) n.endDeaths++;
nodes.set(id, n);
if (i) { const key = seq[i - 1] + ">" + id; const e = edges.get(key) || { a: seq[i - 1], b: id, n: 0, k: 0 }; e.n++; e.k += hit; edges.set(key, e); }
});
});
const minN = state.minN || 10;
const ES = [...edges.values()];
const maxN = Math.max(1, ...ES.map((e) => e.n));
const pmax = Math.max(0.005, ...ES.filter((e) => e.n >= minN).map((e) => e.k / e.n));
const tcol = E.TARGETS[target].color ? INK[E.TARGETS[target].color] : "#8a3f6e";
$(".valley-shell").style.setProperty("--vt", cssVar(E.TARGETS[target].color ? DV[E.TARGETS[target].color] : "--dr-any"));
const colourOf = (e) => (e.n < minN ? "#a58a70" : mix(PAPER.trailLow, tcol, Math.pow(Math.min(1, e.k / e.n / pmax), 0.7)));
// known-but-untracked routes
const gK = el("g", { "pointer-events": "stroke" }, svg);
KNOWN.forEach(([a, b, label]) => {
const A = L[a], B = L[b];
const p = el("path", { d: curve(A, B, 0.18), fill: "none", stroke: PAPER.ink, "stroke-opacity": 0.45, "stroke-width": 2, "stroke-dasharray": "2 7", "stroke-linecap": "round" }, gK);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(label)}</div>A route the community has described. The form doesn't record it, so it has no numbers.`));
p.addEventListener("mouseleave", hideTip);
});
// trails
const gT = el("g", { filter: "url(#vm-brush)" }, svg);
ES.sort((a, b) => b.n - a.n).forEach((e) => {
const A = L[e.a], B = L[e.b];
if (!A || !B) return;
const w = 2 + 24 * Math.sqrt(e.n / maxN);
const d = curve(A, B, 0.08);
el("path", { d, fill: "none", stroke: PAPER.halo, "stroke-width": w + 3, "stroke-opacity": 0.45, "stroke-linecap": "round" }, gT);
const p = el("path", { d, fill: "none", stroke: colourOf(e), "stroke-width": w, "stroke-opacity": e.n >= minN ? 0.85 : 0.45, "stroke-linecap": "round" }, gT);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(e.a))} → ${esc(name(e.b))}</div>${e.n.toLocaleString()} riders<br>${esc(E.TARGETS[target].label)}: <b>${pct(e.k / e.n, 1)}</b> (${e.k}/${e.n})${e.n < minN ? "<br><i>Too few riders to read</i>" : ""}`));
p.addEventListener("mouseleave", hideTip);
});
// places
const gN = el("g", {}, svg);
const total = Math.max(1, ...[...nodes.values()].map((n) => n.n));
Object.entries(L).forEach(([id, P]) => {
const nd = nodes.get(id) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const g = el("g", { class: "loc", tabindex: 0, role: "button", "aria-label": `${name(id)}: ${nd.n} riders` }, gN);
const sel = id === selected;
if (P.kind === "dragon") {
const r = 11 + 9 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 4, fill: PAPER.halo, "fill-opacity": 0.85, stroke: sel ? "#1d0a12" : INK[P.colour], "stroke-width": sel ? 3 : 1.6 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: "#fbf0d6", stroke: INK[P.colour], "stroke-width": 2.2 }, g);
el("path", { d: WING, fill: INK[P.colour], transform: `translate(${P.x - r * 0.82} ${P.y - r * 0.5}) scale(${(r * 1.64) / 100})` }, g);
} else if (P.kind === "start") {
el("path", { d: `M${P.x} ${P.y - 11} L${P.x + 9} ${P.y} L${P.x} ${P.y + 11} L${P.x - 9} ${P.y} Z`, fill: sel ? "#1d0a12" : PAPER.ink, stroke: PAPER.halo, "stroke-width": 2 }, g);
} else {
const r = P.kind === "small" ? 5 : 7 + 5 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 2.5, fill: PAPER.halo, stroke: sel ? "#1d0a12" : "none", "stroke-width": 2.5 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: P.kind === "small" ? "#7a5236" : PAPER.ink }, g);
}
// deaths that ended here
if (nd.endDeaths) {
const bx = P.x + (P.kind === "dragon" ? 18 : 10), by = P.y - (P.kind === "dragon" ? 16 : 10);
el("circle", { cx: bx, cy: by, r: 8.5, fill: PAPER.death, stroke: PAPER.halo, "stroke-width": 1.4 }, g);
const t = el("text", { x: bx, y: by + 3.2, "text-anchor": "middle", "font-size": 8.5, fill: "#fff3e0", "font-family": "var(--font-data)" }, g);
t.textContent = nd.endDeaths > 999 ? Math.round(nd.endDeaths / 100) / 10 + "k" : nd.endDeaths;
}
// labels (first sightings are labelled by their dragon glyph and tooltip only)
if (!P.first) {
const pos = P.lab || "right", off = P.kind === "dragon" ? 24 : 12;
let x = P.x, y = P.y + 4, anchor = "middle";
if (pos === "right") { x = P.x + off; anchor = "start"; }
else if (pos === "left") { x = P.x - off; anchor = "end"; }
else if (pos === "below") y = P.y + off + 12;
else if (pos === "above") y = P.y - off - 18;
const t1 = el("text", { x, y, "text-anchor": anchor, "font-family": "var(--font-display)", "font-size": P.kind === "small" ? 12.5 : 15, fill: PAPER.ink, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g);
t1.textContent = P.name;
if (P.kind !== "small") {
const t2 = el("text", { x, y: y + 14, "text-anchor": anchor, "font-size": 11, fill: PAPER.ink, "fill-opacity": 0.85, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3, "font-family": "var(--font-body)" }, g);
t2.textContent = `${nd.n.toLocaleString()} riders${P.sub ? " · " + P.sub : ""}`;
}
}
const pick = () => { selected = id; render(state); };
g.addEventListener("click", pick);
g.addEventListener("keydown", (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); pick(); } });
g.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(id))}</div>${nd.n.toLocaleString()} riders${nd.endDeaths ? ` · ${nd.endDeaths} died here` : ""}<br>${esc(E.TARGETS[target].label)}: ${pct(nd.n ? nd.k / nd.n : null, 1)}`));
g.addEventListener("mouseleave", hideTip);
});
// sighting captions per direction
["West", "Center", "East"].forEach((dname) => {
const xs = Object.keys(L).filter((k) => k.startsWith(`see:${dname}:`)).map((k) => L[k]);
const cx = xs.reduce((a, p) => a + p.x, 0) / xs.length, cy = Math.min(...xs.map((p) => p.y)) - 26;
const t = el("text", { x: cx, y: cy, "text-anchor": "middle", "font-size": 10.5, "letter-spacing": "0.12em", fill: PAPER.ink, "fill-opacity": 0.8, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, svg);
t.textContent = "FIRST DRAGON · ROLL";
});
// compass
const cr = el("g", { transform: "translate(52 726)", "aria-hidden": "true" }, svg);
el("circle", { r: 24, fill: PAPER.halo, "fill-opacity": 0.7, stroke: PAPER.ink, "stroke-opacity": 0.5 }, cr);
el("path", { d: "M0 -20 L5 0 L0 20 L-5 0 Z", fill: PAPER.ink }, cr);
const nT = el("text", { y: -28, "text-anchor": "middle", "font-size": 11, fill: PAPER.ink, "font-family": "var(--font-display)" }, cr); nT.textContent = "N";
overlay(svg);
renderCard(nodes, edges);
$("#valley-legend").innerHTML = `<span>Trail width = riders who walked it</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${PAPER.trailLow}, ${tcol})"></span> ${pct(pmax)}</span>
<span><span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${PAPER.death};vertical-align:-2px"></span> riders who died at that spot</span>
<span>Dotted = described by the community, not tracked by the form</span>
<span>Faded = fewer than ${minN} riders · positions are illustrative</span>`;
}
function name(id) {
const P = L[id];
if (!P) return id;
if (P.first) { const [, d, c] = id.split(":"); return `${c} dragon (first sighting, ${d === "Center" ? "forest centre" : d.toLowerCase()})`; }
return P.name;
}
function renderCard(nodes, edges) {
const P = L[selected], nd = nodes.get(selected) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const card = $("#loc-card");
card.style.setProperty("--lc", P.colour ? cssVar(DV[P.colour]) : cssVar("--accent"));
const w = E.wilson(nd.k, nd.n);
const out = [...edges.values()].filter((e) => e.a === selected).sort((a, b) => b.n - a.n);
const outN = out.reduce((a, e) => a + e.n, 0);
const ends = {};
nd.runs.forEach((r) => {
const k = r.outcome === "Bonded" ? "Bonded " + r.outcome_color : r.outcome === "Incinerated" ? "Incinerated" : r.outcome === "Died before the hour" ? "Died before the hour" : "Not recorded";
ends[k] = (ends[k] || 0) + 1;
});
const order = ["Bonded Red", "Bonded Orange", "Bonded Brown", "Bonded Green", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour", "Not recorded"];
const bar = (label, n, of, c) => `<div class="bar" style="--c:${c}"><span>${esc(label)}</span><i style="width:${(100 * n) / Math.max(1, of)}%"></i><span>${n} · ${pct(n / Math.max(1, nd.n))}</span></div>`;
const maxEnd = Math.max(1, ...Object.values(ends));
const P2 = P.first ? { desc: "The game rolls which dragon finds you first. Lower your eyes and keep still." } : P;
card.innerHTML = `<span class="eyebrow">${P.kind === "dragon" ? "A dragon waits here" : "Selected place"}</span><h3>${esc(name(selected))}</h3>
<p class="small muted">${esc(P2.desc || "")}</p>
<p class="small"><b>${nd.n.toLocaleString()}</b> logged runs reached this spot${nd.endDeaths ? `, and <b style="color:var(--ember)">${nd.endDeaths}</b> died here` : ""}. ${esc(E.TARGETS[target].label)}: <b>${pct(w.p, 1)}</b> of them (95% CI ${pct(w.lo, 1)}–${pct(w.hi, 1)}).</p>
${out.length ? `<span class="eyebrow">Where they went next</span><div class="bars">${out.map((e) => bar(name(e.b).replace(/ \(first sighting.*\)/, " first"), e.n, out[0].n, L[e.b].colour ? `var(${DV[L[e.b].colour]})` : "var(--accent)")).join("")}</div>` : ""}
<span class="eyebrow">How those runs ended</span><div class="bars">${order.filter((k) => ends[k]).map((k) => bar(k, ends[k], maxEnd, k.startsWith("Bonded") ? `var(${DV[k.split(" ")[1]]})` : k === "Incinerated" ? "var(--ember)" : "var(--faint)")).join("") || '<span class="small muted">No runs.</span>'}</div>`;
}
window.ValleyMap = { render, path, places: L };
})();
+10
View File
@@ -0,0 +1,10 @@
# Data sources
| Source | Where it lives here | How to update |
|---|---|---|
| Community "Threshing Routes" Google Form (u/ClumsyBadger) | `raw/form/*.xlsx` → `public/form_responses.json` | Download the sheet as .xlsx, then `python research/python/export_raw.py` |
| Community route PDF (u/ClumsyBadger) | not redistributed; linked from the Reddit megathreads | A scene crosswalk will be kept in `derived/` |
| Unofficial Dragon Register | `raw/register/` (git-ignored, has rider names) → `public/register.json` | `python research/python/export_register.py` |
| Reddit megathreads (r/fourthwing, Dragonkind bonding Parts 3 and 4) | qualitative; routes cited in the valley map | manual |
| DragonKind bot exports | `bot/runs-YYYY-MM-DD.jsonl` | by pull request, see `docs/BOT_DATA_PROTOCOL.md` |
| Discord | not yet | planned, with admin consent and anonymised usernames |
View File
+314
View File
@@ -0,0 +1,314 @@
{
"07e24681e3b3": {
"stage": "TREE_SHADOW_CHECK",
"tint": "green",
"backdrop": "clearing",
"label": "Descended slowly: two Greens in the clearing",
"options": [
{
"id": "d7f4b4e9da",
"text": "Lower your eyes and turn your body toward the right"
},
{
"id": "9da997c847",
"text": "Lower your eyes but keep your body neutral, letting them decide"
},
{
"id": "bafcacfd8c",
"text": "Lower your eyes and turn your body toward the left"
}
]
},
"0a561d53ad19": {
"stage": "THORN_WALK",
"tint": null,
"backdrop": "clearing",
"label": "An hour later: valley or tree",
"options": [
{
"id": "f0700810bf",
"text": "Continue toward the center of the valley"
},
{
"id": "7276f2fd9a",
"text": "Find the tallest tree and climb for a better view"
}
]
},
"0cfd06cf8939": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "After the fight: choose a direction",
"options": [
{
"id": "d79c512261",
"text": "Walk toward the east"
},
{
"id": "cfe44a775d",
"text": "Walk toward the west"
},
{
"id": "3929adfa07",
"text": "Walk farther into the forest"
}
]
},
"10bc7353b8eb": {
"stage": "FORK_IN_FOREST",
"tint": "red",
"backdrop": "clearing",
"label": "Descended quickly: a Red below",
"options": [
{
"id": "714e3abd94",
"text": "Reds are too hot-tempered. You’d rather take your chance with that green"
},
{
"id": "2991a60b20",
"text": "Jump in a few seconds and you’ll land closer to its tail, farther from the teeth"
},
{
"id": "40c171677e",
"text": "Jump now, and you can land on its back"
}
]
},
"84780dab01e3": {
"stage": "FIRST_SIGHTING",
"tint": "red",
"backdrop": "forest",
"label": "Survived the first sighting",
"options": [
{
"id": "6913c7fb2c",
"text": "Head deeper into the forest"
}
]
},
"96b68612eaf4": {
"stage": "FORK_IN_FOREST",
"tint": null,
"backdrop": "clearing",
"label": "Top of the tree (shadow check)",
"options": [
{
"id": "c71ea9e2b6",
"text": "Descend quickly in preparation for whatever’s coming your way"
},
{
"id": "2c5af7e978",
"text": "Climb down slowly to pursue the green"
}
]
},
"a2368b0dc212": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "Blocked the bigger cadet: bullies’ fate",
"options": [
{
"id": "2fba1113c6",
"text": "Leave the bullies alive. The dragons will sort them out"
},
{
"id": "43fb669800",
"text": "End the lives of the bullies yourself"
},
{
"id": "e579a5cd9f",
"text": "Allow your squadmate to exact their own revenge"
}
]
},
"a68f681076c6": {
"stage": "ENTER_THRESHING",
"tint": null,
"backdrop": "forest",
"label": "Valley edge: choose direction",
"options": [
{
"id": "5f7eefac34",
"text": "Head east toward the roar"
},
{
"id": "9c613e0d47",
"text": "Head west toward the scent"
},
{
"id": "05d19abb5d",
"text": "Head toward the center of the forest"
}
]
},
"abe3011378ac": {
"stage": "ENTER_THRESHING",
"tint": "brown",
"backdrop": "forest",
"label": "First sighting: Brown (forest centre)",
"options": [
{
"id": "1c97464061",
"text": "Run and hope it didn’t see you"
},
{
"id": "bab6a76e8b",
"text": "Lower your eyes and hold still"
},
{
"id": "f6fc843ffc",
"text": "Lower your eyes and turn to face it"
}
]
},
"b209bacacec3": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "Bully fight: first move",
"options": [
{
"id": "6dc46afcb2",
"text": "Pause to assess the situation even though it may risk your squadmate’s life"
},
{
"id": "483000d9b9",
"text": "Charge the other cadet to even out the numbers"
},
{
"id": "249cab536f",
"text": "Unsheathe your weapon and charge between the bigger cadet and your squadmate"
}
]
},
"bc4ee4754b9c": {
"stage": "ENTER_THRESHING",
"tint": "red",
"backdrop": "forest",
"label": "First sighting: Red (forest centre)",
"options": [
{
"id": "a31cbcb659",
"text": "Lower your eyes in respect"
},
{
"id": "14181c8e32",
"text": "Show your bravery by meeting its gaze"
},
{
"id": "1859b3cd4a",
"text": "Hide behind a tree"
}
]
},
"c62f1f1a2b3a": {
"stage": "FORK_IN_FOREST",
"tint": "green",
"backdrop": "clearing",
"label": "Let the Red pass: two Greens in the clearing",
"options": [
{
"id": "d7f4b4e9da",
"text": "Lower your eyes and turn your body toward the right"
},
{
"id": "bafcacfd8c",
"text": "Lower your eyes and turn your body toward the left"
},
{
"id": "9da997c847",
"text": "Lower your eyes but keep your body neutral, letting them decide"
}
]
},
"d25f2759ace0": {
"stage": "FIRST_SIGHTING",
"tint": null,
"backdrop": "forest",
"label": "Deeper in the forest: a scream",
"options": [
{
"id": "2b6d16a461",
"text": "Investigate the scream"
},
{
"id": "8e03986d31",
"text": "Keep walking. The cadets are just as dangerous as the dragons today"
}
]
},
"db7786392626": {
"stage": "ENTER_THRESHING",
"tint": null,
"backdrop": "forest",
"label": "Start: choose company",
"options": [
{
"id": "571af425c8",
"text": "Enter the valley with two of your squadmates"
},
{
"id": "3da794f136",
"text": "Enter the valley with one of your squadmates"
},
{
"id": "c18f80dd1e",
"text": "Enter the valley alone"
}
]
},
"f4b4944d3f3b": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "Beat the smaller cadet: bullies’ fate",
"options": [
{
"id": "e579a5cd9f",
"text": "Allow your squadmate to exact their own revenge"
},
{
"id": "43fb669800",
"text": "End the lives of the bullies yourself"
},
{
"id": "2fba1113c6",
"text": "Leave the bullies alive. The dragons will sort them out"
}
]
},
"f72199f24b91": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "Clearing: squadmate vs two bullies",
"options": [
{
"id": "c5719ec9a7",
"text": "Help your squadmate"
},
{
"id": "5e4947fde1",
"text": "Play it safe and leave them to their own defense so you can find your dragon"
}
]
},
"fbe0f0bea700": {
"stage": "SCREAM_AND_CADETS",
"tint": null,
"backdrop": "forest",
"label": "Bully fight: smaller cadet has a dagger",
"options": [
{
"id": "40b2e3202f",
"text": "Daggers or not, your squadmate is in danger, so you charge the bigger cadet"
},
{
"id": "dd20bac96c",
"text": "Engage the smaller cadet"
}
]
}
}
@@ -0,0 +1,6 @@
{"id":"bot-288b72e52f","source":"bot","meta":{"attempt":2,"startedAt":"2026-10-29T16:25:29.185Z","accountKey":null,"target":null,"decisionMode":null},"steps":[{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["5f7eefac34","9c613e0d47","05d19abb5d"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":null,"manual":false,"at":"2026-10-29T16:25:29.185Z","to":"bc4ee4754b9c"},{"scene":"bc4ee4754b9c","stage":"FIRST_SIGHTING","tint":"red","option":"a31cbcb659","optionText":"Lower your eyes in respect","offered":["a31cbcb659","14181c8e32","1859b3cd4a"],"rule":"SIGHTING_LOWER_EYES_RESPECT","decisionMode":null,"manual":false,"at":"2026-10-29T16:25:31.387Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"ENTER_THRESHING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-29T19:55:36.225Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["2b6d16a461","8e03986d31"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-29T19:55:38.219Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"BLUE_DRAGON_ROUTE","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BLUE_7_HELP_CADET","decisionMode":"guide","manual":false,"at":"2026-10-29T19:55:45.720Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"SCREAM_AND_CADETS","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["6dc46afcb2","483000d9b9","249cab536f"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:56:20.518Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"SCREAM_AND_CADETS","tint":null,"option":"40b2e3202f","optionText":"Daggers or not, your squadmate is in danger, so you charge the bigger cadet","offered":["40b2e3202f","dd20bac96c"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:56:29.785Z","to":"a2368b0dc212"},{"scene":"a2368b0dc212","stage":"SCREAM_AND_CADETS","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["2fba1113c6","43fb669800","e579a5cd9f"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:56:36.498Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"SCREAM_AND_CADETS","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["d79c512261","cfe44a775d","3929adfa07"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:56:42.280Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"THORN_WALK","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["f0700810bf","7276f2fd9a"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:56:51.226Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"FORK_IN_FOREST","tint":null,"option":"c71ea9e2b6","optionText":"Descend quickly in preparation for whatever’s coming your way","offered":["c71ea9e2b6","2c5af7e978"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:57:01.275Z","to":"10bc7353b8eb"},{"scene":"10bc7353b8eb","stage":"FORK_IN_FOREST","tint":"red","option":"2991a60b20","optionText":"Jump in a few seconds and you’ll land closer to its tail, farther from the teeth","offered":["714e3abd94","2991a60b20","40c171677e"],"rule":null,"decisionMode":"manual","manual":true,"at":"2026-10-29T19:57:08.857Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":false}}
{"id":"bot-a181b520f1","source":"bot","meta":{"attempt":3,"startedAt":"2026-10-30T01:21:31.420Z","accountKey":null,"target":null,"decisionMode":null},"steps":[{"scene":"db7786392626","stage":"ENTER_THRESHING","tint":null,"option":"c18f80dd1e","optionText":"Enter the valley alone","offered":["571af425c8","3da794f136","c18f80dd1e"],"rule":"ENTER_GO_ALONE","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:31.420Z","to":"a68f681076c6"},{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["05d19abb5d","9c613e0d47","5f7eefac34"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:34.893Z","to":"bc4ee4754b9c"},{"scene":"bc4ee4754b9c","stage":"FIRST_SIGHTING","tint":"red","option":"a31cbcb659","optionText":"Lower your eyes in respect","offered":["14181c8e32","a31cbcb659","1859b3cd4a"],"rule":"SIGHTING_LOWER_EYES_RESPECT","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:38.316Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"FIRST_SIGHTING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:41.767Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["2b6d16a461","8e03986d31"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:45.219Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"SCREAM_AND_CADETS","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BULLY_1_HELP_THEM","decisionMode":"guide","manual":false,"at":"2026-10-30T01:21:48.695Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"BLUE_DRAGON_ROUTE","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["483000d9b9","249cab536f","6dc46afcb2"],"rule":"LEARNED_EDGE","decisionMode":"learned","manual":false,"at":"2026-10-30T01:21:52.196Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"BLUE_DRAGON_ROUTE","tint":null,"option":"40b2e3202f","optionText":"Daggers or not, your squadmate is in danger, so you charge the bigger cadet","offered":["40b2e3202f","dd20bac96c"],"rule":"LEARNED_DASHBOARD","decisionMode":"learned","manual":false,"at":"2026-10-30T01:21:55.696Z","to":"a2368b0dc212"},{"scene":"a2368b0dc212","stage":"BLUE_DRAGON_ROUTE","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["e579a5cd9f","43fb669800","2fba1113c6"],"rule":"LEARNED_DASHBOARD","decisionMode":"learned","manual":false,"at":"2026-10-30T01:22:00.378Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"BLUE_DRAGON_ROUTE","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["cfe44a775d","d79c512261","3929adfa07"],"rule":"LEARNED_DASHBOARD","decisionMode":"learned","manual":false,"at":"2026-10-30T01:22:03.881Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"THORN_WALK","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["7276f2fd9a","f0700810bf"],"rule":"LEARNED_DASHBOARD","decisionMode":"learned","manual":false,"at":"2026-10-30T01:22:08.585Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"FORK_IN_FOREST","tint":null,"option":"c71ea9e2b6","optionText":"Descend quickly in preparation for whatever’s coming your way","offered":["2c5af7e978","c71ea9e2b6"],"rule":"LEARNED_DASHBOARD","decisionMode":"learned","manual":false,"at":"2026-10-30T01:22:13.279Z","to":"10bc7353b8eb"},{"scene":"10bc7353b8eb","stage":"INTENTIONAL_BURN","tint":"red","option":"714e3abd94","optionText":"Reds are too hot-tempered. You’d rather take your chance with that green","offered":["714e3abd94","40c171677e","2991a60b20"],"rule":"RED_TREE_DIVERT_GREEN_FOR_SAFE_BURN","decisionMode":"guide","manual":false,"at":"2026-10-30T01:22:16.740Z","to":"c62f1f1a2b3a"},{"scene":"c62f1f1a2b3a","stage":"INTENTIONAL_BURN","tint":"green","option":"9da997c847","optionText":"Lower your eyes but keep your body neutral, letting them decide","offered":["d7f4b4e9da","bafcacfd8c","9da997c847"],"rule":"BURN_GUARANTEED_INCINERATION","decisionMode":"guide","manual":false,"at":"2026-10-30T01:22:21.450Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":true}}
{"id":"bot-bb707b0816","source":"bot","meta":{"attempt":4,"startedAt":"2026-10-30T12:31:02.233Z","accountKey":null,"target":null,"decisionMode":null},"steps":[{"scene":"db7786392626","stage":"ENTER_THRESHING","tint":null,"option":"c18f80dd1e","optionText":"Enter the valley alone","offered":["571af425c8","c18f80dd1e","3da794f136"],"rule":"ENTER_GO_ALONE","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:02.233Z","to":"a68f681076c6"},{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["5f7eefac34","05d19abb5d","9c613e0d47"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:05.712Z","to":"abe3011378ac"},{"scene":"abe3011378ac","stage":"FIRST_SIGHTING","tint":"brown","option":"bab6a76e8b","optionText":"Lower your eyes and hold still","offered":["1c97464061","bab6a76e8b","f6fc843ffc"],"rule":"SIGHTING_BROWN_A_HOLD_STILL","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:09.211Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"FIRST_SIGHTING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:12.622Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["8e03986d31","2b6d16a461"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:16.054Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"SCREAM_AND_CADETS","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BULLY_1_HELP_THEM","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:19.501Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"SCREAM_AND_CADETS","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["249cab536f","483000d9b9","6dc46afcb2"],"rule":"BULLY_2_ASSESS_SITUATION","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:22.943Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"SCREAM_AND_CADETS","tint":null,"option":"dd20bac96c","optionText":"Engage the smaller cadet","offered":["40b2e3202f","dd20bac96c"],"rule":"BULLY_3_ENGAGE_SMALLER","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:26.363Z","to":"f4b4944d3f3b"},{"scene":"f4b4944d3f3b","stage":"SCREAM_AND_CADETS","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["e579a5cd9f","43fb669800","2fba1113c6"],"rule":"BULLY_4_KILL_BULLIES","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:31.012Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"SCREAM_AND_CADETS","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["cfe44a775d","d79c512261","3929adfa07"],"rule":"ROAD_FORK_DEEPER_FOREST","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:34.462Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"FORK_IN_FOREST","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["f0700810bf","7276f2fd9a"],"rule":"FORK_CLIMB_TALLEST_TREE","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:39.140Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"TREE_SHADOW_CHECK","tint":null,"option":"2c5af7e978","optionText":"Climb down slowly to pursue the green","offered":["c71ea9e2b6","2c5af7e978"],"rule":"TREE_NO_SHADOW_AUTO_BURN","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:43.809Z","to":"07e24681e3b3"},{"scene":"07e24681e3b3","stage":"INTENTIONAL_BURN","tint":"green","option":"9da997c847","optionText":"Lower your eyes but keep your body neutral, letting them decide","offered":["d7f4b4e9da","9da997c847","bafcacfd8c"],"rule":"BURN_GUARANTEED_INCINERATION","decisionMode":"guide","manual":false,"at":"2026-10-30T12:31:49.673Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":true}}
{"id":"bot-7e96467867","source":"bot","meta":{"attempt":5,"startedAt":"2026-10-30T16:32:01.623Z","accountKey":null,"target":"black","decisionMode":"auto_learn","policyId":null,"experimentId":null,"arm":null},"steps":[{"scene":"db7786392626","stage":"ENTER_THRESHING","tint":null,"option":"c18f80dd1e","optionText":"Enter the valley alone","offered":["c18f80dd1e","3da794f136","571af425c8"],"rule":"ENTER_GO_ALONE","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:01.623Z","to":"a68f681076c6"},{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["5f7eefac34","9c613e0d47","05d19abb5d"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:05.186Z","to":"bc4ee4754b9c"},{"scene":"bc4ee4754b9c","stage":"FIRST_SIGHTING","tint":"red","option":"a31cbcb659","optionText":"Lower your eyes in respect","offered":["a31cbcb659","14181c8e32","1859b3cd4a"],"rule":"SIGHTING_LOWER_EYES_RESPECT","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:08.740Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"FIRST_SIGHTING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:12.292Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["8e03986d31","2b6d16a461"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:15.815Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"SCREAM_AND_CADETS","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BULLY_1_HELP_THEM","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:19.408Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"SCREAM_AND_CADETS","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["249cab536f","6dc46afcb2","483000d9b9"],"rule":"BULLY_2_ASSESS_SITUATION","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:22.937Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"SCREAM_AND_CADETS","tint":null,"option":"dd20bac96c","optionText":"Engage the smaller cadet","offered":["dd20bac96c","40b2e3202f"],"rule":"BULLY_3_ENGAGE_SMALLER","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:26.473Z","to":"f4b4944d3f3b"},{"scene":"f4b4944d3f3b","stage":"SCREAM_AND_CADETS","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["43fb669800","2fba1113c6","e579a5cd9f"],"rule":"BULLY_4_KILL_BULLIES","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:31.222Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"SCREAM_AND_CADETS","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["3929adfa07","cfe44a775d","d79c512261"],"rule":"ROAD_FORK_DEEPER_FOREST","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:34.782Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"FORK_IN_FOREST","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["7276f2fd9a","f0700810bf"],"rule":"FORK_CLIMB_TALLEST_TREE","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:39.593Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"TREE_SHADOW_CHECK","tint":null,"option":"2c5af7e978","optionText":"Climb down slowly to pursue the green","offered":["2c5af7e978","c71ea9e2b6"],"rule":"TREE_NO_SHADOW_AUTO_BURN","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:44.371Z","to":"07e24681e3b3"},{"scene":"07e24681e3b3","stage":"INTENTIONAL_BURN","tint":"green","option":"9da997c847","optionText":"Lower your eyes but keep your body neutral, letting them decide","offered":["9da997c847","d7f4b4e9da","bafcacfd8c"],"rule":"BURN_GUARANTEED_INCINERATION","decisionMode":"guide","manual":false,"at":"2026-10-30T16:32:50.391Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":true}}
{"id":"bot-a4f8157ecf","source":"bot","meta":{"attempt":6,"startedAt":"2026-10-30T20:41:16.681Z","accountKey":null,"target":"black","decisionMode":"auto_learn","policyId":null,"experimentId":null,"arm":null},"steps":[{"scene":"db7786392626","stage":"ENTER_THRESHING","tint":null,"option":"c18f80dd1e","optionText":"Enter the valley alone","offered":["3da794f136","c18f80dd1e","571af425c8"],"rule":"ENTER_GO_ALONE","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:16.681Z","to":"a68f681076c6"},{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["5f7eefac34","9c613e0d47","05d19abb5d"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:20.259Z","to":"abe3011378ac"},{"scene":"abe3011378ac","stage":"FIRST_SIGHTING","tint":"brown","option":"bab6a76e8b","optionText":"Lower your eyes and hold still","offered":["bab6a76e8b","f6fc843ffc","1c97464061"],"rule":"SIGHTING_BROWN_A_HOLD_STILL","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:23.740Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"FIRST_SIGHTING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:27.302Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["8e03986d31","2b6d16a461"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:30.816Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"SCREAM_AND_CADETS","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BULLY_1_HELP_THEM","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:34.353Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"SCREAM_AND_CADETS","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["483000d9b9","6dc46afcb2","249cab536f"],"rule":"BULLY_2_ASSESS_SITUATION","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:37.937Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"SCREAM_AND_CADETS","tint":null,"option":"dd20bac96c","optionText":"Engage the smaller cadet","offered":["40b2e3202f","dd20bac96c"],"rule":"BULLY_3_ENGAGE_SMALLER","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:41.455Z","to":"f4b4944d3f3b"},{"scene":"f4b4944d3f3b","stage":"SCREAM_AND_CADETS","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["43fb669800","2fba1113c6","e579a5cd9f"],"rule":"BULLY_4_KILL_BULLIES","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:46.182Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"SCREAM_AND_CADETS","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["3929adfa07","cfe44a775d","d79c512261"],"rule":"ROAD_FORK_DEEPER_FOREST","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:49.692Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"FORK_IN_FOREST","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["7276f2fd9a","f0700810bf"],"rule":"FORK_CLIMB_TALLEST_TREE","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:54.419Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"TREE_SHADOW_CHECK","tint":null,"option":"2c5af7e978","optionText":"Climb down slowly to pursue the green","offered":["2c5af7e978","c71ea9e2b6"],"rule":"TREE_NO_SHADOW_AUTO_BURN","decisionMode":"guide","manual":false,"at":"2026-10-30T20:41:59.186Z","to":"07e24681e3b3"},{"scene":"07e24681e3b3","stage":"INTENTIONAL_BURN","tint":"green","option":"9da997c847","optionText":"Lower your eyes but keep your body neutral, letting them decide","offered":["9da997c847","d7f4b4e9da","bafcacfd8c"],"rule":"BURN_GUARANTEED_INCINERATION","decisionMode":"guide","manual":false,"at":"2026-10-30T20:42:05.900Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":true}}
{"id":"bot-c95f035604","source":"bot","meta":{"attempt":7,"startedAt":"2026-10-31T00:42:16.218Z","accountKey":null,"target":"black","decisionMode":"auto_learn","policyId":null,"experimentId":null,"arm":null},"steps":[{"scene":"db7786392626","stage":"ENTER_THRESHING","tint":null,"option":"c18f80dd1e","optionText":"Enter the valley alone","offered":["571af425c8","c18f80dd1e","3da794f136"],"rule":"ENTER_GO_ALONE","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:16.218Z","to":"a68f681076c6"},{"scene":"a68f681076c6","stage":"ENTER_THRESHING","tint":null,"option":"05d19abb5d","optionText":"Head toward the center of the forest","offered":["9c613e0d47","05d19abb5d","5f7eefac34"],"rule":"ENTER_TOWARDS_FOREST_CENTER","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:19.802Z","to":"bc4ee4754b9c"},{"scene":"bc4ee4754b9c","stage":"FIRST_SIGHTING","tint":"red","option":"a31cbcb659","optionText":"Lower your eyes in respect","offered":["a31cbcb659","1859b3cd4a","14181c8e32"],"rule":"SIGHTING_LOWER_EYES_RESPECT","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:23.442Z","to":"84780dab01e3"},{"scene":"84780dab01e3","stage":"FIRST_SIGHTING","tint":"red","option":"6913c7fb2c","optionText":"Head deeper into the forest","offered":["6913c7fb2c"],"rule":"SINGLE_CHOICE_ADVANCE","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:26.976Z","to":"d25f2759ace0"},{"scene":"d25f2759ace0","stage":"SCREAM_AND_CADETS","tint":null,"option":"2b6d16a461","optionText":"Investigate the scream","offered":["8e03986d31","2b6d16a461"],"rule":"SCREAM_INVESTIGATE","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:30.510Z","to":"f72199f24b91"},{"scene":"f72199f24b91","stage":"SCREAM_AND_CADETS","tint":null,"option":"c5719ec9a7","optionText":"Help your squadmate","offered":["c5719ec9a7","5e4947fde1"],"rule":"BULLY_1_HELP_THEM","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:34.122Z","to":"b209bacacec3"},{"scene":"b209bacacec3","stage":"SCREAM_AND_CADETS","tint":null,"option":"6dc46afcb2","optionText":"Pause to assess the situation even though it may risk your squadmate’s life","offered":["483000d9b9","6dc46afcb2","249cab536f"],"rule":"BULLY_2_ASSESS_SITUATION","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:37.643Z","to":"fbe0f0bea700"},{"scene":"fbe0f0bea700","stage":"SCREAM_AND_CADETS","tint":null,"option":"dd20bac96c","optionText":"Engage the smaller cadet","offered":["40b2e3202f","dd20bac96c"],"rule":"BULLY_3_ENGAGE_SMALLER","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:41.219Z","to":"f4b4944d3f3b"},{"scene":"f4b4944d3f3b","stage":"SCREAM_AND_CADETS","tint":null,"option":"43fb669800","optionText":"End the lives of the bullies yourself","offered":["43fb669800","2fba1113c6","e579a5cd9f"],"rule":"BULLY_4_KILL_BULLIES","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:46.033Z","to":"0cfd06cf8939"},{"scene":"0cfd06cf8939","stage":"SCREAM_AND_CADETS","tint":null,"option":"3929adfa07","optionText":"Walk farther into the forest","offered":["3929adfa07","d79c512261","cfe44a775d"],"rule":"ROAD_FORK_DEEPER_FOREST","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:50.332Z","to":"0a561d53ad19"},{"scene":"0a561d53ad19","stage":"FORK_IN_FOREST","tint":null,"option":"7276f2fd9a","optionText":"Find the tallest tree and climb for a better view","offered":["7276f2fd9a","f0700810bf"],"rule":"FORK_CLIMB_TALLEST_TREE","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:55.134Z","to":"96b68612eaf4"},{"scene":"96b68612eaf4","stage":"TREE_SHADOW_CHECK","tint":null,"option":"2c5af7e978","optionText":"Climb down slowly to pursue the green","offered":["c71ea9e2b6","2c5af7e978"],"rule":"TREE_NO_SHADOW_AUTO_BURN","decisionMode":"guide","manual":false,"at":"2026-10-31T00:42:59.963Z","to":"07e24681e3b3"},{"scene":"07e24681e3b3","stage":"INTENTIONAL_BURN","tint":"green","option":"9da997c847","optionText":"Lower your eyes but keep your body neutral, letting them decide","offered":["9da997c847","d7f4b4e9da","bafcacfd8c"],"rule":"BURN_GUARANTEED_INCINERATION","decisionMode":"guide","manual":false,"at":"2026-10-31T00:43:06.002Z","to":"BURNED"}],"outcome":{"type":"BURNED","colour":null,"intentional":true}}
+484
View File
@@ -0,0 +1,484 @@
{
"sha256": "f94688c2cfc6075c8d418f6cd3c37c5f36d34f396735551804dd50c533209539",
"bytes": 676134,
"pages": 1,
"page_hashes": [
"b471f398c95a520a"
],
"line_hashes": [
"0005ef79b6b0",
"00c8703a54ea",
"013509f3baab",
"01a142253839",
"01a32ae0ea35",
"021bb8f33946",
"0309a521e7cd",
"033394145a6f",
"0340ff1da1bc",
"061bdd1646d2",
"06845f929ace",
"06deac5b8d4a",
"070e3c5097ec",
"07422fff191a",
"075f329cca76",
"0844df8fee9e",
"084d9c75411f",
"08dbea2e99c7",
"093e7d5fdbaa",
"09ede21a5670",
"0a6389a6b822",
"0c3e015009e5",
"0c5d7989af41",
"0c6edb02c260",
"0caca604d8ec",
"0ce21d402aca",
"0d00728c456e",
"0d063950e5cb",
"0d2b6043baa9",
"0e00db4dcc8a",
"0e4e929314bc",
"0e5021c854fd",
"0f751a4bacc8",
"0fa4700b553a",
"0fb542ca6733",
"106a5842fc5f",
"1137d6133e74",
"115b5cad43c0",
"119a95345c45",
"126b59a70f14",
"1290a0a97b80",
"14558e7e73c8",
"14e2d4c37b5b",
"1584dc810a09",
"16477688c0e0",
"16486a0e2e7e",
"16552853f950",
"167a79b5d437",
"16872ead1390",
"16a87122c069",
"17fce8dabd41",
"18136e0d6414",
"18f42f5e8e05",
"1aefe47e20eb",
"1b4c9133da73",
"1fa9e3998e8b",
"20539cda4fc1",
"208a6d1ce0de",
"21e4274038e8",
"2287d8613d2a",
"2309d4da946e",
"24c668f6df98",
"25135325b8a1",
"25f6f2b99e6c",
"27042f4e6eca",
"27058a345f0b",
"27259f1f9d9b",
"283c7fb53e0f",
"2840a5c2ef51",
"28fdae8deae3",
"29ba6947875f",
"29bdb54f41e3",
"2ad8a7049d7c",
"2af59eff1aba",
"2bfd396cd229",
"2d306ed42cd7",
"2de7de149983",
"2e183f2a7a70",
"2f251aff0a77",
"2f501595d6f2",
"2f63258bd7ea",
"2fe14cd5feca",
"310ff200149b",
"31365ab9453d",
"3253cfe4c152",
"32e48995f98c",
"331306fab15d",
"3342b7db5f17",
"33b6aa152d23",
"3495806a7d6c",
"34bbac2c759b",
"34bef004e7fe",
"351421b8bac7",
"3650b7f3b7c5",
"3693c0f2d9d6",
"36bddc3a241f",
"370b1d50ab9e",
"3ad433972874",
"3af12ce68cd1",
"3af395aa2538",
"3beeaab32ac7",
"3c482346f375",
"3c6120e7558f",
"3cf48f3ba37d",
"3d5d5ba737e9",
"3d7505bbaadb",
"3d7f757f5e80",
"3daa8653d747",
"3e213b2a24a7",
"3e249a6cfd1e",
"3fc4ccfe7458",
"4062a9f595aa",
"40c432addf51",
"40d56877304e",
"40efa81686c6",
"414805731daf",
"41b0c91ed6d1",
"41bc7b0a9de2",
"41f20dee5da8",
"429e5436f520",
"42a21ed159ef",
"447048356f8c",
"453962996160",
"45847b618b88",
"45b162d4052f",
"45ea3e5067ae",
"46b86c91e7dc",
"4743a7d9869f",
"489620cdfe3f",
"491004bb0c9c",
"4945a70fa7f9",
"4978c1d21cf6",
"49c7fc30c959",
"4ac67444801e",
"4acde18a14fe",
"4b7e2845d537",
"4c3598c88d72",
"4cd1594422d4",
"4d0705fe0a43",
"4d74e17e5162",
"4d887b54d1ff",
"4e00a0ada947",
"4e7841613cc7",
"4f253b49f165",
"501ceebb8390",
"509a7aea82f7",
"510e291d89cb",
"519735f7b50e",
"52d74ec925e0",
"532ef4c15de8",
"53d2eb410d18",
"53f62454ac36",
"5586092a2a2e",
"56100f08de18",
"574516c105b3",
"5751e048eb6f",
"57ae2b2ab747",
"582967534d0f",
"5990333f4011",
"59b6221a51c1",
"5a785c0c26ab",
"5a8a1e3f617e",
"5b3975651c3c",
"5bd3de529a8b",
"5c2b4df891b0",
"5c385ea2003b",
"5c6039c55d3e",
"5d09fad99d0b",
"5df17b0e4664",
"5e9c9ea87d06",
"5eb67f9f8409",
"5ed0a10b951b",
"5f3f6470bb31",
"6038ac4d7893",
"6166cc9b0941",
"618cef59e81d",
"626a5a89e9aa",
"62db96bae199",
"63a1d7c638d4",
"6415fae65a2b",
"64f642099e0d",
"65ddfc96e288",
"668fea7bbc6f",
"68058fd701f7",
"680dce633db1",
"684888c0ebb1",
"696a74e35192",
"69dacd6c8b7f",
"6a3432dd57a9",
"6a7ef134f235",
"6b32aa9d4ff4",
"6bb9c00e0aa5",
"6bdb262b0201",
"6c45cb72a36e",
"6c8a73953696",
"6ca23bf7ced0",
"6d19ba36e0fe",
"6d1ef368012c",
"6d4a1297d150",
"6dca03cf2f51",
"6eb4b60a51cf",
"70e0378cb382",
"7148f48873b8",
"715112bd63e9",
"718b3ba4d288",
"7316da8715b2",
"73493e3a688b",
"743b4e8706ef",
"7453ed087523",
"7488af2a0881",
"760efd2269e8",
"7692c3ad3540",
"76a796208b71",
"771b94c11b83",
"77b8d989055a",
"793080bb3a18",
"79ea70ff1e9b",
"7b02bb57a565",
"7b78cfa89480",
"7e125ce01532",
"7e5056bd90f6",
"806112b3adcd",
"812f1ac36f2e",
"817286c6b049",
"81f8bd569345",
"826efdadff57",
"841012fe5a56",
"844c6714bd43",
"844cae5956bf",
"846e18aeea60",
"84ce9897665f",
"859facc5a4c9",
"860ce7852dc3",
"87094fc18528",
"87c3e080dcb4",
"8838a3634b92",
"883caeb7ca11",
"88f682991696",
"89045a19abd3",
"8950aeb7bd2e",
"898d979d655f",
"899b7c875126",
"8bab6b875ef7",
"8c25ea741f54",
"8d988fa37098",
"8d9f59690970",
"8e465d332643",
"8ff7f746ad0b",
"9160990b5196",
"91918d7d290f",
"919bc9b8d743",
"920a5924f124",
"935f14ac67b6",
"937c6644d5a0",
"94ab1f4a7216",
"95a14ed2a7fc",
"95d77302ee47",
"961836168b5b",
"964954c9200c",
"9801077818c0",
"984814d47989",
"987777fb002e",
"997b80a62167",
"99b5f979b8f6",
"9a43a6e28ae1",
"9a72012b0738",
"9b6cdd23ebfd",
"9b74bfb78b8a",
"9c4180730556",
"9c96829a8db2",
"9cf53d397849",
"9d8368e07ec1",
"9dbb8ef0cfbe",
"9dc08e403382",
"9e6242783cf6",
"9f56d2f4cae6",
"9fef67eeac85",
"a00b1ba9e0fb",
"a093d3f5ecff",
"a0f941fee4c0",
"a2066316fa63",
"a2a92faf51c6",
"a35c9fb774e6",
"a36373ed77ba",
"a3d7a6bf2036",
"a3f146576c0e",
"a5973cf86c17",
"a69a4139b340",
"a6e0a42de76e",
"a6e8ab03915b",
"a7cdf72224c0",
"a7dbeb539e04",
"a801e2fa5554",
"a854942a3868",
"a8892d94fb8f",
"a8ac9cbce523",
"a8faaccd9225",
"a9c43be948c5",
"a9c9cca61f97",
"a9d4b2eeab21",
"a9f6216a0284",
"a9fc9e5a9392",
"aa43aff07d84",
"ab455d73f4e1",
"abfc412ce6e5",
"acba25512100",
"acd40c358399",
"ace6f6b30de2",
"aceee3c152b4",
"ad485b06c7ff",
"adb35344b704",
"aea01b0f80d4",
"aeb8e7b22c53",
"aee408847d35",
"aeee13ca5367",
"aef0f56e108d",
"af07ff91ab7c",
"af6ee9910675",
"afa54821283c",
"b00a0d1bf844",
"b02c92648f0c",
"b0c1e513d4a4",
"b2081dd581e8",
"b23641a50841",
"b23a6a8439c0",
"b32c487e019c",
"b33e6cce7e8b",
"b38b92975bcd",
"b3b8898b5da9",
"b4fbbe802d67",
"b5afeb8db3aa",
"b60e38dc4232",
"b7bd4220ff85",
"b8ab74d65421",
"b8b0e7effd20",
"b95206531cb4",
"ba4788b226aa",
"bac081e175b0",
"bb8b9de8437d",
"bc19de4cc649",
"bc807bf2a135",
"be5ba8fe14a3",
"bec9019352b4",
"bf1563e43ef8",
"bf973180096e",
"bfdb888b8751",
"c0119487dd61",
"c0ac6a7adbc9",
"c176f96fff0c",
"c1a6320ab4ad",
"c1c369840b67",
"c25d9aca8b44",
"c29277f55fb3",
"c35c812678a2",
"c4bc2e4b5d80",
"c524989dd971",
"c54dbcd6c9a7",
"c5d35286c108",
"c68fef1abac6",
"c78f34b0d79b",
"c84d205e4185",
"c897882a79aa",
"c95ca8650396",
"c963069aec8e",
"caa6a9ced701",
"cb28392914d1",
"cbef62c551a8",
"cca94b79f1f1",
"cd1bb3012bcf",
"ce8e9aa287dc",
"cebb73212de0",
"cec9111de36d",
"cee6d39a9dae",
"cf6d0c6a1ca9",
"d00d825bba6b",
"d036316da911",
"d06e32ad1536",
"d0a7f376d907",
"d0bf30710858",
"d15a1edfb23c",
"d1dbecdfe93d",
"d2fa0e68a582",
"d3774d36d6cb",
"d3acc6861a0d",
"d413d29b87df",
"d4536f255583",
"d5a0d90574d5",
"d61483fb5f57",
"d76d5e7a3df7",
"d88c2c2a6831",
"d8fe183f5b8e",
"d90b4f86d5e0",
"d942f0a84262",
"d978e0e48792",
"d9a847a1a79a",
"d9ae6af36f3c",
"d9ffc6535d64",
"dab61aea1eb7",
"db875b25b06f",
"dbb3b50e59c7",
"dc439b56f090",
"dc6784c12e4a",
"dc9c5edb8b2d",
"dcebdc7c87c1",
"dd0cb2944980",
"dd6222c3b730",
"dddb00ed93b8",
"ddef924cf594",
"de0e10e162e2",
"de44be0064f1",
"df3f3c5b4066",
"e10ff24d56e9",
"e1d67a1ebbc7",
"e256ee8e7aff",
"e287c2a293ff",
"e3f8ef6845ac",
"e40dfff1a71e",
"e4bcc131d644",
"e4d6190e25b9",
"e53bac8ba854",
"e564b4081d7a",
"e566c53e48ba",
"e596899f114b",
"e5a05ee2bbba",
"e6c66d78c859",
"e6e6263ada92",
"e76566a6d54c",
"e774d221fc45",
"e7c0d9c5bc32",
"e84978ebc645",
"e8902e5de81c",
"e98df9566ae4",
"e9c5da6aa913",
"ea28f8974142",
"ea436127abfb",
"ea7fc9c5ea1c",
"eb04474cc31f",
"ec017cadac18",
"ec17f572de06",
"ec979fa3a0f9",
"ed6f7162410b",
"eded8d613508",
"eeeb42e33061",
"eef98a799e12",
"ef379363dd0c",
"efd8ebf4f438",
"f0dce65b5798",
"f179a509d32b",
"f1cb18decbab",
"f2a49ad419d2",
"f39dda09980e",
"f3c7807d4750",
"f3e394c8b9dc",
"f4909e20a51e",
"f51563619474",
"f6a4807a956f",
"f70b7769ae02",
"f763b9be2dc9",
"f8273be719f5",
"f8c25133ee80",
"f96ae5d430a6",
"f9980badef93",
"fac6a3243ed4",
"facf8b54e5c0",
"faebbd710849",
"fc097e65503c",
"fca413c36342",
"fd5cd809e2aa",
"fdbbfc2be926",
"fe4c73974e0e",
"ff06886f82e3",
"ff1f017072cc",
"ffe503ead4e4"
],
"checked": "2026-11-01"
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
{
"form": {
"name": "Threshing Routes form responses (u/ClumsyBadger)",
"view": "https://docs.google.com/spreadsheets/d/1gnw1AdRg1XT4JsOfRM6QTA0jSaS3n9ZF-rPWnYewzv0",
"download": "https://docs.google.com/spreadsheets/d/1gnw1AdRg1XT4JsOfRM6QTA0jSaS3n9ZF-rPWnYewzv0/export?format=xlsx",
"filename": "Threshing_Routes_Responses.xlsx"
},
"register": {
"name": "Unofficial Dragon Register responses",
"view": "https://docs.google.com/spreadsheets/d/1KMiE9sec0l597Pzue1OhGYf07NF4howtQ_lPeqx7jXQ",
"download": "https://docs.google.com/spreadsheets/d/1KMiE9sec0l597Pzue1OhGYf07NF4howtQ_lPeqx7jXQ/export?format=xlsx",
"filename": "Unofficial_Dragon_Register_Responses.xlsx"
},
"pdf": {
"name": "Community route PDF (u/ClumsyBadger)",
"view": "https://drive.google.com/file/d/17o72ehHsSPW4UdsKF-sXTxMLEuinWeEg/view",
"download": "https://drive.google.com/uc?export=download&id=17o72ehHsSPW4UdsKF-sXTxMLEuinWeEg",
"filename": "Threshing_Options.pdf"
}
}
+152
View File
@@ -0,0 +1,152 @@
# Bot data protocol
How the DragonKind bot should run and log its threshing attempts so that the Threshing Atlas can
estimate route probabilities, including history effects, and find the best route to each dragon colour.
Goal: bond a Blue and bond a Black, and know the best route for every colour.
## 1. Why the bot matters
Community data are observational. People copy routes from guides, so most choices are correlated
with each other and with what people chose to report. That correlation is copied behaviour, not game
mechanics. Only the bot can choose at random, and random assignment is what tells us that an earlier
choice *causes* a later dragon to appear. The bot is the experiment. The community data are the prior.
Two facts shape everything below:
- **An attempt is the scarce resource.** Each one costs a cooldown, and a bond is permanent for that
account. A run must never risk bonding the wrong colour.
- **Seeing a dragon is usually not the same as bonding it.** If the colour is visible before the step
where the player commits, the bot can record what appeared and then burn deliberately. Spawn rates
for every colour can then be learned without using up an account. Only the final "does this choice
actually bond?" step needs real bonds, and that step is close to deterministic.
## 2. What to log
`src/runhistory.js` already records one structured record per attempt. That is the right shape. These
additions turn it into data the solver can use. The most important ones come first.
| # | Field | Why |
|---|-------|-----|
| 1 | `steps[].offered`: every option on screen, as `[{text, norm, hash}]`, plus the index that was picked | Shows "every option at every point", and detects options that only appear after certain earlier choices (that is itself history dependence) |
| 2 | `steps[].observed`: what the scene showed, e.g. `{dragons: ["red"], shadow: false, cadetWounded: true}` | Chance outcomes are the core data. Today a burned run has `dragonColor: null`, and the tree check does not say whether the shadow was there |
| 3 | `steps[].propensity`: the probability with which the bot picked this option (1.0 for a fixed rule, 0.5 for a coin flip) | Lets runs from different policies be pooled without bias (inverse-propensity weighting) |
| 4 | `policyId` / `experimentId` / `arm` per run, plus `botCommit` (git short hash) | Says which policy or experiment produced the run. The learner changes over time, so this is not optional |
| 5 | `burn: {reason, stage, nodeId}` for intentional burns | A deliberate burn cuts the run short on purpose (censoring). The model must know where and why |
| 6 | `accountKey`: a salted hash of the account id, plus `accountAttempt` (that account's attempt number) | Separates account effects from route effects. Never log the account name or email |
| 7 | `startedAt` in UTC, plus the in-game hour if the scene shows one | Time-of-day and patch effects |
| 8 | `manual: true` on any step a human picked, and `decisionMode` on every step (not only the run) | `ai_pilot` and manual picks have no known propensity, so they are analysed separately |
| 9 | `ABORTED` runs kept, with `abortReason` | Dropping failures biases rates |
| 10 | `sceneFp` (the existing sha1 node id) and a short `label` | The public data carry fingerprints and labels only, never the game's prose |
A step would then look like this:
```json
{
"nodeId": "bc4ee4754b9c", "stage": "FIRST_SIGHTING", "label": "first sighting, forest centre",
"observed": { "dragons": ["brown"] },
"offered": [
{ "norm": "lower your eyes in respect", "hash": "9a1c…" },
{ "norm": "meet its gaze", "hash": "41fe…" }
],
"picked": 0, "propensity": 0.5, "decisionMode": "explore", "rule": "EXP-03:arm-A",
"outcome": "SCENE", "toKey": "84780dab01e3", "at": "2026-11-01T21:03:11Z"
}
```
Parsing `observed` from the prose can start as simple keyword rules (colour words, "shadow", "wounded")
kept in one table. The atlas will flag scenes where the rules return nothing.
## 3. How to run the accounts
### Two kinds of account
- **Goal accounts** (the ones meant to bond Blue or Black) run the current best policy for their target
colour from `policy.json`, with the existing Account Lock Guard and intentional-burn protection.
They still log everything. Their runs are data too, with propensity 1.0.
- **Research accounts** run experiments. They also never accept a non-target bond. They observe and
then burn. If one reaches a genuine Blue or Black bonding choice, that is a real result: let it bond
and log it.
### Freeze the policy during an experiment
`auto_learn` rewrites its own rules from its own results. While an experiment is running, that mixes up
the effect of the experiment with the bot's learning, and makes the data non-stationary. For research
runs, use `explore` with a fixed experiment file, and record `policyId`. Update the policy between
batches, not during them.
### Randomize one decision point against a fixed baseline
- The **baseline** is the community guide route (the PDF route) for the target colour.
- In an experiment, exactly one decision point (or two, in a 2×2 design) is chosen by a coin flip with
a known probability. Everything else follows the baseline.
- Assign arms in **balanced blocks per account** (for example A, B, B, A, …), so every account
contributes equally to both arms.
- Use **pre-set run counts**. Do not stop because the results look good: stopping early on a good run
inflates the effect.
- Do not use `ai_pilot` for research runs. If it is used, the runs are tagged and kept out of the
causal estimates.
### Phases
1. **Mapping (first week or two).** At every decision point, try each option a few times (about 5 to 10)
so that every branch has at least been seen. This finds hidden options, dead ends and death scenes.
It uses few runs, because the bot can burn as soon as a branch has been recorded.
2. **Spawn rates (ongoing, nearly free).** Every run records which dragon appeared at the first
sighting, the meadow and the valley, and whether the shadow was at the tree. This builds the
colour-by-location table for all six colours as a by-product.
3. **Targeted experiments.** The atlas produces an experiment list (`experiments.json`), ranked by how
much each result could change the best route for each colour. That ranking is a value-of-information
calculation. The bot runs the top items.
### Blue and Black need different strategies
**Blue (meadow, roughly 10% of meadow visits).** The question is whether anything earlier changes the
Blue rate at the meadow: company, direction, how you met the first dragon, what happened with the
cadets. Each research run goes to the meadow, records the colour, and burns unless it is Blue. Telling a
10% rate from a 20% rate needs about **200 runs per arm**. That is achievable across a few accounts over
a few weeks.
**Black (tree shadow, roughly 1%).** Too rare for full factorial experiments. Instead:
- Take the **shortest route to the tree check**, and burn immediately when there is no shadow. This is
what the bot already does, and it maximizes tree visits per day.
- At the same time, randomize **one** earlier factor 50/50 on every run, so each tree visit also counts
towards a test. Run that one test until it reaches its planned count, then move on to the next factor.
- Log the tree scene's fingerprint and options carefully even when there is no shadow. A change in the
prose or options may be an early sign.
- Telling 1% from 2% needs thousands of runs per arm. This is where pooling with community logs, and
later Discord, will matter most.
### Other colours
Red, Brown, Orange and Green come mostly from the spawn-rate logging in phase 2. Green also needs the
rescue branch (the wounded cadet) to be tried in both directions in phase 1.
## 4. Getting data to the atlas
- The atlas repo already has the exporter: `npm run import-bot -- --bot /path/to/DragonKind`. It reads
`data/knowledge.json`, `data/runs.jsonl` and `logs/encounters.jsonl` from the bot folder and writes
`data/bot/scenes.json` and `data/bot/trajectories-<date>.jsonl`, with:
- prose removed (scene fingerprints, short labels, choice text and outcomes only). The importer
refuses to write any field or string that looks like prose,
- account ids replaced by salted hashes. Set `DK_ACCOUNT_SALT` in your environment; never commit it,
- nothing read from `.browser-profile*/`, `data/accounts.json`, `data/integrations.json` or
`data/state.json`.
- Its scene fingerprints are computed exactly as the bot's `computeSceneFingerprint()` does, so they
match the bot's node ids. If the bot's `normalize()` or fingerprint changes, the importer must change too.
- Commit the result to `threshing-atlas` by pull request. CI rebuilds the graph and runs the tests.
- In return, the atlas publishes `policy.json` (the best decision tree per colour, under both goals)
and `experiments.json`. The bot reads them as a strategy source. The bot's own guards still have the
final say.
## 5. Checklist for Ken
- [ ] Add `offered`, `picked`, `observed`, `propensity` and per-step `decisionMode` to `noteChoice()`.
- [ ] Add `policyId`, `experimentId`, `arm`, `botCommit`, `accountKey` and `accountAttempt` to `beginRun()`.
- [ ] Add `burn.reason` and `abortReason` to `endRun()`.
- [ ] Write the keyword table that fills `observed` (dragon colours, shadow, wounded cadet).
- [ ] Add an `explore` mode that reads an experiment file, assigns arms in balanced blocks per account, and freezes learning.
- [ ] Add the export script, with the account salt in `.env`.
- [ ] Split the accounts into goal accounts and research accounts.
- [ ] Run phase 1 (mapping). Then keep phase 2 logging on for every run, goal accounts included.
+19
View File
@@ -0,0 +1,19 @@
# I ran the numbers on 2,573 logged threshing runs. Here's what holds up (and what doesn't)
*Per the megathread rules, anything that names a specific route is behind spoiler tags.*
Data: the community Threshing Routes form/spreadsheet (thanks u/ClumsyBadger, u/Old_Regular3018, u/Smart_Trifle_2099 and everyone who logged runs). 1946 form submissions, 83 Historical import, 348 Data Import, 196 Manual Upload; form dates 2026-10-04 to 2026-10-19. Every rate below has a 95% confidence interval.
**TL;DR**
* **The meadow Blue shows up a lot less than the spreadsheet suggests.** Runs logged by Blue-chasers show it 50.1% of the time, but bulk logs (people who recorded *every* run) show 11.0% (21/191). The game can't know what you're chasing, so that gap is reporting bias. Expect something closer to the bulk-log number.
* **No recorded route choice changed the Blue's odds** once you account for that bias (direction, first dragon, how you handled the cadet, company). 0 of 25 full routes beat the rest after correcting for multiple testing. The "precise pathways" might still matter through choices the form doesn't record (like how you react to the first dragon), but the form can't confirm them.
* **Getting the Blue to show up is only half of it.** Only 23.1% (92/398) of Blue attempts bonded, which matches the PDF's step-by-step numbers (~25%). Dying with the "right" answer is normal.
* **The tree shadow (→ Black) is rarer than the spreadsheet suggests.** All rows: 2.2% (24/1089), but bulk logs show 0/364 (upper 95% bound 1.0%). Plan on roughly 1 in 100 climbs at best. Once you get the Black, it bonds 86.7% (13/15) of the time.
* **Leads worth testing (not proven):** >!Fork in the road = Forest: shadow in 3.7% (19/514) vs the rest; Attempt = First attempt: shadow in 7.0% (8/114) vs the rest!<. If you bulk-log your tree climbs *including the boring ones*, we can settle this.
**How to help:** log every run in the form, including the ones where nothing rare happened. Those dull runs are what make the rates trustworthy.
Interactive route map, full methods, and code to reproduce every number: [Threshing Route Atlas](LINK)
*Caveats: self-reported data, no player IDs (so runs from one person aren't independent), and the form doesn't record every in-game choice. The author has said there's a ~10% chaos roll, so nothing is guaranteed.*
+25
View File
@@ -0,0 +1,25 @@
# Roadmap
The aim is to move from summary statistics to path finding: for each dragon colour, the decision
policy that maximises the chance of bonding it, with honest uncertainty.
1. **Repo and packaging** (done): monorepo, CI, GitHub Pages, JS/Python parity tests.
2. **Graph format** (`packages/core`, first version done): typed scene, chance and terminal nodes; history-context keys;
per-source counts (bot, form, PDF, Discord); fingerprints and short labels only, no game prose.
Importers in `packages/ingest` for the bot's `knowledge.json`, `runs.jsonl` and `encounters.jsonl`
(done), the form (done, via the crosswalk in `graph.js`), and a PDF scene crosswalk (to do).
Daily source checks for the form, the register and the PDF (done).
3. **Context learning** (`research/`): tests of history dependence (G-tests, BH); variable-order
Markov / context tree with BIC; temporal-tiered DAG structure learning (BDeu/BIC); latent
"character" model vs specific triggers vs memoryless baseline, compared on held-out likelihood;
hierarchical Dirichlet back-off pooling.
4. **Solver**: backward induction on the augmented state (scene, history summary), i.e. an influence
diagram with perfect recall. Two objectives side by side per colour:
- P(target colour on this attempt);
- eventual success when deliberate deaths are free: maximise p_X / (p_X + p_other bond),
solved by Dinkelbach iteration.
Monte Carlo credible intervals, top-k routes, required steps and bottlenecks.
5. **Valley graph UI**: every option at every point, with P(survive) and P(bond) per colour, the
policy overlay for a chosen colour, and untested branches marked.
6. **Bot loop**: the atlas publishes `policy.json` and `experiments.json` (ranked by value of
information); the private DragonKind bot consumes them and returns anonymised runs.
+22
View File
@@ -0,0 +1,22 @@
{
"name": "threshing-atlas",
"private": true,
"description": "Route probabilities and path-finding for the Dragonkind threshing",
"license": "MIT",
"workspaces": [
"packages/*"
],
"scripts": {
"build": "node scripts/build-site.js",
"dev": "node scripts/build-site.js && python3 -m http.server 8000 -d dist",
"test:js": "node tests/run_engine.js data/public/form_responses.json tests/out",
"test:py": "cd research/python && python3 clean.py && python3 analyze.py",
"test": "npm run test:js && npm run test:py && python3 tests/compare_runs.py && python3 tests/compare_results.py && python3 tests/compare_routes.py && node --test tests/graph.test.js",
"graph": "node scripts/build-graph.js",
"import-bot": "node packages/ingest/bin/import-bot.js",
"check-sources": "python3 research/python/update_sources.py"
},
"engines": {
"node": ">=18"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"name": "@threshing-atlas/core",
"version": "0.1.0",
"description": "Coding rules, statistics and (soon) the route graph and solver for the Dragonkind threshing. Runs in Node and the browser, no dependencies.",
"main": "src/engine.js",
"files": ["src"],
"license": "MIT"
}
+731
View File
@@ -0,0 +1,731 @@
/*
* engine.js — Threshing route analysis engine.
*
* One file, used two ways:
* - in the browser (the route map page loads it and recomputes everything from the raw form export)
* - in Node (`node tests/run_engine.js data.json`), so results can be reproduced and checked against
* the Python reference implementation in python/.
*
* Pipeline: raw form rows -> codeRow() (one coded run per row) -> analyse() -> results object
* coded runs + a target outcome -> buildGraph() -> nodes/links for the route map
*
* Every rule here is described in plain language in the Methods section of the page.
*/
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.ThreshEngine = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
// Free-text answers sometimes contain a respondent's email address; never display or export it.
const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
const redact = (v) => (v == null ? v : String(v).replace(EMAIL_RE, "[email removed]"));
const COLORS = ["Red", "Green", "Orange", "Brown", "Blue", "Black"];
// ---------------------------------------------------------------- column detection
const COLUMN_KEYS = {
timestamp: ["timestamp"],
wing_First: ["wing and section", "[first]"],
wing_Second: ["wing and section", "[second]"],
wing_Third: ["wing and section", "[third]"],
wing_Fourth: ["wing and section", "[fourth]"],
squad: ["what squad"],
attempt: ["attempt number"],
company: ["who accompanied"],
dir_East: ["initial direction", "[east"],
dir_West: ["initial direction", "[west"],
dir_Center: ["initial direction", "[forest center"],
cadet: ["outcome of your cadet encounter"],
post: ["path did you take after the bully"],
hour: ["after walking an hour"],
enc_Red: ["attempt to bond", "[red"],
enc_Green: ["attempt to bond", "[green"],
enc_Orange: ["attempt to bond", "[orange"],
enc_Brown: ["attempt to bond", "[brown"],
enc_Blue: ["attempt to bond", "[blue"],
enc_Black: ["attempt to bond", "[black"],
death_note: ["those who died"],
bond_note: ["those who bonded"],
goal: ["colour dragon are you trying"],
combat: ["combat choice"],
};
function findColumns(headers) {
const C = {};
for (const [key, words] of Object.entries(COLUMN_KEYS)) {
const hit = headers.find((h) => words.every((w) => String(h).toLowerCase().includes(w)));
if (hit !== undefined) C[key] = hit;
}
const missing = Object.keys(COLUMN_KEYS).filter((k) => !(k in C));
return { C, missing };
}
// ---------------------------------------------------------------- coding rules
const CADET_MAP = {
"Bullies > You dealt with them": ["Investigate & help", "Killed the bullies yourself"],
"Bullies > Squadmate's revenge": ["Investigate & help", "Squadmate's revenge"],
"Bullies > Left to the Dragons": ["Investigate & help", "Left bullies to the dragons"],
"Bullies > Assessed the situation": ["Investigate & help", "Unknown"],
"Injured Cadet > Tourniquet": ["Ignore the scream", "Tourniquet"],
"Injured Cadet > Left them there": ["Ignore the scream", "Left injured cadet"],
"Injured Cadet > Took their weapons": ["Ignore the scream", "Took their weapons"],
"Avoided combat (Investigated scream > Left them to it)": ["Investigate & leave", "Left them to it"],
"You died in combat": ["Investigate & help", "DIED in combat"],
"N/A - You died with initial dragon sighting": ["DIED at first sighting", "DIED at first sighting"],
};
const COMBAT_MAP = {
"Bullies > Assessed the situation": "Assess the situation",
"Bullies > Even the numbers (Rushed the smaller cadet)": "Even the numbers (smaller cadet)",
"Bullies > Put yourself in the middle (Rushed the bigger cadet attacking your squadmate)":
"Put yourself in the middle (bigger cadet)",
};
const HOUR_MAP = {
"Continued to Valley Centre": "Valley",
"Climbed the tallest tree": "Tree",
"N/A - You're dead": "DIED before the hour",
};
// First-sighting pools per (company, direction) from the community PDF. Only used to FLAG rows.
const SIGHTING_POOL = {
"Alone|East": ["Red", "Orange"],
"Alone|West": ["Red", "Brown", "Green"],
"Alone|Center": ["Red", "Brown"],
"1 Squadmate|East": ["Green", "Orange", "Red"],
"1 Squadmate|West": ["Red", "Brown", "Green"],
"1 Squadmate|Center": ["Red", "Brown"],
"2 Squadmates|East": ["Red", "Orange"],
"2 Squadmates|West": ["Green", "Brown", "Red"],
"2 Squadmates|Center": ["Red", "Brown"],
};
const str = (v) => {
if (v === null || v === undefined) return null;
if (typeof v === "number" && isNaN(v)) return null;
const t = String(v).trim();
return t === "" || t === "nan" || t === "NaN" ? null : t;
};
// Form submissions carry a real timestamp; rows bulk-pasted into the sheet carry a label
// ("Data Import", "Manual Upload", "Historical import") instead.
function parseTimestamp(v) {
if (v instanceof Date && !isNaN(v)) return v;
if (typeof v === "number" && v > 40000 && v < 80000) return new Date(Date.UTC(1899, 11, 30) + Math.floor(v) * 86400000); // Excel serial date
const t = str(v);
if (!t) return null;
let m = t.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (m) return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
m = t.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/); // Google Sheets CSV: M/D/YYYY
if (m) return new Date(Date.UTC(+m[3], +m[1] - 1, +m[2]));
return null;
}
const isoDate = (d) => d.toISOString().slice(0, 10);
function parseAttempt(v) {
const t0 = str(v);
if (!t0) return null;
const t = t0.toLowerCase();
if (t.includes("lost count")) return null;
const words = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5 };
for (const [w, n] of Object.entries(words)) if (t.startsWith(w)) return n;
const m = t.match(/\d+/);
return m ? parseInt(m[0], 10) : null;
}
function codeRow(row, C) {
const g = (k) => (k in C ? str(row[C[k]]) : null);
const flags = [];
const tsRaw = "timestamp" in C ? row[C.timestamp] : null;
const ts = parseTimestamp(tsRaw);
const source = ts ? "Form" : str(tsRaw) || "Unknown import";
const date = ts ? isoDate(ts) : null;
const wings = ["First", "Second", "Third", "Fourth"].filter((w) => g("wing_" + w));
const wing = wings.length === 1 ? wings[0] : wings.length ? "Multiple" : "Unknown";
const section = wings.length === 1 ? g("wing_" + wings[0]) : null;
if (wings.length > 1) flags.push("multiple wings");
const dirs = ["East", "West", "Center"].filter((d) => g("dir_" + d));
let direction, first;
if (dirs.length === 1) {
direction = dirs[0];
first = g("dir_" + dirs[0]);
} else {
direction = dirs.length ? "Multiple" : "Unknown";
first = null;
flags.push("direction " + (dirs.length ? "multiple" : "missing"));
}
const company = g("company") || "Unknown";
const pool = SIGHTING_POOL[company + "|" + direction];
if (first && first !== "Unsure" && pool && !pool.includes(first))
flags.push(`first sighting ${first} not in documented pool for ${company}/${direction}`);
const cadetRaw = g("cadet");
const [scream, resolution] = CADET_MAP[cadetRaw] || ["Unknown", "Unknown"];
if (cadetRaw && !CADET_MAP[cadetRaw]) flags.push("unrecognised cadet answer");
const combat = g("combat") ? COMBAT_MAP[g("combat")] || null : null;
const postRaw = g("post");
let post = null;
if (scream === "Investigate & help" && !resolution.startsWith("DIED"))
post = ["Forest", "West", "East"].includes(postRaw) ? postRaw : "Unknown";
else if (scream === "Ignore the scream" || scream === "Investigate & leave") post = "(no fork)";
const diedEarly = scream.startsWith("DIED") || resolution.startsWith("DIED");
let hour = HOUR_MAP[g("hour")] || null;
if (diedEarly) hour = null;
else if (hour === null) hour = "Unknown";
const enc = {};
for (const c of COLORS) enc[c] = g("enc_" + c);
const bonded = COLORS.filter((c) => enc[c] === "Bonded!");
const burned = COLORS.filter((c) => enc[c] === "Incinerated");
let branch = null;
if (hour === "Tree") {
if (enc.Blue || enc.Black) branch = "Shadow (rare)";
else if (enc.Green) branch = "Descend slowly: two Greens";
else if (enc.Red) branch = "Descend quickly: Red";
else if (enc.Orange || enc.Brown) {
branch = "Descend slowly: two Greens";
flags.push("tree run with Orange/Brown but no Green recorded");
}
} else if (hour === "Valley") {
if (enc.Green) flags.push("Green recorded on a Valley run (no Greens in the valley)");
const meadow = ["Orange", "Brown", "Blue"].some((c) => enc[c]);
if (meadow || enc.Red === "Changed my mind") branch = "Passed the Red: meadow";
else if (enc.Red) branch = "Valley Red";
}
let outcome, outcomeColor = null;
if (diedEarly) outcome = "Died before the hour";
else if (bonded.length === 1) { outcome = "Bonded"; outcomeColor = bonded[0]; }
else if (bonded.length > 1) { outcome = "Ambiguous"; flags.push("more than one dragon marked Bonded"); }
else if (burned.length) {
const order = hour !== "Valley"
? ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
: ["Red", "Orange", "Brown", "Blue", "Green", "Black"];
const inOrder = order.filter((c) => burned.includes(c));
outcome = "Incinerated";
outcomeColor = inOrder[inOrder.length - 1];
if (burned.length > 1) flags.push("more than one dragon marked Incinerated");
} else if (hour === "DIED before the hour") outcome = "Died before the hour";
else outcome = "No outcome recorded";
const rescued = enc.Green === "Saved by another" && outcome === "Bonded" && ["Orange", "Brown"].includes(outcomeColor);
const attempt = parseAttempt(g("attempt"));
return {
source, date, wing, section, squad: g("squad") || "Unknown", attempt,
attempt_group: attempt === 1 ? "First attempt" : attempt > 1 ? "Later attempt" : "Unknown/lost count",
goal: g("goal") || "(not asked/blank)", company, direction, first_sighting: first || "Unknown",
scream, resolution, combat_first: combat || "(not recorded)", post_path: post, hour, branch,
enc_Red: enc.Red, enc_Green: enc.Green, enc_Orange: enc.Orange, enc_Brown: enc.Brown,
enc_Blue: enc.Blue, enc_Black: enc.Black,
outcome, outcome_color: outcomeColor, rescued,
saw_blue_meadow: !!(hour === "Valley" && enc.Blue),
saw_shadow: !!(hour === "Tree" && (enc.Blue || enc.Black)),
data_flags: flags.join("; "),
death_note: redact(g("death_note")), bond_note: redact(g("bond_note")),
};
}
function codeRows(rows, headers) {
if (!headers) {
const seen = new Set();
rows.forEach((r) => Object.keys(r).forEach((k) => seen.add(k)));
headers = [...seen];
}
const { C, missing } = findColumns(headers);
const runs = rows.map((r, i) => Object.assign({ run_id: i + 1 }, codeRow(r, C)));
return { runs, missing };
}
// ---------------------------------------------------------------- statistics
const Z95 = 1.959963984540054;
function wilson(k, n) {
if (!n) return { k, n, p: null, lo: null, hi: null };
const z = Z95, p = k / n, d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return { k, n, p, lo: Math.max(0, c - h), hi: Math.min(1, c + h) };
}
const LOGF = [0];
function logFact(n) {
for (let i = LOGF.length; i <= n; i++) LOGF[i] = LOGF[i - 1] + Math.log(i);
return LOGF[n];
}
// Two-sided Fisher exact test: sum of probabilities of all tables (same margins) no more likely
// than the observed one (same rule as scipy.stats.fisher_exact, with a 1e-7 relative tolerance).
function fisher(a, b, c, d) {
const r1 = a + b, r2 = c + d, c1 = a + c, n = r1 + r2;
const lp = (x) => logFact(r1) + logFact(r2) + logFact(c1) + logFact(n - c1) -
logFact(n) - logFact(x) - logFact(r1 - x) - logFact(c1 - x) - logFact(r2 - c1 + x);
const lo = Math.max(0, c1 - r2), hi = Math.min(r1, c1);
const pObs = lp(a);
let p = 0;
for (let x = lo; x <= hi; x++) {
const q = lp(x);
if (q <= pObs + 1e-7 * Math.abs(pObs) + 1e-12) p += Math.exp(q);
}
return Math.min(1, p);
}
function oddsRatio(a, b, c, d) {
const corrected = a === 0 || b === 0 || c === 0 || d === 0;
const k = corrected ? 0.5 : 0;
const A = a + k, B = b + k, Cc = c + k, D = d + k;
const or = (A * D) / (B * Cc);
const se = Math.sqrt(1 / A + 1 / B + 1 / Cc + 1 / D);
return {
or, or_lo: Math.exp(Math.log(or) - Z95 * se), or_hi: Math.exp(Math.log(or) + Z95 * se),
fisher_p: fisher(a, b, c, d), corrected,
};
}
// Mantel-Haenszel common odds ratio across strata (tables [a,b,c,d]), Robins-Breslow-Greenland 95% CI,
// and the Cochran-Mantel-Haenszel chi-square test (1 df, with continuity correction).
function mantelHaenszel(tables) {
let R = 0, S = 0, PR = 0, PSQR = 0, QS = 0, sumA = 0, sumE = 0, sumV = 0;
for (const [a, b, c, d] of tables) {
const n = a + b + c + d;
if (n < 2) continue;
const r = (a * d) / n, s_ = (b * c) / n, P = (a + d) / n, Q = (b + c) / n;
R += r; S += s_; PR += P * r; PSQR += P * s_ + Q * r; QS += Q * s_;
const m1 = a + b, m0 = c + d, n1 = a + c, n0 = b + d;
sumA += a; sumE += (m1 * n1) / n;
sumV += (m1 * m0 * n1 * n0) / (n * n * (n - 1));
}
if (!R || !S) return { mh_or: null, mh_lo: null, mh_hi: null, mh_p: null };
const or = R / S;
const varLog = PR / (2 * R * R) + PSQR / (2 * R * S) + QS / (2 * S * S);
const se = Math.sqrt(varLog);
const chi = sumV > 0 ? Math.pow(Math.max(0, Math.abs(sumA - sumE) - 0.5), 2) / sumV : 0;
return { mh_or: or, mh_lo: Math.exp(Math.log(or) - Z95 * se), mh_hi: Math.exp(Math.log(or) + Z95 * se), mh_p: normSf2(Math.sqrt(chi)) };
}
function bh(ps) {
const m = ps.length, order = ps.map((p, i) => [p, i]).sort((x, y) => x[0] - y[0]);
const q = new Array(m);
let prev = 1;
for (let r = m; r >= 1; r--) {
const [p, i] = order[r - 1];
prev = Math.min(prev, (p * m) / r);
q[i] = prev;
}
return q;
}
// Normal CDF (Abramowitz-Stegun 7.1.26 is too coarse for small p; use erfc via continued fraction)
function normSf2(z) { // two-sided p for |z|
z = Math.abs(z);
const t = 1 / (1 + 0.5 * z / Math.SQRT2);
const x = z / Math.SQRT2;
const tau = t * Math.exp(-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 +
t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 +
t * (-0.82215223 + t * 0.17087277)))))))));
return Math.min(1, tau); // erfc(x) = 2*P(Z>z)
}
function solve(A, b) { // Gaussian elimination with partial pivoting
const n = b.length, M = A.map((r, i) => r.concat([b[i]]));
for (let i = 0; i < n; i++) {
let p = i;
for (let r = i + 1; r < n; r++) if (Math.abs(M[r][i]) > Math.abs(M[p][i])) p = r;
[M[i], M[p]] = [M[p], M[i]];
for (let r = i + 1; r < n; r++) {
const f = M[r][i] / M[i][i];
for (let c = i; c <= n; c++) M[r][c] -= f * M[i][c];
}
}
const x = new Array(n).fill(0);
for (let i = n - 1; i >= 0; i--) {
let s = M[i][n];
for (let c = i + 1; c < n; c++) s -= M[i][c] * x[c];
x[i] = s / M[i][i];
}
return x;
}
function invert(A) {
const n = A.length;
return A.map((_, j) => solve(A, A.map((__, i) => (i === j ? 1 : 0)))).reduce((acc, col, j) => {
col.forEach((v, i) => (acc[i][j] = v));
return acc;
}, A.map(() => new Array(n).fill(0)));
}
// Logistic regression, Newton-Raphson with an L2 penalty (lambda) on all slopes (not the intercept).
function logisticRidge(X, y, lam = 1, iters = 100) {
const n = X.length, k = X[0].length;
let beta = new Array(k).fill(0);
const info = (b) => {
const H = Array.from({ length: k }, () => new Array(k).fill(0));
const grad = new Array(k).fill(0);
for (let i = 0; i < n; i++) {
let eta = 0;
for (let j = 0; j < k; j++) eta += X[i][j] * b[j];
const mu = 1 / (1 + Math.exp(-eta)), w = mu * (1 - mu);
for (let j = 0; j < k; j++) {
grad[j] += X[i][j] * (y[i] - mu);
if (!X[i][j]) continue;
for (let l = 0; l < k; l++) H[j][l] += X[i][j] * X[i][l] * w;
}
}
for (let j = 1; j < k; j++) { H[j][j] += lam; grad[j] -= lam * b[j]; }
return { H, grad };
};
for (let it = 0; it < iters; it++) {
const { H, grad } = info(beta);
const step = solve(H, grad);
beta = beta.map((v, j) => v + step[j]);
if (Math.max(...step.map(Math.abs)) < 1e-10) break;
}
const { H } = info(beta);
const Hi = invert(H);
const se = Hi.map((r, j) => Math.sqrt(r[j]));
return { beta, se };
}
// ---------------------------------------------------------------- analysis helpers
const rate = (runs, pred) => wilson(runs.filter(pred).length, runs.length);
const groupBy = (arr, key) => arr.reduce((m, r) => {
const k = typeof key === "function" ? key(r) : r[key];
(m[k] = m[k] || []).push(r);
return m;
}, {});
const sortedKeys = (o) => Object.keys(o).sort();
const stratum = (r) => r.source !== "Form" ? "Bulk logs (imports)" :
r.goal === "Blue" ? "Form: chasing Blue" : r.goal === "Black" ? "Form: chasing Black" : "Form: other/blank goal";
const goal2 = (r) => ["Blue", "Black"].includes(r.goal) ? r.goal : r.goal === "(not asked/blank)" ? "Blank/not asked" : "Other colour/any";
// Denominators for each outcome ("who could have had this outcome?")
const OUTCOMES = {
blue_meadow: {
label: "Blue appears in the meadow", denom: (r) => r.branch === "Passed the Red: meadow", event: (r) => r.saw_blue_meadow,
},
shadow: {
label: "Shadow option appears at the tree", denom: (r) => r.hour === "Tree" && r.branch !== null, event: (r) => r.saw_shadow,
},
bond_blue_meadow: {
label: "Bond, given you approached the meadow Blue", denom: (r) => r.branch === "Passed the Red: meadow" && ["Bonded!", "Incinerated"].includes(r.enc_Blue),
event: (r) => r.enc_Blue === "Bonded!",
},
reach_hour: {
label: "Survive to the hour (tree/valley choice)", denom: () => true, event: (r) => r.hour === "Tree" || r.hour === "Valley",
},
};
for (const c of COLORS) {
OUTCOMES["bonded_" + c] = {
label: `Run ends bonded to ${c}`, denom: (r) => r.hour === "Tree" || r.hour === "Valley",
event: (r) => r.outcome === "Bonded" && r.outcome_color === c,
};
}
const FACTORS = ["company", "direction", "first_sighting", "scream", "resolution", "combat_first",
"post_path", "hour", "wing", "squad", "attempt_group", "source", "goal"];
// Encounter contexts: which recorded dragon attempt belongs to which in-game encounter.
const CONTEXTS = [
["Red (tree, descend quickly)", (r) => r.hour === "Tree" && r.branch === "Descend quickly: Red", "enc_Red", "Red"],
["Green (two Greens)", (r) => r.hour === "Tree" && r.branch === "Descend slowly: two Greens", "enc_Green", "Green"],
["Blue (shadow)", (r) => r.hour === "Tree" && r.branch === "Shadow (rare)", "enc_Blue", "Blue"],
["Black (shadow)", (r) => r.hour === "Tree" && r.branch === "Shadow (rare)", "enc_Black", "Black"],
["Red (valley)", (r) => r.hour === "Valley" && r.branch === "Valley Red", "enc_Red", "Red"],
["Orange (meadow)", (r) => r.hour === "Valley" && r.branch === "Passed the Red: meadow", "enc_Orange", "Orange"],
["Brown (meadow)", (r) => r.hour === "Valley" && r.branch === "Passed the Red: meadow", "enc_Brown", "Brown"],
["Blue (meadow)", (r) => r.hour === "Valley" && r.branch === "Passed the Red: meadow", "enc_Blue", "Blue"],
];
function applyFilters(runs, f = {}) {
return runs.filter((r) => {
if (f.source === "form" && r.source !== "Form") return false;
if (f.source === "bulk" && r.source === "Form") return false;
if (f.goal === "exclude_rare" && ["Blue", "Black"].includes(r.goal)) return false;
if (f.goal === "only_rare" && !["Blue", "Black"].includes(r.goal)) return false;
if (f.excludeFlagged && r.data_flags) return false;
return true;
});
}
function factorTable(runs, outKey, minN = 5) {
const O = OUTCOMES[outKey];
const D = runs.filter(O.denom);
const total = D.length, events = D.filter(O.event).length;
const rows = [];
for (const f of FACTORS) {
const groups = groupBy(D.filter((r) => r[f] !== null && r[f] !== undefined), f);
const nf = Object.values(groups).reduce((s, g) => s + g.length, 0);
const ef = Object.values(groups).reduce((s, g) => s + g.filter(O.event).length, 0);
for (const lv of sortedKeys(groups)) {
const g = groups[lv], k = g.filter(O.event).length, n = g.length;
const row = Object.assign({ factor: f, level: lv }, wilson(k, n));
const rk = ef - k, rn = nf - n; // rest of the same factor
if (n >= minN && rn >= minN && ef > 0 && ef < nf) Object.assign(row, oddsRatio(k, n - k, rk, rn - rk));
rows.push(row);
}
}
const tested = rows.filter((r) => r.fisher_p !== undefined);
bh(tested.map((r) => r.fisher_p)).forEach((q, i) => (tested[i].q = q));
return { outcome: outKey, label: O.label, overall: wilson(events, total), rows };
}
// Multivariable model: one row per run in the outcome's denominator; categorical factors dummy-coded
// against their most common level.
function model(runs, outKey, factors, lam = 1) {
const O = OUTCOMES[outKey];
const D = runs.filter(O.denom).map((r) => {
const o = { y: O.event(r) ? 1 : 0 };
for (const [name, fn] of Object.entries(factors)) o[name] = fn(r);
return o;
}).filter((o) => Object.keys(factors).every((f) => o[f] !== null && o[f] !== undefined));
if (D.length < 20) return null;
const cols = [["(intercept)", () => 1]], refs = {};
for (const f of Object.keys(factors)) {
const counts = groupBy(D, f);
const levels = sortedKeys(counts).sort((a, b) => counts[b].length - counts[a].length || (a < b ? -1 : 1));
refs[f] = levels[0];
for (const lv of levels.slice(1)) cols.push([`${f} = ${lv}`, (o) => (o[f] === lv ? 1 : 0), f, lv, counts[lv].length]);
}
const X = D.map((o) => cols.map((c) => c[1](o)));
const y = D.map((o) => o.y);
const { beta, se } = logisticRidge(X, y, lam);
const terms = cols.slice(1).map((c, i) => {
const b = beta[i + 1], s = se[i + 1];
return { term: c[0], factor: c[2], level: c[3], n: c[4], or: Math.exp(b), lo: Math.exp(b - Z95 * s), hi: Math.exp(b + Z95 * s), p: normSf2(b / s) };
});
return { outcome: outKey, label: O.label, n: D.length, events: y.reduce((a, b) => a + b, 0), refs, lambda: lam, terms };
}
const routeKey = (r) => [r.company, r.direction, r.first_sighting, r.scream, r.resolution, r.post_path || "—", r.hour || "—"];
const ROUTE_FIELDS = ["company", "direction", "first_sighting", "scream", "resolution", "post_path", "hour"];
function analyse(allRuns, filters = {}) {
const runs = applyFilters(allRuns, filters);
const res = { filters, n: runs.length };
// meta / data quality
const flagCounts = {};
runs.forEach((r) => r.data_flags && r.data_flags.split("; ").forEach((f) => {
const key = f.startsWith("first sighting") ? "first sighting outside documented pool" : f;
flagCounts[key] = (flagCounts[key] || 0) + 1;
}));
const dates = runs.map((r) => r.date).filter(Boolean).sort();
res.meta = {
sources: Object.fromEntries(Object.entries(groupBy(runs, "source")).map(([k, v]) => [k, v.length])),
date_min: dates[0] || null, date_max: dates[dates.length - 1] || null,
n_flagged: runs.filter((r) => r.data_flags).length, flag_counts: flagCounts,
outcomes: Object.fromEntries(Object.entries(groupBy(runs, (r) => r.outcome + (r.outcome_color ? " " + r.outcome_color : ""))).map(([k, v]) => [k, v.length])),
};
// chance events, overall and by stratum
res.chance = {};
for (const key of ["blue_meadow", "shadow"]) {
const O = OUTCOMES[key], D = runs.filter(O.denom);
res.chance[key] = {
label: O.label, overall: rate(D, O.event),
by_stratum: Object.fromEntries(sortedKeys(groupBy(D, stratum)).map((s) => [s, rate(groupBy(D, stratum)[s], O.event)])),
by_goal: Object.fromEntries(sortedKeys(groupBy(D, "goal")).map((s) => [s, rate(groupBy(D, "goal")[s], O.event)])),
by_attempt: Object.fromEntries(sortedKeys(groupBy(D, "attempt_group")).map((s) => [s, rate(groupBy(D, "attempt_group")[s], O.event)])),
};
}
// first sighting pools
const fs = groupBy(runs.filter((r) => r.direction !== "Multiple" && r.direction !== "Unknown"), (r) => r.company + "|" + r.direction);
res.first_sighting = sortedKeys(fs).map((k) => {
const g = fs[k], cnt = groupBy(g, "first_sighting");
return { key: k, n: g.length, colors: Object.fromEntries(sortedKeys(cnt).map((c) => [c, cnt[c].length])) };
});
// bonding encounters
res.encounters = CONTEXTS.map(([name, where, col, color]) => {
const A = runs.filter((r) => where(r) && ["Bonded!", "Incinerated"].includes(r[col]));
const win = (r) => r[col] === "Bonded!";
const intent = A.filter((r) => r.goal === color || r.goal.startsWith("Any"));
const byS = groupBy(A, stratum);
return {
context: name, color, overall: rate(A, win), intent_matched: rate(intent, win),
by_stratum: Object.fromEntries(sortedKeys(byS).map((s) => [s, rate(byS[s], win)])),
};
});
const greens = runs.filter((r) => r.hour === "Tree" && r.branch === "Descend slowly: two Greens" && r.enc_Green);
res.green_rescue = {
green_encounters: greens.length,
bonded_green: greens.filter((r) => r.enc_Green === "Bonded!").length,
rescued_orange: greens.filter((r) => r.rescued && r.outcome_color === "Orange").length,
rescued_brown: greens.filter((r) => r.rescued && r.outcome_color === "Brown").length,
incinerated: greens.filter((r) => r.outcome === "Incinerated").length,
};
// factor tables
res.factors = {};
for (const key of Object.keys(OUTCOMES)) res.factors[key] = factorTable(runs, key);
// adjusted models
const first2 = (r) => ["Red", "Brown", "Orange", "Green"].includes(r.first_sighting) ? r.first_sighting : "Unsure/unknown";
const src2 = (r) => (r.source === "Form" ? "Form submission" : "Bulk log (import)");
res.models = {
blue_meadow: model(runs, "blue_meadow", {
source: src2, goal: goal2, direction: (r) => r.direction, first_sighting: first2,
resolution: (r) => r.resolution, company: (r) => (r.company === "Unknown" ? null : r.company),
}),
shadow: model(runs, "shadow", {
source: src2, goal: goal2, attempt: (r) => r.attempt_group, direction: (r) => r.direction,
}),
bond_blue_meadow: model(runs, "bond_blue_meadow", {
source: src2, goal: goal2, direction: (r) => r.direction, resolution: (r) => r.resolution,
}),
};
// daily trend (form submissions only, since imports have no date)
const byDate = groupBy(runs.filter((r) => r.date), "date");
res.daily = sortedKeys(byDate).map((d) => {
const g = byDate[d];
const m = g.filter(OUTCOMES.blue_meadow.denom), t = g.filter(OUTCOMES.shadow.denom);
return { date: d, runs: g.length, meadow_n: m.length, blue_k: m.filter((r) => r.saw_blue_meadow).length, tree_n: t.length, shadow_k: t.filter((r) => r.saw_shadow).length };
});
// routes (choices up to the hour) with outcome rates
const R = groupBy(runs.filter((r) => r.hour === "Tree" || r.hour === "Valley"), (r) => routeKey(r).join(" › "));
res.routes = sortedKeys(R).map((k) => {
const g = R[k], m = g.filter(OUTCOMES.blue_meadow.denom), t = g.filter(OUTCOMES.shadow.denom);
const o = { route: k, parts: routeKey(g[0]), n: g.length, blue_meadow: rate(m, (r) => r.saw_blue_meadow), shadow: rate(t, (r) => r.saw_shadow) };
for (const c of COLORS) o["bonded_" + c] = rate(g, (r) => r.outcome === "Bonded" && r.outcome_color === c);
o.bonded_any = rate(g, (r) => r.outcome === "Bonded");
return o;
});
return res;
}
// ---------------------------------------------------------------- route-map graph
const STAGES = [
{ key: "company", label: "Company" },
{ key: "direction", label: "Direction" },
{ key: "first_sighting", label: "First sighting" },
{ key: "cadet", label: "Cadet encounter" },
{ key: "post_path", label: "Fork in the road" },
{ key: "hour", label: "After an hour" },
{ key: "encounter", label: "Encounter" },
{ key: "end", label: "Outcome" },
];
const CHANCE_STAGES = new Set(["first_sighting", "encounter"]); // decided (partly) by the game, not the player
function stageValue(r, key) {
switch (key) {
case "company": return r.company;
case "direction": return r.direction;
case "first_sighting": return r.scream === "DIED at first sighting" ? null : r.first_sighting;
case "cadet":
if (r.scream.startsWith("DIED")) return null;
return r.scream === "Investigate & help" ? "Help → " + r.resolution : r.scream + " → " + r.resolution;
case "post_path": return r.post_path;
case "hour": return r.hour === "Tree" ? "Climb the tree" : r.hour === "Valley" ? "Valley centre" : null;
case "encounter": {
if (!r.branch) return null;
if (r.hour === "Tree") {
if (r.branch === "Shadow (rare)") return "Tree: shadow → Blue/Black";
if (r.branch === "Descend quickly: Red") return "Tree: Red below";
return "Tree: two Greens";
}
if (r.branch === "Valley Red") return "Valley: bond the Red";
if (r.enc_Blue) return "Meadow: Blue";
if (r.enc_Orange && r.enc_Brown) return "Meadow: Orange/Brown";
if (r.enc_Orange) return "Meadow: Orange";
if (r.enc_Brown) return "Meadow: Brown";
return "Meadow (no attempt recorded)";
}
case "end":
if (r.outcome === "Bonded") return "Bonded " + r.outcome_color;
if (r.outcome === "Incinerated") return "Incinerated";
if (r.outcome === "Died before the hour") return "Died before the hour";
return null;
}
return null;
}
// pool = which runs could have reached this outcome at all (used by rankRoutes as the comparison group)
const BOTH = (r) => r.hour === "Tree" || r.hour === "Valley";
const TREE = (r) => r.hour === "Tree";
const VALLEY = (r) => r.hour === "Valley";
const TARGETS = {
bond_Blue: { label: "Bond Blue", color: "Blue", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Blue", pool: VALLEY },
bond_Black: { label: "Bond Black", color: "Black", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Black", pool: TREE },
see_Blue: { label: "Meet a Blue (meadow)", color: "Blue", fn: (r) => r.saw_blue_meadow, pool: (r) => r.branch === "Passed the Red: meadow" },
see_shadow: { label: "Get the tree shadow", color: "Black", fn: (r) => r.saw_shadow, pool: (r) => r.hour === "Tree" && r.branch !== null },
bond_Red: { label: "Bond Red", color: "Red", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Red", pool: BOTH },
bond_Green: { label: "Bond Green", color: "Green", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Green", pool: TREE },
bond_Orange: { label: "Bond Orange", color: "Orange", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Orange", pool: BOTH },
bond_Brown: { label: "Bond Brown", color: "Brown", fn: (r) => r.outcome === "Bonded" && r.outcome_color === "Brown", pool: BOTH },
bond_any: { label: "Bond any dragon", color: null, fn: (r) => r.outcome === "Bonded", pool: BOTH },
};
// conditions: { stageKey: Set(values) } — a run passes if, for every stage with a condition, its value is in the set.
function buildGraph(runs, targetKey, conditions = {}) {
const T = TARGETS[targetKey].fn;
const sel = runs.filter((r) => Object.entries(conditions).every(([k, set]) => !set.size || set.has(stageValue(r, k))));
const nodes = new Map(), links = new Map();
const node = (si, v) => {
const id = si + "|" + v;
if (!nodes.has(id)) nodes.set(id, { id, stage: si, stageKey: STAGES[si].key, value: v, n: 0, k: 0 });
return nodes.get(id);
};
for (const r of sel) {
const hit = T(r) ? 1 : 0;
let prev = null;
STAGES.forEach((s, si) => {
const v = stageValue(r, s.key);
if (v === null || v === undefined) return;
const nd = node(si, v);
nd.n++; nd.k += hit;
if (prev) {
const id = prev.id + "→" + nd.id;
if (!links.has(id)) links.set(id, { id, source: prev.id, target: nd.id, n: 0, k: 0, chance: CHANCE_STAGES.has(s.key) });
const l = links.get(id); l.n++; l.k += hit;
}
prev = nd;
});
}
const out = (o) => Object.assign(o, wilson(o.k, o.n));
return {
stages: STAGES, selected: sel.length, target: targetKey,
nodes: [...nodes.values()].map(out), links: [...links.values()].map(out),
};
}
// Rank full routes (every choice up to the hour) for a target outcome.
// Each route with at least minN runs is compared with all other runs by Fisher's exact test;
// q-values use Benjamini-Hochberg across all ranked routes. Ranking uses the lower 95% Wilson
// bound, so a route needs both a high rate and enough runs to rank high.
function rankRoutes(runs, targetKey, minN = 10, denomStage = null) {
const T = TARGETS[targetKey].fn;
const keyStages = STAGES.slice(0, 6).map((s) => s.key);
const pool = runs.filter(TARGETS[targetKey].pool);
const totK = pool.filter(T).length, totN = pool.length;
const groups = groupBy(pool, (r) => keyStages.map((k) => stageValue(r, k) || "—").join(" › "));
const rows = Object.entries(groups).filter(([, g]) => g.length >= minN).map(([key, g]) => {
const k = g.filter(T).length, n = g.length;
const o = Object.assign({ route: key, values: keyStages.map((s) => stageValue(g[0], s)) }, wilson(k, n));
Object.assign(o, oddsRatio(k, n - k, totK - k, totN - n - (totK - k)));
// same comparison, adjusted for data source / chase-goal stratum (reporting bias)
const inRoute = new Set(g);
const tabs = Object.values(groupBy(pool, stratum)).map((sg) => {
const a = sg.filter((r) => inRoute.has(r) && T(r)).length, nin = sg.filter((r) => inRoute.has(r)).length;
const c = sg.filter((r) => !inRoute.has(r) && T(r)).length, nout = sg.length - nin;
return [a, nin - a, c, nout - c];
});
Object.assign(o, mantelHaenszel(tabs));
return o;
});
bh(rows.map((r) => r.fisher_p)).forEach((q, i) => (rows[i].q = q));
const mhIdx = rows.map((r, i) => [r.mh_p, i]).filter(([p]) => p !== null);
bh(mhIdx.map(([p]) => p)).forEach((q, j) => (rows[mhIdx[j][1]].mh_q = q));
rows.sort((a, b) => b.lo - a.lo || b.n - a.n);
return { target: targetKey, overall: wilson(totK, totN), minN, n_routes_tested: rows.length, rows };
}
return {
COLORS, COLUMN_KEYS, STAGES, TARGETS, OUTCOMES, FACTORS, ROUTE_FIELDS, rankRoutes,
findColumns, codeRow, codeRows, parseTimestamp,
wilson, fisher, oddsRatio, bh, logisticRidge, mantelHaenszel,
applyFilters, analyse, factorTable, model, buildGraph, stageValue, stratum,
};
});
+214
View File
@@ -0,0 +1,214 @@
/*
* 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"],
[/^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)"],
[/^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"]
];
/** 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", "direction", "first_sighting", "scream", "combat_first", "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"];
const MISSING = new Set([null, undefined, "", "Unknown", "Unsure", "Multiple", "(no fork)", "(not recorded)"]);
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 };
});
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env node
'use strict';
/**
* Convert a local copy of the DragonKind bot's data into the public, anonymised format.
*
* node packages/ingest/bin/import-bot.js --bot /path/to/DragonKind [--out data/bot] [--tag 2026-11-01]
*
* Reads <bot>/data/knowledge.json, <bot>/data/runs.jsonl and <bot>/logs/encounters.jsonl.
* Writes <out>/scenes.json (merged with any existing catalogue) and <out>/trajectories-<tag>.jsonl.
* Set DK_ACCOUNT_SALT in the environment to hash account ids; never commit the salt.
*/
const fs = require('node:fs');
const path = require('node:path');
const { importBot, assertPublicSafe } = require('../src/bot');
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => {
if (a.startsWith('--')) acc.push([a.slice(2), all[i + 1]]);
return acc;
}, []));
if (!args.bot) {
console.error('usage: import-bot.js --bot /path/to/DragonKind [--out data/bot] [--tag YYYY-MM-DD]');
process.exit(2);
}
const out = path.resolve(args.out || 'data/bot');
const tag = args.tag || new Date().toISOString().slice(0, 10);
const { scenes, trajectories, unlabeled } = importBot({
dataDir: path.join(args.bot, 'data'),
logsDir: path.join(args.bot, 'logs')
});
assertPublicSafe(scenes);
assertPublicSafe(trajectories);
fs.mkdirSync(out, { recursive: true });
const sceneFile = path.join(out, 'scenes.json');
const existing = fs.existsSync(sceneFile) ? JSON.parse(fs.readFileSync(sceneFile, 'utf8')) : {};
for (const [id, s] of Object.entries(scenes)) {
const old = existing[id];
if (!old) { existing[id] = s; continue; }
const ids = new Set(old.options.map((o) => o.id));
for (const o of s.options) if (!ids.has(o.id)) old.options.push(o);
old.tint = old.tint || s.tint;
old.backdrop = old.backdrop || s.backdrop;
if (old.label.includes('·') && !s.label.includes('·')) old.label = s.label;
}
const sorted = Object.fromEntries(Object.entries(existing).sort(([a], [b]) => a.localeCompare(b)));
fs.writeFileSync(sceneFile, `${JSON.stringify(sorted, null, 1)}\n`);
const trajFile = path.join(out, `trajectories-${tag}.jsonl`);
fs.writeFileSync(trajFile, trajectories.map((t) => JSON.stringify(t)).join('\n') + '\n');
const outcomes = trajectories.reduce((m, t) => ((m[t.outcome.type] = (m[t.outcome.type] || 0) + 1), m), {});
console.log(`${Object.keys(scenes).length} scenes, ${trajectories.length} attempts ${JSON.stringify(outcomes)}`);
console.log(`wrote ${path.relative(process.cwd(), sceneFile)} and ${path.relative(process.cwd(), trajFile)}`);
if (unlabeled.length) console.log(`scenes without a short label (add them to LABELS in packages/ingest/src/bot.js):\n ${unlabeled.join('\n ')}`);
+8
View File
@@ -0,0 +1,8 @@
{
"name": "@threshing-atlas/ingest",
"version": "0.1.0",
"description": "Importers that turn DragonKind bot data and community sources into the shared graph format (no game prose).",
"main": "src/bot.js",
"bin": { "threshing-import-bot": "bin/import-bot.js" },
"license": "MIT"
}
+211
View File
@@ -0,0 +1,211 @@
'use strict';
/**
* Import DragonKind bot data into anonymised trajectories and a scene catalogue.
*
* Inputs (all from the PRIVATE bot repo, read locally, never committed):
* data/knowledge.json scene atlas: nodes (prose, choices, tint, backdrop) and edges
* data/runs.jsonl one record per attempt (newer bot versions)
* logs/encounters.jsonl every decision the bot made, with the options on screen
*
* Outputs (public, CC BY 4.0): no game prose, only fingerprints, short labels and choice text.
* scenes.json { sceneId: { stage, tint, backdrop, label, options: [{ id, text }] } }
* trajectories.jsonl one line per attempt: { id, source, meta, steps: [...], outcome }
*/
const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const sha1 = (s, n = 12) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, n);
// Must match normalize() in the bot's src/strategy.js, so fingerprints line up.
function normalize(text) {
return String(text || '')
.toLowerCase()
.replace(/[‘’‛`']/g, "'")
.replace(/[“”"]/g, '"')
.replace(/[–—-]/g, ' ')
.replace(/…/g, ' ')
.replace(/[^a-z0-9'\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
// Must match computeSceneFingerprint() in the bot's src/learner.js.
function sceneId(prose, choices) {
const proseNorm = normalize(prose).slice(0, 500);
const sorted = choices.map(normalize).filter(Boolean).sort();
return sha1(`${proseNorm} ### ${sorted.join(' || ')}`);
}
const optionId = (text) => sha1(normalize(text), 10);
const readJsonl = (file) => {
if (!file || !fs.existsSync(file)) return [];
return fs.readFileSync(file, 'utf8').split(/\r?\n/).filter((l) => l.trim()).map((l) => {
try { return JSON.parse(l); } catch { return null; }
}).filter(Boolean);
};
/**
* Short public labels. Keys are scene fingerprints; values are our own paraphrases, not game prose.
* Unknown scenes fall back to "<stage> · <tint>" and are listed by the importer so labels can be added.
*/
const LABELS = {
db7786392626: 'Start: choose company',
a68f681076c6: 'Valley edge: choose direction',
bc4ee4754b9c: 'First sighting: Red (forest centre)',
abe3011378ac: 'First sighting: Brown (forest centre)',
'84780dab01e3': 'Survived the first sighting',
d25f2759ace0: 'Deeper in the forest: a scream',
f72199f24b91: 'Clearing: squadmate vs two bullies',
b209bacacec3: 'Bully fight: first move',
fbe0f0bea700: 'Bully fight: smaller cadet has a dagger',
a2368b0dc212: 'Blocked the bigger cadet: bullies’ fate',
f4b4944d3f3b: 'Beat the smaller cadet: bullies’ fate',
'0cfd06cf8939': 'After the fight: choose a direction',
'0a561d53ad19': 'An hour later: valley or tree',
'96b68612eaf4': 'Top of the tree (shadow check)',
'10bc7353b8eb': 'Descended quickly: a Red below',
c62f1f1a2b3a: 'Let the Red pass: two Greens in the clearing',
'07e24681e3b3': 'Descended slowly: two Greens in the clearing'
};
function labelFor(id, node) {
if (LABELS[id]) return LABELS[id];
const bits = [node.stage || 'Scene'];
if (node.tint) bits.push(node.tint);
return bits.join(' · ');
}
/** Scene catalogue from knowledge.json (and, for scenes only in the log, from the log). */
function buildScenes(knowledge, encounters) {
const scenes = {};
for (const [id, n] of Object.entries((knowledge && knowledge.nodes) || {})) {
scenes[id] = {
stage: n.stage || 'UNKNOWN',
tint: n.tint || null,
backdrop: n.backdrop || null,
label: labelFor(id, n),
options: Object.values(n.choices || {}).map((c) => ({ id: optionId(c.label || c.choiceNorm), text: c.label || c.choiceNorm }))
};
}
for (const e of encounters) {
if (!Array.isArray(e.choices) || !e.prose) continue;
const id = e.nodeId || sceneId(e.prose, e.choices);
if (scenes[id]) continue;
const stage = (e.decision && e.decision.stage) || e.stage || 'UNKNOWN';
scenes[id] = { stage, tint: null, backdrop: null, label: labelFor(id, { stage }), options: e.choices.map((t) => ({ id: optionId(t), text: t })) };
}
return scenes;
}
const CHOICE_EVENTS = new Set(['DECISION', 'MANUAL_DECISION', 'MANUAL_EDGE_PICK']);
/**
* Trajectories from the encounter log: group events by attempt, keep the decisions that were acted on,
* and close each attempt at its first BURNED / DRAGON_BONDED event. Repeated BURNED events with no
* decisions in between (the cooldown screen being re-detected) are ignored.
*/
function trajectoriesFromEncounters(encounters, scenes) {
const byAttempt = new Map();
for (const e of encounters) {
const key = e.account ? `${e.account}:${e.attempt}` : String(e.attempt);
if (!byAttempt.has(key)) byAttempt.set(key, []);
byAttempt.get(key).push(e);
}
const out = [];
for (const [key, events] of byAttempt) {
events.sort((a, b) => String(a.ts).localeCompare(String(b.ts)));
const steps = [];
let outcome = null;
for (const e of events) {
if (outcome) break;
if (CHOICE_EVENTS.has(e.event)) {
const d = e.decision || {};
const text = d.choiceText || e.choiceText;
if (d.action && d.action !== 'choose') continue; // paused, nothing happened
if (!text || !Array.isArray(e.choices)) continue;
const scene = e.nodeId || sceneId(e.prose || '', e.choices);
const manual = e.event !== 'DECISION';
steps.push({
scene,
stage: d.stage || (scenes[scene] && scenes[scene].stage) || 'UNKNOWN',
tint: (scenes[scene] && scenes[scene].tint) || null,
option: optionId(text),
optionText: text,
offered: e.choices.map(optionId),
rule: d.rule || null,
decisionMode: manual ? 'manual' : d.source || null,
manual,
at: e.ts
});
} else if (e.event === 'BURNED' && steps.length) {
outcome = { type: 'BURNED', colour: null, intentional: Boolean(e.intentional) };
} else if (e.event === 'DRAGON_BONDED' && steps.length) {
outcome = { type: 'BONDED', colour: e.dragon ? String(e.dragon).toLowerCase() : null, intentional: false };
}
}
// A decision repeated on the same scene (the bot re-detecting the screen) counts once.
const dedup = steps.filter((s, i) => !(i > 0 && steps[i - 1].scene === s.scene && steps[i - 1].option === s.option));
for (let i = 0; i < dedup.length; i++) dedup[i].to = i + 1 < dedup.length ? dedup[i + 1].scene : null;
if (!dedup.length) continue;
const last = dedup[dedup.length - 1];
if (outcome) last.to = outcome.type === 'BURNED' ? 'BURNED' : `BONDED:${outcome.colour || 'unknown'}`;
out.push({
id: `bot-${sha1(`${key}:${dedup[0].at}`, 10)}`,
source: 'bot',
meta: { attempt: Number(String(key).split(':').pop()) || null, startedAt: dedup[0].at, accountKey: null, target: null, decisionMode: null },
steps: dedup,
outcome: outcome || { type: 'ABORTED', colour: null, intentional: false }
});
}
return out;
}
/** Fill run-level metadata (target colour, mode) from runs.jsonl where an attempt is covered by both. */
function attachRunMeta(trajs, runs, salt) {
for (const r of runs) {
const t = trajs.find((x) => x.meta.attempt === r.attempt && Math.abs(Date.parse(x.meta.startedAt) - Date.parse(r.startedAt)) < 6 * 3600e3);
if (!t) continue;
t.meta.target = r.targetDragon || null;
t.meta.decisionMode = r.decisionMode || null;
t.meta.policyId = r.policyId || null;
t.meta.experimentId = r.experimentId || null;
t.meta.arm = r.arm || null;
if (r.accountKey) t.meta.accountKey = r.accountKey;
else if (r.accountId && salt) t.meta.accountKey = sha1(`${salt}:${r.accountId}`, 10);
if (r.outcome === 'BONDED' && r.dragonColor) t.outcome = { type: 'BONDED', colour: String(r.dragonColor).toLowerCase(), intentional: false };
if (r.intentionalBurn) t.outcome.intentional = true;
}
return trajs;
}
function importBot({ dataDir, logsDir, salt = process.env.DK_ACCOUNT_SALT || null }) {
const knowledgeFile = path.join(dataDir, 'knowledge.json');
const knowledge = fs.existsSync(knowledgeFile) ? JSON.parse(fs.readFileSync(knowledgeFile, 'utf8')) : { nodes: {} };
const encounters = readJsonl(path.join(logsDir, 'encounters.jsonl'));
const runs = readJsonl(path.join(dataDir, 'runs.jsonl'));
const scenes = buildScenes(knowledge, encounters);
const trajectories = attachRunMeta(trajectoriesFromEncounters(encounters, scenes), runs, salt);
const unlabeled = Object.entries(scenes).filter(([id]) => !LABELS[id]).map(([id, s]) => `${id} (${s.stage}${s.tint ? `, ${s.tint}` : ''})`);
return { scenes, trajectories, unlabeled };
}
/** Guard: nothing that looks like game prose or an account identifier may leave this module. */
function assertPublicSafe(obj) {
const banned = ['prose', 'proseNorm', 'proseExcerpt', 'email', 'password', 'accountId', 'accountName'];
const walk = (v, p) => {
if (Array.isArray(v)) return v.forEach((x, i) => walk(x, `${p}[${i}]`));
if (v && typeof v === 'object') {
for (const [k, x] of Object.entries(v)) {
if (banned.includes(k)) throw new Error(`refusing to export field "${k}" at ${p}`);
walk(x, `${p}.${k}`);
}
} else if (typeof v === 'string' && v.length > 200) {
throw new Error(`refusing to export a ${v.length}-character string at ${p} (looks like prose)`);
}
};
walk(obj, '$');
}
module.exports = { normalize, sceneId, optionId, buildScenes, trajectoriesFromEncounters, attachRunMeta, importBot, assertPublicSafe, LABELS };
+134
View File
@@ -0,0 +1,134 @@
"""
analyze.py — Python reference implementation of the statistics shown on the route-map page.
python analyze.py ../../data/derived/runs_clean.csv ../../tests/out/results_py.json
It mirrors analyse() in packages/core/src/engine.js (same denominators, same tests, same model); tests/compare_results.py
checks that both produce the same numbers. Edit either, then re-run the comparison.
"""
import json
import sys
import numpy as np
import pandas as pd
from stats_core import Z95, bh, logistic_ridge, odds_ratio, p_from_z, wilson
COLORS = ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
FACTORS = ["company", "direction", "first_sighting", "scream", "resolution", "combat_first",
"post_path", "hour", "wing", "squad", "attempt_group", "source", "goal"]
def W(k, n):
p, lo, hi = wilson(k, n)
return {"k": int(k), "n": int(n), "p": p, "lo": lo, "hi": hi}
def outcomes():
o = {
"blue_meadow": (lambda d: d.branch == "Passed the Red: meadow", lambda d: d.saw_blue_meadow),
"shadow": (lambda d: (d.hour == "Tree") & d.branch.notna(), lambda d: d.saw_shadow),
"bond_blue_meadow": (lambda d: (d.branch == "Passed the Red: meadow") & d.enc_Blue.isin(["Bonded!", "Incinerated"]),
lambda d: d.enc_Blue == "Bonded!"),
"reach_hour": (lambda d: pd.Series(True, index=d.index), lambda d: d.hour.isin(["Tree", "Valley"])),
}
for c in COLORS:
o["bonded_" + c] = (lambda d: d.hour.isin(["Tree", "Valley"]),
(lambda c: lambda d: (d.outcome == "Bonded") & (d.outcome_color == c))(c))
return o
OUT = outcomes()
def factor_table(d, key, min_n=5):
den, ev = OUT[key]
D = d[den(d)].copy()
D["_e"] = ev(D).astype(bool)
rows = []
for f in FACTORS:
sub = D[D[f].notna()]
nf, ef = len(sub), int(sub._e.sum())
for lv in sorted(sub[f].astype(str).unique()):
g = sub[sub[f].astype(str) == lv]
k, n = int(g._e.sum()), len(g)
row = {"factor": f, "level": lv, **W(k, n)}
rk, rn = ef - k, nf - n
if n >= min_n and rn >= min_n and 0 < ef < nf:
or_, lo, hi, p, corr = odds_ratio(k, n - k, rk, rn - rk)
row.update({"or": or_, "or_lo": lo, "or_hi": hi, "fisher_p": p, "corrected": corr})
rows.append(row)
tested = [r for r in rows if "fisher_p" in r]
for r, q in zip(tested, bh([r["fisher_p"] for r in tested])):
r["q"] = q
return {"outcome": key, "overall": W(int(D._e.sum()), len(D)), "rows": rows}
def model(d, key, factors, lam=1.0):
den, ev = OUT[key]
D = d[den(d)].copy()
y = ev(D).astype(int).values
F = pd.DataFrame({name: D.apply(fn, axis=1) for name, fn in factors.items()}, index=D.index)
keep = F.notna().all(axis=1).values
F, y = F[keep], y[keep]
cols, names = [np.ones(len(F))], []
refs = {}
for f in factors:
counts = F[f].value_counts()
levels = sorted(counts.index, key=lambda lv: (-counts[lv], lv))
refs[f] = levels[0]
for lv in levels[1:]:
cols.append((F[f] == lv).astype(float).values)
names.append((f, lv, int(counts[lv])))
X = np.column_stack(cols)
b, se = logistic_ridge(X, y, lam)
terms = [{"term": f"{f} = {lv}", "factor": f, "level": lv, "n": n, "or": float(np.exp(b[i + 1])),
"lo": float(np.exp(b[i + 1] - Z95 * se[i + 1])), "hi": float(np.exp(b[i + 1] + Z95 * se[i + 1])),
"p": float(p_from_z(b[i + 1] / se[i + 1]))} for i, (f, lv, n) in enumerate(names)]
return {"outcome": key, "n": int(len(y)), "events": int(y.sum()), "refs": refs, "lambda": lam, "terms": terms}
def goal2(r):
if r.goal in ("Blue", "Black"):
return r.goal
return "Blank/not asked" if r.goal == "(not asked/blank)" else "Other colour/any"
def src2(r):
return "Form submission" if r.source == "Form" else "Bulk log (import)"
def first2(r):
return r.first_sighting if r.first_sighting in ("Red", "Brown", "Orange", "Green") else "Unsure/unknown"
def period(r):
if not isinstance(r.date, str):
return "No date (import)"
return "Oct 4–10" if r.date < "2026-10-11" else "Oct 11 onward"
def analyse(d):
res = {"n": len(d), "factors": {k: factor_table(d, k) for k in OUT}}
res["models"] = {
"blue_meadow": model(d, "blue_meadow", {
"source": src2, "goal": goal2, "direction": lambda r: r.direction, "first_sighting": first2,
"resolution": lambda r: r.resolution, "company": lambda r: None if r.company == "Unknown" else r.company}),
"shadow": model(d, "shadow", {
"source": src2, "goal": goal2, "attempt": lambda r: r.attempt_group,
"direction": lambda r: r.direction}),
"bond_blue_meadow": model(d, "bond_blue_meadow", {
"source": src2, "goal": goal2, "direction": lambda r: r.direction, "resolution": lambda r: r.resolution}),
}
return res
if __name__ == "__main__":
src = sys.argv[1] if len(sys.argv) > 1 else "../../data/derived/runs_clean.csv"
out = sys.argv[2] if len(sys.argv) > 2 else "../../tests/out/results_py.json"
d = pd.read_csv(src, keep_default_na=False, na_values=[""])
for c in ("saw_blue_meadow", "saw_shadow", "rescued"):
d[c] = d[c].astype(str) == "True"
res = analyse(d)
json.dump(res, open(out, "w"), indent=1, default=float)
print("wrote", out)
+301
View File
@@ -0,0 +1,301 @@
"""
clean.py — turn the raw "Threshing Routes Responses" Google Form export into one
coded row per threshing run.
Reference implementation in Python. The web page (packages/core/src/engine.js) implements the
same rules in JavaScript; tests/compare.py checks that both give identical output.
Usage:
python clean.py ../../data/raw/form/Threshing_Routes_Responses.xlsx -> writes ../../data/derived/runs_clean.csv
Every coding rule is listed in RULES below and in the "Methods" section of the page.
"""
import re
import sys
from datetime import datetime
import pandas as pd
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def redact(v):
"""Free-text answers sometimes contain a respondent's email address; never display or export it."""
return v if v is None else EMAIL_RE.sub("[email removed]", str(v))
COLORS = ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
# Columns are found by keywords in the question text, so the script keeps working
# if the form owner reorders or adds questions.
COLUMN_KEYS = {
"timestamp": ["timestamp"],
"wing_First": ["wing and section", "[first]"],
"wing_Second": ["wing and section", "[second]"],
"wing_Third": ["wing and section", "[third]"],
"wing_Fourth": ["wing and section", "[fourth]"],
"squad": ["what squad"],
"attempt": ["attempt number"],
"company": ["who accompanied"],
"dir_East": ["initial direction", "[east"],
"dir_West": ["initial direction", "[west"],
"dir_Center": ["initial direction", "[forest center"],
"cadet": ["outcome of your cadet encounter"],
"post": ["path did you take after the bully"],
"hour": ["after walking an hour"],
"enc_Red": ["attempt to bond", "[red"],
"enc_Green": ["attempt to bond", "[green"],
"enc_Orange": ["attempt to bond", "[orange"],
"enc_Brown": ["attempt to bond", "[brown"],
"enc_Blue": ["attempt to bond", "[blue"],
"enc_Black": ["attempt to bond", "[black"],
"death_note": ["those who died"],
"bond_note": ["those who bonded"],
"goal": ["colour dragon are you trying"],
"combat": ["combat choice"],
}
CADET_MAP = {
"Bullies > You dealt with them": ("Investigate & help", "Killed the bullies yourself"),
"Bullies > Squadmate's revenge": ("Investigate & help", "Squadmate's revenge"),
"Bullies > Left to the Dragons": ("Investigate & help", "Left bullies to the dragons"),
"Bullies > Assessed the situation": ("Investigate & help", "Unknown"),
"Injured Cadet > Tourniquet": ("Ignore the scream", "Tourniquet"),
"Injured Cadet > Left them there": ("Ignore the scream", "Left injured cadet"),
"Injured Cadet > Took their weapons": ("Ignore the scream", "Took their weapons"),
"Avoided combat (Investigated scream > Left them to it)": ("Investigate & leave", "Left them to it"),
"You died in combat": ("Investigate & help", "DIED in combat"),
"N/A - You died with initial dragon sighting": ("DIED at first sighting", "DIED at first sighting"),
}
COMBAT_MAP = {
"Bullies > Assessed the situation": "Assess the situation",
"Bullies > Even the numbers (Rushed the smaller cadet)": "Even the numbers (smaller cadet)",
"Bullies > Put yourself in the middle (Rushed the bigger cadet attacking your squadmate)": "Put yourself in the middle (bigger cadet)",
}
HOUR_MAP = {
"Continued to Valley Centre": "Valley",
"Climbed the tallest tree": "Tree",
"N/A - You're dead": "DIED before the hour",
}
# First-sighting pools per (company, direction) according to the community PDF map.
# Used only to FLAG rows that report a dragon outside the documented pool.
SIGHTING_POOL = {
("Alone", "East"): {"Red", "Orange"},
("Alone", "West"): {"Red", "Brown", "Green"},
("Alone", "Center"): {"Red", "Brown"},
("1 Squadmate", "East"): {"Green", "Orange", "Red"}, # 'leave squadmate' -> alone pools also possible
("1 Squadmate", "West"): {"Red", "Brown", "Green"},
("1 Squadmate", "Center"): {"Red", "Brown"},
("2 Squadmates", "East"): {"Red", "Orange"},
("2 Squadmates", "West"): {"Green", "Brown", "Red"},
("2 Squadmates", "Center"): {"Red", "Brown"},
}
def find_columns(cols):
out = {}
low = {c: str(c).lower() for c in cols}
for key, words in COLUMN_KEYS.items():
hits = [c for c in cols if all(w in low[c] for w in words)]
if hits:
out[key] = hits[0]
missing = [k for k in COLUMN_KEYS if k not in out]
return out, missing
def blank(v):
if v is None or v is pd.NaT:
return True
if not isinstance(v, str):
try:
if pd.isna(v):
return True
except (TypeError, ValueError):
pass
return str(v).strip() in ("", "nan", "NaN", "NaT")
def s(v):
return None if blank(v) else str(v).strip()
def parse_timestamp(v):
"""Form submissions carry a timestamp; bulk-pasted rows carry a label such as 'Data Import'.
Returns 'YYYY-MM-DD' or None."""
if isinstance(v, (datetime, pd.Timestamp)) and not pd.isna(v):
return pd.Timestamp(v).strftime("%Y-%m-%d")
if isinstance(v, (int, float)) and not isinstance(v, bool) and 40000 < v < 80000: # Excel serial date
return (pd.Timestamp("1899-12-30") + pd.Timedelta(days=int(v))).strftime("%Y-%m-%d")
t = s(v)
if not t:
return None
m = re.match(r"^(\d{4})-(\d{2})-(\d{2})", t)
if m:
return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
m = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{4})", t) # Google Sheets CSV export: M/D/YYYY
if m:
return f"{m.group(3)}-{int(m.group(1)):02d}-{int(m.group(2)):02d}"
return None
def parse_attempt(v):
v = s(v)
if v is None:
return None
t = v.lower()
if "lost count" in t:
return None
words = {"first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5}
for w, n in words.items():
if t.startswith(w):
return n
m = re.search(r"\d+", t)
return int(m.group()) if m else None
def code_row(r, C):
g = lambda k: s(r[C[k]]) if k in C else None
flags = []
ts = r[C["timestamp"]] if "timestamp" in C else None
d = parse_timestamp(ts)
if d:
source, date = "Form", d
else:
source, date = (s(ts) or "Unknown import"), None
wings = [w for w in ("First", "Second", "Third", "Fourth") if g("wing_" + w)]
wing = wings[0] if len(wings) == 1 else ("Multiple" if wings else "Unknown")
section = g("wing_" + wings[0]) if len(wings) == 1 else None
if len(wings) > 1:
flags.append("multiple wings")
dirs = [d for d in ("East", "West", "Center") if g("dir_" + d)]
if len(dirs) == 1:
direction, first = dirs[0], g("dir_" + dirs[0])
else:
direction, first = ("Multiple" if dirs else "Unknown"), None
flags.append("direction " + ("multiple" if dirs else "missing"))
company = g("company") or "Unknown"
if first and first != "Unsure" and (company, direction) in SIGHTING_POOL:
if first not in SIGHTING_POOL[(company, direction)]:
flags.append(f"first sighting {first} not in documented pool for {company}/{direction}")
cadet_raw = g("cadet")
scream, resolution = CADET_MAP.get(cadet_raw, ("Unknown", "Unknown"))
if cadet_raw and cadet_raw not in CADET_MAP:
flags.append("unrecognised cadet answer")
combat = COMBAT_MAP.get(g("combat")) if g("combat") else None
post_raw = g("post")
if scream == "Investigate & help" and not resolution.startswith("DIED"):
post = post_raw if post_raw in ("Forest", "West", "East") else "Unknown"
elif scream in ("Ignore the scream", "Investigate & leave"):
post = "(no fork)"
if post_raw in ("Forest", "West", "East"):
post = "(no fork)" # the form allowed an answer here; the game has no fork on this branch
else:
post = None
hour = HOUR_MAP.get(g("hour"))
died_early = scream.startswith("DIED") or resolution.startswith("DIED")
if died_early:
hour = None
elif hour is None:
hour = "Unknown"
enc = {c: g("enc_" + c) for c in COLORS}
bonded = [c for c in COLORS if enc[c] == "Bonded!"]
burned = [c for c in COLORS if enc[c] == "Incinerated"]
# Which encounter branch did the run take after the hour?
branch = None
if hour == "Tree":
if enc["Blue"] or enc["Black"]:
branch = "Shadow (rare)"
elif enc["Green"]:
branch = "Descend slowly: two Greens"
elif enc["Red"]:
branch = "Descend quickly: Red"
elif enc["Orange"] or enc["Brown"]:
branch = "Descend slowly: two Greens"
flags.append("tree run with Orange/Brown but no Green recorded")
elif hour == "Valley":
if enc["Green"]:
flags.append("Green recorded on a Valley run (no Greens in the valley)")
red_passed = enc["Red"] in ("Changed my mind",)
meadow = [c for c in ("Orange", "Brown", "Blue") if enc[c]]
if meadow or red_passed:
branch = "Passed the Red: meadow"
elif enc["Red"]:
branch = "Valley Red"
# Final outcome of the run
outcome, outcome_color = None, None
if died_early:
outcome = "Died before the hour"
elif len(bonded) == 1:
outcome, outcome_color = "Bonded", bonded[0]
elif len(bonded) > 1:
outcome = "Ambiguous"
flags.append("more than one dragon marked Bonded")
elif burned:
order = ["Red", "Green", "Orange", "Brown", "Blue", "Black"] if hour != "Valley" else \
["Red", "Orange", "Brown", "Blue", "Green", "Black"]
last = [c for c in order if c in burned][-1]
outcome, outcome_color = "Incinerated", last
if len(burned) > 1:
flags.append("more than one dragon marked Incinerated")
elif hour == "DIED before the hour":
outcome = "Died before the hour"
else:
outcome = "No outcome recorded"
# The dragon whose bonding encounter decided the run (attempted = Bonded or Incinerated)
rescued = enc["Green"] == "Saved by another" and outcome == "Bonded" and outcome_color in ("Orange", "Brown")
attempt = parse_attempt(g("attempt"))
return {
"source": source, "date": date, "wing": wing, "section": section,
"squad": g("squad") or "Unknown", "attempt": attempt,
"attempt_group": "First attempt" if attempt == 1 else ("Later attempt" if attempt and attempt > 1 else "Unknown/lost count"),
"goal": g("goal") or "(not asked/blank)", "company": company,
"direction": direction, "first_sighting": first or "Unknown",
"scream": scream, "resolution": resolution, "combat_first": combat or "(not recorded)",
"post_path": post, "hour": hour, "branch": branch,
**{"enc_" + c: enc[c] for c in COLORS},
"outcome": outcome, "outcome_color": outcome_color, "rescued": rescued,
"saw_blue_meadow": bool(hour == "Valley" and enc["Blue"]),
"saw_shadow": bool(hour == "Tree" and (enc["Blue"] or enc["Black"])),
"data_flags": "; ".join(flags),
"death_note": redact(g("death_note")), "bond_note": redact(g("bond_note")),
}
def load(path):
if str(path).lower().endswith(".json"): # the page's bundled export (data/public/form_responses.json)
import json
d = json.load(open(path, encoding="utf-8"))
raw = pd.DataFrame(d["rows"], columns=d["headers"])
elif str(path).lower().endswith(".csv"):
raw = pd.read_csv(path)
else:
xl = pd.ExcelFile(path)
sheet = next((n for n in xl.sheet_names if "form responses" in n.lower()), xl.sheet_names[0])
raw = pd.read_excel(xl, sheet)
C, missing = find_columns(raw.columns)
rows = [code_row(r, C) for _, r in raw.iterrows()]
df = pd.DataFrame(rows)
df.insert(0, "run_id", range(1, len(df) + 1))
return df, missing
if __name__ == "__main__":
src = sys.argv[1] if len(sys.argv) > 1 else "../../data/public/form_responses.json"
out = sys.argv[2] if len(sys.argv) > 2 else "../../data/derived/runs_clean.csv"
df, missing = load(src)
if missing:
print("WARNING: columns not found:", missing)
df.to_csv(out, index=False)
print(f"{len(df)} runs -> {out}")
print(df.outcome.value_counts().to_string())
print("rows with flags:", (df["data_flags"] != "").sum())
+49
View File
@@ -0,0 +1,49 @@
"""export_raw.py — convert the Google Sheets .xlsx (or .csv) export into the raw JSON the web page loads.
python export_raw.py ../../data/raw/form/Threshing_Routes_Responses.xlsx ../../data/public/form_responses.json
The JSON is a list of objects keyed by the original question text (no recoding happens here, so the page
applies exactly the same cleaning rules to it as it would to a freshly uploaded export).
"""
import json
import sys
from datetime import datetime
import re
import pandas as pd
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def load_raw(path):
if str(path).lower().endswith(".csv"):
return pd.read_csv(path)
xl = pd.ExcelFile(path)
sheet = next((n for n in xl.sheet_names if "form responses" in n.lower()), xl.sheet_names[0])
return pd.read_excel(xl, sheet)
def cell(v):
if v is None or v is pd.NaT or (not isinstance(v, str) and pd.isna(v)):
return None
if isinstance(v, (datetime, pd.Timestamp)):
return pd.Timestamp(v).strftime("%Y-%m-%d %H:%M:%S")
if isinstance(v, float) and v.is_integer():
return int(v)
if isinstance(v, str):
return EMAIL_RE.sub("[email removed]", v) # respondents sometimes leave an email in free text
return v
if __name__ == "__main__":
src = sys.argv[1] if len(sys.argv) > 1 else "../../data/raw/form/Threshing_Routes_Responses.xlsx"
out = sys.argv[2] if len(sys.argv) > 2 else "../../data/public/form_responses.json"
raw = load_raw(src)
rows = [{str(k): cell(v) for k, v in r.items() if cell(v) is not None} for _, r in raw.iterrows()]
# keep every header present even if a row is blank there, so column detection sees all questions
headers = [str(c) for c in raw.columns]
with open(out, "w", encoding="utf-8") as f:
json.dump({"source_file": str(src).split("/")[-1], "exported": datetime.now().strftime("%Y-%m-%d"),
"headers": headers, "rows": rows}, f, ensure_ascii=False, separators=(",", ":"))
print(f"{len(rows)} rows -> {out}")
+43
View File
@@ -0,0 +1,43 @@
"""export_register.py — convert the "Unofficial Dragon Register" .xlsx/.csv export into web/data/register.json.
python export_register.py ../../data/raw/register/Unofficial_Dragon_Register_Responses.xlsx ../../data/public/register.json
Raw rows are kept as-is, except that photo links and rider names are dropped. Dragons read from public dragonkind.com result pages
linked in the Reddit megathreads are stored separately under "extra" with their source URL.
"""
import json
import sys
from datetime import datetime
import pandas as pd
from export_raw import cell, load_raw
# Read from dragonkind.com/results/<id> pages linked in the Part 3 and Part 4 megathreads (2026-10-19).
REDDIT_RESULTS = [
("THRESH-VFRQVM5K3B0CP", "Thiduach", "Blue", "Swordtail", "Female", 51, "Gormfaileas"),
("THRESH-3M4P9MNFQGBS8", "Caenuis", "Blue", "Swordtail", "Female", 38, "Gormfaileas"),
("THRESH-5JQDJ21G1BYKR", "Oavuagh", "Green", "Morningstartail", "Female", 43, "Uaineloidsig"),
("THRESH-5KRAAVFB3D1MG", "Geagios", "Blue", "Clubtail", "Male", 99, "Gormfaileas"),
("THRESH-B5HSM00J4A2Z4", "Fiedheil", "Black", "Clubtail", "Male", 32, "Moerlaighen"),
("THRESH-BMPM2GAPK58JT", "Teirfua", "Green", "Morningstartail", "Female", 68, "Eifyrielle"),
("THRESH-MCQ8D6GAGF4K8", "Caollo", "Blue", "Morningstartail", "Female", 93, "Nyghmuiron"),
("THRESH-Q0XDBFMNBEB86", "Aenminn", "Red", "Swordtail", "Male", 59, "Berradhyr"),
("THRESH-W99DB29MG16QA", "Meinso", "Green", "Clubtail", "Female", 63, "Eifyrielle"),
("THRESH-XCJCY7HW7QSSP", "Einmial", "Blue", "Clubtail", "Male", 58, "Gormfaileas"),
("THRESH-XR6G68VPGT48M", "Recuagh", "Brown", "Morningstartail", "Female", 55, "Vormalgh"),
("THRESH-YQC97TK34214E", "Dannidh", "Orange", "Clubtail", "Male", 61, "Cariaslog"),
]
if __name__ == "__main__":
src = sys.argv[1] if len(sys.argv) > 1 else "../../data/raw/register/Unofficial_Dragon_Register_Responses.xlsx"
out = sys.argv[2] if len(sys.argv) > 2 else "../../data/public/register.json"
raw = load_raw(src)
raw = raw[[c for c in raw.columns if "photo" not in str(c).lower() and "cadet name" not in str(c).lower()]]
rows = [{str(k): cell(v) for k, v in r.items() if cell(v) is not None} for _, r in raw.iterrows()]
extra = [{"source": "dragonkind.com result page linked on Reddit", "url": f"https://dragonkind.com/results/{i}",
"name": n, "colour": c, "tail": t, "sex": s, "age": a, "lineage": l} for i, n, c, t, s, a, l in REDDIT_RESULTS]
json.dump({"source_file": str(src).split("/")[-1], "exported": datetime.now().strftime("%Y-%m-%d"),
"headers": [str(c) for c in raw.columns], "rows": rows, "extra": extra},
open(out, "w", encoding="utf-8"), ensure_ascii=False, separators=(",", ":"))
print(f"{len(rows)} register rows + {len(extra)} Reddit result pages -> {out}")
+5
View File
@@ -0,0 +1,5 @@
pandas>=2.0
numpy>=1.24
scipy>=1.10
openpyxl>=3.1
pypdf>=4.0
+98
View File
@@ -0,0 +1,98 @@
"""Small, dependency-light statistics used by the analysis (mirrored in packages/core/src/engine.js)."""
import math
import numpy as np
from scipy.stats import fisher_exact, norm
Z95 = 1.959963984540054
def wilson(k, n, z=Z95):
"""Wilson score 95% interval for a proportion k/n. Returns (p, lo, hi); None when n == 0."""
if n == 0:
return (None, None, None)
p = k / n
d = 1 + z * z / n
c = (p + z * z / (2 * n)) / d
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return (p, max(0.0, c - h), min(1.0, c + h))
def odds_ratio(a, b, c, d):
"""2x2 table [[a, b], [c, d]] = [[exposed&event, exposed&no-event], [unexposed&event, unexposed&no-event]].
Returns OR, 95% CI (Woolf log method with Haldane-Anscombe +0.5 correction when any cell is 0),
and the two-sided Fisher exact p-value (computed on the uncorrected table)."""
corr = 0.5 if 0 in (a, b, c, d) else 0.0
A, B, C, D = a + corr, b + corr, c + corr, d + corr
or_ = (A * D) / (B * C)
se = math.sqrt(1 / A + 1 / B + 1 / C + 1 / D)
lo, hi = math.exp(math.log(or_) - Z95 * se), math.exp(math.log(or_) + Z95 * se)
p = fisher_exact([[a, b], [c, d]], alternative="two-sided")[1]
return or_, lo, hi, p, corr > 0
def bh(pvals):
"""Benjamini-Hochberg false-discovery-rate adjusted q-values."""
m = len(pvals)
if m == 0:
return []
order = sorted(range(m), key=lambda i: pvals[i])
q = [0.0] * m
prev = 1.0
for rank in range(m, 0, -1):
i = order[rank - 1]
prev = min(prev, pvals[i] * m / rank)
q[i] = prev
return q
def logistic_ridge(X, y, lam=1.0, iters=100, tol=1e-10):
"""Logistic regression fitted by Newton-Raphson (IRLS) with a small L2 penalty `lam`
on every coefficient except the intercept (column 0). The penalty keeps estimates finite
when a category has 0 events (complete separation). Returns beta and Wald standard errors
from the penalised information matrix."""
X = np.asarray(X, float)
y = np.asarray(y, float)
n, k = X.shape
beta = np.zeros(k)
P = np.eye(k) * lam
P[0, 0] = 0
for _ in range(iters):
eta = X @ beta
mu = 1 / (1 + np.exp(-eta))
W = mu * (1 - mu)
grad = X.T @ (y - mu) - P @ beta
H = (X * W[:, None]).T @ X + P
step = np.linalg.solve(H, grad)
beta += step
if np.max(np.abs(step)) < tol:
break
mu = 1 / (1 + np.exp(-(X @ beta)))
H = (X * (mu * (1 - mu))[:, None]).T @ X + P
se = np.sqrt(np.diag(np.linalg.inv(H)))
return beta, se
def p_from_z(z):
return 2 * (1 - norm.cdf(abs(z)))
def mantel_haenszel(tables):
"""Mantel-Haenszel common OR over 2x2 tables [a, b, c, d], Robins-Breslow-Greenland 95% CI,
and the CMH chi-square p-value (1 df, continuity-corrected). Mirrors mantelHaenszel() in engine.js."""
R = S = PR = PSQR = QS = sA = sE = sV = 0.0
for a, b, c, d in tables:
n = a + b + c + d
if n < 2:
continue
r, s_ = a * d / n, b * c / n
P, Q = (a + d) / n, (b + c) / n
R += r; S += s_; PR += P * r; PSQR += P * s_ + Q * r; QS += Q * s_
m1, m0, n1, n0 = a + b, c + d, a + c, b + d
sA += a; sE += m1 * n1 / n; sV += m1 * m0 * n1 * n0 / (n * n * (n - 1))
if not R or not S:
return None
or_ = R / S
se = math.sqrt(PR / (2 * R * R) + PSQR / (2 * R * S) + QS / (2 * S * S))
chi = max(0.0, abs(sA - sE) - 0.5) ** 2 / sV if sV > 0 else 0.0
return or_, math.exp(math.log(or_) - Z95 * se), math.exp(math.log(or_) + Z95 * se), p_from_z(math.sqrt(chi))
+182
View File
@@ -0,0 +1,182 @@
"""update_sources.py: check the community spreadsheets and the route PDF for new information.
python research/python/update_sources.py [--report report.md] [--form FILE] [--register FILE] [--pdf FILE]
Run from the repo root. Without file arguments it downloads the current versions from the URLs in
data/sources.json (the GitHub Action does this every day). With file arguments it uses local copies,
which is handy for testing or when a download link changes.
What it does:
* Threshing Routes form: re-exports data/public/form_responses.json and data/derived/runs_clean.csv
when the responses changed, and reports how many rows were added or edited.
* Dragon Register: re-exports data/public/register.json (rider names and photos dropped) when it changed.
The raw register export is never written into the repo.
* Route PDF: the PDF is not redistributed. Only a fingerprint is kept (data/derived/pdf_fingerprint.json):
the file hash, per-page text hashes and per-line hashes. When it changes, the report lists the pages that
changed and the lines that are new, so the coding rules and the scene crosswalk can be updated by hand.
Exit code is 0 either way; "changed" files are visible to git, and the report says what happened.
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
sys.path.insert(0, HERE)
from export_raw import cell, load_raw # noqa: E402
P = lambda *a: os.path.join(ROOT, *a) # noqa: E731
def sha(data, n=None):
h = hashlib.sha256(data if isinstance(data, bytes) else data.encode("utf-8")).hexdigest()
return h[:n] if n else h
def download(url, dest):
req = urllib.request.Request(url, headers={"User-Agent": "threshing-atlas-updater"})
with urllib.request.urlopen(req, timeout=60) as r, open(dest, "wb") as f:
data = r.read()
f.write(data)
head = data[:15].lower()
if head.startswith(b"<!doctype html") or head.startswith(b"<html"):
raise RuntimeError(f"{url} returned a web page, not a file (is the link still shared publicly?)")
return dest
def sheet_rows(path, drop=()):
raw = load_raw(path)
raw = raw[[c for c in raw.columns if not any(d in str(c).lower() for d in drop)]]
rows = [{str(k): cell(v) for k, v in r.items() if cell(v) is not None} for _, r in raw.iterrows()]
return [str(c) for c in raw.columns], rows
def diff_rows(old, new):
key = lambda r: json.dumps(r, sort_keys=True, ensure_ascii=False) # noqa: E731
o, n = {key(r) for r in old}, {key(r) for r in new}
return len(n - o), len(o - n)
def update_form(src, report):
out = P("data", "public", "form_responses.json")
current = json.load(open(out, encoding="utf-8"))
headers, rows = sheet_rows(src)
added, removed = diff_rows(current["rows"], rows)
if headers == current["headers"] and not added and not removed:
report.append(f"- **Threshing Routes form:** no change ({len(rows)} responses).")
return False
subprocess.run([sys.executable, P("research", "python", "export_raw.py"), src, out], check=True, cwd=HERE)
subprocess.run([sys.executable, P("research", "python", "clean.py"), out, P("data", "derived", "runs_clean.csv")], check=True, cwd=HERE)
raw_copy = P("data", "raw", "form", "Threshing_Routes_Responses.xlsx")
if os.path.abspath(src) != raw_copy:
shutil.copyfile(src, raw_copy)
new_q = [h for h in headers if h not in current["headers"]]
gone_q = [h for h in current["headers"] if h not in headers]
report.append(f"- **Threshing Routes form:** {len(current['rows'])} → {len(rows)} responses "
f"({added} new or edited, {removed} removed or edited).")
if new_q:
report.append(f" - New questions (check `COLUMN_KEYS` in engine.js and clean.py): {', '.join(new_q)}")
if gone_q:
report.append(f" - Questions no longer in the sheet: {', '.join(gone_q)}")
return True
def update_register(src, report):
out = P("data", "public", "register.json")
current = json.load(open(out, encoding="utf-8"))
headers, rows = sheet_rows(src, drop=("photo", "cadet name"))
added, removed = diff_rows(current["rows"], rows)
if headers == current["headers"] and not added and not removed:
report.append(f"- **Dragon Register:** no change ({len(rows)} dragons).")
return False
subprocess.run([sys.executable, P("research", "python", "export_register.py"), src, out], check=True, cwd=HERE)
report.append(f"- **Dragon Register:** {len(current['rows'])} → {len(rows)} entries ({added} new or edited, {removed} removed or edited).")
return True
def pdf_lines(path):
try:
from pypdf import PdfReader
except ImportError:
sys.exit("pypdf is required: pip install -r research/python/requirements.txt")
pages = []
for page in PdfReader(path).pages:
text = page.extract_text() or ""
pages.append([" ".join(l.split()) for l in text.splitlines() if l.strip()])
return pages
def update_pdf(src, report):
out = P("data", "derived", "pdf_fingerprint.json")
old = json.load(open(out)) if os.path.exists(out) else None
data = open(src, "rb").read()
pages = pdf_lines(src)
fp = {
"sha256": sha(data),
"bytes": len(data),
"pages": len(pages),
"page_hashes": [sha("\n".join(p), 16) for p in pages],
"line_hashes": sorted({sha(l.lower(), 12) for p in pages for l in p}),
"checked": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
}
if old and old["sha256"] == fp["sha256"]:
report.append(f"- **Route PDF:** no change ({fp['pages']} pages).")
return False
if old and old.get("page_hashes") == fp["page_hashes"]:
report.append("- **Route PDF:** the file changed but its text did not (layout or images only). Worth a look.")
elif old:
changed = [i + 1 for i, h in enumerate(fp["page_hashes"]) if i >= len(old["page_hashes"]) or old["page_hashes"][i] != h]
old_lines = set(old["line_hashes"])
new_lines = [l for p in pages for l in p if sha(l.lower(), 12) not in old_lines]
removed = len(old_lines - set(fp["line_hashes"]))
report.append(f"- **Route PDF:** changed. {old['pages']} → {fp['pages']} pages; pages with new text: "
f"{', '.join(map(str, changed)) or 'none'}; {len(new_lines)} new lines, {removed} lines gone.")
if new_lines:
report.append(" - New lines (update the coding rules or the scene crosswalk if they add options):")
report.extend(f" - {l}" for l in new_lines[:60])
if len(new_lines) > 60:
report.append(f" - … and {len(new_lines) - 60} more")
else:
report.append(f"- **Route PDF:** fingerprint recorded for the first time ({fp['pages']} pages).")
json.dump(fp, open(out, "w"), indent=1)
return True
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--report", default=None)
ap.add_argument("--form")
ap.add_argument("--register")
ap.add_argument("--pdf")
args = ap.parse_args()
sources = json.load(open(P("data", "sources.json")))
report, changed, failed = [], False, []
tmp = tempfile.mkdtemp(prefix="sources-")
steps = [("form", args.form, update_form), ("register", args.register, update_register), ("pdf", args.pdf, update_pdf)]
for key, local, fn in steps:
try:
path = local or download(sources[key]["download"], os.path.join(tmp, sources[key]["filename"]))
changed |= fn(os.path.abspath(path), report)
except Exception as e: # keep going: one broken link should not block the others
failed.append(key)
report.append(f"- **{sources[key]['name']}:** could not check ({e}).")
head = f"Source check {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}"
text = "\n".join([f"## {head}", ""] + report) + "\n"
print(text)
if args.report:
open(args.report, "w", encoding="utf-8").write(text)
if os.environ.get("GITHUB_OUTPUT"):
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"changed={'true' if changed else 'false'}\nfailed={','.join(failed)}\n")
if __name__ == "__main__":
main()
+35
View File
@@ -0,0 +1,35 @@
// Build data/public/graph.json from every source: community form runs + DragonKind bot trajectories.
// node scripts/build-graph.js
const fs = require("fs");
const path = require("path");
const E = require("../packages/core/src/engine.js");
const G = require("../packages/core/src/graph.js");
const root = path.resolve(__dirname, "..");
const rel = (p) => path.join(root, p);
const raw = JSON.parse(fs.readFileSync(rel("data/public/form_responses.json"), "utf8"));
const { runs } = E.codeRows(raw.rows, raw.headers);
const records = runs.map((r) => ({ source: r.source === "Form" ? "form" : "form-bulk", vars: G.formRunVariables(r) }));
const botDir = rel("data/bot");
const scenes = fs.existsSync(path.join(botDir, "scenes.json")) ? JSON.parse(fs.readFileSync(path.join(botDir, "scenes.json"), "utf8")) : {};
const trajs = [];
for (const f of fs.readdirSync(botDir).filter((f) => /^trajectories-.*\.jsonl$/.test(f)).sort()) {
for (const line of fs.readFileSync(path.join(botDir, f), "utf8").split("\n")) if (line.trim()) trajs.push(JSON.parse(line));
}
const unmapped = {};
for (const t of trajs) {
const { vars, unmapped: u } = G.trajectoryVariables(t);
records.push({ source: "bot", vars });
for (const x of u) unmapped[x] = (unmapped[x] || 0) + 1;
}
const graph = {
sources: records.reduce((m, r) => ((m[r.source] = (m[r.source] || 0) + 1), m), {}),
variables: G.buildVariableGraph(records),
scenes: G.buildSceneGraph(scenes, trajs)
};
fs.writeFileSync(rel("data/public/graph.json"), JSON.stringify(graph));
console.log(`graph.json: ${JSON.stringify(graph.sources)}, ${Object.keys(graph.variables.nodes).length} variable nodes, ${Object.keys(graph.scenes).length} scenes`);
const um = Object.keys(unmapped).filter((t) => !/^(head deeper|investigate the scream|lower your|show your bravery|hide behind|run and hope|reds are too|jump|daggers or not|engage the smaller)/i.test(t));
if (um.length) console.log("bot choices with no form equivalent:", um);
+22
View File
@@ -0,0 +1,22 @@
// Assemble the static Atlas site into dist/ (no dependencies).
// node scripts/build-site.js [outDir]
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const out = path.resolve(root, process.argv[2] || "dist");
const copy = (from, to) => {
fs.mkdirSync(path.dirname(path.join(out, to)), { recursive: true });
fs.copyFileSync(path.join(root, from), path.join(out, to));
};
fs.rmSync(out, { recursive: true, force: true });
for (const f of fs.readdirSync(path.join(root, "apps/atlas"))) copy(`apps/atlas/${f}`, f);
copy("packages/core/src/engine.js", "engine.js");
copy("packages/core/src/graph.js", "graph.js");
for (const f of ["form_responses.json", "register.json", "graph.json"]) copy(`data/public/${f}`, `data/${f}`);
// Source files shown in the page's "view the code" panel
for (const f of ["analyze.py", "clean.py", "stats_core.py"]) copy(`research/python/${f}`, `python/${f}`);
copy("README.md", "README.md");
fs.writeFileSync(path.join(out, ".nojekyll"), "");
console.log(`Site built in ${path.relative(root, out) || "."}`);
+37
View File
@@ -0,0 +1,37 @@
"""Compare factor tables and models between the JS engine and the Python reference."""
import json, sys
js = json.load(open("tests/out/results_js.json"))
py = json.load(open("tests/out/results_py.json"))
TOL = 1e-6
fails = 0
def close(a, b, rel=TOL):
if a is None or b is None:
return a is None and b is None
return abs(a - b) <= rel * max(1, abs(a), abs(b))
for key, ft in py["factors"].items():
jrows = {(r["factor"], r["level"]): r for r in js["factors"][key]["rows"]}
for r in ft["rows"]:
j = jrows.get((r["factor"], r["level"]))
if j is None:
print("missing in JS:", key, r["factor"], r["level"]); fails += 1; continue
for f in ("k", "n", "p", "lo", "hi", "or", "or_lo", "or_hi", "fisher_p", "q"):
if (f in r) != (f in j) or (f in r and not close(r[f], j[f], 1e-5)):
print("diff", key, r["factor"], r["level"], f, r.get(f), j.get(f)); fails += 1
for key, m in py["models"].items():
jm = js["models"][key]
if m["n"] != jm["n"] or m["events"] != jm["events"]:
print("model size diff", key); fails += 1
jt = {t["term"]: t for t in jm["terms"]}
for t in m["terms"]:
j = jt.get(t["term"])
if not j:
print("term missing", key, t["term"]); fails += 1; continue
for f in ("or", "lo", "hi"):
if not close(t[f], j[f], 1e-4):
print("model diff", key, t["term"], f, t[f], j[f]); fails += 1
if abs(t["p"] - j["p"]) > 1e-6:
print("model p diff", key, t["term"], t["p"], j["p"]); fails += 1
n_rows = sum(len(f["rows"]) for f in py["factors"].values())
n_terms = sum(len(m["terms"]) for m in py["models"].values())
print(f"checked {n_rows} factor rows and {n_terms} model terms: {'ALL MATCH' if not fails else str(fails) + ' differences'}")
sys.exit(1 if fails else 0)
+53
View File
@@ -0,0 +1,53 @@
"""Recompute route rankings in Python (crude Fisher and stratified Mantel-Haenszel) and compare with engine.js."""
import json, subprocess, sys
sys.path.insert(0, "research/python")
import pandas as pd
from stats_core import odds_ratio, mantel_haenszel, bh
d = pd.DataFrame(json.load(open("tests/out/runs_js.json")))
js = json.loads(subprocess.check_output(["node", "-e", """
const E=require('./packages/core/src/engine.js'),fs=require('fs');const raw=JSON.parse(fs.readFileSync('data/public/form_responses.json'));
const {runs}=E.codeRows(raw.rows,raw.headers);const o={};for(const t of ['see_Blue','bond_Blue','see_shadow','bond_Green']){o[t]=E.rankRoutes(runs,t,10)}
console.log(JSON.stringify(o));"""]))
def stage(r):
if r.scream.startswith("DIED"): cad = None # noqa
else: cad = ("Help → " + r.resolution) if r.scream == "Investigate & help" else (r.scream + " → " + r.resolution)
hour = {"Tree": "Climb the tree", "Valley": "Valley centre"}.get(r.hour)
fs = None if r.scream == "DIED at first sighting" else r.first_sighting
return " › ".join(v if isinstance(v, str) and v else "—" for v in [r.company, r.direction, fs, cad, r.post_path, hour])
def stratum(r):
if r.source != "Form": return "bulk"
return {"Blue": "blue", "Black": "black"}.get(r.goal, "other")
d["route"] = d.apply(stage, axis=1); d["stratum"] = d.apply(stratum, axis=1)
d["branch"] = d.branch.where(d.branch.notna(), None)
T = {"see_Blue": (lambda x: x.branch == "Passed the Red: meadow", lambda x: x.saw_blue_meadow),
"bond_Blue": (lambda x: x.hour == "Valley", lambda x: (x.outcome == "Bonded") & (x.outcome_color == "Blue")),
"see_shadow": (lambda x: (x.hour == "Tree") & x.branch.notna(), lambda x: x.saw_shadow),
"bond_Green": (lambda x: x.hour == "Tree", lambda x: (x.outcome == "Bonded") & (x.outcome_color == "Green"))}
fails = 0
for t, (pool, ev) in T.items():
P = d[pool(d)].copy(); P["e"] = ev(P).astype(bool)
K, N = int(P.e.sum()), len(P)
rows = {}
for route, g in P.groupby("route"):
if len(g) < 10: continue
k, n = int(g.e.sum()), len(g)
orr = odds_ratio(k, n - k, K - k, N - n - (K - k))
tabs = []
for s, sg in P.groupby("stratum"):
inr = sg.route == route
a = int((inr & sg.e).sum()); nin = int(inr.sum()); c = int((~inr & sg.e).sum()); nout = len(sg) - nin
tabs.append([a, nin - a, c, nout - c])
rows[route] = (k, n, orr, mantel_haenszel(tabs))
jr = {r["route"]: r for r in js[t]["rows"]}
if set(jr) != set(rows): print(t, "route sets differ", set(jr) ^ set(rows)); fails += 1
for route, (k, n, orr, mh) in rows.items():
j = jr.get(route)
if not j: continue
if (k, n) != (j["k"], j["n"]) or abs(orr[0] - j["or"]) > 1e-6 * max(1, orr[0]) or abs(orr[3] - j["fisher_p"]) > 1e-6:
print("crude diff", t, route); fails += 1
if mh is None:
if j["mh_or"] is not None: print("mh none diff", t, route); fails += 1
elif j["mh_or"] is None or abs(mh[0] - j["mh_or"]) > 1e-6 * max(1, mh[0]) or abs(mh[3] - j["mh_p"]) > 1e-5:
print("mh diff", t, route, mh, j["mh_or"], j["mh_p"]); fails += 1
print(f"route rankings for {len(T)} outcomes: {'ALL MATCH' if not fails else str(fails) + ' differences'}")
sys.exit(1 if fails else 0)
+21
View File
@@ -0,0 +1,21 @@
"""Check that the JS engine (packages/core/src/engine.js) and the Python reference (python/clean.py) code every run identically."""
import json, sys
import pandas as pd
js = pd.DataFrame(json.load(open(sys.argv[1] if len(sys.argv) > 1 else "tests/out/runs_js.json")))
py = pd.read_csv(sys.argv[2] if len(sys.argv) > 2 else "data/derived/runs_clean.csv", keep_default_na=False, na_values=[""])
def norm(v):
if v is None or (not isinstance(v, str) and pd.isna(v)) or v == "":
return None
if isinstance(v, float) and v.is_integer():
return str(int(v))
if isinstance(v, bool):
return str(v)
return str(v)
bad = {}
for c in py.columns:
a, b = [norm(v) for v in py[c]], [norm(v) for v in js[c]]
d = [(i, x, y) for i, (x, y) in enumerate(zip(a, b)) if x != y]
if d:
bad[c] = (len(d), d[:3])
print("runs:", len(py), len(js), "| mismatching columns:", bad or "NONE")
sys.exit(1 if bad else 0)
+1
View File
@@ -0,0 +1 @@
{"version":1,"nodes":{},"edges":{}}
+1
View File
@@ -0,0 +1 @@
{"runId":"r1","attempt":1,"startedAt":"2026-01-01T00:00:00.000Z","targetDragon":"black","decisionMode":"explore","outcome":"BURNED","intentionalBurn":true,"accountId":"acct-1","steps":[]}
+10
View File
@@ -0,0 +1,10 @@
{"ts":"2026-01-01T00:00:00.000Z","attempt":1,"event":"DECISION","nodeId":"b0fa671066ec","prose":"Synthetic start scene.","choices":["Enter the valley alone","Enter the valley with one of your squadmates"],"decision":{"action":"choose","choiceIndex":0,"choiceText":"Enter the valley alone","stage":"TEST","rule":"R","source":"guide"}}
{"ts":"2026-01-01T00:00:01.000Z","attempt":1,"event":"DECISION","nodeId":"b0fa671066ec","prose":"Synthetic start scene.","choices":["Enter the valley alone","Enter the valley with one of your squadmates"],"decision":{"action":"choose","choiceIndex":0,"choiceText":"Enter the valley alone","stage":"TEST","rule":"R","source":"guide"}}
{"ts":"2026-01-01T00:00:02.000Z","attempt":1,"event":"DECISION","nodeId":"e0b5530601be","prose":"Synthetic fork.","choices":["Head east toward the roar","Head toward the center of the forest"],"decision":{"action":"choose","choiceIndex":1,"choiceText":"Head toward the center of the forest","stage":"TEST","rule":"R","source":"guide"}}
{"ts":"2026-01-01T00:00:03.000Z","attempt":1,"event":"DECISION","nodeId":"1c86a35c091f","prose":"Synthetic dragon.","choices":["Lower your eyes in respect","Hide behind a tree"],"decision":{"action":"choose","choiceIndex":1,"choiceText":"Hide behind a tree","stage":"TEST","rule":"R","source":"guide"}}
{"ts":"2026-01-01T00:00:04.000Z","attempt":1,"event":"BURNED","prose":"x","stage":"TEST","intentional":false}
{"ts":"2026-01-01T00:00:05.000Z","attempt":1,"event":"BURNED","prose":"x","stage":"TEST","intentional":false}
{"ts":"2026-01-01T00:00:06.000Z","attempt":2,"event":"DECISION","prose":"Synthetic start scene.","choices":["Enter the valley alone","Enter the valley with one of your squadmates"],"decision":{"action":"pause","stage":"TEST"}}
{"ts":"2026-01-01T00:00:07.000Z","attempt":2,"event":"MANUAL_DECISION","prose":"Synthetic start scene.","choices":["Enter the valley alone","Enter the valley with one of your squadmates"],"choiceIndex":1,"choiceText":"Enter the valley with one of your squadmates","source":"manual"}
{"ts":"2026-01-01T00:00:08.000Z","attempt":2,"event":"DECISION","nodeId":"e0b5530601be","prose":"Synthetic fork.","choices":["Head east toward the roar","Head toward the center of the forest"],"decision":{"action":"choose","choiceIndex":0,"choiceText":"Head east toward the roar","stage":"TEST","rule":"R","source":"guide"}}
{"ts":"2026-01-01T00:00:09.000Z","attempt":2,"event":"DRAGON_BONDED","dragon":"Green"}
+72
View File
@@ -0,0 +1,72 @@
// node --test tests/
const test = require("node:test");
const assert = require("node:assert");
const path = require("path");
const { importBot, assertPublicSafe } = require("../packages/ingest/src/bot");
const G = require("../packages/core/src/graph");
const fx = path.join(__dirname, "fixtures/bot");
const { scenes, trajectories } = importBot({ dataDir: path.join(fx, "data"), logsDir: path.join(fx, "logs"), salt: "test-salt" });
test("one trajectory per attempt, duplicates and repeated burns collapsed", () => {
assert.strictEqual(trajectories.length, 2);
const [t1, t2] = trajectories;
assert.strictEqual(t1.steps.length, 3);
assert.deepStrictEqual(t1.steps.map((s) => s.to).slice(-1), ["BURNED"]);
assert.strictEqual(t1.steps[0].to, t1.steps[1].scene);
assert.strictEqual(t2.outcome.type, "BONDED");
assert.strictEqual(t2.steps.at(-1).to, "BONDED:green");
assert.strictEqual(t2.steps[0].manual, true, "manual picks are flagged");
});
test("run metadata attached, account id hashed with the salt", () => {
const t1 = trajectories[0];
assert.strictEqual(t1.meta.target, "black");
assert.strictEqual(t1.meta.decisionMode, "explore");
assert.strictEqual(t1.outcome.intentional, true);
assert.match(t1.meta.accountKey, /^[0-9a-f]{10}$/);
assert.ok(!JSON.stringify(trajectories).includes("acct-1"));
});
test("public export contains no prose", () => {
assertPublicSafe(scenes);
assertPublicSafe(trajectories);
assert.ok(!JSON.stringify({ scenes, trajectories }).includes("Synthetic"));
assert.throws(() => assertPublicSafe({ prose: "x" }));
assert.throws(() => assertPublicSafe({ note: "y".repeat(201) }));
});
test("crosswalk maps bot choices to form variables", () => {
const { vars } = G.trajectoryVariables(trajectories[0]);
assert.strictEqual(vars.company, "Alone");
assert.strictEqual(vars.direction, "Center");
assert.strictEqual(vars.outcome, "Incinerated");
const v2 = G.trajectoryVariables(trajectories[1]).vars;
assert.strictEqual(v2.company, "1 Squadmate");
assert.strictEqual(v2.outcome_color, "Green");
});
test("variable graph counts by source", () => {
const recs = trajectories.map((t) => ({ source: "bot", vars: G.trajectoryVariables(t).vars }));
recs.push({ source: "form", vars: { company: "Alone", direction: "Center", outcome: "Bonded", outcome_color: "Blue" } });
const g = G.buildVariableGraph(recs);
const e = g.edges.find((x) => x.from === "company=Alone" && x.to === "direction=Center");
assert.deepStrictEqual(e.bySource, { bot: 1, form: 1 });
assert.ok(Math.abs(e.p.mean - 2.5 / 3) < 1e-12);
});
test("scene graph marks chance, burns and untested options", () => {
const g = G.buildSceneGraph(scenes, trajectories);
const start = Object.values(g).find((n) => Object.values(n.options).some((o) => /alone/i.test(o.text)));
assert.strictEqual(Object.values(start.options).every((o) => o.n === 1), true);
const dragon = Object.values(g).find((n) => Object.values(n.options).some((o) => /hide behind/i.test(o.text)));
const hide = Object.values(dragon.options).find((o) => /hide/i.test(o.text));
const respect = Object.values(dragon.options).find((o) => /respect/i.test(o.text));
assert.strictEqual(hide.to.BURNED, 1);
assert.strictEqual(respect.untested, true);
});
test("Beta credible interval", () => {
const p = G.betaPosterior(0, 4);
assert.ok(p.lo >= 0 && p.hi < 0.5 && p.mean === 0.1);
});
+13
View File
@@ -0,0 +1,13 @@
// node tests/run_engine.js data/public/form_responses.json out_dir
// Runs the browser engine in Node and writes coded runs + results, for comparison with Python.
const fs = require("fs");
const path = require("path");
const E = require("../packages/core/src/engine.js");
const [, , src = "data/public/form_responses.json", outDir = "tests/out"] = process.argv;
const raw = JSON.parse(fs.readFileSync(src, "utf8"));
const { runs, missing } = E.codeRows(raw.rows, raw.headers);
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "runs_js.json"), JSON.stringify(runs));
const res = E.analyse(runs, {});
fs.writeFileSync(path.join(outDir, "results_js.json"), JSON.stringify(res, null, 1));
console.log(`${runs.length} runs coded; missing columns: ${missing.join(", ") || "none"}`);