From 2c8ee3408c9221e826221d28c11fb4460cdbe835 Mon Sep 17 00:00:00 2001 From: techmore Date: Tue, 20 Oct 2026 06:20:42 -0400 Subject: [PATCH 1/2] Add ruff configuration and apply its safe fixes Adds [tool.ruff] to pyproject (pyflakes, pycodestyle errors, bugbear, isort, pyupgrade; line length not enforced) and ruff to the dev extra. Everything in this commit is ruff --fix output plus two one-line manual fixes: a percent-format in train.py and a semicolon in a test. No behaviour changes. Co-Authored-By: Claude Fable 5.1 --- dr_adapter/__init__.py | 2 +- dr_adapter/action_space.py | 1 + dr_adapter/experiment.py | 8 +++++--- dr_adapter/navigation.py | 2 ++ dr_adapter/observation.py | 2 +- dr_adapter/outcome.py | 1 + dr_adapter/pilot.py | 18 +++++++++++------- dr_adapter/policy.py | 3 +++ dr_adapter/reward.py | 2 +- dr_adapter/training.py | 5 ++++- dr_adapter/transport.py | 9 ++++++--- notflyguy/chat_policy.py | 4 ++-- notflyguy/controller.py | 3 ++- pyproject.toml | 26 +++++++++++++++++++++++++- scripts/catalog_leg_neurons.py | 1 + scripts/check_habitat.py | 3 ++- scripts/extract_motor_circuit.py | 1 + tests/test_chat_policy.py | 11 +++++++++-- tests/test_corpus.py | 7 +++---- tests/test_dr_adapter.py | 21 ++++++++++++--------- tests/test_motor_projection.py | 3 +-- tests/test_persona.py | 5 +---- tests/test_train_chat.py | 3 +-- 23 files changed, 96 insertions(+), 45 deletions(-) diff --git a/dr_adapter/__init__.py b/dr_adapter/__init__.py index 3c5377b..60f325d 100644 --- a/dr_adapter/__init__.py +++ b/dr_adapter/__init__.py @@ -1,6 +1,6 @@ """Removable, advisory-only DragonRealms adapter for NotFlyGuy.""" -from .observation import Observation, parse_transcript from .action_space import Action, allowed_action +from .observation import Observation, parse_transcript __all__ = ["Observation", "parse_transcript", "Action", "allowed_action"] diff --git a/dr_adapter/action_space.py b/dr_adapter/action_space.py index ce5d444..2b45267 100644 --- a/dr_adapter/action_space.py +++ b/dr_adapter/action_space.py @@ -1,4 +1,5 @@ from __future__ import annotations + from dataclasses import dataclass from typing import Literal diff --git a/dr_adapter/experiment.py b/dr_adapter/experiment.py index 65374b7..3052c3e 100644 --- a/dr_adapter/experiment.py +++ b/dr_adapter/experiment.py @@ -3,17 +3,19 @@ import hashlib import json import os -from pathlib import Path import secrets +import shutil import signal import subprocess -import shutil import time +from pathlib import Path from urllib.request import urlopen + from .fly_bridge import FlyBridge from .pilot import FlyPilot -from .transport import DragonRealmsHTTPTransport from .reward import REWARD_VERSION +from .transport import DragonRealmsHTTPTransport + def copy_checkpoint(source, destination): """Snapshot explicit learning artifacts without modifying the source.""" diff --git a/dr_adapter/navigation.py b/dr_adapter/navigation.py index bc11161..71dd0fd 100644 --- a/dr_adapter/navigation.py +++ b/dr_adapter/navigation.py @@ -1,7 +1,9 @@ """Routes over directed exits actually reported by the game client.""" from collections import deque + from .action_space import MOVES + class ObservedMap: def __init__(self): self.rooms = {} diff --git a/dr_adapter/observation.py b/dr_adapter/observation.py index 9b8605f..74e7211 100644 --- a/dr_adapter/observation.py +++ b/dr_adapter/observation.py @@ -1,8 +1,8 @@ from __future__ import annotations -from dataclasses import asdict, dataclass, field import re import time +from dataclasses import asdict, dataclass, field from typing import Any SCHEMA = "notflyguy.dr.observation/1" diff --git a/dr_adapter/outcome.py b/dr_adapter/outcome.py index 7849996..a0c2dd4 100644 --- a/dr_adapter/outcome.py +++ b/dr_adapter/outcome.py @@ -1,6 +1,7 @@ """Read delayed game outcomes without issuing another command.""" import time + def settle_outcome(transport, initial, *, until, deadline, target=2, clock=time.time, sleep=time.sleep): state = initial diff --git a/dr_adapter/pilot.py b/dr_adapter/pilot.py index 677f5a1..eecbac2 100644 --- a/dr_adapter/pilot.py +++ b/dr_adapter/pilot.py @@ -1,18 +1,22 @@ """Bounded autonomous DR pilot using the real HTTP transport.""" from __future__ import annotations -import argparse, json, time + +import argparse +import json import re +import time from pathlib import Path + from .action_space import allowed_action +from .curriculum import equipment_proposal, field_candidates, purchase_proposal from .fly_bridge import FlyBridge -from .observation import from_game_state -from .transport import DragonRealmsHTTPTransport from .learning import LinearActionLearner -from .training import TrainingLedger -from .curriculum import field_candidates, equipment_proposal, purchase_proposal from .navigation import ObservedMap -from .reward import requirement_gap +from .observation import from_game_state from .outcome import settle_outcome +from .reward import requirement_gap +from .training import TrainingLedger +from .transport import DragonRealmsHTTPTransport TOWN = {'square': [], 'bazaar': ['w','w'], 'bank_plaza': ['w','w','w','w'], 'hall_barbarian': ['s','s','w','e']} # Observed-route path from square through the dense Crossing rooms into the @@ -177,7 +181,7 @@ def run(self): # sufficient evidence of a kill, so do not invent a kill bonus. kill = False if 'invalid' in text or 'cannot' in text or 'not here' in text: self.failures += 1 - from .reward import score_transition, REWARD_VERSION + from .reward import REWARD_VERSION, score_transition failed_text = ('cannot', 'do not have', 'invalid', 'not here', 'must be in', 'unable', 'must wait', 'skin what') command_ok = result.ok and not any(token in text for token in failed_text) score = score_transition(state, after_state, command_ok=command_ok, unsafe=self.t.stopped, target_circle=self.target, kill=kill) diff --git a/dr_adapter/policy.py b/dr_adapter/policy.py index 2ffedb8..dc9a791 100644 --- a/dr_adapter/policy.py +++ b/dr_adapter/policy.py @@ -1,9 +1,12 @@ from __future__ import annotations + import time from dataclasses import dataclass + from .action_space import Action, allowed_action from .observation import Observation + @dataclass(frozen=True) class Proposal: action: Action diff --git a/dr_adapter/reward.py b/dr_adapter/reward.py index bb5c9ea..9c4fb69 100644 --- a/dr_adapter/reward.py +++ b/dr_adapter/reward.py @@ -1,8 +1,8 @@ """Experiment scoring; this does not change DragonRealms progression rules.""" from __future__ import annotations -from dataclasses import dataclass import math +from dataclasses import dataclass REWARD_VERSION = 'balanced-requirements-exp/3' diff --git a/dr_adapter/training.py b/dr_adapter/training.py index 3240d37..c767da9 100644 --- a/dr_adapter/training.py +++ b/dr_adapter/training.py @@ -1,8 +1,11 @@ """Durable training-run ledger for the DR adapter.""" from __future__ import annotations -import json, time + +import json +import time from pathlib import Path + class TrainingLedger: def __init__(self, path): self.path = Path(path) diff --git a/dr_adapter/transport.py b/dr_adapter/transport.py index 6c515b2..b81f84e 100644 --- a/dr_adapter/transport.py +++ b/dr_adapter/transport.py @@ -1,11 +1,14 @@ from __future__ import annotations + +import json from dataclasses import dataclass from typing import Protocol -from .observation import parse_transcript, Observation, from_game_state -from .action_space import Action -import json from urllib.request import Request, urlopen +from .action_space import Action +from .observation import parse_transcript + + @dataclass(frozen=True) class GameEvent: text: str diff --git a/notflyguy/chat_policy.py b/notflyguy/chat_policy.py index 175ac34..27299cf 100644 --- a/notflyguy/chat_policy.py +++ b/notflyguy/chat_policy.py @@ -108,7 +108,7 @@ def _fit_scaler(self, X) -> None: self.scale = np.where(scale > EPS, scale, 1.0) # -- training ---------------------------------------------------------- - def fit(self, X, y_respond, y_length=None, sample_weight=None) -> 'ChatPolicy': + def fit(self, X, y_respond, y_length=None, sample_weight=None) -> ChatPolicy: X = np.asarray(X, dtype=float) y = np.asarray(y_respond, dtype=float) if X.ndim != 2: @@ -179,7 +179,7 @@ def save(self, path) -> Path: return path @classmethod - def load(cls, path) -> 'ChatPolicy': + def load(cls, path) -> ChatPolicy: path = Path(path) if not path.exists(): raise FileNotFoundError(f'No trained group-chat policy at {path}') diff --git a/notflyguy/controller.py b/notflyguy/controller.py index 1fa871f..17ed1a7 100644 --- a/notflyguy/controller.py +++ b/notflyguy/controller.py @@ -1,7 +1,8 @@ """Replaceable controller boundary between a brain and a simulated body.""" +from collections.abc import Sequence from dataclasses import dataclass, field -from typing import Protocol, Sequence +from typing import Protocol @dataclass(frozen=True) diff --git a/pyproject.toml b/pyproject.toml index a298ab9..ebc7929 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["pytest>=8"] +dev = ["pytest>=8", "ruff>=0.6"] # Reading the released MaleCNS feather tables (scripts/fetch_connectome.py, # scripts/catalog_leg_neurons.py, scripts/extract_motor_circuit.py). connectome = ["pyarrow>=18"] @@ -45,3 +45,27 @@ dr_adapter = ["*.html"] [tool.pytest.ini_options] testpaths = ["tests"] + +[tool.ruff] +target-version = "py310" +line-length = 120 +extend-exclude = ["data", ".venv"] + +[tool.ruff.lint] +# Correctness (F, E4/E7/E9, B), import order (I), and modern syntax (UP). +# Line length is deliberately not enforced: the trainer and adapter modules +# carry long self-describing argparse help strings and JSON report keys. +select = ["E4", "E7", "E9", "F", "W", "I", "B", "UP"] +ignore = [ + "B904", # raise ... from err: the HTTP handlers return, they do not re-raise + "B007", # unused loop variables in report builders + "B905", # zip(strict=...) would be churn across the report builders +] + +[tool.ruff.lint.per-file-ignores] +# The DragonRealms adapter is written one statement per line on purpose; it +# is removable and advisory-only (see dr_adapter/README.md). +"dr_adapter/*" = ["E401", "E701", "E702", "E731"] + +[tool.ruff.lint.isort] +known-first-party = ["notflyguy", "dr_adapter"] diff --git a/scripts/catalog_leg_neurons.py b/scripts/catalog_leg_neurons.py index d5172fe..26a05a2 100644 --- a/scripts/catalog_leg_neurons.py +++ b/scripts/catalog_leg_neurons.py @@ -2,6 +2,7 @@ import json from collections import Counter from pathlib import Path + import pyarrow.feather as feather root = Path(__file__).resolve().parents[1] / 'data' / 'malecns-v1.0' diff --git a/scripts/check_habitat.py b/scripts/check_habitat.py index 8240d97..c69fb9b 100644 --- a/scripts/check_habitat.py +++ b/scripts/check_habitat.py @@ -1,9 +1,10 @@ """Read-only runtime check: real JPEG frames and advancing simulation time.""" +import base64 import io import json -import base64 import time from urllib.request import urlopen + from PIL import Image diff --git a/scripts/extract_motor_circuit.py b/scripts/extract_motor_circuit.py index 8bb7bd9..290fd22 100644 --- a/scripts/extract_motor_circuit.py +++ b/scripts/extract_motor_circuit.py @@ -1,6 +1,7 @@ """Extract a reproducible motor-centered subgraph from released MaleCNS edges.""" import json from pathlib import Path + import numpy as np import pyarrow.feather as feather diff --git a/tests/test_chat_policy.py b/tests/test_chat_policy.py index 49c53ca..795cd74 100644 --- a/tests/test_chat_policy.py +++ b/tests/test_chat_policy.py @@ -2,8 +2,15 @@ import numpy as np import pytest -from notflyguy.chat_policy import (ChatPolicy, accuracy, brier_score, majority_baseline, - mean_absolute_error, roc_auc, sigmoid) +from notflyguy.chat_policy import ( + ChatPolicy, + accuracy, + brier_score, + majority_baseline, + mean_absolute_error, + roc_auc, + sigmoid, +) def test_sigmoid_is_stable_at_extremes(): diff --git a/tests/test_corpus.py b/tests/test_corpus.py index 625b15a..0007548 100644 --- a/tests/test_corpus.py +++ b/tests/test_corpus.py @@ -1,14 +1,13 @@ """Corpus readiness: gates, projections, and text-free reporting.""" import json -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone import pytest from notflyguy.chatlog import ChatEvent, pseudonym -from notflyguy.corpus import (DEFAULT_GATES, project, readiness, status, summarise, - weekly_counts) -from notflyguy.groupchat import DecisionPoint from notflyguy.connectome import ConnectomeState +from notflyguy.corpus import DEFAULT_GATES, project, readiness, status, summarise, weekly_counts +from notflyguy.groupchat import DecisionPoint def _events(count, session_id, sender, start, spacing_hours=1.0, chat_type='group'): diff --git a/tests/test_dr_adapter.py b/tests/test_dr_adapter.py index 9141acd..17e68d8 100644 --- a/tests/test_dr_adapter.py +++ b/tests/test_dr_adapter.py @@ -1,13 +1,14 @@ -import time import numpy as np + from dr_adapter.action_space import allowed_action -from dr_adapter.observation import parse_transcript, from_game_state -from dr_adapter.policy import propose -from dr_adapter.transport import MockTransport from dr_adapter.dashboard import Adapter -from dr_adapter.reward import requirement_gap, score_transition -from dr_adapter.learning import LinearActionLearner from dr_adapter.fly_bridge import FlyBridge +from dr_adapter.learning import LinearActionLearner +from dr_adapter.observation import from_game_state, parse_transcript +from dr_adapter.policy import propose +from dr_adapter.reward import requirement_gap, score_transition +from dr_adapter.transport import MockTransport + def test_parser_explicit_fields_and_schema(): obs = parse_transcript("Location: Crossing\nHP: 80/100 Mana: 20/40\nYou are attacking a goblin. RT: 3") @@ -85,8 +86,8 @@ def test_reward_uses_requirement_gap_and_target_as_primary_signal(): assert done.reached_target and done.reward == 100 def test_trainable_readout_updates_and_persists_without_changing_connectome(): - from pathlib import Path import tempfile + from pathlib import Path with tempfile.TemporaryDirectory() as d: path = Path(d) / 'policy.json' learner = LinearActionLearner(path, epsilon=0, seed=3) @@ -176,7 +177,7 @@ def test_navigation_uses_directed_observed_exits_and_reroutes(): assert nav.next_step('square', 'square') is None def test_equipment_rotation_uses_distinct_owned_lanes_and_live_targets(): - from dr_adapter.curriculum import equipment_proposal, WEAPONS + from dr_adapter.curriculum import WEAPONS, equipment_proposal state = {'requirements': {'circle': 2, 'rows': [ {'label': label, 'have': 0, 'need': need} for label, need in zip(('1st weapon', '2nd weapon', '3rd weapon', '4th weapon'), (8, 8, 4, 2))]}, @@ -303,9 +304,11 @@ def test_frozen_mode_never_updates_or_writes_learning_checkpoints(tmp_path): def test_checkpoint_copy_preserves_source_and_records_exact_hashes(tmp_path): import hashlib + from dr_adapter.experiment import copy_checkpoint source, destination = tmp_path / 'source', tmp_path / 'destination' - source.mkdir(); destination.mkdir() + source.mkdir() + destination.mkdir() bridge = FlyBridge(checkpoint=source / 'connectome.npz') bridge.observe(parse_transcript('Location: Field\nHP: 10/10')) bridge.learn(.1) diff --git a/tests/test_motor_projection.py b/tests/test_motor_projection.py index 3e67788..bdaee50 100644 --- a/tests/test_motor_projection.py +++ b/tests/test_motor_projection.py @@ -2,8 +2,7 @@ import numpy as np import pytest -from notflyguy.motor_projection import (ACTION_MAX, ACTION_MIN, ACTION_NEUTRAL, - LegMotorReadout, to_action) +from notflyguy.motor_projection import ACTION_MAX, ACTION_MIN, ACTION_NEUTRAL, LegMotorReadout, to_action ACTUATORS = ( 'walker/head_abduct', 'walker/abdomen', diff --git a/tests/test_persona.py b/tests/test_persona.py index 08a0a80..6106724 100644 --- a/tests/test_persona.py +++ b/tests/test_persona.py @@ -2,10 +2,7 @@ import importlib.util from pathlib import Path -import pytest - -from notflyguy.persona import (ALIASES, IDENTITY, PERSONA, style_guidance, system_prompt, - technical_question) +from notflyguy.persona import ALIASES, IDENTITY, PERSONA, style_guidance, system_prompt, technical_question PLUGIN_PATH = Path(__file__).parents[1] / 'integrations/hermes/notflyguy/__init__.py' diff --git a/tests/test_train_chat.py b/tests/test_train_chat.py index 44aba83..48ac48f 100644 --- a/tests/test_train_chat.py +++ b/tests/test_train_chat.py @@ -1,6 +1,5 @@ """Cross-validation splits, trainer plumbing, and the honesty gate.""" import numpy as np -import pytest from notflyguy.chat_policy import ChatPolicy from notflyguy.train_chat import evaluate_cross_validation, make_folds, verdict @@ -8,8 +7,8 @@ def _synthetic_points(count=240, sessions=12, seed=0, signal=3.0): """Decision-point lookalikes with a learnable relationship.""" - from notflyguy.groupchat import CONTEXT_NAMES, DecisionPoint from notflyguy.connectome import ConnectomeState + from notflyguy.groupchat import CONTEXT_NAMES, DecisionPoint rng = np.random.default_rng(seed) context = rng.normal(size=(count, len(CONTEXT_NAMES))) From a34ef5954df9469faef542f873927df692b726b0 Mon Sep 17 00:00:00 2001 From: techmore Date: Tue, 20 Oct 2026 06:20:42 -0400 Subject: [PATCH 2/2] Make the test suite green on a fresh clone and add CI Before this, 16 tests failed and one errored on any clone that had not run the ~1 GB MaleCNS bootstrap, contradicting the README's claim that circuit tests skip themselves. Loaders hard-coded data/malecns-v1.0 relative to the package in four places with no way to redirect them. - notflyguy/paths.py: one data_root() resolver, honouring a new NOTFLYGUY_DATA_ROOT variable read at call time. connectome, motor_training, circuit, habitat, wiring_control, train and the DR bridge all go through it; their missing-data errors now name the override. - notflyguy/synthetic.py: writes a random circuit, catalog and summary in the measured file layout, flagged synthetic:true. The test session (tests/conftest.py) writes one and points NOTFLYGUY_DATA_ROOT at it when the measured circuit is absent, so the 29 formerly skipped or failing circuit tests now run everywhere. Also usable to start the dashboard without the download. - .github/workflows/ci.yml: ruff + pytest on 3.10/3.11/3.12 and a dashboard smoke boot against a synthetic circuit. - dr_adapter/dashboard.py: same-origin check on POST, matching the main server; /api/approve sends real game commands and had no CSRF defence. - habitat: validate the aliases payload (a bare string was iterated per character, marking nearly every message as addressed). - chatlog: NOTFLYGUY_ID_SALT was documented in a comment but never read. - test_server: the 503-without-habitat test now exercises the server. - python -m notflyguy starts the server. - README: install table, data root, synthetic stand-in, tests/lint/CI, environment variable reference. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 53 ++++++++++++ README.md | 79 ++++++++++++++--- dr_adapter/dashboard.py | 33 +++++-- dr_adapter/fly_bridge.py | 8 +- notflyguy/__main__.py | 5 ++ notflyguy/chatlog.py | 5 +- notflyguy/circuit.py | 9 +- notflyguy/connectome.py | 18 ++-- notflyguy/habitat.py | 34 ++++++-- notflyguy/motor_training.py | 24 +++--- notflyguy/paths.py | 40 +++++++++ notflyguy/synthetic.py | 139 ++++++++++++++++++++++++++++++ notflyguy/train.py | 11 +-- notflyguy/wiring_control.py | 8 +- tests/conftest.py | 25 +++++- tests/test_chatlog.py | 20 ++++- tests/test_connectome.py | 13 +-- tests/test_dr_dashboard.py | 68 +++++++++++++++ tests/test_groupchat.py | 23 ++--- tests/test_habitat.py | 12 +++ tests/test_paths_and_synthetic.py | 105 ++++++++++++++++++++++ tests/test_server.py | 12 ++- tests/test_wiring_control.py | 23 ++--- 23 files changed, 659 insertions(+), 108 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 notflyguy/__main__.py create mode 100644 notflyguy/paths.py create mode 100644 notflyguy/synthetic.py create mode 100644 tests/test_dr_dashboard.py create mode 100644 tests/test_paths_and_synthetic.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2a38a75 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: ruff + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install --upgrade pip + - run: python -m pip install -e '.[dev]' + - run: ruff check . + + test: + name: pytest (py${{ matrix.python-version }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - run: python -m pip install --upgrade pip + - run: python -m pip install -e '.[dev]' + # No MaleCNS download in CI: the test session writes a synthetic circuit + # (see tests/conftest.py) and points NOTFLYGUY_DATA_ROOT at it. + - run: python -m pytest -q + - name: Dashboard smoke run (no body, no model) + run: | + python -m notflyguy.synthetic --root "$RUNNER_TEMP/circuit" > /dev/null + NOTFLYGUY_DATA_ROOT="$RUNNER_TEMP/circuit" timeout 20 python -m notflyguy.server --no-body --no-replies --port 8766 & + for i in $(seq 1 20); do curl -fsS http://127.0.0.1:8766/api/state > /dev/null && break; sleep 1; done + curl -fsS http://127.0.0.1:8766/api/state | python -c 'import json,sys; s=json.load(sys.stdin); assert s["chat"]["circuit_loaded"], s' + curl -fsS http://127.0.0.1:8766/ | grep -q NotFlyGuy diff --git a/README.md b/README.md index 49fe941..dfff579 100644 --- a/README.md +++ b/README.md @@ -25,20 +25,52 @@ results and their limits, and [docs/wiring-control.md](docs/wiring-control.md) for the control that tests whether the measured wiring beats a rewired graph of the same size. It currently does not. -## Setup +## Install -`data/` is not committed, so a fresh clone must reproduce the circuit first. +Python 3.10–3.12 (FlyBody's documented environment is 3.10; the core package +needs only numpy and scipy). ```bash python3.12 -m venv .venv source .venv/bin/activate -pip install -e '.[dev,connectome,body]' -python scripts/bootstrap_data.py # download + extract the measured circuit +pip install -e '.[dev]' # core + pytest + ruff ``` -`bootstrap_data.py` runs the three derivation steps in order: fetch and -checksum the published MaleCNS feather tables, catalog the annotated leg motor -neurons, then induce the motor-centred subgraph. +Optional extras: + +| extra | adds | needed for | +|--------------|----------------------------------------|----------------------------------------------| +| `connectome` | `pyarrow` | reading the released MaleCNS feather tables | +| `body` | FlyBody (pinned git commit) + Pillow | the MuJoCo body and the dashboard's frames | +| `all` | everything above | | + +### Get the measured circuit + +`data/` is not committed. Reproduce the circuit from the published MaleCNS +v1.0 release (a large download) once per clone: + +```bash +pip install -e '.[connectome]' +python scripts/bootstrap_data.py # fetch + checksum, catalog leg motor neurons, extract subgraph +``` + +`bootstrap_data.py` runs the three derivation steps in order and writes +`data/malecns-v1.0/{motor-circuit.npz,motor-circuit.json,leg-motor-catalog.json}`. + +Every loader resolves that directory through `notflyguy.paths.data_root()`: +set **`NOTFLYGUY_DATA_ROOT`** to use a circuit stored elsewhere (a shared +download, a read-only mount, or the synthetic stand-in below). + +### Run without the download + +A random circuit with the same file layout lets you exercise the dashboard, +the trainer plumbing, and the tests without fetching anything. It is **not +measured biology** and says so in its `motor-circuit.json` (`"synthetic": true`). + +```bash +python -m notflyguy.synthetic --root /path/to/fake-circuit +NOTFLYGUY_DATA_ROOT=/path/to/fake-circuit python -m notflyguy.server --no-body +``` ## Run the dashboard @@ -110,20 +142,43 @@ declared range. The all-zeros command is a strong do-nothing local optimum at completed a held-out evaluation that beats the zero baseline by a real margin. See [docs/learning-baseline.md](docs/learning-baseline.md). -## Tests +## Tests and lint ```bash -python -m pytest -q +python -m pytest -q # ~25 s +ruff check . # lint + import order; `ruff check . --fix` applies the safe fixes ``` -No test requires FlyBody, MuJoCo, or a live server; the simulator is faked and -the corpus is synthetic. The circuit tests skip themselves when `data/` has not -been bootstrapped. +No test requires FlyBody, MuJoCo, a live server, or the MaleCNS download: the +simulator is faked, the Hermes corpus is synthetic, and when `data/` has not +been bootstrapped the test session writes a synthetic circuit once and points +`NOTFLYGUY_DATA_ROOT` at it (`tests/conftest.py`). If the measured circuit is +present it is used instead. Tests assert contracts -- shapes, determinism, +stability bounds, labels -- never biological results, so they are valid on +either. + +CI (`.github/workflows/ci.yml`) runs ruff and the suite on Python 3.10, 3.11 +and 3.12 on every push and pull request, then boots the dashboard against a +synthetic circuit and checks `/api/state`. + +## Environment variables + +| variable | default | purpose | +|-------------------------|--------------------------------------|-----------------------------------------------------| +| `NOTFLYGUY_DATA_ROOT` | `data/malecns-v1.0` | directory holding the circuit and leg catalog | +| `NOTFLYGUY_LLM_URL` | `http://127.0.0.1:8083` | OpenAI-compatible endpoint for dashboard replies | +| `NOTFLYGUY_LLM_MODEL` | first model the endpoint lists | model name sent with each completion | +| `NOTFLYGUY_HERMES_DB` | `~/.hermes/**/state.db` | colon-separated Hermes databases for the trainer | +| `NOTFLYGUY_GATEWAY_LOG` | `~/.hermes/profiles/not-rocky/logs/agent.log` | gateway log the dashboard watches for activity | +| `NOTFLYGUY_ID_SALT` | `notflyguy/v1` | pseudonymisation salt for exported identifiers (read at import) | +| `NOTFLYGUY_BASE` | `http://127.0.0.1:8765` | habitat URL the Hermes plugin talks to | +| `NOTFLYGUY_DR_AUTOSTART`| unset | `1` starts the DragonRealms pilot with the server (needs `NOTFLYGUY_DR_URL/USER/PASSWORD`) | ## Development notes Targets Python 3.10–3.12 because FlyBody's documented environment uses 3.10. Python 3.14 is intentionally not used for the simulator environment. +`python -m notflyguy` is a shortcut for `python -m notflyguy.server`. The native [Hermes integration](integrations/hermes/README.md) registers `/fly` commands, feeds the circuit, and injects the policy reading as advisory style diff --git a/dr_adapter/dashboard.py b/dr_adapter/dashboard.py index 8ec5a99..aa6adbe 100644 --- a/dr_adapter/dashboard.py +++ b/dr_adapter/dashboard.py @@ -1,12 +1,34 @@ from __future__ import annotations -import argparse, json, threading, time -from pathlib import Path + +import argparse +import json +import threading +import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from .action_space import Action -from .observation import Observation, parse_transcript, from_game_state +from pathlib import Path +from urllib.parse import urlsplit + +from .observation import from_game_state, parse_transcript from .policy import Proposal, propose from .transport import GameTransport, MockTransport + +def origin_ok(headers) -> bool: + """Same-origin check for browser writes; non-browser clients send no Origin. + + ``/api/approve`` sends a real game command, so a page from any other origin + open in the same browser must not be able to drive it. Mirrors + ``notflyguy.server._origin_ok``. + """ + origin = headers.get('Origin') + if origin is None: + return True + host = headers.get('Host') + if not host: + return False + parsed = urlsplit(origin) + return parsed.scheme in ('http', 'https') and parsed.netloc == host + class Adapter: def __init__(self, transport: GameTransport, combat_command="attack", fly_bridge=None): self.transport, self.combat_command, self.fly_bridge = transport, combat_command, fly_bridge @@ -93,6 +115,7 @@ def do_GET(self): self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8"); self.send_header('Cache-Control', 'no-store'); self.send_header("Content-Length", str(len(body))); self.end_headers(); return self.wfile.write(body) return self.send_json({"error":"not found"},404) def do_POST(self): + if not origin_ok(self.headers): return self.send_json({"error": "origin not allowed"}, 403) try: length=int(self.headers.get("Content-Length","0")); body=json.loads(self.rfile.read(min(length,16384))) except (ValueError, json.JSONDecodeError): return self.send_json({"error":"invalid JSON"},400) if self.path == "/api/observe" and isinstance(body,dict) and isinstance(body.get("text"),str): return self.send_json(self.adapter.observe(body["text"])) @@ -110,8 +133,8 @@ def main(): transport = MockTransport() bridge = None if args.dr_url: - from .transport import DragonRealmsHTTPTransport from .fly_bridge import FlyBridge + from .transport import DragonRealmsHTTPTransport transport = (DragonRealmsHTTPTransport(args.dr_url, args.dr_token) if args.dr_token else DragonRealmsHTTPTransport.bootstrap(args.dr_url, args.user, args.password, args.character)) diff --git a/dr_adapter/fly_bridge.py b/dr_adapter/fly_bridge.py index 474afc7..aa8d86b 100644 --- a/dr_adapter/fly_bridge.py +++ b/dr_adapter/fly_bridge.py @@ -1,13 +1,17 @@ """Small public bridge from DR observations into the downloaded Fly circuit.""" from __future__ import annotations + import numpy as np + from .observation import Observation + class FlyBridge: namespace = 'notflyguy.dr_adapter' def __init__(self, circuit_root=None, seed=0, checkpoint=None, learning_rate=.002): - from notflyguy.connectome import ConnectomeState, DEFAULT_ROOT - self.brain = ConnectomeState(circuit_root or DEFAULT_ROOT, seed=seed, drive_channels=5) + from notflyguy.connectome import ConnectomeState + # ``None`` resolves to NOTFLYGUY_DATA_ROOT or the in-repo default. + self.brain = ConnectomeState(circuit_root or None, seed=seed, drive_channels=5) self.checkpoint = checkpoint self.learning_rate = float(learning_rate) self.updates = 0 diff --git a/notflyguy/__main__.py b/notflyguy/__main__.py new file mode 100644 index 0000000..553b35e --- /dev/null +++ b/notflyguy/__main__.py @@ -0,0 +1,5 @@ +"""``python -m notflyguy`` starts the habitat server and dashboard.""" +from .server import main + +if __name__ == '__main__': + main() diff --git a/notflyguy/chatlog.py b/notflyguy/chatlog.py index c5da8a1..c3dcf1d 100644 --- a/notflyguy/chatlog.py +++ b/notflyguy/chatlog.py @@ -22,8 +22,9 @@ from pathlib import Path # Pseudonymisation salt. Stable by default so handles are reproducible across -# runs; override with NOTFLYGUY_ID_SALT when sharing derived data. -DEFAULT_SALT = 'notflyguy/v1' +# runs; override with NOTFLYGUY_ID_SALT when sharing derived data. Read once at +# import so every module (trainer, habitat, plugin) agrees on the same handles. +DEFAULT_SALT = os.environ.get('NOTFLYGUY_ID_SALT') or 'notflyguy/v1' MAX_TEXT = 8000 AGENT_SENDER = 'agent' diff --git a/notflyguy/circuit.py b/notflyguy/circuit.py index 90280b8..109c766 100644 --- a/notflyguy/circuit.py +++ b/notflyguy/circuit.py @@ -8,12 +8,12 @@ from __future__ import annotations import json -from pathlib import Path import numpy as np from .connectome import ConnectomeState from .motor_projection import LegMotorReadout +from .paths import CATALOG_FILE, data_root # The walk_on_ball task's reward target. Kept here so the controller and the # trainer cannot disagree about what the fly is being asked to do. @@ -27,11 +27,12 @@ class MotorCircuitController: def __init__(self, root, actuator_names, seed=0, decay=0.2, drive_scale=6.0, action_limits=None): - root = Path(root) - catalog = root / 'leg-motor-catalog.json' + root = data_root(root) + catalog = root / CATALOG_FILE if not catalog.exists(): raise FileNotFoundError( - f'Missing {catalog}. Run scripts/catalog_leg_neurons.py first.' + f'Missing {catalog}. Run scripts/catalog_leg_neurons.py first, or point ' + 'NOTFLYGUY_DATA_ROOT at a directory that holds it.' ) self.brain = ConnectomeState(root, seed=seed, gain=0.8, decay=decay, drive_scale=drive_scale, drive_channels=3) diff --git a/notflyguy/connectome.py b/notflyguy/connectome.py index 913eb9f..151e493 100644 --- a/notflyguy/connectome.py +++ b/notflyguy/connectome.py @@ -14,12 +14,12 @@ from __future__ import annotations import json -from pathlib import Path import numpy as np from scipy.sparse import csr_matrix, diags -DEFAULT_ROOT = Path(__file__).resolve().parents[1] / 'data' / 'malecns-v1.0' +from .paths import CIRCUIT_FILE, SUMMARY_FILE, data_root +from .paths import DEFAULT_DATA_ROOT as DEFAULT_ROOT # noqa: F401 (kept for callers) # Number of modeled sensory drive channels injected into upstream neurons. DRIVE_CHANNELS = 5 @@ -37,15 +37,17 @@ class ConnectomeDataMissing(RuntimeError): class ConnectomeState: """Fixed recurrent dynamics with an explicit, replaceable input projection.""" - def __init__(self, root=DEFAULT_ROOT, seed=0, gain=0.8, decay=0.8, + def __init__(self, root=None, seed=0, gain=0.8, decay=0.8, drive_scale=6.0, drive_channels=DRIVE_CHANNELS, - circuit_file='motor-circuit.npz'): - root = Path(root) + circuit_file=CIRCUIT_FILE): + root = data_root(root) circuit = root / circuit_file if not circuit.exists(): raise ConnectomeDataMissing( f'Missing {circuit}. Run scripts/fetch_connectome.py, then ' - 'scripts/catalog_leg_neurons.py, then scripts/extract_motor_circuit.py.' + 'scripts/catalog_leg_neurons.py, then scripts/extract_motor_circuit.py ' + '(or python scripts/bootstrap_data.py for all three), or point ' + 'NOTFLYGUY_DATA_ROOT at a directory that already holds the circuit.' ) graph = np.load(circuit, allow_pickle=False) self.body_ids = graph['body_ids'] @@ -123,9 +125,9 @@ def feature_names() -> tuple[str, ...]: 'mean_abs_motor', 'mean_upstream', 'mean_abs_upstream', 'peak_activity') -def load_summary(root=DEFAULT_ROOT) -> dict: +def load_summary(root=None) -> dict: """Read the recorded extraction summary, if present.""" - path = Path(root) / 'motor-circuit.json' + path = data_root(root) / SUMMARY_FILE if not path.exists(): raise ConnectomeDataMissing(f'Missing {path}. Run scripts/extract_motor_circuit.py.') return json.loads(path.read_text()) diff --git a/notflyguy/habitat.py b/notflyguy/habitat.py index 71323d6..c8fe1e2 100644 --- a/notflyguy/habitat.py +++ b/notflyguy/habitat.py @@ -11,7 +11,6 @@ """ from __future__ import annotations -import base64 import io import json import threading @@ -20,10 +19,12 @@ from queue import Empty, SimpleQueue from .chat_activity import ChatActivity -from .chatlog import ChatEvent, pseudonym, DEFAULT_SALT +from .chatlog import DEFAULT_SALT, ChatEvent, pseudonym +from .paths import DEFAULT_DATA_ROOT, REPO_ROOT, data_root -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_CIRCUIT_ROOT = ROOT / 'data' / 'malecns-v1.0' +ROOT = REPO_ROOT +DEFAULT_CIRCUIT_ROOT = DEFAULT_DATA_ROOT +DEFAULT_ALIASES = ('notflyguy', 'not-rocky', 'not rocky') DEFAULT_POLICY = ROOT / 'data' / 'training' / 'chat-policy-v1' / 'policy.npz' DEFAULT_SHADOW_LOG = ROOT / 'data' / 'training' / 'chat-policy-v1' / 'shadow.jsonl' @@ -85,10 +86,15 @@ def __init__(self, env=None, controller=None, chat_brain=None, policy=None, # -- construction ------------------------------------------------------ @classmethod - def create(cls, circuit_root=DEFAULT_CIRCUIT_ROOT, policy_path=DEFAULT_POLICY, + def create(cls, circuit_root=None, policy_path=DEFAULT_POLICY, shadow_log=DEFAULT_SHADOW_LOG, with_body=True, llm_url=None, - llm_model=None, llm=None, **kwargs) -> 'Habitat': - """Best-effort construction: a missing body, circuit, policy, or model degrades.""" + llm_model=None, llm=None, **kwargs) -> Habitat: + """Best-effort construction: a missing body, circuit, policy, or model degrades. + + ``circuit_root`` defaults to :func:`notflyguy.paths.data_root`, so + ``NOTFLYGUY_DATA_ROOT`` is honoured. + """ + circuit_root = data_root(circuit_root) env = controller = chat_brain = policy = None if with_body: try: @@ -242,8 +248,17 @@ def _ingest_group_message(self, payload: dict): self.chat_counts['groups'] = len(self._known_groups) sender_raw = str(payload.get('sender') or 'unknown') text = str(payload.get('text') or '')[:2000] - aliases = payload.get('aliases') or ('notflyguy', 'not-rocky', 'not rocky') - addressed = any(a.lower() in text.lower() for a in aliases if a) + aliases = payload.get('aliases') + if isinstance(aliases, str): + # A bare string would otherwise be iterated character by character, + # marking nearly every message as addressed to the fly. + aliases = (aliases,) + elif not isinstance(aliases, (list, tuple)): + aliases = () + aliases = tuple(a.strip() for a in aliases if isinstance(a, str) and a.strip()) + if not aliases: + aliases = DEFAULT_ALIASES + addressed = any(a.lower() in text.lower() for a in aliases) chat_type = str(payload.get('chat_type') or 'group') event = ChatEvent( session_id=group_id, group_id=group_id, @@ -261,6 +276,7 @@ def _ingest_group_message(self, payload: dict): decision['error'] = 'connectome unavailable' else: import numpy as np + from .groupchat import CONTEXT_NAMES context, connectome = self.chat_tracker.observe_user(event) features = np.concatenate([context, connectome]) diff --git a/notflyguy/motor_training.py b/notflyguy/motor_training.py index e7aefc4..6364157 100644 --- a/notflyguy/motor_training.py +++ b/notflyguy/motor_training.py @@ -13,12 +13,14 @@ from __future__ import annotations import json +from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path -from typing import Callable, Mapping import numpy as np +from .paths import CATALOG_FILE, DEFAULT_DATA_ROOT, data_root + # --- Frozen dimensions ----------------------------------------------------- # The catalog holds 381 leg motor neurons and ``walk_on_ball`` exposes 59 # actuators, so the mask has 3048 selectable weights plus 59 biases. @@ -58,25 +60,27 @@ 'walker/adhere_claw_T3_left', 'walker/adhere_claw_T3_right', ) -DEFAULT_CATALOG_ROOT = Path(__file__).resolve().parents[1] / 'data' / 'malecns-v1.0' +DEFAULT_CATALOG_ROOT = DEFAULT_DATA_ROOT # --- Readout construction -------------------------------------------------- -def make_readout(root=DEFAULT_CATALOG_ROOT, actuator_names=None, seed=0, limits=None): +def make_readout(root=None, actuator_names=None, seed=0, limits=None): """Build the frozen :class:`LegMotorReadout` without a MuJoCo import. - ``limits`` is the per-actuator ``[min, max]`` from the live action spec. - Omitting it falls back to a single ``(0, 1)`` range, which is *not* the live - FlyBody spec; pass ``limits_from_spec(env.action_spec())`` to search the - space the body actually accepts. + ``root`` defaults to :func:`notflyguy.paths.data_root` (honouring + ``NOTFLYGUY_DATA_ROOT``). ``limits`` is the per-actuator ``[min, max]`` + from the live action spec. Omitting it falls back to a single ``(0, 1)`` + range, which is *not* the live FlyBody spec; pass + ``limits_from_spec(env.action_spec())`` to search the space the body + actually accepts. """ from .motor_projection import LegMotorReadout - root = Path(root) - catalog = root / 'leg-motor-catalog.json' + catalog = data_root(root) / CATALOG_FILE if not catalog.exists(): raise FileNotFoundError( - f'Missing {catalog}. Run scripts/catalog_leg_neurons.py first.' + f'Missing {catalog}. Run scripts/catalog_leg_neurons.py first, or point ' + 'NOTFLYGUY_DATA_ROOT at a directory that holds it.' ) neurons = json.loads(catalog.read_text())['neurons'] names = tuple(actuator_names) if actuator_names is not None else DEFAULT_ACTUATOR_NAMES diff --git a/notflyguy/paths.py b/notflyguy/paths.py new file mode 100644 index 0000000..8afd3bb --- /dev/null +++ b/notflyguy/paths.py @@ -0,0 +1,40 @@ +"""Where the derived circuit data lives. + +``data/`` is not committed, so every module that loads the measured circuit +needs one agreed place to look. By default that is ``/data/malecns-v1.0``; +set ``NOTFLYGUY_DATA_ROOT`` to point somewhere else (a shared download, a +synthetic stand-in for tests, a read-only mount). The variable is read at call +time, not import time, so a test or a wrapper script can set it after the +package has been imported. +""" +from __future__ import annotations + +import os +from pathlib import Path + +ENV_DATA_ROOT = 'NOTFLYGUY_DATA_ROOT' +REPO_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_DATA_ROOT = REPO_ROOT / 'data' / 'malecns-v1.0' + +CIRCUIT_FILE = 'motor-circuit.npz' +SUMMARY_FILE = 'motor-circuit.json' +CATALOG_FILE = 'leg-motor-catalog.json' + + +def data_root(override=None) -> Path: + """Directory holding ``motor-circuit.npz`` and ``leg-motor-catalog.json``. + + ``override`` wins when given; otherwise ``NOTFLYGUY_DATA_ROOT``; otherwise + the in-repo default. The directory is not required to exist. + """ + if override is not None: + return Path(override).expanduser() + env = os.environ.get(ENV_DATA_ROOT, '').strip() + if env: + return Path(env).expanduser() + return DEFAULT_DATA_ROOT + + +def training_root() -> Path: + """Directory holding trainer output (``data/training//report.json``).""" + return REPO_ROOT / 'data' / 'training' diff --git a/notflyguy/synthetic.py b/notflyguy/synthetic.py new file mode 100644 index 0000000..4bac9c9 --- /dev/null +++ b/notflyguy/synthetic.py @@ -0,0 +1,139 @@ +"""A small random stand-in for the measured circuit, for tests and smoke runs. + +The real circuit is derived from a ~1 GB MaleCNS download +(``scripts/bootstrap_data.py``). Nothing produced here is measured biology: the +graph is random, the "leg motor neurons" are labels assigned round-robin, and +the only thing this stand-in shares with the real artifact is its **file +format** -- the same ``motor-circuit.npz`` keys, the same +``leg-motor-catalog.json`` fields, and a ``motor-circuit.json`` summary whose +``synthetic`` flag is ``true`` so nothing downstream can mistake it for data. + +Use it to run the test suite on a fresh clone, or to start the dashboard +without the download:: + + python -m notflyguy.synthetic --root /tmp/fake-circuit + NOTFLYGUY_DATA_ROOT=/tmp/fake-circuit python -m notflyguy.server --no-body +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +from .paths import CATALOG_FILE, CIRCUIT_FILE, SUMMARY_FILE + +# The real catalog holds 381 annotated leg motor neurons; the readout's frozen +# parameter count (3107) follows from that, so the default matches it. +DEFAULT_MOTOR_NEURONS = 381 +DEFAULT_UPSTREAM_NEURONS = 256 +DEFAULT_EDGES_PER_NODE = 12 + +LEGS = (('T1', 'L', 'fl'), ('T1', 'R', 'fl'), ('T2', 'L', 'ml'), + ('T2', 'R', 'ml'), ('T3', 'L', 'hl'), ('T3', 'R', 'hl')) + + +def synthetic_catalog(n_motor: int = DEFAULT_MOTOR_NEURONS, first_id: int = 10_000) -> dict: + """Catalog shaped like ``scripts/catalog_leg_neurons.py`` output.""" + neurons = [] + for index in range(n_motor): + neuromere, side, subclass = LEGS[index % len(LEGS)] + neurons.append({'bodyId': first_id + index, 'type': f'synthetic-{subclass}-{index}', + 'subclass': subclass, 'somaSide': side, 'somaNeuromere': neuromere, + 'consensus_nt': None}) + counts: dict[str, int] = {} + for neuron in neurons: + counts[neuron['subclass']] = counts.get(neuron['subclass'], 0) + 1 + return { + 'dataset': 'synthetic stand-in (not MaleCNS)', + 'synthetic': True, + 'selection': 'labels assigned round-robin over six legs; no biology', + 'count': len(neurons), + 'counts_by_subclass': counts, + 'limitations': ['Synthetic labels. Not a measured catalog.'], + 'neurons': neurons, + } + + +def synthetic_graph(n_motor: int = DEFAULT_MOTOR_NEURONS, + n_upstream: int = DEFAULT_UPSTREAM_NEURONS, + edges_per_node: int = DEFAULT_EDGES_PER_NODE, seed: int = 0) -> dict: + """Random sparse digraph in the ``motor-circuit.npz`` layout. + + Every motor neuron receives at least one upstream edge, no node has a + self-loop, and there are no duplicate edges, so the stand-in satisfies the + same invariants the wiring control relies on. + """ + if n_motor < 1 or n_upstream < 1: + raise ValueError('need at least one motor and one upstream neuron') + rng = np.random.default_rng(seed) + motors = np.arange(10_000, 10_000 + n_motor, dtype=np.int64) + upstream = np.arange(20_000, 20_000 + n_upstream, dtype=np.int64) + nodes = np.unique(np.concatenate([motors, upstream])) + n_nodes = len(nodes) + motor_idx = np.searchsorted(nodes, motors) + upstream_idx = np.searchsorted(nodes, upstream) + + edges: set[tuple[int, int]] = set() + # Guaranteed upstream -> motor coverage. + for i, target in enumerate(motor_idx): + source = upstream_idx[i % n_upstream] + edges.add((int(source), int(target))) + # Random fan-out from every node, skipping self-loops. + for source in range(n_nodes): + targets = rng.choice(n_nodes, size=min(edges_per_node, n_nodes - 1), replace=False) + for target in targets: + if int(target) != source: + edges.add((source, int(target))) + ordered = sorted(edges) + pre = np.array([e[0] for e in ordered], dtype=np.int64) + post = np.array([e[1] for e in ordered], dtype=np.int64) + counts = rng.geometric(0.15, size=len(ordered)).astype(np.int64) + return {'body_ids': nodes, 'pre': pre, 'post': post, 'synapse_counts': counts, + 'motor_indices': motor_idx, 'upstream_indices': upstream_idx} + + +def write_synthetic_circuit(root, n_motor: int = DEFAULT_MOTOR_NEURONS, + n_upstream: int = DEFAULT_UPSTREAM_NEURONS, + edges_per_node: int = DEFAULT_EDGES_PER_NODE, + seed: int = 0) -> dict: + """Write the three files the package loads; return the summary.""" + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + catalog = synthetic_catalog(n_motor) + graph = synthetic_graph(n_motor, n_upstream, edges_per_node, seed) + np.savez_compressed(root / CIRCUIT_FILE, **graph) + (root / CATALOG_FILE).write_text(json.dumps(catalog, indent=2) + '\n') + summary = { + 'dataset': 'synthetic stand-in (not MaleCNS)', + 'synthetic': True, + 'seed': int(seed), + 'nodes': int(len(graph['body_ids'])), + 'edges': int(len(graph['pre'])), + 'motor_neurons': int(n_motor), + 'selection': 'random graph with the motor-circuit.npz layout; no biology', + 'limitations': ['Random wiring. Any result computed on it says nothing about the fly.'], + } + (root / SUMMARY_FILE).write_text(json.dumps(summary, indent=2) + '\n') + return summary + + +def main() -> None: + parser = argparse.ArgumentParser( + description='Write a synthetic circuit so the package can run without the ' + 'MaleCNS download. The result is random, not measured.') + parser.add_argument('--root', required=True, help='directory to write into') + parser.add_argument('--motor', type=int, default=DEFAULT_MOTOR_NEURONS) + parser.add_argument('--upstream', type=int, default=DEFAULT_UPSTREAM_NEURONS) + parser.add_argument('--edges-per-node', type=int, default=DEFAULT_EDGES_PER_NODE) + parser.add_argument('--seed', type=int, default=0) + args = parser.parse_args() + summary = write_synthetic_circuit(args.root, args.motor, args.upstream, + args.edges_per_node, args.seed) + print(json.dumps(summary, indent=2)) + print(f'Point NOTFLYGUY_DATA_ROOT at {Path(args.root).resolve()} to use it.') + + +if __name__ == '__main__': + main() diff --git a/notflyguy/train.py b/notflyguy/train.py index e0822ac..852acb7 100644 --- a/notflyguy/train.py +++ b/notflyguy/train.py @@ -71,8 +71,9 @@ def build_parser() -> argparse.ArgumentParser: '(0 = all training seeds). The sampler still covers every training seed.') parser.add_argument('--seed', type=int, default=17, help='optimizer RNG seed') parser.add_argument('--output', default=DEFAULT_OUTPUT, help='new output directory') - parser.add_argument('--catalog-root', default=str(mt.DEFAULT_CATALOG_ROOT), - help='directory holding leg-motor-catalog.json') + parser.add_argument('--catalog-root', default=None, + help='directory holding leg-motor-catalog.json (default: ' + f'NOTFLYGUY_DATA_ROOT or {mt.DEFAULT_CATALOG_ROOT})') return parser @@ -155,7 +156,7 @@ def main(argv=None) -> int: 'using the live order'}), flush=True) controller = MotorCircuitController( - Path(args.catalog_root), actuator_names, + args.catalog_root, actuator_names, action_limits=limits_from_spec(spec)) space = mt.ParameterSpace(controller.readout, mode=args.parameterization, rank=args.rank) @@ -327,8 +328,8 @@ def evaluate_policy(policy, seeds, steps: int) -> dict: 'seed_degeneracy_note': ( 'walk_on_ball() does not randomize the episode: every seed produced a bit-identical ' 'zero-baseline reward in this build, so "held-out seeds" are nominal only. The ' - 'genuine held-out axis here is episode length (train %d steps vs eval %d steps).' - % (args.steps, args.eval_steps) + f'genuine held-out axis here is episode length (train {args.steps} steps vs eval ' + f'{args.eval_steps} steps).' ) if seeds_degenerate else 'Held-out seeds produced distinct baseline rewards.', }, 'limitations': [ diff --git a/notflyguy/wiring_control.py b/notflyguy/wiring_control.py index 0556fff..54e2968 100644 --- a/notflyguy/wiring_control.py +++ b/notflyguy/wiring_control.py @@ -19,14 +19,14 @@ import argparse import json -from collections import Counter from pathlib import Path import numpy as np from .chatlog import default_db_paths, load_all -from .connectome import DEFAULT_ROOT, ConnectomeState +from .connectome import ConnectomeState from .groupchat import build_decision_points +from .paths import CIRCUIT_FILE, data_root from .train_chat import evaluate_cross_validation DEFAULT_OUTPUT = 'data/training/wiring-control' @@ -231,7 +231,9 @@ def evaluate(source_npz, events, shuffle_seeds=SHUFFLE_SEEDS, folds=5, l2=1.0, def main() -> None: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--circuit', default=str(DEFAULT_ROOT / 'motor-circuit.npz')) + parser.add_argument('--circuit', default=str(data_root() / CIRCUIT_FILE), + help='measured circuit to compare against (default honours ' + 'NOTFLYGUY_DATA_ROOT)') parser.add_argument('--output', default=DEFAULT_OUTPUT) parser.add_argument('--chat-types', default='all', help="comma-separated sessions.chat_type filter, or 'all'") diff --git a/tests/conftest.py b/tests/conftest.py index 296d848..037e323 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,6 +4,30 @@ import pytest +@pytest.fixture(scope='session', autouse=True) +def circuit_root(tmp_path_factory): + """Guarantee a loadable circuit for the whole session. + + If the measured circuit has been bootstrapped (or ``NOTFLYGUY_DATA_ROOT`` + already points at one) it is used as-is. Otherwise a synthetic stand-in is + written once and ``NOTFLYGUY_DATA_ROOT`` is pointed at it, so a fresh clone + runs the full suite without the MaleCNS download. The stand-in is random: + tests assert contracts (shapes, determinism, bounds), never biology. + """ + from notflyguy.paths import CIRCUIT_FILE, data_root + from notflyguy.synthetic import write_synthetic_circuit + + root = data_root() + if (root / CIRCUIT_FILE).exists(): + yield root + return + root = tmp_path_factory.mktemp('synthetic-circuit') + write_synthetic_circuit(root) + with pytest.MonkeyPatch.context() as patch: + patch.setenv('NOTFLYGUY_DATA_ROOT', str(root)) + yield root + + def _create_schema(connection): connection.executescript( """ @@ -159,7 +183,6 @@ def step(self, action): return FakeTimestep(self._reward, last) def action_spec(self): - import numpy as np return type('Spec', (), {'shape': (4,)})() diff --git a/tests/test_chatlog.py b/tests/test_chatlog.py index 2b026bc..db388cf 100644 --- a/tests/test_chatlog.py +++ b/tests/test_chatlog.py @@ -1,7 +1,7 @@ """Transcript loading: identity handling, filtering, and text-free summaries.""" import json -from notflyguy.chatlog import ChatEvent, corpus_stats, load_events, load_all, pseudonym +from notflyguy.chatlog import ChatEvent, corpus_stats, load_all, load_events, pseudonym def test_pseudonym_is_stable_distinct_and_not_reversible(): @@ -86,3 +86,21 @@ def test_chat_event_is_hashable_and_frozen(group_events): except Exception: return raise AssertionError('ChatEvent should be immutable') + + +def test_salt_can_be_overridden_through_the_environment(monkeypatch): + """The documented NOTFLYGUY_ID_SALT override must actually change the handles.""" + import importlib + + import notflyguy.chatlog as chatlog + stable = chatlog.pseudonym('+15550001') + monkeypatch.setenv('NOTFLYGUY_ID_SALT', 'shared-export') + try: + reloaded = importlib.reload(chatlog) + assert reloaded.DEFAULT_SALT == 'shared-export' + assert reloaded.pseudonym('+15550001') != stable + assert reloaded.pseudonym('+15550001') == chatlog.pseudonym('+15550001', 'shared-export') + finally: + monkeypatch.delenv('NOTFLYGUY_ID_SALT') + importlib.reload(chatlog) + assert chatlog.pseudonym('+15550001') == stable diff --git a/tests/test_connectome.py b/tests/test_connectome.py index c99efe0..9b0617b 100644 --- a/tests/test_connectome.py +++ b/tests/test_connectome.py @@ -2,13 +2,7 @@ import numpy as np import pytest -from notflyguy.connectome import (DRIVE_CHANNELS, DRIVE_NAMES, ConnectomeDataMissing, - ConnectomeState, load_summary) - -requires_data = pytest.mark.skipif( - not (ConnectomeState and __import__('pathlib').Path('data/malecns-v1.0/motor-circuit.npz').exists()), - reason='measured circuit not extracted', -) +from notflyguy.connectome import DRIVE_CHANNELS, DRIVE_NAMES, ConnectomeDataMissing, ConnectomeState, load_summary def test_drive_contract_is_documented(): @@ -16,7 +10,6 @@ def test_drive_contract_is_documented(): assert len(set(DRIVE_NAMES)) == DRIVE_CHANNELS -@requires_data def test_recurrent_operator_cannot_diverge(): brain = ConnectomeState() row_sums = np.asarray(abs(brain.recurrent).sum(axis=1)).ravel() @@ -30,7 +23,6 @@ def test_recurrent_operator_cannot_diverge(): assert np.abs(brain.activity).max() <= 1.0 + 1e-9 -@requires_data def test_zero_drive_leaves_the_circuit_quiet(): brain = ConnectomeState() brain.reset() @@ -39,7 +31,6 @@ def test_zero_drive_leaves_the_circuit_quiet(): assert np.allclose(brain.activity, 0.0) -@requires_data def test_drive_changes_activity(): brain = ConnectomeState() brain.reset() @@ -54,7 +45,6 @@ def test_drive_changes_activity(): assert np.abs(driven).max() > 0.01 -@requires_data def test_step_validates_drive_shape_and_finiteness(): brain = ConnectomeState() with pytest.raises(ValueError): @@ -63,7 +53,6 @@ def test_step_validates_drive_shape_and_finiteness(): brain.step(np.array([np.nan] * DRIVE_CHANNELS)) -@requires_data def test_feature_contract_is_consistent(): brain = ConnectomeState() assert len(brain.features()) == len(brain.feature_names()) == 8 diff --git a/tests/test_dr_dashboard.py b/tests/test_dr_dashboard.py new file mode 100644 index 0000000..28849ab --- /dev/null +++ b/tests/test_dr_dashboard.py @@ -0,0 +1,68 @@ +"""DR adapter dashboard: origin defence for the command-sending endpoints.""" +import json +from http.server import ThreadingHTTPServer +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +import pytest + +from dr_adapter.dashboard import Adapter, Handler, origin_ok +from dr_adapter.transport import MockTransport + + +@pytest.fixture +def dr_server(): + class TestHandler(Handler): + adapter = Adapter(MockTransport()) + training_state = None + + httpd = ThreadingHTTPServer(('127.0.0.1', 0), TestHandler) + import threading + threading.Thread(target=httpd.serve_forever, daemon=True).start() + host, port = httpd.server_address[:2] + try: + yield f'http://{host}:{port}' + finally: + httpd.shutdown() + httpd.server_close() + + +def _post(url, payload, origin=None): + headers = {'Content-Type': 'application/json'} + if origin: + headers['Origin'] = origin + request = Request(url, data=json.dumps(payload).encode(), headers=headers, method='POST') + try: + with urlopen(request, timeout=5) as response: + return response.status, json.loads(response.read()) + except HTTPError as error: + return error.code, json.loads(error.read() or b'null') + + +def test_origin_ok_is_same_origin_only(): + assert origin_ok({'Host': '127.0.0.1:8787'}) is True # non-browser + assert origin_ok({'Host': '127.0.0.1:8787', 'Origin': 'http://127.0.0.1:8787'}) is True + assert origin_ok({'Host': '127.0.0.1:8787', 'Origin': 'http://127.0.0.1:1'}) is False + assert origin_ok({'Host': '127.0.0.1:8787', 'Origin': 'http://evil.example'}) is False + assert origin_ok({'Host': '127.0.0.1:8787', 'Origin': 'null'}) is False + assert origin_ok({'Origin': 'http://127.0.0.1:8787'}) is False # no Host + + +def test_cross_origin_approve_is_refused(dr_server): + status, body = _post(dr_server + '/api/approve', {}, origin='http://evil.example') + assert status == 403 + assert body == {'error': 'origin not allowed'} + + +def test_same_origin_and_non_browser_writes_still_work(dr_server): + status, body = _post(dr_server + '/api/pause', {'paused': True}, origin=dr_server) + assert status == 200 and body['paused'] is True + status, body = _post(dr_server + '/api/pause', {'paused': False}) + assert status == 200 and body['paused'] is False + + +def test_state_endpoint_is_readable(dr_server): + with urlopen(dr_server + '/api/state', timeout=5) as response: + snapshot = json.loads(response.read()) + assert snapshot['armed'] is True + assert snapshot['proposal'] is None diff --git a/tests/test_groupchat.py b/tests/test_groupchat.py index f84724b..e121433 100644 --- a/tests/test_groupchat.py +++ b/tests/test_groupchat.py @@ -3,13 +3,15 @@ import pytest from notflyguy.connectome import DRIVE_CHANNELS -from notflyguy.groupchat import (CONTEXT_NAMES, ChatStateTracker, build_decision_points, - dataset_stats, drive_for_agent, drive_for_user, - feature_matrix, feature_names) - -requires_data = pytest.mark.skipif( - not __import__('pathlib').Path('data/malecns-v1.0/motor-circuit.npz').exists(), - reason='measured circuit not extracted', +from notflyguy.groupchat import ( + CONTEXT_NAMES, + ChatStateTracker, + build_decision_points, + dataset_stats, + drive_for_agent, + drive_for_user, + feature_matrix, + feature_names, ) @@ -19,7 +21,6 @@ def test_drive_vectors_match_the_circuit_contract(): assert np.isfinite(drive_for_user('x' * 5000, True, False, 1e9, 99)).all() -@requires_data def test_labels_follow_the_transcript(decision_points): # group-1: reply, reply, no reply (user-user), reply; group-2: reply. assert len(decision_points) == 5 @@ -28,7 +29,6 @@ def test_labels_follow_the_transcript(decision_points): assert dataset_stats(decision_points)['responded'] == 4 -@requires_data def test_silent_decisions_carry_no_length_label(decision_points): silent = [p for p in decision_points if not p.respond] assert silent @@ -37,7 +37,6 @@ def test_silent_decisions_carry_no_length_label(decision_points): assert np.isnan(y_length).sum() == len(silent) -@requires_data def test_features_are_causal(decision_points, group_events): """A prefix of the transcript must produce identical earlier features. @@ -53,7 +52,6 @@ def test_features_are_causal(decision_points, group_events): assert full_point.connectome == pytest.approx(partial_point.connectome) -@requires_data def test_decision_points_are_deterministic(group_events): first = build_decision_points(group_events, seed=0) second = build_decision_points(group_events, seed=0) @@ -61,7 +59,6 @@ def test_decision_points_are_deterministic(group_events): assert [p.connectome for p in first] == [p.connectome for p in second] -@requires_data def test_live_tracker_matches_offline_features(group_events): """Training and serving must produce byte-identical features. @@ -86,7 +83,6 @@ def test_live_tracker_matches_offline_features(group_events): assert connectome == pytest.approx(point.connectome) -@requires_data def test_tracker_reset_clears_state(group_events): from notflyguy.connectome import ConnectomeState tracker = ChatStateTracker(ConnectomeState(seed=0)) @@ -105,7 +101,6 @@ def test_feature_names_match_matrix_width(decision_points): assert len(CONTEXT_NAMES) == X_context.shape[1] -@requires_data def test_dataset_stats_report_group_coverage(decision_points): stats = dataset_stats(decision_points) assert stats['group_decision_points'] == len(decision_points) diff --git a/tests/test_habitat.py b/tests/test_habitat.py index b5897d3..01aa4a6 100644 --- a/tests/test_habitat.py +++ b/tests/test_habitat.py @@ -136,6 +136,18 @@ def test_group_message_without_a_policy_reports_clearly(tmp_path): assert 'respond_probability' not in decision +def test_aliases_payload_is_validated(tmp_path): + """A bare-string alias used to be iterated per character, so 'n' matched everything.""" + habitat = make_habitat(tmp_path) + plain = {'text': 'nothing to see here', 'sender': 'x'} + assert habitat.observe_group_message({**plain, 'aliases': 'notflyguy'})['addressed'] is False + assert habitat.observe_group_message({**plain, 'aliases': 'nothing'})['addressed'] is True + assert habitat.observe_group_message({**plain, 'aliases': ['', 7, None]})['addressed'] is False + assert habitat.observe_group_message({**plain, 'aliases': {'bad': 1}})['addressed'] is False + assert habitat.observe_group_message( + {'text': 'hey not-rocky', 'sender': 'x', 'aliases': []})['addressed'] is True + + def test_group_message_without_a_circuit_reports_an_error(tmp_path): habitat = make_habitat(tmp_path, brain=False) decision = habitat.observe_group_message({'text': 'hi', 'sender': 'x'}) diff --git a/tests/test_paths_and_synthetic.py b/tests/test_paths_and_synthetic.py new file mode 100644 index 0000000..1f232c9 --- /dev/null +++ b/tests/test_paths_and_synthetic.py @@ -0,0 +1,105 @@ +"""Data-root resolution and the synthetic circuit's format contract.""" +import json + +import numpy as np +import pytest + +from notflyguy import motor_training as mt +from notflyguy.connectome import ConnectomeState, load_summary +from notflyguy.paths import CATALOG_FILE, CIRCUIT_FILE, DEFAULT_DATA_ROOT, ENV_DATA_ROOT, SUMMARY_FILE, data_root +from notflyguy.synthetic import synthetic_catalog, synthetic_graph, write_synthetic_circuit + + +# --- paths ------------------------------------------------------------------- +def test_data_root_prefers_explicit_then_env_then_default(tmp_path, monkeypatch): + monkeypatch.delenv(ENV_DATA_ROOT, raising=False) + assert data_root() == DEFAULT_DATA_ROOT + monkeypatch.setenv(ENV_DATA_ROOT, str(tmp_path / 'env')) + assert data_root() == tmp_path / 'env' + assert data_root(tmp_path / 'explicit') == tmp_path / 'explicit' + monkeypatch.setenv(ENV_DATA_ROOT, ' ') + assert data_root() == DEFAULT_DATA_ROOT + + +def test_env_override_is_read_at_call_time(tmp_path, monkeypatch): + """Setting the variable after import must still take effect (tests rely on it).""" + write_synthetic_circuit(tmp_path, n_motor=12, n_upstream=8) + monkeypatch.setenv(ENV_DATA_ROOT, str(tmp_path)) + brain = ConnectomeState() + assert len(brain) == 20 + assert load_summary()['synthetic'] is True + + +def test_missing_circuit_error_mentions_the_override(tmp_path): + with pytest.raises(Exception) as info: + ConnectomeState(tmp_path / 'nowhere') + assert ENV_DATA_ROOT in str(info.value) + + +# --- synthetic circuit ------------------------------------------------------- +def test_synthetic_files_match_the_measured_layout(tmp_path): + summary = write_synthetic_circuit(tmp_path, n_motor=30, n_upstream=20, seed=3) + for name in (CIRCUIT_FILE, CATALOG_FILE, SUMMARY_FILE): + assert (tmp_path / name).exists(), name + with np.load(tmp_path / CIRCUIT_FILE, allow_pickle=False) as graph: + assert set(graph.files) == {'body_ids', 'pre', 'post', 'synapse_counts', + 'motor_indices', 'upstream_indices'} + assert len(graph['motor_indices']) == 30 + assert len(graph['upstream_indices']) == 20 + assert len(graph['pre']) == len(graph['post']) == len(graph['synapse_counts']) + assert summary['edges'] == len(graph['pre']) + catalog = json.loads((tmp_path / CATALOG_FILE).read_text()) + assert catalog['count'] == len(catalog['neurons']) == 30 + assert summary['synthetic'] is True + assert json.loads((tmp_path / SUMMARY_FILE).read_text())['synthetic'] is True + + +def test_synthetic_graph_has_no_self_loops_or_duplicates_and_covers_motors(): + graph = synthetic_graph(n_motor=40, n_upstream=16, edges_per_node=5, seed=1) + pre, post = graph['pre'], graph['post'] + assert not np.any(pre == post) + assert len(set(zip(pre.tolist(), post.tolist()))) == len(pre) + assert np.all(graph['synapse_counts'] >= 1) + incoming = set(post.tolist()) + assert all(int(m) in incoming for m in graph['motor_indices']) + + +def test_synthetic_graph_is_deterministic_per_seed(): + a = synthetic_graph(n_motor=10, n_upstream=6, seed=7) + b = synthetic_graph(n_motor=10, n_upstream=6, seed=7) + c = synthetic_graph(n_motor=10, n_upstream=6, seed=8) + assert np.array_equal(a['post'], b['post']) + assert np.array_equal(a['synapse_counts'], b['synapse_counts']) + assert not np.array_equal(a['synapse_counts'], c['synapse_counts']) + + +def test_synthetic_catalog_assigns_every_neuron_to_a_leg(): + catalog = synthetic_catalog(n_motor=13) + for neuron in catalog['neurons']: + assert neuron['somaNeuromere'] in ('T1', 'T2', 'T3') + assert neuron['somaSide'] in ('L', 'R') + assert sum(catalog['counts_by_subclass'].values()) == 13 + + +def test_default_synthetic_catalog_reproduces_the_frozen_readout_size(tmp_path): + """381 leg neurons x 8 trainable actuators per leg = 3048 weights, as measured.""" + write_synthetic_circuit(tmp_path) + readout = mt.make_readout(root=tmp_path, seed=0) + assert int(readout.mask.sum()) == mt.N_WEIGHT_PARAMETERS + assert readout.parameters().shape == (mt.N_PARAMETERS,) + + +def test_synthetic_circuit_obeys_the_stability_bound(tmp_path): + write_synthetic_circuit(tmp_path, n_motor=50, n_upstream=30) + brain = ConnectomeState(tmp_path) + row_sums = np.asarray(abs(brain.recurrent).sum(axis=1)).ravel() + assert row_sums.max() <= brain.gain + 1e-9 + for _ in range(100): + brain.step(np.ones(brain.drive_channels)) + assert np.isfinite(brain.activity).all() + assert np.abs(brain.activity).max() <= 1.0 + 1e-9 + + +def test_synthetic_rejects_empty_graphs(): + with pytest.raises(ValueError): + synthetic_graph(n_motor=0) diff --git a/tests/test_server.py b/tests/test_server.py index 85d9de1..8372e5e 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -188,6 +188,14 @@ def test_events_stream_is_not_inline_framed(live_server): assert b'data:image/jpeg;base64' not in chunk -def test_handler_returns_503_without_a_habitat(monkeypatch): +def test_handler_returns_503_without_a_habitat(live_server, monkeypatch): + base, _ = live_server monkeypatch.setattr(server_module, 'HABITAT', None) - assert server_module.HABITAT is None + for route in ('/api/state', '/api/report', '/api/corpus'): + with pytest.raises(HTTPError) as info: + _get(base + route) + assert info.value.code == 503, route + assert json.loads(info.value.read()) == {'error': 'habitat unavailable'} + assert _post(base + '/api/signal', {'message': 'pause'})[0] == 503 + # The page itself still serves, so the dashboard can show its own error state. + assert _get(base + '/')[0] == 200 diff --git a/tests/test_wiring_control.py b/tests/test_wiring_control.py index eba2b2f..d1c976f 100644 --- a/tests/test_wiring_control.py +++ b/tests/test_wiring_control.py @@ -2,8 +2,7 @@ import numpy as np import pytest -from notflyguy.wiring_control import (_degrees, build_shuffled_circuit, evaluate, - shuffle_edges) +from notflyguy.wiring_control import _degrees, build_shuffled_circuit, evaluate, shuffle_edges def _toy_graph(): @@ -99,15 +98,9 @@ def test_build_shuffled_writes_a_loadable_circuit(toy_circuit, tmp_path): # --- evaluate: orchestration only (no real dataset needed) ------------------- -def test_evaluate_refuses_to_claim_on_a_tiny_corpus(toy_circuit, group_events): +def test_evaluate_refuses_to_claim_on_a_tiny_corpus(circuit_root, group_events): """A 13-point corpus must never yield a wiring claim, however the AUCs order.""" - pytest.importorskip('scipy') - from pathlib import Path - real_root = Path('data/malecns-v1.0') - if not (real_root / 'motor-circuit.npz').exists(): - pytest.skip('measured circuit not extracted') - - report = evaluate(Path('data/malecns-v1.0/motor-circuit.npz'), group_events, + report = evaluate(circuit_root / 'motor-circuit.npz', group_events, shuffle_seeds=(0,), folds=2) assert report['verdict']['sufficient_data'] is False assert report['verdict']['claim'].startswith('NOT ESTABLISHED') @@ -115,14 +108,8 @@ def test_evaluate_refuses_to_claim_on_a_tiny_corpus(toy_circuit, group_events): assert 'must not be read as evidence' in report['verdict']['claim'] -def test_evaluate_runs_and_compares_against_shuffles(group_events): - pytest.importorskip('scipy') - from pathlib import Path - real_root = Path('data/malecns-v1.0') - if not (real_root / 'motor-circuit.npz').exists(): - pytest.skip('measured circuit not extracted') - - report = evaluate(Path('data/malecns-v1.0/motor-circuit.npz'), group_events, +def test_evaluate_runs_and_compares_against_shuffles(circuit_root, group_events): + report = evaluate(circuit_root / 'motor-circuit.npz', group_events, shuffle_seeds=(0, 1), folds=2, workdir=None) assert report['real']['mean_roc_auc'] is not None assert len(report['shuffles']) == 2