diff --git a/.github/workflows/agonist02.yml b/.github/workflows/agonist02.yml new file mode 100644 index 00000000..1017619c --- /dev/null +++ b/.github/workflows/agonist02.yml @@ -0,0 +1,39 @@ +name: AGN-02 learned research curation pilot + +on: + pull_request: + paths: + - "Agonist/**" + - "tests/unit/test_agonist02.py" + - ".github/workflows/agonist02.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + offline-student: + runs-on: ubuntu-latest + timeout-minutes: 12 + env: + PYTHONHASHSEED: "0" + OPENBLAS_NUM_THREADS: "1" + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + HF_HUB_OFFLINE: "1" + TRANSFORMERS_OFFLINE: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install offline dependency and test tools + run: python -m pip install -e ".[dev]" + - name: Lint both agonist modules + run: ruff check Agonist tests/unit/test_agonist_gym.py tests/unit/test_agonist02.py + - name: Run causal and matched-student unit tests + run: python -m pytest tests/unit/test_agonist_gym.py tests/unit/test_agonist02.py + - name: Produce 50-root pilot and replay independent checks + run: | + python -m Agonist.agn02 run --seed 17 --out "$RUNNER_TEMP/agonist02_dev50" + python -m Agonist.agn02 replay --archive "$RUNNER_TEMP/agonist02_dev50" diff --git a/AGENTS.md b/AGENTS.md index 0e1c76bf..66848cc4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,3 +9,4 @@ outside an operator-provided hard resource-cap wrapper. - Upstream repositories are read-only references. Do not copy unlicensed source or mutate upstream files. - When the human provides research taste for storyworld or videogame experimentation, use `Agonist/SKILL.md` and its offline `Agonist/gym.py` verifier before proposing a live Inkling worker. +- For student-uplift curation experiments after AGN-01 world verification, follow `Agonist/skills/agonist02/SKILL.md` and preserve evaluation-root custody. diff --git a/Agonist/AGN02.md b/Agonist/AGN02.md new file mode 100644 index 00000000..d53b7655 --- /dev/null +++ b/Agonist/AGN02.md @@ -0,0 +1,131 @@ +# AGN-02: research-selection and downstream student gym + +AGN-02 advances the [AGN-01 research agonist](README.md) from verifying a proposed +counterfactual world to testing whether **a curator can choose training worlds +that make another learner more capable**. Its first implementation is an offline +public development experiment. It is a contract and scientific pilot, not a +trained 1B DataGoblin result or evidence of a working Inkling provider. + +## Reproduce + +From the repository root with Python 3.10+, numpy and the test extras installed: + + python -m Agonist.agn02 run --out runs/agonist02/dev50 --seed 17 + python -m Agonist.agn02 replay --archive runs/agonist02/dev50 + python -m pytest tests/unit/test_agonist02.py + ruff check Agonist tests/unit/test_agonist02.py + +The run uses fifty synthetic, independently identified **taste families**. +A caller may pass a source-attributed JSONL taste file with exactly 34 train +and 16 dev family roots using the AGN-01 schema: + + python -m Agonist.agn02 run --tastes /path/to/tastes.jsonl \ + --out runs/agonist02/from_taste + +In this development fixture the source ID affects the generated mechanics +through a stable hash. The example source ideas are original and fictional. +Meaningful interpretation of an arbitrary new human idea requires the +separately authorized local Inky world-building worker. The present run +issues **zero teacher calls** and assigns **no measured teacher tokens**. + +The cohorts are disjoint by taste family: + +| Cohort | Roots | Purpose | +| --- | ---: | --- | +| Anchor | 10 train | Common supervised seed set for every learner | +| Candidate pool | 24 train | Curators choose 12 additional roots | +| Calibration | 8 dev | Estimate candidate utility for the learned surrogate | +| Evaluation | 8 dev | Evaluate trained students; isolated from curation and fitting | + +All eight evaluation roots remain public synthetic development samples. +There is no sealed confirmation or cross-generator structural holdout. + +## Three decisions from one evidence revision + +For each canonical root, an exact environment produces two counterfactual +fictional worlds with one changed prerequisite and the same surface cue. +The agent is asked to: + +1. **Act:** decide deploy or hold in the original public state. +2. **Revise:** decide again after an independently supplied prerequisite + change. The correct action must reverse. +3. **Check or stop:** evaluate the expected utility of buying another + source-freshness check before committing a later decision. The source + change hazard, check price and mistake cost are public. A check can help + only when resource and safety prerequisites permit deployment. + +The environment computes the label for the third action from its public +contract: if structural prerequisites permit deployment, checking has +expected advantage in hundredths of a unit of +\`hazard_percent * mistake_cost - 100 * check_cost\`. Otherwise checking +costs \`100 * check_cost\`. Check iff the advantage is strictly positive. + +The two world labels come from the AGN-01 exact action verifier. The +student receives one public decision state at a time. Labels are held +by the grader and used for supervised training only on anchor and +selected candidate roots. The surface cue is a heuristic confound. + +## Matched curator arms + +- **Anchor only:** common supervised anchor roots, for measuring what + adding any pool examples does. +- **Random:** seeded random selection of twelve pool roots. +- **Fixed:** frozen ranking that favors wrong surface cues, positive + verification actions and near-threshold resource margins. +- **Learned:** a small ridge utility selector trained on ten leave-one-out + anchor utility measurements on the calibration cohort. Its training + targets are the downstream student's accuracy changes. It is a + research proxy for DataGoblin's future agonist selection head. + +All non-anchor arms share the same candidate pool, exact oracle and 12-root +selection quota. Each student trains on 66 labeled decisions using 240 SGD +updates per seed. Three student seeds are matched by arm; the anchor-only +reference has 30 labeled decisions and also receives 240 updates. Every +selector has access to the same source corpus. The learned arm incurs +an additional eleven calibration-student fits and a ridge solve, which +must be accounted for when comparing total research cost. + +Full episode completion requires all three decisions correct. Record +per-decision accuracy, per-root/seed whole-episode success, paired +learned-minus-baseline differences and a descriptive root bootstrap. +The eight evaluation roots are too few for a powered efficacy claim. + +## Artifact contract + +\`runs/agonist02/dev50/\` is a content-hashed experiment archive: + +| File | Contents | +| --- | --- | +| roots.jsonl | Public synthetic worlds, causal revisions, checks and source custody | +| oracle_receipts.jsonl | Independent initial/revised/check actions and exact value of checking | +| selector_training.jsonl | Ten leave-one-out calibration utility targets | +| selections.jsonl | Exact chosen train roots and matched exposure counts | +| student_scores.jsonl | Per-root, per-seed, per-arm outcomes | +| manifest.json | Provenance, work counts, predictive control comparison and artifact SHA-256 | + +Replay verifies digests and **independently recomputes** all labels, +candidate choices and trained student scores. It detects a relabeled +receipt even when the archive manifest hash has been rewritten. +Existing output directories are protected against silent overwrites. + +## Interpretation and next research gate + +The AGN-02 selector is a small trained **surrogate** with an intentionally +weak generalization probe. It cannot establish that DataGoblin 1B learns +research taste, that Inky improves world diversity, or that the student +benefit generalizes to unseen generator programs. + +To advance toward those claims, use the AGN-01 teacher queue and +approved local Inkling service to generate executable worlds with +real token receipts. Add a versioned environment adapter for richer +storyworlds and games; retain exact or independent verifiers for their +actions. Compare learned DG curation against fixed and random policies +with identical teacher budget and candidate pool, then train students +at matched sample and optimizer budgets on entirely held-out +generator families. A preregistered EvalMath analysis should include +root-clustered intervals, failure rates, contamination audits and the +cost of fitting the selector. + +All candidate training views remain \`training_ready=false\`. +No private seeds, real model activations, model weights, secrets, +provider responses or generated run archives are committed. diff --git a/Agonist/README.md b/Agonist/README.md index a13bc2de..02b9e8cc 100644 --- a/Agonist/README.md +++ b/Agonist/README.md @@ -124,3 +124,7 @@ multi-turn game adapters for costly information gathering, source revisions, social play, and research selection. Connect the verified root exports to the DataGoblin curator only after measuring the small-learner uplift against matched-budget baselines. + +## AGN-02 student-uplift pilot + +[AGN-02](AGN02.md) adds a 50-family, three-decision offline experiment with a learned utility-selection surrogate, matched random and fixed curation, trained small-student comparisons, and independently recomputed receipts. Its [selection skill](skills/agonist02/SKILL.md) describes the downstream learner objective and promotion protocol. The current AGN-02 fixture uses no live Inky inference or sealed confirmation roots. diff --git a/Agonist/agn02.py b/Agonist/agn02.py new file mode 100644 index 00000000..30cffb56 --- /dev/null +++ b/Agonist/agn02.py @@ -0,0 +1,583 @@ +"""AGN-02: offline research-agonist selection and downstream-student pilot. + +This is a public synthetic development fixture. The learned selector is a small +ridge regressor, not the pretrained DataGoblin model. No teacher inference, paid +compute, real-world actions, sealed roots, or production data admission occurs. +""" + +from __future__ import annotations + +import argparse +import json +import random +from pathlib import Path +from typing import Any + +import numpy as np + +from Agonist.gym import ( + canonical, + digest, + new_dir, + read_jsonl, + sha256_file, + validate_tastes, + verify_pair, + write_jsonl, +) + +SCHEMA = "datagoblin.agonist02.dev.v1" +COHORT = {"anchor": 10, "pool": 24, "calibration": 8, "evaluation": 8} +ARM_NAMES = ("anchor_only", "random", "fixed", "learned") +STUDENT_SEEDS = (11, 23, 47) +THEMES = ( + "a simulated scientific field station", + "a fictional logistics expedition", + "a cooperative strategy game", + "a simulated archive repair lab", + "a fictional asteroid research habitat", +) +STAGES = ("initial", "revised", "check") + + +def make_tastes(seed: int) -> list[dict[str, Any]]: + """Original fictional premises: 50 independently identified root families.""" + rows = [] + for index in range(sum(COHORT.values())): + theme = THEMES[index % len(THEMES)] + rows.append( + { + "taste_id": f"agn02-taste-{seed}-{index:03d}", + "family_id": f"agn02-family-{seed}-{index:03d}", + "idea": f"Test whether an agent revises a decision in {theme} after one causal prerequisite changes.", + "source_kind": "fixture", + "source_ref": f"AGn02 original synthetic seed {seed}/{index}", + "rights": "project_original", + "split": "train" if index < 34 else "dev", + } + ) + return rows + + +def _assign_cohorts(tastes: list[dict[str, Any]]) -> list[tuple[str, dict[str, Any]]]: + validate_tastes(tastes) + if len(tastes) != 50 or len({t["family_id"] for t in tastes}) != 50: + raise ValueError("AGN-02 development fixture needs 50 independent taste families") + train = sorted((t for t in tastes if t["split"] == "train"), key=lambda t: t["taste_id"]) + dev = sorted((t for t in tastes if t["split"] == "dev"), key=lambda t: t["taste_id"]) + if len(train) != 34 or len(dev) != 16: + raise ValueError("required custody is 34 train families and 16 dev families") + if any(t["rights"] == "reference_only" for t in train): + raise ValueError("reference-only taste cannot supply a training root") + return [ + *(("anchor", t) for t in train[:10]), + *(("pool", t) for t in train[10:]), + *(("calibration", t) for t in dev[:8]), + *(("evaluation", t) for t in dev[8:]), + ] + + +def generate_root(taste: dict[str, Any], cohort: str, seed: int) -> dict[str, Any]: + """Deterministic initial->revised world; the label comes from AGN-01's oracle.""" + rng = random.Random(int(digest([taste["taste_id"], seed])[:16], 16)) + required = rng.randint(2, 7) + positive = { + "available": required + rng.randint(0, 2), + "required": required, + "safety_approved": True, + "source_fresh": True, + } + negative = dict(positive) + field = rng.choice(("available", "safety_approved", "source_fresh")) + negative[field] = required - 1 if field == "available" else False + first_positive = bool(rng.getrandbits(1)) + initial_state = positive if first_positive else negative + revised_state = negative if first_positive else positive + surface = rng.choice(("red", "green")) + theme = THEMES[int(digest(taste["family_id"])[:6], 16) % len(THEMES)] + shared = { + "setting": "Fictional research trial " + taste["taste_id"][:48], + "scenario": ( + f"An agent in {theme} must decide on a bounded deployment " + "from the current rule and source evidence." + ), + "surface_cue": surface, + } + world_a = {**shared, "state": dict(initial_state)} + world_b = {**shared, "state": dict(revised_state)} + intervention = { + "field": field, + "from": initial_state[field], + "to": revised_state[field], + } + verify_pair(world_a, world_b, intervention) + return { + "schema": SCHEMA, + "root": "agn02-" + digest([taste["taste_id"], seed])[:24], + "taste_id": taste["taste_id"], + "family_id": taste["family_id"], + "cohort": cohort, + "source_kind": taste["source_kind"], + "rights": taste["rights"], + "taste_digest": digest(taste["idea"]), + "generation_kind": "offline_rule_fixture_no_teacher", + "world_a": world_a, + "world_b": world_b, + "intervention": intervention, + "check_case": { + "hazard_percent": rng.choice((10, 25, 40, 65, 85)), + "check_cost": rng.choice((1, 2, 3)), + "mistake_cost": rng.choice((4, 8, 12)), + }, + } + + +def check_value(root: dict[str, Any]) -> int: + """Expected value, in hundredths of a utility unit, of another check. + + The announced exogenous source-change hazard matters only when structural + prerequisites allow deployment. A tie is resolved by stopping. + """ + state = root["world_b"]["state"] + case = root["check_case"] + if not ( + type(case["hazard_percent"]) is int + and type(case["check_cost"]) is int + and type(case["mistake_cost"]) is int + and case["hazard_percent"] in (10, 25, 40, 65, 85) + and case["check_cost"] in (1, 2, 3) + and case["mistake_cost"] in (4, 8, 12) + ): + raise ValueError("invalid prospective check case") + if state["available"] < state["required"] or not state["safety_approved"]: + return -100 * case["check_cost"] + return case["hazard_percent"] * case["mistake_cost"] - 100 * case["check_cost"] + + +def exact_actions(root: dict[str, Any]) -> tuple[str, str, str]: + first, revised = verify_pair(root["world_a"], root["world_b"], root["intervention"]) + return first, revised, "check" if check_value(root) > 0 else "stop" + + +def validate_root(root: dict[str, Any]) -> None: + if root.get("schema") != SCHEMA or root.get("cohort") not in COHORT: + raise ValueError("invalid AGN-02 root schema or cohort") + if not all(isinstance(root.get(k), str) for k in ("root", "taste_id", "family_id", "rights")): + raise ValueError("invalid root identity") + if root["rights"] == "reference_only" and root["cohort"] in ("anchor", "pool"): + raise ValueError("unauthorized reference-only training root") + exact_actions(root) + + +def construct_roots(seed: int, tastes: list[dict[str, Any]]) -> list[dict[str, Any]]: + roots = [generate_root(taste, group, seed) for group, taste in _assign_cohorts(tastes)] + if len({r["root"] for r in roots}) != 50: + raise ValueError("duplicate root") + for row in roots: + validate_root(row) + return roots + + +def _features(world: dict[str, Any], check_case: dict[str, int] | None = None) -> np.ndarray: + state = world["state"] + # The later value-of-information case is visible only at the check stage. + check_case = check_case or {"hazard_percent": 0, "check_cost": 0, "mistake_cost": 0} + return np.asarray( + ( + 1.0, + (state["available"] - state["required"]) / 6.0, + float(state["available"] >= state["required"]), + float(state["safety_approved"]), + float(state["source_fresh"]), + float(world["surface_cue"] == "green"), + check_case["hazard_percent"] / 100.0, + check_case["check_cost"] / 3.0, + check_case["mistake_cost"] / 12.0, + check_case["hazard_percent"] * check_case["mistake_cost"] / 1200.0, + ), + dtype=np.float64, + ) + + +def _examples(root: dict[str, Any]) -> list[tuple[int, np.ndarray, int]]: + labels = exact_actions(root) + return [ + (0, _features(root["world_a"]), int(labels[0] == "deploy")), + (0, _features(root["world_b"]), int(labels[1] == "deploy")), + (1, _features(root["world_b"], root["check_case"]), int(labels[2] == "check")), + ] + + +def _sigmoid(value: float) -> float: + bounded = max(-40.0, min(40.0, value)) + return float(1.0 / (1.0 + np.exp(-bounded))) + + +def fit_student(roots: list[dict[str, Any]], seed: int, updates: int = 240) -> np.ndarray: + """Genuine small supervised linear-policy training with equal update count.""" + if not roots or updates < 1: + raise ValueError("student training requires roots and positive updates") + rows = [example for root in roots for example in _examples(root)] + weights = np.zeros((2, 10), dtype=np.float64) + rng = random.Random(seed) + order = list(range(len(rows))) + rng.shuffle(order) + for step in range(updates): + if step and step % len(order) == 0: + rng.shuffle(order) + head, features, gold = rows[order[step % len(order)]] + p = _sigmoid(float(weights[head] @ features)) + weights[head] -= 0.15 * ((p - gold) * features + 0.002 * weights[head]) + return weights + + +def _student_decisions(weights: np.ndarray, root: dict[str, Any]) -> tuple[bool, bool, bool]: + examples = _examples(root) + return tuple( + bool((_sigmoid(float(weights[head] @ features)) >= 0.5) == bool(label)) + for head, features, label in examples + ) + + +def _evaluation_rate(weights: np.ndarray, roots: list[dict[str, Any]]) -> float: + if not roots: + raise ValueError("empty calibration roots") + return sum(sum(_student_decisions(weights, root)) for root in roots) / (len(roots) * 3) + + +def _selector_features(root: dict[str, Any]) -> np.ndarray: + """Public and train-verifier-derived curation features, never eval labels.""" + a, b, check = exact_actions(root) + case = root["check_case"] + state = root["world_b"]["state"] + cue = "deploy" if root["world_a"]["surface_cue"] == "green" else "hold" + field = root["intervention"]["field"] + return np.asarray( + ( + 1.0, + float(field == "available"), + float(field == "safety_approved"), + float(field == "source_fresh"), + float(cue != a), + float(a == "deploy"), + float(check == "check"), + abs(state["available"] - state["required"]) / 6.0, + case["hazard_percent"] * case["mistake_cost"] / 1200.0, + case["check_cost"] / 3.0, + float(b == "deploy"), + ), + dtype=np.float64, + ) + + +def _calibrate_selector( + anchors: list[dict[str, Any]], + calibration: list[dict[str, Any]], + updates: int, +) -> tuple[np.ndarray, list[dict[str, Any]]]: + """Leave-one-out marginal utility, regressed on ten train-only roots. + + Calibration outcomes train this small research-utility proxy. The separate + evaluation cohort is never used for utility fitting or choosing candidates. + """ + full_student = fit_student(anchors, seed=41, updates=updates) + full_accuracy = _evaluation_rate(full_student, calibration) + observed: list[dict[str, Any]] = [] + x: list[np.ndarray] = [] + y: list[float] = [] + for i, root in enumerate(anchors): + without = anchors[:i] + anchors[i + 1 :] + baseline = fit_student(without, seed=41, updates=updates) + delta = full_accuracy - _evaluation_rate(baseline, calibration) + x.append(_selector_features(root)) + y.append(delta) + observed.append( + { + "root": root["root"], + "cohort": "anchor", + "utility_delta_calibration_decision_accuracy": round(delta, 9), + "family_id": root["family_id"], + } + ) + matrix = np.stack(x) + targets = np.asarray(y, dtype=np.float64) + regularizer = np.eye(matrix.shape[1]) * 0.5 + regularizer[0, 0] = 0.05 + weights = np.linalg.solve(matrix.T @ matrix + regularizer, matrix.T @ targets) + return weights, observed + + +def _fixed_score(root: dict[str, Any]) -> float: + """Frozen heuristic: favor cue-counterexamples and narrow resource margins.""" + a, _, c = exact_actions(root) + cue = "deploy" if root["world_a"]["surface_cue"] == "green" else "hold" + margin = abs( + root["world_b"]["state"]["available"] - root["world_b"]["state"]["required"] + ) + return 4 * float(cue != a) + 2 * float(c == "check") + 1 / (1 + margin) + + +def select_roots( + anchors: list[dict[str, Any]], + pool: list[dict[str, Any]], + calibration: list[dict[str, Any]], + seed: int, + updates: int, + selection_count: int = 12, +) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, Any]], dict[str, Any]]: + if len(anchors) != 10 or len(pool) != 24 or len(calibration) != 8: + raise ValueError("incorrect selection cohort dimensions") + if not 1 <= selection_count <= len(pool): + raise ValueError("selection_count out of range") + utility_weights, observations = _calibrate_selector(anchors, calibration, updates) + random_pool = list(pool) + random.Random(seed + 4901).shuffle(random_pool) + learned = sorted( + pool, + key=lambda root: (-float(utility_weights @ _selector_features(root)), root["root"]), + ) + fixed = sorted(pool, key=lambda root: (-_fixed_score(root), root["root"])) + selections = { + "anchor_only": list(anchors), + "random": anchors + random_pool[:selection_count], + "fixed": anchors + fixed[:selection_count], + "learned": anchors + learned[:selection_count], + } + meta = { + "selector": "small_ridge_utility_proxy", + "meta_train_roots": len(anchors), + "calibration_roots": len(calibration), + "calibration_student_fits": len(anchors) + 1, + "selector_weights": [round(float(x), 12) for x in utility_weights], + "all_arms_share_verified_pool": True, + "learned_controller_is_data_goblin_1b": False, + } + return selections, observations, meta + + +def _paired_differences( + rows: list[dict[str, Any]], + seed: int, + replicates: int = 500, +) -> dict[str, Any]: + """Root-clustered descriptive bootstrap, with all student seeds within a root.""" + grouped: dict[str, dict[str, list[int]]] = {} + for row in rows: + grouped.setdefault(row["root"], {}).setdefault(row["arm"], []).append( + int(row["whole_episode_correct"]) + ) + root_ids = sorted(grouped) + for root in root_ids: + if set(grouped[root]) != set(ARM_NAMES): + raise ValueError("incomplete paired root/arm score matrix") + if any(len(grouped[root][arm]) != len(STUDENT_SEEDS) for arm in ARM_NAMES): + raise ValueError("missing student seed for root/arm") + rng = random.Random(seed + 118) + report = {} + for comparator in ("random", "fixed", "anchor_only"): + differences = [ + (sum(grouped[root]["learned"]) - sum(grouped[root][comparator])) / len(STUDENT_SEEDS) + for root in root_ids + ] + mean = sum(differences) / len(differences) + boot = [] + for _ in range(replicates): + sample = [differences[rng.randrange(len(differences))] for _ in root_ids] + boot.append(sum(sample) / len(sample)) + boot.sort() + report[f"learned_minus_{comparator}"] = { + "mean_whole_episode_fraction": round(mean, 6), + "descriptive_root_bootstrap_95": [ + round(boot[int(0.025 * replicates)], 6), + round(boot[int(0.975 * replicates) - 1], 6), + ], + } + return report + + +def simulate( + seed: int = 17, + updates: int = 240, + selection_count: int = 12, + tastes: list[dict[str, Any]] | None = None, +) -> tuple[dict[str, list[dict[str, Any]]], dict[str, Any]]: + if not 1 <= updates <= 5_000: + raise ValueError("student updates outside the predeclared development cap") + actual_tastes = make_tastes(seed) if tastes is None else tastes + roots = construct_roots(seed, actual_tastes) + by_cohort = {name: [r for r in roots if r["cohort"] == name] for name in COHORT} + selections, utility_rows, utility_meta = select_roots( + by_cohort["anchor"], + by_cohort["pool"], + by_cohort["calibration"], + seed, + updates, + selection_count, + ) + oracle_receipts = [ + { + "root": root["root"], + "cohort": root["cohort"], + "family_id": root["family_id"], + "world_digest": digest([root["world_a"], root["world_b"], root["intervention"]]), + "actions": list(exact_actions(root)), + "check_value_hundredths": check_value(root), + "verifier": "agn01_exact_actions_plus_agn02_expected_check_v1", + } + for root in roots + ] + selected_rows = [ + { + "arm": arm, + "roots": [r["root"] for r in selected], + "selected_pool_roots": len(selected) - len(by_cohort["anchor"]), + "train_examples": 3 * len(selected), + } + for arm, selected in selections.items() + ] + scores = [] + for arm in ARM_NAMES: + selected = selections[arm] + for student_seed in STUDENT_SEEDS: + weights = fit_student(selected, student_seed, updates) + for root in by_cohort["evaluation"]: + results = _student_decisions(weights, root) + scores.append( + { + "arm": arm, + "student_seed": student_seed, + "root": root["root"], + "family_id": root["family_id"], + "cohort": "evaluation", + "phase_correct": { + stage: correct for stage, correct in zip(STAGES, results, strict=True) + }, + "whole_episode_correct": all(results), + "correct_decisions": sum(results), + "checked_decisions": 3, + "updates": updates, + } + ) + whole = { + arm: { + "whole_episodes": sum(int(x["whole_episode_correct"]) for x in scores if x["arm"] == arm), + "correct_decisions": sum(x["correct_decisions"] for x in scores if x["arm"] == arm), + "episodes": len(by_cohort["evaluation"]) * len(STUDENT_SEEDS), + "decisions": 3 * len(by_cohort["evaluation"]) * len(STUDENT_SEEDS), + } + for arm in ARM_NAMES + } + extra = { + "schema": SCHEMA, + "phase": "public_synthetic_dev_only", + "seed": seed, + "training_updates_per_student": updates, + "selection_count": selection_count, + "cohorts": COHORT, + "student_seeds": list(STUDENT_SEEDS), + "source_tastes": "original_fixture" if tastes is None else "operator_supplied", + "teacher_inference_calls": 0, + "teacher_tokens": None, + "candidate_verifier_decisions": 3 * len(roots), + "evaluation_roots": len(by_cohort["evaluation"]), + "selector_training": utility_meta, + "student_results": whole, + "paired": _paired_differences(scores, seed), + "scientific_claim": "development-only mechanics and learned surrogate comparison", + "sealed_confirmation_run": False, + "training_ready": False, + } + return { + "roots.jsonl": roots, + "oracle_receipts.jsonl": oracle_receipts, + "selector_training.jsonl": utility_rows, + "selections.jsonl": selected_rows, + "student_scores.jsonl": scores, + }, extra + + +def _make_manifest(folder: Path, files: dict[str, list[dict[str, Any]]], extra: dict[str, Any]) -> dict[str, Any]: + manifest = { + **extra, + "artifacts": { + name: {"rows": len(rows), "sha256": sha256_file(folder / name)} + for name, rows in sorted(files.items()) + }, + } + (folder / "manifest.json").write_text(canonical(manifest) + "\n", encoding="utf-8") + return manifest + + +def run( + out: Path, + seed: int = 17, + updates: int = 240, + selection_count: int = 12, + tastes_path: Path | None = None, +) -> dict[str, Any]: + tastes = read_jsonl(tastes_path) if tastes_path else None + files, extra = simulate(seed, updates, selection_count, tastes) + if tastes_path: + extra["tastes_sha256"] = sha256_file(tastes_path) + new_dir(out) + for name, rows in files.items(): + write_jsonl(out / name, rows) + return _make_manifest(out, files, extra) + + +def replay(out: Path, tastes_path: Path | None = None) -> dict[str, Any]: + manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != SCHEMA or manifest.get("phase") != "public_synthetic_dev_only": + raise ValueError("invalid AGN-02 replay manifest") + supplied = manifest["source_tastes"] == "operator_supplied" + if supplied != (tastes_path is not None): + raise ValueError("source taste file required exactly for operator-supplied archive") + if supplied and sha256_file(tastes_path) != manifest["tastes_sha256"]: + raise ValueError("taste input hash mismatch") + tastes = read_jsonl(tastes_path) if supplied else None + expected_files, expected = simulate( + manifest["seed"], manifest["training_updates_per_student"], manifest["selection_count"], tastes + ) + for key, value in expected.items(): + if manifest.get(key) != value: + raise ValueError(f"experiment manifest differs: {key}") + if set(manifest["artifacts"]) != set(expected_files): + raise ValueError("unexpected artifact inventory") + for name, rows in expected_files.items(): + path = out / name + if not path.is_file() or sha256_file(path) != manifest["artifacts"][name]["sha256"]: + raise ValueError(f"archive hash mismatch: {name}") + if len(rows) != manifest["artifacts"][name]["rows"]: + raise ValueError(f"archive row count mismatch: {name}") + if canonical(read_jsonl(path)) != canonical(rows): + raise ValueError(f"independent recomputation disagrees: {name}") + return { + "verified_roots": len(expected_files["oracle_receipts.jsonl"]), + "student_score_rows": len(expected_files["student_scores.jsonl"]), + "recomputed": True, + "sealed_confirmation_run": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description="AGN-02 offline curator/student experiment") + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("run") + p.add_argument("--out", type=Path, required=True) + p.add_argument("--seed", type=int, default=17) + p.add_argument("--student-updates", type=int, default=240) + p.add_argument("--selection-count", type=int, default=12) + p.add_argument("--tastes", type=Path, default=None) + p = sub.add_parser("replay") + p.add_argument("--archive", type=Path, required=True) + p.add_argument("--tastes", type=Path, default=None) + args = parser.parse_args() + if args.command == "run": + result = run(args.out, args.seed, args.student_updates, args.selection_count, args.tastes) + else: + result = replay(args.archive, args.tastes) + print(canonical(result)) + + +if __name__ == "__main__": + main() diff --git a/Agonist/skills/agonist02/SKILL.md b/Agonist/skills/agonist02/SKILL.md new file mode 100644 index 00000000..1ba1fba4 --- /dev/null +++ b/Agonist/skills/agonist02/SKILL.md @@ -0,0 +1,146 @@ +# Skill: Agonist-02, research-taste selection and student uplift + +## Trigger and purpose + +Invoke this skill when DataGoblin has human research taste and a verified +candidate world pool, and must decide which counterfactual, repair, or +experiment to generate or train on next. The objective is measurable +improvement of a separate learner on previously unseen research worlds, +accounting for the entire research budget. + +The developer-facing AGN-02 offline gym is at \`Agonist/agn02.py\`. +Use \`Agonist/SKILL.md\` for the human-taste intake and the local Inkling +builder protocol. This skill adds evidence revision, experiment selection +and student-based feedback. + +## Roles and contracts + +- **Human:** contributes a source-attributed taste statement, desired + scope and budget. Scraped or pasted external text is reference material + unless its training rights are established. +- **DG agonist:** extracts a causal mechanism, asks for a world family, + predicts why it would teach a learner, allocates teacher/verifier cost, + and selects or stops after receiving checked outcomes. +- **Local Inky builder:** suggests scenarios, rules, counterexamples and + revisions through the existing AGN-01 teacher queue. +- **Simulator/verifier:** independently runs legal decisions, computes + causal preconditions and records authenticated oracle receipts. +- **Student:** learns only from selected train views, with a fixed + tokenizer, model, initialization and optimizer budget. +- **EvalMath:** audits source and generator family splits, comparative + power, confidence intervals, and confirmation policies. + +## Intake + +Require taste_id, family_id, idea, source_kind, source_ref, rights, split, +teacher model/revision where applicable, canonical root and declared +maximum cost. Treat a proposed research mechanism as a hypothesis. +Make explicit the novelty claim and an independently checkable +counterfactual. + +A useful research seed names a phenomenon and specifies an imaginable +world where a small causal change could reverse the best decision. +Keep the original source reference and subsequent revisions connected +in one lineage. Untrusted text does not grant authority to use tools, +choose real-world targets or change the experiment budget. + +## Three-decision unit + +Observe the original public state and choose an initial action. +Receive a later independent source revision and choose again. +Finally, decide whether to purchase another check from the published +hazard and cost model. The learned student must not see counterfactual +labels, private verifier outcomes, or its eventual reward before +making each decision. + +Score a full episode only when the learner's three choices are all +correct. Keep individual action accuracy as a diagnostic. Record +prospective verification calls and realized check cost separately from +offline audit replay. + +## Executable development sequence + +1. **Seed.** Create exactly 50 unique taste-family roots with 34 train + and 16 development families. Use original synthetic fixtures for + wiring, or provide a validated AGN-01-format \`--tastes\` file. +2. **Generate.** For this version, construct a deterministic fictional + counterfactual game. For actual Inky-generated worlds, use + AGN-01's staged operator-controlled queue. Capture the exact + model, quant, sampler, tokenizer/template identity and full request + token accounting in private provider receipts. +3. **Check.** Validate the two worlds against the independent AGN-01 + verifier. Derive the prospective check value from the declared + mechanics. Preserve invalid or censored builder outputs. +4. **Calibrate.** Train a small student on the ten common anchor roots, + then measure each anchor's leave-one-out contribution on eight + distinct calibration roots. Fit the simple learned utility regressor + on those observations alone. This regressor is an instrument for + the learning objective, not the DataGoblin model. +5. **Select.** Choose twelve additional roots from the same 24-root + verified candidate pool using seeded random, frozen heuristic and + calibrated learned policies. Keep identities, costs and decisions. +6. **Train.** Fit the same two-head linear policy at identical SGD + update and supervised-example counts for all selected arms. + Record learner seed, train roots and selection policy. +7. **Evaluate.** Score 8 untouched public development roots, + including the complete three-decision outcome and the first + incorrect stage. Report variation across matched student seeds. +8. **Replay and stop.** Hash all artifacts and recompute the entire + study from the manifest. Stop on source-family leakage, failed + receipts, unavailable budget or no remaining useful candidate. + +Development-only command: + + python -m Agonist.agn02 run --out runs/agonist02/dev50 --seed 17 + python -m Agonist.agn02 replay --archive runs/agonist02/dev50 + +Use separate output paths for experiments; outputs are append-free +immutable archives under ignored \`runs/\` directories. + +## Policy input and score + +A curation policy receives only approved train-root facts, optional +independently verified train outcomes, the remaining budget and +observed previous development results. Its response contains chosen +root IDs or a STOP action, expected downstream benefit, expected +cost, and the evidence IDs supporting the choice. + +For a later neural DG controller use: + + expected_learner_gain / (teacher_tokens + verifier_work + learner_cost) + +Report each denominator component in native units as well as the +chosen scalar conversion. Keep an exploration allocation for +randomized selection so the controller's research-taste predictions +can be tested prospectively. + +The AGN-02 fixture's regressor learns on calibration outcomes; a +comparison against random and frozen curation uses equal candidate +and final student budgets. Calibration-student computation is +additional policy cost and must be reported. The anchor-only arm is +a lower-data reference, not a sample-matched control. + +## Promotion policy + +A positive claim requires gains in complete verified episodes on +independent roots, uncertainty that treats the source family as the +sampling unit, and no task-family leakage. Compare against the +full-cost matched fixed and random baselines. Hold actual sealed +confirmation roots and generator programs outside all policy +training, calibration, teacher prompting and parameter selection. + +Require new evidence on genuinely executed worlds before making +claims about videogame generation, agentic research judgment, +Inkling 2 Mini integration or BPD-guided learning. Stage a richer +world adapter only when it has reproducible state transitions, +an executable action whitelist, source/rights admission and an +independent scoring authority. + +## Non-claims + +The AGN-02 fixture is synthetic development research. Its "learned" +arm is an explicit tiny ridge utility regressor. It does not use a +trained 1B DataGoblin, live Inky inference, Silico credits or Google +TPUs. It exports no admitted pretraining data. Its small same-grammar +evaluation cohort is a mechanics test and a pilot comparison, not a +powered demonstration of transfer to new storyworld generators. diff --git a/tests/unit/test_agonist02.py b/tests/unit/test_agonist02.py new file mode 100644 index 00000000..d4866f51 --- /dev/null +++ b/tests/unit/test_agonist02.py @@ -0,0 +1,192 @@ +"""AGN-02: exact three-decision semantics, matched student budget and replay.""" + +from __future__ import annotations + +import json + +import pytest + +from Agonist.agn02 import ( + ARM_NAMES, + COHORT, + STUDENT_SEEDS, + _assign_cohorts, + _examples, + _student_decisions, + check_value, + construct_roots, + exact_actions, + fit_student, + make_tastes, + replay, + run, + simulate, +) +from Agonist.gym import canonical, read_jsonl, verify_pair, write_jsonl + + +def test_fifty_independent_taste_families_and_custody(): + tastes = make_tastes(17) + assert len(tastes) == 50 + assigned = _assign_cohorts(tastes) + assert {group for group, _ in assigned} == set(COHORT) + assert {group: sum(name == group for name, _ in assigned) for group in COHORT} == COHORT + assert len({item["family_id"] for _, item in assigned}) == 50 + assert all(t["split"] == "train" for group, t in assigned if group in ("anchor", "pool")) + assert all(t["split"] == "dev" for group, t in assigned if group in ("calibration", "evaluation")) + + +def test_fifty_valid_causal_flips_and_three_decisions(): + roots = construct_roots(17, make_tastes(17)) + assert len(roots) == 50 + for root in roots: + initial, revised, check = exact_actions(root) + assert (initial, revised) == verify_pair( + root["world_a"], root["world_b"], root["intervention"] + ) + assert initial != revised + assert check in ("check", "stop") + assert (check == "check") == (check_value(root) > 0) + assert root["generation_kind"] == "offline_rule_fixture_no_teacher" + + +def test_check_has_value_only_when_structural_action_possible(): + roots = construct_roots(17, make_tastes(17)) + structural = next( + root for root in roots + if root["world_b"]["state"]["available"] >= root["world_b"]["state"]["required"] + and root["world_b"]["state"]["safety_approved"] + ) + state = dict(structural["world_b"]["state"]) + root = {**structural, "check_case": {"hazard_percent": 85, "check_cost": 1, "mistake_cost": 12}} + assert check_value(root) > 0 + root = {**root, "world_b": {**root["world_b"], "state": {**state, "safety_approved": False}}} + assert check_value(root) == -100 + + + +def test_future_check_information_is_masked_during_earlier_actions(): + root = construct_roots(17, make_tastes(17))[0] + initial, revised, check = _examples(root) + assert all(float(value) == 0.0 for value in initial[1][6:]) + assert all(float(value) == 0.0 for value in revised[1][6:]) + assert any(float(value) > 0.0 for value in check[1][6:]) + assert initial[0] == revised[0] == 0 + assert check[0] == 1 + + +def test_learned_selector_is_actual_training_and_eval_is_heldout(): + files, report = simulate(seed=17, updates=96, selection_count=12) + assert len(files["oracle_receipts.jsonl"]) == 50 + assert len(files["selector_training.jsonl"]) == 10 + assert len(files["selections.jsonl"]) == 4 + assert len(files["student_scores.jsonl"]) == 8 * 3 * 4 + assert report["teacher_inference_calls"] == 0 + assert report["student_seeds"] == list(STUDENT_SEEDS) + assert report["training_ready"] is False + assert report["sealed_confirmation_run"] is False + assert report["selector_training"]["calibration_student_fits"] == 11 + assert report["selector_training"]["learned_controller_is_data_goblin_1b"] is False + selected = {row["arm"]: row for row in files["selections.jsonl"]} + assert set(selected) == set(ARM_NAMES) + assert selected["anchor_only"]["train_examples"] == 30 + for arm in ("random", "fixed", "learned"): + assert selected[arm]["train_examples"] == 66 + assert selected[arm]["selected_pool_roots"] == 12 + training_roots = {r["root"] for r in files["roots.jsonl"] if r["cohort"] in ("anchor", "pool")} + evaluation_roots = {r["root"] for r in files["roots.jsonl"] if r["cohort"] == "evaluation"} + assert not (training_roots & evaluation_roots) + for row in selected.values(): + assert set(row["roots"]) <= training_roots + assert {r["root"] for r in files["student_scores.jsonl"]} == evaluation_roots + + +def test_stable_ridge_surrogate_and_genuine_student_fitting(): + files, report = simulate(seed=17, updates=80, selection_count=5) + assert len(report["selector_training"]["selector_weights"]) == 11 + roots = files["roots.jsonl"] + student_a = fit_student(roots[:10], seed=11, updates=80) + student_b = fit_student(roots[:10], seed=11, updates=80) + assert (student_a == student_b).all() + assert any(float(abs(x)) > 0 for x in student_a.flatten()) + assert len(_student_decisions(student_a, roots[-1])) == 3 + + +def test_deterministic_archive_replay_and_sha256_tamper_detection(tmp_path): + first = tmp_path / "first" + second = tmp_path / "second" + a = run(first, seed=17, updates=80, selection_count=5) + b = run(second, seed=17, updates=80, selection_count=5) + assert a == b + assert replay(first) == { + "verified_roots": 50, + "student_score_rows": 96, + "recomputed": True, + "sealed_confirmation_run": False, + } + with pytest.raises(FileExistsError): + run(first, seed=17, updates=80, selection_count=5) + path = first / "student_scores.jsonl" + path.write_text(path.read_text(encoding="utf-8") + " ", encoding="utf-8") + with pytest.raises(ValueError, match="archive hash mismatch"): + replay(first) + + +def test_source_root_rights_and_external_taste_manifest(tmp_path): + tastes = make_tastes(29) + tastes_path = tmp_path / "tastes.jsonl" + write_jsonl(tastes_path, tastes) + archive = tmp_path / "archive" + manifest = run(archive, seed=29, updates=50, selection_count=4, tastes_path=tastes_path) + assert manifest["source_tastes"] == "operator_supplied" + assert replay(archive, tastes_path)["verified_roots"] == 50 + with pytest.raises(ValueError, match="required exactly"): + replay(archive) + tastes[0]["rights"] = "reference_only" + write_jsonl(tastes_path, tastes) + with pytest.raises(ValueError, match="taste input hash mismatch"): + replay(archive, tastes_path) + with pytest.raises(ValueError, match="reference-only"): + _assign_cohorts(tastes) + + +def test_split_crossing_and_repeated_family_is_rejected(): + tastes = make_tastes(17) + tastes[1]["family_id"] = tastes[0]["family_id"] + with pytest.raises(ValueError, match="independent taste families"): + _assign_cohorts(tastes) + tastes = make_tastes(17) + tastes[40]["split"] = "train" + with pytest.raises(ValueError, match="34 train"): + _assign_cohorts(tastes) + + +def test_manifest_gold_cannot_be_relabelled_after_hash_update(tmp_path): + archive = tmp_path / "run" + run(archive, seed=17, updates=50) + receipt_file = archive / "oracle_receipts.jsonl" + receipts = read_jsonl(receipt_file) + receipts[0]["actions"][0] = "hold" if receipts[0]["actions"][0] == "deploy" else "deploy" + write_jsonl(receipt_file, receipts) + manifest_file = archive / "manifest.json" + manifest = json.loads(manifest_file.read_text(encoding="utf-8")) + from Agonist.gym import sha256_file + + manifest["artifacts"]["oracle_receipts.jsonl"]["sha256"] = sha256_file(receipt_file) + manifest_file.write_text(canonical(manifest) + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="independent recomputation disagrees"): + replay(archive) + + +def test_archived_eval_scores_are_dev_only_and_completely_paired(): + files, report = simulate(seed=21, updates=60) + scores = files["student_scores.jsonl"] + assert all(row["cohort"] == "evaluation" for row in scores) + assert all(row["checked_decisions"] == 3 for row in scores) + assert len({(row["root"], row["arm"], row["student_seed"]) for row in scores}) == len(scores) + assert set(report["paired"]) == { + "learned_minus_random", "learned_minus_fixed", "learned_minus_anchor_only" + } + for value in report["paired"].values(): + lo, hi = value["descriptive_root_bootstrap_95"] + assert -1 <= lo <= hi <= 1