Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
79 changes: 67 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion dr_adapter/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
1 change: 1 addition & 0 deletions dr_adapter/action_space.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Literal

Expand Down
33 changes: 28 additions & 5 deletions dr_adapter/dashboard.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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"]))
Expand All @@ -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))
Expand Down
8 changes: 5 additions & 3 deletions dr_adapter/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
8 changes: 6 additions & 2 deletions dr_adapter/fly_bridge.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 2 additions & 0 deletions dr_adapter/navigation.py
Original file line number Diff line number Diff line change
@@ -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 = {}
Expand Down
2 changes: 1 addition & 1 deletion dr_adapter/observation.py
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
1 change: 1 addition & 0 deletions dr_adapter/outcome.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
18 changes: 11 additions & 7 deletions dr_adapter/pilot.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions dr_adapter/policy.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion dr_adapter/reward.py
Original file line number Diff line number Diff line change
@@ -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'

Expand Down
5 changes: 4 additions & 1 deletion dr_adapter/training.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
9 changes: 6 additions & 3 deletions dr_adapter/transport.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Loading
Loading