Spaces:
Paused
Paused
Sync GitHub main e8a04aea24121d15707238534e635cf0ceee8eaf (part 7)
Browse filesFiles changed (30)
- scripts/run_stage1_reference_integrator_calibration.pyAdded+198
- scripts/run_stage1_reference_reset_calibration.pyAdded+143
- scripts/run_stage1_reference_synapse_calibration.pyAdded+174
- scripts/run_stage1_reference_topology_mapping_r2.pyAdded+108
- scripts/run_stage1_temporal_order_promotion_r1.pyAdded+316
- scripts/run_stage1_topology_efficiency_calibration.pyAdded+220
- scripts/run_stage1_topology_efficiency_r1.pyAdded+511
- scripts/run_stage1_topology_promotion_r1.pyAdded+242
- scripts/validate_playground_ptx.pyAdded+33
- scripts/verify_stage1_reference_dynamics_reuse_r2.pyAdded+138
- scripts/verify_stage1_temporal_order_promotion_r1.pyAdded+210
- scripts/verify_stage1_topology_efficiency_calibration.pyAdded+100
- scripts/verify_stage1_topology_efficiency_r1.pyAdded+138
- scripts/verify_stage1_topology_promotion_r1.pyAdded+166
- scripts/verify_stage1_topology_reference_r1.pyAdded+285
- scripts/verify_stage1_topology_reference_r2.pyAdded+285
- src/dashboard/file_manager.py+11-1
- src/dashboard/file_rendering.py+6-1
- src/dashboard/playground_api.pyAdded+253
- src/dashboard/server.py+45
- src/dashboard/static/file-viewer.js+1-1
- src/dashboard/static/formula-renderer.js+1-1
- src/dashboard/static/frontend/index.js+2
- src/dashboard/static/frontend/modules/playground.jsAdded
- src/dashboard/static/frontend/workspace-router.js+15-1
- src/dashboard/static/gate-board.js+30-2
- src/dashboard/static/index.html+28-1
- src/dashboard/static/scientific-progress.js+88-8
- src/dashboard/static/scientific-progress.json+21-17
- src/dashboard/static/styles.css+21-1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198#!/usr/bin/env python3"""Pre-freeze one-neuron parity calibration between MHRN and Brian2 reference."""
from __future__ import annotations
import hashlibimport jsonimport mathimport platformimport sysfrom pathlib import Path
import brian2
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from reference.stage1_topology_brian2.integrator_probe import ( run_one_tick, run_trajectory,)from src.core.neuron import NeuronConfig, create_neuron
ROOT = Path(__file__).resolve().parents[1]OUT = ROOT / "research" / "calibrations" / "CAL-S1-TOPO-REFERENCE-INTEGRATOR-R1"REFERENCE_PROBE = ROOT / "reference" / "stage1_topology_brian2" / "integrator_probe.py"NEURON_SOURCE = ROOT / "src" / "core" / "neuron.py"MODEL_SOURCE = ROOT / "src" / "core" / "neuron_models.py"
def sha256_file(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def run_mhrn_one_tick(current: float) -> dict[str, float | bool]: config = NeuronConfig( model="izhikevich-2003", dt_ms=1.0, a=0.02, b=0.2, c=-65.0, d=8.0, initial_v=-65.0, initial_u=-13.0, izhikevich_threshold=30.0, refractory_ticks=0, threshold_adaptation_rate=0.01, threshold_adaptation_decay=0.999, target_rate_hz=10.0, firing_rate_tau_ms=1000.0, homeostasis_learning_rate=0.001, enable_threshold_adaptation=True, enable_energy_dynamics=True, enable_traces=True, enable_homeostasis=True, ) neuron = create_neuron(1, config=config) spiked = neuron.step(float(current), 0) return { "v": neuron.v, "u": neuron.u, "threshold_adaptation": neuron.threshold_adaptation, "firing_rate_estimate": neuron.firing_rate_estimate, "spiked": spiked, }
def run_mhrn_trajectory(currents: list[float]) -> list[dict[str, float | bool]]: config = NeuronConfig( model="izhikevich-2003", dt_ms=1.0, a=0.02, b=0.2, c=-65.0, d=8.0, initial_v=-65.0, initial_u=-13.0, izhikevich_threshold=30.0, refractory_ticks=0, threshold_adaptation_rate=0.01, threshold_adaptation_decay=0.999, target_rate_hz=10.0, firing_rate_tau_ms=1000.0, homeostasis_learning_rate=0.001, enable_threshold_adaptation=True, enable_energy_dynamics=True, enable_traces=True, enable_homeostasis=True, ) neuron = create_neuron(1, config=config) rows: list[dict[str, float | bool]] = [] for tick, current in enumerate(currents): spiked = neuron.step(float(current), tick) rows.append( { "v": neuron.v, "u": neuron.u, "threshold_adaptation": neuron.threshold_adaptation, "firing_rate_estimate": neuron.firing_rate_estimate, "spiked": spiked, } ) return rows
def main() -> int: tolerance = 1e-12 cases = [] passed = True for current in (0.0, 100.0): mhrn = run_mhrn_one_tick(current) reference = run_one_tick(current).to_dict() diffs: dict[str, float] = {} case_pass = bool(mhrn["spiked"] == reference["spiked"]) for key in ("v", "u", "threshold_adaptation", "firing_rate_estimate"): diff = abs(float(mhrn[key]) - float(reference[key])) diffs[key] = diff case_pass = case_pass and math.isclose( float(mhrn[key]), float(reference[key]), rel_tol=0.0, abs_tol=tolerance ) passed = passed and case_pass cases.append( { "input_current": current, "mhrn": mhrn, "brian2_reference": reference, "absolute_differences": diffs, "pass": case_pass, } ) trajectory_currents = [100.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0] mhrn_trajectory = run_mhrn_trajectory(trajectory_currents) brian2_trajectory = [row.to_dict() for row in run_trajectory(trajectory_currents)] trajectory_cases = [] trajectory_pass = True for tick, (mhrn, reference) in enumerate( zip(mhrn_trajectory, brian2_trajectory, strict=True) ): diffs: dict[str, float] = {} tick_pass = bool(mhrn["spiked"] == reference["spiked"]) for key in ("v", "u", "threshold_adaptation", "firing_rate_estimate"): diff = abs(float(mhrn[key]) - float(reference[key])) diffs[key] = diff tick_pass = tick_pass and math.isclose( float(mhrn[key]), float(reference[key]), rel_tol=0.0, abs_tol=tolerance, ) trajectory_pass = trajectory_pass and tick_pass trajectory_cases.append( { "tick": tick, "input_current": trajectory_currents[tick], "mhrn": mhrn, "brian2_reference": reference, "absolute_differences": diffs, "pass": tick_pass, } ) if not any(bool(row["mhrn"]["spiked"]) for row in trajectory_cases): trajectory_pass = False passed = passed and trajectory_pass
payload = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-REFERENCE-INTEGRATOR-R1", "role": "pre-freeze method calibration; not confirmatory DATA and not EVID", "tolerance_abs": tolerance, "single_tick_cases": cases, "multi_tick": { "input_currents": trajectory_currents, "cases": trajectory_cases, "contains_spike": any( bool(row["mhrn"]["spiked"]) for row in trajectory_cases ), "pass": trajectory_pass, }, "provenance": { "python_version": sys.version, "platform": platform.platform(), "brian2_version": brian2.__version__, "reference_probe_sha256": sha256_file(REFERENCE_PROBE), "mhrn_neuron_source_sha256": sha256_file(NEURON_SOURCE), "mhrn_neuron_model_source_sha256": sha256_file(MODEL_SOURCE), }, "cases": cases, "pass": passed, } OUT.mkdir(parents=True, exist_ok=True) (OUT / "result.json").write_text( json.dumps(payload, indent=2) + "\n", encoding="utf-8" ) print(json.dumps({"status": "PASS" if passed else "FAIL", "cases": cases})) return 0 if passed else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143#!/usr/bin/env python3"""Explicit reset/post-spike parity calibration for Stage-1 Brian2 reference."""
from __future__ import annotations
import hashlibimport jsonimport mathimport platformimport sysfrom pathlib import Path
import brian2
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from reference.stage1_topology_brian2.integrator_probe import run_trajectoryfrom src.core.neuron import NeuronConfig, create_neuron
ROOT = Path(__file__).resolve().parents[1]OUT = ROOT / "research" / "calibrations" / "CAL-S1-TOPO-REFERENCE-RESET-R1"PROBE = ROOT / "reference" / "stage1_topology_brian2" / "integrator_probe.py"NEURON = ROOT / "src" / "core" / "neuron.py"MODELS = ROOT / "src" / "core" / "neuron_models.py"
def sha256_file(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def config() -> NeuronConfig: return NeuronConfig( model="izhikevich-2003", dt_ms=1.0, a=0.02, b=0.2, c=-65.0, d=8.0, initial_v=-65.0, initial_u=-13.0, izhikevich_threshold=30.0, refractory_ticks=0, threshold_adaptation_rate=0.01, threshold_adaptation_decay=0.999, target_rate_hz=10.0, firing_rate_tau_ms=1000.0, homeostasis_learning_rate=0.001, enable_threshold_adaptation=True, enable_energy_dynamics=True, enable_traces=True, enable_homeostasis=True, )
def mhrn_trajectory(currents: list[float]) -> list[dict[str, float | bool]]: neuron = create_neuron(1, config=config()) rows: list[dict[str, float | bool]] = [] for tick, current in enumerate(currents): spiked = neuron.step(float(current), tick) rows.append( { "v": neuron.v, "u": neuron.u, "threshold_adaptation": neuron.threshold_adaptation, "firing_rate_estimate": neuron.firing_rate_estimate, "spiked": spiked, } ) return rows
def main() -> int: tolerance = 1e-12 currents = [100.0, 0.0] mhrn = mhrn_trajectory(currents) reference = [row.to_dict() for row in run_trajectory(currents)]
checks: list[dict[str, object]] = [] passed = True for tick, (left, right) in enumerate(zip(mhrn, reference, strict=True)): diffs: dict[str, float] = {} tick_pass = bool(left["spiked"] == right["spiked"]) for key in ("v", "u", "threshold_adaptation", "firing_rate_estimate"): diff = abs(float(left[key]) - float(right[key])) diffs[key] = diff tick_pass = tick_pass and math.isclose( float(left[key]), float(right[key]), rel_tol=0.0, abs_tol=tolerance ) passed = passed and tick_pass checks.append( { "tick": tick, "input_current": currents[tick], "mhrn": left, "brian2_reference": right, "absolute_differences": diffs, "pass": tick_pass, } )
reset_semantics = { "spike_on_tick_0": bool(mhrn[0]["spiked"] and reference[0]["spiked"]), "reset_v_equals_c": bool( math.isclose(float(mhrn[0]["v"]), -65.0, abs_tol=tolerance) and math.isclose(float(reference[0]["v"]), -65.0, abs_tol=tolerance) ), "u_incremented_by_d_in_matching_state": bool( math.isclose( float(mhrn[0]["u"]), float(reference[0]["u"]), abs_tol=tolerance ) ), "next_tick_state_matches": bool(checks[1]["pass"]), } passed = passed and all(reset_semantics.values())
payload = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-REFERENCE-RESET-R1", "role": "pre-freeze method calibration; not confirmatory DATA and not EVID", "tolerance_abs": tolerance, "currents": currents, "cases": checks, "reset_semantics": reset_semantics, "provenance": { "python_version": sys.version, "platform": platform.platform(), "brian2_version": brian2.__version__, "reference_probe_sha256": sha256_file(PROBE), "mhrn_neuron_source_sha256": sha256_file(NEURON), "mhrn_neuron_model_source_sha256": sha256_file(MODELS), }, "pass": passed, } OUT.mkdir(parents=True, exist_ok=True) (OUT / "result.json").write_text( json.dumps(payload, indent=2) + "\n", encoding="utf-8" ) print(json.dumps({"status": "PASS" if passed else "FAIL"})) return 0 if passed else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174#!/usr/bin/env python3"""Two-neuron fixed-delay parity calibration for Stage-1 Brian2 reference."""
from __future__ import annotations
import hashlibimport jsonimport mathimport platformimport randomimport sysfrom pathlib import Path
import brian2
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from reference.stage1_topology_brian2.synapse_probe import run_two_neuron_delay_probefrom src.core.network import Brain5DConfig, NeuralNetwork, SimulationConfigfrom src.core.neuron import NeuronConfigfrom src.core.synapse import SynapseConfig
ROOT = Path(__file__).resolve().parents[1]OUT = ROOT / "research" / "calibrations" / "CAL-S1-TOPO-REFERENCE-SYNAPSE-R1"PROBE = ROOT / "reference" / "stage1_topology_brian2" / "synapse_probe.py"NETWORK = ROOT / "src" / "core" / "network.py"NEURON = ROOT / "src" / "core" / "neuron.py"
def sha256_file(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def neuron_config() -> NeuronConfig: return NeuronConfig( model="izhikevich-2003", dt_ms=1.0, a=0.02, b=0.2, c=-65.0, d=8.0, initial_v=-65.0, initial_u=-13.0, izhikevich_threshold=30.0, refractory_ticks=0, threshold_adaptation_rate=0.01, threshold_adaptation_decay=0.999, target_rate_hz=10.0, firing_rate_tau_ms=1000.0, homeostasis_learning_rate=0.001, enable_threshold_adaptation=True, enable_energy_dynamics=True, enable_traces=True, enable_homeostasis=True, )
def run_mhrn() -> list[dict[str, object]]: cfg = Brain5DConfig( dimensions=(2, 1, 1, 1, 1), simulation=SimulationConfig(dt_ms=1.0, max_delay=1), neuron=neuron_config(), synapse=SynapseConfig(w_min=0.0, w_max=200.0), ) net = NeuralNetwork(cfg, random.Random(1)) source = net.add_neuron((0, 0, 0, 0, 0)) target = net.add_neuron((1, 0, 0, 0, 0)) net.connect(source, target, weight=55.0, delay=1)
rows: list[dict[str, object]] = [] for tick in range(3): if tick == 0: net.inject_current(source, 100.0) result = net.step() rows.append( { "tick": tick, "source_spiked": source in result.spike_ids, "target_spiked": target in result.spike_ids, "delivered_events": result.delivered_events, "target_v": net.neurons[target].v, "target_u": net.neurons[target].u, "target_threshold_adaptation": net.neurons[target].threshold_adaptation, "target_firing_rate_estimate": net.neurons[target].firing_rate_estimate, } ) return rows
def main() -> int: tolerance = 1e-12 mhrn = run_mhrn() reference = [row.to_dict() for row in run_two_neuron_delay_probe()]
checks: list[dict[str, object]] = [] passed = True for tick in range(3): left = mhrn[tick] right = reference[tick] target = right["target"] diffs = { "target_v": abs(float(left["target_v"]) - float(target["v"])), "target_u": abs(float(left["target_u"]) - float(target["u"])), "target_threshold_adaptation": abs( float(left["target_threshold_adaptation"]) - float(target["threshold_adaptation"]) ), "target_firing_rate_estimate": abs( float(left["target_firing_rate_estimate"]) - float(target["firing_rate_estimate"]) ), } tick_pass = ( bool(left["source_spiked"]) == bool(right["source"]["spiked"]) and bool(left["target_spiked"]) == bool(target["spiked"]) and int(left["delivered_events"]) == int(right["delivered_events"]) and all( math.isclose(value, 0.0, rel_tol=0.0, abs_tol=tolerance) for value in diffs.values() ) ) passed = passed and tick_pass checks.append( { "tick": tick, "mhrn": left, "brian2_reference": right, "absolute_differences": diffs, "pass": tick_pass, } )
semantics = { "source_spikes_tick_0": bool(mhrn[0]["source_spiked"]), "no_delivery_tick_0": int(mhrn[0]["delivered_events"]) == 0, "one_delivery_tick_1": int(mhrn[1]["delivered_events"]) == 1, "reference_current_tick_1_is_55": math.isclose( float(reference[1]["target_synaptic_current"]), 55.0, rel_tol=0.0, abs_tol=tolerance, ), } passed = passed and all(semantics.values())
payload = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-REFERENCE-SYNAPSE-R1", "role": "pre-freeze method calibration; not confirmatory DATA and not EVID", "weight": 55.0, "delay_ticks": 1, "tolerance_abs": tolerance, "cases": checks, "event_semantics": semantics, "provenance": { "python_version": sys.version, "platform": platform.platform(), "brian2_version": brian2.__version__, "reference_probe_sha256": sha256_file(PROBE), "mhrn_network_source_sha256": sha256_file(NETWORK), "mhrn_neuron_source_sha256": sha256_file(NEURON), }, "pass": passed, } OUT.mkdir(parents=True, exist_ok=True) (OUT / "result.json").write_text( json.dumps(payload, indent=2) + "\n", encoding="utf-8" ) print(json.dumps({"status": "PASS" if passed else "FAIL"})) return 0 if passed else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108#!/usr/bin/env python3"""Executable R2 topology mapping parity gate; calibration only, never EVID."""
from __future__ import annotations
import hashlibimport jsonimport randomfrom pathlib import Pathfrom typing import Any
from reference.stage1_topology_brian2 import runner_r2 as referencefrom scripts.run_stage1_topology_v2 import ( canonical_coords, edge_list, read_json, shape_for,)
ROOT = Path(__file__).resolve().parents[1]CANON = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-PROMO-R1.json"PROTOCOL = ROOT / "reference" / "stage1_topology_brian2" / "reference_protocol_r2.json"OUT = ( ROOT / "research" / "calibrations" / "CAL-S1-TOPO-REFERENCE-TOPOLOGY-MAP-R2" / "result.json")PROBE_SEEDS = (820099901, 820099902, 820099903)
def sha(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def digest(value: Any) -> str: return hashlib.sha256( json.dumps(value, sort_keys=True, separators=(",", ":")).encode() ).hexdigest()
def main() -> int: canon = read_json(CANON) protocol = json.loads(PROTOCOL.read_text(encoding="utf-8")) out_degree = int(protocol["network"]["out_degree_cap"]) cases = [] for condition in protocol["conditions"]: shape = shape_for(canon, condition) for seed in PROBE_SEEDS: mc = canonical_coords(shape) if condition == "5d_shuffled": random.Random(seed ^ 0x5D5D5D).shuffle(mc) me = edge_list(canon, condition, seed, mc) rc, re = reference._graph(condition, shape, seed, out_degree) ok = mc == rc and me == re and len(me) == 246 cases.append( { "condition": condition, "probe_seed": seed, "coordinate_digest_mhrn": digest(mc), "coordinate_digest_reference": digest(rc), "edge_digest_mhrn": digest(me), "edge_digest_reference": digest(re), "coordinate_lists_exactly_equal": mc == rc, "edge_lists_exactly_equal": me == re, "edge_count": len(me), "pass": ok, } ) payload = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-REFERENCE-TOPOLOGY-MAP-R2", "role": "pre-freeze topology translation calibration; not confirmatory DATA and not EVID", "probe_seeds": list(PROBE_SEEDS), "evaluation_seed_overlap": False, "cases": cases, "source_sha256": { "scripts/run_stage1_topology_v2.py": sha( ROOT / "scripts" / "run_stage1_topology_v2.py" ), "reference/stage1_topology_brian2/runner_r2.py": sha( ROOT / "reference" / "stage1_topology_brian2" / "runner_r2.py" ), "reference/stage1_topology_brian2/reference_protocol_r2.json": sha( PROTOCOL ), }, "pass": all(c["pass"] for c in cases), } OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text( json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) print( json.dumps( { "calibration_id": payload["calibration_id"], "pass": payload["pass"], "cases": len(cases), } ) ) return 0 if payload["pass"] else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316#!/usr/bin/env python3"""Prospective promotion-eligible Stage-1 Temporal-Order replication.
The historical V2 task implementation is reused without rewriting its DATA.This wrapper executes fresh preregistered seeds and records the currentEvidenceEngine provenance contract. Execution creates DATA only."""
from __future__ import annotations
import hashlibimport importlib.utilimport jsonimport subprocessimport timefrom pathlib import Pathfrom typing import Any
import yaml
from src.research.experiment_recorder import ExperimentRecorderfrom src.research_assistant.governance import ( DataPartition, NetworkMode, ResearchRunMode,)
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TEMP-PROMO-R1.json"EXPERIMENT_ID = "EXP-S1-TEMP-PROMO-R1-20260927"OUT = ROOT / "research" / "experiments" / EXPERIMENT_IDCANDIDATE = ROOT / "scripts" / "run_stage1_temporal_order_v2.py"CONFIG = ROOT / "configs" / "learning_experiment.yaml"
HISTORICAL_SEEDS = ( set(range(101, 121)) | set(range(2101, 2121)) | set(range(6101, 6121)) | set(range(6201, 6221)) | set(range(6301, 6321)) | set(range(7101, 7121)))
def _sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def _sha256_file(path: Path) -> str: return _sha256_bytes(path.read_bytes())
def _canonical_digest(value: object) -> str: raw = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") return _sha256_bytes(raw)
def _tracked_source_digest() -> str: names = ( subprocess.check_output(["git", "ls-files", "-z"], cwd=ROOT) .decode() .split("\0") ) selected: dict[str, str] = {} include_exact = { "pyproject.toml", "configs/learning_experiment.yaml", "research/preregistrations/PREREG-S1-TEMP-PROMO-R1.json", } for name in names: if not name: continue if name.startswith(("src/", "scripts/")) or name in include_exact: selected[name] = _sha256_file(ROOT / name) return _canonical_digest(selected)
def _load_candidate() -> Any: spec = importlib.util.spec_from_file_location("stage1_temporal_order_v2", CANDIDATE) if spec is None or spec.loader is None: raise RuntimeError("cannot load run_stage1_temporal_order_v2.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.EXP_ID = EXPERIMENT_ID return module
def _write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", )
def _integrity( runs: list[dict[str, Any]], prereg: dict[str, Any], temporal: Any) -> dict[str, Any]: seeds = {int(v) for v in prereg["evaluation"]["seeds"]} checks = { "run_count": len(runs) == len(seeds) * len(temporal.ARMS) * len(temporal.ORDERS), "coverage": all( sum( int(r["seed"]) == seed and r["arm"] == arm and r["order"] == order for r in runs ) == 1 for seed in seeds for arm in temporal.ARMS for order in temporal.ORDERS ), "network_budget": all( int(r["node_count"]) == 6 and int(r["edge_count"]) == 4 for r in runs ), "paired_parameters": all( len( { ( round(float(r["synaptic_weight"]), 12), round(float(r["stimulus_current"]), 12), round(float(r["total_injected_charge"]), 12), ) for r in runs if int(r["seed"]) == seed } ) == 1 for seed in seeds ), "arm_set": {str(r["arm"]) for r in runs} == {"intact", "identity_destroyed"}, "order_set": {str(r["order"]) for r in runs} == {"forward", "reverse", "simultaneous"}, "historical_seed_disjoint": seeds.isdisjoint(HISTORICAL_SEEDS), "unique_seed_count": len(seeds) == len(prereg["evaluation"]["seeds"]) == 20, "matched_injected_charge": all( len( { round(float(r["total_injected_charge"]), 12) for r in runs if int(r["seed"]) == seed } ) == 1 for seed in seeds ), } return {"checks": checks, "pass": all(checks.values())}
def _report( prereg: dict[str, Any], analysis: dict[str, Any], integrity: dict[str, Any], run_count: int,) -> str: summary = analysis["summary"] ci = summary["paired_accuracy_delta_bootstrap_ci95"] return ( f"# {EXPERIMENT_ID}: Stage-1 Temporal-Order promotion R1\n\n" f"**Claim:** `{prereg['claim_id']}` \n" f"**RQ/H:** `{prereg['research_question']}` / `{prereg['hypothesis']}` \n" "**Role:** promotion-eligible DATA; no automatic EVID promotion \n" "**Independent replication:** false\n\n" "## Result\n\n" f"- status: `{analysis['status']}`\n" f"- design integrity: {integrity['pass']}\n" f"- evaluation runs: {run_count}\n" f"- intact order accuracy median: {summary['intact_order_accuracy_median']:.6g}\n" f"- identity-destroyed order accuracy median: " f"{summary['identity_destroyed_order_accuracy_median']:.6g}\n" f"- simultaneous control success: " f"{summary['intact_simultaneous_success_fraction']:.6g}\n" f"- paired accuracy delta median: {summary['paired_accuracy_delta_median']:.6g}\n" f"- paired delta CI95: [{ci[0]:.6g}, {ci[1]:.6g}]\n" f"- paired sign-test p: {summary['paired_sign_test_p']:.9g}\n\n" "## Claim boundary\n\n" f"{prereg['claim_boundary']}\n" )
def main() -> int: prereg = json.loads(PREREG.read_text(encoding="utf-8")) if prereg.get("status") != "FROZEN_BEFORE_PROMOTION_REPLICATION": raise RuntimeError("promotion preregistration is not frozen") if prereg.get("execution_authorized") is not True: raise RuntimeError("promotion replication is not authorized") if prereg.get("claim_id") != "CLAIM-S1-TEMP-001": raise RuntimeError("unexpected scoped claim") if prereg["evidence_engine_contract"]["automatic_evidence_promotion"]: raise RuntimeError("automatic EVID promotion must remain disabled") if OUT.exists(): raise FileExistsError(f"Refusing to overwrite existing experiment: {OUT}")
seeds = {int(seed) for seed in prereg["evaluation"]["seeds"]} if len(seeds) != len(prereg["evaluation"]["seeds"]): raise RuntimeError("evaluation seeds must be unique") if seeds & HISTORICAL_SEEDS: raise RuntimeError("promotion seeds overlap historical Stage-1 seeds")
recorder = ExperimentRecorder(EXPERIMENT_ID, output_dir=OUT, fail_fast=True) if recorder.manifest["git"].get("dirty") is not False: raise RuntimeError("promotion replication requires a clean git tree")
started = time.perf_counter() temporal = _load_candidate() config = yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
runs = [ temporal.simulate(config, prereg, int(seed), arm, order) for seed in prereg["evaluation"]["seeds"] for arm in temporal.ARMS for order in temporal.ORDERS ] analysis = temporal.analyze(runs, prereg) integrity = _integrity(runs, prereg, temporal) if not integrity["pass"]: analysis["status"] = "NOT_TESTED_INTEGRITY_FAILURE"
data_path = OUT / "data" / "evaluation.json" stats_path = OUT / "analysis" / "statistics.json" report_path = OUT / "report.md" _write_json(data_path, runs) _write_json( stats_path, { "schema_version": 1, "experiment_id": EXPERIMENT_ID, "claim_id": prereg["claim_id"], "protocol": prereg["protocol"], "analysis": analysis, "integrity": integrity, "claim_boundary": prereg["claim_boundary"], }, ) report_path.write_text( _report(prereg, analysis, integrity, len(runs)), encoding="utf-8" )
config_digest = _sha256_file(PREREG) prompt_digest = _sha256_bytes(b"NO_PROMPT_STAGE1_TEMPORAL_PROMOTION_R1") analysis_digest = _sha256_bytes( b"TEMP_V2_PAIRED_SIGN_TEST_BOOTSTRAP_IDENTITY_DESTROYED_CONTROL" ) code_digest = _tracked_source_digest() data_digest = _sha256_file(data_path)
recorder.record_config( str(PREREG.relative_to(ROOT)).replace("\\", "/"), config_digest ) recorder.record_research_links( research_questions=[prereg["research_question"]], hypotheses=[prereg["hypothesis"]], ) recorder.record_research_run_mode(ResearchRunMode.REPLICATION) recorder.record_network_mode(NetworkMode.OFFLINE) recorder.record_data_partition(DataPartition.SCIENTIFIC_HOLDOUT) recorder.lock_confirmatory_run( protocol=prereg, prompt_digest=prompt_digest, analysis_digest=analysis_digest, ) recorder.record_research_run_mode(ResearchRunMode.REPLICATION) recorder.record_simulation_params( seeds=sorted(seeds), dt_ms=1.0, neuron_count=6, edge_count=4, arms=list(temporal.ARMS), orders=list(temporal.ORDERS), ) recorder.record_artifact("evaluation_data", "data/evaluation.json") recorder.record_artifact("statistics", "analysis/statistics.json") recorder.record_artifact("report", "report.md") recorder.record_artifact( "preregistration", str(PREREG.relative_to(ROOT)).replace("\\", "/") ) recorder.record_provenance_digests( code_digest=code_digest, config_digest=config_digest, prompt_digest=prompt_digest, data_digest=data_digest, ) recorder.record_results( claim_id=prereg["claim_id"], protocol=prereg["protocol"], replication_class="INTERNAL_PROMOTION_REPLICATION", result_status=analysis["status"], design_integrity_passed=bool(integrity["pass"]), intact_order_accuracy_median=float( analysis["summary"]["intact_order_accuracy_median"] ), identity_destroyed_order_accuracy_median=float( analysis["summary"]["identity_destroyed_order_accuracy_median"] ), paired_accuracy_delta_median=float( analysis["summary"]["paired_accuracy_delta_median"] ), automatic_evidence_promotion=False, scientific_evidence=False, human_review_required=True, independent_authorship_replication=False, ) recorder.record_runtime(time.perf_counter() - started) recorder.mark_completed().save()
print((OUT / "manifest.json").read_text(encoding="utf-8")) if not integrity["pass"]: raise SystemExit("STAGE1_TEMPORAL_PROMOTION_INTEGRITY_FAILURE") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220#!/usr/bin/env python3"""Calibration-only runner for Stage-1 topology efficiency R1.
This is method-development/calibration DATA, not confirmatory evaluation and not EVID.It may run while the efficiency preregistration is DRAFT, but it must never read orexecute the evaluation seed block."""
from __future__ import annotations
import hashlibimport jsonimport statisticsfrom pathlib import Pathfrom typing import Any
from run_stage1_topology_v2 import build_network, load_config
from src.research.canonical_state import canonical_state_digest
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-EFFICIENCY-R1.json"OUT = ROOT / "research" / "calibrations" / "CAL-S1-TOPO-EFFICIENCY-R1-20260927"
def read_json(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise TypeError(path) return value
def write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", )
def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def _topology_prereg(prereg: dict[str, Any]) -> dict[str, Any]: adapted = dict(prereg) adapted["conditions"] = { "3d": prereg["conditions"]["3d_reference"]["shape"], "5d": prereg["conditions"]["5d_reference"]["shape"], "5d_shuffled": prereg["conditions"]["5d_shuffled"]["shape"], "random_graph": prereg["conditions"]["random_graph"]["shape"], } matched = dict(prereg["matched_budgets"]) matched["stimulus_current"] = float( prereg["calibration"]["reference_stimulus_current"] ) adapted["matched_budgets"] = matched return adapted
def simulate( config: dict[str, Any], prereg: dict[str, Any], graph_condition: str, seed: int, stimulus_current: float,) -> dict[str, Any]: weight = float(prereg["matched_budgets"]["synaptic_weight"]) network, neuron_ids, coords, edges = build_network( config, _topology_prereg(prereg), graph_condition, seed, weight ) before = canonical_state_digest(network) ticks = int(prereg["matched_budgets"]["evaluation_ticks"]) stimulus_ticks = int(prereg["matched_budgets"]["stimulus_ticks"]) input_labels = [int(v) for v in prereg["matched_budgets"]["stimulus_input_labels"]] output_labels = [int(v) for v in prereg["matched_budgets"]["output_labels"]] input_ids = [neuron_ids[label] for label in input_labels] output_ids = {neuron_ids[label] for label in output_labels}
active: set[int] = set() active_outputs: set[int] = set() total_spikes = 0 delivered_events = 0 for tick in range(ticks): if tick < stimulus_ticks: network.inject_current_batch( {neuron_id: stimulus_current for neuron_id in input_ids} ) result = network.step() spikes = {int(v) for v in result.spike_ids} total_spikes += int(result.spikes_this_tick) delivered_events += int(result.delivered_events) active.update(spikes) active_outputs.update(spikes & output_ids)
return { "graph_condition": graph_condition, "seed": seed, "stimulus_current": stimulus_current, "node_count": len(neuron_ids), "edge_count": len(edges), "final_active_fraction": len(active) / float(len(neuron_ids)), "output_reach_fraction": len(active_outputs) / float(len(output_ids)), "total_spikes": total_spikes, "delivered_events": delivered_events, "state_digest_before": before, "state_digest_after": canonical_state_digest(network), "edge_digest": hashlib.sha256(json.dumps(edges).encode()).hexdigest(), "coordinate_digest": hashlib.sha256(json.dumps(coords).encode()).hexdigest(), }
def summarize(rows: list[dict[str, Any]]) -> dict[str, float]: return { "n": len(rows), "final_active_fraction_median": float( statistics.median(float(row["final_active_fraction"]) for row in rows) ), "output_reach_fraction_median": float( statistics.median(float(row["output_reach_fraction"]) for row in rows) ), "delivered_events_median": float( statistics.median(float(row["delivered_events"]) for row in rows) ), "total_spikes_median": float( statistics.median(float(row["total_spikes"]) for row in rows) ), }
def choose_3d(summary: dict[str, dict[str, float]]) -> float | None: for current in sorted(map(float, summary)): row = summary[str(current)] if ( 0.84 <= row["final_active_fraction_median"] <= 0.90 and row["output_reach_fraction_median"] >= 0.95 and row["delivered_events_median"] >= 32 ): return current return None
def choose_5d(summary: dict[str, dict[str, float]]) -> float | None: for current in sorted(map(float, summary)): row = summary[str(current)] if ( row["final_active_fraction_median"] >= 0.98 and row["output_reach_fraction_median"] >= 0.95 and row["delivered_events_median"] >= 32 ): return current return None
def main() -> int: prereg = read_json(PREREG) if prereg.get("status") != "DRAFT_BEFORE_FREEZE": raise RuntimeError("calibration is allowed only while preregistration is DRAFT") if prereg.get("execution_authorized") is not False: raise RuntimeError( "confirmatory execution must remain unauthorized during calibration" ) if OUT.exists(): raise FileExistsError(f"Refusing to overwrite calibration: {OUT}")
calibration_seeds = list(map(int, prereg["calibration"]["seeds"])) evaluation_seeds = set(map(int, prereg["evaluation"]["seeds"])) if set(calibration_seeds) & evaluation_seeds: raise RuntimeError("calibration and evaluation seeds overlap")
currents = list(map(float, prereg["calibration"]["candidate_stimulus_currents"])) config = load_config() rows: list[dict[str, Any]] = [] for graph_condition in ("3d", "5d"): for current in currents: for seed in calibration_seeds: rows.append(simulate(config, prereg, graph_condition, seed, current))
by_graph: dict[str, dict[str, dict[str, float]]] = {"3d": {}, "5d": {}} for graph_condition in ("3d", "5d"): for current in currents: selected = [ row for row in rows if row["graph_condition"] == graph_condition and float(row["stimulus_current"]) == current ] by_graph[graph_condition][str(current)] = summarize(selected)
selected_3d = choose_3d(by_graph["3d"]) selected_5d = choose_5d(by_graph["5d"]) result = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-EFFICIENCY-R1-20260927", "preregistration_id": prereg["preregistration_id"], "role": "pre-freeze calibration only; not confirmatory DATA and not EVID", "calibration_seeds": calibration_seeds, "evaluation_seeds_read_or_executed": False, "candidate_stimulus_currents": currents, "summaries": by_graph, "selection": { "3d_recruitment_matched_stimulus_current": selected_3d, "5d_high_recruitment_stimulus_current": selected_5d, "3d_recruitment_matched_gate_passed": selected_3d is not None, "5d_high_recruitment_gate_passed": selected_5d is not None, }, "selection_inputs_excluded": prereg["calibration"][ "forbidden_selection_inputs" ], "preregistration_sha256": sha256(PREREG), }
write_json(OUT / "data" / "calibration.json", rows) write_json(OUT / "result.json", result) print(json.dumps(result["selection"], sort_keys=True)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511#!/usr/bin/env python3"""Confirmatory Stage-1 topology efficiency R1 evaluation.
Execution is impossible until calibration results and seed-freshness evidence arefrozen into the preregistration and explicit execution authorization is granted."""
from __future__ import annotations
import hashlibimport jsonimport mathimport statisticsimport subprocessimport timefrom pathlib import Pathfrom typing import Any
from run_stage1_topology_v2 import bootstrap_ci, build_network, holm, load_config
from src.research.canonical_state import canonical_state_digestfrom src.research.experiment_recorder import ExperimentRecorderfrom src.research_assistant.governance import ( DataPartition, NetworkMode, ResearchRunMode,)
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-EFFICIENCY-R1.json"EXPERIMENT_ID = "EXP-S1-TOPO-EFFICIENCY-R1-20260927"OUT = ROOT / "research" / "experiments" / EXPERIMENT_IDCALIBRATION = ROOT / "research" / "calibrations" / "CAL-S1-TOPO-EFFICIENCY-R1-20260927"CONFIG = ROOT / "configs" / "learning_experiment.yaml"
CONDITIONS = ( "3d_reference", "5d_reference", "5d_shuffled", "random_graph", "3d_recruitment_matched", "5d_high_recruitment",)PRIMARY_ENDPOINTS = ( "activation_auc_per_spike", "activation_auc_per_delivered_event",)
def _sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def _sha256_file(path: Path) -> str: return _sha256_bytes(path.read_bytes())
def _canonical_digest(value: object) -> str: raw = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") return _sha256_bytes(raw)
def _tracked_source_digest() -> str: names = ( subprocess.check_output(["git", "ls-files", "-z"], cwd=ROOT) .decode() .split("\0") ) selected: dict[str, str] = {} for name in names: if not name: continue if name.startswith(("src/", "scripts/")) or name in { "pyproject.toml", "configs/learning_experiment.yaml", "research/preregistrations/PREREG-S1-TOPO-EFFICIENCY-R1.json", }: selected[name] = _sha256_file(ROOT / name) return _canonical_digest(selected)
def _write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", )
def _topology_prereg(prereg: dict[str, Any]) -> dict[str, Any]: adapted = dict(prereg) adapted["conditions"] = { "3d": prereg["conditions"]["3d_reference"]["shape"], "5d": prereg["conditions"]["5d_reference"]["shape"], "5d_shuffled": prereg["conditions"]["5d_shuffled"]["shape"], "random_graph": prereg["conditions"]["random_graph"]["shape"], } matched = dict(prereg["matched_budgets"]) matched["stimulus_current"] = float( prereg["calibration"]["reference_stimulus_current"] ) adapted["matched_budgets"] = matched return adapted
def _graph_condition(condition: str) -> str: return { "3d_reference": "3d", "5d_reference": "5d", "5d_shuffled": "5d_shuffled", "random_graph": "random_graph", "3d_recruitment_matched": "3d", "5d_high_recruitment": "5d", }[condition]
def _stimulus_current(prereg: dict[str, Any], condition: str) -> float: if condition == "3d_recruitment_matched": return float( prereg["frozen_calibration"]["3d_recruitment_matched_stimulus_current"] ) if condition == "5d_high_recruitment": return float( prereg["frozen_calibration"]["5d_high_recruitment_stimulus_current"] ) return float(prereg["calibration"]["reference_stimulus_current"])
def simulate( config: dict[str, Any], prereg: dict[str, Any], condition: str, seed: int,) -> dict[str, Any]: graph_condition = _graph_condition(condition) current = _stimulus_current(prereg, condition) weight = float(prereg["matched_budgets"]["synaptic_weight"]) network, neuron_ids, coords, edges = build_network( config, _topology_prereg(prereg), graph_condition, seed, weight ) before = canonical_state_digest(network)
ticks = int(prereg["matched_budgets"]["evaluation_ticks"]) stimulus_ticks = int(prereg["matched_budgets"]["stimulus_ticks"]) input_labels = [int(v) for v in prereg["matched_budgets"]["stimulus_input_labels"]] output_labels = [int(v) for v in prereg["matched_budgets"]["output_labels"]] input_ids = [neuron_ids[label] for label in input_labels] output_ids = {neuron_ids[label] for label in output_labels} auc_window = int(prereg["matched_budgets"]["auc_window_ticks"])
active: set[int] = set() active_outputs: set[int] = set() cumulative_active_fraction: list[float] = [] total_spikes = 0 delivered_events = 0 first_output: int | None = None
for tick in range(ticks): if tick < stimulus_ticks: network.inject_current_batch({nid: current for nid in input_ids}) result = network.step() spikes = {int(v) for v in result.spike_ids} total_spikes += int(result.spikes_this_tick) delivered_events += int(result.delivered_events) active.update(spikes) output_spikes = spikes & output_ids active_outputs.update(output_spikes) if first_output is None and output_spikes: first_output = tick cumulative_active_fraction.append(len(active) / float(len(neuron_ids)))
auc = float(sum(cumulative_active_fraction[:auc_window])) auc_per_spike = auc / float(total_spikes) if total_spikes else math.inf auc_per_event = auc / float(delivered_events) if delivered_events else math.inf return { "condition": condition, "graph_condition": graph_condition, "seed": seed, "stimulus_current": current, "synaptic_weight": weight, "ticks": ticks, "node_count": len(neuron_ids), "edge_count": len(edges), "activation_auc_0_32": auc, "activation_auc_per_spike": auc_per_spike, "activation_auc_per_delivered_event": auc_per_event, "total_spikes": total_spikes, "delivered_events": delivered_events, "final_active_fraction": len(active) / float(len(neuron_ids)), "output_reach_fraction": len(active_outputs) / float(len(output_ids)), "first_output_latency_censored": ( first_output if first_output is not None else ticks + 1 ), "state_digest_before": before, "state_digest_after": canonical_state_digest(network), "edge_digest": hashlib.sha256(json.dumps(edges).encode()).hexdigest(), "coordinate_digest": hashlib.sha256(json.dumps(coords).encode()).hexdigest(), }
def _one_sided_sign_test_p(values: list[float]) -> float: nonzero = [value for value in values if abs(value) > 1e-12] if not nonzero: return 1.0 positives = sum(value > 0.0 for value in nonzero) return min( 1.0, sum(math.comb(len(nonzero), k) for k in range(positives, len(nonzero) + 1)) / (2 ** len(nonzero)), )
def _summaries(runs: list[dict[str, Any]]) -> dict[str, Any]: out: dict[str, Any] = {} for condition in CONDITIONS: rows = [row for row in runs if row["condition"] == condition] out[condition] = { "n": len(rows), "activation_auc_0_32_median": float( statistics.median(row["activation_auc_0_32"] for row in rows) ), "activation_auc_per_spike_median": float( statistics.median(row["activation_auc_per_spike"] for row in rows) ), "activation_auc_per_delivered_event_median": float( statistics.median( row["activation_auc_per_delivered_event"] for row in rows ) ), "total_spikes_median": float( statistics.median(row["total_spikes"] for row in rows) ), "delivered_events_median": float( statistics.median(row["delivered_events"] for row in rows) ), "final_active_fraction_median": float( statistics.median(row["final_active_fraction"] for row in rows) ), "first_output_latency_censored_median": float( statistics.median(row["first_output_latency_censored"] for row in rows) ), } return out
def _analyze(runs: list[dict[str, Any]], prereg: dict[str, Any]) -> dict[str, Any]: seeds = list(map(int, prereg["evaluation"]["seeds"])) lookup = {(row["condition"], int(row["seed"])): row for row in runs} tests: list[dict[str, Any]] = []
for endpoint in PRIMARY_ENDPOINTS: for contrast in prereg["evaluation"]["primary_contrasts"]: left = str(contrast["left"]) right = str(contrast["right"]) differences = [ float(lookup[(right, seed)][endpoint]) - float(lookup[(left, seed)][endpoint]) for seed in seeds ] boot_seed = int( hashlib.sha256( f"{EXPERIMENT_ID}:{endpoint}:{left}:{right}".encode() ).hexdigest()[:12], 16, ) tests.append( { "endpoint": endpoint, "contrast_label": contrast["label"], "contrast": [left, right], "difference_definition": "right-minus-left", "n_pairs": len(differences), "nonzero_pairs": sum(abs(v) > 1e-12 for v in differences), "positive_pairs": sum(v > 0.0 for v in differences), "median_difference": float(statistics.median(differences)), "bootstrap_median_difference_ci95": bootstrap_ci( differences, boot_seed ), "p_raw": _one_sided_sign_test_p(differences), } ) holm(tests) for row in tests: low, high = row["bootstrap_median_difference_ci95"] row["positive_ci"] = bool(low > 0.0 and high > 0.0) row["significant_positive"] = bool( float(row["p_holm"]) < float(prereg["evaluation"]["alpha"]) and row["positive_ci"] and float(row["median_difference"]) > 0.0 )
by_label: dict[str, dict[str, dict[str, Any]]] = {} for row in tests: by_label.setdefault(row["contrast_label"], {})[row["endpoint"]] = row
def passes(label: str) -> bool: return all( by_label[label][endpoint]["significant_positive"] for endpoint in PRIMARY_ENDPOINTS )
three_d = passes("5d_vs_3d_reference") shuffled = passes("5d_vs_5d_shuffled") random_graph = passes("5d_vs_random_graph") recruitment = passes("5d_vs_3d_recruitment_matched")
if not three_d: status = "REFUTES_WITHIN_PROTOCOL" decision_case = "C" elif not shuffled or not random_graph: status = "INCONCLUSIVE_SPECIFICITY" decision_case = "B_specificity" elif not recruitment: status = "REFUTES_WITHIN_PROTOCOL" decision_case = "B_recruitment" else: status = "SUPPORTED_WITHIN_PREREGISTERED_PROTOCOL" decision_case = "A"
return { "alpha": float(prereg["evaluation"]["alpha"]), "primary_test": "exact one-sided paired sign test", "primary_multiple_testing": prereg["evaluation"]["multiple_testing"], "primary_tests": tests, "decision_case": decision_case, "status": status, "exploratory_latency_only": True, }
def _integrity(runs: list[dict[str, Any]], prereg: dict[str, Any]) -> dict[str, Any]: seeds = set(map(int, prereg["evaluation"]["seeds"])) floor = prereg["evaluation"]["ratio_validity"] checks = { "run_count": len(runs) == len(CONDITIONS) * len(seeds), "coverage": all( sum( row["condition"] == condition and int(row["seed"]) == seed for row in runs ) == 1 for condition in CONDITIONS for seed in seeds ), "node_count": all(int(row["node_count"]) == 64 for row in runs), "edge_count": all( int(row["edge_count"]) == int(prereg["matched_budgets"]["expected_edge_count"]) for row in runs ), "spike_denominator_floor": all( int(row["total_spikes"]) >= int(floor["total_spikes_minimum_per_run"]) for row in runs ), "event_denominator_floor": all( int(row["delivered_events"]) >= int(floor["delivered_events_minimum_per_run"]) for row in runs ), "finite_ratios": all( math.isfinite(float(row["activation_auc_per_spike"])) and math.isfinite(float(row["activation_auc_per_delivered_event"])) for row in runs ), } return {"checks": checks, "pass": all(checks.values())}
def main() -> None: prereg = json.loads(PREREG.read_text(encoding="utf-8")) if prereg.get("status") != "FROZEN_BEFORE_EFFICIENCY_EVALUATION": raise RuntimeError("efficiency preregistration is not frozen for evaluation") if prereg.get("execution_authorized") is not True: raise RuntimeError("efficiency evaluation is not authorized") if prereg.get("claim_id") != "CLAIM-S1-EFFICIENCY-001": raise RuntimeError("unexpected scoped efficiency claim") if OUT.exists(): raise FileExistsError(f"Refusing to overwrite existing experiment: {OUT}")
frozen_calibration = prereg.get("frozen_calibration") seed_freeze = prereg.get("seed_freeze_record") if not isinstance(frozen_calibration, dict): raise RuntimeError("frozen calibration binding is missing") if ( not isinstance(seed_freeze, dict) or seed_freeze.get("collision_free") is not True ): raise RuntimeError("seed freshness freeze record is missing or failed") calibration_result = CALIBRATION / "result.json" if not calibration_result.is_file(): raise RuntimeError("calibration result is missing") if _sha256_file(calibration_result) != frozen_calibration.get("result_sha256"): raise RuntimeError("calibration result hash does not match frozen binding")
recorder = ExperimentRecorder(EXPERIMENT_ID, output_dir=OUT, fail_fast=True) if recorder.manifest["git"].get("dirty") is not False: raise RuntimeError("efficiency evaluation requires a clean git tree")
started = time.perf_counter() base_config = load_config() runs = [ simulate(base_config, prereg, condition, int(seed)) for seed in prereg["evaluation"]["seeds"] for condition in CONDITIONS ] summary = _summaries(runs) integrity = _integrity(runs, prereg) if integrity["pass"]: analysis = _analyze(runs, prereg) else: analysis = { "status": "NOT_TESTED_DENOMINATOR_VALIDITY", "decision_case": "NOT_TESTED", "primary_tests": [], "primary_multiple_testing": prereg["evaluation"]["multiple_testing"], }
data_path = OUT / "data" / "evaluation.json" stats_path = OUT / "analysis" / "statistics.json" report_path = OUT / "report.md" _write_json(data_path, runs) _write_json( stats_path, { "schema_version": 1, "experiment_id": EXPERIMENT_ID, "claim_id": prereg["claim_id"], "condition_summary": summary, "analysis": analysis, "integrity": integrity, "claim_boundary": prereg["claim_boundary"], }, ) report_path.write_text( ( f"# {EXPERIMENT_ID}\n\n" f"Status: `{analysis['status']}`\n\n" f"Decision case: `{analysis['decision_case']}`\n\n" f"Design integrity: {integrity['pass']}\n\n" "This execution creates DATA only. Human review and explicit EVID promotion " "remain separate.\n\n" f"## Claim boundary\n\n{prereg['claim_boundary']}\n" ), encoding="utf-8", )
config_digest = _sha256_file(PREREG) prompt_digest = _sha256_bytes(b"NO_PROMPT_STAGE1_TOPOLOGY_EFFICIENCY_R1") analysis_digest = _sha256_bytes( b"8_TEST_SINGLE_HOLM_ONE_SIDED_SIGN_PAIRED_RATIO_BOOTSTRAP_DECISION_ABC" ) recorder.record_config(str(PREREG.relative_to(ROOT)), config_digest) recorder.record_research_links( research_questions=[prereg["research_question"]], hypotheses=[prereg["hypothesis"]], ) recorder.record_research_run_mode(ResearchRunMode.CONFIRMATORY) recorder.record_network_mode(NetworkMode.OFFLINE) recorder.record_data_partition(DataPartition.SCIENTIFIC_HOLDOUT) recorder.lock_confirmatory_run( protocol=prereg, prompt_digest=prompt_digest, analysis_digest=analysis_digest, ) recorder.record_simulation_params( seeds=sorted(map(int, prereg["evaluation"]["seeds"])), dt_ms=1.0, neuron_count=64, edge_count=int(prereg["matched_budgets"]["expected_edge_count"]), ) recorder.record_artifact("evaluation_data", "data/evaluation.json") recorder.record_artifact("statistics", "analysis/statistics.json") recorder.record_artifact("report", "report.md") recorder.record_provenance_digests( code_digest=_tracked_source_digest(), config_digest=config_digest, prompt_digest=prompt_digest, data_digest=_sha256_file(data_path), ) recorder.record_results( claim_id=prereg["claim_id"], protocol=prereg["protocol"], result_status=analysis["status"], decision_case=analysis["decision_case"], design_integrity_passed=bool(integrity["pass"]), automatic_evidence_promotion=False, scientific_evidence=False, human_review_required=True, independent_authorship_replication=False, ) recorder.record_runtime(time.perf_counter() - started) recorder.mark_completed().save()
print( json.dumps( { "experiment_id": EXPERIMENT_ID, "status": analysis["status"], "decision_case": analysis["decision_case"], "runs": len(runs), "integrity": integrity["pass"], }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242#!/usr/bin/env python3"""Prospective promotion-eligible Stage-1 topology replication.
This runner reuses the already verified V3-R1 topology implementation but writesa new append-only experiment with fresh seeds and the current EvidenceEngineprovenance contract. Execution creates DATA only; EVID promotion is separate."""
from __future__ import annotations
import hashlibimport importlib.utilimport jsonimport subprocessimport timefrom pathlib import Pathfrom typing import Any
from src.research.experiment_recorder import ExperimentRecorderfrom src.research_assistant.governance import ( DataPartition, NetworkMode, ResearchRunMode,)
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-PROMO-R1.json"EXPERIMENT_ID = "EXP-S1-TOPO-PROMO-R1-20260927"OUT = ROOT / "research" / "experiments" / EXPERIMENT_IDCANDIDATE = ROOT / "scripts" / "run_stage1_topology_v3_r1.py"CONFIG = ROOT / "configs" / "learning_experiment.yaml"
HISTORICAL_SEEDS = ( set(range(2101, 2121)) | set(range(6101, 6121)) | set(range(6201, 6221)))
def _sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def _sha256_file(path: Path) -> str: return _sha256_bytes(path.read_bytes())
def _canonical_digest(value: object) -> str: raw = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") return _sha256_bytes(raw)
def _tracked_source_digest() -> str: names = ( subprocess.check_output(["git", "ls-files", "-z"], cwd=ROOT) .decode() .split("\0") ) selected: dict[str, str] = {} include_exact = { "pyproject.toml", "configs/learning_experiment.yaml", "research/preregistrations/PREREG-S1-TOPO-PROMO-R1.json", } for name in names: if not name: continue if name.startswith(("src/", "scripts/")) or name in include_exact: selected[name] = _sha256_file(ROOT / name) return _canonical_digest(selected)
def _load_candidate() -> Any: spec = importlib.util.spec_from_file_location("stage1_topology_v3_r1", CANDIDATE) if spec is None or spec.loader is None: raise RuntimeError("cannot load run_stage1_topology_v3_r1.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.EXP_ID = EXPERIMENT_ID return module
def _write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", )
def _report( prereg: dict[str, Any], summary: dict[str, Any], analysis: dict[str, Any], integrity: dict[str, Any],) -> str: return ( f"# {EXPERIMENT_ID}: Stage-1 topology promotion R1\n\n" f"**Claim:** `{prereg['claim_id']}` \n" f"**RQ/H:** `{prereg['research_question']}` / `{prereg['hypothesis']}` \n" "**Role:** promotion-eligible DATA; no automatic EVID promotion \n" "**Independent replication:** false\n\n" "## Result\n\n" f"- status: `{analysis['status']}`\n" f"- design integrity: {integrity['pass']}\n" f"- ceiling-resolution criterion: {analysis['ceiling_resolution_supported']}\n" f"- V2-latency replication criterion: {analysis['replication_supported']}\n" f"- evaluation runs: {sum(int(v['n']) for v in summary.values())}\n\n" "## Claim boundary\n\n" f"{prereg['interpretation_boundary']}\n" )
def main() -> None: prereg = json.loads(PREREG.read_text(encoding="utf-8")) if prereg.get("status") != "FROZEN_BEFORE_PROMOTION_REPLICATION": raise RuntimeError("promotion preregistration is not frozen") if prereg.get("execution_authorized") is not True: raise RuntimeError("promotion replication is not authorized") if prereg.get("claim_id") != "CLAIM-S1-TOPO-001": raise RuntimeError("unexpected scoped claim") if prereg["evidence_engine_contract"]["automatic_evidence_promotion"]: raise RuntimeError("automatic EVID promotion must remain disabled") if OUT.exists(): raise FileExistsError(f"Refusing to overwrite existing experiment: {OUT}")
seeds = {int(seed) for seed in prereg["evaluation"]["seeds"]} if len(seeds) != len(prereg["evaluation"]["seeds"]): raise RuntimeError("evaluation seeds must be unique") if seeds & HISTORICAL_SEEDS: raise RuntimeError("promotion seeds overlap historical topology seeds")
recorder = ExperimentRecorder(EXPERIMENT_ID, output_dir=OUT, fail_fast=True) if recorder.manifest["git"].get("dirty") is not False: raise RuntimeError("promotion replication requires a clean git tree")
started = time.perf_counter() topo = _load_candidate() base_config = topo.load_config()
evaluation: list[dict[str, Any]] = [] for seed in prereg["evaluation"]["seeds"]: for condition in topo.CONDITIONS: evaluation.append(topo.simulate(base_config, prereg, condition, int(seed)))
summary = topo.summarize(evaluation) analysis = topo.analyze(evaluation, prereg) integrity = topo.validate_design(prereg, evaluation) integrity.setdefault("checks", {})["all_historical_topology_seeds_disjoint"] = ( seeds.isdisjoint(HISTORICAL_SEEDS) ) integrity["pass"] = bool( integrity.get("pass") and integrity["checks"]["all_historical_topology_seeds_disjoint"] ) if not integrity["pass"]: analysis["status"] = "NOT_TESTED_INTEGRITY_FAILURE"
data_path = OUT / "data" / "evaluation.json" stats_path = OUT / "analysis" / "statistics.json" report_path = OUT / "report.md" _write_json(data_path, evaluation) _write_json( stats_path, { "schema_version": 1, "experiment_id": EXPERIMENT_ID, "claim_id": prereg["claim_id"], "protocol": prereg["protocol"], "condition_summary": summary, "analysis": analysis, "integrity": integrity, "claim_boundary": prereg["interpretation_boundary"], }, ) report_path.write_text( _report(prereg, summary, analysis, integrity), encoding="utf-8" )
config_digest = _sha256_file(PREREG) prompt_digest = _sha256_bytes(b"NO_PROMPT_STAGE1_TOPOLOGY_PROMOTION_R1") analysis_digest = _sha256_bytes(b"V3_R1_SINGLE_HOLM_10_PRIMARY_PLUS_HOLM_5_LATENCY") code_digest = _tracked_source_digest() data_digest = _sha256_file(data_path)
recorder.record_config( str(PREREG.relative_to(ROOT)).replace("\\", "/"), config_digest ) recorder.record_research_links( research_questions=[prereg["research_question"]], hypotheses=[prereg["hypothesis"]], ) recorder.record_research_run_mode(ResearchRunMode.REPLICATION) recorder.record_network_mode(NetworkMode.OFFLINE) recorder.record_data_partition(DataPartition.SCIENTIFIC_HOLDOUT) recorder.lock_confirmatory_run( protocol=prereg, prompt_digest=prompt_digest, analysis_digest=analysis_digest, ) recorder.record_research_run_mode(ResearchRunMode.REPLICATION) recorder.record_simulation_params( seeds=sorted(seeds), dt_ms=1.0, neuron_count=int(prereg["matched_budgets"]["neuron_count"]), edge_count=int(prereg["matched_budgets"]["expected_edge_count"]), ) recorder.record_artifact("evaluation_data", "data/evaluation.json") recorder.record_artifact("statistics", "analysis/statistics.json") recorder.record_artifact("report", "report.md") recorder.record_artifact( "preregistration", str(PREREG.relative_to(ROOT)).replace("\\", "/") ) recorder.record_provenance_digests( code_digest=code_digest, config_digest=config_digest, prompt_digest=prompt_digest, data_digest=data_digest, ) recorder.record_results( claim_id=prereg["claim_id"], protocol=prereg["protocol"], replication_class="INTERNAL_PROMOTION_REPLICATION", result_status=analysis["status"], design_integrity_passed=bool(integrity["pass"]), ceiling_resolution_supported=bool(analysis["ceiling_resolution_supported"]), replication_supported=bool(analysis["replication_supported"]), automatic_evidence_promotion=False, scientific_evidence=False, human_review_required=True, independent_authorship_replication=False, ) recorder.record_runtime(time.perf_counter() - started) recorder.mark_completed().save()
print((OUT / "manifest.json").read_text(encoding="utf-8")) if not integrity["pass"]: raise SystemExit("STAGE1_TOPOLOGY_PROMOTION_INTEGRITY_FAILURE")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233"""CI entry point for assembling generated Playground PTX with ptxas."""
from __future__ import annotations
import jsonfrom pathlib import Path
from src.playground.cuda import assemble_bundle, compile_mapping
def main() -> int: root = Path("build") / "playground-ptxas" results: dict[str, object] = {} for preset in ("minimal_closed_loop", "credit_assignment"): bundle = compile_mapping({"closed_loop_preset": preset}) report = assemble_bundle(bundle, output_dir=root / preset) if report.registers is None: raise RuntimeError(f"ptxas did not report register use for {preset}") results[preset] = { "gate_count": bundle.manifest["gate_count"], "registers": report.registers, "shared_bytes": report.shared_bytes, "constant_bytes": report.constant_bytes, "stack_bytes": report.stack_bytes, "spill_store_bytes": report.spill_store_bytes, "spill_load_bytes": report.spill_load_bytes, } print(json.dumps(results, indent=2, sort_keys=True)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138#!/usr/bin/env python3"""Validate immutable reuse of R1 dynamics parity artifacts for R2.
This writes an R2 method-validation artifact without modifying the historicalR1 integrator/reset/synapse calibration files."""
from __future__ import annotations
import hashlibimport jsonimport platformfrom pathlib import Pathfrom typing import Any
ROOT = Path(__file__).resolve().parents[1]INTEGRATOR = ( ROOT / "research/calibrations/CAL-S1-TOPO-REFERENCE-INTEGRATOR-R1/result.json")RESET = ROOT / "research/calibrations/CAL-S1-TOPO-REFERENCE-RESET-R1/result.json"SYNAPSE = ROOT / "research/calibrations/CAL-S1-TOPO-REFERENCE-SYNAPSE-R1/result.json"OUT = ROOT / "research/calibrations/CAL-S1-TOPO-REFERENCE-DYNAMICS-REUSE-R2/result.json"
def read(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise TypeError(path) return value
def sha(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def check_source(actual_path: str, expected: str) -> dict[str, Any]: path = ROOT / actual_path current = sha(path) return { "path": actual_path, "expected_sha256": expected, "current_sha256": current, "match": current == expected, }
def main() -> int: integ, reset, syn = map(read, (INTEGRATOR, RESET, SYNAPSE)) checks = [ check_source( "reference/stage1_topology_brian2/integrator_probe.py", str(integ["provenance"]["reference_probe_sha256"]), ), check_source( "src/core/neuron.py", str(integ["provenance"]["mhrn_neuron_source_sha256"]) ), check_source( "src/core/neuron_models.py", str(integ["provenance"]["mhrn_neuron_model_source_sha256"]), ), check_source( "reference/stage1_topology_brian2/integrator_probe.py", str(reset["provenance"]["reference_probe_sha256"]), ), check_source( "src/core/neuron.py", str(reset["provenance"]["mhrn_neuron_source_sha256"]) ), check_source( "src/core/neuron_models.py", str(reset["provenance"]["mhrn_neuron_model_source_sha256"]), ), check_source( "reference/stage1_topology_brian2/synapse_probe.py", str(syn["provenance"]["reference_probe_sha256"]), ), check_source( "src/core/network.py", str(syn["provenance"]["mhrn_network_source_sha256"]) ), check_source( "src/core/neuron.py", str(syn["provenance"]["mhrn_neuron_source_sha256"]) ), ] pass_value = bool( integ.get("pass") is True and integ.get("multi_tick", {}).get("pass") is True and integ.get("multi_tick", {}).get("contains_spike") is True and reset.get("pass") is True and syn.get("pass") is True and integ.get("provenance", {}).get("brian2_version") == "2.10.1" and reset.get("provenance", {}).get("brian2_version") == "2.10.1" and syn.get("provenance", {}).get("brian2_version") == "2.10.1" and all(item["match"] for item in checks) ) payload = { "schema_version": 1, "calibration_id": "CAL-S1-TOPO-REFERENCE-DYNAMICS-REUSE-R2", "role": "R2 pre-freeze source-hash revalidation of immutable R1 dynamics parity artifacts; not DATA and not EVID", "historical_artifacts": { "integrator": { "path": str(INTEGRATOR.relative_to(ROOT)), "sha256": sha(INTEGRATOR), "pass": integ.get("pass"), }, "reset": { "path": str(RESET.relative_to(ROOT)), "sha256": sha(RESET), "pass": reset.get("pass"), }, "synapse_delay": { "path": str(SYNAPSE.relative_to(ROOT)), "sha256": sha(SYNAPSE), "pass": syn.get("pass"), }, }, "source_hash_checks": checks, "python_version": platform.python_version(), "brian2_version": "2.10.1", "historical_artifacts_modified": False, "pass": pass_value, } OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text( json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) print( json.dumps( { "calibration_id": payload["calibration_id"], "pass": pass_value, "checks": len(checks), } ) ) return 0 if pass_value else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210#!/usr/bin/env python3"""Verify prospective Stage-1 Temporal-Order promotion DATA."""
from __future__ import annotations
import importlib.utilimport jsonfrom pathlib import Pathfrom typing import Any
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TEMP-PROMO-R1.json"EXPERIMENT_ID = "EXP-S1-TEMP-PROMO-R1-20260927"OUT = ROOT / "research" / "experiments" / EXPERIMENT_IDCANDIDATE = ROOT / "scripts" / "run_stage1_temporal_order_v2.py"
HISTORICAL_SEEDS = ( set(range(101, 121)) | set(range(2101, 2121)) | set(range(6101, 6121)) | set(range(6201, 6221)) | set(range(6301, 6321)) | set(range(7101, 7121)))
def _read(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def _load_candidate() -> Any: spec = importlib.util.spec_from_file_location("stage1_temporal_order_v2", CANDIDATE) if spec is None or spec.loader is None: raise RuntimeError("cannot load temporal-order V2 runner") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.EXP_ID = EXPERIMENT_ID return module
def _integrity( runs: list[dict[str, Any]], prereg: dict[str, Any], temporal: Any) -> dict[str, Any]: seeds = {int(v) for v in prereg["evaluation"]["seeds"]} checks = { "run_count": len(runs) == len(seeds) * len(temporal.ARMS) * len(temporal.ORDERS), "coverage": all( sum( int(r["seed"]) == seed and r["arm"] == arm and r["order"] == order for r in runs ) == 1 for seed in seeds for arm in temporal.ARMS for order in temporal.ORDERS ), "network_budget": all( int(r["node_count"]) == 6 and int(r["edge_count"]) == 4 for r in runs ), "paired_parameters": all( len( { ( round(float(r["synaptic_weight"]), 12), round(float(r["stimulus_current"]), 12), round(float(r["total_injected_charge"]), 12), ) for r in runs if int(r["seed"]) == seed } ) == 1 for seed in seeds ), "matched_injected_charge": all( len( { round(float(r["total_injected_charge"]), 12) for r in runs if int(r["seed"]) == seed } ) == 1 for seed in seeds ), "historical_seed_disjoint": seeds.isdisjoint(HISTORICAL_SEEDS), "unique_seed_count": len(seeds) == len(prereg["evaluation"]["seeds"]) == 20, "arm_set": {str(r["arm"]) for r in runs} == {"intact", "identity_destroyed"}, "order_set": {str(r["order"]) for r in runs} == {"forward", "reverse", "simultaneous"}, } return {"checks": checks, "pass": all(checks.values())}
def main() -> int: errors: list[str] = [] required = [ OUT / "manifest.json", OUT / "report.md", OUT / "data" / "evaluation.json", OUT / "analysis" / "statistics.json", ] for path in required: if not path.is_file(): errors.append(f"missing: {path.relative_to(ROOT)}") if errors: print(json.dumps({"status": "FAIL", "errors": errors}, indent=2)) return 1
prereg = _read(PREREG) manifest = _read(OUT / "manifest.json") runs_raw = _read(OUT / "data" / "evaluation.json") statistics = _read(OUT / "analysis" / "statistics.json") if not isinstance(runs_raw, list): errors.append("evaluation data is not a list") runs: list[dict[str, Any]] = [] else: runs = [dict(row) for row in runs_raw if isinstance(row, dict)]
if prereg.get("status") != "FROZEN_BEFORE_PROMOTION_REPLICATION": errors.append("preregistration was not frozen") if prereg.get("execution_authorized") is not True: errors.append("execution was not authorized") if prereg.get("claim_id") != "CLAIM-S1-TEMP-001": errors.append("claim id mismatch")
seeds = {int(seed) for seed in prereg["evaluation"]["seeds"]} if seeds & HISTORICAL_SEEDS: errors.append("promotion seeds overlap historical Stage-1 seeds") if len(seeds) != 20: errors.append("promotion requires 20 unique evaluation seeds")
temporal = _load_candidate() recomputed_analysis = temporal.analyze(runs, prereg) recomputed_integrity = _integrity(runs, prereg, temporal) if statistics.get("analysis") != recomputed_analysis: errors.append("analysis differs from deterministic recomputation") if statistics.get("integrity") != recomputed_integrity: errors.append("integrity differs from deterministic recomputation") if not recomputed_integrity["pass"]: errors.append("design integrity did not pass")
if manifest.get("experiment_id") != EXPERIMENT_ID: errors.append("manifest experiment id mismatch") if manifest.get("experiment_status") != "completed": errors.append("manifest is not completed") validity = manifest.get("validity", {}) if validity.get("valid") is not True: errors.append("manifest validity.valid is not true") if validity.get("runtime_error_count") != 0: errors.append("runtime_error_count is not zero") if validity.get("fatal_error_count") != 0: errors.append("fatal_error_count is not zero") if manifest.get("git", {}).get("dirty") is not False: errors.append("source tree was dirty before execution")
digests = manifest.get("provenance_digests") if not isinstance(digests, dict) or set(digests) != { "code", "config", "prompt", "data", }: errors.append("provenance_digests incomplete") elif any( not isinstance(value, str) or len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value) for value in digests.values() ): errors.append("invalid provenance digest format") freeze = manifest.get("source_freeze_sha") if not isinstance(freeze, str) or len(freeze) != 64: errors.append("source_freeze_sha missing or malformed")
results = manifest.get("results", {}) if results.get("claim_id") != "CLAIM-S1-TEMP-001": errors.append("manifest result claim mismatch") if results.get("automatic_evidence_promotion") is not False: errors.append("automatic EVID promotion must be false") if results.get("scientific_evidence") is not False: errors.append("execution incorrectly claims EVID") if results.get("human_review_required") is not True: errors.append("canonical human review is not required") if results.get("independent_authorship_replication") is not False: errors.append("internal promotion run incorrectly claims independence")
summary = recomputed_analysis["summary"] payload = { "status": "PASS" if not errors else "FAIL", "experiment_id": EXPERIMENT_ID, "claim_id": "CLAIM-S1-TEMP-001", "evaluation_runs": len(runs), "result_status": recomputed_analysis["status"], "design_integrity_passed": recomputed_integrity["pass"], "intact_order_accuracy_median": summary["intact_order_accuracy_median"], "identity_destroyed_order_accuracy_median": summary[ "identity_destroyed_order_accuracy_median" ], "paired_accuracy_delta_median": summary["paired_accuracy_delta_median"], "promotion_manifest_ready_for_human_review": not errors, "errors": errors, } print(json.dumps(payload, indent=2, sort_keys=True)) return 0 if not errors else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100#!/usr/bin/env python3"""Verify pre-freeze Stage-1 topology efficiency calibration."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
from run_stage1_topology_efficiency_calibration import ( OUT, PREREG, choose_3d, choose_5d, read_json, summarize,)
ROOT = Path(__file__).resolve().parents[1]
def main() -> int: errors: list[str] = [] result_path = OUT / "result.json" data_path = OUT / "data" / "calibration.json" for path in (result_path, data_path): if not path.is_file(): errors.append(f"missing: {path.relative_to(ROOT)}") if errors: print(json.dumps({"status": "FAIL", "errors": errors}, indent=2)) return 1
prereg = read_json(PREREG) result = read_json(result_path) rows_raw: Any = json.loads(data_path.read_text(encoding="utf-8")) rows = [dict(row) for row in rows_raw if isinstance(row, dict)]
seeds = list(map(int, prereg["calibration"]["seeds"])) currents = list(map(float, prereg["calibration"]["candidate_stimulus_currents"])) expected_runs = 2 * len(seeds) * len(currents) if len(rows) != expected_runs: errors.append(f"expected {expected_runs} calibration runs, got {len(rows)}")
if any( int(row["seed"]) in set(map(int, prereg["evaluation"]["seeds"])) for row in rows ): errors.append("evaluation seed appeared in calibration DATA")
for graph_condition in ("3d", "5d"): for current in currents: count = sum( row["graph_condition"] == graph_condition and float(row["stimulus_current"]) == current for row in rows ) if count != len(seeds): errors.append( f"coverage mismatch for {graph_condition} current={current}: {count}" )
if any(int(row["node_count"]) != 64 for row in rows): errors.append("calibration node_count mismatch") if any(int(row["edge_count"]) != 246 for row in rows): errors.append("calibration edge_count mismatch")
recomputed: dict[str, dict[str, dict[str, float]]] = {"3d": {}, "5d": {}} for graph_condition in ("3d", "5d"): for current in currents: selected = [ row for row in rows if row["graph_condition"] == graph_condition and float(row["stimulus_current"]) == current ] recomputed[graph_condition][str(current)] = summarize(selected)
if result.get("summaries") != recomputed: errors.append("calibration summaries differ from deterministic recomputation")
selected_3d = choose_3d(recomputed["3d"]) selected_5d = choose_5d(recomputed["5d"]) selection = result.get("selection", {}) if selection.get("3d_recruitment_matched_stimulus_current") != selected_3d: errors.append("3d recruitment-matched selection mismatch") if selection.get("5d_high_recruitment_stimulus_current") != selected_5d: errors.append("5d high-recruitment selection mismatch")
payload = { "status": "PASS" if not errors else "FAIL", "calibration_id": result.get("calibration_id"), "runs": len(rows), "selection": selection, "errors": errors, } print(json.dumps(payload, indent=2, sort_keys=True)) return 0 if not errors else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138#!/usr/bin/env python3"""Verify Stage-1 topology efficiency R1 confirmatory DATA."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
from run_stage1_topology_efficiency_r1 import ( CALIBRATION, CONDITIONS, EXPERIMENT_ID, OUT, PREREG, _analyze, _integrity, _sha256_file, _summaries,)
ROOT = Path(__file__).resolve().parents[1]
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def main() -> int: errors: list[str] = [] required = [ OUT / "manifest.json", OUT / "report.md", OUT / "data" / "evaluation.json", OUT / "analysis" / "statistics.json", PREREG, CALIBRATION / "result.json", ] for path in required: if not path.is_file(): errors.append(f"missing: {path.relative_to(ROOT)}") if errors: print(json.dumps({"status": "FAIL", "errors": errors}, indent=2)) return 1
prereg = read_json(PREREG) manifest = read_json(OUT / "manifest.json") runs_raw = read_json(OUT / "data" / "evaluation.json") statistics = read_json(OUT / "analysis" / "statistics.json") runs = [dict(row) for row in runs_raw if isinstance(row, dict)]
if prereg.get("status") != "FROZEN_BEFORE_EFFICIENCY_EVALUATION": errors.append("preregistration is not frozen") if prereg.get("execution_authorized") is not True: errors.append("execution is not authorized")
frozen_calibration = prereg.get("frozen_calibration", {}) if _sha256_file(CALIBRATION / "result.json") != frozen_calibration.get( "result_sha256" ): errors.append("frozen calibration hash mismatch") seed_freeze = prereg.get("seed_freeze_record", {}) if seed_freeze.get("collision_free") is not True: errors.append("seed freeze record is not collision-free")
if len(runs) != 120: errors.append(f"expected 120 evaluation runs, got {len(runs)}") seeds = set(map(int, prereg["evaluation"]["seeds"])) for condition in CONDITIONS: if sum(row["condition"] == condition for row in runs) != len(seeds): errors.append(f"condition coverage mismatch: {condition}")
recomputed_summary = _summaries(runs) recomputed_integrity = _integrity(runs, prereg) if recomputed_integrity["pass"]: recomputed_analysis = _analyze(runs, prereg) else: recomputed_analysis = { "status": "NOT_TESTED_DENOMINATOR_VALIDITY", "decision_case": "NOT_TESTED", "primary_tests": [], "primary_multiple_testing": prereg["evaluation"]["multiple_testing"], }
if statistics.get("condition_summary") != recomputed_summary: errors.append("condition summary differs from deterministic recomputation") if statistics.get("integrity") != recomputed_integrity: errors.append("integrity differs from deterministic recomputation") if statistics.get("analysis") != recomputed_analysis: errors.append("analysis differs from deterministic recomputation")
if recomputed_integrity["pass"] and len(recomputed_analysis["primary_tests"]) != 8: errors.append("primary Holm family does not contain exactly 8 tests")
if manifest.get("experiment_id") != EXPERIMENT_ID: errors.append("manifest experiment id mismatch") if manifest.get("experiment_status") != "completed": errors.append("manifest experiment status is not completed") if manifest.get("validity", {}).get("valid") is not True: errors.append("manifest validity.valid is not true") if manifest.get("validity", {}).get("runtime_error_count") != 0: errors.append("runtime_error_count is not zero") if manifest.get("validity", {}).get("fatal_error_count") != 0: errors.append("fatal_error_count is not zero") if manifest.get("git", {}).get("dirty") is not False: errors.append("source tree was dirty") if manifest.get("results", {}).get("scientific_evidence") is not False: errors.append("execution incorrectly claims EVID") if manifest.get("results", {}).get("automatic_evidence_promotion") is not False: errors.append("automatic EVID promotion is not false")
provenance = manifest.get("provenance_digests") if not isinstance(provenance, dict) or set(provenance) != { "code", "config", "prompt", "data", }: errors.append("provenance_digests incomplete") freeze = manifest.get("source_freeze_sha") if not isinstance(freeze, str) or len(freeze) != 64: errors.append("source_freeze_sha missing or malformed")
payload = { "status": "PASS" if not errors else "FAIL", "experiment_id": EXPERIMENT_ID, "result_status": recomputed_analysis["status"], "decision_case": recomputed_analysis["decision_case"], "runs": len(runs), "design_integrity_passed": recomputed_integrity["pass"], "errors": errors, } print(json.dumps(payload, indent=2, sort_keys=True)) return 0 if not errors else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166#!/usr/bin/env python3"""Verify the prospective Stage-1 topology promotion replication."""
from __future__ import annotations
import importlib.utilimport jsonfrom pathlib import Pathfrom typing import Any
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-PROMO-R1.json"EXPERIMENT_ID = "EXP-S1-TOPO-PROMO-R1-20260927"OUT = ROOT / "research" / "experiments" / EXPERIMENT_IDTOPOLOGY_RUNNER = ROOT / "scripts" / "run_stage1_topology_v3_r1.py"HISTORICAL_SEEDS = ( set(range(2101, 2121)) | set(range(6101, 6121)) | set(range(6201, 6221)))
def _read(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def _load_topology() -> Any: spec = importlib.util.spec_from_file_location( "stage1_topology_v3_r1", TOPOLOGY_RUNNER ) if spec is None or spec.loader is None: raise RuntimeError("cannot load topology runner") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.EXP_ID = EXPERIMENT_ID return module
def main() -> int: errors: list[str] = [] required = [ OUT / "manifest.json", OUT / "report.md", OUT / "data" / "evaluation.json", OUT / "analysis" / "statistics.json", ] for path in required: if not path.is_file(): errors.append(f"missing: {path.relative_to(ROOT)}") if errors: print(json.dumps({"status": "FAIL", "errors": errors}, indent=2)) return 1
prereg = _read(PREREG) manifest = _read(OUT / "manifest.json") evaluation_raw = _read(OUT / "data" / "evaluation.json") statistics = _read(OUT / "analysis" / "statistics.json")
if not isinstance(evaluation_raw, list): errors.append("evaluation data is not a list") evaluation: list[dict[str, Any]] = [] else: evaluation = [dict(row) for row in evaluation_raw if isinstance(row, dict)]
if prereg.get("status") != "FROZEN_BEFORE_PROMOTION_REPLICATION": errors.append("preregistration was not frozen") if prereg.get("execution_authorized") is not True: errors.append("execution was not authorized") if prereg.get("claim_id") != "CLAIM-S1-TOPO-001": errors.append("claim id mismatch")
seeds = {int(seed) for seed in prereg["evaluation"]["seeds"]} if seeds & HISTORICAL_SEEDS: errors.append("promotion seeds overlap historical topology seeds") if len(seeds) != 20: errors.append("promotion requires 20 unique evaluation seeds")
topo = _load_topology() recomputed_summary = topo.summarize(evaluation) recomputed_analysis = topo.analyze(evaluation, prereg) recomputed_integrity = topo.validate_design(prereg, evaluation) recomputed_integrity.setdefault("checks", {})[ "all_historical_topology_seeds_disjoint" ] = seeds.isdisjoint(HISTORICAL_SEEDS) recomputed_integrity["pass"] = bool( recomputed_integrity.get("pass") and recomputed_integrity["checks"]["all_historical_topology_seeds_disjoint"] )
if statistics.get("condition_summary") != recomputed_summary: errors.append("condition summary differs from deterministic recomputation") if statistics.get("analysis") != recomputed_analysis: errors.append("analysis differs from deterministic recomputation") if statistics.get("integrity") != recomputed_integrity: errors.append("integrity differs from deterministic recomputation") if not recomputed_integrity["pass"]: errors.append("design integrity did not pass")
if manifest.get("experiment_id") != EXPERIMENT_ID: errors.append("manifest experiment id mismatch") if manifest.get("experiment_status") != "completed": errors.append("manifest is not completed") validity = manifest.get("validity", {}) if validity.get("valid") is not True: errors.append("manifest validity.valid is not true") if validity.get("runtime_error_count") != 0: errors.append("runtime_error_count is not zero") if validity.get("fatal_error_count") != 0: errors.append("fatal_error_count is not zero") if manifest.get("git", {}).get("dirty") is not False: errors.append("source tree was dirty before execution")
digests = manifest.get("provenance_digests") if not isinstance(digests, dict) or set(digests) != { "code", "config", "prompt", "data", }: errors.append("provenance_digests incomplete") elif any( not isinstance(value, str) or len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value) for value in digests.values() ): errors.append("invalid provenance digest format") freeze = manifest.get("source_freeze_sha") if not isinstance(freeze, str) or len(freeze) != 64: errors.append("source_freeze_sha missing or malformed")
results = manifest.get("results", {}) if results.get("claim_id") != "CLAIM-S1-TOPO-001": errors.append("manifest result claim mismatch") if results.get("automatic_evidence_promotion") is not False: errors.append("automatic EVID promotion must be false") if results.get("scientific_evidence") is not False: errors.append("execution incorrectly claims EVID") if results.get("human_review_required") is not True: errors.append("canonical human review is not required") if results.get("independent_authorship_replication") is not False: errors.append("internal promotion run incorrectly claims independence")
human_review = OUT / "human_review.json" if human_review.exists(): review = _read(human_review) if review.get("experiment_id") != EXPERIMENT_ID: errors.append("human review experiment id mismatch") if review.get("decision") not in {"supports", "refutes", "inconclusive"}: errors.append("human review decision is not canonical")
payload = { "status": "PASS" if not errors else "FAIL", "experiment_id": EXPERIMENT_ID, "claim_id": "CLAIM-S1-TOPO-001", "evaluation_runs": len(evaluation), "result_status": recomputed_analysis["status"], "design_integrity_passed": recomputed_integrity["pass"], "promotion_manifest_ready_for_human_review": not errors, "human_review_present": human_review.exists(), "errors": errors, } print(json.dumps(payload, indent=2, sort_keys=True)) return 0 if not errors else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285#!/usr/bin/env python3"""Verifier for Stage-1 Brian2 cross-implementation reference DATA.
This verifier is intentionally separate from the blinded reference runner. Itmay read the canonical preregistration targets and classify persisted referenceDATA, but it never mutates EVID or maturity state automatically."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport randomimport statisticsfrom pathlib import Pathfrom typing import Any
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-REFERENCE-R1.json"
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def paired_sign_p(values: list[float]) -> float: nonzero = [value for value in values if abs(value) > 1e-12] n = len(nonzero) if n == 0: return 1.0 positive = sum(value > 0 for value in nonzero) extreme = min(positive, n - positive) one_tail = sum(math.comb(n, k) for k in range(0, extreme + 1)) / (2**n) return min(1.0, 2.0 * one_tail)
def bootstrap_median_ci(values: list[float], label: str) -> list[float]: if not values: return [0.0, 0.0] seed = int(hashlib.sha256(label.encode()).hexdigest()[:16], 16) rng = random.Random(seed) medians: list[float] = [] for _ in range(5000): sample = [values[rng.randrange(len(values))] for _ in values] medians.append(float(statistics.median(sample))) medians.sort() low_index = int(0.025 * (len(medians) - 1)) high_index = int(0.975 * (len(medians) - 1)) return [medians[low_index], medians[high_index]]
def holm(rows: list[dict[str, Any]]) -> None: ordered = sorted(enumerate(rows), key=lambda item: float(item[1]["p_raw"])) running = 0.0 m = len(rows) adjusted: dict[int, float] = {} for rank, (index, row) in enumerate(ordered): value = min(1.0, (m - rank) * float(row["p_raw"])) running = max(running, value) adjusted[index] = running for index, row in enumerate(rows): row["p_holm"] = adjusted[index]
def interval_relation(ci: list[float], bound: list[float]) -> str: low, high = map(float, ci) b_low, b_high = map(float, bound) if high < b_low or low > b_high: return "wholly_outside" if low >= b_low and high <= b_high: return "wholly_inside" return "spans_boundary"
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--data", required=True) parser.add_argument("--output", required=True) args = parser.parse_args()
prereg = read_json(PREREG) data_path = Path(args.data) output_path = Path(args.output) payload = read_json(data_path) if not isinstance(payload, dict): raise TypeError("reference DATA must be a JSON object")
expected_conditions = list(prereg["evaluation"]["conditions"]) expected_seeds = [int(v) for v in prereg["evaluation"]["seeds"]] runs_raw = payload.get("runs") runs = [dict(row) for row in runs_raw] if isinstance(runs_raw, list) else []
errors: list[str] = [] if payload.get("framework") != "Brian2": errors.append("framework mismatch") if str(payload.get("framework_version")) != str( prereg["independence_contract"]["framework_version"] ): errors.append("framework version mismatch") if payload.get("conditions") != expected_conditions: errors.append("condition list mismatch") if payload.get("seeds") != expected_seeds: errors.append("seed list mismatch") if len(runs) != 120: errors.append(f"expected 120 runs, got {len(runs)}")
lookup: dict[tuple[str, int], dict[str, Any]] = {} for row in runs: key = (str(row.get("condition")), int(row.get("seed", -1))) if key in lookup: errors.append(f"duplicate run {key}") lookup[key] = row if int(row.get("node_count", -1)) != 64: errors.append(f"node count mismatch {key}") if int(row.get("edge_count", -1)) != 246: errors.append(f"edge count mismatch {key}")
for condition in expected_conditions: for seed in expected_seeds: if (condition, seed) not in lookup: errors.append(f"missing run {(condition, seed)}")
primary_rows: list[dict[str, Any]] = [] bounds = prereg["canonical_targets"]["frozen_bounds"] canonical = prereg["canonical_targets"]["first_output_latency_median_deltas"]
for left, right in prereg["evaluation"]["primary_contrasts"]: label = f"{left}_to_{right}" differences = [ float(lookup[(right, seed)]["first_output_latency_censored"]) - float(lookup[(left, seed)]["first_output_latency_censored"]) for seed in expected_seeds if (left, seed) in lookup and (right, seed) in lookup ] median = float(statistics.median(differences)) if differences else 0.0 ci = bootstrap_median_ci(differences, f"latency:{label}") bound = [float(v) for v in bounds[label]] target = float(canonical[label]) canonical_sign = -1 if target < 0 else 1 direction_retained = median < 0 if canonical_sign < 0 else median > 0 in_bound = bound[0] <= median <= bound[1] row = { "label": label, "contrast": [left, right], "paired_differences": differences, "median_difference": median, "bootstrap_ci95": ci, "p_raw": paired_sign_p(differences), "canonical_sign": canonical_sign, "direction_retained": direction_retained, "equivalence_bound": bound, "median_inside_bound": in_bound, "ci_relation_to_bound": interval_relation(ci, bound), } primary_rows.append(row)
holm(primary_rows) alpha = float(prereg["evaluation"]["alpha"]) for row in primary_rows: ci = row["bootstrap_ci95"] row["ci_excludes_zero"] = bool(float(ci[1]) < 0 or float(ci[0]) > 0) row["holm_significant"] = bool(float(row["p_holm"]) < alpha) row["primary_criterion_pass"] = bool( row["direction_retained"] and row["median_inside_bound"] and row["holm_significant"] and row["ci_excludes_zero"] )
auc_expected = prereg["canonical_targets"]["activation_auc_direction_only"] auc_rows: list[dict[str, Any]] = [] for left, right in prereg["evaluation"]["primary_contrasts"]: label = f"{left}_to_{right}" differences = [ float(lookup[(right, seed)]["activation_auc_0_32"]) - float(lookup[(left, seed)]["activation_auc_0_32"]) for seed in expected_seeds if (left, seed) in lookup and (right, seed) in lookup ] median = float(statistics.median(differences)) if differences else 0.0 expected = str(auc_expected[label]) direction_match = median > 0 if expected == "positive" else median < 0 auc_rows.append( { "label": label, "median_difference": median, "expected_direction": expected, "direction_match": direction_match, } )
reversal_count = sum(not row["direction_retained"] for row in primary_rows) significant_count = sum(bool(row["holm_significant"]) for row in primary_rows) wholly_outside_count = sum( row["ci_relation_to_bound"] == "wholly_outside" for row in primary_rows ) spans_boundary_count = sum( row["ci_relation_to_bound"] == "spans_boundary" for row in primary_rows ) primary_pass_count = sum( bool(row["primary_criterion_pass"]) for row in primary_rows ) auc_match_count = sum(bool(row["direction_match"]) for row in auc_rows)
if errors: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "design_integrity_or_comparability_failure" elif reversal_count > 0: classification = "FAILED_REPLICATION" reason = "primary_direction_reversal" elif significant_count < 3: classification = "FAILED_REPLICATION" reason = "fewer_than_three_primary_contrasts_holm_significant" elif wholly_outside_count >= 2: classification = "FAILED_REPLICATION" reason = "two_or_more_primary_effects_wholly_outside_bounds" elif primary_pass_count == 5 and auc_match_count >= 4: classification = "PARTIAL_REPLICATION" reason = "all_primary_and_secondary_concordance_criteria_met" elif spans_boundary_count > 0: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "equivalence_boundary_spanned" elif primary_pass_count in (3, 4): classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "three_or_four_primary_criteria_met_without_reversal" elif wholly_outside_count == 1 and primary_pass_count == 4: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "one_primary_effect_wholly_outside_bound" else: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "predeclared_success_and_failure_rules_do_not_resolve_stably"
result = { "schema_version": 1, "preregistration_id": prereg["preregistration_id"], "reference_data": str(data_path), "design_integrity_passed": not errors, "integrity_errors": errors, "primary_endpoint": "first_output_latency_censored", "primary_tests": primary_rows, "secondary_auc_direction_checks": auc_rows, "summary": { "primary_direction_reversals": reversal_count, "holm_significant_primary": significant_count, "primary_wholly_outside_bounds": wholly_outside_count, "primary_spanning_bounds": spans_boundary_count, "primary_criteria_passed": primary_pass_count, "auc_direction_matches": auc_match_count, }, "classification": classification, "classification_reason": reason, "replication_credit_automatically_awarded": False, "scientific_evidence": False, "human_review_required": True, "maturity_update_automatic": False, "claim_boundary": ( "This verifier classifies only the preregistered project-side " "cross-implementation reference result. Even PARTIAL_REPLICATION " "cannot become EVID or Stage-1 maturity credit without separate " "human review and canonical state update." ), }
if output_path.exists(): raise FileExistsError(f"refusing to overwrite {output_path}") output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) print( json.dumps( { "classification": classification, "reason": reason, "design_integrity_passed": not errors, } ) ) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285#!/usr/bin/env python3"""Verifier for Stage-1 Brian2 cross-implementation reference DATA R2.
This verifier is intentionally separate from the blinded reference runner. Itmay read the canonical preregistration targets and classify persisted referenceDATA, but it never mutates EVID or maturity state automatically."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport randomimport statisticsfrom pathlib import Pathfrom typing import Any
ROOT = Path(__file__).resolve().parents[1]PREREG = ROOT / "research" / "preregistrations" / "PREREG-S1-TOPO-REFERENCE-R2.json"
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def paired_sign_p(values: list[float]) -> float: nonzero = [value for value in values if abs(value) > 1e-12] n = len(nonzero) if n == 0: return 1.0 positive = sum(value > 0 for value in nonzero) extreme = min(positive, n - positive) one_tail = sum(math.comb(n, k) for k in range(0, extreme + 1)) / (2**n) return min(1.0, 2.0 * one_tail)
def bootstrap_median_ci(values: list[float], label: str) -> list[float]: if not values: return [0.0, 0.0] seed = int(hashlib.sha256(label.encode()).hexdigest()[:16], 16) rng = random.Random(seed) medians: list[float] = [] for _ in range(5000): sample = [values[rng.randrange(len(values))] for _ in values] medians.append(float(statistics.median(sample))) medians.sort() low_index = int(0.025 * (len(medians) - 1)) high_index = int(0.975 * (len(medians) - 1)) return [medians[low_index], medians[high_index]]
def holm(rows: list[dict[str, Any]]) -> None: ordered = sorted(enumerate(rows), key=lambda item: float(item[1]["p_raw"])) running = 0.0 m = len(rows) adjusted: dict[int, float] = {} for rank, (index, row) in enumerate(ordered): value = min(1.0, (m - rank) * float(row["p_raw"])) running = max(running, value) adjusted[index] = running for index, row in enumerate(rows): row["p_holm"] = adjusted[index]
def interval_relation(ci: list[float], bound: list[float]) -> str: low, high = map(float, ci) b_low, b_high = map(float, bound) if high < b_low or low > b_high: return "wholly_outside" if low >= b_low and high <= b_high: return "wholly_inside" return "spans_boundary"
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--data", required=True) parser.add_argument("--output", required=True) args = parser.parse_args()
prereg = read_json(PREREG) data_path = Path(args.data) output_path = Path(args.output) payload = read_json(data_path) if not isinstance(payload, dict): raise TypeError("reference DATA must be a JSON object")
expected_conditions = list(prereg["evaluation"]["conditions"]) expected_seeds = [int(v) for v in prereg["evaluation"]["seeds"]] runs_raw = payload.get("runs") runs = [dict(row) for row in runs_raw] if isinstance(runs_raw, list) else []
errors: list[str] = [] if payload.get("framework") != "Brian2": errors.append("framework mismatch") if str(payload.get("framework_version")) != str( prereg["independence_contract"]["framework_version"] ): errors.append("framework version mismatch") if payload.get("conditions") != expected_conditions: errors.append("condition list mismatch") if payload.get("seeds") != expected_seeds: errors.append("seed list mismatch") if len(runs) != 120: errors.append(f"expected 120 runs, got {len(runs)}")
lookup: dict[tuple[str, int], dict[str, Any]] = {} for row in runs: key = (str(row.get("condition")), int(row.get("seed", -1))) if key in lookup: errors.append(f"duplicate run {key}") lookup[key] = row if int(row.get("node_count", -1)) != 64: errors.append(f"node count mismatch {key}") if int(row.get("edge_count", -1)) != 246: errors.append(f"edge count mismatch {key}")
for condition in expected_conditions: for seed in expected_seeds: if (condition, seed) not in lookup: errors.append(f"missing run {(condition, seed)}")
primary_rows: list[dict[str, Any]] = [] bounds = prereg["canonical_targets"]["frozen_bounds"] canonical = prereg["canonical_targets"]["first_output_latency_median_deltas"]
for left, right in prereg["evaluation"]["primary_contrasts"]: label = f"{left}_to_{right}" differences = [ float(lookup[(right, seed)]["first_output_latency_censored"]) - float(lookup[(left, seed)]["first_output_latency_censored"]) for seed in expected_seeds if (left, seed) in lookup and (right, seed) in lookup ] median = float(statistics.median(differences)) if differences else 0.0 ci = bootstrap_median_ci(differences, f"latency:{label}") bound = [float(v) for v in bounds[label]] target = float(canonical[label]) canonical_sign = -1 if target < 0 else 1 direction_retained = median < 0 if canonical_sign < 0 else median > 0 in_bound = bound[0] <= median <= bound[1] row = { "label": label, "contrast": [left, right], "paired_differences": differences, "median_difference": median, "bootstrap_ci95": ci, "p_raw": paired_sign_p(differences), "canonical_sign": canonical_sign, "direction_retained": direction_retained, "equivalence_bound": bound, "median_inside_bound": in_bound, "ci_relation_to_bound": interval_relation(ci, bound), } primary_rows.append(row)
holm(primary_rows) alpha = float(prereg["evaluation"]["alpha"]) for row in primary_rows: ci = row["bootstrap_ci95"] row["ci_excludes_zero"] = bool(float(ci[1]) < 0 or float(ci[0]) > 0) row["holm_significant"] = bool(float(row["p_holm"]) < alpha) row["primary_criterion_pass"] = bool( row["direction_retained"] and row["median_inside_bound"] and row["holm_significant"] and row["ci_excludes_zero"] )
auc_expected = prereg["canonical_targets"]["activation_auc_direction_only"] auc_rows: list[dict[str, Any]] = [] for left, right in prereg["evaluation"]["primary_contrasts"]: label = f"{left}_to_{right}" differences = [ float(lookup[(right, seed)]["activation_auc_0_32"]) - float(lookup[(left, seed)]["activation_auc_0_32"]) for seed in expected_seeds if (left, seed) in lookup and (right, seed) in lookup ] median = float(statistics.median(differences)) if differences else 0.0 expected = str(auc_expected[label]) direction_match = median > 0 if expected == "positive" else median < 0 auc_rows.append( { "label": label, "median_difference": median, "expected_direction": expected, "direction_match": direction_match, } )
reversal_count = sum(not row["direction_retained"] for row in primary_rows) significant_count = sum(bool(row["holm_significant"]) for row in primary_rows) wholly_outside_count = sum( row["ci_relation_to_bound"] == "wholly_outside" for row in primary_rows ) spans_boundary_count = sum( row["ci_relation_to_bound"] == "spans_boundary" for row in primary_rows ) primary_pass_count = sum( bool(row["primary_criterion_pass"]) for row in primary_rows ) auc_match_count = sum(bool(row["direction_match"]) for row in auc_rows)
if errors: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "design_integrity_or_comparability_failure" elif reversal_count > 0: classification = "FAILED_REPLICATION" reason = "primary_direction_reversal" elif significant_count < 3: classification = "FAILED_REPLICATION" reason = "fewer_than_three_primary_contrasts_holm_significant" elif wholly_outside_count >= 2: classification = "FAILED_REPLICATION" reason = "two_or_more_primary_effects_wholly_outside_bounds" elif primary_pass_count == 5 and auc_match_count >= 4: classification = "PARTIAL_REPLICATION" reason = "all_primary_and_secondary_concordance_criteria_met" elif spans_boundary_count > 0: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "equivalence_boundary_spanned" elif primary_pass_count in (3, 4): classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "three_or_four_primary_criteria_met_without_reversal" elif wholly_outside_count == 1 and primary_pass_count == 4: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "one_primary_effect_wholly_outside_bound" else: classification = "INCONCLUSIVE_REFERENCE_REPLICATION" reason = "predeclared_success_and_failure_rules_do_not_resolve_stably"
result = { "schema_version": 1, "preregistration_id": prereg["preregistration_id"], "reference_data": str(data_path), "design_integrity_passed": not errors, "integrity_errors": errors, "primary_endpoint": "first_output_latency_censored", "primary_tests": primary_rows, "secondary_auc_direction_checks": auc_rows, "summary": { "primary_direction_reversals": reversal_count, "holm_significant_primary": significant_count, "primary_wholly_outside_bounds": wholly_outside_count, "primary_spanning_bounds": spans_boundary_count, "primary_criteria_passed": primary_pass_count, "auc_direction_matches": auc_match_count, }, "classification": classification, "classification_reason": reason, "replication_credit_automatically_awarded": False, "scientific_evidence": False, "human_review_required": True, "maturity_update_automatic": False, "claim_boundary": ( "This verifier classifies only the preregistered project-side " "cross-implementation reference result. Even PARTIAL_REPLICATION " "cannot become EVID or Stage-1 maturity credit without separate " "human review and canonical state update." ), }
if output_path.exists(): raise FileExistsError(f"refusing to overwrite {output_path}") output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) print( json.dumps( { "classification": classification, "reason": reason, "design_integrity_passed": not errors, } ) ) return 0
if __name__ == "__main__": raise SystemExit(main())16 unmodified lines171819202122299 unmodified lines322323324325326327173 unmodified lines501502503504505506560 unmodified lines106710681069107010711072107316 unmodified linesfrom .docs_source import DocumentationSource, create_docs_sourcefrom .file_rendering import (FileContractError,atomic_write,file_is_read_only,299 unmodified linesdocs = self._docs or create_docs_source(self._default_docs_root)return docs, docs.docs_root, "docs"raise InvalidSourceError(f"Unknown source: {source}")def _root(self, source: str) -> Path:173 unmodified linesexcept FileManagerError:raise SourceNotAvailableError(f"Source '{source}' is not available.")candidate = (root / file_path).resolve()try:candidate.relative_to(root.resolve())560 unmodified lineshandler._send_json({"error": str(exc)}, exc.status)return Truefm = FileManager(research_source, docs_source, _DEFAULT_DOCS_ROOT)roots = {"docs": docs_source.docs_root if docs_source else _DEFAULT_DOCS_ROOT}if research_source is not None:roots["research"] = research_source.root()if handle_file_rendering(handler, path, query, roots):16 unmodified lines17181920212223299 unmodified lines323324325326327328329330331173 unmodified lines505506507508509510511512513560 unmodified lines107410751076107710781079108010811082108316 unmodified linesfrom .docs_source import DocumentationSource, create_docs_sourcefrom .file_rendering import (PROJECT_FILE_ALLOWLIST,FileContractError,atomic_write,file_is_read_only,299 unmodified linesdocs = self._docs or create_docs_source(self._default_docs_root)return docs, docs.docs_root, "docs"if source == "project":return None, self._default_docs_root.parent, "project"raise InvalidSourceError(f"Unknown source: {source}")def _root(self, source: str) -> Path:173 unmodified linesexcept FileManagerError:raise SourceNotAvailableError(f"Source '{source}' is not available.")if source == "project" and file_path not in PROJECT_FILE_ALLOWLIST:raise PathTraversalError("Project file is not exposed.")candidate = (root / file_path).resolve()try:candidate.relative_to(root.resolve())560 unmodified lineshandler._send_json({"error": str(exc)}, exc.status)return Truefm = FileManager(research_source, docs_source, _DEFAULT_DOCS_ROOT)roots = {"docs": docs_source.docs_root if docs_source else _DEFAULT_DOCS_ROOT,"project": _DEFAULT_DOCS_ROOT.parent,}if research_source is not None:roots["research"] = research_source.root()if handle_file_rendering(handler, path, query, roots):
32 unmodified lines333435363738237 unmodified lines27627727827928028128260 unmodified lines34334434534634734832 unmodified linesPREVIEW_BYTES = 256 * 1024EDIT_BYTES = 1024 * 1024DIGEST_BYTES = 64 * 1024 * 1024ARCHIVE_BYTES = 32 * 1024 * 1024MEDIA_PROBE_BYTES = 64 * 1024237 unmodified linesdef file_is_read_only(source: str, path: str) -> bool:"""Preserve scientific provenance even when a file is otherwise editable."""parts = PurePosixPath(path.replace("\\", "/")).partsreturn source == "research" and bool(parts and parts[0] in _PROTECTED_RESEARCH)def validate_file_write_access(handler: Any) -> None:60 unmodified lines"Path traversal is not allowed", HTTPStatus.FORBIDDEN)root = self.roots[source]candidate = (root / path).resolve()if not candidate.is_relative_to(root):raise FileContractError("Path escapes file source", HTTPStatus.FORBIDDEN)32 unmodified lines33343536373839237 unmodified lines27727827928028128228328428560 unmodified lines34634734834935035135235332 unmodified linesPREVIEW_BYTES = 256 * 1024EDIT_BYTES = 1024 * 1024PROJECT_FILE_ALLOWLIST = frozenset({"INDEPENDENT_REPLICATION.md"})DIGEST_BYTES = 64 * 1024 * 1024ARCHIVE_BYTES = 32 * 1024 * 1024MEDIA_PROBE_BYTES = 64 * 1024237 unmodified linesdef file_is_read_only(source: str, path: str) -> bool:"""Preserve scientific provenance even when a file is otherwise editable."""parts = PurePosixPath(path.replace("\\", "/")).partsreturn source == "project" or (source == "research" and bool(parts and parts[0] in _PROTECTED_RESEARCH))def validate_file_write_access(handler: Any) -> None:60 unmodified lines"Path traversal is not allowed", HTTPStatus.FORBIDDEN)root = self.roots[source]if source == "project" and path not in PROJECT_FILE_ALLOWLIST:raise FileContractError("Project file is not exposed", HTTPStatus.FORBIDDEN)candidate = (root / path).resolve()if not candidate.is_relative_to(root):raise FileContractError("Path escapes file source", HTTPStatus.FORBIDDEN)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253"""Dashboard adapter for the isolated non-canonical Playground."""
from __future__ import annotations
import threadingimport timefrom collections import dequefrom collections.abc import Mappingfrom typing import cast
from src.playground import servicefrom src.playground.cuda import compile_mappingfrom src.playground.models import PlaygroundConfigfrom src.playground.night_run import NightRunManagerfrom src.playground.pan import PANEmbodiedSandboxSession, PANSessionDaemon
_MAX_CONCURRENT_RUNS = 2_RUNS_PER_MINUTE = 20_RUN_WINDOW_SECONDS = 60.0
_RUN_SEMAPHORE = threading.BoundedSemaphore(_MAX_CONCURRENT_RUNS)_RATE_LOCK = threading.Lock()_RECENT_RUNS: deque[float] = deque()
def _payload_int( payload: Mapping[str, object], name: str, default: int,) -> int: value = payload.get(name, default) if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{name} must be numeric") converted = int(value) if float(value) != float(converted): raise ValueError(f"{name} must be an integer") return converted
def _payload_float( payload: Mapping[str, object], name: str, default: float,) -> float: value = payload.get(name, default) if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{name} must be numeric") return float(value)
def _payload_text( payload: Mapping[str, object], name: str, default: str,) -> str: value = payload.get(name, default) if not isinstance(value, str): raise ValueError(f"{name} must be a string") return value
def _numeric_list(value: object, name: str) -> list[float]: if not isinstance(value, list): raise ValueError(f"{name} must be a list") items = cast(list[object], value) result: list[float] = [] for item in items: if isinstance(item, bool) or not isinstance(item, (int, float)): raise ValueError(f"{name} entries must be numeric") result.append(float(item)) return result
_LIVE_DAEMON = PANSessionDaemon()_LIVE_SANDBOXES: dict[str, PANEmbodiedSandboxSession] = {}_LIVE_LOCK = threading.RLock()_NIGHT_RUN = NightRunManager()
class PlaygroundRateLimitError(RuntimeError): """Raised when the bounded Playground API rate is exceeded."""
class PlaygroundBusyError(RuntimeError): """Raised when all bounded Playground worker slots are occupied."""
def _reserve_rate_slot() -> None: now = time.monotonic() with _RATE_LOCK: cutoff = now - _RUN_WINDOW_SECONDS while _RECENT_RUNS and _RECENT_RUNS[0] < cutoff: _RECENT_RUNS.popleft() if len(_RECENT_RUNS) >= _RUNS_PER_MINUTE: raise PlaygroundRateLimitError( "Playground run rate exceeded; retry after the current minute window." ) _RECENT_RUNS.append(now)
def _bounded_run(path: str, payload: Mapping[str, object]) -> dict[str, object]: _reserve_rate_slot() if not _RUN_SEMAPHORE.acquire(blocking=False): raise PlaygroundBusyError( "Playground is busy; at most two simulation requests run concurrently." ) try: if path == "/api/playground/run": return service.run(payload) if path == "/api/playground/robustness": return service.robustness(payload) raise ValueError(f"unknown Playground POST route: {path}") finally: _RUN_SEMAPHORE.release()
def _live_parts(path: str) -> list[str]: prefix = "/api/playground/live/" if not path.startswith(prefix): return [] return [part for part in path[len(prefix) :].split("/") if part]
def get_playground(path: str) -> dict[str, object] | None: if path == "/api/playground/catalog": return service.catalog() if path == "/api/playground/sessions": return service.sessions() if path.startswith("/api/playground/sessions/"): session_id = path[len("/api/playground/sessions/") :] return service.replay(session_id) if path == "/api/playground/night": return _NIGHT_RUN.status() if path == "/api/playground/live": return { "class": "PLAYGROUND_LIVE_SESSIONS", "scientific_evidence": False, "sessions": _LIVE_DAEMON.list(), } parts = _live_parts(path) if len(parts) == 1: return {"session_id": parts[0], **_LIVE_DAEMON.get(parts[0]).snapshot()} return None
def post_playground( path: str, payload: Mapping[str, object]) -> dict[str, object] | None: if path in {"/api/playground/run", "/api/playground/robustness"}: return _bounded_run(path, payload)
if path == "/api/playground/determinism": return service.determinism(payload)
if path == "/api/playground/cuda/compile": target_sm = _payload_text(payload, "target_sm", "sm_86") ptx_version = _payload_text(payload, "ptx_version", "7.1") config_payload = dict(payload) config_payload.pop("target_sm", None) config_payload.pop("ptx_version", None) return compile_mapping( config_payload, target_sm=target_sm, ptx_version=ptx_version, ).to_mapping()
if path == "/api/playground/night/start": return _NIGHT_RUN.start( hours=_payload_float(payload, "hours", 8.0), max_episodes=_payload_int(payload, "max_episodes", 10_000), checkpoint_seconds=_payload_float(payload, "checkpoint_seconds", 600.0), seed=_payload_int(payload, "seed", 12345), ) if path == "/api/playground/night/stop": return _NIGHT_RUN.stop()
if path == "/api/playground/live/stop-all": with _LIVE_LOCK: _LIVE_SANDBOXES.clear() return _LIVE_DAEMON.stop_all()
if path == "/api/playground/live/create": config_payload = dict(payload) config_payload.setdefault("neuron_model", "pan_adex_5d") config_payload.setdefault("pan_enabled", True) config_payload.setdefault("thalamic_relay_threshold", 0.0) config_payload.setdefault("pan_bias_current", 10.0) config_payload.setdefault("behavior_target_mode", "cycle") config = PlaygroundConfig.from_mapping(config_payload) session_id = _LIVE_DAEMON.create(config) with _LIVE_LOCK: _LIVE_SANDBOXES[session_id] = PANEmbodiedSandboxSession( _LIVE_DAEMON.get(session_id) ) return { "class": "PLAYGROUND_LIVE_SESSION", "scientific_evidence": False, "session_id": session_id, "state": _LIVE_DAEMON.get(session_id).snapshot(), }
parts = _live_parts(path) if len(parts) >= 2: session_id, action = parts[0], parts[1] session = _LIVE_DAEMON.get(session_id) if action == "step": ticks = _payload_int(payload, "ticks", 32) return {"session_id": session_id, **session.step(ticks)} if action == "input": values = _numeric_list(payload.get("values", []), "values") duration = _payload_int(payload, "duration_ticks", 16) gain = _payload_float(payload, "gain", 25.0) session.inject_vector(values, duration_ticks=duration, gain=gain) return {"session_id": session_id, "accepted": True} if action == "strategy": context = _payload_text(payload, "context", "default") options = _payload_int(payload, "action_count", 4) chosen = session.choose_strategy(context, options) return { "session_id": session_id, "classification": "PLAYGROUND_META_STRATEGY", "scientific_evidence": False, "context": context, "action": chosen, "action_count": options, } if action == "reward": context = _payload_text(payload, "context", "default") chosen = _payload_int(payload, "action", 0) action_count = _payload_int(payload, "action_count", 4) reward = _payload_float(payload, "reward", 0.0) return { "session_id": session_id, **session.apply_strategy_reward( context=context, action=chosen, reward=reward, action_count=action_count, ), } if action == "sandbox": with _LIVE_LOCK: sandbox = _LIVE_SANDBOXES.get(session_id) if sandbox is None: sandbox = PANEmbodiedSandboxSession(session) _LIVE_SANDBOXES[session_id] = sandbox ticks = _payload_int(payload, "ticks", 1) return {"session_id": session_id, **sandbox.step(ticks)} if action == "stop": with _LIVE_LOCK: _LIVE_SANDBOXES.pop(session_id, None) return {"session_id": session_id, **_LIVE_DAEMON.stop(session_id)} return None119 unmodified lines120121122123124125187 unmodified lines313314315316317318498 unmodified lines8178188198208218224844 unmodified lines566756685669567056715672119 unmodified lines)from .network_inspector import NetworkInspectorfrom .operator_bridge import OperatorBridgefrom .release_timeline import build_release_timelinefrom .research_source import ResearchSource, create_research_sourcefrom .review_inbox import build_review_inbox187 unmodified linesquery = parse_qs(parsed.query)try:# ----------------------------------------------------------------# Debug / diagnostics# ----------------------------------------------------------------498 unmodified linespath = parsed.pathtry:# ----------------------------------------------------------------# Control API# ----------------------------------------------------------------4844 unmodified lines)returnif isinstance(exc,RuntimeError,119 unmodified lines120121122123124125126127128129130131187 unmodified lines319320321322323324325326327328329330331332333334335336498 unmodified lines8358368378388398408418428438448458468478488498508518528534844 unmodified lines56985699570057015702570357045705570657075708570957105711571257135714571557165717119 unmodified lines)from .network_inspector import NetworkInspectorfrom .operator_bridge import OperatorBridgefrom .playground_api import (PlaygroundBusyError,PlaygroundRateLimitError,get_playground,post_playground,)from .release_timeline import build_release_timelinefrom .research_source import ResearchSource, create_research_sourcefrom .review_inbox import build_review_inbox187 unmodified linesquery = parse_qs(parsed.query)try:# ----------------------------------------------------------------# Playground API — non-canonical, non-evidential# ----------------------------------------------------------------if path.startswith("/api/playground/"):payload = get_playground(path)if payload is None:self._send_api_not_found(path)else:self._send_json(cast(Mapping[str, JSONValue], payload))return# ----------------------------------------------------------------# Debug / diagnostics# ----------------------------------------------------------------498 unmodified linespath = parsed.pathtry:# ----------------------------------------------------------------# Playground API — non-canonical, non-evidential# ----------------------------------------------------------------if path.startswith("/api/playground/"):body = self._read_json_object()payload = post_playground(path, body)if payload is None:self._send_api_not_found(path)else:self._send_json(cast(Mapping[str, JSONValue], payload))return# ----------------------------------------------------------------# Control API# ----------------------------------------------------------------4844 unmodified lines)returnif isinstance(exc, PlaygroundRateLimitError):self._send_json({"error": str(exc)},HTTPStatus.TOO_MANY_REQUESTS,)returnif isinstance(exc, PlaygroundBusyError):self._send_json({"error": str(exc)},HTTPStatus.SERVICE_UNAVAILABLE,)returnif isinstance(exc,RuntimeError,
1082 unmodified lines10831084108510861087108810891082 unmodified lines}export function openBrain5DFile(source, path) {if (!['docs', 'research'].includes(source) || typeof path !== 'string') return Promise.resolve(null);initFileManager();fmCurrentSource = source;document.querySelectorAll('.fm-source-btn').forEach((button) => {1082 unmodified lines10831084108510861087108810891082 unmodified lines}export function openBrain5DFile(source, path) {if (!['docs', 'research', 'project'].includes(source) || typeof path !== 'string') return Promise.resolve(null);initFileManager();fmCurrentSource = source;document.querySelectorAll('.fm-source-btn').forEach((button) => {
123456"use strict";import "./scientific-progress.js";/*** Scientific formula renderer for dynamically opened Markdown files and the123456"use strict";import "./scientific-progress.js?v=scientific-register-20260927";/*** Scientific formula renderer for dynamically opened Markdown files and the
33 unmodified lines3435363738391 unmodified line41424344454633 unmodified linesimport { initSmallSNNStage } from "./modules/small-snn-stage.js";import { initRecurrentSNNStage } from "./modules/recurrent-snn-stage.js";import { initWorkspaceRouter } from "./workspace-router.js";import { initExternalReview } from "../external-review.js";installPollingGovernor();1 unmodified linefunction init() {initI18n();initWorkspaceRouter();// The legacy bootstrap may have created this panel before its mount existed.// Idempotent reattachment keeps the original listeners and metadata request.initExternalReview();33 unmodified lines343536373839401 unmodified line4243444546474833 unmodified linesimport { initSmallSNNStage } from "./modules/small-snn-stage.js";import { initRecurrentSNNStage } from "./modules/recurrent-snn-stage.js";import { initWorkspaceRouter } from "./workspace-router.js";import { initPlayground } from "./modules/playground.js";import { initExternalReview } from "../external-review.js";installPollingGovernor();1 unmodified linefunction init() {initI18n();initWorkspaceRouter();initPlayground();// The legacy bootstrap may have created this panel before its mount existed.// Idempotent reattachment keeps the original listeners and metadata request.initExternalReview();
48 unmodified lines49505152535428 unmodified lines8384858687888997 unmodified lines18718818919019119248 unmodified lines["data", "Daten", "network", "view", "data"], ["registry", "Registry", "research", "research", "registry"],],},wesen: {number: "03", label: "Runtime & Wesen", subtitle: "Körper & Verhalten", owner: "embodiment",purpose: "Runtime, Körpergrenze, Sensorik, Aktorik, Kognition und technische Identität in einer Arbeitsfläche.",28 unmodified linesroutes: [["overview", "Übersicht", "gate"], ["gate", "Gate", "gate", "release", "gate"], ["releases", "Releases", "gate", "release", "releases"],["preview", "Vorschau", "gate", "release", "preview"], ["timeline", "Timeline", "gate", "release", "timeline"],["development", "Entwicklung", "gate", "release", "development"], ["science", "Wissenschaft", "gate", "release", "science"],["documents", "Roadmap", "gate", "release", "documents"],],},97 unmodified lines}function ensureGeneratedWorkspaces() {const settings = createGeneratedWorkspace("appsettings", "Settings", "APPLICATION");if (settings && !byId("appsettings-content")) settings.insertAdjacentHTML("beforeend", `<div id="appsettings-content" class="mhrn-generated-panels">48 unmodified lines4950515253545556575859606162636465666728 unmodified lines9697989910010110297 unmodified lines20020120220320420520648 unmodified lines["data", "Daten", "network", "view", "data"], ["registry", "Registry", "research", "research", "registry"],],},playground: {number: "PG", label: "Playground", subtitle: "Exploration & Baukasten", owner: "playground",purpose: "Nicht-kanonische Exploration von Neuronen, Netzen, Hyperzuständen und PAN-Ideen unter harter Nicht-Evidenz-Grenze.",howto: ["Bausteine neutral kombinieren.", "PAN und andere Läufe nur explorativ interpretieren.", "Für Forschung neue Hypothese, Preregistration und kanonischen Lauf erzeugen."],contracts: ["/api/playground/catalog", "/api/playground/sessions"],routes: [["overview", "Übersicht", "playground"],["builder", "Builder", "playground", "generated", "builder"],["run", "Lauf & Auswertung", "playground", "generated", "run"],["sessions", "Sessions", "playground", "generated", "sessions"],["catalog", "Bausteine", "playground", "generated", "catalog"],],},wesen: {number: "03", label: "Runtime & Wesen", subtitle: "Körper & Verhalten", owner: "embodiment",purpose: "Runtime, Körpergrenze, Sensorik, Aktorik, Kognition und technische Identität in einer Arbeitsfläche.",28 unmodified linesroutes: [["overview", "Übersicht", "gate"], ["gate", "Gate", "gate", "release", "gate"], ["releases", "Releases", "gate", "release", "releases"],["preview", "Vorschau", "gate", "release", "preview"], ["timeline", "Timeline", "gate", "release", "timeline"],["development", "Entwicklung", "gate", "release", "development"], ["science", "Wissenschaft", "gate", "release", "science"], ["publication", "Gesamtarbeit", "gate", "release", "publication"],["documents", "Roadmap", "gate", "release", "documents"],],},97 unmodified lines}function ensureGeneratedWorkspaces() {createGeneratedWorkspace("playground", "Playground", "EXPLORATION · NON-CANONICAL");const settings = createGeneratedWorkspace("appsettings", "Settings", "APPLICATION");if (settings && !byId("appsettings-content")) settings.insertAdjacentHTML("beforeend", `<div id="appsettings-content" class="mhrn-generated-panels">
9 unmodified lines1011121314151611 unmodified lines2829303132333 unmodified lines373839404142486 unmodified lines52953053153253353453599 unmodified lines63563663763863964045 unmodified lines6866876886899 unmodified lines"use strict";import { openDocumentationFile } from './file-viewer.js';const $ = (id) => document.getElementById(id);11 unmodified linesunavailable: '—',error: '❌',};const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({'&': '&',3 unmodified lines"'": ''',}[character]));function renderLiveRuntime(items) {const container = $('gate-live-list');if (!container) return;486 unmodified lines${criteria.map((criterion) => `<div class="dev-criterion dev-criterion-${escapeHtml(criterion.status || 'missing')}"><span>${escapeHtml(criterion.label || criterion.id)}</span><strong>${escapeHtml(criterion.status || 'missing')}</strong>${Array.isArray(criterion.evidence) && criterion.evidence.length ? `<small>${escapeHtml(criterion.evidence.join(' · '))}</small>` : ''}</div>`).join('')}99 unmodified lines});}async function loadReleaseTimeline() {try {const response = await fetch('/api/releases/timeline', { cache: 'no-store' });45 unmodified linesloadReleaseTimeline();loadDevelopmentTimeline();bindReleaseDocumentLinks();}9 unmodified lines1011121314151611 unmodified lines282930313233343536373839404142433 unmodified lines47484950515253545556575859486 unmodified lines54654754854955055155299 unmodified lines65265365465565665765865966066166266366466566666745 unmodified lines7137147157167179 unmodified lines"use strict";import { openBrain5DFile, openDocumentationFile } from './file-viewer.js';const $ = (id) => document.getElementById(id);11 unmodified linesunavailable: '—',error: '❌',};const RELEASE_STATUS_MARKERS = {met: '✓',partial: '◐',open: '○',implemented: '✓',verified: '✓',experimental: '◐',planned: '○',missing: '○',};const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({'&': '&',3 unmodified lines"'": ''',}[character]));const releaseStatusMarkup = (status) => {const label = String(status ?? 'open');const key = label.toLowerCase();const marker = RELEASE_STATUS_MARKERS[key] || '·';return `<span class="release-status-mark release-status-${escapeHtml(key)}" aria-hidden="true">${marker}</span><span>${escapeHtml(label)}</span>`;};function renderLiveRuntime(items) {const container = $('gate-live-list');if (!container) return;486 unmodified lines${criteria.map((criterion) => `<div class="dev-criterion dev-criterion-${escapeHtml(criterion.status || 'missing')}"><span>${escapeHtml(criterion.label || criterion.id)}</span><strong class="release-status-value">${releaseStatusMarkup(criterion.status || 'missing')}</strong>${Array.isArray(criterion.evidence) && criterion.evidence.length ? `<small>${escapeHtml(criterion.evidence.join(' · '))}</small>` : ''}</div>`).join('')}99 unmodified lines});}let scientificWorkLinksBound = false;function bindScientificWorkLinks() {if (scientificWorkLinksBound) return;scientificWorkLinksBound = true;document.querySelectorAll('[data-scientific-work-file]').forEach((button) => {button.addEventListener('click', () => openBrain5DFile('research', button.dataset.scientificWorkFile || ''));});}async function loadReleaseTimeline() {try {const response = await fetch('/api/releases/timeline', { cache: 'no-store' });45 unmodified linesloadReleaseTimeline();loadDevelopmentTimeline();bindReleaseDocumentLinks();bindScientificWorkLinks();}
790 unmodified lines791792793794795796227 unmodified lines1024102510261027102810291030790 unmodified lines<aside class="development-detail" id="development-detail" hidden></aside></section><section class="release-view-panel release-documents-panel" data-release-view="documents" data-workspace-panel hidden aria-labelledby="release-documents-title"><div class="release-header"><span class="workspace-kicker">PROJECT SOURCES</span>227 unmodified lines<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/d3-graphviz/5.0.2/d3-graphviz.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script src="https://cdn.jsdelivr.net/npm/plantuml-encoder@1.4.0/dist/plantuml-encoder.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script type="module" src="/formula-renderer.js"></script><script type="module" src="/app.js?v=research-popup-20260920a"></script></body></html>790 unmodified lines791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823227 unmodified lines1051105210531054105510561057790 unmodified lines<aside class="development-detail" id="development-detail" hidden></aside></section><section class="release-view-panel scientific-work-panel scientific-progress-panel" data-release-view="publication" data-workspace-panel hidden aria-labelledby="scientific-work-title"><header class="scientific-progress-head"><div><span class="workspace-kicker">SCIENTIFIC MATURITY</span><h2 id="scientific-work-title">Wissenschaftliche Gesamtarbeit · 11 Teile</h2><p>Das vollständige integrierte Manuskript als wissenschaftliche Gesamtarbeit. Die Prozentwerte zeigen den redaktionellen Arbeitsstand; sie sind keine wissenschaftliche Evidenz- oder Kognitionskennzahl.</p></div><div class="scientific-progress-score"><span>Gesamtarbeitsstand</span><strong>87.3%</strong><small>redaktioneller Arbeitsstand</small></div></header><div class="scientific-progress-status-legend" aria-label="Statusmarker der Manuskriptteile"><span><b class="scientific-status-mark scientific-status-met">✓</b><span>met</span></span><span><b class="scientific-status-mark scientific-status-partial">◐</b><span>partial</span></span><span><b class="scientific-status-mark scientific-status-open">○</b><span>open</span></span></div><div class="scientific-two-axis-note"><div><strong>Wissenschaftliche Gesamtarbeit</strong><p>Entstehung · Forschungsobjekt · empirisches Programm · Methodik · Integrität · Synthese</p></div><div><strong>Arbeitsstand der 11 Teile</strong><p>met = redaktionell geschlossen · partial = weiter zu schärfen · open = offene Forschungslandschaft</p></div></div><div class="scientific-progress-legend"><span>Teil I–III · 100%</span><span>Teil IV–VII · 90–100%</span><span>Teil VIII–XI · 50–85%</span></div><div class="scientific-work-grid"><article class="scientific-work-card"><header><span>TEIL I</span><h3>Nullpunkt, Autor und Entstehungsbedingungen</h3></header><div class="scientific-work-metric scientific-work-met"><span>✓ met</span><strong>100%</strong></div><div class="scientific-work-bar"><span style="width:100%"></span></div><p>Ausgangspunkt, Autorschaft und Bedingungen der Entstehung.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL II</span><h3>Schaffensgeschichte und Architekturgenese</h3></header><div class="scientific-work-metric scientific-work-met"><span>✓ met</span><strong>100%</strong></div><div class="scientific-work-bar"><span style="width:100%"></span></div><p>Entwicklungsgeschichte und Entstehung der Architektur.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL III</span><h3>Forschungsobjekt MHRN</h3></header><div class="scientific-work-metric scientific-work-met"><span>✓ met</span><strong>100%</strong></div><div class="scientific-work-bar"><span style="width:100%"></span></div><p>Definition, Abgrenzung und Gegenstand des Forschungsobjekts.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL IV</span><h3>Empirisches Forschungsprogramm</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>90%</strong></div><div class="scientific-work-bar"><span style="width:90%"></span></div><p>Fragen, Hypothesen, Protokolle, DATA und Auswertung.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL V</span><h3>Wissenschaftliche Infrastruktur und Engineering</h3></header><div class="scientific-work-metric scientific-work-met"><span>✓ met</span><strong>100%</strong></div><div class="scientific-work-bar"><span style="width:100%"></span></div><p>Technische Infrastruktur als prüfbarer Teil der Forschungsarbeit.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL VI</span><h3>Epistemologie und Methodik der Schaffensgeschichte</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>90%</strong></div><div class="scientific-work-bar"><span style="width:90%"></span></div><p>Methodische Reflexion und epistemische Einordnung.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL VII</span><h3>Integrität, Autorschaft und kumulative Wissenschaft</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>90%</strong></div><div class="scientific-work-bar"><span style="width:90%"></span></div><p>Integrität, Attribution und wissenschaftliche Kumulation.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL VIII</span><h3>Philosophie, Ethik und Sicherheit</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>85%</strong></div><div class="scientific-work-bar"><span style="width:85%"></span></div><p>Philosophische Grenzen, Ethik und Sicherheitsbedingungen.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL IX</span><h3>Rekursive Epistemik</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>80%</strong></div><div class="scientific-work-bar"><span style="width:80%"></span></div><p>Das zentrale epistemische Modell der Gesamtarbeit.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL X</span><h3>Synthese und revidierbare Beiträge</h3></header><div class="scientific-work-metric scientific-work-partial"><span>◐ partial</span><strong>75%</strong></div><div class="scientific-work-bar"><span style="width:75%"></span></div><p>Synthese, Beiträge und Bedingungen ihrer Revision.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article><article class="scientific-work-card"><header><span>TEIL XI</span><h3>Offene Forschungslandschaft</h3></header><div class="scientific-work-metric scientific-work-open"><span>○ open</span><strong>50%</strong></div><div class="scientific-work-bar"><span style="width:50%"></span></div><p>Offene Fragen, Grenzen und nächste Forschungsrichtungen.</p><button type="button" data-scientific-work-file="publications/2026-09-17_recursive-epistemics_v1.8/MANUSCRIPT.md">Im Manuskript öffnen</button></article></div></section><section class="release-view-panel release-documents-panel" data-release-view="documents" data-workspace-panel hidden aria-labelledby="release-documents-title"><div class="release-header"><span class="workspace-kicker">PROJECT SOURCES</span>227 unmodified lines<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/d3-graphviz/5.0.2/d3-graphviz.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script src="https://cdn.jsdelivr.net/npm/plantuml-encoder@1.4.0/dist/plantuml-encoder.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script><script type="module" src="/formula-renderer.js?v=scientific-register-20260927"></script><script type="module" src="/app.js?v=research-popup-20260920a"></script></body></html>
1234566 unmodified lines13141516171830 unmodified lines4950515253545556575859606162636461 unmodified lines1261271281291301311321335 unmodified lines13914014114214314411 unmodified lines1561571581591601611621631641651661671681 unmodified line1701711721731741754 unmodified lines180181182183184185"use strict";const SCIENCE_MANIFEST_URL = "/scientific-progress.json";function escapeHtml(value) {return String(value ?? "").replace(/[&<>"']/g, (character) => ({6 unmodified linesreturn `${Number.isInteger(pct) ? pct.toFixed(0) : pct.toFixed(1)}%`;}function setVisible(element, visible) {if (!element) return;element.hidden = !visible;30 unmodified lines.scientific-progress-track{display:grid;grid-template-columns:repeat(11,minmax(86px,1fr));gap:7px;overflow-x:auto;padding:5px 0 10px}.scientific-stage-node{display:grid;grid-template-rows:auto auto auto auto;gap:5px;text-align:left;padding:9px;border:1px solid var(--rule);border-radius:8px;background:var(--paper);color:inherit;cursor:pointer}.scientific-stage-node:hover,.scientific-stage-node:focus-visible,.scientific-stage-node.is-selected{outline:2px solid var(--accent);outline-offset:1px}.scientific-stage-number{font-size:.72rem;opacity:.75}.scientific-stage-name{font-size:.78rem;font-weight:700;line-height:1.2;min-height:2.4em}.scientific-stage-bar{height:6px;background:var(--paper-3,#d9d9d9);border-radius:999px;overflow:hidden}.scientific-stage-fill{display:block;height:100%;background:currentColor;opacity:.7}.scientific-stage-meta{display:flex;justify-content:space-between;gap:4px;font-size:.68rem;opacity:.8}.scientific-progress-legend{display:flex;flex-wrap:wrap;gap:7px;margin:8px 0}.scientific-progress-legend span{padding:4px 7px;border:1px solid var(--rule);border-radius:999px;font-size:.72rem}.scientific-progress-detail{margin-top:12px;padding:13px;border-top:1px solid var(--rule)}.scientific-progress-detail h4{margin:.2rem 0}.scientific-progress-boundary{padding:9px;border-left:3px solid var(--accent);background:var(--paper)}.scientific-criteria{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px;margin:10px 0}.scientific-criterion{padding:8px;border:1px solid var(--rule);border-radius:7px}.scientific-criterion strong{float:right}.scientific-criterion small{display:block;clear:both;margin-top:5px;opacity:.75;overflow-wrap:anywhere}.scientific-integrity-note{margin-top:10px;font-size:.78rem;opacity:.85}.scientific-two-axis-note{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.scientific-two-axis-note>div{padding:10px;border:1px solid var(--rule);border-radius:8px;background:var(--paper)}@media(max-width:900px){.scientific-progress-head{display:block}.scientific-progress-score{text-align:left;margin-top:8px}.scientific-progress-track{grid-template-columns:repeat(11,110px)}.scientific-two-axis-note{grid-template-columns:1fr}}`;document.head.appendChild(style);}61 unmodified linesfunction criterionMarkup(criterion) {const sources = Array.isArray(criterion.sources) ? criterion.sources : [];return `<div class="scientific-criterion" data-status="${escapeHtml(criterion.status)}"><span>${escapeHtml(criterion.label || criterion.id)}</span><strong>${escapeHtml(criterion.status)}</strong>${sources.length ? `<small>${sources.map(escapeHtml).join(" · ")}</small>` : "<small>kein evidenztragender Nachweis eingetragen</small>"}</div>`;}5 unmodified lines<h4>${escapeHtml(stage.name)} · ${percent(stage.score)}</h4><p class="scientific-progress-boundary"><strong>Claim-Grenze:</strong> ${escapeHtml(stage.claim_boundary)}</p><div class="scientific-criteria">${criteria.map(criterionMarkup).join("")}</div><h5>Nächste wissenschaftliche Schritte</h5><ul>${next.map((item) => `<li>${escapeHtml(item)}</li>`).join("")}</ul></div>`;11 unmodified lines<div><span class="workspace-kicker">SCIENTIFIC MATURITY</span><h2 id="scientific-progress-title">Wissenschaftliche Timeline · Stufen 0–10</h2><p>${escapeHtml(data.scope_note)}</p></div><div class="scientific-progress-score"><span>Stage-Mittel</span><strong>${percent(overall)}</strong><small>keine Kognitionskennzahl</small></div></header><div class="scientific-two-axis-note"><div><strong>Technische Timeline</strong><p>Implementierung · Integration · Verification · Runtime/Persistenz</p></div><div><strong>Wissenschaftliche Timeline</strong><p>RQ/Hypothese · Protokoll · DATA · reviewte EVID · Replikation · Attribution</p></div></div><div class="scientific-progress-legend"><span>RQ 15%</span><span>Protokoll 20%</span><span>DATA 20%</span><span>reviewte EVID 20%</span><span>Replikation 15%</span><span>Attribution 10%</span></div><div class="scientific-progress-track" role="list" aria-label="Wissenschaftliche Reife je Entwicklungsstufe">${stages.map((stage) => `<button type="button" class="scientific-stage-node ${stage.stage === 6 ? "is-selected" : ""}" data-scientific-stage="${stage.stage}" role="listitem" title="Stufe ${stage.stage}: ${escapeHtml(stage.name)}"><span class="scientific-stage-number">STUFE ${stage.stage}</span><span class="scientific-stage-name">${escapeHtml(stage.name)}</span><span class="scientific-stage-bar"><span class="scientific-stage-fill" style="width:${percent(stage.score)}"></span></span><span class="scientific-stage-meta"><b>${percent(stage.score)}</b><em>${escapeHtml(stage.status)}</em></span></button>`).join("")}</div><div id="scientific-progress-detail">${stages.length ? detailMarkup(stages.find((stage) => stage.stage === 6) || stages[0]) : ""}</div>1 unmodified line</section>`;host.addEventListener("click", (event) => {const button = event.target.closest("[data-scientific-stage]");if (!button) return;host.querySelectorAll(".scientific-stage-node").forEach((node) => node.classList.toggle("is-selected", node === button));4 unmodified lines}async function loadScientificProgress() {try {const response = await fetch(SCIENCE_MANIFEST_URL, { cache: "no-store" });if (!response.ok) throw new Error(`HTTP ${response.status}`);123456789106 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848530 unmodified lines11611711811912012112212312412512612712812913013113213313461 unmodified lines1961971981992002012022035 unmodified lines20921021121221321421511 unmodified lines2272282292302312322332342352362372382392401 unmodified line2422432442452462472482492502512522532544 unmodified lines259260261262263264265"use strict";const SCIENCE_MANIFEST_URL = "/scientific-progress.json";const SCIENTIFIC_STATUS_MARKERS = {met: "✓", partial: "◐", open: "○",advanced: "✓", active: "◐", early: "◐", planned: "○", frontier: "○",};function escapeHtml(value) {return String(value ?? "").replace(/[&<>"']/g, (character) => ({6 unmodified linesreturn `${Number.isInteger(pct) ? pct.toFixed(0) : pct.toFixed(1)}%`;}function statusMarkup(status) {const label = String(status ?? "open");const key = label.toLowerCase();const marker = SCIENTIFIC_STATUS_MARKERS[key] || "·";const classKey = Object.prototype.hasOwnProperty.call(SCIENTIFIC_STATUS_MARKERS, key) ? key : "unknown";return `<span class="scientific-status-mark scientific-status-${classKey}">${marker}</span><span>${escapeHtml(label)}</span>`;}function directoryEntryPoint(path) {if (path === "research/protocols") return "protocols/COGNITION_CONSCIOUSNESS.md";if (path.startsWith("research/experiments/")) return `${path.slice("research/".length)}/manifest.json`;if (path.startsWith("research/publications/")) return `${path.slice("research/".length)}/README.md`;return null;}function registryEntryPoint(identifier) {if (/^CLAIM-[A-Z0-9-]+$/.test(identifier)) return "registry/claims.yaml";if (/^EVID-\d{4}-\d+$/.test(identifier)) return identifier === "EVID-2026-17" ? "registry/evidence/retired_ids.json" : `registry/evidence/${identifier}.json`;const families = [["MEM", "behavior_memory"], ["WM", "behavior_memory"], ["CNS", "cognition"],["EMB", "connectome"], ["GW", "gateway"], ["META", "meta"],["MSBA", "msba"], ["SAFE", "safety"],];const family = families.find(([prefix]) => identifier.startsWith(`H-${prefix}-`) || identifier.startsWith(`RQ-${prefix}-`))?.[1];if (identifier.startsWith("H-EVAL-")) return "registry/hypotheses.empirical.yaml";if (identifier.startsWith("H-")) return family ? `registry/hypotheses.${family}.yaml` : "registry/hypotheses.yaml";if (identifier.startsWith("RQ-EVAL-")) return "registry/questions.empirical.yaml";if (identifier.startsWith("RQ-")) return family ? `registry/questions.${family}.yaml` : "registry/questions.yaml";return null;}function sourceMarkup(source) {const label = String(source ?? "");const normalized = label.replaceAll("\\", "/");const match = normalized.match(/^\/?(research|docs)\/(.+)$/);let target = null;if (match) {const filePath = /\.[A-Za-z0-9]{1,12}$/.test(match[2]) ? match[2] : directoryEntryPoint(normalized);if (filePath) target = { kind: match[1], path: filePath, directory: filePath !== match[2] };} else {const registryPath = registryEntryPoint(normalized.trim());if (registryPath) target = { kind: "research", path: registryPath, directory: false };if (normalized.trim() === "INDEPENDENT_REPLICATION.md") target = { kind: "project", path: normalized.trim(), directory: false };}if (!target) return `<span class="scientific-source-text">${escapeHtml(label)}</span>`;return `<button type="button" class="scientific-source-link${target.directory ? " scientific-source-directory-link" : ""}" data-scientific-source-kind="${target.kind}" data-scientific-source-path="${escapeHtml(target.path)}" title="${target.directory ? "Ordnerreferenz öffnen" : "Im File Viewer öffnen"}">${escapeHtml(label)}</button>`;}function referenceGroupMarkup(title, references) {const unique = [...new Set(references)];return `<div class="scientific-reference-group"><h5>${escapeHtml(title)}</h5><div class="scientific-reference-links">${unique.length ? unique.map(sourceMarkup).join("") : '<span class="scientific-source-text">Keine registrierte Referenz</span>'}</div></div>`;}function referencePanelMarkup(stage, criteria) {const sourceValues = criteria.flatMap((criterion) => Array.isArray(criterion.sources) ? criterion.sources : []);const serialized = JSON.stringify(stage);const claims = serialized.match(/CLAIM-[A-Z0-9-]+/g) || [];const evidence = serialized.match(/EVID-\d{4}-\d+/g) || [];const hypotheses = serialized.match(/H-[A-Z0-9-]+/g) || [];const experiments = sourceValues.filter((source) => String(source).replaceAll("\\", "/").startsWith("research/experiments/"));return `<section class="scientific-reference-panel" aria-label="Wissenschaftliche Register"><div class="scientific-reference-columns">${referenceGroupMarkup("Claims & EVID", [...claims, ...evidence])}${referenceGroupMarkup("Experimente & Hypothesen", [...experiments, ...hypotheses])}</div></section>`;}function setVisible(element, visible) {if (!element) return;element.hidden = !visible;30 unmodified lines.scientific-progress-track{display:grid;grid-template-columns:repeat(11,minmax(86px,1fr));gap:7px;overflow-x:auto;padding:5px 0 10px}.scientific-stage-node{display:grid;grid-template-rows:auto auto auto auto;gap:5px;text-align:left;padding:9px;border:1px solid var(--rule);border-radius:8px;background:var(--paper);color:inherit;cursor:pointer}.scientific-stage-node:hover,.scientific-stage-node:focus-visible,.scientific-stage-node.is-selected{outline:2px solid var(--accent);outline-offset:1px}.scientific-stage-number{font-size:.72rem;opacity:.75}.scientific-stage-name{min-width:0;font-size:.78rem;font-weight:700;line-height:1.2;min-height:2.4em;overflow-wrap:anywhere;word-break:break-word}.scientific-stage-bar{height:6px;background:var(--paper-3,#d9d9d9);border-radius:999px;overflow:hidden}.scientific-stage-fill{display:block;height:100%;background:currentColor;opacity:.7}.scientific-stage-meta{display:flex;justify-content:space-between;gap:4px;font-size:.68rem;opacity:.8}.scientific-stage-meta em{display:inline-flex;align-items:center;gap:3px;font-style:normal}.scientific-progress-legend{display:flex;flex-wrap:wrap;gap:7px;margin:8px 0}.scientific-progress-legend span{padding:4px 7px;border:1px solid var(--rule);border-radius:999px;font-size:.72rem}.scientific-progress-status-legend{display:flex;flex-wrap:wrap;gap:7px;margin:8px 0}.scientific-progress-status-legend>span{display:inline-flex;align-items:center;gap:4px;padding:4px 7px;border:1px solid var(--rule);border-radius:999px;font-size:.72rem}.scientific-progress-status-legend .scientific-status-mark{padding:0;border:0}.scientific-progress-detail{margin-top:12px;padding:13px;border-top:1px solid var(--rule)}.scientific-progress-detail h4{margin:.2rem 0}.scientific-progress-boundary{padding:9px;border-left:3px solid var(--accent);background:var(--paper)}.scientific-reference-panel{margin:10px 0;padding-top:10px;border-top:1px solid var(--rule)}.scientific-reference-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.scientific-reference-group{min-height:76px;padding:8px;border:1px solid var(--rule);border-radius:6px;background:var(--paper)}.scientific-reference-group h5{margin:0 0 7px;font-size:.68rem}.scientific-reference-links{display:flex;flex-wrap:wrap;gap:4px}.scientific-criteria{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px;margin:10px 0}.scientific-criterion{padding:8px;border:1px solid var(--rule);border-radius:7px}.scientific-criterion strong{float:right;display:inline-flex;align-items:center;gap:4px}.scientific-status-mark{display:inline-grid;place-items:center;width:1em;height:1em;font-weight:800}.scientific-status-met{color:var(--moss,#3d8b5c)}.scientific-status-partial{color:var(--amber,#a47720)}.scientific-status-open{color:var(--ink-4,#777)}.scientific-criterion small{display:block;clear:both;margin-top:5px;opacity:.75;overflow-wrap:anywhere}.scientific-integrity-note{margin-top:10px;font-size:.78rem;opacity:.85}.scientific-two-axis-note{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin:12px 0}.scientific-two-axis-note>div{min-height:76px;padding:10px;border:1px solid var(--rule);border-radius:8px;background:var(--paper)}.scientific-two-axis-note strong{display:block;margin-bottom:5px}.scientific-two-axis-note p{margin:0;font-size:.74rem;line-height:1.45}.scientific-criterion{display:grid;grid-template-rows:auto minmax(34px,auto);gap:8px;min-height:112px}.scientific-criterion-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;min-height:2.5em}.scientific-criterion-label{font-size:.74rem;line-height:1.35}.scientific-criterion-status{display:inline-flex;align-items:center;gap:4px;flex-shrink:0;font-size:.68rem}.scientific-criterion-sources{display:flex;flex-wrap:wrap;align-content:flex-start;gap:4px;margin:0;padding-top:7px;border-top:1px solid var(--rule)}.scientific-source-link,.scientific-source-text{max-width:100%;padding:2px 5px;border:1px solid var(--rule);border-radius:3px;background:var(--paper-3);color:var(--ink-3);font:500 .58rem/1.35 var(--font-mono);overflow-wrap:anywhere;text-align:left}.scientific-source-link{cursor:pointer;text-decoration:underline;text-underline-offset:2px}.scientific-source-directory-link{border-style:dashed}.scientific-source-link:hover,.scientific-source-link:focus-visible{border-color:var(--accent);color:var(--accent-2);background:var(--accent-wash)}@media(max-width:900px){.scientific-progress-head{display:block}.scientific-progress-score{text-align:left;margin-top:8px}.scientific-progress-track{grid-template-columns:repeat(11,110px)}.scientific-two-axis-note,.scientific-reference-columns{grid-template-columns:1fr}}`;document.head.appendChild(style);}61 unmodified linesfunction criterionMarkup(criterion) {const sources = Array.isArray(criterion.sources) ? criterion.sources : [];return `<div class="scientific-criterion" data-status="${escapeHtml(criterion.status)}"><div class="scientific-criterion-head"><span class="scientific-criterion-label">${escapeHtml(criterion.label || criterion.id)}</span><strong class="scientific-criterion-status">${statusMarkup(criterion.status)}</strong></div><div class="scientific-criterion-sources">${sources.length ? sources.map(sourceMarkup).join("") : '<span class="scientific-source-text">kein evidenztragender Nachweis eingetragen</span>'}</div></div>`;}5 unmodified lines<h4>${escapeHtml(stage.name)} · ${percent(stage.score)}</h4><p class="scientific-progress-boundary"><strong>Claim-Grenze:</strong> ${escapeHtml(stage.claim_boundary)}</p><div class="scientific-criteria">${criteria.map(criterionMarkup).join("")}</div>${referencePanelMarkup(stage, criteria)}<h5>Nächste wissenschaftliche Schritte</h5><ul>${next.map((item) => `<li>${escapeHtml(item)}</li>`).join("")}</ul></div>`;11 unmodified lines<div><span class="workspace-kicker">SCIENTIFIC MATURITY</span><h2 id="scientific-progress-title">Wissenschaftliche Timeline · Stufen 0–10</h2><p>${escapeHtml(data.scope_note)}</p></div><div class="scientific-progress-score"><span>Stage-Mittel</span><strong>${percent(overall)}</strong><small>keine Kognitionskennzahl</small></div></header><div class="scientific-progress-status-legend" aria-label="Statusmarker der wissenschaftlichen Kriterien"><span>${statusMarkup("met")}</span><span>${statusMarkup("partial")}</span><span>${statusMarkup("open")}</span></div><div class="scientific-two-axis-note"><div><strong>Technische Timeline</strong><p>Implementierung · Integration · Verification · Runtime/Persistenz</p></div><div><strong>Wissenschaftliche Timeline</strong><p>RQ/Hypothese · Protokoll · DATA · reviewte EVID · Replikation · Attribution</p></div></div><div class="scientific-progress-legend"><span>RQ 15%</span><span>Protokoll 20%</span><span>DATA 20%</span><span>reviewte EVID 20%</span><span>Replikation 15%</span><span>Attribution 10%</span></div><div class="scientific-progress-track" role="list" aria-label="Wissenschaftliche Reife je Entwicklungsstufe">${stages.map((stage) => `<button type="button" class="scientific-stage-node ${stage.stage === 6 ? "is-selected" : ""}" data-scientific-stage="${stage.stage}" role="listitem" title="Stufe ${stage.stage}: ${escapeHtml(stage.name)}"><span class="scientific-stage-number">STUFE ${stage.stage}</span><span class="scientific-stage-name">${escapeHtml(stage.name)}</span><span class="scientific-stage-bar"><span class="scientific-stage-fill" style="width:${percent(stage.score)}"></span></span><span class="scientific-stage-meta"><b>${percent(stage.score)}</b><em>${statusMarkup(stage.status)}</em></span></button>`).join("")}</div><div id="scientific-progress-detail">${stages.length ? detailMarkup(stages.find((stage) => stage.stage === 6) || stages[0]) : ""}</div>1 unmodified line</section>`;host.addEventListener("click", (event) => {const source = event.target.closest("[data-scientific-source-path]");if (source) {document.dispatchEvent(new CustomEvent("brain5d:open-file", {detail: { source: source.dataset.scientificSourceKind, path: source.dataset.scientificSourcePath },}));return;}const button = event.target.closest("[data-scientific-stage]");if (!button) return;host.querySelectorAll(".scientific-stage-node").forEach((node) => node.classList.toggle("is-selected", node === button));4 unmodified lines}async function loadScientificProgress() {ensureReleaseView();try {const response = await fetch(SCIENCE_MANIFEST_URL, { cache: "no-store" });if (!response.ok) throw new Error(`HTTP ${response.status}`);
123456117 unmodified lines12412512612712812913013113214 unmodified lines1471481491501511521533 unmodified lines15715815916016116216316416516616716816917017117217317417517617717817918018111 unmodified lines193194195196197198199200201{"schema_version": 1,"as_of": "2026-09-25","as_of_commit": "f9d926a9209dc17a11fbe29c6c82074824f75aa0","title": "MHRN scientific maturity timeline","scope_note": "Scientific maturity is intentionally separate from engineering maturity. Scores summarize registered questions, frozen protocols, collected DATA, human-reviewed EVID, independent replication and attribution. They do not measure intelligence, consciousness or biological equivalence.",117 unmodified lines{"stage": 1,"name": "Kleines SNN","score": 0.75,"status": "advanced","claim_boundary": "Die zentrale Stage-1-Topologielinie (V2 + V3-R1) und die getrennte Temporal-Order-Funktionslinie sind innerhalb ihrer präregistrierten Small-SNN-Operating-Envelopes human-reviewed DATA. Das ist weder kanonische EVID noch unabhängige Replikation und begründet keine Kognition, Skalierbarkeit oder 5D-Überlegenheit.","criteria": [{"id": "research_question",14 unmodified lines"sources": ["research/preregistrations/PREREG-S1-TOPO-V2.json","research/preregistrations/PREREG-S1-TOPO-V3-R1-TIME-RESOLVED.json","research/preregistrations/PREREG-S1-TEMP-ORDER-V2.json"]},{3 unmodified lines"sources": ["research/experiments/EXP-S1-TOPO-V2-20260918","research/experiments/EXP-S1-TOPO-V3-R1-20260918","research/experiments/EXP-S1-TEMP-ORDER-V2-20260919"]},{"id": "reviewed_evidence","status": "partial","label": "Human Reviews der Topologie- und Temporal-Order-Linien abgeschlossen; kanonische EvidenceEngine-Promotion separat offen","sources": ["research/experiments/EXP-S1-TOPO-V2-20260918/review_request.json.review.json","research/experiments/EXP-S1-TOPO-V3-R1-20260918/review_request.json.human-review.json","research/experiments/EXP-S1-TEMP-ORDER-V2-20260919/review_request.json.review.json","research/registry/stage1_baseline.json","research/decisions/2026-09-25_stage1_scientific_consolidation.md"]},{"id": "independent_replication","status": "open","label": "Interne R1-Replikation vorhanden; keine unabhängig autorisierte Replikation","sources": ["INDEPENDENT_REPLICATION.md","research/registry/stage1_baseline.json",11 unmodified lines}],"next_scientific_steps": ["Für die human-reviewte Topologie- und Temporal-Order-DATA jeweils einen scoped Claim und einen prospektiven EvidenceEngine-kompatiblen Promotion-Pfad definieren; historische Manifeste nicht rückwirkend umschreiben.","Unabhängig implementierte beziehungsweise unabhängig kontrollierte Replikation durchführen; weder V3-R1 noch Temporal Order als unabhängige Replikation der Topologielinie zählen.","Task-, Störungs- und Skalierungsregime erweitern; die stärkere 5D-Hypothese weiterhin separat prüfen."],"criterion_contracts": {"reviewed_evidence": {123456117 unmodified lines12412512612712812913013113214 unmodified lines1471481491501511521531543 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418511 unmodified lines197198199200201202203204205{"schema_version": 1,"as_of": "2026-09-27","as_of_commit": "f9d926a9209dc17a11fbe29c6c82074824f75aa0","title": "MHRN scientific maturity timeline","scope_note": "Scientific maturity is intentionally separate from engineering maturity. Scores summarize registered questions, frozen protocols, collected DATA, human-reviewed EVID, independent replication and attribution. They do not measure intelligence, consciousness or biological equivalence.",117 unmodified lines{"stage": 1,"name": "Kleines SNN","score": 0.85,"status": "active","claim_boundary": "Stage 1 besitzt jetzt zwei getrennte kanonische, human-reviewte EVID-Linien: Topologie EVID-2026-19 im 64-Neuronen/246-Kanten-Regime und Temporal Order EVID-2026-20 im sechsneuronigen Zweikanal-Task. Der Temporal-Human-Review dokumentiert Perfect-Score-Sättigung und die simultane Bedingung als nicht-inferentiellen Task-Adequacy-Control. Das begründet weder Kognition, Lernen/Gedächtnis, Skalierbarkeit, biologische Äquivalenz, 5D-Überlegenheit noch unabhängige Replikation.","criteria": [{"id": "research_question",14 unmodified lines"sources": ["research/preregistrations/PREREG-S1-TOPO-V2.json","research/preregistrations/PREREG-S1-TOPO-V3-R1-TIME-RESOLVED.json","research/preregistrations/PREREG-S1-TEMP-ORDER-V2.json","research/preregistrations/PREREG-S1-TEMP-PROMO-R1.json"]},{3 unmodified lines"sources": ["research/experiments/EXP-S1-TOPO-V2-20260918","research/experiments/EXP-S1-TOPO-V3-R1-20260918","research/experiments/EXP-S1-TEMP-ORDER-V2-20260919","research/experiments/EXP-S1-TOPO-PROMO-R1-20260927","research/experiments/EXP-S1-TEMP-PROMO-R1-20260927"]},{"id": "reviewed_evidence","status": "met","label": "Human Review + EvidenceEngine-Promotion für Topologie- und Temporal-Order-Claims","sources": ["CLAIM-S1-TOPO-001","EVID-2026-19","research/experiments/EXP-S1-TOPO-PROMO-R1-20260927/human_review.json","CLAIM-S1-TEMP-001","EVID-2026-20","research/experiments/EXP-S1-TEMP-PROMO-R1-20260927/human_review.json"]},{"id": "independent_replication","status": "open","label": "Unabhängige Referenz-/Cross-Implementation-Replikation offen","sources": ["INDEPENDENT_REPLICATION.md","research/registry/stage1_baseline.json",11 unmodified lines}],"next_scientific_steps": ["Topologie als unabhängig implementierte Referenz-/Cross-Implementation-Replikation präregistrieren, um den nächsten 7,5-%-Schritt zu adressieren.","Temporal-Order-Decoder/Task separat mit schwierigeren, präregistrierten Gap-/Channel-Swap-/Perturbationskontrollen stress-testen; dies ändert EVID-2026-20 nicht rückwirkend.","CLAIM-S1-EFFICIENCY-001 / H-SNN-003-C getrennt als prospektive untested Effizienzlinie weiterentwickeln; keine post-hoc Effizienzbeobachtung als EVID verwenden."],"criterion_contracts": {"reviewed_evidence": {
556 unmodified lines557558559560561562158 unmodified lines721722723724725726277 unmodified lines1004100510061007100810091010556 unmodified lines.preview-boundary { margin-top:10px; padding:8px 10px; border-left:2px solid var(--indigo); background:var(--indigo-wash); color:var(--ink-2); font-size:.66rem; line-height:1.4; }.release-empty { padding:24px; text-align:center; color:var(--ink-4); font:.65rem/1.45 var(--font-mono); }.gate-board { border:0; }.gate-header { display:grid; grid-template-columns:1fr auto; }158 unmodified lines.dev-criterion-fail { border-left:3px solid var(--crimson); }.dev-criterion-missing { border-left:3px solid var(--rule-3); }.dev-criterion strong { margin-left:auto; font-family:var(--font-mono); font-size:.6rem; }.dev-criterion small { display:block; width:100%; margin-top:2px; color:var(--ink-4); font-size:.55rem; }.dev-detail-columns { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:8px; }.dev-detail-columns section h4 { font-size:.7rem; margin-bottom:4px; color:var(--ink-3); }277 unmodified lines.overview-operations-grid,.overview-metrics-row,.control-causal-grid { grid-template-columns:1fr; }.overview-body-surface { grid-column:auto; }.overview-status-rail { grid-template-columns:repeat(3,minmax(0,1fr)); }.heatmap-split,.experiment-form,.settings-guardrail-grid,.release-documents-grid,.gate-sections-grid { grid-template-columns:1fr; }.workflow-form-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.workflow-steps { grid-template-columns:repeat(3,minmax(0,1fr)); }.workflow-actions { grid-template-columns:1fr; }556 unmodified lines557558559560561562563564565566567568569570571572573574575576577158 unmodified lines736737738739740741742743744745746277 unmodified lines1024102510261027102810291030556 unmodified lines.preview-boundary { margin-top:10px; padding:8px 10px; border-left:2px solid var(--indigo); background:var(--indigo-wash); color:var(--ink-2); font-size:.66rem; line-height:1.4; }.release-empty { padding:24px; text-align:center; color:var(--ink-4); font:.65rem/1.45 var(--font-mono); }.scientific-work-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:10px; padding:13px 14px 16px; }.scientific-work-card { display:flex; flex-direction:column; min-width:0; min-height:160px; padding:11px 12px; border:1px solid var(--rule); border-left:3px solid var(--accent); border-radius:var(--r-sm); background:var(--paper-2); }.scientific-work-card header { display:block; margin-bottom:7px; }.scientific-work-card header span { color:var(--accent); font:700 .5rem/1 var(--font-mono); letter-spacing:.08em; }.scientific-work-card h3 { margin:5px 0 0; font-size:.82rem; line-height:1.25; overflow-wrap:anywhere; }.scientific-work-metric { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:2px 0 4px; font:700 .58rem/1 var(--font-mono); }.scientific-work-metric strong { font-size:.68rem; }.scientific-work-met { color:var(--moss); }.scientific-work-partial { color:var(--amber); }.scientific-work-open { color:var(--ink-4); }.scientific-work-bar { height:5px; margin-bottom:8px; border-radius:99px; background:var(--paper-4); overflow:hidden; }.scientific-work-bar span { display:block; height:100%; border-radius:inherit; background:currentColor; opacity:.75; }.scientific-work-card p { flex:1; margin:0 0 10px; color:var(--ink-3); font-size:.68rem; line-height:1.45; }.scientific-work-card button { align-self:flex-start; padding:5px 8px; border:1px solid var(--rule-2); border-radius:var(--r-xs); background:var(--paper-3); color:var(--ink-2); font:600 .58rem/1 var(--font-ui); cursor:pointer; }.scientific-work-card button:hover,.scientific-work-card button:focus-visible { border-color:var(--accent); color:var(--accent-2); background:var(--accent-wash); }.gate-board { border:0; }.gate-header { display:grid; grid-template-columns:1fr auto; }158 unmodified lines.dev-criterion-fail { border-left:3px solid var(--crimson); }.dev-criterion-missing { border-left:3px solid var(--rule-3); }.dev-criterion strong { margin-left:auto; font-family:var(--font-mono); font-size:.6rem; }.release-status-value { display:inline-flex; align-items:center; gap:4px; white-space:nowrap; }.release-status-mark { display:inline-grid; place-items:center; width:1em; height:1em; font-weight:800; }.release-status-met,.release-status-implemented,.release-status-verified { color:var(--moss); }.release-status-partial,.release-status-experimental { color:var(--amber); }.release-status-open,.release-status-planned,.release-status-missing { color:var(--ink-4); }.dev-criterion small { display:block; width:100%; margin-top:2px; color:var(--ink-4); font-size:.55rem; }.dev-detail-columns { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:8px; }.dev-detail-columns section h4 { font-size:.7rem; margin-bottom:4px; color:var(--ink-3); }277 unmodified lines.overview-operations-grid,.overview-metrics-row,.control-causal-grid { grid-template-columns:1fr; }.overview-body-surface { grid-column:auto; }.overview-status-rail { grid-template-columns:repeat(3,minmax(0,1fr)); }.heatmap-split,.experiment-form,.settings-guardrail-grid,.release-documents-grid,.scientific-work-grid,.gate-sections-grid { grid-template-columns:1fr; }.workflow-form-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.workflow-steps { grid-template-columns:repeat(3,minmax(0,1fr)); }.workflow-actions { grid-template-columns:1fr; }
scripts/run_stage1_reference_integrator_calibration.pyAdded+198
scripts/run_stage1_reference_reset_calibration.pyAdded+143
scripts/run_stage1_reference_synapse_calibration.pyAdded+174
scripts/run_stage1_reference_topology_mapping_r2.pyAdded+108
scripts/run_stage1_temporal_order_promotion_r1.pyAdded+316
scripts/run_stage1_topology_efficiency_calibration.pyAdded+220
scripts/run_stage1_topology_efficiency_r1.pyAdded+511
scripts/run_stage1_topology_promotion_r1.pyAdded+242
scripts/validate_playground_ptx.pyAdded+33
scripts/verify_stage1_reference_dynamics_reuse_r2.pyAdded+138
scripts/verify_stage1_temporal_order_promotion_r1.pyAdded+210
scripts/verify_stage1_topology_efficiency_calibration.pyAdded+100
scripts/verify_stage1_topology_efficiency_r1.pyAdded+138
scripts/verify_stage1_topology_promotion_r1.pyAdded+166
scripts/verify_stage1_topology_reference_r1.pyAdded+285
scripts/verify_stage1_topology_reference_r2.pyAdded+285
src/dashboard/file_manager.py+11-1
src/dashboard/file_rendering.py+6-1
src/dashboard/playground_api.pyAdded+253
src/dashboard/server.py+45
src/dashboard/static/file-viewer.js+1-1
src/dashboard/static/formula-renderer.js+1-1
src/dashboard/static/frontend/index.js+2
src/dashboard/static/frontend/modules/playground.jsAdded
src/dashboard/static/frontend/workspace-router.js+15-1
src/dashboard/static/gate-board.js+30-2
src/dashboard/static/index.html+28-1
src/dashboard/static/scientific-progress.js+88-8
src/dashboard/static/scientific-progress.json+21-17
src/dashboard/static/styles.css+21-1