diff --git a/FARMHOUSE-CHANGES.md b/FARMHOUSE-CHANGES.md index af26bd0..62f1228 100644 --- a/FARMHOUSE-CHANGES.md +++ b/FARMHOUSE-CHANGES.md @@ -56,6 +56,13 @@ Forge's concrete priority path, extra typed questions in the same call, a captur How it fits the strategic-intelligence work, what is measured and how to fine-tune: [docs/LAYA-CONNECTIONS.md](docs/LAYA-CONNECTIONS.md). Reference copies of the Laya image, manifests and CI are in `farmhouse/laya/`. +### Forge, and rules-accurate simulation with phase-rs +- **Forge is installed** in the cluster image (it was left out by mistake): `farmhouse/forge/README.md`. Batches are clamped to one game at a time (`FORGE_MAX_THREADS`). +- **Rules-accurate simulation** through the phase-rs engine (Rust, headless): `routes/farmhouse_phase.py`, `ui/phase-sim.html` (linked from the home page) and the service in + `farmhouse/phase/`. Four saved decks play real Commander games; the page shows wins by seat with a 95% interval and warns about cards the engine did not recognise. + Seats can be put on a **model** (twin-turbo through Olla, or Laya): the model chooses among the engine's own legal options only, anything wrong or slow is played by phase's AI, + and a call cap bounds the cost (`farmhouse/phase/README.md`). Assessment and plan: `docs/PHASE-AND-PLAYTESTER.md`. + ## Settings (environment variables) | Variable | Meaning | |---|---| diff --git a/docs/PHASE-AND-PLAYTESTER.md b/docs/PHASE-AND-PLAYTESTER.md index 23c2a89..45e5121 100644 --- a/docs/PHASE-AND-PLAYTESTER.md +++ b/docs/PHASE-AND-PLAYTESTER.md @@ -54,6 +54,17 @@ the engine-smoke gate that boots the real engine and plays a match to completion heuristic-only, LLM and Laya seats. Record every decision for the Laya dataset. 4. **Only then** consider the playtester's UI ideas, after the author adds a licence or as a clean reimplementation. +## What was built from this plan (2026-10-27) +1. **The headless runner** (`ai-commander`, Commander four-player, batch mode) is built from the v0.118.0 tag with the card database that release was published with, in a + container (`farmhouse/phase/Dockerfile`). Not `ai-duel` for the decks: `ai-commander` takes a feed JSON of four decks, which is exactly what the app has. +2. **The service and the app side**: `farmhouse/phase/phase_sim.py` (HTTP, jobs, parser, warnings) and `routes/farmhouse_phase.py` + `ui/phase-sim.html`. Games that stall, hit the + action cap or panic are reported and never counted. +3. **Model seats**: not a setting. phase's model support lives only in its browser client (`engine-wasm` calls `phase-llm`; the HTTP is done by TypeScript), and + `phase-llm` depends on `phase-ai`, so the headless binary cannot use it. `farmhouse/phase/llm-seat/` is a new crate that includes the runner and installs a hook + (two anchored edits to phase's source). The server-side Jev relay and the browser client were not needed. Details: `farmhouse/phase/README.md`. +Not done: the playtester's UI (no licence), a Python client for phase's WebSocket server (a large, fast-moving protocol), feeding the captured model-seat decisions into +`scripts/farmhouse_laya_dataset.py` (the natural next step: each is an engine-issued option list plus a pick). + ## Risks and open questions - Phase is a one-person, fast-moving project: pin tags, keep a smoke test that plays a full game, expect breaking changes. - Rust builds are heavy; keep them in CI/containers. Resource and image size are unmeasured. diff --git a/farmhouse/forge/README.md b/farmhouse/forge/README.md new file mode 100644 index 0000000..19e1c20 --- /dev/null +++ b/farmhouse/forge/README.md @@ -0,0 +1,20 @@ +# Forge in the cluster image + +The batch simulator on the Simulator page runs on **Forge**, the Java rules engine. The first cluster builds left it out by mistake ("Python-only" +was read as "no Java"), so the page answered `Forge JAR not found`. It is now built into the image (reference copy of the Dockerfile stage: +`infrastructure/apps/commander-lab/image/Dockerfile` in the farmhouse-os repo). + +What the image build does: + +1. **Stage 1** (`maven:3.9-eclipse-temurin-17`): fetch the official `Card-Forge/forge` at commit `edb28158f6d8` (the commit `KoalaTrapLord/Forge-Repo` + is on; that fork is 0 commits ahead of upstream, so this is the code the lab's Java was written against; newer Forge may have changed APIs), then + `mvn install -pl forge-gui-desktop -am -DskipTests -Drevision=2.0.12-SNAPSHOT`, retried up to three times (Maven Central downloads fail now and then). +2. **The lab's Java tool** (`LabCli`, from this repository's `pom.xml`) is built against it. Forge's installed poms keep `${revision}` as their parent + version, which Maven cannot resolve for a consumer even with `-Drevision`; the placeholder is rewritten in the installed `.pom` files first. +3. **Runtime**: `openjdk-17-jre-headless`, the two jars, and Forge's `res/` data without `adventure`, `music`, `sound`, `quest` and `skins` + (about 190 MB the headless simulator never reads). The environment the app reads: `FORGE_JAR`, `FORGE_DIR`, `LAB_JAR`, `FORGE_DECKS_DIR`, `PRECON_DIR`, `JAVA_HOME`. +4. `FORGE_MAX_THREADS` (default 1) clamps the batch's thread count: every Forge game is its own JVM with up to a 4 GB heap, and the cluster has two small nodes. +5. CI plays one Commander game with the lab's Java tool before the image is published. + +Speed: about 25 seconds per game, one at a time (the project's own figure is ~0.04 simulations/s single-threaded). For many games with real rules, the +phase-rs engine (`farmhouse/phase/`) is far faster. Forge is GPL-3.0: private use, do not redistribute the built image. diff --git a/farmhouse/phase/Dockerfile b/farmhouse/phase/Dockerfile new file mode 100644 index 0000000..be39d30 --- /dev/null +++ b/farmhouse/phase/Dockerfile @@ -0,0 +1,61 @@ +# phase-sim: rules-accurate four-player Commander games with phase-rs's headless AI (github.com/phase-rs/phase), behind a small HTTP service. +# +# phase is a Rust rules engine (stack, priority, combat, layers, triggers, replacement effects), dual licensed Apache-2.0 / MIT, with card +# data from MTGJSON (MIT). Pinned to release v0.118.0 (commit ad0de6a) and to the card database that release was published with +# (`card-data-5e541a38c99b97f0.json`, named in data.phase-rs.dev/card-data-meta.json for that commit); the file's SHA-256 is checked, so a +# changed file fails the build instead of silently changing results. Nothing is fetched at run time, and the pod has no network. +# +# Built: the `ai-commander` binary (4-player Commander, batch mode) and `ai-duel` with the repo's `server-release` profile (unwinding +# panics, so one game's panic cannot kill a batch). The toolchain is whatever rust-toolchain.toml pins (a dated nightly). +FROM rust:slim-bookworm AS build + +ARG PHASE_REPO=https://github.com/phase-rs/phase.git +ARG PHASE_TAG=v0.118.0 +ARG PHASE_SHA=ad0de6adf00153a6e6eb89604f6670be5b1d5168 +ARG CARD_DATA_URL=https://data.phase-rs.dev/card-data-5e541a38c99b97f0.json +ARG CARD_DATA_SHA256=5e541a38c99b97f0ef12c81f7b249e7cd253f38b32bd5c156cf19608cb6f1218 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl build-essential pkg-config python3 \ + && rm -rf /var/lib/apt/lists/* + +RUN set -eux; \ + mkdir /phase; cd /phase; \ + git init -q; \ + git remote add origin "$PHASE_REPO"; \ + git fetch -q --depth 1 origin "$PHASE_SHA"; \ + git checkout -q FETCH_HEAD; \ + test "$(git rev-parse HEAD)" = "$PHASE_SHA" + +WORKDIR /phase +# phase's server-release profile uses thin LTO and 16 code-generation units; compiling its big engine crate that way ran a 7 GB CI machine +# out of memory ("cannot allocate memory", 2026-10-27). LTO off and two parallel jobs trade some build time (and a few percent of run +# speed) for a build that fits; the optimisation level and panic=unwind (which batch isolation needs) are unchanged. +ENV CARGO_BUILD_JOBS=2 \ + CARGO_PROFILE_SERVER_RELEASE_LTO=off \ + CARGO_PROFILE_SERVER_RELEASE_CODEGEN_UNITS=8 +RUN cargo build --profile server-release -p phase-ai --bin ai-commander --bin ai-duel + +RUN set -eux; \ + curl -fsSL --retry 3 -o /card-data.json "$CARD_DATA_URL"; \ + echo "$CARD_DATA_SHA256 /card-data.json" | sha256sum -c -; \ + cp /phase/client/public/feeds/mtggoldfish-commander.json /sample-feed.json + +FROM python:3.12-slim-bookworm +ARG PHASE_TAG=v0.118.0 + +RUN groupadd -g 10001 phase && useradd -u 10001 -g 10001 -d /tmp -s /usr/sbin/nologin phase +COPY --from=build /phase/target/server-release/ai-commander /opt/phase/ai-commander +COPY --from=build /phase/target/server-release/ai-duel /opt/phase/ai-duel +COPY --from=build /card-data.json /opt/phase/data/card-data.json +COPY --from=build /sample-feed.json /opt/phase/sample-feed.json +COPY phase_sim.py phase_smoke.py /opt/phase/ + +ENV PHASE_ENGINE_VERSION="phase-rs ${PHASE_TAG}" \ + PHASE_AI_COMMANDER=/opt/phase/ai-commander \ + PHASE_CARD_DATA=/opt/phase/data/card-data.json \ + PYTHONUNBUFFERED=1 PORT=8090 +USER 10001 +WORKDIR /tmp +EXPOSE 8090 +CMD ["python", "/opt/phase/phase_sim.py"] diff --git a/farmhouse/phase/Dockerfile.llm b/farmhouse/phase/Dockerfile.llm new file mode 100644 index 0000000..c5b44c4 --- /dev/null +++ b/farmhouse/phase/Dockerfile.llm @@ -0,0 +1,72 @@ +# phase-sim: rules-accurate four-player Commander games with phase-rs's headless AI (github.com/phase-rs/phase), behind a small HTTP service. +# +# phase is a Rust rules engine (stack, priority, combat, layers, triggers, replacement effects), dual licensed Apache-2.0 / MIT, with card +# data from MTGJSON (MIT). Pinned to release v0.118.0 (commit ad0de6a) and to the card database that release was published with +# (`card-data-5e541a38c99b97f0.json`, named in data.phase-rs.dev/card-data-meta.json for that commit); the file's SHA-256 is checked, so a +# changed file fails the build instead of silently changing results. Nothing is fetched at run time, and the pod has no network. +# +# Built: the `ai-commander` binary (4-player Commander, batch mode) and `ai-duel` with the repo's `server-release` profile (unwinding +# panics, so one game's panic cannot kill a batch). The toolchain is whatever rust-toolchain.toml pins (a dated nightly). +FROM rust:slim-bookworm AS build + +ARG PHASE_REPO=https://github.com/phase-rs/phase.git +ARG PHASE_TAG=v0.118.0 +ARG PHASE_SHA=ad0de6adf00153a6e6eb89604f6670be5b1d5168 +ARG CARD_DATA_URL=https://data.phase-rs.dev/card-data-5e541a38c99b97f0.json +ARG CARD_DATA_SHA256=5e541a38c99b97f0ef12c81f7b249e7cd253f38b32bd5c156cf19608cb6f1218 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl build-essential pkg-config python3 \ + && rm -rf /var/lib/apt/lists/* + +RUN set -eux; \ + mkdir /phase; cd /phase; \ + git init -q; \ + git remote add origin "$PHASE_REPO"; \ + git fetch -q --depth 1 origin "$PHASE_SHA"; \ + git checkout -q FETCH_HEAD; \ + test "$(git rev-parse HEAD)" = "$PHASE_SHA" + +WORKDIR /phase +# phase's server-release profile uses thin LTO and 16 code-generation units; compiling its big engine crate that way ran a 7 GB CI machine +# out of memory ("cannot allocate memory", 2026-10-27). LTO off and two parallel jobs trade some build time (and a few percent of run +# speed) for a build that fits; the optimisation level and panic=unwind (which batch isolation needs) are unchanged. +ENV CARGO_BUILD_JOBS=2 \ + CARGO_PROFILE_SERVER_RELEASE_LTO=off \ + CARGO_PROFILE_SERVER_RELEASE_CODEGEN_UNITS=8 +RUN cargo build --profile server-release -p phase-ai --bin ai-commander --bin ai-duel + +# ---- model seats (this Dockerfile only) ------------------------------------------------------------------------------------------- +# Everything above is identical to Dockerfile, so the long compile above comes from the build cache. These steps add `ai-commander-llm`: the +# same runner with a hook that lets a language model or a decision model (Laya / Kev) choose for named seats among the engine's OWN legal +# options. Two anchored edits to phase's source (apply_phase_patches.py: the build stops if phase moved either line) and one new crate. +# phase-llm depends on phase-ai, so the hook cannot live in phase-ai's binary; the new crate depends on both and includes the runner. +COPY llm-seat /llm-seat +RUN python3 /llm-seat/apply_phase_patches.py /phase /llm-seat +RUN cargo build --profile server-release -p farmhouse-llm-seat --bin ai-commander-llm + +RUN set -eux; \ + curl -fsSL --retry 3 -o /card-data.json "$CARD_DATA_URL"; \ + echo "$CARD_DATA_SHA256 /card-data.json" | sha256sum -c -; \ + cp /phase/client/public/feeds/mtggoldfish-commander.json /sample-feed.json + +FROM python:3.12-slim-bookworm +ARG PHASE_TAG=v0.118.0 + +RUN groupadd -g 10001 phase && useradd -u 10001 -g 10001 -d /tmp -s /usr/sbin/nologin phase +COPY --from=build /phase/target/server-release/ai-commander /opt/phase/ai-commander +COPY --from=build /phase/target/server-release/ai-duel /opt/phase/ai-duel +COPY --from=build /phase/target/server-release/ai-commander-llm /opt/phase/ai-commander-llm +COPY --from=build /card-data.json /opt/phase/data/card-data.json +COPY --from=build /sample-feed.json /opt/phase/sample-feed.json +COPY phase_sim.py phase_smoke.py /opt/phase/ + +ENV PHASE_ENGINE_VERSION="phase-rs ${PHASE_TAG}" \ + PHASE_AI_COMMANDER=/opt/phase/ai-commander \ + PHASE_AI_COMMANDER_LLM=/opt/phase/ai-commander-llm \ + PHASE_CARD_DATA=/opt/phase/data/card-data.json \ + PYTHONUNBUFFERED=1 PORT=8090 +USER 10001 +WORKDIR /tmp +EXPOSE 8090 +CMD ["python", "/opt/phase/phase_sim.py"] diff --git a/farmhouse/phase/README.md b/farmhouse/phase/README.md new file mode 100644 index 0000000..7d3e314 --- /dev/null +++ b/farmhouse/phase/README.md @@ -0,0 +1,36 @@ +# phase-sim: rules-accurate Commander games with phase-rs + +Reference copies of what runs in the cluster (source of truth: `infrastructure/apps/commander-lab/` in the farmhouse-os repo). Background and the assessment +that led here: `docs/PHASE-AND-PLAYTESTER.md`. + +| File | What | +|---|---| +| `phase_sim.py` | the service: stdlib HTTP, one job at a time. `POST /run` four decks -> `GET /job/` per-game results, wins by seat, 95% interval, warnings. Optional model seats and two loopback-only relays (`/llm/v1/chat/completions`, `/jev/systemone`) | +| `Dockerfile` | builds phase-rs `v0.118.0` (`ai-commander`, `ai-duel`) and takes the card database that release was published with (SHA-256 checked) | +| `Dockerfile.llm` | the same plus `ai-commander-llm`: model-driven seats | +| `llm-seat/` | the Rust crate and the two anchored edits to phase's source that make model seats possible | +| `phase_smoke.py`, `test_phase_sim.py` | CI: real games through the service; 49 offline checks against a stub engine | +| `deployment-phase.yaml` | Deployment, Service and a NetworkPolicy (in: the app only; out: DNS, Olla and Laya only) | + +The app side is `routes/farmhouse_phase.py` (four saved decks -> the service) and `ui/phase-sim.html`; both are real source in this repository, registered by +`lab_api.py` and linked from the home page. + +## Model seats: how they work and why they are safe +phase's headless runner has no model support; the model seats exist only in phase's browser client. `phase-llm` (the crate) deliberately does no networking: +it renders the engine's option list into a prompt, builds the HTTP request, and parses the reply, and the host performs the call. `llm-seat/` is that host +for the headless runner: + +1. `apply_phase_patches.py` adds a process-wide `ACTION_OVERRIDE` hook in `phase-ai/src/auto_play.rs` (asked before the built-in AI chooses) and makes the runner's `main` `pub`. +2. The crate `farmhouse-llm-seat` includes the runner's source as a module (`#[path]`) and installs the hook. `phase-llm` depends on `phase-ai`, so the hook cannot + live inside phase-ai's own binary. +3. For each decision on a model seat: the engine issues its option list (`AiDecisionContract`); phase-llm builds the prompt (a forced move with one option is never asked); + this crate makes the HTTP call (blocking, no TLS, 20 s limit); phase-llm turns the reply into one of the engine's options; the choice is checked against the contract + here and again by `run_ai_action`. **Any** problem returns "no opinion" and phase's own AI plays the move. A cap on model calls per run (default 300) bounds the cost. +4. The service supplies the endpoints through its own loopback-only relays: the chat relay switches the model's thinking off (twin-turbo otherwise thinks for tens of + seconds a move) and caps the answer; the decision relay unwraps phase's `Jev` envelope and forwards the System One request to Laya or Kev. + +The model never authors an action and never sees hidden cards beyond what phase-llm renders for that seat. + +## Status +Written 2026-10-27. The service logic is tested offline; the Rust crate has not compiled outside CI when this was written (no Rust toolchain on the workstation), so +its first CI run is the first real test. Check `.github/workflows/build-farmhouse-phase-sim.yml` results in the farmhouse-os repo. diff --git a/farmhouse/phase/deployment-phase.yaml b/farmhouse/phase/deployment-phase.yaml new file mode 100644 index 0000000..9ef8f89 --- /dev/null +++ b/farmhouse/phase/deployment-phase.yaml @@ -0,0 +1,111 @@ +# phase-sim (phase/Dockerfile): rules-accurate four-player Commander games over a small HTTP API. Only the app may call it; it has no +# network and no volume (engine and card data are in the image). One game at a time, CPU heavy. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: phase-sim + namespace: commander-lab + labels: {app: phase-sim} +spec: + replicas: 1 + selector: + matchLabels: {app: phase-sim} + template: + metadata: + labels: {app: phase-sim} + spec: + automountServiceAccountToken: false + # A Service named like the app injects PHASE_SIM_* variables into the pod; nothing here wants them (the same kind of collision + # crash-looped Laya on LAYA_PORT). + enableServiceLinks: false + imagePullSecrets: + - name: ghcr-pull + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + containers: + - name: phase-sim + image: ghcr.io/fez5587/farmhouse-phase-sim:v1-llm # -llm = the baseline plus ai-commander-llm (model seats) + ports: + - {name: http, containerPort: 8090} + env: + - {name: PORT, value: "8090"} + - {name: PHASE_SIM_MAX_GAMES, value: "50"} + - {name: PHASE_SIM_TIMEOUT, value: "3600"} + # Model seats. The engine talks to THIS service's loopback-only relays, which forward to these (see phase_sim.py): chat = an + # OpenAI-style endpoint (Olla -> twin-turbo; the relay switches thinking off and caps the answer), decision = a System One server + # (Laya / Kev; the deployment is scaled to 0 until it is fine-tuned, so a decision-seat run answers 502 and falls back to phase's AI). + - {name: PHASE_LLM_CHAT_URL, value: "http://olla.ai-system.svc.cluster.local:40114/olla/openai/v1"} + - {name: PHASE_LLM_DECISION_URL, value: "http://laya.commander-lab.svc.cluster.local:8080/v1/systemone"} + - {name: PHASE_LLM_REASONING, value: "none"} + - {name: PHASE_LLM_MAX_TOKENS_CAP, value: "256"} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + volumeMounts: + - {name: tmp, mountPath: /tmp} + resources: + requests: {cpu: "500m", memory: 1Gi} + limits: {cpu: "3", memory: 3Gi} + readinessProbe: + httpGet: {path: /health, port: http} + periodSeconds: 10 + livenessProbe: + httpGet: {path: /health, port: http} + periodSeconds: 30 + failureThreshold: 6 + volumes: + - name: tmp + emptyDir: {sizeLimit: 512Mi} +--- +apiVersion: v1 +kind: Service +metadata: + name: phase-sim + namespace: commander-lab +spec: + type: ClusterIP + selector: {app: phase-sim} + ports: + - {name: http, port: 8090, targetPort: http} +--- +# IN: only the app. OUT: DNS and the two model endpoints the relays use (Olla for the chat model, Laya for the decision model); nothing else. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: phase-sim + namespace: commander-lab +spec: + podSelector: + matchLabels: {app: phase-sim} + policyTypes: [Ingress, Egress] + ingress: + - from: + - podSelector: + matchLabels: {app: commander-lab} + ports: + - {protocol: TCP, port: 8090} + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: kube-system} + podSelector: + matchLabels: {k8s-app: kube-dns} + ports: + - {protocol: UDP, port: 53} + - {protocol: TCP, port: 53} + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: ai-system} + podSelector: + matchLabels: {app.kubernetes.io/name: olla} + ports: + - {protocol: TCP, port: 40114} + - to: + - podSelector: + matchLabels: {app: laya} + ports: + - {protocol: TCP, port: 8080} diff --git a/farmhouse/phase/llm-seat/Cargo.toml b/farmhouse/phase/llm-seat/Cargo.toml new file mode 100644 index 0000000..335a2ef --- /dev/null +++ b/farmhouse/phase/llm-seat/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "farmhouse-llm-seat" +version.workspace = true +edition = "2021" +license.workspace = true +publish = false + +# FarmHouse: phase's headless four-player Commander runner (`ai-commander`) with MODEL-DRIVEN SEATS. The runner's own source is included +# as a module (src/main.rs, #[path]); this crate adds only the network transport phase-llm deliberately leaves to the host. phase-llm +# depends on phase-ai, so the hook cannot live inside phase-ai's own binary: a new crate that depends on both is the way round that. + +[[bin]] +name = "ai-commander-llm" +path = "src/main.rs" + +[dependencies] +engine = { path = "../engine", package = "phase-engine" } +phase-ai = { path = "../phase-ai" } +phase-llm = { path = "../phase-llm" } +serde = { workspace = true } +serde_json = "1" +rand = "0.9" +tracing = "0.1" +mimalloc = "0.1" +# Blocking HTTP, no TLS: the model endpoints are cluster-internal http:// relays (phase-sim's own /llm and /jev routes). +ureq = { version = "2", default-features = false } diff --git a/farmhouse/phase/llm-seat/apply_phase_patches.py b/farmhouse/phase/llm-seat/apply_phase_patches.py new file mode 100644 index 0000000..274ef56 --- /dev/null +++ b/farmhouse/phase/llm-seat/apply_phase_patches.py @@ -0,0 +1,66 @@ +"""Apply the FarmHouse edits to a phase-rs checkout (run in the Docker build, from the repository root). + + python apply_phase_patches.py + +1. crates/phase-ai/src/auto_play.rs: a process-wide ACTION_OVERRIDE hook, asked before the built-in AI chooses. It returns Option; + None (the default, and what every failure returns) leaves phase's own choice untouched. The chosen action still goes through the same + contract check (`contract.permits`) as before. +2. crates/phase-ai/src/bin/ai_commander.rs: `fn main` becomes `pub fn main` so the new crate can include and call it. +3. The new crate is copied into crates/farmhouse-llm-seat (the workspace takes every crates/* member). + +Every anchor must match exactly once or the build stops, so a phase update that moves a line is reported here, not in a compile error.""" +import os +import shutil +import sys + +root, crate = sys.argv[1], sys.argv[2] + + +def edit(rel, edits): + path = os.path.join(root, rel) + text = open(path, encoding="utf-8", newline="").read() + for old, new in edits: + n = text.count(old) + if n != 1: + raise SystemExit("%s: anchor found %d times (need 1): %r" % (rel, n, old[:80])) + text = text.replace(old, new) + open(path, "w", encoding="utf-8", newline="").write(text) + print("patched", rel) + + +HOOK = '''use crate::search::choose_action_with_session; + +/// FarmHouse: an optional process-wide override, asked BEFORE the built-in AI chooses for a seat. A host (see crates/farmhouse-llm-seat) +/// installs one to let a model pick among the engine's own options. It returns None to leave the choice to the built-in AI, which is also +/// what it must return on any failure; whatever it returns still has to pass the same decision-contract check below. +pub type ActionOverride = Box< + dyn Fn( + &engine::types::game_state::GameState, + &engine::ai_support::AiDecisionContract, + engine::types::player::PlayerId, + engine::types::player::PlayerId, + ) -> Option + + Send + + Sync, +>; +static ACTION_OVERRIDE: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Install the override. Returns false if one is already installed (it can be set once per process). +pub fn install_action_override(hook: ActionOverride) -> bool { + ACTION_OVERRIDE.set(hook).is_ok() +} +''' + +edit("crates/phase-ai/src/auto_play.rs", [ + ("use crate::search::choose_action_with_session;\n", HOOK), + (" let action = match choose_action_with_session(state, semantic_owner, config, rng, session) {\n Some(action) => action,\n None => {\n tracing::warn!(player = ?actor, \"choose_action returned None", + " let farmhouse_choice = ACTION_OVERRIDE\n .get()\n .and_then(|hook| hook(&*state, &contract, semantic_owner, actor));\n" + " let action = match farmhouse_choice\n .or_else(|| choose_action_with_session(state, semantic_owner, config, rng, session))\n {\n Some(action) => action,\n None => {\n tracing::warn!(player = ?actor, \"choose_action returned None"), +]) +edit("crates/phase-ai/src/bin/ai_commander.rs", [("\nfn main() {\n", "\npub fn main() {\n")]) + +dest = os.path.join(root, "crates", "farmhouse-llm-seat") +os.makedirs(os.path.join(dest, "src"), exist_ok=True) +shutil.copy(os.path.join(crate, "Cargo.toml"), os.path.join(dest, "Cargo.toml")) +shutil.copy(os.path.join(crate, "src", "main.rs"), os.path.join(dest, "src", "main.rs")) +print("added crates/farmhouse-llm-seat") diff --git a/farmhouse/phase/llm-seat/src/main.rs b/farmhouse/phase/llm-seat/src/main.rs new file mode 100644 index 0000000..d879cb4 --- /dev/null +++ b/farmhouse/phase/llm-seat/src/main.rs @@ -0,0 +1,185 @@ +//! ai-commander with model-driven seats (FarmHouse). +//! +//! phase's headless runner plays four-player Commander games with the built-in AI on every seat. This binary is that same runner (its +//! source is included below, unchanged but for `fn main` being `pub`) plus a hook, installed before the games start, that asks a +//! language model or a decision model (Laya / Kev, over the System One protocol) to choose for the seats named in `PHASE_LLM_SEATS`. +//! +//! The model never authors an action. For each decision the engine issues its own option list (`AiDecisionContract`), phase-llm renders +//! it and builds the HTTP request, this file performs the HTTP call (the one thing phase-llm leaves to the host), and phase-llm turns the +//! reply into one of the engine's options. The pick is then checked against the contract a second time here, and again by +//! `run_ai_action`. ANY problem (forced move, timeout, an unreadable or stale answer, the call cap) returns `None` and phase's own AI +//! plays the move, so a model that is down, slow or wrong cannot stall or corrupt a game. +//! +//! Settings (environment): PHASE_LLM_SEATS "1,3" (seats 0-3; empty = none, the plain runner), PHASE_LLM_PROVIDER (OpenAiCompatible | Jev), +//! PHASE_LLM_BASE_URL, PHASE_LLM_MODEL, PHASE_LLM_API_KEY (leave empty for http:// endpoints), PHASE_LLM_MAX_TOKENS (256), +//! PHASE_LLM_TEMPERATURE (0.2), PHASE_LLM_TIMEOUT_S (20), PHASE_LLM_MAX_CALLS (total model calls for the whole process, default 300), +//! PHASE_LLM_DIFFICULTY (Medium: the strength hint in the prompt). + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; +use std::time::Duration; + +use engine::ai_support::AiDecisionContract; +use engine::database::CardDatabase; +use engine::types::actions::GameAction; +use engine::types::game_state::GameState; +use engine::types::player::PlayerId; +use phase_ai::auto_play::install_action_override; +use phase_ai::config::AiDifficulty; +use phase_llm::{LlmEndpointConfig, LlmProvider, LlmReply}; + +// The unchanged runner, with `fn main` made `pub` by apply_phase_patches.py. +#[path = "../../phase-ai/src/bin/ai_commander.rs"] +#[allow(dead_code, unused_imports, unused_variables)] +mod commander; + +struct Seats { + seats: HashSet, + endpoint: LlmEndpointConfig, + difficulty: AiDifficulty, + agent: ureq::Agent, + cards_path: PathBuf, + db: OnceLock>, + max_calls: u64, + asked: [AtomicU64; 4], + used: [AtomicU64; 4], + fell_back: [AtomicU64; 4], + total: AtomicU64, +} + +impl Seats { + fn database(&self) -> Option<&CardDatabase> { + self.db + .get_or_init(|| CardDatabase::from_export(&self.cards_path.join("card-data.json")).ok()) + .as_ref() + } + + /// The model's pick for `actor`, or None to let phase's AI play. Never panics on a bad answer. + fn decide(&self, state: &GameState, contract: &AiDecisionContract, actor: PlayerId) -> Option { + let seat = (actor.0 as usize).min(3); + // A forced move (one legal option) is never put to a model: build_game_decision_prompt refuses it. + let request = phase_llm::build_game_decision_prompt( + state, + contract, + self.difficulty, + self.database(), + &Vec::new(), + ) + .ok()?; + if self.total.fetch_add(1, Ordering::Relaxed) >= self.max_calls { + return None; // the call cap: every later decision is phase's AI + } + self.asked[seat].fetch_add(1, Ordering::Relaxed); + let http = phase_llm::build_chat_request(&self.endpoint, &request.prompt).ok()?; + let mut call = self.agent.request(http.method, &http.url); + for header in &http.headers { + call = call.set(&header.name, &header.value); + } + let (status, body) = match call.send_string(&http.body) { + Ok(response) => { + let status = response.status(); + (status, response.into_string().ok()?) + } + // A 4xx/5xx still carries a body phase-llm knows how to classify. + Err(ureq::Error::Status(code, response)) => (code, response.into_string().unwrap_or_default()), + Err(_) => return None, + }; + let selection = phase_llm::select_action_from_response( + state, + contract, + &request.fingerprint, + LlmReply { provider: self.endpoint.provider, status, body: &body }, + ) + .ok()?; + if !contract.contains_action(state, &selection.action) { + return None; + } + self.used[seat].fetch_add(1, Ordering::Relaxed); + Some(selection.action) + } + + fn report(&self, seat: usize) { + let asked = self.asked[seat].load(Ordering::Relaxed); + if asked > 0 && asked % 25 == 0 { + println!( + "LLM-SEAT seat={seat} asked={asked} used={} total_calls={}", + self.used[seat].load(Ordering::Relaxed), + self.total.load(Ordering::Relaxed) + ); + } + } +} + +fn env_or(name: &str, default: &str) -> String { + std::env::var(name).ok().filter(|v| !v.trim().is_empty()).unwrap_or_else(|| default.to_string()) +} + +fn install_model_seats() { + let seats: HashSet = env_or("PHASE_LLM_SEATS", "") + .split(',') + .filter_map(|s| s.trim().parse::().ok()) + .filter(|s| *s < 4) + .collect(); + if seats.is_empty() { + println!("LLM seats: none (plain ai-commander)"); + return; + } + let provider = LlmProvider::from_label(&env_or("PHASE_LLM_PROVIDER", "OpenAiCompatible")); + let endpoint = LlmEndpointConfig { + provider, + base_url: std::env::var("PHASE_LLM_BASE_URL").ok().filter(|v| !v.trim().is_empty()), + api_key: env_or("PHASE_LLM_API_KEY", ""), + model: env_or("PHASE_LLM_MODEL", "model"), + max_output_tokens: env_or("PHASE_LLM_MAX_TOKENS", "256").parse().ok(), + temperature: env_or("PHASE_LLM_TEMPERATURE", "0.2").parse().ok(), + }; + let timeout = env_or("PHASE_LLM_TIMEOUT_S", "20").parse::().unwrap_or(20); + // The runner's first positional argument is the data folder (card-data.json lives there). + let cards_path = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| ".".to_string())); + let state = Seats { + seats: seats.clone(), + endpoint, + difficulty: AiDifficulty::from_label(&env_or("PHASE_LLM_DIFFICULTY", "Medium")), + agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(timeout)).redirects(0).build(), + cards_path, + db: OnceLock::new(), + max_calls: env_or("PHASE_LLM_MAX_CALLS", "300").parse().unwrap_or(300), + asked: Default::default(), + used: Default::default(), + fell_back: Default::default(), + total: AtomicU64::new(0), + }; + println!( + "LLM seats: {:?} provider={} model={} max_calls={}", + { + let mut v: Vec = seats.iter().copied().collect(); + v.sort(); + v + }, + provider.label(), + state.endpoint.model, + state.max_calls + ); + let installed = install_action_override(Box::new(move |game, contract, _owner, actor| { + if !state.seats.contains(&actor.0) { + return None; + } + let seat = (actor.0 as usize).min(3); + let pick = state.decide(game, contract, actor); + if pick.is_none() { + state.fell_back[seat].fetch_add(1, Ordering::Relaxed); + } + state.report(seat); + pick + })); + if !installed { + eprintln!("LLM seats: an action override was already installed; model seats are off"); + } +} + +fn main() { + install_model_seats(); + commander::main(); +} diff --git a/farmhouse/phase/phase_sim.py b/farmhouse/phase/phase_sim.py new file mode 100644 index 0000000..33ffef7 --- /dev/null +++ b/farmhouse/phase/phase_sim.py @@ -0,0 +1,480 @@ +"""phase-sim: run rules-accurate four-player Commander games with phase-rs's headless `ai-commander` and report what happened. + +Standard library only. One job runs at a time (a game is CPU-heavy); more wait in a queue. The service never touches the network. + + GET /health {"ok": true, "engine": ..., "queued": n, "running": id|null} + POST /run {"decks": [4 x {"name", "commander": ["Card"], "main": [{"name","count"}, ...]}], + "games": 1..MAX_GAMES, "seed": int, "difficulty": "Medium", "seat_difficulty": {"2": "Hard"}, "action_cap": int} + -> {"job": id} + GET /job/ status queued|running|done|error, games finished, and when done: per-game rows, wins by seat and by deck, + win rate with a 95% interval, the cards the engine could not resolve, and the tail of the engine's output + +Seat i is the i-th deck in the request (P0 = first). The engine treats every seat as AI; difficulty is per seat if given. +A game that stalls, hits the action cap, or panics is reported as such and is NEVER counted as a win or a draw. + +Model seats (optional, needs the image's ai-commander-llm binary): "llm_seats": [1, 3] and "llm": {"kind": "chat" | "decision", "model": "...", +"max_calls": 300}. Those seats ask a model to pick among the ENGINE'S OWN legal options (phase-llm builds the prompt and checks the answer; +anything wrong or slow falls back to phase's AI). kind "chat" goes to PHASE_LLM_CHAT_URL (an OpenAI-style endpoint, e.g. Olla) through this +service's /llm relay, which switches the model's thinking off and caps its answer; kind "decision" goes to PHASE_LLM_DECISION_URL (a System One +server: Laya or Kev) through /jev/systemone. Both relays accept connections from this machine only. +""" +import json +import math +import os +import re +import subprocess +import sys +import tempfile +import threading +import time +import urllib.error +import urllib.request +import uuid +from collections import deque +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +BIN = os.environ.get("PHASE_AI_COMMANDER", "/opt/phase/ai-commander") +CARD_DATA = os.environ.get("PHASE_CARD_DATA", "/opt/phase/data/card-data.json") +ENGINE = os.environ.get("PHASE_ENGINE_VERSION", "phase-rs (version unknown)") +MAX_GAMES = int(os.environ.get("PHASE_SIM_MAX_GAMES", "50")) +JOB_TIMEOUT = int(os.environ.get("PHASE_SIM_TIMEOUT", "3600")) +PORT = int(os.environ.get("PORT", "8090")) +DIFFICULTIES = ("VeryEasy", "Easy", "Medium", "Hard", "VeryHard") +BIN_LLM = os.environ.get("PHASE_AI_COMMANDER_LLM", "/opt/phase/ai-commander-llm") +CHAT_URL = os.environ.get("PHASE_LLM_CHAT_URL", "").rstrip("/") # e.g. http://olla...:40114/olla/openai/v1 +DECISION_URL = os.environ.get("PHASE_LLM_DECISION_URL", "") # e.g. http://laya...:8080/v1/systemone +DECISION_KEY = os.environ.get("PHASE_LLM_DECISION_KEY", "") +CHAT_REASONING = os.environ.get("PHASE_LLM_REASONING", "none") +CHAT_MAX_TOKENS = int(os.environ.get("PHASE_LLM_MAX_TOKENS_CAP", "256")) +MAX_LLM_CALLS = int(os.environ.get("PHASE_LLM_MAX_CALLS", "600")) +LOCAL_ONLY = ("127.0.0.1", "::1") +MAX_DECK_ENTRIES = 400 + +_jobs = {} +_queue = deque() +_cv = threading.Condition() +_running = {"id": None} + + +# ---------- request -> engine inputs ------------------------------------------------------------------------------------------ + +class BadRequest(ValueError): + pass + + +def validate(req): + decks = req.get("decks") + if not isinstance(decks, list) or len(decks) != 4: + raise BadRequest("decks must be a list of exactly 4 decks (one per seat)") + feed = [] + for i, d in enumerate(decks): + if not isinstance(d, dict) or not str(d.get("name") or "").strip(): + raise BadRequest("deck %d needs a name" % i) + cmd = d.get("commander") + if isinstance(cmd, str): + cmd = [cmd] + if not isinstance(cmd, list) or not cmd or not all(isinstance(c, str) and c.strip() for c in cmd): + raise BadRequest("deck %d needs commander: [\"Card Name\"]" % i) + main = d.get("main") + if main is None and isinstance(d.get("cards"), list): + counts = {} + for n in d["cards"]: + counts[str(n)] = counts.get(str(n), 0) + 1 + main = [{"name": k, "count": v} for k, v in counts.items()] + if not isinstance(main, list) or not main or len(main) > MAX_DECK_ENTRIES: + raise BadRequest("deck %d needs a non-empty main list (at most %d entries)" % (i, MAX_DECK_ENTRIES)) + rows = [] + for e in main: + try: + name, count = str(e["name"]), int(e["count"]) + except (KeyError, TypeError, ValueError): + raise BadRequest("deck %d has a bad main entry: %r" % (i, e)) + if not name.strip() or not 1 <= count <= 99: + raise BadRequest("deck %d has a bad main entry: %r" % (i, e)) + rows.append({"name": name, "count": count}) + feed.append({"name": str(d["name"]), "commander": [c.strip() for c in cmd], "main": rows}) + try: + games = int(req.get("games", 1)) + seed = int(req.get("seed", 1)) + except (TypeError, ValueError): + raise BadRequest("games and seed must be integers") + if not 1 <= games <= MAX_GAMES: + raise BadRequest("games must be 1 to %d" % MAX_GAMES) + difficulty = req.get("difficulty", "Medium") + if difficulty not in DIFFICULTIES: + raise BadRequest("difficulty must be one of %s" % ", ".join(DIFFICULTIES)) + seat_diff = {} + for k, v in (req.get("seat_difficulty") or {}).items(): + if str(k) not in ("0", "1", "2", "3") or v not in DIFFICULTIES: + raise BadRequest("seat_difficulty keys are seats 0-3, values one of %s" % ", ".join(DIFFICULTIES)) + seat_diff[int(k)] = v + cap = req.get("action_cap") + if cap is not None: + try: + cap = int(cap) + except (TypeError, ValueError): + raise BadRequest("action_cap must be an integer") + if not 100 <= cap <= 200000: + raise BadRequest("action_cap must be 100 to 200000") + llm = None + seats = req.get("llm_seats") or [] + if seats: + if not isinstance(seats, list) or not all(isinstance(x, int) and 0 <= x <= 3 for x in seats): + raise BadRequest("llm_seats must be a list of seats 0-3") + cfg = req.get("llm") or {} + kind = cfg.get("kind", "chat") + if kind not in ("chat", "decision"): + raise BadRequest("llm.kind must be chat or decision") + if (kind == "chat" and not CHAT_URL) or (kind == "decision" and not DECISION_URL): + raise BadRequest("this service has no %s model endpoint configured" % kind) + if not os.path.isfile(BIN_LLM) and not os.environ.get("PHASE_SIM_ALLOW_MISSING_LLM_BIN"): + raise BadRequest("this image has no model-seat engine (ai-commander-llm)") + model = str(cfg.get("model") or "").strip() + if kind == "chat" and not model: + raise BadRequest("llm.model is required for a chat model") + try: + max_calls = int(cfg.get("max_calls", 300)) + except (TypeError, ValueError): + raise BadRequest("llm.max_calls must be an integer") + if not 1 <= max_calls <= MAX_LLM_CALLS: + raise BadRequest("llm.max_calls must be 1 to %d" % MAX_LLM_CALLS) + llm = {"seats": sorted(set(seats)), "kind": kind, "model": model or "decision-model", "max_calls": max_calls} + return {"feed": feed, "games": games, "seed": seed, "difficulty": difficulty, "seat_difficulty": seat_diff, "action_cap": cap, "llm": llm} + + +def engine_env(spec): + """The environment for the engine process: model-seat settings, or None (inherit) for the plain runner.""" + llm = spec.get("llm") + if not llm: + return None + env = dict(os.environ) + local = "http://127.0.0.1:%d" % PORT + env.update(PHASE_LLM_SEATS=",".join(str(x) for x in llm["seats"]), PHASE_LLM_MODEL=llm["model"], PHASE_LLM_API_KEY="", + PHASE_LLM_MAX_CALLS=str(llm["max_calls"]), PHASE_LLM_DIFFICULTY=spec["difficulty"]) + if llm["kind"] == "chat": + env.update(PHASE_LLM_PROVIDER="OpenAiCompatible", PHASE_LLM_BASE_URL=local + "/llm/v1") + else: + env.update(PHASE_LLM_PROVIDER="Jev", PHASE_LLM_BASE_URL=local) + return env + + +def command(spec, root): + cmd = [BIN_LLM if spec.get("llm") else BIN, root, "--feed", "feed.json", "--games-file", os.path.join(root, "games.txt")] + for seat, level in sorted(spec["seat_difficulty"].items()): + cmd += ["--difficulty-p%d" % seat, level] + if spec["action_cap"]: + cmd += ["--action-cap", str(spec["action_cap"])] + return cmd + + +# ---------- engine output -> results ------------------------------------------------------------------------------------------ + +GAME_HEAD = re.compile(r"^--- GAME\b(.*)$") +WINNER = re.compile(r"Game ended cleanly\. Winner: (draw|P(\d))") +TURNS = re.compile(r"^Turns played: (\d+)") +ELIM = re.compile(r"^ELIMINATED: P(\d)\s+turn=(\d+)") +RESOLVED = re.compile(r"^\s+P(\d)\s+main=\s*(\d+)\s+commander=(\d+)") +LLM_STAT = re.compile(r"^LLM-SEAT seat=(\d) asked=(\d+) used=(\d+)") +SKIP = re.compile(r"^\s+SKIP (.+?): commander '(.+)' not in card db") +PRE = re.compile(r"^\s+(.+?)\s+\|\s+commander: (.+?)\s+\|\s+main: (\d+) cards") + + +def parse(output): + """Per-game rows and the deck-resolution facts from the engine's stdout. Games that did not finish are kept, labelled, never counted.""" + lines = output.splitlines() + pre, resolved, skipped, games, cur = [], {}, [], [], None + + def finish(): + if cur is not None: + games.append(cur) + + def new_game(label=""): + return {"label": label, "status": "unfinished", "winner_seat": None, "turns": None, "eliminated": []} + + result_line = re.compile(r"Game ended cleanly|^Turns played|^ELIMINATED:|^STALL:|ABORT: hit action cap|PANICKED") + for ln in lines: + if cur is None and not games: # the preamble: decks listed, then their resolved sizes + m = PRE.match(ln) + if m: + pre.append({"deck": m.group(1), "commander": m.group(2), "listed": int(m.group(3))}) + continue + m = SKIP.match(ln) + if m: + skipped.append({"deck": m.group(1), "commander": m.group(2)}) + continue + m = RESOLVED.match(ln) + if m and int(m.group(1)) not in resolved: + resolved[int(m.group(1))] = {"main": int(m.group(2)), "commanders": int(m.group(3))} + continue + if GAME_HEAD.match(ln): + finish() + cur = new_game(GAME_HEAD.match(ln).group(1).strip(" -")) + continue + if cur is None: + if not result_line.search(ln): + continue # banner and preamble lines are not a game + cur = new_game() # a single-game run prints no "--- GAME" header + m = WINNER.search(ln) + if m: + cur["status"] = "draw" if m.group(1) == "draw" else "won" + cur["winner_seat"] = None if m.group(2) is None else int(m.group(2)) + continue + m = TURNS.match(ln) + if m: + cur["turns"] = int(m.group(1)) + continue + m = ELIM.match(ln) + if m: + cur["eliminated"].append({"seat": int(m.group(1)), "turn": int(m.group(2))}) + continue + if ln.startswith("STALL:"): + cur["status"] = "stalled" + cur.setdefault("detail", ln) + elif "ABORT: hit action cap" in ln: + cur["status"] = "action_cap" + elif re.search(r"GAME .* PANICKED", ln): + cur["status"] = "panicked" + cur["detail"] = ln[:300] + finish() + games = [g for g in games if g["status"] != "unfinished" or g["turns"] is not None or g["eliminated"] or g["label"]] + return {"pre": pre, "resolved": resolved, "skipped": skipped, "games": games} + + +def llm_summary(llm, lines): + """The model seats' own counters (the engine prints one every 25th question), last value per seat.""" + per_seat = {} + for ln in lines: + m = LLM_STAT.match(ln) + if m: + per_seat[int(m.group(1))] = {"asked": int(m.group(2)), "used": int(m.group(3))} + return {"seats": llm["seats"], "kind": llm["kind"], "model": llm["model"], "max_calls": llm["max_calls"], "per_seat": per_seat, + "note": "counters are printed every 25th question, so the last few may be missing"} + + +def wilson(wins, n, z=1.96): + if n == 0: + return [0.0, 0.0] + p = wins / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return [round(max(0.0, (c - h) / d), 4), round(min(1.0, (c + h) / d), 4)] + + +def summarize(spec, parsed, seeds): + decks = [d["name"] for d in spec["feed"]] + finished = [g for g in parsed["games"] if g["status"] in ("won", "draw")] + won = [g for g in finished if g["status"] == "won"] + by_seat = [sum(1 for g in won if g["winner_seat"] == i) for i in range(4)] + n = len(finished) + warnings = [] + for s in parsed["skipped"]: + warnings.append("deck %r was skipped: commander %r is not in the engine's card database" % (s["deck"], s["commander"])) + for i, pre in enumerate(parsed["pre"][:4]): + got = (parsed["resolved"].get(i) or {}).get("main") + if got is not None and got < pre["listed"]: + warnings.append("seat %d (%s): %d of %d cards were not recognised by the engine and were left out" % ( + i, pre["deck"], pre["listed"] - got, pre["listed"])) + bad = [g for g in parsed["games"] if g["status"] not in ("won", "draw")] + if bad: + warnings.append("%d game(s) did not finish (%s): not counted as wins or draws" % ( + len(bad), ", ".join(sorted({g["status"] for g in bad})))) + for i, g in enumerate(parsed["games"]): + if i < len(seeds): + g["seed"] = seeds[i] + return {"games_requested": spec["games"], "games_finished": n, "games_not_finished": len(bad), "draws": n - len(won), + "wins_by_seat": by_seat, + "decks": [{"seat": i, "name": decks[i], "wins": by_seat[i], "win_rate": round(by_seat[i] / n, 4) if n else None, + "win_rate_95": wilson(by_seat[i], n)} for i in range(4)], + "avg_turns": round(sum(g["turns"] or 0 for g in finished) / n, 1) if n else None, + "warnings": warnings, "games": parsed["games"]} + + +# ---------- jobs ---------------------------------------------------------------------------------------------------------------- + +def run_job(job): + spec = job["spec"] + root = tempfile.mkdtemp(prefix="phase-sim-") + out_lines = [] + try: + os.symlink(CARD_DATA, os.path.join(root, "card-data.json")) + with open(os.path.join(root, "feed.json"), "w", encoding="utf-8") as f: + json.dump({"decks": spec["feed"]}, f) + seeds = [spec["seed"] + i for i in range(spec["games"])] + with open(os.path.join(root, "games.txt"), "w", encoding="utf-8") as f: + f.write("".join("%d,%s\n" % (s, spec["difficulty"]) for s in seeds)) + job["status"], job["started"] = "running", time.time() + proc = subprocess.Popen(command(spec, root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", cwd=root, + env=engine_env(spec)) + timer = threading.Timer(JOB_TIMEOUT, proc.kill) + timer.start() + try: + for ln in proc.stdout: + out_lines.append(ln.rstrip("\n")) + if GAME_HEAD.match(ln): + job["games_started"] += 1 + if WINNER.search(ln) or "GAME" in ln and "PANICKED" in ln or ln.startswith("STALL:") or "ABORT: hit action cap" in ln: + job["games_done"] += 1 + code = proc.wait() + finally: + timer.cancel() + text = "\n".join(out_lines) + parsed = parse(text) + job["result"] = summarize(spec, parsed, seeds) + if spec.get("llm"): + job["result"]["llm"] = llm_summary(spec["llm"], out_lines) + job["result"]["warnings"].append( + "model seats %s: the model is asked about each non-forced decision, up to %d calls for the whole run; an answer the engine " + "cannot use, a timeout, or any decision after the cap is played by phase's own AI instead" % (spec["llm"]["seats"], spec["llm"]["max_calls"])) + job["engine_exit_code"] = code + job["output_tail"] = out_lines[-40:] + job["status"] = "done" if parsed["games"] else "error" + if not parsed["games"]: + job["error"] = "the engine produced no game results (exit code %s); see output_tail" % code + except Exception as exc: # the job fails, the service does not + job["status"], job["error"] = "error", "%s: %s" % (type(exc).__name__, exc) + job["output_tail"] = out_lines[-40:] + finally: + job["finished"] = time.time() + try: + for name in os.listdir(root): + os.unlink(os.path.join(root, name)) + os.rmdir(root) + except OSError: + pass + + +def worker(): + while True: + with _cv: + while not _queue: + _cv.wait() + job = _queue.popleft() + _running["id"] = job["id"] + run_job(job) + with _cv: + _running["id"] = None + + +def submit(req): + spec = validate(req) + job = {"id": uuid.uuid4().hex[:12], "status": "queued", "created": time.time(), "spec": spec, "games_started": 0, "games_done": 0} + with _cv: + _jobs[job["id"]] = job + _queue.append(job) + for old in sorted(_jobs.values(), key=lambda j: j["created"])[:-50]: # remember the last 50 + if old["status"] in ("done", "error"): + _jobs.pop(old["id"], None) + _cv.notify() + return job["id"] + + +def public(job): + out = {k: job[k] for k in ("id", "status", "games_started", "games_done") if k in job} + out["games_requested"] = job["spec"]["games"] + for k in ("result", "error", "output_tail", "engine_exit_code"): + if k in job: + out[k] = job[k] + if "started" in job: + out["seconds"] = round((job.get("finished") or time.time()) - job["started"], 1) + return out + + +def forward(url, data, headers): + req = urllib.request.Request(url, data=data, headers=dict({"content-type": "application/json"}, **headers)) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read() or b"{}") + except urllib.error.HTTPError as exc: + try: + return exc.code, json.loads(exc.read() or b"{}") + except ValueError: + return exc.code, {"error": "upstream error"} + except (urllib.error.URLError, OSError, ValueError): + return 502, {"error": "the model endpoint is not reachable"} + + +def relay_chat(body, remote): + """POST /llm/v1/chat/completions -> the OpenAI-style endpoint, with the model's thinking off and its answer capped.""" + if remote not in LOCAL_ONLY or not CHAT_URL: + return 403, {"error": "not available"} + try: + req = json.loads(body) + req["max_tokens"] = min(int(req.get("max_tokens") or CHAT_MAX_TOKENS), CHAT_MAX_TOKENS) + req["stream"] = False + if CHAT_REASONING: + req["reasoning_effort"] = CHAT_REASONING + data = json.dumps(req).encode() + except (ValueError, TypeError): + return 400, {"error": "bad chat request"} + return forward(CHAT_URL + "/chat/completions", data, {}) + + +def relay_decision(body, remote): + """POST /jev/systemone: phase's Jev envelope {"apiKey", "request": {...}} -> a System One server (Laya / Kev); the key comes from the environment.""" + if remote not in LOCAL_ONLY or not DECISION_URL: + return 403, {"error": "not available"} + try: + data = json.dumps(json.loads(body)["request"]).encode() + except (ValueError, KeyError, TypeError): + return 400, {"error": "bad decision request"} + return forward(DECISION_URL, data, {"authorization": "Bearer " + DECISION_KEY} if DECISION_KEY else {}) + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server_version = "phase-sim/1" + + def log_message(self, fmt, *args): + if os.environ.get("PHASE_SIM_LOG") == "1": + sys.stderr.write("%s\n" % (fmt % args)) + + def _send(self, code, obj): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + with _cv: + return self._send(200, {"ok": os.path.isfile(BIN) and os.path.isfile(CARD_DATA), "engine": ENGINE, + "queued": len(_queue), "running": _running["id"], "max_games": MAX_GAMES}) + m = re.match(r"^/job/([0-9a-f]+)$", self.path) + if m: + with _cv: + job = _jobs.get(m.group(1)) + return self._send(200, public(job)) if job else self._send(404, {"error": "no such job"}) + self._send(404, {"error": "not found"}) + + def do_POST(self): + if self.path in ("/llm/v1/chat/completions", "/jev/systemone"): + n = int(self.headers.get("Content-Length") or 0) + if n > 4_000_000: + return self._send(413, {"error": "request too large"}) + fn = relay_chat if self.path.startswith("/llm") else relay_decision + code, obj = fn(self.rfile.read(n), self.client_address[0]) + return self._send(code, obj) + if self.path != "/run": + return self._send(404, {"error": "not found"}) + try: + n = int(self.headers.get("Content-Length") or 0) + if n > 2_000_000: + return self._send(413, {"error": "request too large"}) + req = json.loads(self.rfile.read(n) or b"{}") + if not isinstance(req, dict): + raise BadRequest("the body must be a JSON object") + self._send(202, {"job": submit(req)}) + except (BadRequest, json.JSONDecodeError) as exc: + self._send(400, {"error": str(exc)}) + + +def main(): + threading.Thread(target=worker, daemon=True).start() + ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/farmhouse/phase/phase_smoke.py b/farmhouse/phase/phase_smoke.py new file mode 100644 index 0000000..ccbb21f --- /dev/null +++ b/farmhouse/phase/phase_smoke.py @@ -0,0 +1,108 @@ +"""Smoke test, run INSIDE the image (CI and by hand): four real decks from phase's own sample feed play real games through the service. + + python /opt/phase/phase_smoke.py [games] [difficulty] plain engine + python /opt/phase/phase_smoke.py --llm model seats against a stub model inside this process + +Exits non-zero unless at least one game finished with a winner or a draw. Prints what the engine reported, including any cards it did +not recognise, so a bad data/engine pairing shows up here and not in a result someone trusts. + +--llm starts a stub OpenAI-style model on 127.0.0.1:9099 (the service must have been started with PHASE_LLM_CHAT_URL=http://127.0.0.1:9099/v1), +puts seats 1 and 3 on it, and passes when the engine's own counters show the model was asked AND its answers were used by the engine: that +proves the Rust hook, the relay and phase's answer check end to end without any outside service. The stub always answers option 0, so the +game itself may not finish (it can hit the action cap); that is not what is being tested. +""" +import json +import sys +import threading +import time +import urllib.request +from http.server import BaseHTTPRequestHandler, HTTPServer + +BASE = "http://127.0.0.1:8090" +LLM = "--llm" in sys.argv +args = [a for a in sys.argv[1:] if not a.startswith("--")] +games = int(args[0]) if args else (1 if LLM else 2) +difficulty = args[1] if len(args) > 1 else "VeryEasy" + +ASKED = [] + + +class StubModel(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0))) + ASKED.append(body) + out = json.dumps({"choices": [{"index": 0, "message": {"role": "assistant", "content": "{\"choice\": 0, \"reason\": \"stub\"}"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + +if LLM: + threading.Thread(target=HTTPServer(("127.0.0.1", 9099), StubModel).serve_forever, daemon=True).start() + + +def call(path, body=None): + req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.load(r) + + +for _ in range(60): + try: + h = call("/health") + break + except Exception: + time.sleep(1) +else: + sys.exit("the service did not come up") +print("health:", h) +assert h["ok"], "binary or card data missing" + +feed = json.load(open("/opt/phase/sample-feed.json", encoding="utf-8"))["decks"] +decks = [] +for d in feed: + cmd = d.get("commander") or [d["name"]] + decks.append({"name": d["name"], "commander": cmd, "main": d["main"]}) + if len(decks) == 4: + break +request = {"decks": decks, "games": games, "seed": 7, "difficulty": difficulty, "action_cap": 60000} +if LLM: + request.update(action_cap=6000, llm_seats=[1, 3], llm={"kind": "chat", "model": "stub-model", "max_calls": 60}) +job = call("/run", request)["job"] +t0 = time.time() +while True: + j = call("/job/" + job) + if j["status"] in ("done", "error"): + break + if time.time() - t0 > 1500: + sys.exit("timed out; last: %s" % json.dumps(j)[:300]) + time.sleep(3) +print("job: %s in %.0f s" % (j["status"], time.time() - t0)) +res = j.get("result") or {} +print(json.dumps({k: res.get(k) for k in ("games_requested", "games_finished", "games_not_finished", "draws", "wins_by_seat", "avg_turns", "warnings")}, indent=1)) +for g in res.get("games", []): + print(" game seed=%s %s winner=%s turns=%s eliminated=%s" % (g.get("seed"), g["status"], g.get("winner_seat"), g.get("turns"), g.get("eliminated"))) +if LLM: + llm = res.get("llm") or {} + print("model seats:", json.dumps(llm), "| requests the stub model received:", len(ASKED)) + print("\n".join((j.get("output_tail") or [])[-15:])) + seats = llm.get("per_seat") or {} + asked = sum(v["asked"] for v in seats.values()) + used = sum(v["used"] for v in seats.values()) + reasoned = [a for a in ASKED if a.get("reasoning_effort") == "none"] + if not ASKED or not asked or not used: + sys.exit("the model seats were not exercised: stub got %d requests, engine counters asked=%d used=%d" % (len(ASKED), asked, used)) + if len(reasoned) != len(ASKED): + sys.exit("the relay did not switch the model's thinking off on every request") + print("PHASE LLM SMOKE OK (asked %d, engine used %d, stub saw %d requests, all with thinking off)" % (asked, used, len(ASKED))) + sys.exit(0) +if j["status"] != "done" or res.get("games_finished", 0) < 1: + print("\n".join(j.get("output_tail") or [])) + sys.exit("no game finished") +print("PHASE SMOKE OK") diff --git a/farmhouse/phase/test_phase_sim.py b/farmhouse/phase/test_phase_sim.py new file mode 100644 index 0000000..1c1f348 --- /dev/null +++ b/farmhouse/phase/test_phase_sim.py @@ -0,0 +1,264 @@ +"""Run: python -I -X utf8 test_phase_sim.py (offline: a stub engine prints output in the format phase's ai-commander prints)""" +import json +import os +import sys +import tempfile +import threading +import time +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import phase_sim as P # noqa: E402 + +FAILS = 0 + + +def ck(name, cond, detail=""): + global FAILS + print(" %s %s%s" % ("ok " if cond else "FAIL", name, (" -- " + str(detail)[:260]) if detail and not cond else "")) + if not cond: + FAILS += 1 + + +def deck(name, cmd, n=3): + return {"name": name, "commander": [cmd], "main": [{"name": "Sol Ring", "count": 1}, {"name": "Forest", "count": n}]} + + +GOOD = {"decks": [deck("A", "Cmd A"), deck("B", "Cmd B"), deck("C", "Cmd C"), deck("D", "Cmd D")], "games": 3, "seed": 10} + +# --- validation +def bad(mut, why): + req = json.loads(json.dumps(GOOD)) + mut(req) + try: + P.validate(req) + ck("rejects " + why, False) + except P.BadRequest as exc: + ck("rejects " + why, True, exc) + +ck("a good request validates", P.validate(GOOD)["games"] == 3) +bad(lambda r: r["decks"].pop(), "three decks") +bad(lambda r: r["decks"][0].pop("commander"), "a deck with no commander") +bad(lambda r: r["decks"][1].update(main=[]), "an empty main list") +bad(lambda r: r["decks"][2]["main"].append({"name": "X", "count": 0}), "a zero count") +bad(lambda r: r.update(games=P.MAX_GAMES + 1), "too many games") +bad(lambda r: r.update(difficulty="Impossible"), "an unknown difficulty") +bad(lambda r: r.update(seat_difficulty={"7": "Easy"}), "a seat outside 0-3") +bad(lambda r: r.update(action_cap=5), "a tiny action cap") +v = P.validate(dict(GOOD, decks=[dict(deck("A", "Cmd A"), commander="Cmd A", main=None, cards=["Forest", "Forest", "Sol Ring"])] + GOOD["decks"][1:])) +ck("a plain card list becomes counted rows and a commander string becomes a list", + v["feed"][0]["commander"] == ["Cmd A"] and {"name": "Forest", "count": 2} in v["feed"][0]["main"], v["feed"][0]) + +# --- parsing the engine's output +OUT = """=== 4-player Commander AI test === +Feed: feed.json +Batch mode: 5 games from games.txt + + A | commander: Cmd A | main: 99 cards + B | commander: Cmd B | main: 99 cards + SKIP C: commander 'Cmd C' not in card db + D | commander: Cmd D | main: 99 cards +Resolved deck sizes (post name-resolution, 0-indexed by seat): + P0 main= 99 commander=1 + P1 main= 97 commander=1 + P2 main= 99 commander=1 + P3 main= 99 commander=1 + +ExecutionMode: measurement +--- GAME seed=10 difficulty=Medium --- +Game started. 4 players. +ELIMINATED: P1 turn=9 actions= 400 elapsed=3.1s +ELIMINATED: P3 turn=12 actions= 600 elapsed=5.0s + +=== RESULT === +Elapsed: 8.0s +Turns played: 14 + +Game ended cleanly. Winner: P2 +--- GAME seed=11 difficulty=Medium --- +Game started. 4 players. +=== RESULT === +Turns played: 40 +Game ended cleanly. Winner: draw +--- GAME seed=12 difficulty=Medium --- +=== RESULT === +Turns played: 7 +STALL: waiting_for=ChooseTarget turn=7 active=P0 priority=P0 pending_cast=none +Game did NOT reach GameOver. waiting_for = ChooseTarget +--- GAME seed=13 difficulty=Medium --- +ABORT: hit action cap=50000 +=== RESULT === +Turns played: 31 +Game did NOT reach GameOver. waiting_for = Priority +--- GAME seed=14 difficulty=Medium --- +GAME 14 PANICKED: index out of bounds +""" +parsed = P.parse(OUT) +st = [g["status"] for g in parsed["games"]] +ck("five games found with their outcomes in order", st == ["won", "draw", "stalled", "action_cap", "panicked"], st) +g0 = parsed["games"][0] +ck("winner seat, turns and elimination order are read", g0["winner_seat"] == 2 and g0["turns"] == 14 + and [e["seat"] for e in g0["eliminated"]] == [1, 3], g0) +ck("a draw has no winner seat", parsed["games"][1]["winner_seat"] is None) +ck("pre-resolution and resolved deck sizes and the skipped deck are read", len(parsed["pre"]) == 3 and parsed["resolved"][1]["main"] == 97 + and parsed["skipped"] == [{"deck": "C", "commander": "Cmd C"}], (parsed["pre"], parsed["resolved"], parsed["skipped"])) + +spec = P.validate(dict(GOOD, games=5)) +res = P.summarize(spec, parsed, [10, 11, 12, 13, 14]) +ck("only finished games are counted", res["games_finished"] == 2 and res["games_not_finished"] == 3 and res["draws"] == 1, res) +ck("wins by seat and per-deck win rate", res["wins_by_seat"] == [0, 0, 1, 0] and res["decks"][2]["win_rate"] == 0.5 and res["decks"][0]["win_rate"] == 0.0) +lo, hi = res["decks"][2]["win_rate_95"] +ck("a 95% interval wraps the rate and stays in 0..1", 0 <= lo < 0.5 < hi <= 1) +w = " | ".join(res["warnings"]) +ck("warnings: a skipped deck, unrecognised cards, and unfinished games (never counted)", + "was skipped" in w and "2 of 99" in w and "not counted as wins or draws" in w and "stalled" in w, w) +ck("each game carries its seed", [g["seed"] for g in res["games"]] == [10, 11, 12, 13, 14]) +ck("interval of nothing is zeros, of a sweep is high", P.wilson(0, 0) == [0.0, 0.0] and P.wilson(10, 10)[0] > 0.7) + +# --- a whole job through the real worker path with a stub engine +STUB = os.path.join(tempfile.mkdtemp(), "stub_engine.py") +with open(STUB, "w", encoding="utf-8") as f: + f.write('''import sys, os +root = sys.argv[1] +seeds = [l.split(",")[0] for l in open(os.path.join(root, "games.txt")) if l.strip()] +feed = __import__("json").load(open(os.path.join(root, "feed.json"))) +assert os.path.exists(os.path.join(root, "card-data.json")) and len(feed["decks"]) == 4 +for d in feed["decks"]: + print(" %s | commander: %s | main: %d cards" % (d["name"], d["commander"][0], sum(e["count"] for e in d["main"]))) +print("Resolved deck sizes (post name-resolution, 0-indexed by seat):") +for i, d in enumerate(feed["decks"]): + print(" P%d main=%3d commander=1" % (i, sum(e["count"] for e in d["main"]))) +for k, s in enumerate(seeds): + print("--- GAME seed=%s ---" % s) + print("Turns played: %d" % (10 + k)) + print("Game ended cleanly. Winner: P%d" % (k % 4)) +''') +CD = os.path.join(os.path.dirname(STUB), "card-data.json") +open(CD, "w").write("{}") +P.CARD_DATA = CD +ORIG_COMMAND = P.command +P.command = lambda spec, root: [sys.executable, STUB, root] +job_id = P.submit(dict(GOOD, games=4)) +threading.Thread(target=P.worker, daemon=True).start() +for _ in range(100): + j = P._jobs[job_id] + if j["status"] in ("done", "error"): + break + time.sleep(0.1) +pub = P.public(P._jobs[job_id]) +ck("a queued job runs to done with four finished games, one win each", pub["status"] == "done" and pub["result"]["games_finished"] == 4 + and pub["result"]["wins_by_seat"] == [1, 1, 1, 1] and pub["games_done"] == 4, pub) +ck("no warnings when every card resolved", pub["result"]["warnings"] == [], pub["result"]["warnings"]) +ck("the temp folder is cleaned up", not [d for d in os.listdir(tempfile.gettempdir()) if d.startswith("phase-sim-")]) + +# --- the HTTP surface +srv = P.ThreadingHTTPServer(("127.0.0.1", 0), P.Handler) +threading.Thread(target=srv.serve_forever, daemon=True).start() +base = "http://127.0.0.1:%d" % srv.server_port +def call(path, body=None): + req = urllib.request.Request(base + path, data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"}) + try: + r = urllib.request.urlopen(req, timeout=10) + return r.status, json.load(r) + except urllib.error.HTTPError as e: + return e.code, json.load(e) +code, h = call("/health") +ck("/health answers (ok is false only because the real binary is not here)", code == 200 and "engine" in h and h["max_games"] == P.MAX_GAMES, h) +code, r = call("/run", dict(GOOD, games=1)) +ck("POST /run is accepted with a job id", code == 202 and len(r["job"]) == 12, r) +for _ in range(100): + code, j = call("/job/" + r["job"]) + if j["status"] in ("done", "error"): + break + time.sleep(0.1) +ck("GET /job/ returns the result", code == 200 and j["status"] == "done" and j["result"]["games_finished"] == 1, j) +ck("a bad request is a 400 with a reason", call("/run", {"decks": []})[0] == 400) +ck("an unknown job is a 404", call("/job/deadbeef")[0] == 404) +ck("an unknown path is a 404", call("/nope")[0] == 404) +# --- model seats: validation, environment, relays +from http.server import BaseHTTPRequestHandler, HTTPServer + +UP = [] + + +class Upstream(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0))) + UP.append((self.path, body, self.headers.get("authorization"))) + out = json.dumps({"echo": True, "path": self.path}).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + +up = HTTPServer(("127.0.0.1", 0), Upstream) +threading.Thread(target=up.serve_forever, daemon=True).start() +UPBASE = "http://127.0.0.1:%d" % up.server_port +os.environ["PHASE_SIM_ALLOW_MISSING_LLM_BIN"] = "1" +LLMREQ = dict(GOOD, llm_seats=[1, 3], llm={"kind": "chat", "model": "twin-turbo", "max_calls": 120}) + +P.CHAT_URL, P.DECISION_URL = "", "" +try: + P.validate(LLMREQ) + ck("model seats are refused when no model endpoint is configured", False) +except P.BadRequest as exc: + ck("model seats are refused when no model endpoint is configured", "no chat model endpoint" in str(exc), exc) +P.CHAT_URL, P.DECISION_URL, P.DECISION_KEY = UPBASE + "/v1", UPBASE + "/v1/systemone", "sekret" +v = P.validate(LLMREQ) +ck("a chat model seat request validates", v["llm"] == {"seats": [1, 3], "kind": "chat", "model": "twin-turbo", "max_calls": 120}, v["llm"]) +ck("a request with no model seats has no llm settings", P.validate(GOOD)["llm"] is None) +for mut, why in ((lambda r: r.update(llm_seats=[4]), "a seat outside 0-3"), + (lambda r: r["llm"].pop("model"), "a chat model with no name"), + (lambda r: r["llm"].update(max_calls=P.MAX_LLM_CALLS + 1), "too many model calls"), + (lambda r: r["llm"].update(kind="telepathy"), "an unknown kind")): + req = json.loads(json.dumps(LLMREQ)) + mut(req) + try: + P.validate(req) + ck("rejects " + why, False) + except P.BadRequest: + ck("rejects " + why, True) +dv = P.validate(dict(GOOD, llm_seats=[0], llm={"kind": "decision"})) +ck("a decision-model seat needs no model name", dv["llm"]["kind"] == "decision" and dv["llm"]["model"] == "decision-model") + +env = P.engine_env(v) +ck("chat seats: the engine is pointed at this service's /llm relay as an OpenAI-compatible endpoint with no key", + env["PHASE_LLM_SEATS"] == "1,3" and env["PHASE_LLM_PROVIDER"] == "OpenAiCompatible" and env["PHASE_LLM_BASE_URL"].endswith("/llm/v1") + and env["PHASE_LLM_MODEL"] == "twin-turbo" and env["PHASE_LLM_API_KEY"] == "" and env["PHASE_LLM_MAX_CALLS"] == "120", env) +denv = P.engine_env(dv) +ck("decision seats: provider Jev, base is this service (the engine adds /jev/systemone)", denv["PHASE_LLM_PROVIDER"] == "Jev" + and denv["PHASE_LLM_BASE_URL"] == "http://127.0.0.1:%d" % P.PORT) +ck("no model seats: no special environment, the plain engine", P.engine_env(P.validate(GOOD)) is None + and ORIG_COMMAND(P.validate(GOOD), "/r")[0] == P.BIN and ORIG_COMMAND(v, "/r")[0] == P.BIN_LLM) + +code, out = P.relay_chat(json.dumps({"model": "twin-turbo", "messages": [{"role": "user", "content": "x"}], "max_tokens": 4000, "stream": True}).encode(), "127.0.0.1") +path, body, auth = UP[-1] +ck("the chat relay forwards to /chat/completions with thinking off, the answer capped and streaming off", + code == 200 and path == "/v1/chat/completions" and body["reasoning_effort"] == "none" and body["max_tokens"] == P.CHAT_MAX_TOKENS + and body["stream"] is False and body["model"] == "twin-turbo", (code, path, body)) +ck("a request without max_tokens gets the cap", (P.relay_chat(b'{"model": "m", "messages": []}', "127.0.0.1"), UP[-1][1]["max_tokens"] == P.CHAT_MAX_TOKENS)[1]) +ck("the relays refuse anyone but this machine", P.relay_chat(b"{}", "10.1.2.3")[0] == 403 and P.relay_decision(b"{}", "10.1.2.3")[0] == 403) +ck("a malformed chat body is a 400, not an exception", P.relay_chat(b"not json", "127.0.0.1")[0] == 400) +envelope = {"apiKey": "ignored-by-us", "request": {"state": {"body": "t"}, "questions": {"pick": {"type": "choice"}}}} +code, out = P.relay_decision(json.dumps(envelope).encode(), "127.0.0.1") +path, body, auth = UP[-1] +ck("the decision relay unwraps phase's envelope and sends only the request, with OUR key", code == 200 and path == "/v1/systemone" + and body == envelope["request"] and auth == "Bearer sekret", (code, path, body, auth)) +ck("a decision body with no request is a 400", P.relay_decision(b'{"apiKey": "k"}', "127.0.0.1")[0] == 400) +P.CHAT_URL = "http://127.0.0.1:1/v1" +ck("an unreachable model endpoint is a 502", P.relay_chat(b'{"model": "m", "messages": []}', "127.0.0.1")[0] == 502) +P.CHAT_URL = UPBASE + "/v1" + +summ = P.llm_summary({"seats": [1], "kind": "chat", "model": "m", "max_calls": 9}, + ["LLM-SEAT seat=1 asked=25 used=20 total_calls=25", "noise", "LLM-SEAT seat=1 asked=50 used=41 total_calls=50"]) +ck("the model seats' counters are read from the engine's output (last value wins)", summ["per_seat"] == {1: {"asked": 50, "used": 41}}, summ) + +code, r = call("/llm/v1/chat/completions", {"model": "m", "messages": []}) +ck("over HTTP from this machine the chat relay answers", code == 200 and r["echo"] is True, (code, r)) +print("\nFAILURES: %d" % FAILS) +sys.exit(1 if FAILS else 0) diff --git a/lab_api.py b/lab_api.py index 987f14b..a643088 100644 --- a/lab_api.py +++ b/lab_api.py @@ -38,6 +38,7 @@ from routes.lab import router as lab_router from routes.scanner import router as scanner_router from routes.rag import router as rag_router from routes.deepseek import router as deepseek_router +from routes.farmhouse_phase import router as farmhouse_phase_router # FARMHOUSE_PHASE_IMPORT from routes.deckgen import router as deckgen_router from routes.coach import router as coach_router, init_coach_service from routes.ml import router as ml_router @@ -129,6 +130,7 @@ app.include_router(deckbuilder_router) app.include_router(precon_router) app.include_router(import_router) app.include_router(lab_router) +app.include_router(farmhouse_phase_router) app.include_router(scanner_router) app.include_router(rag_router) app.include_router(deepseek_router) diff --git a/routes/farmhouse_phase.py b/routes/farmhouse_phase.py new file mode 100644 index 0000000..339842a --- /dev/null +++ b/routes/farmhouse_phase.py @@ -0,0 +1,116 @@ +"""Rules-accurate simulation through phase-sim (copied into the app as routes/farmhouse_phase.py by the Dockerfile). + +The phase-rs engine (Rust, headless) plays four-player Commander with a real stack, priority, combat, layers and triggers; the +phase-sim service wraps it. This route turns four SAVED decks into the service's request, relays the job, and returns what the +engine reported. Nothing is simulated here, and a game that stalled, hit the action cap or panicked is reported, never counted as a win. + + GET /api/farmhouse/phase/status the service's health (is the engine there, how many jobs are waiting) + POST /api/farmhouse/phase/run {"deckIds": [4 saved deck ids], "games": 1..50, "seed": 1, "difficulty": "Medium", + "seatDifficulty": {"2": "Hard"}} -> {"job": id, "decks": [names]} + GET /api/farmhouse/phase/job/{job} status, progress and, when finished, wins by seat, win rate with a 95% interval, + warnings (cards the engine did not recognise) and each game's outcome + +Setting: PHASE_SIM_URL (e.g. http://phase-sim.commander-lab.svc.cluster.local:8090). Unset, every endpoint answers 503 and nothing else changes. +""" +import json +import os +import urllib.error +import urllib.request +from typing import Dict, List, Optional + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel + +from services.database import _get_db_conn + +router = APIRouter(tags=["farmhouse-phase"]) + + +class PhaseRun(BaseModel): + deckIds: List[int] + games: int = 1 + seed: int = 1 + difficulty: str = "Medium" + seatDifficulty: Optional[Dict[str, str]] = None + actionCap: Optional[int] = None + # Seats (0-3) a MODEL plays instead of phase's built-in AI, and which kind: {"kind": "chat"|"decision", "model": "twin-turbo", "max_calls": 300}. + # The model only ever picks among the engine's own legal options; the service falls back to phase's AI on any problem. + llmSeats: Optional[List[int]] = None + llm: Optional[Dict] = None + + +def _base(): + url = os.environ.get("PHASE_SIM_URL", "").rstrip("/") + if not url: + raise HTTPException(503, "the rules engine service is not configured (PHASE_SIM_URL)") + return url + + +def _call(path, body=None, timeout=20): + req = urllib.request.Request(_base() + path, data=None if body is None else json.dumps(body).encode(), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.load(r) + except urllib.error.HTTPError as exc: + try: + detail = json.load(exc).get("error", "") + except Exception: + detail = "" + raise HTTPException(exc.code if exc.code in (400, 404, 413) else 502, detail or "the rules engine service refused the request") + except (urllib.error.URLError, OSError, ValueError): + raise HTTPException(503, "the rules engine service is not reachable") + + +def deck_feed(deck_id): + """A saved deck as the phase-sim feed entry: {"name", "commander": [...], "main": [{"name", "count"}]}.""" + conn = _get_db_conn() + deck = conn.execute("SELECT id, name, commander_name FROM decks WHERE id = ?", (deck_id,)).fetchone() + if not deck: + raise HTTPException(404, "deck %s not found" % deck_id) + rows = conn.execute("SELECT card_name, quantity, is_commander FROM deck_cards WHERE deck_id = ?", (deck_id,)).fetchall() + commanders, main = [], {} + for r in rows: + name, qty = (r["card_name"] or "").strip(), int(r["quantity"] or 1) + if not name: + continue + if r["is_commander"]: + if name not in commanders: + commanders.append(name) + else: + main[name] = main.get(name, 0) + qty + if not commanders and (deck["commander_name"] or "").strip(): + commanders = [deck["commander_name"].strip()] + if not commanders: + raise HTTPException(400, "deck %r has no commander set" % deck["name"]) + main = {n: c for n, c in main.items() if n not in commanders} + if not main: + raise HTTPException(400, "deck %r has no cards" % deck["name"]) + return {"name": deck["name"], "commander": commanders, "main": [{"name": n, "count": c} for n, c in sorted(main.items())]} + + +@router.get("/api/farmhouse/phase/status") +def phase_status(): + return _call("/health", timeout=5) + + +@router.post("/api/farmhouse/phase/run") +def phase_run(req: PhaseRun): + if len(req.deckIds) != 4: + raise HTTPException(400, "pick exactly 4 decks (one per seat)") + feed = [deck_feed(i) for i in req.deckIds] + body = {"decks": feed, "games": req.games, "seed": req.seed, "difficulty": req.difficulty} + if req.seatDifficulty: + body["seat_difficulty"] = req.seatDifficulty + if req.actionCap: + body["action_cap"] = req.actionCap + if req.llmSeats: + body["llm_seats"] = req.llmSeats + body["llm"] = req.llm or {} + out = _call("/run", body) + return {"job": out["job"], "decks": [d["name"] for d in feed]} + + +@router.get("/api/farmhouse/phase/job/{job}") +def phase_job(job: str): + return _call("/job/" + "".join(c for c in job if c in "0123456789abcdef"), timeout=10) diff --git a/routes/lab.py b/routes/lab.py index 5acb674..1baaa3b 100644 --- a/routes/lab.py +++ b/routes/lab.py @@ -98,6 +98,7 @@ async def start_batch(req: StartRequest, background_tasks: BackgroundTasks): if req.threads < 1 or req.threads > 32: raise HTTPException(400, "threads must be 1-32") + req.threads = min(req.threads, int(os.environ.get("FORGE_MAX_THREADS", "1"))) # FARMHOUSE_FORGE_THREADS if not os.path.exists(CFG.forge_jar): raise HTTPException(500, f"Forge JAR not found: {CFG.forge_jar}") if not os.path.isdir(CFG.forge_dir): diff --git a/tests/farmhouse/test_farmhouse_phase_route.py b/tests/farmhouse/test_farmhouse_phase_route.py new file mode 100644 index 0000000..5f09fb8 --- /dev/null +++ b/tests/farmhouse/test_farmhouse_phase_route.py @@ -0,0 +1,78 @@ +"""Run INSIDE the image (needs the app's FastAPI): python /tmp/test_farmhouse_phase_route.py +Checks routes/farmhouse_phase.py against an in-memory database and a stubbed phase-sim service.""" +import json +import os +import sqlite3 +import sys + +import os as _os; sys.path[:0] = [_os.path.abspath(_os.path.join(_os.path.dirname(__file__), "..", "..")), _os.path.abspath(_os.path.join(_os.path.dirname(__file__), "..", "..", "src"))] +from fastapi import FastAPI # noqa: E402 +from fastapi.testclient import TestClient # noqa: E402 +import routes.farmhouse_phase as R # noqa: E402 + +FAILS = 0 + + +def ck(name, cond, detail=""): + global FAILS + print(" %s %s%s" % ("ok " if cond else "FAIL", name, (" -- " + str(detail)[:240]) if detail and not cond else "")) + if not cond: + FAILS += 1 + + +db = sqlite3.connect(":memory:", check_same_thread=False) +db.row_factory = sqlite3.Row +db.executescript(""" +CREATE TABLE decks (id INTEGER PRIMARY KEY, name TEXT, commander_name TEXT DEFAULT ''); +CREATE TABLE deck_cards (id INTEGER PRIMARY KEY, deck_id INTEGER, scryfall_id TEXT DEFAULT '', card_name TEXT, quantity INTEGER DEFAULT 1, is_commander INTEGER DEFAULT 0); +INSERT INTO decks VALUES (1, 'Atraxa', ''), (2, 'No commander', ''), (3, 'Empty', 'Solo'), (4, 'Named only', 'Ghave'); +INSERT INTO deck_cards (deck_id, card_name, quantity, is_commander) VALUES + (1, 'Atraxa, Praetors'' Voice', 1, 1), (1, 'Sol Ring', 1, 0), (1, 'Forest', 20, 0), (1, 'Forest', 3, 0), (1, 'Fire // Ice', 1, 0), (1, 'Atraxa, Praetors'' Voice', 1, 0), + (2, 'Sol Ring', 1, 0), + (4, 'Sol Ring', 1, 0); +""") +R._get_db_conn = lambda: db + +feed = R.deck_feed(1) +ck("the commander row is the commander, and is not also in the main list", feed["commander"] == ["Atraxa, Praetors' Voice"] + and all(e["name"] != "Atraxa, Praetors' Voice" for e in feed["main"]), feed) +ck("duplicate rows add up (20 + 3 Forests) and split cards keep their full name", {"name": "Forest", "count": 23} in feed["main"] + and {"name": "Fire // Ice", "count": 1} in feed["main"], feed["main"]) +ck("a deck with only a named commander uses it", R.deck_feed(4)["commander"] == ["Ghave"]) +for did, why in ((2, "no commander"), (3, "no cards"), (99, "missing")): + try: + R.deck_feed(did) + ck("refuses a deck with " + why, False) + except Exception as exc: + ck("refuses a deck with " + why, getattr(exc, "status_code", 0) in (400, 404), exc) + +app = FastAPI() +app.include_router(R.router) +client = TestClient(app) +os.environ.pop("PHASE_SIM_URL", None) +ck("not configured: 503, nothing else", client.get("/api/farmhouse/phase/status").status_code == 503 + and client.post("/api/farmhouse/phase/run", json={"deckIds": [1, 1, 1, 1]}).status_code == 503) + +os.environ["PHASE_SIM_URL"] = "http://phase-sim.invalid:8090" +calls = [] +def fake_call(path, body=None, timeout=20): + calls.append((path, body)) + return {"job": "abc123def456"} if path == "/run" else {"ok": True, "status": "done", "path": path} +R._call = fake_call +ck("fewer than four decks is a 400", client.post("/api/farmhouse/phase/run", json={"deckIds": [1, 4]}).status_code == 400) +r = client.post("/api/farmhouse/phase/run", json={"deckIds": [1, 4, 1, 4], "games": 6, "seed": 5, "difficulty": "Hard", "seatDifficulty": {"2": "VeryHard"}}) +body = calls[-1][1] +ck("the run is forwarded with four feed decks, the games, seed, difficulty and per-seat difficulty", + r.status_code == 200 and r.json() == {"job": "abc123def456", "decks": ["Atraxa", "Named only", "Atraxa", "Named only"]} + and calls[-1][0] == "/run" and len(body["decks"]) == 4 and body["games"] == 6 and body["seed"] == 5 and body["difficulty"] == "Hard" + and body["seat_difficulty"] == {"2": "VeryHard"}, (r.status_code, r.text, body)) +r = client.post("/api/farmhouse/phase/run", json={"deckIds": [1, 4, 1, 4], "llmSeats": [1, 3], "llm": {"kind": "chat", "model": "twin-turbo", "max_calls": 80}}) +body = calls[-1][1] +ck("model seats and the model settings are forwarded as the service names them", r.status_code == 200 and body["llm_seats"] == [1, 3] + and body["llm"] == {"kind": "chat", "model": "twin-turbo", "max_calls": 80}, (r.status_code, body)) +client.post("/api/farmhouse/phase/run", json={"deckIds": [1, 4, 1, 4]}) +ck("no model seats: nothing about models is sent", "llm_seats" not in calls[-1][1] and "llm" not in calls[-1][1]) +ck("a job id is passed through and cleaned of anything but hex", client.get("/api/farmhouse/phase/job/abc123").json()["path"] == "/job/abc123" + and client.get("/api/farmhouse/phase/job/abc123..%2f..%2fx").status_code in (200, 404, 422)) +print("\nFAILURES: %d" % FAILS) +sys.exit(1 if FAILS else 0) diff --git a/ui/ai-lab.js b/ui/ai-lab.js index 11b10c8..04e9cf1 100644 --- a/ui/ai-lab.js +++ b/ui/ai-lab.js @@ -177,7 +177,8 @@ const AiLab = (() => {
+ +
A ticked seat is played by the model instead of phase's built-in AI. The model only chooses among the engine's own legal options (it cannot invent a move), is asked at most 300 questions per run, and anything it gets wrong or is too slow for is played by the built-in AI. Model seats take much longer than built-in AI seats.
+ +
+ +
+ + + +