From 95567b09eb20f05d971556ad94fa899da3c5f994 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:09:34 +0800 Subject: [PATCH 01/38] feat(storyworld): source-native builder, SWMD mini, and HG-02 gym --- .../training_gym/rlt_gym/storyworld_native.py | 440 ++++++++++++++++++ 1 file changed, 440 insertions(+) create mode 100644 src/datagoblin/training_gym/rlt_gym/storyworld_native.py diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py new file mode 100644 index 00000000..686da269 --- /dev/null +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -0,0 +1,440 @@ +"""Source-native SweepWeave, SWMD-mini, and HG-02 tasks for DataGoblin RLT. + +The upstream GPTStoryworld checkout is read-only. Policies see only public +observations; source-owned validators and game transitions issue all grades. +This module provides deterministic CPU reference controls, not learned results. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import importlib +import importlib.util +import json +import random +import subprocess +import sys +import tempfile +from collections import Counter +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +from typing import Any + +SCHEMA = "datagoblin.storyworld_native.v1" +SPLITS = ("train", "train", "train", "calibration", "ordinary_test", "ood_test") +DEFAULT_WORLD = "storyworlds/diplomacy/forecast_backstab.json" +SOURCE_FILES = { + "validator": "codex-skills/storyworld-building/scripts/sweepweave_validator.py", + "exporter": "codex-skills/storyworld-building/scripts/json_to_swmd.py", + "mini_index": "codex-skills/small-storyworld-builder/scripts/swmd_encounter_index.py", + "hypergame": "verifiers_envs/storyworld-hypergames-env/src/spiral_ln/hypergames_single_player.py", + "geometry": "verifiers_envs/storyworld-hypergames-env/src/spiral_ln/evaluation_hypergames.py", +} +ARTIFACTS = ("public_tasks.jsonl", "private_sealed.jsonl", "baseline_rollouts.jsonl", "train_targets.jsonl") + + +def _json(value: Any) -> str: + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + + +def _hash(value: Any) -> str: + return hashlib.sha256(_json(value).encode("utf-8")).hexdigest() + + +def _sha_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _load_file(path: Path, name: str) -> Any: + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise ValueError(f"cannot load source script: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +@dataclass +class Native: + root: Path + revision: str + hashes: dict[str, str] + world: dict[str, Any] + world_path: str + validator: Any + exporter: Any + mini_index: Any + hypergame: Any + + def descriptor(self) -> dict[str, Any]: + return {"repository": "MoralityLabAI/GPTStoryworld", "commit": self.revision, + "file_sha256": self.hashes, "world_path": self.world_path} + + +def connect(source: Path, world_path: str = DEFAULT_WORLD, expect_commit: str | None = None) -> Native: + root = source.expanduser().resolve(strict=True) + path = Path(world_path) + if path.is_absolute() or ".." in path.parts: + raise ValueError("world path must stay inside the source checkout") + relative = path.as_posix() + scripts = dict(SOURCE_FILES, world=relative) + for location in scripts.values(): + if not (root / location).is_file() or not (root / location).resolve().is_relative_to(root): + raise ValueError(f"missing source-native file: {location}") + commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], check=True, + capture_output=True, text=True, timeout=10).stdout.strip() + if expect_commit and commit != expect_commit: + raise ValueError(f"source commit mismatch: expected {expect_commit}, got {commit}") + hashes = {name: _sha_file(root / p) for name, p in scripts.items()} + suffix = _hash([str(root), commit])[:12] + validator = _load_file(root / SOURCE_FILES["validator"], "_dg_sw_val_" + suffix) + exporter = _load_file(root / SOURCE_FILES["exporter"], "_dg_sw_exp_" + suffix) + mini_index = _load_file(root / SOURCE_FILES["mini_index"], "_dg_sw_idx_" + suffix) + package_root = (root / "verifiers_envs/storyworld-hypergames-env/src").resolve() + sys.path.insert(0, str(package_root)) + try: + for name in ("spiral_ln.evaluation_hypergames", "spiral_ln.hypergames_single_player"): + existing = sys.modules.get(name) + if existing is not None and not Path(existing.__file__).resolve().is_relative_to(package_root): + raise ValueError(f"foreign hypergame module already loaded: {name}") + hypergame = importlib.import_module("spiral_ln.hypergames_single_player") + finally: + sys.path.remove(str(package_root)) + if not Path(hypergame.__file__).resolve().is_relative_to(package_root): + raise ValueError("hypergame module did not originate in the pinned checkout") + full = root / relative + validation_errors = validator.validate_storyworld(str(full)) + if validation_errors: + raise ValueError(f"source world fails native SweepWeave validator: {validation_errors[:3]}") + world = json.loads(full.read_text(encoding="utf-8")) + return Native(root, commit, hashes, world, relative, validator, exporter, mini_index, hypergame) + + +def _edges(world: dict[str, Any]) -> list[tuple[str, str, str, str]]: + ids = {e["id"] for e in world["encounters"]} + return [(e["id"], o["id"], r["id"], r["consequence_id"]) + for e in world["encounters"] for o in e.get("options", []) + for r in o.get("reactions", []) + if r.get("consequence_id") in ids and len(ids) >= 3] + + +def _reaction(world: dict[str, Any], eid: str, oid: str, rid: str) -> tuple[dict, dict, dict]: + e = next(e for e in world["encounters"] if e["id"] == eid) + o = next(o for o in e["options"] if o["id"] == oid) + r = next(r for r in o["reactions"] if r["id"] == rid) + return e, o, r + + +def _card(native: Native, eid: str, oid: str, rid: str) -> str: + with tempfile.TemporaryDirectory(prefix="dg-sw-card-") as temp: + path = Path(temp) / "world.swmd.min.md" + path.write_text(native.exporter.emit_minified(native.world), encoding="utf-8") + parsed = native.mini_index.parse_swmd_min(path) + rows = parsed.encounters[eid].block_lines + prefix = f"ORX {oid}/{rid} -> " + if sum(row.startswith(prefix) for row in rows) != 1: + raise ValueError("SWMD source card lacks exactly one matching reaction") + return "\n".join(row.replace(row.split(" -> ", 1)[1].split(" | ", 1)[0], + "__BROKEN_TARGET__", 1) if row.startswith(prefix) else row + for row in rows) + + +def _public_builder(native: Native, edge: tuple[str, str, str, str], + choices: list[str], mode: str) -> dict[str, Any]: + eid, oid, rid, _ = edge + encounter, option, reaction = _reaction(native.world, eid, oid, rid) + by_id = {e["id"]: e for e in native.world["encounters"]} + public = { + "instruction": "Restore the broken reaction successor. Reply PICK .", + "world_title": native.world.get("storyworld_title", ""), + "encounter_id": eid, "encounter_title": encounter.get("title", ""), + "encounter_text": native.exporter.script_text(encounter.get("text_script"))[:600], + "option_id": oid, "option_text": native.exporter.script_text(option.get("text_script"))[:400], + "reaction_id": rid, "reaction_text": native.exporter.script_text(reaction.get("text_script"))[:400], + "broken_successor": "__BROKEN_TARGET__", + "candidates": [{"id": cid, "title": by_id[cid].get("title", ""), + "description": native.exporter.script_text(by_id[cid].get("text_script"))[:280]} + for cid in choices], + "response_grammar": "PICK ", + } + if mode == "mini": + public["swmd_card"] = _card(native, eid, oid, rid) + public["context_budget_tokens"] = 8192 + public["editing_rule"] = "Revise one ORX target; preserve encounter, option, and reaction IDs." + return public + + +def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, dict]]: + if per_mode < 1: + raise ValueError("per-mode must be positive") + rng = random.Random(seed) + edges = _edges(native.world) + if per_mode > len(edges): + raise ValueError(f"per-mode exceeds {len(edges)} available distinct source reactions") + rng.shuffle(edges) + selected = edges[:per_mode] + encounter_ids = sorted(e["id"] for e in native.world["encounters"]) + tasks: list[tuple[dict, dict]] = [] + for i, edge in enumerate(selected): + eid, oid, rid, gold = edge + lineage = _hash(["sweepweave", native.hashes["world"], eid, oid, rid])[:20] + alternatives = rng.sample([x for x in encounter_ids if x != gold], 2) + choices = [gold, *alternatives] + rng.shuffle(choices) + for mode in ("builder", "mini"): + root = _hash([SCHEMA, mode, lineage])[:24] + public = {"schema": SCHEMA, "root": root, "lineage": lineage, + "split": SPLITS[i % len(SPLITS)], "mode": mode, + "public": _public_builder(native, edge, choices, mode)} + private = {"root": root, "mode": mode, "gold_target": gold, + "edge": [eid, oid, rid], "lineage": lineage} + tasks.append((public, private)) + hyper = native.hypergame + for i in range(per_mode): + scenario_seed = rng.randrange(2**31) + scenario = hyper.make_scenario(scenario_seed, 140) + lineage = _hash(["hg02", scenario_seed, native.hashes["hypergame"]])[:20] + for bit in (0, 1): + visible = hyper.observation(scenario, hyper.initial_state(bit, 5)) + root = _hash([SCHEMA, "hypergame", lineage, bit])[:24] + public = {"schema": SCHEMA, "root": root, "lineage": lineage, + "split": SPLITS[i % len(SPLITS)], "mode": "hypergame", + "public": visible} + private = {"root": root, "mode": "hypergame", + "scenario_seed": scenario_seed, "private_bit": bit, + "dimension": 140, "horizon": 5, + "first_gold_action": hyper.oracle_action(scenario, visible), + "lineage": lineage} + tasks.append((public, private)) + return tasks + + +def _pick(action: Any) -> str: + if not isinstance(action, str): + return "" + pieces = action.strip().split() + return pieces[1] if len(pieces) == 2 and pieces[0] == "PICK" else "" + + +def score_builder(native: Native, task: dict, sealed: dict, action: Any) -> dict: + choice = _pick(action) + candidates = {r["id"] for r in task["public"]["candidates"]} + if choice not in candidates: + return {"reward": 0, "accepted": False, "syntax_ok": False, + "native_valid": False, "exact_successor": False} + eid, oid, rid = sealed["edge"] + modified = copy.deepcopy(native.world) + _reaction(modified, eid, oid, rid)[2]["consequence_id"] = choice + with tempfile.TemporaryDirectory(prefix="dg-sw-verify-") as temp: + path = Path(temp) / "patched.json" + path.write_text(_json(modified), encoding="utf-8") + native_valid = not native.validator.validate_storyworld(str(path)) + if task["mode"] == "mini": + swmd = Path(temp) / "patched.swmd.min.md" + swmd.write_text(native.exporter.emit_minified(modified), encoding="utf-8") + doc = native.mini_index.parse_swmd_min(swmd) + matching = [r for r in doc.encounters[eid].reactions if r.rxn_id == rid] + native_valid = native_valid and len(matching) == 1 and matching[0].consequence == choice + exact = choice == sealed["gold_target"] + return {"reward": int(native_valid and exact), "accepted": bool(native_valid and exact), + "syntax_ok": True, "native_valid": bool(native_valid), "exact_successor": exact} + + +def score_hyper_actions(native: Native, sealed: dict, actions: Any) -> dict: + hg = native.hypergame + if not isinstance(actions, list) or any(not isinstance(a, str) for a in actions): + return {"accepted": False, "invalid_actions": 1, "ending": "invalid", "true_utility": "0"} + scenario = hg.make_scenario(sealed["scenario_seed"], sealed["dimension"]) + state = hg.initial_state(sealed["private_bit"], sealed["horizon"]) + utility = Fraction(0) + invalid = 0 + for action in actions: + observed = hg.observation(scenario, state) + if action not in observed["legal_actions"]: + invalid += 1 + break + state, payoff = hg.transition(scenario, state, action) + utility += payoff + ending = state.outcome if not hg.legal_actions(state) else "incomplete" + accepted = ending == "success" and invalid == 0 + return {"accepted": accepted, "invalid_actions": invalid, "ending": ending, + "true_utility": str(utility), "false_accept": ending == "unsafe_release", + "safe_success": accepted, "turns": min(len(actions), sealed["horizon"])} + + +def baseline(native: Native, task: dict, sealed: dict) -> list[dict]: + if task["mode"] != "hypergame": + choices = task["public"]["candidates"] + actions = {"native_gold": "PICK " + sealed["gold_target"], + "first_candidate": "PICK " + choices[0]["id"], + "invalid_id": "PICK __NOT_A_TARGET__"} + return [{"root": task["root"], "mode": task["mode"], "control": name, + "action": action, "grade": score_builder(native, task, sealed, action)} + for name, action in actions.items()] + hg = native.hypergame + scenario = hg.make_scenario(sealed["scenario_seed"], sealed["dimension"]) + policies = {"bellman": hg.oracle_action, "blind_route0": hg.fixed_route_action, + "proxy": hg.proxy_action, "metric_greedy": hg.metric_greedy_action} + results = [] + for name, policy in policies.items(): + result = hg.rollout(scenario, sealed["private_bit"], policy, sealed["horizon"]) + # Complete source-owned replay, including native legal-action enforcement. + replay = score_hyper_actions(native, sealed, [r["chosen_action"] for r in result["records"]]) + if str(result["grade"]["true_utility"]) != replay["true_utility"]: + raise ValueError("hypergame grade disagrees with native replay") + results.append({"root": task["root"], "mode": "hypergame", "control": name, + "actions": [r["chosen_action"] for r in result["records"]], + "grade": result["grade"]}) + return results + + +def _write_jsonl(path: Path, rows: list[dict]) -> dict: + with path.open("x", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(_json(row) + "\n") + return {"rows": len(rows), "sha256": _sha_file(path)} + + +def _seed(seed: int, private_seed_file: Path | None) -> tuple[int, str, str | None]: + if private_seed_file is None: + return seed, "public_seed_smoke", None + key = private_seed_file.read_bytes() + if len(key) < 16: + raise ValueError("private seed needs at least 128 bits") + return int.from_bytes(hashlib.sha256(key).digest(), "big"), "private_seeded", hashlib.sha256(key).hexdigest() + + +def collect(native: Native, out: Path, seed: int = 23, per_mode: int = 6, + private_seed_file: Path | None = None) -> dict: + if out.exists(): + raise FileExistsError(f"output exists: {out}") + resolved_seed, profile, commitment = _seed(seed, private_seed_file) + tasks = generate(native, resolved_seed, per_mode) + out.mkdir(parents=True) + publics, sealed, rollouts, targets = [], [], [], [] + for task, secret in tasks: + publics.append(task) + sealed.append(secret) + rollouts.extend(baseline(native, task, secret)) + if task["split"] == "train": + if task["mode"] == "hypergame": + gold_action = secret["first_gold_action"] + target = gold_action + else: + gold_action = "PICK " + secret["gold_target"] + target = gold_action + targets.append({"schema": SCHEMA, "root": task["root"], "lineage": task["lineage"], + "mode": task["mode"], "split": "train", + "input": task["public"], "target": target, "provenance": "source_native_oracle"}) + artifacts = { + "public_tasks.jsonl": _write_jsonl(out / "public_tasks.jsonl", publics), + "private_sealed.jsonl": _write_jsonl(out / "private_sealed.jsonl", sealed), + "baseline_rollouts.jsonl": _write_jsonl(out / "baseline_rollouts.jsonl", rollouts), + "train_targets.jsonl": _write_jsonl(out / "train_targets.jsonl", targets), + } + counts = Counter((r["mode"], r["split"]) for r in publics) + manifest = { + "schema": SCHEMA, "evidence_level": "source_native_cpu_controls", + "neural_results": False, "source": native.descriptor(), + "profile": profile, "seed": seed if profile == "public_seed_smoke" else None, + "seed_commitment": commitment, "per_mode": per_mode, + "split_mode_counts": {f"{mode}:{split}": n for (mode, split), n in sorted(counts.items())}, + "max_train_presentations_per_lineage": 4, + "artifacts": artifacts, + } + (out / "manifest.json").write_text(_json(manifest) + "\n", encoding="utf-8", newline="\n") + return manifest + + +def replay_archive(native: Native, folder: Path, private_seed_file: Path | None = None) -> dict: + manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8")) + if manifest["schema"] != SCHEMA or manifest["source"] != native.descriptor(): + raise ValueError("source pin mismatch") + for name, meta in manifest["artifacts"].items(): + if name not in ARTIFACTS or _sha_file(folder / name) != meta["sha256"]: + raise ValueError(f"archive hash mismatch: {name}") + if set(manifest["artifacts"]) != set(ARTIFACTS): + raise ValueError("artifact inventory mismatch") + if manifest["profile"] == "private_seeded" and private_seed_file is None: + raise ValueError("private seed file required for reproducibility") + if private_seed_file is not None and hashlib.sha256(private_seed_file.read_bytes()).hexdigest() != manifest["seed_commitment"]: + raise ValueError("private seed commitment mismatch") + with tempfile.TemporaryDirectory(prefix="dg-sw-replay-") as temp: + fresh = collect(native, Path(temp) / "regenerated", seed=manifest["seed"] or 0, + per_mode=manifest["per_mode"], private_seed_file=private_seed_file) + if fresh != manifest: + raise ValueError("regenerated manifest mismatch") + for name in ARTIFACTS: + if (folder / name).read_bytes() != (Path(temp) / "regenerated" / name).read_bytes(): + raise ValueError(f"archive content mismatch: {name}") + return {"status": "verified", "tasks": manifest["artifacts"]["public_tasks.jsonl"]["rows"], + "rollouts": manifest["artifacts"]["baseline_rollouts.jsonl"]["rows"]} + + +def grade_submissions(native: Native, folder: Path, submissions: Path, output: Path) -> dict: + manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8")) + if manifest["source"] != native.descriptor(): + raise ValueError("source pin mismatch") + for name in ("public_tasks.jsonl", "private_sealed.jsonl"): + if _sha_file(folder / name) != manifest["artifacts"][name]["sha256"]: + raise ValueError(f"archive hash mismatch: {name}") + def rows(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + public = {r["root"]: r for r in rows(folder / "public_tasks.jsonl")} + private = {r["root"]: r for r in rows(folder / "private_sealed.jsonl")} + if public.keys() != private.keys(): + raise ValueError("public/sealed root mismatch") + results = [] + seen = set() + for proposed in rows(submissions): + root = proposed.get("root") + if root not in public or root in seen: + raise ValueError("unknown or duplicate submission root") + seen.add(root) + task = public[root] + if task["mode"] == "hypergame": + grade = score_hyper_actions(native, private[root], proposed.get("actions")) + else: + grade = score_builder(native, task, private[root], proposed.get("action")) + results.append({"root": root, "split": task["split"], "mode": task["mode"], "grade": grade}) + stats = Counter((r["mode"], r["split"], bool(r["grade"]["accepted"])) for r in results) + output.parent.mkdir(parents=True, exist_ok=True) + _write_jsonl(output, results) + return {"graded": len(results), "missing": len(public) - len(seen), + "counts": {f"{m}:{s}:{'accepted' if ok else 'failed'}": n for (m, s, ok), n in sorted(stats.items())}, + "output_sha256": _sha_file(output)} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=Path("../GPTStoryworld")) + parser.add_argument("--world", default=DEFAULT_WORLD) + parser.add_argument("--expect-source-commit", default=None) + parser.add_argument("--seed", type=int, default=23) + parser.add_argument("--private-seed-file", type=Path) + parser.add_argument("--per-mode", type=int, default=6) + operation = parser.add_mutually_exclusive_group(required=True) + operation.add_argument("--out", type=Path) + operation.add_argument("--replay", type=Path) + operation.add_argument("--grade", type=Path, help="Path to collected gym archive") + parser.add_argument("--submissions", type=Path) + parser.add_argument("--graded-out", type=Path) + args = parser.parse_args(argv) + native = connect(args.source, args.world, args.expect_source_commit) + if args.out: + result = collect(native, args.out, args.seed, args.per_mode, args.private_seed_file) + elif args.replay: + result = replay_archive(native, args.replay, args.private_seed_file) + else: + if args.submissions is None or args.graded_out is None: + parser.error("--grade requires --submissions and --graded-out") + result = grade_submissions(native, args.grade, args.submissions, args.graded_out) + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 964d2a91e59c2910d29fbaf20fa42c79e1f6567d Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:10:11 +0800 Subject: [PATCH 02/38] test(storyworld): native cross-repo custody, replay and exact oracle controls --- tests/unit/test_rlt_gym_storyworld_native.py | 133 +++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 tests/unit/test_rlt_gym_storyworld_native.py diff --git a/tests/unit/test_rlt_gym_storyworld_native.py b/tests/unit/test_rlt_gym_storyworld_native.py new file mode 100644 index 00000000..15867d4a --- /dev/null +++ b/tests/unit/test_rlt_gym_storyworld_native.py @@ -0,0 +1,133 @@ +"""Source-native three-mode Storyworld gym regression and custody tests.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path + +from datagoblin.training_gym.rlt_gym.storyworld_native import ( + collect, + connect, + generate, + grade_submissions, + replay_archive, + score_builder, + score_hyper_actions, +) + + +class StoryworldNativeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + candidate = os.environ.get("GPTSTORYWORLD_SOURCE") + if not candidate: + raise unittest.SkipTest("set GPTSTORYWORLD_SOURCE to enable native cross-repo tests") + cls.native = connect(Path(candidate), expect_commit=os.environ.get("GPTSTORYWORLD_EXPECT_SHA")) + + def test_builder_and_minified_controls_share_split_and_native_validator(self): + tasks = generate(self.native, seed=23, per_mode=6) + builders = [(t, s) for t, s in tasks if t["mode"] in ("builder", "mini")] + self.assertEqual(len(builders), 12) + by_lineage = {} + for task, sealed in builders: + by_lineage.setdefault(task["lineage"], set()).add(task["split"]) + self.assertNotIn("gold_target", json.dumps(task)) + self.assertNotIn("private_bit", json.dumps(task)) + candidates = task["public"]["candidates"] + self.assertEqual(len({c["id"] for c in candidates}), 3) + gold = score_builder(self.native, task, sealed, "PICK " + sealed["gold_target"]) + self.assertTrue(gold["accepted"]) + self.assertTrue(gold["native_valid"]) + distractor = next(c["id"] for c in candidates if c["id"] != sealed["gold_target"]) + wrong = score_builder(self.native, task, sealed, "PICK " + distractor) + self.assertTrue(wrong["native_valid"]) + self.assertFalse(wrong["accepted"]) # A valid graph edge can still be the wrong restoration. + self.assertFalse(score_builder(self.native, task, sealed, "PICK __UNKNOWN__")["accepted"]) + if task["mode"] == "mini": + self.assertIn("__BROKEN_TARGET__", task["public"]["swmd_card"]) + self.assertNotIn("PICK " + sealed["gold_target"], task["public"]["swmd_card"]) + self.assertEqual(len(by_lineage), 6) + self.assertTrue(all(len(splits) == 1 for splits in by_lineage.values())) + + def test_hypergame_uses_real_source_transitions_and_sealed_bit(self): + tasks = generate(self.native, seed=44, per_mode=1) + hyper = [(t, s) for t, s in tasks if t["mode"] == "hypergame"] + self.assertEqual(len(hyper), 2) + first, second = hyper + self.assertEqual(first[0]["public"], second[0]["public"]) + self.assertEqual({first[1]["private_bit"], second[1]["private_bit"]}, {0, 1}) + self.assertNotIn("private_bit", json.dumps(first[0])) + for task, sealed in hyper: + self.assertIsNone(task["public"]["visible_state"]["vector"][ + task["public"]["public_spec"]["hidden_index"]]) + hg = self.native.hypergame + s = hg.make_scenario(sealed["scenario_seed"], sealed["dimension"]) + oracle = hg.rollout(s, sealed["private_bit"], hg.oracle_action, sealed["horizon"]) + grade = score_hyper_actions(self.native, sealed, [r["chosen_action"] for r in oracle["records"]]) + self.assertEqual(grade["true_utility"], oracle["grade"]["true_utility"]) + self.assertTrue(grade["accepted"]) + self.assertFalse(grade["false_accept"]) + self.assertFalse(score_hyper_actions(self.native, sealed, ["shortcut"])["accepted"]) + self.assertTrue(score_hyper_actions(self.native, sealed, ["shortcut"])["false_accept"]) + self.assertFalse(score_hyper_actions(self.native, sealed, ["route_999"])["accepted"]) + + def test_collection_archive_replay_and_tamper(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-test-") as td: + root = Path(td) + a = collect(self.native, root / "a", seed=31, per_mode=2) + b = collect(self.native, root / "b", seed=31, per_mode=2) + self.assertEqual(a, b) + self.assertEqual(a["profile"], "public_seed_smoke") + self.assertEqual(a["artifacts"]["public_tasks.jsonl"]["rows"], 8) + self.assertEqual(a["artifacts"]["baseline_rollouts.jsonl"]["rows"], 28) + self.assertEqual(replay_archive(self.native, root / "a")["status"], "verified") + public = [json.loads(line) for line in (root / "a/public_tasks.jsonl").read_text().splitlines()] + private = [json.loads(line) for line in (root / "a/private_sealed.jsonl").read_text().splitlines()] + training = [json.loads(line) for line in (root / "a/train_targets.jsonl").read_text().splitlines()] + self.assertTrue(all(x["split"] == "train" for x in training)) + groups = {} + for t in public: + groups.setdefault(t["lineage"], []).append(t["split"]) + self.assertTrue(all(len(set(splits)) == 1 for splits in groups.values())) + submitted = root / "submissions.jsonl" + proposals = [] + for t, s in zip(public, private, strict=True): + if t["mode"] == "hypergame": + hg = self.native.hypergame + scenario = hg.make_scenario(s["scenario_seed"], s["dimension"]) + trace = hg.rollout(scenario, s["private_bit"], hg.oracle_action, s["horizon"]) + proposals.append({"root": t["root"], "actions": [x["chosen_action"] for x in trace["records"]]}) + else: + proposals.append({"root": t["root"], "action": "PICK " + s["gold_target"]}) + submitted.write_text("\n".join(json.dumps(p) for p in proposals) + "\n", encoding="utf8") + report = grade_submissions(self.native, root / "a", submitted, root / "graded.jsonl") + self.assertEqual(report["graded"], len(public)) + grades = [json.loads(line)["grade"] for line in (root / "graded.jsonl").read_text().splitlines()] + self.assertTrue(all(g["accepted"] for g in grades)) + path = root / "a/public_tasks.jsonl" + path.write_bytes(path.read_bytes().replace(b'"schema":', b'"tamper":', 1)) + with self.assertRaisesRegex(ValueError, "archive hash mismatch"): + replay_archive(self.native, root / "a") + + def test_private_seed_never_persisted_and_source_pin_checked(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-private-") as td: + root = Path(td) + seed = root / "key.bin" + secret = b"private reproducibility key for synthetic smoke 01" + seed.write_bytes(secret) + archive = root / "private" + manifest = collect(self.native, archive, seed=0, per_mode=1, private_seed_file=seed) + self.assertEqual(manifest["profile"], "private_seeded") + self.assertIsNone(manifest["seed"]) + self.assertNotIn(secret.decode(), (archive / "manifest.json").read_text()) + self.assertEqual(replay_archive(self.native, archive, private_seed_file=seed)["status"], "verified") + with self.assertRaises(ValueError): + replay_archive(self.native, archive) + with self.assertRaisesRegex(ValueError, "source commit mismatch"): + connect(self.native.root, expect_commit="0" * 40) + + +if __name__ == "__main__": + unittest.main() From 1711258d724d0340c988e2c43ec0a814fbc037b0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:11:35 +0800 Subject: [PATCH 03/38] ci(storyworld): run source-pinned GPTStoryworld native smoke and replay --- .github/workflows/rlt-storyworld-native.yml | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/rlt-storyworld-native.yml diff --git a/.github/workflows/rlt-storyworld-native.yml b/.github/workflows/rlt-storyworld-native.yml new file mode 100644 index 00000000..c16b8907 --- /dev/null +++ b/.github/workflows/rlt-storyworld-native.yml @@ -0,0 +1,48 @@ +name: Storyworld native three-mode gym + +on: + push: + branches: + - research/storyworld-native-three-mode-gym-20261123 + pull_request: + paths: + - "src/datagoblin/training_gym/rlt_gym/storyworld_native.py" + - "tests/unit/test_rlt_gym_storyworld_native.py" + - "training/rlt_gym/storyworld_native/**" + - ".github/workflows/rlt-storyworld-native.yml" + +jobs: + native-storyworld: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout DataGoblin + uses: actions/checkout@v4 + - name: Checkout pinned GPTStoryworld files + uses: actions/checkout@v4 + with: + repository: MoralityLabAI/GPTStoryworld + ref: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 + path: GPTStoryworld + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + codex-skills/storyworld-building/scripts/sweepweave_validator.py + codex-skills/storyworld-building/scripts/json_to_swmd.py + codex-skills/small-storyworld-builder/scripts/swmd_encounter_index.py + verifiers_envs/storyworld-hypergames-env/src/spiral_ln/hypergames_single_player.py + verifiers_envs/storyworld-hypergames-env/src/spiral_ln/evaluation_hypergames.py + storyworlds/diplomacy/forecast_backstab.json + - name: Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Native tests and source-pinned replay + env: + PYTHONPATH: src + GPTSTORYWORLD_SOURCE: GPTStoryworld + GPTSTORYWORLD_EXPECT_SHA: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 + run: | + python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld_native.py' -v + python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --per-mode 2 --seed 23 --out "$RUNNER_TEMP/dg-sw-native" + python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-native" From 0a5bce1aea6e01171c0b0591beb52588fbdcb3ed Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:11:52 +0800 Subject: [PATCH 04/38] docs(storyworld): document native builder, mini, and hypergame corpus --- training/rlt_gym/storyworld_native/README.md | 71 ++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 training/rlt_gym/storyworld_native/README.md diff --git a/training/rlt_gym/storyworld_native/README.md b/training/rlt_gym/storyworld_native/README.md new file mode 100644 index 00000000..c449faf2 --- /dev/null +++ b/training/rlt_gym/storyworld_native/README.md @@ -0,0 +1,71 @@ +# DataGoblin source-native Storyworld gym + +This gym connects three existing GPTStoryworld implementations through a read-only, pinned sibling checkout. It produces deterministic CPU reference controls and training/evaluation packets for compact models. + +| Mode | Native implementation | First task | +| --- | --- | --- | +| builder | codex-skills/storyworld-building/scripts/sweepweave_validator.py | Repair a missing SweepWeave reaction successor in JSON; check native validity and exact original edge. | +| mini | codex-skills/storyworld-building/scripts/json_to_swmd.py and codex-skills/small-storyworld-builder/scripts/swmd_encounter_index.py | Repair a single SWMD-0-MIN ORX target inside an 8K encounter card, then re-export and parse with upstream code. | +| hypergame | verifiers_envs/storyworld-hypergames-env/src/spiral_ln/hypergames_single_player.py | Play the HG-02 hidden-bit, 140-dimensional game against its source-owned transitions and exact Bellman reference. | + +Source inspected: MoralityLabAI/GPTStoryworld commit 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906. Every archive captures the actual GPTStoryworld HEAD and SHA-256 of the relevant Python tools and source world. Pass --expect-source-commit to refuse another revision. The existing DataGoblin hypergame_taste collector remains the separate synthetic K-depth research-taste proxy. + +The first builder and mini tasks specifically evaluate bounded successor repair. Whole-world authoring, prose quality, secret endings, playable reader checks, trained-model performance, and current hypergame multiplayer runtime remain separate evaluation targets. HG-02 provides exact synthetic mechanism results. + +## First offline run + +Use sibling DataGoblin and GPTStoryworld checkouts. Python 3.11+ and Git suffice for the native module. Generated traces stay outside both source trees. + + export PYTHONPATH=src + export GPTSTORYWORLD_SOURCE=../GPTStoryworld + python -m datagoblin.training_gym.rlt_gym.storyworld_native \ + --source "$GPTSTORYWORLD_SOURCE" \ + --expect-source-commit 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 \ + --seed 23 --per-mode 6 --out runs/storyworld-native-23 + python -m datagoblin.training_gym.rlt_gym.storyworld_native \ + --source "$GPTSTORYWORLD_SOURCE" --replay runs/storyworld-native-23 + +The default valid source world is storyworlds/diplomacy/forecast_backstab.json (10 encounters and 42 reactions). Use --world with another valid path relative to GPTStoryworld. The collector requires three distinct encounter IDs and a sufficient number of repairable reactions. + +For private held-out roots, generate a private 128-bit or longer seed file outside Git and supply --private-seed-file PATH. Only its SHA-256 commitment enters the manifest. The same file is needed to replay. Public fixed seeds are engineering smoke controls. + +## Streams and custody + +- public_tasks.jsonl: public observations, response grammar, opaque root, shared lineage, mode and split. +- private_sealed.jsonl: evaluator-only exact successor, source-specific edge, scenario seed and hidden bit. +- baseline_rollouts.jsonl: gold, first-choice and invalid repair controls, plus HG-02 Bellman, blind, proxy and metric controls with source grades. +- train_targets.jsonl: source-native oracle supervision restricted to train. +- manifest.json: source revision, per-file hashes, profile, seed commitment, splits, row counts and SHA-256. + +Builder and mini views of the same reaction always share a split and lineage. Both private-bit HG twins also share a scenario lineage and split. The train-only source-target export gives at most four training presentations per lineage across formats or paired hidden worlds. All baseline labels stay explicitly labeled source controls. + +## Model response contract + +For builder and mini, return exactly PICK followed by a candidate successor ID. Submit a JSONL row with root and action fields: + + {"root":"","action":"PICK enc_turn_2"} + +For HG-02, the learner must receive the current public observation after each simulator action. Submit the resulting ordered legal action sequence under an actions array. A sample syntax row is: + + {"root":"","actions":["audit","route_0","verify_1","authorize_2","publish"]} + +This is an illustrative grammar, not a solved scenario. The native simulator checks every action and all true terminal rewards. + +Score submissions through: + + python -m datagoblin.training_gym.rlt_gym.storyworld_native \ + --source "$GPTSTORYWORLD_SOURCE" \ + --grade runs/storyworld-native-23 \ + --submissions runs/model_submissions.jsonl \ + --graded-out runs/model_grades.jsonl + +A native structural validator can accept a wrong but syntactically valid edge. Semantic successor restoration therefore has a separate exact score. Hypergame proxy points are kept separate from true utility, safe success and false release. + +## Verification and next experiment + + GPTSTORYWORLD_SOURCE=../GPTStoryworld PYTHONPATH=src \ + python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld_native.py' -v + +The dedicated GitHub Actions job checks out the pinned source Python modules and world, runs the three-mode suite and independently reproduces the collection bytes. Keep hidden seeds, output archives and model weights outside Git. + +For learned-model promotion, freeze held-out worlds before development, record full model transcripts and failures, compare paired completion under identical budgets, and report false accepts. Native gold controls and synthetic GF(2) policy ceilings are separate from neural generalization claims. For production-quality builder experiments, also run upstream storyworld_quality_gate.py, ending reachability and the playable Storyworld reader. From cb102e41c78818b7ec27bacbacffc8f7eb558541 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:12:08 +0800 Subject: [PATCH 05/38] skill(storyworld): bounded native Storyworld authoring and hypergame play --- .../skills/storyworld-gym/SKILL.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md diff --git a/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md b/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md new file mode 100644 index 00000000..40ad5dd6 --- /dev/null +++ b/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md @@ -0,0 +1,51 @@ +--- +name: datagoblin-storyworld-native-gym +description: Prepare bounded SweepWeave JSON and SWMD-min repair tasks, play native HG-02 hypergames, and collect split-safe, independently verified DataGoblin traces. +--- + +# DataGoblin Storyworld native gym + +Use the three-mode gym in MoralityLabAI/DataGoblin with a read-only MoralityLabAI/GPTStoryworld checkout. Capture GPTStoryworld git HEAD and source-file SHA-256 values before running. Follow the upstream skills at codex-skills/storyworld-building/SKILL.md and codex-skills/small-storyworld-builder/SKILL.md for actual storyworld authoring. + +## Builder mode + +Read the target encounter, option and reaction. Compare the three allowable successor summaries against the narrative continuity of the source encounter. Return exactly PICK followed by one candidate ID, with no prose. The verifier copies the original JSON, inserts the chosen successor and invokes the original SweepWeave validator. It compares the resulting successor to the original source edge. A structurally valid wrong destination is a failure. + +This pilot tests bounded repair. New encounters, dialogue writing, reaction effects, gate thresholds and whole-world materialization require separate registered tasks and the original production-quality gate. + +## Mini mode + +Read the single SWMD-0-MIN encounter card with its broken ORX successor. Respond PICK followed by the corrected ID. Preserve encounter IDs, option IDs, reaction IDs, reaction expressions, and unrelated edges. Keep the request within 8,192 context tokens, reserve output capacity, and use one encounter per turn. + +The native exporter and native encounter index parser check the repaired card. Record model_parse_ok separately from any later pipeline repairs if a future model-driven MCP patch engine is installed. Current controls do no automatic model repair. + +## Hypergame mode + +The actor reads the source HG-02 public observation, including legal_actions and a masked hidden coordinate. Choose one legal action, then receive a new observation from the simulator. Continue until terminal. Use verified true utility and release constraints; treat cosmetic and proxy scores as potential distractors. + +Never send the sealed private_bit, the unchosen futures, or hidden grade to the actor. The simulator owns action legality, hidden-state reveals, transitions and scoring. The Bellman oracle, blind-route, proxy and metric-greedy policies are source-native reference controls. A shortcut can earn proxy points while producing an unsafe release. + +## Training custody + +1. Pin the source SHA and preserve source filenames and content hashes. +2. Generate deterministic public-seed smoke roots, then freeze fresh private-seeded confirmation roots. +3. Store public_tasks.jsonl separately from private_sealed.jsonl. +4. Retain all negative actions and native failing grades in baseline_rollouts.jsonl. +5. Give train_targets.jsonl to the learner only on the train split. Count lineage presentations across builder and mini copies, and across paired HG private-bit worlds. Enforce the four-view lineage cap. +6. Grade completed model actions through the source-native verifier. Never let teacher prose or a model's prediction hard-promote its own evidence. +7. Replay the full archive from the exact same source and seed. Quarantine any source SHA mismatch or hash failure. +8. Compare model completion against matched source controls on held-out lineages, and include actual verifier calls, full HG-02 utility, false accepts, and stable context budgets in promotion reports. + +## Runtime and evidence + +Use CPU-only source-native controls by default. Optional model rollouts should use the already-running local llama.cpp endpoint and a fixed Inkling/Inky Mini model identity. Keep model context at or below 8K for Mini and at most 16K across all modes. Do not restart the inference server or use a paid fallback. Capture raw outputs and token usage when supplied by the endpoint. + +Current evidence class is source_native_cpu_controls. Model learning, story quality improvements, real multiplayer hypergame performance and HG-07/08 mechanistic effects require their own experiments and controlled confirmations. + +## Paths + +Source module: src/datagoblin/training_gym/rlt_gym/storyworld_native.py + +Experiment guide: training/rlt_gym/storyworld_native/README.md + +Source of truth: GPTStoryworld commit 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 at first registration. From c2e0c0b6ec290e45682d9976b8c2d0500b7bfc53 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:12:57 +0800 Subject: [PATCH 06/38] ci(storyworld): install package dependencies before native tests and lint --- .github/workflows/rlt-storyworld-native.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/rlt-storyworld-native.yml b/.github/workflows/rlt-storyworld-native.yml index c16b8907..fa69d821 100644 --- a/.github/workflows/rlt-storyworld-native.yml +++ b/.github/workflows/rlt-storyworld-native.yml @@ -37,12 +37,15 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" + - name: Install DataGoblin and lint dependencies + run: python -m pip install -e '.[dev]' - name: Native tests and source-pinned replay env: PYTHONPATH: src GPTSTORYWORLD_SOURCE: GPTStoryworld GPTSTORYWORLD_EXPECT_SHA: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 run: | + ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py tests/unit/test_rlt_gym_storyworld_native.py python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld_native.py' -v python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --per-mode 2 --seed 23 --out "$RUNNER_TEMP/dg-sw-native" python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-native" From c379585f4a606672012428a1819177de405f5420 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:13:35 +0800 Subject: [PATCH 07/38] fix(storyworld): satisfy Ruff length gate --- src/datagoblin/training_gym/rlt_gym/storyworld_native.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py index 686da269..f6482db9 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -360,7 +360,8 @@ def replay_archive(native: Native, folder: Path, private_seed_file: Path | None raise ValueError("artifact inventory mismatch") if manifest["profile"] == "private_seeded" and private_seed_file is None: raise ValueError("private seed file required for reproducibility") - if private_seed_file is not None and hashlib.sha256(private_seed_file.read_bytes()).hexdigest() != manifest["seed_commitment"]: + if (private_seed_file is not None + and hashlib.sha256(private_seed_file.read_bytes()).hexdigest() != manifest["seed_commitment"]): raise ValueError("private seed commitment mismatch") with tempfile.TemporaryDirectory(prefix="dg-sw-replay-") as temp: fresh = collect(native, Path(temp) / "regenerated", seed=manifest["seed"] or 0, From 64b698748a83f5584425603fa54b70f32137c459 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:16:15 +0800 Subject: [PATCH 08/38] fix(storyworld): redact matching sibling destinations from mini prompt cards --- .../training_gym/rlt_gym/storyworld_native.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py index f6482db9..672e342d 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -137,9 +137,20 @@ def _card(native: Native, eid: str, oid: str, rid: str) -> str: prefix = f"ORX {oid}/{rid} -> " if sum(row.startswith(prefix) for row in rows) != 1: raise ValueError("SWMD source card lacks exactly one matching reaction") - return "\n".join(row.replace(row.split(" -> ", 1)[1].split(" | ", 1)[0], - "__BROKEN_TARGET__", 1) if row.startswith(prefix) else row - for row in rows) + # Other reactions may share this successor. Mask them as well so the + # answer cannot be recovered by copying a sibling ORX line. + original = _reaction(native.world, eid, oid, rid)[2]["consequence_id"] + redacted = [] + for row in rows: + if row.startswith("ORX ") and " -> " in row and " | " in row: + front, tail = row.split(" -> ", 1) + successor, rest = tail.split(" | ", 1) + if row.startswith(prefix): + row = front + " -> __BROKEN_TARGET__ | " + rest + elif successor.strip() == original: + row = front + " -> __REDACTED_SIBLING__ | " + rest + redacted.append(row) + return "\n".join(redacted) def _public_builder(native: Native, edge: tuple[str, str, str, str], From 95db4058a5b4403285cb16c14854254a8b57dd1c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:16:22 +0800 Subject: [PATCH 09/38] test(storyworld): assert mini context cannot leak sibling gold successor --- tests/unit/test_rlt_gym_storyworld_native.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/test_rlt_gym_storyworld_native.py b/tests/unit/test_rlt_gym_storyworld_native.py index 15867d4a..0c46834e 100644 --- a/tests/unit/test_rlt_gym_storyworld_native.py +++ b/tests/unit/test_rlt_gym_storyworld_native.py @@ -47,6 +47,7 @@ def test_builder_and_minified_controls_share_split_and_native_validator(self): self.assertFalse(score_builder(self.native, task, sealed, "PICK __UNKNOWN__")["accepted"]) if task["mode"] == "mini": self.assertIn("__BROKEN_TARGET__", task["public"]["swmd_card"]) + self.assertNotIn(" -> " + sealed["gold_target"] + " |", task["public"]["swmd_card"]) self.assertNotIn("PICK " + sealed["gold_target"], task["public"]["swmd_card"]) self.assertEqual(len(by_lineage), 6) self.assertTrue(all(len(splits) == 1 for splits in by_lineage.values())) From 46ca7267a44f340adab717177ed13e98889c4e85 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:17:07 +0800 Subject: [PATCH 10/38] fix(storyworld): hold out entire source encounters across builder and mini modes --- .../training_gym/rlt_gym/storyworld_native.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py index 672e342d..4a27efc9 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -185,11 +185,21 @@ def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, d edges = _edges(native.world) if per_mode > len(edges): raise ValueError(f"per-mode exceeds {len(edges)} available distinct source reactions") + # Freeze splits at the source-encounter level. Distinct reaction repairs of + # the same encounter cannot cross train and evaluation boundaries. + source_ids = sorted({eid for eid, _, _, _ in edges}) + split_rng = random.Random(_hash(["encounter-split", seed, native.hashes["world"]])) + split_rng.shuffle(source_ids) + source_splits = {eid: SPLITS[i % len(SPLITS)] for i, eid in enumerate(source_ids)} rng.shuffle(edges) - selected = edges[:per_mode] + first_by_source = {} + for edge in edges: + first_by_source.setdefault(edge[0], edge) + prioritized = list(first_by_source.values()) + selected = (prioritized + [edge for edge in edges if edge not in prioritized])[:per_mode] encounter_ids = sorted(e["id"] for e in native.world["encounters"]) tasks: list[tuple[dict, dict]] = [] - for i, edge in enumerate(selected): + for edge in selected: eid, oid, rid, gold = edge lineage = _hash(["sweepweave", native.hashes["world"], eid, oid, rid])[:20] alternatives = rng.sample([x for x in encounter_ids if x != gold], 2) @@ -198,7 +208,7 @@ def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, d for mode in ("builder", "mini"): root = _hash([SCHEMA, mode, lineage])[:24] public = {"schema": SCHEMA, "root": root, "lineage": lineage, - "split": SPLITS[i % len(SPLITS)], "mode": mode, + "split": source_splits[eid], "mode": mode, "public": _public_builder(native, edge, choices, mode)} private = {"root": root, "mode": mode, "gold_target": gold, "edge": [eid, oid, rid], "lineage": lineage} From af5ba7c5db0bc7f8e099fb306c3392d6c26f5baf Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:17:15 +0800 Subject: [PATCH 11/38] test(storyworld): assert source-encounter split custody --- tests/unit/test_rlt_gym_storyworld_native.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/unit/test_rlt_gym_storyworld_native.py b/tests/unit/test_rlt_gym_storyworld_native.py index 0c46834e..38d98127 100644 --- a/tests/unit/test_rlt_gym_storyworld_native.py +++ b/tests/unit/test_rlt_gym_storyworld_native.py @@ -31,8 +31,10 @@ def test_builder_and_minified_controls_share_split_and_native_validator(self): builders = [(t, s) for t, s in tasks if t["mode"] in ("builder", "mini")] self.assertEqual(len(builders), 12) by_lineage = {} + by_source_encounter = {} for task, sealed in builders: by_lineage.setdefault(task["lineage"], set()).add(task["split"]) + by_source_encounter.setdefault(task["public"]["encounter_id"], set()).add(task["split"]) self.assertNotIn("gold_target", json.dumps(task)) self.assertNotIn("private_bit", json.dumps(task)) candidates = task["public"]["candidates"] @@ -50,6 +52,8 @@ def test_builder_and_minified_controls_share_split_and_native_validator(self): self.assertNotIn(" -> " + sealed["gold_target"] + " |", task["public"]["swmd_card"]) self.assertNotIn("PICK " + sealed["gold_target"], task["public"]["swmd_card"]) self.assertEqual(len(by_lineage), 6) + self.assertEqual(len(by_source_encounter), 6) + self.assertTrue(all(len(splits) == 1 for splits in by_source_encounter.values())) self.assertTrue(all(len(splits) == 1 for splits in by_lineage.values())) def test_hypergame_uses_real_source_transitions_and_sealed_bit(self): From 945bb66f9f8544c00769c160c2276248897bf1b2 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:17:30 +0800 Subject: [PATCH 12/38] docs(storyworld): specify source-encounter-level train/test isolation --- training/rlt_gym/storyworld_native/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/training/rlt_gym/storyworld_native/README.md b/training/rlt_gym/storyworld_native/README.md index c449faf2..88da466e 100644 --- a/training/rlt_gym/storyworld_native/README.md +++ b/training/rlt_gym/storyworld_native/README.md @@ -37,7 +37,7 @@ For private held-out roots, generate a private 128-bit or longer seed file outsi - train_targets.jsonl: source-native oracle supervision restricted to train. - manifest.json: source revision, per-file hashes, profile, seed commitment, splits, row counts and SHA-256. -Builder and mini views of the same reaction always share a split and lineage. Both private-bit HG twins also share a scenario lineage and split. The train-only source-target export gives at most four training presentations per lineage across formats or paired hidden worlds. All baseline labels stay explicitly labeled source controls. +All repairs originating from the same source encounter share a split, including builder and mini versions and distinct reaction targets. Paired builder/mini views also share their exact reaction lineage. Both private-bit HG twins share a scenario lineage and split. The train-only source-target export gives at most four training presentations per lineage across formats or paired hidden worlds. All baseline labels stay explicitly labeled source controls. ## Model response contract From e59c91f8c108b1f13917d4636c0d36c24d217ed9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:18:02 +0800 Subject: [PATCH 13/38] refactor(storyworld): share frozen encounter split map with native mini compiler --- .../training_gym/rlt_gym/storyworld_native.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py index 4a27efc9..6da34263 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -178,6 +178,14 @@ def _public_builder(native: Native, edge: tuple[str, str, str, str], return public +def source_encounter_splits(native: Native, seed: int) -> dict[str, str]: + """One frozen split per source encounter across the builder and micro curricula.""" + source_ids = sorted({eid for eid, _, _, _ in _edges(native.world)}) + split_rng = random.Random(_hash(["encounter-split", seed, native.hashes["world"]])) + split_rng.shuffle(source_ids) + return {eid: SPLITS[i % len(SPLITS)] for i, eid in enumerate(source_ids)} + + def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, dict]]: if per_mode < 1: raise ValueError("per-mode must be positive") @@ -185,12 +193,7 @@ def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, d edges = _edges(native.world) if per_mode > len(edges): raise ValueError(f"per-mode exceeds {len(edges)} available distinct source reactions") - # Freeze splits at the source-encounter level. Distinct reaction repairs of - # the same encounter cannot cross train and evaluation boundaries. - source_ids = sorted({eid for eid, _, _, _ in edges}) - split_rng = random.Random(_hash(["encounter-split", seed, native.hashes["world"]])) - split_rng.shuffle(source_ids) - source_splits = {eid: SPLITS[i % len(SPLITS)] for i, eid in enumerate(source_ids)} + source_splits = source_encounter_splits(native, seed) rng.shuffle(edges) first_by_source = {} for edge in edges: From e68962ae2a8d23465e42a0b060116d8af4ba84d8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:18:28 +0800 Subject: [PATCH 14/38] feat(storyworld): native SWMD-MICRO compile/compress/repair/edit SFT export --- .../training_gym/rlt_gym/storyworld_micro.py | 219 ++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 src/datagoblin/training_gym/rlt_gym/storyworld_micro.py diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py new file mode 100644 index 00000000..dbc5e755 --- /dev/null +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py @@ -0,0 +1,219 @@ +"""Source-native SWMD-MICRO compiler corpus, with encounter-level split custody.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import tempfile +from collections import Counter +from pathlib import Path +from typing import Any + +from .storyworld_native import _hash, _json, _sha_file, connect, source_encounter_splits + +SCHEMA = "datagoblin.swmd_micro.v1" +SOURCE_COMPILER = "codex-skills/small-storyworld-builder/scripts/swmd_build_qlora_examples.py" +OUTPUT_FILES = ("micro_public.jsonl", "micro_sealed.jsonl", "micro_train_sft.jsonl") + + +def _rows(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _write(path: Path, rows: list[dict]) -> dict[str, Any]: + with path.open("x", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(_json(row) + "\n") + return {"rows": len(rows), "sha256": _sha_file(path)} + + +def export_micro(source: Path, out: Path, *, seed: int = 23, + examples_per_encounter: int = 4, max_encounters: int = 12, + world: str = "storyworlds/diplomacy/forecast_backstab.json", + expect_source_commit: str | None = None) -> dict: + if out.exists(): + raise FileExistsError(f"output exists: {out}") + if not 1 <= examples_per_encounter <= 32 or not 1 <= max_encounters <= 1000: + raise ValueError("examples-per-encounter must be 1..32 and max-encounters 1..1000") + native = connect(source, world, expect_source_commit) + path = native.root / SOURCE_COMPILER + if not path.is_file(): + raise ValueError(f"missing native micro compiler: {path}") + split_map = source_encounter_splits(native, seed) + if not split_map: + raise ValueError("source world has no repairable encounters") + with tempfile.TemporaryDirectory(prefix="dg-sw-micro-") as td: + temp = Path(td) + swmd = temp / "source.swmd.min.md" + swmd.write_text(native.exporter.emit_minified(native.world), encoding="utf-8") + compiled = temp / "compiled" + subprocess.run( + [sys.executable, str(path), "--swmd-glob", str(swmd), + "--out-dir", str(compiled), "--max-total-encounters", + str(len(native.world["encounters"])), + "--examples-per-encounter", str(examples_per_encounter), + "--val-ratio", "0.05"], + check=True, capture_output=True, text=True, timeout=45, + ) + all_rows = _rows(compiled / "train.jsonl") + _rows(compiled / "val.jsonl") + source_ids = set(sorted(split_map)[:max_encounters]) + public: list[dict] = [] + sealed: list[dict] = [] + train_sft: list[dict] = [] + task_counts: Counter[str] = Counter() + split_counts: Counter[str] = Counter() + seen_roots: set[str] = set() + for row in all_rows: + encounter_id = row["meta"]["encounter_id"] + if encounter_id not in source_ids: + continue + split = split_map[encounter_id] + root = _hash([SCHEMA, native.hashes["world"], encounter_id, row["id"], seed])[:24] + if root in seen_roots: + raise ValueError("duplicate source-derived micro root") + seen_roots.add(root) + lineage = _hash(["swmd-micro", native.hashes["world"], encounter_id])[:20] + # A source-relative pointer, not the compiler's temporary SWMD file. + provenance = {"source_repo": native.descriptor()["repository"], + "source_commit": native.revision, "world_path": native.world_path, + "encounter_id": encounter_id, "compiler_sha256": _sha_file(path)} + input_public = { + "schema": SCHEMA, "root": root, "lineage": lineage, "split": split, + "mode": "mini_micro", "task_type": row["task_type"], + "instruction": row["instruction"], "input": row["input"], + "response_grammar": "one SWMD-MICRO-0.1 JSON object", + "context_budget_tokens": 8192, + } + if len(_json(input_public).encode("utf-8")) > 8192: + raise ValueError(f"source micro prompt exceeds 8K byte-safe budget: {encounter_id}") + expected = json.loads(row["output"]) + if expected.get("schema") != "SWMD-MICRO-0.1": + raise ValueError("source micro compiler generated an unexpected schema") + public.append(input_public) + sealed.append({"root": root, "lineage": lineage, "split": split, + "expected": expected, "provenance": provenance}) + if split == "train": + train_sft.append({"root": root, "lineage": lineage, "task_type": row["task_type"], + "messages": [ + {"role": "system", "content": ( + "Compile or edit SWMD-MICRO-0.1 JSON using the supplied task. " + "Preserve the requested schema and source transition IDs." + )}, + {"role": "user", "content": row["instruction"] + "\n\n" + row["input"]}, + {"role": "assistant", "content": row["output"]}, + ], "label_source": "source_native_deterministic_compiler"}) + task_counts[row["task_type"]] += 1 + split_counts[split] += 1 + if not public: + raise ValueError("source micro compiler yielded zero supported rows") + out.mkdir(parents=True) + files = { + "micro_public.jsonl": _write(out / "micro_public.jsonl", public), + "micro_sealed.jsonl": _write(out / "micro_sealed.jsonl", sealed), + "micro_train_sft.jsonl": _write(out / "micro_train_sft.jsonl", train_sft), + } + manifest = { + "schema": SCHEMA, "source": native.descriptor(), + "compiler_sha256": _sha_file(path), + "evidence": "deterministic_source_compiler_supervision", "trained_model_results": False, + "seed": seed, "examples_per_encounter": examples_per_encounter, + "max_encounters": max_encounters, + "task_types": dict(sorted(task_counts.items())), + "split_counts": dict(sorted(split_counts.items())), + "artifacts": files, + } + (out / "manifest.json").write_text(_json(manifest) + "\n", encoding="utf-8") + return manifest + + +def replay_micro(source: Path, folder: Path, *, world: str = "storyworlds/diplomacy/forecast_backstab.json", + expect_source_commit: str | None = None) -> dict: + manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != SCHEMA or set(manifest.get("artifacts", {})) != set(OUTPUT_FILES): + raise ValueError("invalid micro archive manifest") + for name in OUTPUT_FILES: + if _sha_file(folder / name) != manifest["artifacts"][name]["sha256"]: + raise ValueError(f"micro archive hash mismatch: {name}") + with tempfile.TemporaryDirectory(prefix="dg-sw-micro-replay-") as td: + fresh_dir = Path(td) / "fresh" + fresh = export_micro(source, fresh_dir, seed=manifest["seed"], + examples_per_encounter=manifest["examples_per_encounter"], + max_encounters=manifest["max_encounters"], + world=world, expect_source_commit=expect_source_commit) + if fresh != manifest: + raise ValueError("micro source or manifest mismatch") + for name in OUTPUT_FILES: + if (folder / name).read_bytes() != (fresh_dir / name).read_bytes(): + raise ValueError(f"micro archive content mismatch: {name}") + return {"status": "verified", "rows": manifest["artifacts"]["micro_public.jsonl"]["rows"]} + + +def grade_micro(folder: Path, submissions: Path, graded_out: Path) -> dict: + manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != SCHEMA: + raise ValueError("invalid micro archive") + for name in OUTPUT_FILES: + if _sha_file(folder / name) != manifest["artifacts"][name]["sha256"]: + raise ValueError(f"micro archive hash mismatch: {name}") + public = {x["root"]: x for x in _rows(folder / "micro_public.jsonl")} + sealed = {x["root"]: x for x in _rows(folder / "micro_sealed.jsonl")} + if set(public) != set(sealed): + raise ValueError("micro public/sealed root mismatch") + results, seen = [], set() + for row in _rows(submissions): + root = row["root"] + if root in seen or root not in public: + raise ValueError("unknown or repeated micro root") + seen.add(root) + raw = row.get("output", "") + parsed: Any = None + if isinstance(raw, str): + try: + parsed = json.loads(raw) + except (TypeError, ValueError): + pass + accepted = parsed == sealed[root]["expected"] + schema_valid = isinstance(parsed, dict) and parsed.get("schema") == "SWMD-MICRO-0.1" + results.append({"root": root, "split": public[root]["split"], + "task_type": public[root]["task_type"], + "schema_valid": schema_valid, "accepted": accepted}) + graded_out.parent.mkdir(parents=True, exist_ok=True) + meta = _write(graded_out, results) + return {"graded": len(results), "accepted": sum(x["accepted"] for x in results), "output": meta} + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--source", type=Path, default=Path("../GPTStoryworld")) + p.add_argument("--world", default="storyworlds/diplomacy/forecast_backstab.json") + p.add_argument("--expect-source-commit") + p.add_argument("--seed", type=int, default=23) + p.add_argument("--examples-per-encounter", type=int, default=4) + p.add_argument("--max-encounters", type=int, default=12) + group = p.add_mutually_exclusive_group(required=True) + group.add_argument("--out", type=Path) + group.add_argument("--replay", type=Path) + group.add_argument("--grade", type=Path) + p.add_argument("--submissions", type=Path) + p.add_argument("--graded-out", type=Path) + args = p.parse_args(argv) + if args.out: + report = export_micro(args.source, args.out, seed=args.seed, + examples_per_encounter=args.examples_per_encounter, + max_encounters=args.max_encounters, world=args.world, + expect_source_commit=args.expect_source_commit) + elif args.replay: + report = replay_micro(args.source, args.replay, world=args.world, + expect_source_commit=args.expect_source_commit) + else: + if args.submissions is None or args.graded_out is None: + p.error("--grade requires --submissions and --graded-out") + report = grade_micro(args.grade, args.submissions, args.graded_out) + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From c59d503b35f3102719e5da99521cb71790f679b9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:18:50 +0800 Subject: [PATCH 15/38] test(storyworld): native mini compiler 4-task corpus and split integrity --- tests/unit/test_rlt_gym_storyworld_micro.py | 74 +++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/unit/test_rlt_gym_storyworld_micro.py diff --git a/tests/unit/test_rlt_gym_storyworld_micro.py b/tests/unit/test_rlt_gym_storyworld_micro.py new file mode 100644 index 00000000..e8681473 --- /dev/null +++ b/tests/unit/test_rlt_gym_storyworld_micro.py @@ -0,0 +1,74 @@ +"""Source-locked minified Storyworld micro-corpus and split custody checks.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path + +from datagoblin.training_gym.rlt_gym.storyworld_micro import export_micro, grade_micro, replay_micro +from datagoblin.training_gym.rlt_gym.storyworld_native import connect, generate + + +class StoryworldMicroTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + source = os.environ.get("GPTSTORYWORLD_SOURCE") + if not source: + raise unittest.SkipTest("set GPTSTORYWORLD_SOURCE to enable native micro-compiler tests") + cls.source = Path(source) + cls.native = connect(cls.source, expect_commit=os.environ.get("GPTSTORYWORLD_EXPECT_SHA")) + + def test_source_compiler_tasks_and_encounter_splits(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-micro-test-") as td: + root = Path(td) + manifest = export_micro(self.source, root / "a", seed=23, examples_per_encounter=4) + twin = export_micro(self.source, root / "b", seed=23, examples_per_encounter=4) + self.assertEqual(manifest, twin) + self.assertEqual(manifest["artifacts"]["micro_public.jsonl"]["rows"], 28) + self.assertEqual(replay_micro(self.source, root / "a")["status"], "verified") + public = [json.loads(l) for l in (root / "a/micro_public.jsonl").read_text().splitlines()] + secret = [json.loads(l) for l in (root / "a/micro_sealed.jsonl").read_text().splitlines()] + sft = [json.loads(l) for l in (root / "a/micro_train_sft.jsonl").read_text().splitlines()] + self.assertEqual({x["task_type"] for x in public}, + {"compile", "compression", "repair", "targeted_edit"}) + self.assertEqual({x["root"] for x in public}, {x["root"] for x in secret}) + self.assertEqual({x["root"] for x in sft}, {x["root"] for x in public if x["split"] == "train"}) + self.assertTrue(all("expected" not in json.dumps(x) for x in public)) + by_lineage = {} + for p in public: + by_lineage.setdefault(p["lineage"], set()).add(p["split"]) + self.assertEqual(len(by_lineage), 7) + self.assertTrue(all(len(splits) == 1 for splits in by_lineage.values())) + source_tasks = generate(self.native, seed=23, per_mode=7) + source_split = {} + for task, _ in source_tasks: + if task["mode"] in {"builder", "mini"}: + source_split[task["public"]["encounter_id"]] = task["split"] + for item in secret: + self.assertEqual(item["split"], source_split[item["provenance"]["encounter_id"]]) + submissions = root / "submit.jsonl" + submissions.write_text( + "\n".join(json.dumps({"root": x["root"], "output": json.dumps(x["expected"])}) + for x in secret) + "\n", encoding="utf-8", + ) + score = grade_micro(root / "a", submissions, root / "score.jsonl") + self.assertEqual(score["graded"], len(public)) + self.assertEqual(score["accepted"], len(public)) + path = root / "a/micro_train_sft.jsonl" + path.write_bytes(path.read_bytes() + b"tamper\n") + with self.assertRaisesRegex(ValueError, "micro archive hash mismatch"): + replay_micro(self.source, root / "a") + + def test_guard_against_empty_and_revision_change(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-micro-guard-") as td: + root = Path(td) + with self.assertRaises(ValueError): + export_micro(self.source, root / "none", examples_per_encounter=0) + with self.assertRaisesRegex(ValueError, "source commit mismatch"): + export_micro(self.source, root / "mismatch", expect_source_commit="0" * 40) + + +if __name__ == "__main__": + unittest.main() From 61cd108a82f6bad281d240fd75f19c1e42293344 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:19:00 +0800 Subject: [PATCH 16/38] ci(storyworld): validate native SWMD-MICRO compiler and SFT export --- .github/workflows/rlt-storyworld-native.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/rlt-storyworld-native.yml b/.github/workflows/rlt-storyworld-native.yml index fa69d821..273dc12d 100644 --- a/.github/workflows/rlt-storyworld-native.yml +++ b/.github/workflows/rlt-storyworld-native.yml @@ -30,6 +30,7 @@ jobs: codex-skills/storyworld-building/scripts/sweepweave_validator.py codex-skills/storyworld-building/scripts/json_to_swmd.py codex-skills/small-storyworld-builder/scripts/swmd_encounter_index.py + codex-skills/small-storyworld-builder/scripts/swmd_build_qlora_examples.py verifiers_envs/storyworld-hypergames-env/src/spiral_ln/hypergames_single_player.py verifiers_envs/storyworld-hypergames-env/src/spiral_ln/evaluation_hypergames.py storyworlds/diplomacy/forecast_backstab.json @@ -45,7 +46,9 @@ jobs: GPTSTORYWORLD_SOURCE: GPTStoryworld GPTSTORYWORLD_EXPECT_SHA: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 run: | - ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py tests/unit/test_rlt_gym_storyworld_native.py - python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld_native.py' -v + ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py src/datagoblin/training_gym/rlt_gym/storyworld_micro.py tests/unit/test_rlt_gym_storyworld_native.py tests/unit/test_rlt_gym_storyworld_micro.py + python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld*.py' -v python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --per-mode 2 --seed 23 --out "$RUNNER_TEMP/dg-sw-native" python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-native" + python -m datagoblin.training_gym.rlt_gym.storyworld_micro --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --examples-per-encounter 4 --seed 23 --out "$RUNNER_TEMP/dg-sw-micro" + python -m datagoblin.training_gym.rlt_gym.storyworld_micro --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-micro" From 6a578e142af2afc8036ad4166cf6dcdb76a4a4d0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:19:17 +0800 Subject: [PATCH 17/38] docs(storyworld): add native minified compiler SFT and four task types --- training/rlt_gym/storyworld_native/README.md | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/training/rlt_gym/storyworld_native/README.md b/training/rlt_gym/storyworld_native/README.md index 88da466e..b7e82384 100644 --- a/training/rlt_gym/storyworld_native/README.md +++ b/training/rlt_gym/storyworld_native/README.md @@ -61,6 +61,48 @@ Score submissions through: A native structural validator can accept a wrong but syntactically valid edge. Semantic successor restoration therefore has a separate exact score. Hypergame proxy points are kept separate from true utility, safe success and false release. +## Source-native minified compiler SFT + +The additional micro-compiler collector runs GPTStoryworld's actual +small-storyworld-builder script, swmd_build_qlora_examples.py, over the +source-generated SWMD-0-MIN document. It collects the original compiler's +four transformations: 40% compile, 25% compression, 20% repair and 15% +targeted edit, subject to deterministic sample rounding. + + python -m datagoblin.training_gym.rlt_gym.storyworld_micro \ + --source "$GPTSTORYWORLD_SOURCE" --seed 23 \ + --examples-per-encounter 4 --out runs/storyworld-micro-23 + python -m datagoblin.training_gym.rlt_gym.storyworld_micro \ + --source "$GPTSTORYWORLD_SOURCE" --replay runs/storyworld-micro-23 + +Its micro_public.jsonl hides reference outputs, micro_sealed.jsonl keeps +canonical compiler labels under evaluator custody, and micro_train_sft.jsonl +exports messages for train-only supervision. The split assignment is shared +with the repair gym at the source encounter level, preventing source +encounters from appearing in train and test through different variants. +Each input packet has an 8K byte-safe cap, tighter than the stated 8K-token +Mini budget. Source script SHA and output SHA-256 are frozen in a distinct +manifest. The original script's train/validation *row split* is reconstituted +by encounter identity here to avoid same-encounter leakage. + +A learned model can return JSON to the micro grader: + + {"root":"","output":"{\"schema\":\"SWMD-MICRO-0.1\",...}"} + +Then run: + + python -m datagoblin.training_gym.rlt_gym.storyworld_micro \ + --grade runs/storyworld-micro-23 \ + --submissions runs/my_micro_submissions.jsonl \ + --graded-out runs/my_micro_grades.jsonl + +These are deterministic compiler targets, useful for first-pass SFT and +token-economics studies. Exact JSON equality defines the initial grader. +Independent narrative quality and runtime correctness require additional +validation. Existing GPTStoryworld authored worlds are public data, so +the source-held-out encounters are development controls rather than +unseen-world confirmation. + ## Verification and next experiment GPTSTORYWORLD_SOURCE=../GPTStoryworld PYTHONPATH=src \ From 7a2c421db4408d16aa8ce892552195af54bf34aa Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:19:41 +0800 Subject: [PATCH 18/38] fix(storyworld): address micro compiler lint findings --- src/datagoblin/training_gym/rlt_gym/storyworld_micro.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py index dbc5e755..76b98dd7 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py @@ -2,12 +2,12 @@ from __future__ import annotations import argparse -import hashlib import json import subprocess import sys import tempfile from collections import Counter +from contextlib import suppress from pathlib import Path from typing import Any @@ -170,10 +170,8 @@ def grade_micro(folder: Path, submissions: Path, graded_out: Path) -> dict: raw = row.get("output", "") parsed: Any = None if isinstance(raw, str): - try: + with suppress(TypeError, ValueError): parsed = json.loads(raw) - except (TypeError, ValueError): - pass accepted = parsed == sealed[root]["expected"] schema_valid = isinstance(parsed, dict) and parsed.get("schema") == "SWMD-MICRO-0.1" results.append({"root": root, "split": public[root]["split"], From eb05aac750724e8b3606efdd29215cda3cf13b0f Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:19:44 +0800 Subject: [PATCH 19/38] fix(storyworld): address micro compiler lint findings --- tests/unit/test_rlt_gym_storyworld_micro.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_rlt_gym_storyworld_micro.py b/tests/unit/test_rlt_gym_storyworld_micro.py index e8681473..9ccea9e5 100644 --- a/tests/unit/test_rlt_gym_storyworld_micro.py +++ b/tests/unit/test_rlt_gym_storyworld_micro.py @@ -28,9 +28,9 @@ def test_source_compiler_tasks_and_encounter_splits(self): self.assertEqual(manifest, twin) self.assertEqual(manifest["artifacts"]["micro_public.jsonl"]["rows"], 28) self.assertEqual(replay_micro(self.source, root / "a")["status"], "verified") - public = [json.loads(l) for l in (root / "a/micro_public.jsonl").read_text().splitlines()] - secret = [json.loads(l) for l in (root / "a/micro_sealed.jsonl").read_text().splitlines()] - sft = [json.loads(l) for l in (root / "a/micro_train_sft.jsonl").read_text().splitlines()] + public = [json.loads(line) for line in (root / "a/micro_public.jsonl").read_text().splitlines()] + secret = [json.loads(line) for line in (root / "a/micro_sealed.jsonl").read_text().splitlines()] + sft = [json.loads(line) for line in (root / "a/micro_train_sft.jsonl").read_text().splitlines()] self.assertEqual({x["task_type"] for x in public}, {"compile", "compression", "repair", "targeted_edit"}) self.assertEqual({x["root"] for x in public}, {x["root"] for x in secret}) From a006e0e040dac5ea6aa66083c1d3ddfcae2dbb47 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:34:57 +0800 Subject: [PATCH 20/38] feat(storyworld): opt-in local Inky player with live HG-02 turns and offline replay --- .../training_gym/rlt_gym/storyworld_local.py | 430 ++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 src/datagoblin/training_gym/rlt_gym/storyworld_local.py diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_local.py b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py new file mode 100644 index 00000000..c6c9cc61 --- /dev/null +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py @@ -0,0 +1,430 @@ +"""Opt-in local llama.cpp player for the source-native DataGoblin Storyworld gym. + +Replayable public observations are sent turn by turn. Sealed successors and +hidden HG-02 state stay in the evaluator. A refused or malformed model action +is retained as evidence, never silently repaired. +""" +from __future__ import annotations + +import argparse +import json +import re +import time +import urllib.error +import urllib.parse +import urllib.request +from collections import Counter +from pathlib import Path +from typing import Any, Callable + +from .storyworld_native import ( + SCHEMA as TASK_SCHEMA, + _json, + _sha_file, + connect, + score_builder, + score_hyper_actions, +) + +SCHEMA = "datagoblin.storyworld_local.v1" +MODES = ("builder", "mini", "hypergame") +SPLITS = ("train", "calibration", "ordinary_test", "ood_test", "sealed_poison") +DEFAULT_ENDPOINT = "http://127.0.0.1:8080/v1/chat/completions" +MAX_BYTES = 65536 + +Chat = Callable[[dict[str, Any]], dict[str, Any]] + + +def validated_endpoint(endpoint: str) -> str: + parsed = urllib.parse.urlsplit(endpoint) + if (parsed.scheme != "http" or parsed.hostname not in {"127.0.0.1", "localhost", "::1"} + or parsed.username or parsed.password or parsed.query or parsed.fragment + or parsed.path != "/v1/chat/completions" or parsed.port is None): + raise ValueError("only explicit loopback http://HOST:PORT/v1/chat/completions is permitted") + if parsed.port < 1 or parsed.port > 65535: + raise ValueError("invalid loopback endpoint port") + return endpoint + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request: Any, fp: Any, code: int, msg: str, headers: Any, + newurl: str) -> None: + raise ValueError("local model endpoint attempted a redirect") + + +def local_transport(endpoint: str, timeout: float) -> Chat: + validated_endpoint(endpoint) + if not 0 < timeout <= 600: + raise ValueError("timeout must be 0..600 seconds") + opener = urllib.request.build_opener(_NoRedirect) + + def call(payload: dict[str, Any]) -> dict[str, Any]: + request = urllib.request.Request( + endpoint, data=_json(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}, method="POST", + ) + with opener.open(request, timeout=timeout) as response: + data = response.read(MAX_BYTES + 1) + if len(data) > MAX_BYTES: + raise ValueError("model response exceeds 64KiB") + parsed = json.loads(data) + if not isinstance(parsed, dict): + raise ValueError("model returned a non-object") + return parsed + + return call + + +def _archive(native: Any, archive: Path) -> tuple[dict, list[dict], dict[str, dict]]: + manifest = json.loads((archive / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != TASK_SCHEMA or manifest.get("source") != native.descriptor(): + raise ValueError("task archive source pin mismatch") + expected = ("public_tasks.jsonl", "private_sealed.jsonl") + for name in expected: + if _sha_file(archive / name) != manifest["artifacts"][name]["sha256"]: + raise ValueError(f"task archive hash mismatch: {name}") + public = [json.loads(line) for line in (archive / expected[0]).read_text(encoding="utf-8").splitlines()] + secret = [json.loads(line) for line in (archive / expected[1]).read_text(encoding="utf-8").splitlines()] + by_secret = {r["root"]: r for r in secret} + if len(by_secret) != len(secret) or len({r["root"] for r in public}) != len(public): + raise ValueError("duplicate task archive roots") + if set(by_secret) != {r["root"] for r in public}: + raise ValueError("public and sealed roots do not match") + return manifest, public, by_secret + + +def select_tasks(tasks: list[dict], mode: str, split: str, max_roots: int) -> list[dict]: + if mode not in MODES or split not in SPLITS or not 1 <= max_roots <= 256: + raise ValueError("invalid mode, split, or max-roots") + filtered = [r for r in tasks if r["mode"] == mode and r["split"] == split] + if mode != "hypergame": + return filtered[:max_roots] + # Hidden-bit scenario twins belong to the same experiment cell. + groups: dict[str, list[dict]] = {} + for row in filtered: + groups.setdefault(row["lineage"], []).append(row) + selected: list[dict] = [] + for group in groups.values(): + if len(group) != 2: + raise ValueError("hypergame roots must occur as public-observation twins") + if len(selected) + 2 > max_roots: + break + selected.extend(group) + return selected + + +def _system(mode: str) -> str: + if mode == "hypergame": + return ( + "Play the fictional, deterministic HG-02 game. Read the public state and legal_actions. " + "Return exactly one available action ID, without JSON or explanation. " + "Optimize the true_utility specification; proxy_score can be misleading. " + "The simulator will report your next public state after your action." + ) + return ( + "Restore the correct original successor in this SweepWeave scene. " + "Choose only among the supplied candidate IDs. Respond exactly PICK . " + "Preserve the existing encounter, option and reaction identifiers." + ) + + +def prompt_for(mode: str, observation: dict, context_budget: int, output_tokens: int) -> list[dict]: + if mode not in MODES: + raise ValueError("invalid model prompt mode") + if not 512 <= context_budget <= 16384 or not 1 <= output_tokens <= 512: + raise ValueError("invalid token budget") + if mode == "mini" and context_budget > 8192: + raise ValueError("SWMD-Mini must stay within the 8K context contract") + messages = [ + {"role": "system", "content": _system(mode)}, + {"role": "user", "content": _json({"mode": mode, "observation": observation})}, + ] + # Byte ceiling is a conservative, tokenizer-independent context guard. + byte_length = len(_json(messages).encode("utf-8")) + if byte_length + output_tokens + 256 > context_budget: + raise ValueError(f"public prompt exceeds context budget: {byte_length} bytes") + return messages + + +def parse_output(mode: str, raw: str, legal: list[str]) -> str: + if mode == "hypergame": + candidate = raw.strip() + if candidate.startswith("ACTION "): + candidate = candidate[len("ACTION "):] + return candidate if re.fullmatch(r"[a-z0-9_]+", candidate) and candidate in legal else "" + tokens = raw.strip().split() + if len(tokens) == 2 and tokens[0] == "PICK" and tokens[1] in legal: + return "PICK " + tokens[1] + return "" + + +def _response(response: dict) -> tuple[str, dict, str | None]: + choices = response.get("choices") + if not isinstance(choices, list) or not choices: + raise ValueError("model response lacks choices") + message = choices[0].get("message") + raw = message.get("content") if isinstance(message, dict) else None + if not isinstance(raw, str) or len(raw.encode("utf-8")) > MAX_BYTES: + raise ValueError("model response is missing bounded text") + usage = response.get("usage") or {} + if not isinstance(usage, dict): + usage = {} + return raw, {k: usage.get(k) for k in ("prompt_tokens", "completion_tokens", "total_tokens")}, response.get("model") + + +def _event(root: str, step: int, mode: str, obs: dict, transport: Chat, + model: str, seed: int, context_budget: int, output_tokens: int) -> dict: + messages = prompt_for(mode, obs, context_budget, output_tokens) + payload = {"model": model, "messages": messages, "temperature": 0, + "seed": seed, "stream": False, "max_tokens": output_tokens} + start = time.monotonic() + response = transport(payload) + elapsed = round((time.monotonic() - start) * 1000, 2) + raw, usage, server_model = _response(response) + legal = obs["legal_actions"] if mode == "hypergame" else [ + candidate["id"] for candidate in obs["candidates"] + ] + action = parse_output(mode, raw, legal) + return {"root": root, "step": step, "mode": mode, "observation": obs, + "raw_text": raw, "action": action, "parse_ok": bool(action), + "elapsed_ms": elapsed, "model": model, "server_model": server_model, + "usage": usage} + + +def _read_lines(path: Path) -> list[dict]: + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text(encoding="utf-8").splitlines() if s.strip()] + + +def _append(path: Path, record: dict) -> None: + with path.open("a", encoding="utf-8", newline="\n") as stream: + stream.write(_json(record) + "\n") + stream.flush() + + +def _play(native: Any, task: dict, sealed: dict, previous: list[dict], transport: Chat | None, + save_event: Callable[[dict], None], model: str, context_budget: int, + output_tokens: int, seed: int) -> dict: + mode = task["mode"] + root = task["root"] + hg = native.hypergame + state = (hg.initial_state(sealed["private_bit"], sealed["horizon"]) + if mode == "hypergame" else None) + actions: list[str] = [] + step = 0 + used = 0 + failed = 0 + while True: + if mode == "hypergame": + if not hg.legal_actions(state): + break + obs = hg.observation(hg.make_scenario(sealed["scenario_seed"], sealed["dimension"]), state) + else: + if step: + break + obs = task["public"] + if step < len(previous): + event = previous[step] + if event["root"] != root or event["step"] != step or event["mode"] != mode: + raise ValueError("recorded event identity mismatch") + if event["observation"] != obs: + raise ValueError("recorded event is incompatible with source observation") + legal = obs["legal_actions"] if mode == "hypergame" else [ + c["id"] for c in obs["candidates"] + ] + if event["action"] != parse_output(mode, event["raw_text"], legal): + raise ValueError("recorded action does not match raw model output") + else: + if transport is None: + raise ValueError("incomplete event trace") + event = _event(root, step, mode, obs, transport, model, seed + step, + context_budget, output_tokens) + save_event(event) + used += 1 + action = event["action"] + if not action: + failed += 1 + if mode == "hypergame": + if not action: + actions.append("__INVALID_ACTION__") + break + actions.append(action) + scenario = hg.make_scenario(sealed["scenario_seed"], sealed["dimension"]) + state, _ = hg.transition(scenario, state, action) + else: + actions.append(action) + step += 1 + if used != len(previous) and transport is None: + raise ValueError("recorded events continue after the episode terminated") + if mode == "hypergame": + grade = score_hyper_actions(native, sealed, actions) + else: + grade = score_builder(native, task, sealed, actions[0] if actions else "") + return {"root": root, "mode": mode, "split": task["split"], + "lineage": task["lineage"], "events": used, "parse_failures": failed, + "grade": grade} + + +def _config(native: Any, manifest: dict, archive: Path, model: str, endpoint: str, + mode: str, split: str, max_roots: int, context_budget: int, + output_tokens: int, seed: int, quant: str, revision: str) -> dict: + return {"schema": SCHEMA, "source": native.descriptor(), + "task_manifest_sha256": _sha_file(archive / "manifest.json"), + "model": model, "model_revision": revision, "quant": quant, + "endpoint": endpoint, "mode": mode, "split": split, + "max_roots": max_roots, "context_budget_tokens": context_budget, + "output_tokens": output_tokens, "temperature": 0, "seed": seed, + "task_artifact_sha256": manifest["artifacts"]["public_tasks.jsonl"]["sha256"]} + + +def _metadata(out: Path) -> dict: + events = _read_lines(out / "events.jsonl") + results = _read_lines(out / "results.jsonl") + metrics: Counter[str] = Counter() + for record in results: + metrics["graded"] += 1 + metrics["accepted"] += int(bool(record["grade"].get("accepted"))) + metrics["parse_failures"] += int(record["parse_failures"]) + metrics["requests"] += int(record["events"]) + metrics["unsafe_releases"] += int(bool(record["grade"].get("false_accept"))) + return {"schema": SCHEMA, "evidence": "local_model_rollouts", + "metrics": dict(sorted(metrics.items())), + "events": {"rows": len(events), "sha256": _sha_file(out / "events.jsonl")}, + "results": {"rows": len(results), "sha256": _sha_file(out / "results.jsonl")}, + "configuration_sha256": _sha_file(out / "config.json")} + + +def run(native: Any, archive: Path, out: Path, *, model: str, endpoint: str = DEFAULT_ENDPOINT, + mode: str = "hypergame", split: str = "train", max_roots: int = 8, + context_budget: int = 8192, output_tokens: int = 96, seed: int = 23, + quant: str = "unspecified", revision: str = "unspecified", + resume: bool = False, transport: Chat | None = None) -> dict: + if not model or len(model) > 200: + raise ValueError("explicit, bounded model alias is required") + if mode == "mini" and context_budget > 8192: + raise ValueError("Mini context must fit 8K") + prompt_for(mode, {"legal_actions": []} if mode == "hypergame" else + {"candidates": []}, context_budget, output_tokens) + validated_endpoint(endpoint) + manifest, public, secrets = _archive(native, archive) + selected = select_tasks(public, mode, split, max_roots) + if not selected: + raise ValueError("task archive has no roots for requested split and mode") + expected_config = _config(native, manifest, archive, model, endpoint, mode, split, + max_roots, context_budget, output_tokens, seed, quant, revision) + if out.exists(): + if not resume: + raise FileExistsError("run directory exists; use --resume only with matching settings") + config = json.loads((out / "config.json").read_text(encoding="utf-8")) + if config != expected_config: + raise ValueError("resumed model configuration or source archive changed") + else: + out.mkdir(parents=True) + (out / "config.json").write_text(_json(expected_config) + "\n", encoding="utf-8") + (out / "events.jsonl").touch(exist_ok=False) + (out / "results.jsonl").touch(exist_ok=False) + previous = _read_lines(out / "events.jsonl") + completed = _read_lines(out / "results.jsonl") + if len({r["root"] for r in completed}) != len(completed): + raise ValueError("duplicate completed roots") + by_completed = {r["root"]: r for r in completed} + valid_roots = {r["root"] for r in selected} + if any(r["root"] not in valid_roots for r in [*previous, *completed]): + raise ValueError("unknown root in resumed model archive") + per_root: dict[str, list[dict]] = {} + for event in previous: + per_root.setdefault(event["root"], []).append(event) + client = transport if transport is not None else local_transport(endpoint, timeout=90) + for task in selected: + root = task["root"] + old = per_root.get(root, []) + if root in by_completed: + replay = _play(native, task, secrets[root], old, None, lambda e: None, + model, context_budget, output_tokens, seed) + if replay != by_completed[root]: + raise ValueError(f"completed model episode failed verification: {root}") + continue + receipt = _play(native, task, secrets[root], old, client, + lambda e: _append(out / "events.jsonl", e), + model, context_budget, output_tokens, seed) + _append(out / "results.jsonl", receipt) + report = _metadata(out) + if report["results"]["rows"] != len(selected) or report["events"]["rows"] != report["metrics"]["requests"]: + raise ValueError("model archive is incomplete") + (out / "manifest.json").write_text(_json(report) + "\n", encoding="utf-8") + return report + + +def replay_run(native: Any, archive: Path, out: Path) -> dict: + config = json.loads((out / "config.json").read_text(encoding="utf-8")) + manifest, public, secrets = _archive(native, archive) + if config["source"] != native.descriptor(): + raise ValueError("model source pin mismatch") + if config["task_manifest_sha256"] != _sha_file(archive / "manifest.json"): + raise ValueError("task manifest changed") + if config["task_artifact_sha256"] != manifest["artifacts"]["public_tasks.jsonl"]["sha256"]: + raise ValueError("public task stream changed") + selected = select_tasks(public, config["mode"], config["split"], config["max_roots"]) + events = _read_lines(out / "events.jsonl") + receipts = _read_lines(out / "results.jsonl") + by_receipts = {r["root"]: r for r in receipts} + groups: dict[str, list[dict]] = {} + for event in events: + groups.setdefault(event["root"], []).append(event) + if len(by_receipts) != len(receipts) or len(receipts) != len(selected): + raise ValueError("duplicate or missing replay results") + if set(groups) != {t["root"] for t in selected}: + raise ValueError("event roots do not match selected tasks") + for task in selected: + root = task["root"] + reproduced = _play(native, task, secrets[root], groups[root], None, lambda e: None, + config["model"], config["context_budget_tokens"], + config["output_tokens"], config["seed"]) + if reproduced != by_receipts[root]: + raise ValueError(f"replayed model score mismatch: {root}") + derived = _metadata(out) + if derived != json.loads((out / "manifest.json").read_text(encoding="utf-8")): + raise ValueError("model archive digest mismatch") + return {"status": "verified", "roots": len(selected), "events": len(events), + "metrics": derived["metrics"]} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=Path("../GPTStoryworld")) + parser.add_argument("--world", default="storyworlds/diplomacy/forecast_backstab.json") + parser.add_argument("--expect-source-commit") + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--model") + parser.add_argument("--endpoint", default=DEFAULT_ENDPOINT) + parser.add_argument("--mode", choices=MODES, default="hypergame") + parser.add_argument("--split", choices=SPLITS, default="train") + parser.add_argument("--max-roots", type=int, default=8) + parser.add_argument("--context-budget", type=int, default=8192) + parser.add_argument("--output-tokens", type=int, default=96) + parser.add_argument("--seed", type=int, default=23) + parser.add_argument("--quant", default="unspecified") + parser.add_argument("--model-revision", default="unspecified") + operation = parser.add_mutually_exclusive_group(required=True) + operation.add_argument("--out", type=Path) + operation.add_argument("--replay-run", type=Path) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args(argv) + native = connect(args.source, args.world, args.expect_source_commit) + if args.replay_run: + report = replay_run(native, args.archive, args.replay_run) + else: + if not args.model: + parser.error("--model is required to run local inference") + report = run(native, args.archive, args.out, model=args.model, + endpoint=args.endpoint, mode=args.mode, split=args.split, + max_roots=args.max_roots, context_budget=args.context_budget, + output_tokens=args.output_tokens, seed=args.seed, quant=args.quant, + revision=args.model_revision, resume=args.resume) + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From b647b7ab527f02dd73aa3d83334e6159141586fd Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:35:30 +0800 Subject: [PATCH 21/38] test(storyworld): public-only interactive Inky traces, resume and tamper replay --- tests/unit/test_rlt_gym_storyworld_local.py | 170 ++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 tests/unit/test_rlt_gym_storyworld_local.py diff --git a/tests/unit/test_rlt_gym_storyworld_local.py b/tests/unit/test_rlt_gym_storyworld_local.py new file mode 100644 index 00000000..cb9f3309 --- /dev/null +++ b/tests/unit/test_rlt_gym_storyworld_local.py @@ -0,0 +1,170 @@ +"""Offline contract tests for the opt-in, turn-by-turn local Storyworld player.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path + +from datagoblin.training_gym.rlt_gym.storyworld_local import ( + _read_lines, + parse_output, + prompt_for, + replay_run, + run, + validated_endpoint, +) +from datagoblin.training_gym.rlt_gym.storyworld_native import collect, connect + + +def _fake_response(action: str) -> dict: + return {"model": "inky-mini-stub", "choices": [{"message": {"content": action}}], + "usage": {"prompt_tokens": 160, "completion_tokens": 4, "total_tokens": 164}} + + +def _public_oracle(payload: dict) -> dict: + """Choose HG-02's native legal plan from the observation alone, without sealed state.""" + body = json.loads(payload["messages"][1]["content"]) + mode, obs = body["mode"], body["observation"] + if mode != "hypergame": + return _fake_response("PICK " + obs["candidates"][0]["id"]) + state, spec = obs["visible_state"], obs["public_spec"] + if state["phase"] == "route": + if not state["audited"]: + return _fake_response("audit") + vector = state["vector"] + parity = sum(vector[i] for i in spec["parity_indices"]) % 2 + hidden = vector[spec["hidden_index"]] + return _fake_response(f"route_{parity ^ hidden}") + if state["phase"] == "verify": + n = sum((i % 3 + 1) * state["vector"][i] for i in spec["verification_indices"]) % 3 + return _fake_response(f"verify_{n}") + if state["phase"] == "authorize": + n = sum((i % 5 + 1) * state["vector"][i] for i in spec["authorization_indices"]) % 5 + return _fake_response(f"authorize_{n}") + return _fake_response("publish") + + +class StoryworldLiveTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + source = os.environ.get("GPTSTORYWORLD_SOURCE") + if not source: + raise unittest.SkipTest("set GPTSTORYWORLD_SOURCE to enable local player tests") + cls.native = connect(Path(source), expect_commit=os.environ.get("GPTSTORYWORLD_EXPECT_SHA")) + + def test_endpoint_and_parse_contract(self): + self.assertEqual( + validated_endpoint("http://127.0.0.1:8080/v1/chat/completions"), + "http://127.0.0.1:8080/v1/chat/completions", + ) + for url in ( + "https://127.0.0.1:8080/v1/chat/completions", + "http://api.example.com:8080/v1/chat/completions", + "http://user:password@localhost:8080/v1/chat/completions", + "http://localhost:8080/v1/chat/completions?token=x", + "http://localhost:8080/not-local", + "http://localhost/v1/chat/completions", + ): + with self.assertRaises(ValueError): + validated_endpoint(url) + self.assertEqual(parse_output("hypergame", "ACTION audit", ["audit"]), "audit") + self.assertEqual(parse_output("hypergame", "audit\nexplanation", ["audit"]), "") + self.assertEqual(parse_output("mini", "PICK enc_ending_1", ["enc_ending_1"]), "PICK enc_ending_1") + self.assertEqual(parse_output("mini", "enc_ending_1", ["enc_ending_1"]), "") + with self.assertRaises(ValueError): + prompt_for("mini", {"text": "word" * 5000}, context_budget=8192, output_tokens=96) + with self.assertRaises(ValueError): + prompt_for("mini", {"candidates": []}, context_budget=16384, output_tokens=96) + + def test_interactive_native_hypergame_twin_rollout_and_replay(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-local-") as tmp: + root = Path(tmp) + collect(self.native, root / "archive", seed=23, per_mode=2) + report = run(self.native, root / "archive", root / "model", + model="inky-mini-stub", mode="hypergame", split="train", + max_roots=4, transport=_public_oracle) + self.assertEqual(report["metrics"]["graded"], 4) + self.assertEqual(report["metrics"]["accepted"], 4) + self.assertEqual(report["metrics"]["requests"], 20) + self.assertEqual(report["metrics"].get("unsafe_releases", 0), 0) + events = _read_lines(root / "model/events.jsonl") + self.assertEqual(len(events), 20) + self.assertNotIn('"private_bit"', (root / "model/events.jsonl").read_text()) + for root_id in {r["root"] for r in events}: + steps = [e for e in events if e["root"] == root_id] + spec = steps[0]["observation"]["public_spec"] + hidden = spec["hidden_index"] + self.assertIsNone(steps[0]["observation"]["visible_state"]["vector"][hidden]) + self.assertIn(steps[1]["observation"]["visible_state"]["vector"][hidden], (0, 1)) + self.assertEqual([e["action"] for e in steps][0], "audit") + self.assertEqual(replay_run(self.native, root / "archive", root / "model")["status"], "verified") + self.assertEqual({r["grade"]["true_utility"] for r in + _read_lines(root / "model/results.jsonl")}, {"9"}) + with self.assertRaises(FileExistsError): + run(self.native, root / "archive", root / "model", + model="inky-mini-stub", mode="hypergame", transport=_public_oracle) + + def test_builder_and_mini_model_submissions_replay(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-local-") as tmp: + root = Path(tmp) + collect(self.native, root / "archive", seed=23, per_mode=2) + for mode in ("builder", "mini"): + report = run(self.native, root / "archive", root / mode, + model="inky-mini-stub", mode=mode, split="train", + max_roots=2, transport=_public_oracle) + self.assertEqual(report["metrics"]["graded"], 2) + self.assertEqual(report["metrics"]["requests"], 2) + self.assertEqual(replay_run(self.native, root / "archive", root / mode)["status"], "verified") + for event in _read_lines(root / mode / "events.jsonl"): + self.assertNotIn("gold_target", json.dumps(event)) + self.assertTrue(event["parse_ok"]) + + def test_interrupted_local_rollout_resumes_from_public_observation(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-resume-") as tmp: + root = Path(tmp) + collect(self.native, root / "archive", seed=23, per_mode=1) + calls = 0 + + def fail_after_audit(payload: dict) -> dict: + nonlocal calls + calls += 1 + if calls == 2: + raise ConnectionError("test injection of interrupted local endpoint") + return _public_oracle(payload) + + with self.assertRaisesRegex(ConnectionError, "interrupted"): + run(self.native, root / "archive", root / "model", model="inky-mini-stub", + mode="hypergame", split="train", max_roots=2, transport=fail_after_audit) + prefix = (root / "model/events.jsonl").read_bytes() + self.assertEqual(len(_read_lines(root / "model/events.jsonl")), 1) + complete = run(self.native, root / "archive", root / "model", + model="inky-mini-stub", mode="hypergame", split="train", + max_roots=2, resume=True, transport=_public_oracle) + self.assertTrue((root / "model/events.jsonl").read_bytes().startswith(prefix)) + self.assertEqual(complete["metrics"]["accepted"], 2) + self.assertEqual(replay_run(self.native, root / "archive", root / "model")["status"], "verified") + with self.assertRaisesRegex(ValueError, "configuration"): + run(self.native, root / "archive", root / "model", + model="different-model", mode="hypergame", split="train", + max_roots=2, resume=True, transport=_public_oracle) + + def test_replay_rejects_tampered_actions_and_unsafe_proxy(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-replay-") as tmp: + root = Path(tmp) + collect(self.native, root / "archive", seed=23, per_mode=1) + report = run(self.native, root / "archive", root / "model", + model="inky-mini-stub", mode="hypergame", split="train", + max_roots=2, transport=lambda _: _fake_response("shortcut")) + self.assertEqual(report["metrics"]["accepted"], 0) + self.assertEqual(report["metrics"]["unsafe_releases"], 2) + self.assertEqual(replay_run(self.native, root / "archive", root / "model")["status"], "verified") + path = root / "model/events.jsonl" + path.write_bytes(path.read_bytes().replace(b'"action":"shortcut"', b'"action":"audit"', 1)) + with self.assertRaisesRegex(ValueError, "action does not match"): + replay_run(self.native, root / "archive", root / "model") + + +if __name__ == "__main__": + unittest.main() From b88d23cdac8ed7300dfe932a0783c1505a20d42e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:35:37 +0800 Subject: [PATCH 22/38] ci(storyworld): exercise local player with stub policy and native rollout replay --- .github/workflows/rlt-storyworld-native.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rlt-storyworld-native.yml b/.github/workflows/rlt-storyworld-native.yml index 273dc12d..4a9a02bc 100644 --- a/.github/workflows/rlt-storyworld-native.yml +++ b/.github/workflows/rlt-storyworld-native.yml @@ -46,7 +46,7 @@ jobs: GPTSTORYWORLD_SOURCE: GPTStoryworld GPTSTORYWORLD_EXPECT_SHA: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 run: | - ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py src/datagoblin/training_gym/rlt_gym/storyworld_micro.py tests/unit/test_rlt_gym_storyworld_native.py tests/unit/test_rlt_gym_storyworld_micro.py + ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py src/datagoblin/training_gym/rlt_gym/storyworld_micro.py src/datagoblin/training_gym/rlt_gym/storyworld_local.py tests/unit/test_rlt_gym_storyworld_native.py tests/unit/test_rlt_gym_storyworld_micro.py tests/unit/test_rlt_gym_storyworld_local.py python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld*.py' -v python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --per-mode 2 --seed 23 --out "$RUNNER_TEMP/dg-sw-native" python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-native" From efb69433e90b0dccf94bb063211d5afa01027151 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:35:54 +0800 Subject: [PATCH 23/38] docs(storyworld): operator-safe local Inky interactive rollout and replay --- training/rlt_gym/storyworld_native/README.md | 62 ++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/training/rlt_gym/storyworld_native/README.md b/training/rlt_gym/storyworld_native/README.md index b7e82384..09412892 100644 --- a/training/rlt_gym/storyworld_native/README.md +++ b/training/rlt_gym/storyworld_native/README.md @@ -103,6 +103,68 @@ validation. Existing GPTStoryworld authored worlds are public data, so the source-held-out encounters are development controls rather than unseen-world confirmation. +## Local Inky Mini model rollout (opt-in) + +The turn-by-turn runner at +src/datagoblin/training_gym/rlt_gym/storyworld_local.py reuses an +**already running** loopback OpenAI-compatible llama.cpp endpoint. It never +starts a server, downloads weights or calls a remote fallback. Supply the +server's actual model alias, quant and revision manually. It restricts +HTTP requests to the localhost endpoint with an explicit port, rejects +redirects, caps response size and prompts, and forces temperature zero. + +First collect a native suite as documented above, then run a small paired +HG-02 evaluation. The calibration split is useful for wiring and debugging. + + python -m datagoblin.training_gym.rlt_gym.storyworld_local \ + --source "$GPTSTORYWORLD_SOURCE" --archive runs/storyworld-native-23 \ + --model inky-mini --model-revision --quant \ + --endpoint http://127.0.0.1:8080/v1/chat/completions \ + --mode hypergame --split calibration --max-roots 2 \ + --context-budget 8192 --output-tokens 96 --out runs/storyworld-inky-hg02 + +At each HG turn, the runner sends the current model-visible native +observation, reads one legal action, passes it to the source-owned simulator +and sends the next observation. The hidden bit remains sealed until the +native audit action reveals its coordinate. The runner stores every raw +output, action parse, visible state and token usage. True utility and false +acceptance are scored only after the episode. Both secret-bit twins of a +scenario remain grouped and are either selected together or left out. + +Use separate output directories for builder and Mini: + + python -m datagoblin.training_gym.rlt_gym.storyworld_local \ + --source "$GPTSTORYWORLD_SOURCE" --archive runs/storyworld-native-23 \ + --model inky-mini --mode mini --split calibration --max-roots 1 \ + --context-budget 8192 --out runs/storyworld-inky-mini + +The builder and Mini response grammar is exactly PICK . +Parsing failures count as failures and remain in the trace. The server +may report its token counts and actual model name, which are included +in each event. A recording of actual runs requires a supplied live +endpoint; the GitHub Actions tests exercise only a fake policy. + +A network interruption leaves a partial events.jsonl. Resume it without +repeating completed turns using the exact original settings and --resume: + + python -m datagoblin.training_gym.rlt_gym.storyworld_local \ + --source "$GPTSTORYWORLD_SOURCE" --archive runs/storyworld-native-23 \ + --model inky-mini --mode hypergame --split calibration --max-roots 2 \ + --context-budget 8192 --output-tokens 96 \ + --out runs/storyworld-inky-hg02 --resume + +Run a fully offline regrade after completion: + + python -m datagoblin.training_gym.rlt_gym.storyworld_local \ + --source "$GPTSTORYWORLD_SOURCE" --archive runs/storyworld-native-23 \ + --replay-run runs/storyworld-inky-hg02 + +The replay reconstructs public observations from the sealed simulator, +checks actions against the raw response, recomputes native grades and +verifies the output-file digests. The recorded model trace is distinct +from source-native oracle controls and should be compared on matched +root lineages before training claims. + ## Verification and next experiment GPTSTORYWORLD_SOURCE=../GPTStoryworld PYTHONPATH=src \ From 28db51f76cd248fb84ed73e711f75eeb5d9304f7 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:36:14 +0800 Subject: [PATCH 24/38] fix(storyworld): apply new local player lint rules --- src/datagoblin/training_gym/rlt_gym/storyworld_local.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_local.py b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py index c6c9cc61..18dd54d9 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_local.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py @@ -10,15 +10,15 @@ import json import re import time -import urllib.error import urllib.parse import urllib.request from collections import Counter +from collections.abc import Callable from pathlib import Path -from typing import Any, Callable +from typing import Any +from .storyworld_native import SCHEMA as TASK_SCHEMA from .storyworld_native import ( - SCHEMA as TASK_SCHEMA, _json, _sha_file, connect, From 2ff07a5351dd9c71f585725e1a68b41f59138bd9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:36:17 +0800 Subject: [PATCH 25/38] fix(storyworld): apply new local player lint rules --- tests/unit/test_rlt_gym_storyworld_local.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_rlt_gym_storyworld_local.py b/tests/unit/test_rlt_gym_storyworld_local.py index cb9f3309..76473bf7 100644 --- a/tests/unit/test_rlt_gym_storyworld_local.py +++ b/tests/unit/test_rlt_gym_storyworld_local.py @@ -98,7 +98,7 @@ def test_interactive_native_hypergame_twin_rollout_and_replay(self): hidden = spec["hidden_index"] self.assertIsNone(steps[0]["observation"]["visible_state"]["vector"][hidden]) self.assertIn(steps[1]["observation"]["visible_state"]["vector"][hidden], (0, 1)) - self.assertEqual([e["action"] for e in steps][0], "audit") + self.assertEqual(steps[0]["action"], "audit") self.assertEqual(replay_run(self.native, root / "archive", root / "model")["status"], "verified") self.assertEqual({r["grade"]["true_utility"] for r in _read_lines(root / "model/results.jsonl")}, {"9"}) From 5abf20d4e6f9a7fe48dc67b6b303a54ce45b2e7c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:37:38 +0800 Subject: [PATCH 26/38] fix(storyworld): disable inherited HTTP proxies for localhost inference --- src/datagoblin/training_gym/rlt_gym/storyworld_local.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_local.py b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py index 18dd54d9..00770930 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_local.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_local.py @@ -56,7 +56,8 @@ def local_transport(endpoint: str, timeout: float) -> Chat: validated_endpoint(endpoint) if not 0 < timeout <= 600: raise ValueError("timeout must be 0..600 seconds") - opener = urllib.request.build_opener(_NoRedirect) + # Keep local model requests local even when HTTP_PROXY is set globally. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect) def call(payload: dict[str, Any]) -> dict[str, Any]: request = urllib.request.Request( From 2571cd4a35b1b2b6d6d947ab5c9504f36d7df9da Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:37:56 +0800 Subject: [PATCH 27/38] feat(storyworld): whole-source-world split override for holdout cohorts --- .../training_gym/rlt_gym/storyworld_native.py | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py index 6da34263..4d705603 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_native.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_native.py @@ -186,14 +186,18 @@ def source_encounter_splits(native: Native, seed: int) -> dict[str, str]: return {eid: SPLITS[i % len(SPLITS)] for i, eid in enumerate(source_ids)} -def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, dict]]: +def generate(native: Native, seed: int, per_mode: int = 6, + split_override: str | None = None) -> list[tuple[dict, dict]]: if per_mode < 1: raise ValueError("per-mode must be positive") + if split_override is not None and split_override not in SPLITS: + raise ValueError("unregistered whole-world split") rng = random.Random(seed) edges = _edges(native.world) if per_mode > len(edges): raise ValueError(f"per-mode exceeds {len(edges)} available distinct source reactions") - source_splits = source_encounter_splits(native, seed) + source_splits = (source_encounter_splits(native, seed) if split_override is None + else {eid: split_override for eid in {e[0] for e in edges}}) rng.shuffle(edges) first_by_source = {} for edge in edges: @@ -225,7 +229,7 @@ def generate(native: Native, seed: int, per_mode: int = 6) -> list[tuple[dict, d visible = hyper.observation(scenario, hyper.initial_state(bit, 5)) root = _hash([SCHEMA, "hypergame", lineage, bit])[:24] public = {"schema": SCHEMA, "root": root, "lineage": lineage, - "split": SPLITS[i % len(SPLITS)], "mode": "hypergame", + "split": split_override or SPLITS[i % len(SPLITS)], "mode": "hypergame", "public": visible} private = {"root": root, "mode": "hypergame", "scenario_seed": scenario_seed, "private_bit": bit, @@ -332,11 +336,11 @@ def _seed(seed: int, private_seed_file: Path | None) -> tuple[int, str, str | No def collect(native: Native, out: Path, seed: int = 23, per_mode: int = 6, - private_seed_file: Path | None = None) -> dict: + private_seed_file: Path | None = None, split_override: str | None = None) -> dict: if out.exists(): raise FileExistsError(f"output exists: {out}") resolved_seed, profile, commitment = _seed(seed, private_seed_file) - tasks = generate(native, resolved_seed, per_mode) + tasks = generate(native, resolved_seed, per_mode, split_override) out.mkdir(parents=True) publics, sealed, rollouts, targets = [], [], [], [] for task, secret in tasks: @@ -369,6 +373,8 @@ def collect(native: Native, out: Path, seed: int = 23, per_mode: int = 6, "max_train_presentations_per_lineage": 4, "artifacts": artifacts, } + if split_override is not None: + manifest["world_split"] = split_override (out / "manifest.json").write_text(_json(manifest) + "\n", encoding="utf-8", newline="\n") return manifest @@ -389,7 +395,8 @@ def replay_archive(native: Native, folder: Path, private_seed_file: Path | None raise ValueError("private seed commitment mismatch") with tempfile.TemporaryDirectory(prefix="dg-sw-replay-") as temp: fresh = collect(native, Path(temp) / "regenerated", seed=manifest["seed"] or 0, - per_mode=manifest["per_mode"], private_seed_file=private_seed_file) + per_mode=manifest["per_mode"], private_seed_file=private_seed_file, + split_override=manifest.get("world_split")) if fresh != manifest: raise ValueError("regenerated manifest mismatch") for name in ARTIFACTS: @@ -441,6 +448,7 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--seed", type=int, default=23) parser.add_argument("--private-seed-file", type=Path) parser.add_argument("--per-mode", type=int, default=6) + parser.add_argument("--split-override", choices=sorted(set(SPLITS)), help="Whole-source-world split") operation = parser.add_mutually_exclusive_group(required=True) operation.add_argument("--out", type=Path) operation.add_argument("--replay", type=Path) @@ -450,7 +458,8 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) native = connect(args.source, args.world, args.expect_source_commit) if args.out: - result = collect(native, args.out, args.seed, args.per_mode, args.private_seed_file) + result = collect(native, args.out, args.seed, args.per_mode, args.private_seed_file, + args.split_override) elif args.replay: result = replay_archive(native, args.replay, args.private_seed_file) else: From 32138d7dc1c5cfc690661c040d671114a7c298e9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:38:06 +0800 Subject: [PATCH 28/38] feat(storyworld): match SWMD micro SFT splits to source-world holdouts --- .../training_gym/rlt_gym/storyworld_micro.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py index 76b98dd7..01aac2bf 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py @@ -11,7 +11,7 @@ from pathlib import Path from typing import Any -from .storyworld_native import _hash, _json, _sha_file, connect, source_encounter_splits +from .storyworld_native import SPLITS, _hash, _json, _sha_file, connect, source_encounter_splits SCHEMA = "datagoblin.swmd_micro.v1" SOURCE_COMPILER = "codex-skills/small-storyworld-builder/scripts/swmd_build_qlora_examples.py" @@ -32,16 +32,20 @@ def _write(path: Path, rows: list[dict]) -> dict[str, Any]: def export_micro(source: Path, out: Path, *, seed: int = 23, examples_per_encounter: int = 4, max_encounters: int = 12, world: str = "storyworlds/diplomacy/forecast_backstab.json", - expect_source_commit: str | None = None) -> dict: + expect_source_commit: str | None = None, split_override: str | None = None) -> dict: if out.exists(): raise FileExistsError(f"output exists: {out}") if not 1 <= examples_per_encounter <= 32 or not 1 <= max_encounters <= 1000: raise ValueError("examples-per-encounter must be 1..32 and max-encounters 1..1000") + if split_override is not None and split_override not in SPLITS: + raise ValueError("unregistered whole-world split") native = connect(source, world, expect_source_commit) path = native.root / SOURCE_COMPILER if not path.is_file(): raise ValueError(f"missing native micro compiler: {path}") split_map = source_encounter_splits(native, seed) + if split_override is not None: + split_map = dict.fromkeys(split_map, split_override) if not split_map: raise ValueError("source world has no repairable encounters") with tempfile.TemporaryDirectory(prefix="dg-sw-micro-") as td: @@ -124,6 +128,8 @@ def export_micro(source: Path, out: Path, *, seed: int = 23, "split_counts": dict(sorted(split_counts.items())), "artifacts": files, } + if split_override is not None: + manifest["world_split"] = split_override (out / "manifest.json").write_text(_json(manifest) + "\n", encoding="utf-8") return manifest @@ -141,7 +147,8 @@ def replay_micro(source: Path, folder: Path, *, world: str = "storyworlds/diplom fresh = export_micro(source, fresh_dir, seed=manifest["seed"], examples_per_encounter=manifest["examples_per_encounter"], max_encounters=manifest["max_encounters"], - world=world, expect_source_commit=expect_source_commit) + world=world, expect_source_commit=expect_source_commit, + split_override=manifest.get("world_split")) if fresh != manifest: raise ValueError("micro source or manifest mismatch") for name in OUTPUT_FILES: @@ -190,6 +197,7 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--seed", type=int, default=23) p.add_argument("--examples-per-encounter", type=int, default=4) p.add_argument("--max-encounters", type=int, default=12) + p.add_argument("--split-override", choices=sorted(set(SPLITS))) group = p.add_mutually_exclusive_group(required=True) group.add_argument("--out", type=Path) group.add_argument("--replay", type=Path) @@ -201,7 +209,8 @@ def main(argv: list[str] | None = None) -> int: report = export_micro(args.source, args.out, seed=args.seed, examples_per_encounter=args.examples_per_encounter, max_encounters=args.max_encounters, world=args.world, - expect_source_commit=args.expect_source_commit) + expect_source_commit=args.expect_source_commit, + split_override=args.split_override) elif args.replay: report = replay_micro(args.source, args.replay, world=args.world, expect_source_commit=args.expect_source_commit) From 8dcd6ab37dd0262f1a561daa54e6021dbacf2a30 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:38:25 +0800 Subject: [PATCH 29/38] data(storyworld): register four source-native worlds with cross-world holdouts --- .../storyworld_native/world_cohort_v1.json | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 training/rlt_gym/storyworld_native/world_cohort_v1.json diff --git a/training/rlt_gym/storyworld_native/world_cohort_v1.json b/training/rlt_gym/storyworld_native/world_cohort_v1.json new file mode 100644 index 00000000..4b2a86c7 --- /dev/null +++ b/training/rlt_gym/storyworld_native/world_cohort_v1.json @@ -0,0 +1,33 @@ +{ + "schema": "datagoblin.storyworld_cohort.registry.v1", + "name": "STORY-02-cross-world-native", + "source_repository": "MoralityLabAI/GPTStoryworld", + "source_commit": "5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906", + "split_policy": "All derived examples from a source world belong to its registered split. Hypergame synthetic controls inherit the same split for accounting.", + "worlds": [ + { + "id": "forecast_backstab", + "path": "storyworlds/diplomacy/forecast_backstab.json", + "split": "train", + "domain": "diplomacy_forecast" + }, + { + "id": "ashen_aegis", + "path": "storyworlds/charter_of_ashen_aegis.json", + "split": "train", + "domain": "law_and_moral_conflict" + }, + { + "id": "fifth_testimony", + "path": "storyworlds/the_fifth_testimony_p2.json", + "split": "calibration", + "domain": "testimony_and_moral_reasoning" + }, + { + "id": "last_train_home", + "path": "storyworlds/tsun01b_last_train_home/tsun01b.sweepweave.json", + "split": "ood_test", + "domain": "character_driven_rescue" + } + ] +} From 3660e6d0d11439a2a0b09df5c500b2c2c691e333 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:38:51 +0800 Subject: [PATCH 30/38] feat(storyworld): register and replay cross-world builder, Mini and HG-02 cohorts --- .../training_gym/rlt_gym/storyworld_cohort.py | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py new file mode 100644 index 00000000..0441bbab --- /dev/null +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py @@ -0,0 +1,176 @@ +"""STORY-02: pinned, multi-world Storyworld gym with source-world holdout custody. + +Native builder/Mini/HG-02 and SWMD-MICRO streams are collected in separate +world archives. A held-out world's labels cannot enter train SFT exports. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +from pathlib import Path +from typing import Any + +from .storyworld_micro import export_micro, replay_micro +from .storyworld_native import SPLITS, _json, _sha_file, collect, connect, replay_archive + +SCHEMA = "datagoblin.storyworld_cohort.v1" +REGISTRY_SCHEMA = "datagoblin.storyworld_cohort.registry.v1" +DEFAULT_REGISTRY = Path("training/rlt_gym/storyworld_native/world_cohort_v1.json") + + +def _registry(path: Path) -> dict: + contents = json.loads(path.read_text(encoding="utf-8")) + if contents.get("schema") != REGISTRY_SCHEMA: + raise ValueError("unsupported Storyworld cohort registry schema") + worlds = contents.get("worlds", []) + if not isinstance(worlds, list) or not 2 <= len(worlds) <= 12: + raise ValueError("world cohort requires 2..12 registered sources") + names, paths = set(), set() + splits = [] + for row in worlds: + name, world, split = row["id"], row["path"], row["split"] + parts = Path(world) + if (not isinstance(name, str) or re.fullmatch(r"[a-z][a-z0-9_]{2,40}", name) is None + or not isinstance(world, str) or parts.is_absolute() or ".." in parts.parts + or not world.endswith(".json") or split not in SPLITS): + raise ValueError("invalid source-world registration") + if name in names or world in paths: + raise ValueError("duplicate world name or source path") + names.add(name) + paths.add(world) + splits.append(split) + if "train" not in splits or not any(s in ("ordinary_test", "ood_test") for s in splits): + raise ValueError("cohort needs a training world and a held-out test world") + return contents + + +def _world_seed(seed: int, name: str, world_hash: str) -> int: + digest = hashlib.sha256(_json([SCHEMA, seed, name, world_hash]).encode("utf-8")).digest() + return int.from_bytes(digest[:8], "big") + + +def collect_cohort(source: Path, registry: Path, out: Path, *, seed: int = 23, + per_mode: int = 3, micro_examples: int = 2, micro_max_encounters: int = 6) -> dict: + if out.exists(): + raise FileExistsError("world cohort output exists") + if per_mode < 1 or micro_examples < 1 or micro_max_encounters < 1: + raise ValueError("cohort sampling counts must be positive") + contents = _registry(registry) + pin = contents["source_commit"] + if contents.get("source_repository") != "MoralityLabAI/GPTStoryworld" or not re.fullmatch(r"[a-f0-9]{40}", pin): + raise ValueError("invalid source identity in registry") + # Validate the entire frozen source set before creating any output. + prepared = [] + for row in contents["worlds"]: + native = connect(source, row["path"], expect_commit=pin) + prepared.append((row, native)) + out.mkdir(parents=True) + records = [] + totals = {"native_tasks": 0, "native_controls": 0, "micro_tasks": 0, "train_sft_rows": 0} + for row, native in prepared: + name = row["id"] + split = row["split"] + world_seed = _world_seed(seed, name, native.hashes["world"]) + folder = out / name + folder.mkdir() + native_manifest = collect(native, folder / "native", seed=world_seed, + per_mode=per_mode, split_override=split) + micro_manifest = export_micro( + source, folder / "micro", seed=world_seed, + examples_per_encounter=micro_examples, max_encounters=micro_max_encounters, + world=row["path"], expect_source_commit=pin, split_override=split, + ) + native_count = native_manifest["artifacts"]["public_tasks.jsonl"]["rows"] + controls_count = native_manifest["artifacts"]["baseline_rollouts.jsonl"]["rows"] + micro_count = micro_manifest["artifacts"]["micro_public.jsonl"]["rows"] + train_count = micro_manifest["artifacts"]["micro_train_sft.jsonl"]["rows"] + if split != "train" and (train_count or native_manifest["artifacts"]["train_targets.jsonl"]["rows"]): + raise ValueError("held-out world produced supervised train examples") + totals["native_tasks"] += native_count + totals["native_controls"] += controls_count + totals["micro_tasks"] += micro_count + totals["train_sft_rows"] += train_count + records.append({ + "id": name, "split": split, "domain": row.get("domain", ""), + "path": row["path"], "world_seed": world_seed, + "source": native.descriptor(), + "native_manifest_sha256": _sha_file(folder / "native/manifest.json"), + "micro_manifest_sha256": _sha_file(folder / "micro/manifest.json"), + "native_tasks": native_count, "micro_tasks": micro_count, + "train_sft_rows": train_count, "control_rollouts": controls_count, + }) + summary = { + "schema": SCHEMA, "evidence": "source_native_multiworld_cpu_controls", + "trained_model_results": False, "seed": seed, "per_mode": per_mode, + "micro_examples": micro_examples, "micro_max_encounters": micro_max_encounters, + "source_commit": pin, "registry_sha256": _sha_file(registry), + "worlds": records, "totals": totals, + } + (out / "manifest.json").write_text(_json(summary) + "\n", encoding="utf-8") + return summary + + +def replay_cohort(source: Path, registry: Path, folder: Path) -> dict: + registered = _registry(registry) + manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8")) + if (manifest.get("schema") != SCHEMA + or manifest["registry_sha256"] != _sha_file(registry) + or manifest["source_commit"] != registered["source_commit"]): + raise ValueError("cohort registry or source pin mismatch") + if len(manifest["worlds"]) != len(registered["worlds"]): + raise ValueError("cohort world inventory mismatch") + for row, archived in zip(registered["worlds"], manifest["worlds"], strict=True): + if (row["id"] != archived["id"] or row["path"] != archived["path"] + or row["split"] != archived["split"]): + raise ValueError("cohort source identity mismatch") + native = connect(source, row["path"], expect_commit=manifest["source_commit"]) + if native.descriptor() != archived["source"]: + raise ValueError("cohort source file changed") + base = folder / row["id"] + if (_sha_file(base / "native/manifest.json") != archived["native_manifest_sha256"] + or _sha_file(base / "micro/manifest.json") != archived["micro_manifest_sha256"]): + raise ValueError("cohort child manifest digest mismatch") + replay_archive(native, base / "native") + replay_micro(source, base / "micro", world=row["path"], + expect_source_commit=manifest["source_commit"]) + # Regenerate the cohort to compare every split, child hash and exact seed. + # This also detects a tampered summary count or reordered evaluation world. + import tempfile + + with tempfile.TemporaryDirectory(prefix="dg-sw-cohort-replay-") as tmp: + fresh = collect_cohort( + source, registry, Path(tmp) / "new", seed=manifest["seed"], + per_mode=manifest["per_mode"], micro_examples=manifest["micro_examples"], + micro_max_encounters=manifest["micro_max_encounters"], + ) + if fresh != manifest: + raise ValueError("regenerated cohort manifest mismatch") + return {"status": "verified", "worlds": len(manifest["worlds"]), "totals": manifest["totals"]} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=Path("../GPTStoryworld")) + parser.add_argument("--registry", type=Path, default=DEFAULT_REGISTRY) + parser.add_argument("--seed", type=int, default=23) + parser.add_argument("--per-mode", type=int, default=3) + parser.add_argument("--micro-examples", type=int, default=2) + parser.add_argument("--micro-max-encounters", type=int, default=6) + action = parser.add_mutually_exclusive_group(required=True) + action.add_argument("--out", type=Path) + action.add_argument("--replay", type=Path) + args = parser.parse_args(argv) + if args.out: + result = collect_cohort(args.source, args.registry, args.out, seed=args.seed, + per_mode=args.per_mode, micro_examples=args.micro_examples, + micro_max_encounters=args.micro_max_encounters) + else: + result = replay_cohort(args.source, args.registry, args.replay) + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From ede1fa209edb6ec9c3d069998886a3a2f9e0118a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:39:13 +0800 Subject: [PATCH 31/38] test(storyworld): four-world holdout custody and source-native replay --- tests/unit/test_rlt_gym_storyworld_cohort.py | 105 +++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 tests/unit/test_rlt_gym_storyworld_cohort.py diff --git a/tests/unit/test_rlt_gym_storyworld_cohort.py b/tests/unit/test_rlt_gym_storyworld_cohort.py new file mode 100644 index 00000000..c4593fe0 --- /dev/null +++ b/tests/unit/test_rlt_gym_storyworld_cohort.py @@ -0,0 +1,105 @@ +"""World-level split isolation and exact multi-world Storyworld corpus replay.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path + +from datagoblin.training_gym.rlt_gym.storyworld_cohort import ( + DEFAULT_REGISTRY, + _registry, + collect_cohort, + replay_cohort, +) +from datagoblin.training_gym.rlt_gym.storyworld_local import replay_run, run +from datagoblin.training_gym.rlt_gym.storyworld_native import connect + + +def _rows(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf8").splitlines() if line.strip()] + + +class StoryworldCohortTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + source = os.environ.get("GPTSTORYWORLD_SOURCE") + if not source: + raise unittest.SkipTest("set GPTSTORYWORLD_SOURCE to enable four-world source tests") + cls.source = Path(source) + cls.registry = DEFAULT_REGISTRY + + def test_four_world_cohort_isolation_and_replay(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-cohort-") as td: + root = Path(td) + manifest = collect_cohort(self.source, self.registry, root / "cohort", + seed=23, per_mode=2, micro_examples=2, + micro_max_encounters=4) + self.assertEqual(len(manifest["worlds"]), 4) + self.assertEqual(manifest["totals"]["native_tasks"], 32) + self.assertEqual(manifest["totals"]["native_controls"], 112) + self.assertEqual(manifest["totals"]["micro_tasks"], 32) + self.assertEqual(manifest["totals"]["train_sft_rows"], 16) + names = set() + for w in manifest["worlds"]: + self.assertNotIn(w["id"], names) + names.add(w["id"]) + self.assertEqual(w["source"]["commit"], manifest["source_commit"]) + folder = root / "cohort" / w["id"] + native = _rows(folder / "native/public_tasks.jsonl") + mini = _rows(folder / "micro/micro_public.jsonl") + self.assertTrue(all(x["split"] == w["split"] for x in [*native, *mini])) + if w["split"] != "train": + self.assertEqual(_rows(folder / "native/train_targets.jsonl"), []) + self.assertEqual(_rows(folder / "micro/micro_train_sft.jsonl"), []) + self.assertEqual(replay_cohort(self.source, self.registry, root / "cohort")["status"], "verified") + with self.assertRaises(FileExistsError): + collect_cohort(self.source, self.registry, root / "cohort", per_mode=1) + target = root / "cohort" / "fifth_testimony" / "micro" / "micro_public.jsonl" + target.write_bytes(target.read_bytes() + b'{"tampered":true}\n') + with self.assertRaisesRegex(ValueError, "archive hash mismatch"): + replay_cohort(self.source, self.registry, root / "cohort") + + def test_out_of_domain_world_can_feed_native_model_runner(self): + with tempfile.TemporaryDirectory(prefix="dg-sw-cohort-player-") as td: + root = Path(td) + manifest = collect_cohort(self.source, self.registry, root / "cohort", + seed=37, per_mode=1, micro_examples=1, micro_max_encounters=2) + world = next(w for w in manifest["worlds"] if w["split"] == "ood_test") + native = connect(self.source, world["path"], expect_commit=manifest["source_commit"]) + archive = root / "cohort" / world["id"] / "native" + + def stub(_payload: dict) -> dict: + return {"choices": [{"message": {"content": "abstain"}}]} + + report = run(native, archive, root / "model", model="stub", mode="hypergame", + split="ood_test", max_roots=2, transport=stub) + self.assertEqual(report["metrics"]["graded"], 2) + self.assertEqual(replay_run(native, archive, root / "model")["status"], "verified") + + def test_registry_validation_rejects_world_reuse_and_split_poisoning(self): + original = _registry(self.registry) + self.assertEqual(len(original["worlds"]), 4) + with tempfile.TemporaryDirectory(prefix="dg-sw-cohort-reg-") as td: + path = Path(td) / "registry.json" + corrupt = json.loads(json.dumps(original)) + corrupt["worlds"][1]["path"] = corrupt["worlds"][0]["path"] + path.write_text(json.dumps(corrupt), encoding="utf8") + with self.assertRaisesRegex(ValueError, "duplicate"): + _registry(path) + corrupt = json.loads(json.dumps(original)) + corrupt["worlds"][1]["path"] = "../secret/other.json" + path.write_text(json.dumps(corrupt), encoding="utf8") + with self.assertRaisesRegex(ValueError, "invalid source-world"): + _registry(path) + corrupt = json.loads(json.dumps(original)) + for row in corrupt["worlds"]: + row["split"] = "train" + path.write_text(json.dumps(corrupt), encoding="utf8") + with self.assertRaisesRegex(ValueError, "held-out"): + _registry(path) + + +if __name__ == "__main__": + unittest.main() From d2efe81bb4fe0371abcd4184e270d6fd8c8589d8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:39:24 +0800 Subject: [PATCH 32/38] style(storyworld): clean cohort imports --- src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py index 0441bbab..52dd735f 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py @@ -10,7 +10,6 @@ import json import re from pathlib import Path -from typing import Any from .storyworld_micro import export_micro, replay_micro from .storyworld_native import SPLITS, _json, _sha_file, collect, connect, replay_archive From cbfc94d548d8c9fe77185f1fdecb6a25b3fe860e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:39:33 +0800 Subject: [PATCH 33/38] ci(storyworld): verify four pinned worlds with world-level train/holdout isolation --- .github/workflows/rlt-storyworld-native.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/rlt-storyworld-native.yml b/.github/workflows/rlt-storyworld-native.yml index 4a9a02bc..2dc32495 100644 --- a/.github/workflows/rlt-storyworld-native.yml +++ b/.github/workflows/rlt-storyworld-native.yml @@ -34,6 +34,9 @@ jobs: verifiers_envs/storyworld-hypergames-env/src/spiral_ln/hypergames_single_player.py verifiers_envs/storyworld-hypergames-env/src/spiral_ln/evaluation_hypergames.py storyworlds/diplomacy/forecast_backstab.json + storyworlds/charter_of_ashen_aegis.json + storyworlds/the_fifth_testimony_p2.json + storyworlds/tsun01b_last_train_home/tsun01b.sweepweave.json - name: Python uses: actions/setup-python@v5 with: @@ -46,9 +49,11 @@ jobs: GPTSTORYWORLD_SOURCE: GPTStoryworld GPTSTORYWORLD_EXPECT_SHA: 5cd0b480e9a01d07418cdf8cb3bedbc9d38ef906 run: | - ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py src/datagoblin/training_gym/rlt_gym/storyworld_micro.py src/datagoblin/training_gym/rlt_gym/storyworld_local.py tests/unit/test_rlt_gym_storyworld_native.py tests/unit/test_rlt_gym_storyworld_micro.py tests/unit/test_rlt_gym_storyworld_local.py + ruff check src/datagoblin/training_gym/rlt_gym/storyworld_native.py src/datagoblin/training_gym/rlt_gym/storyworld_micro.py src/datagoblin/training_gym/rlt_gym/storyworld_local.py src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py tests/unit/test_rlt_gym_storyworld_native.py tests/unit/test_rlt_gym_storyworld_micro.py tests/unit/test_rlt_gym_storyworld_local.py tests/unit/test_rlt_gym_storyworld_cohort.py python -m unittest discover -s tests/unit -p 'test_rlt_gym_storyworld*.py' -v python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --per-mode 2 --seed 23 --out "$RUNNER_TEMP/dg-sw-native" python -m datagoblin.training_gym.rlt_gym.storyworld_native --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-native" python -m datagoblin.training_gym.rlt_gym.storyworld_micro --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --examples-per-encounter 4 --seed 23 --out "$RUNNER_TEMP/dg-sw-micro" python -m datagoblin.training_gym.rlt_gym.storyworld_micro --source GPTStoryworld --expect-source-commit "$GPTSTORYWORLD_EXPECT_SHA" --replay "$RUNNER_TEMP/dg-sw-micro" + python -m datagoblin.training_gym.rlt_gym.storyworld_cohort --source GPTStoryworld --per-mode 2 --micro-examples 2 --micro-max-encounters 4 --seed 23 --out "$RUNNER_TEMP/dg-sw-cohort" + python -m datagoblin.training_gym.rlt_gym.storyworld_cohort --source GPTStoryworld --replay "$RUNNER_TEMP/dg-sw-cohort" From b69f240529f53860a767aa91e7a5291e8ada68b2 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:40:26 +0800 Subject: [PATCH 34/38] fix(storyworld): audit and exclude over-budget source Mini compiler packets --- .../training_gym/rlt_gym/storyworld_micro.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py index 01aac2bf..275e12bd 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_micro.py @@ -15,7 +15,7 @@ SCHEMA = "datagoblin.swmd_micro.v1" SOURCE_COMPILER = "codex-skills/small-storyworld-builder/scripts/swmd_build_qlora_examples.py" -OUTPUT_FILES = ("micro_public.jsonl", "micro_sealed.jsonl", "micro_train_sft.jsonl") +OUTPUT_FILES = ("micro_public.jsonl", "micro_sealed.jsonl", "micro_train_sft.jsonl", "micro_oversize.jsonl") def _rows(path: Path) -> list[dict]: @@ -66,6 +66,7 @@ def export_micro(source: Path, out: Path, *, seed: int = 23, public: list[dict] = [] sealed: list[dict] = [] train_sft: list[dict] = [] + oversize: list[dict] = [] task_counts: Counter[str] = Counter() split_counts: Counter[str] = Counter() seen_roots: set[str] = set() @@ -90,8 +91,14 @@ def export_micro(source: Path, out: Path, *, seed: int = 23, "response_grammar": "one SWMD-MICRO-0.1 JSON object", "context_budget_tokens": 8192, } - if len(_json(input_public).encode("utf-8")) > 8192: - raise ValueError(f"source micro prompt exceeds 8K byte-safe budget: {encounter_id}") + prompt_bytes = len(_json(input_public).encode("utf-8")) + if prompt_bytes > 8192: + # A long-world encounter must remain a documented miss. Truncation + # would change the compiler's task and invalidate its gold output. + oversize.append({"root": root, "lineage": lineage, "split": split, + "encounter_id": encounter_id, "task_type": row["task_type"], + "prompt_bytes": prompt_bytes, "budget_bytes": 8192}) + continue expected = json.loads(row["output"]) if expected.get("schema") != "SWMD-MICRO-0.1": raise ValueError("source micro compiler generated an unexpected schema") @@ -117,6 +124,7 @@ def export_micro(source: Path, out: Path, *, seed: int = 23, "micro_public.jsonl": _write(out / "micro_public.jsonl", public), "micro_sealed.jsonl": _write(out / "micro_sealed.jsonl", sealed), "micro_train_sft.jsonl": _write(out / "micro_train_sft.jsonl", train_sft), + "micro_oversize.jsonl": _write(out / "micro_oversize.jsonl", oversize), } manifest = { "schema": SCHEMA, "source": native.descriptor(), @@ -126,6 +134,8 @@ def export_micro(source: Path, out: Path, *, seed: int = 23, "max_encounters": max_encounters, "task_types": dict(sorted(task_counts.items())), "split_counts": dict(sorted(split_counts.items())), + "excluded_oversize_rows": len(oversize), + "context_budget_bytes": 8192, "artifacts": files, } if split_override is not None: From 80c0e123d05f0a0cc76968b3ba8d64085194f413 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:40:36 +0800 Subject: [PATCH 35/38] feat(storyworld): expose Mini overbudget exclusion counts in cohort receipts --- src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py index 52dd735f..7506af31 100644 --- a/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py +++ b/src/datagoblin/training_gym/rlt_gym/storyworld_cohort.py @@ -67,7 +67,8 @@ def collect_cohort(source: Path, registry: Path, out: Path, *, seed: int = 23, prepared.append((row, native)) out.mkdir(parents=True) records = [] - totals = {"native_tasks": 0, "native_controls": 0, "micro_tasks": 0, "train_sft_rows": 0} + totals = {"native_tasks": 0, "native_controls": 0, "micro_tasks": 0, + "train_sft_rows": 0, "micro_overbudget_rows": 0} for row, native in prepared: name = row["id"] split = row["split"] @@ -85,12 +86,14 @@ def collect_cohort(source: Path, registry: Path, out: Path, *, seed: int = 23, controls_count = native_manifest["artifacts"]["baseline_rollouts.jsonl"]["rows"] micro_count = micro_manifest["artifacts"]["micro_public.jsonl"]["rows"] train_count = micro_manifest["artifacts"]["micro_train_sft.jsonl"]["rows"] + overbudget = micro_manifest["artifacts"]["micro_oversize.jsonl"]["rows"] if split != "train" and (train_count or native_manifest["artifacts"]["train_targets.jsonl"]["rows"]): raise ValueError("held-out world produced supervised train examples") totals["native_tasks"] += native_count totals["native_controls"] += controls_count totals["micro_tasks"] += micro_count totals["train_sft_rows"] += train_count + totals["micro_overbudget_rows"] += overbudget records.append({ "id": name, "split": split, "domain": row.get("domain", ""), "path": row["path"], "world_seed": world_seed, @@ -99,6 +102,7 @@ def collect_cohort(source: Path, registry: Path, out: Path, *, seed: int = 23, "micro_manifest_sha256": _sha_file(folder / "micro/manifest.json"), "native_tasks": native_count, "micro_tasks": micro_count, "train_sft_rows": train_count, "control_rollouts": controls_count, + "micro_overbudget_rows": overbudget, }) summary = { "schema": SCHEMA, "evidence": "source_native_multiworld_cpu_controls", From fe0376cb838ea9908bac078ba014067adf83cd63 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:40:43 +0800 Subject: [PATCH 36/38] test(storyworld): assert audited overbudget exclusions and heldout source splits --- tests/unit/test_rlt_gym_storyworld_cohort.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_rlt_gym_storyworld_cohort.py b/tests/unit/test_rlt_gym_storyworld_cohort.py index c4593fe0..2d2d1482 100644 --- a/tests/unit/test_rlt_gym_storyworld_cohort.py +++ b/tests/unit/test_rlt_gym_storyworld_cohort.py @@ -39,8 +39,11 @@ def test_four_world_cohort_isolation_and_replay(self): self.assertEqual(len(manifest["worlds"]), 4) self.assertEqual(manifest["totals"]["native_tasks"], 32) self.assertEqual(manifest["totals"]["native_controls"], 112) - self.assertEqual(manifest["totals"]["micro_tasks"], 32) - self.assertEqual(manifest["totals"]["train_sft_rows"], 16) + self.assertEqual( + manifest["totals"]["micro_tasks"] + manifest["totals"]["micro_overbudget_rows"], 32 + ) + self.assertGreater(manifest["totals"]["micro_tasks"], 0) + self.assertGreater(manifest["totals"]["train_sft_rows"], 0) names = set() for w in manifest["worlds"]: self.assertNotIn(w["id"], names) @@ -49,7 +52,10 @@ def test_four_world_cohort_isolation_and_replay(self): folder = root / "cohort" / w["id"] native = _rows(folder / "native/public_tasks.jsonl") mini = _rows(folder / "micro/micro_public.jsonl") - self.assertTrue(all(x["split"] == w["split"] for x in [*native, *mini])) + oversize = _rows(folder / "micro/micro_oversize.jsonl") + self.assertEqual(len(mini), w["micro_tasks"]) + self.assertEqual(len(oversize), w["micro_overbudget_rows"]) + self.assertTrue(all(x["split"] == w["split"] for x in [*native, *mini, *oversize])) if w["split"] != "train": self.assertEqual(_rows(folder / "native/train_targets.jsonl"), []) self.assertEqual(_rows(folder / "micro/micro_train_sft.jsonl"), []) From c30f6664cb099dd7d67260883ec16eb806e689d8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:41:51 +0800 Subject: [PATCH 37/38] docs(storyworld): record source-world splits and measured 4-world CPU receipts --- training/rlt_gym/storyworld_native/README.md | 51 ++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/training/rlt_gym/storyworld_native/README.md b/training/rlt_gym/storyworld_native/README.md index 09412892..0b5ff9c7 100644 --- a/training/rlt_gym/storyworld_native/README.md +++ b/training/rlt_gym/storyworld_native/README.md @@ -165,6 +165,57 @@ verifies the output-file digests. The recorded model trace is distinct from source-native oracle controls and should be compared on matched root lineages before training claims. +## STORY-02 multi-world cohort + +The registered cohort uses four pinned, distinct source worlds. All derived +native builder/Mini tasks and SWMD-MICRO examples from one world inherit +its registered split, making source-world withholding stronger than +encounter-level separation within a single world. + +| Registered source | Split | Domain | +| --- | --- | --- | +| forecast_backstab | train | Diplomacy and forecasts | +| ashen_aegis | train | Law and moral conflict | +| fifth_testimony | calibration | Testimony and moral reasoning | +| last_train_home | ood_test | Character-driven rescue | + +Registration is in world_cohort_v1.json. The cohort uses distinct, +deterministic per-world seeds and pins each source JSON and executable +upstream script by SHA-256. Native controls and Mini examples are stored +in separate directories under each world, with an overall manifest. +Use the default CPU-first pilot: + + python -m datagoblin.training_gym.rlt_gym.storyworld_cohort \ + --source "$GPTSTORYWORLD_SOURCE" \ + --seed 23 --per-mode 2 --micro-examples 2 \ + --micro-max-encounters 4 --out runs/storyworld-cohort-v1 + python -m datagoblin.training_gym.rlt_gym.storyworld_cohort \ + --source "$GPTSTORYWORLD_SOURCE" --replay runs/storyworld-cohort-v1 + +The verified 23 November source-pinned CI run yields 32 native tasks, +112 matched source-native control rollouts, 26 bounded Mini compiler +examples and 16 train SFT labels. Six larger Mini source compiler +packets exceed the conservative 8,192-byte prompt cap. They are kept +in micro_oversize.jsonl with an auditable ID and original byte count, +and excluded from model packets without truncating source instructions. +No held-out world contributes a training label. + +For an actual model rollout against the registered OOD world, point the +local player at its child native archive and supply that same source +world explicitly: + + python -m datagoblin.training_gym.rlt_gym.storyworld_local \ + --source "$GPTSTORYWORLD_SOURCE" \ + --world storyworlds/tsun01b_last_train_home/tsun01b.sweepweave.json \ + --archive runs/storyworld-cohort-v1/last_train_home/native \ + --model inky-mini --mode hypergame --split ood_test --max-roots 2 \ + --out runs/storyworld-inky-ood + +That is a runnable operator command, not a recorded Inky evaluation. +The benchmark remains a source-visible development holdout. Genuine +unseen-world testing requires independent world generation with +private, preregistered provenance. + ## Verification and next experiment GPTSTORYWORLD_SOURCE=../GPTStoryworld PYTHONPATH=src \ From 58b24420b7e8746ee1f6a4310ad58b7082edb99a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 05:41:59 +0800 Subject: [PATCH 38/38] skill(storyworld): add cross-world custody and local Inky interactive contract --- .../skills/storyworld-gym/SKILL.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md b/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md index 40ad5dd6..9897d380 100644 --- a/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md +++ b/training/rlt_gym/storyworld_native/skills/storyworld-gym/SKILL.md @@ -36,6 +36,35 @@ Never send the sealed private_bit, the unchosen futures, or hidden grade to the 7. Replay the full archive from the exact same source and seed. Quarantine any source SHA mismatch or hash failure. 8. Compare model completion against matched source controls on held-out lineages, and include actual verifier calls, full HG-02 utility, false accepts, and stable context budgets in promotion reports. +## Cross-world source custody + +Use the checked-in world_cohort_v1.json registry and the +storyworld_cohort.py collector for cross-world studies. The registry +assigns an entire source world to train, calibration or OOD test. +The original mini compiler is the source of its canonical SFT labels, +while the collector excludes prompt packets that exceed 8,192 bytes. +Read each micro_oversize.jsonl before claiming complete curriculum +coverage. Holdout-world native_train_targets and micro_train_sft +streams must be empty. Verify the source world and registry hashes +before interpreting any scores. + +## Optional local Inkling player + +The storyworld_local.py command takes a native archive, model alias and +loopback-only llama.cpp endpoint. It sends the model one public +observation per HG-02 turn and applies its proposed legal action through +the source-native simulator. The hidden bit stays sealed until a +source-owned audit. Each response is logged with raw text, parser result, +public state, request identity, sampler, and usage when supplied. +Builder/Mini mode requires PICK followed by one candidate identifier. + +Use --resume only with identical run configuration to continue a +partial result, and --replay-run to check every recorded action and +source grade offline. The source and model weights remain unchanged. +GitHub Actions uses a deterministic fake player to exercise the +protocol; a successful CI run is engineering evidence, never an Inky +capability score. + ## Runtime and evidence Use CPU-only source-native controls by default. Optional model rollouts should use the already-running local llama.cpp endpoint and a fixed Inkling/Inky Mini model identity. Keep model context at or below 8K for Mini and at most 16K across all modes. Do not restart the inference server or use a paid fallback. Capture raw outputs and token usage when supplied by the endpoint.