Solver: best decisions per dragon colour, and the bot advisor

- packages/core/src/solver.js: decision tree with perfect recall over the
  community form's choices; chance events (first dragon, deaths, shadow,
  meadow dragon, encounter outcome) depend on earlier choices through
  hierarchical Dirichlet back-off with empirical-Bayes concentration per
  event; backward induction for P(colour this attempt) and Dinkelbach for
  P(colour) / (P(colour) + P(other colour)); 200 posterior draws for
  credible intervals and "still best" rates; cross-fitted held-out check.
- Only genuine attempts inform encounter outcomes (goal / Malek intent).
- data/public/policy.json (all runs and a low-bias sample) and the readable
  docs/POLICY.md; published on Pages with solver.js for the bot.
- Bot advisor: re-solves from any history, maps advice onto screen text,
  reports margins so ties can be randomised. docs/BOT_INTEGRATION.md.
- Tests on a synthetic world with known answers; daily source update now
  rebuilds the policy.

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 22:34:38 +00:00
co-authored by Claude Opus 5.5
parent 46ee08a56b
commit d2ffb84b5e
12 changed files with 1842 additions and 5 deletions
+39
View File
@@ -0,0 +1,39 @@
// Build data/public/policy.json: the best decisions for each dragon colour, under both objectives.
// node scripts/build-policy.js [--draws 200]
const fs = require("fs");
const path = require("path");
const E = require("../packages/core/src/engine.js");
const S = require("../packages/core/src/solver.js");
const root = path.resolve(__dirname, "..");
const arg = (k, d) => { const i = process.argv.indexOf("--" + k); return i > 0 ? process.argv[i + 1] : d; };
const draws = +arg("draws", 200);
const raw = JSON.parse(fs.readFileSync(path.join(root, "data/public/form_responses.json"), "utf8"));
const { runs } = E.codeRows(raw.rows, raw.headers);
const isRare = (g) => ["Blue", "Black", "Blue or Black"].includes(g);
const samples = {
// every run
all: runs,
// runs least affected by selective reporting: bulk logs, plus form runs from riders not chasing a rare dragon
lowBias: runs.filter((r) => r.source !== "Form" || !isRare(r.goal)),
};
const t0 = Date.now();
const out = { schema: 1, source: { form_rows: raw.rows.length }, samples: {} };
for (const [name, rs] of Object.entries(samples)) {
out.samples[name] = S.buildPolicy(rs, { draws });
console.log(`${name}: ${rs.length} runs, ${((Date.now() - t0) / 1000).toFixed(1)} s`);
}
// a content id, so the bot can record which policy produced each run (no timestamps: the build is reproducible)
out.id = require("crypto").createHash("sha1").update(JSON.stringify(out.samples)).digest("hex").slice(0, 12);
fs.writeFileSync(path.join(root, "data/public/policy.json"), JSON.stringify(out));
console.log("policy id", out.id);
const pct = (p) => (100 * p).toFixed(p < 0.01 ? 2 : 1) + "%";
for (const [name, s] of Object.entries(out.samples)) {
console.log(`\n${name} alphas ${JSON.stringify(s.model.alphas)}`);
for (const [X, t] of Object.entries(s.targets)) {
const a = t.thisAttempt, b = t.eventually;
console.log(` ${X.padEnd(6)} this attempt ${pct(a.pX.mean)} [${pct(a.pX.lo)}, ${pct(a.pX.hi)}] other bond ${pct(a.pOther.mean)}` +
` | eventually: ratio ${pct(b.ratio.mean)}, P(X) ${pct(b.pX.mean)}, ~${b.expectedAttempts.mean.toFixed(0)} attempts` +
` | cross-fit ${pct(t.crossFit.inSample)} -> held-out ${pct(t.crossFit.heldOut)}`);
}
}
+2 -1
View File
@@ -14,7 +14,8 @@ 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}`);
copy("packages/core/src/solver.js", "solver.js");
for (const f of ["form_responses.json", "register.json", "graph.json", "policy.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");
+62
View File
@@ -0,0 +1,62 @@
// Write docs/POLICY.md: a readable summary of data/public/policy.json.
// node scripts/policy-report.js
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const P = JSON.parse(fs.readFileSync(path.join(root, "data/public/policy.json"), "utf8"));
const pct = (p) => (p == null ? "–" : (100 * p).toFixed(p < 0.1 ? 1 : 0) + "%");
const conf = (n) => (n.stillBest == null ? "" : ` (still best in ${pct(n.stillBest)} of posterior draws)`);
function walk(n, out, indent = "") {
if (!n) return;
if (n.type === "decision") {
const alts = Object.entries(n.options).sort((a, b) => b[1].pX - a[1].pX)
.map(([k, v]) => `${k} ${pct(v.pX)}`).join(", ");
if (n.tie) out.push(`${indent}- ${n.label}: any (no difference for this colour)`);
else out.push(`${indent}- **${n.label}: ${n.choice}**${conf(n)}${n.stillBest != null && n.stillBest < 0.75 ? " — no clear winner" : ""}. If chosen, then best play after: ${alts}`);
walk(n.next, out, indent);
} else if (n.type === "chance") {
const br = Object.entries(n.branches).sort((a, b) => b[1].p - a[1].p);
const live = br.filter(([k]) => !["die"].includes(k));
if (br.some(([k]) => k === "die")) {
const d = br.find(([k]) => k === "die");
out.push(`${indent}- ${n.label}: ${pct(1 - d[1].p)} survive`);
for (const [, b] of live) walk(b.next, out, indent);
return;
}
if (live.length === 1) return walk(live[0][1].next, out, indent);
out.push(`${indent}- ${n.label}: ${br.map(([k, b]) => `${k} ${pct(b.p)}`).join(", ")}`);
for (const [k, b] of br) {
out.push(`${indent} - if **${k}**:`);
walk(b.next, out, indent + " ");
}
} else if (n.outcomes) {
out.push(`${indent}- Outcome if you attempt: ${Object.entries(n.outcomes).sort((a, b) => b[1] - a[1]).map(([k, p]) => `${k === "burn" ? "incinerated" : "bond " + k} ${pct(p)}`).join(", ")}`);
} else out.push(`${indent}- ${n.what}`);
}
const s = P.samples.all, lb = P.samples.lowBias;
const L = [];
L.push("# Best routes by dragon colour", "");
L.push(`Generated from ${s.data.runs} community runs by \`scripts/build-policy.js\`. Machine-readable version: \`data/public/policy.json\`.`, "");
L.push("**How to read this.** \"This attempt\" maximises the chance of bonding the colour on one run. \"Eventually\" assumes you will die on purpose and try again whenever the run goes wrong, so it avoids any choice that can end the account on a different dragon. Percentages are posterior means with 95% credible intervals. \"Held-out\" is the same policy chosen on half of the runs and scored on the other half: when it is much lower than the in-sample number, the route's advantage is mostly noise.", "");
L.push("**Caveats.** The form records choices only at the level of company, direction, first dragon, cadet encounter, fork, tree or valley, and which dragon you met. Choices inside each encounter are not recorded, so the bond chance at an encounter is the community's average with whatever answers people used. Riders chasing a rare dragon report sightings more often than riders who log every run; the \"low-bias\" columns use only bulk logs and non-chasers.", "");
L.push("| Colour | This attempt | Low-bias sample | Held-out | Eventually: chance the account ends on this colour | Attempts needed (about) |");
L.push("|---|---|---|---|---|---|");
for (const X of Object.keys(s.targets)) {
const t = s.targets[X], a = t.thisAttempt, e = t.eventually, l = lb.targets[X].thisAttempt;
L.push(`| ${X} | ${pct(a.pX.mean)} (${pct(a.pX.lo)}–${pct(a.pX.hi)}) | ${pct(l.pX.mean)} (${pct(l.pX.lo)}–${pct(l.pX.hi)}) | ${pct(t.crossFit.heldOut)} | ${pct(e.ratio.mean)} | ${Math.round(e.expectedAttempts.mean)} |`);
}
L.push("", "## How much do earlier choices matter?", "");
L.push("Each chance event can depend on the choices before it. The model learns how much from the data (empirical-Bayes concentration; larger means the history matters less):", "");
L.push("| Chance event | Depends on (most important first) | Concentration |", "|---|---|---|");
for (const [k, ctx] of Object.entries(s.model.chanceContext)) L.push(`| ${k} | ${ctx.join(", ") || "nothing"} | ${s.model.alphas[k]} |`);
for (const X of Object.keys(s.targets)) {
for (const [obj, title] of [["thisAttempt", "this attempt"], ["eventually", "eventually"]]) {
const out = [];
walk(s.targets[X][obj].tree, out);
L.push("", `## ${X}: ${title}`, "", ...out);
}
}
fs.writeFileSync(path.join(root, "docs/POLICY.md"), L.join("\n") + "\n");
console.log("wrote docs/POLICY.md", L.length, "lines");