public-release phases 1-3: read-only public mode, gunicorn container, demo bootstrap, CI, README

- before_request guard: visitors browse + explore; writes need PHYSCOM_ADMIN_TOKEN login
- SameSite=Lax/HttpOnly cookies, persisted secret key, debug off unless FLASK_DEBUG=1
- non-root gunicorn container with healthcheck; physcom demo --if-empty on first start
- landing page Top Concepts, write controls hidden from visitors
- CI workflow, pyproject metadata, compose Ollama parity, README rewrite
- tests/test_web_access.py: access control + GET smoke test of every page

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-25 15:40:02 -05:00
parent 2e38a6cf73
commit 8171fc023e
23 changed files with 510 additions and 112 deletions

View File

@@ -1,15 +0,0 @@
{
"permissions": {
"allow": [
"Bash(git *)",
"Bash(pip install *)",
"Bash(python -m pytest *)",
"Bash(python -m physcom *)",
"Bash(python -m physcom_web *)",
"Bash(python -c *)",
"WebFetch(domain:127.0.0.1)",
"WebFetch(domain:localhost)",
"Bash(curl:*)"
]
}
}

View File

@@ -8,3 +8,5 @@ data/
.claude/ .claude/
.venv/ .venv/
*.md *.md
!README.md
.env

View File

@@ -1,6 +1,13 @@
# Copy to .env — FLASK_SECRET_KEY is auto-generated on first run if omitted. # Copy to .env — FLASK_SECRET_KEY is auto-generated (and saved next to the DB) if omitted.
FLASK_SECRET_KEY= FLASK_SECRET_KEY=
# Web visitors are read-only unless logged in at /login with this token.
# Leave blank for a fully read-only public site. `python -m physcom_web`
# (the localhost dev server) is open when this is blank.
PHYSCOM_ADMIN_TOKEN=
# Set to 1 when served over HTTPS so the session cookie is Secure-only.
PHYSCOM_SECURE_COOKIES=0
# LLM provider for the optional pass 4 review (leave blank to skip it) # LLM provider for the optional pass 4 review (leave blank to skip it)
# Supported: gemini, ollama # Supported: gemini, ollama
LLM_PROVIDER= LLM_PROVIDER=

19
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: tests
on:
push:
pull_request:
jobs:
pytest:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: pip install -e ".[dev,web]"
- run: python -m pytest tests/ -q

3
.gitignore vendored
View File

@@ -178,3 +178,6 @@ cython_debug/
data/ data/
.aider* .aider*
# Local Claude Code settings
.claude/settings.local.json

View File

@@ -12,10 +12,10 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates
- **Tests (all)**: `python -m pytest tests/ -q` (~130 tests, ~2 min). Run after every change. - **Tests (all)**: `python -m pytest tests/ -q` (~130 tests, ~2 min). Run after every change.
- **Single test file**: `python -m pytest tests/test_scorer.py -q` - **Single test file**: `python -m pytest tests/test_scorer.py -q`
- **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q` - **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q`
- **Web dev server**: `python -m physcom_web` - **Web dev server**: `python -m physcom_web` (localhost, open access, debug only with `FLASK_DEBUG=1`)
- **CLI**: `python -m physcom` (or `physcom` if installed) - **CLI**: `python -m physcom` (or `physcom` if installed)
- **Docker**: `docker compose up web` / `docker compose run cli physcom seed` - **Docker**: `docker compose up web` / `docker compose run cli physcom seed`
- **Seed data**: loaded automatically on first DB init (SQLite, `physcom.db` or `$PHYSCOM_DB`) - **Demo data**: `python -m physcom demo` seeds + runs passes 1-3 for every domain (~20s). The Docker image does this on first start (`--if-empty`). DB is `data/physcom.db` or `$PHYSCOM_DB`.
## Architecture ## Architecture
@@ -35,7 +35,7 @@ src/physcom/ # Core library (no web dependency)
seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains
src/physcom_web/ # Flask web UI src/physcom_web/ # Flask web UI
app.py # App factory, get_repo(), DB path resolution app.py # App factory, get_repo(), DB path, read-only public mode + /login
routes/pipeline.py # Background thread pipeline execution, HTMX status/cancel endpoints routes/pipeline.py # Background thread pipeline execution, HTMX status/cancel endpoints
routes/results.py # Results browse, detail view, human review submission routes/results.py # Results browse, detail view, human review submission
routes/entities.py # Entity CRUD routes/entities.py # Entity CRUD
@@ -58,6 +58,7 @@ tests/ # pytest, uses seeded_repo fixture from conftest.py
- **`save_combination`** loads existing status/block_reason on dedup (important for resume). - **`save_combination`** loads existing status/block_reason on dedup (important for resume).
- **`ensure_metric`** backfills unit if the row already exists with an empty unit. - **`ensure_metric`** backfills unit if the row already exists with an empty unit.
- **MetricBound** carries `unit` — flows through seed → ensure_metric → metrics table → get_combination_scores → template display. - **MetricBound** carries `unit` — flows through seed → ensure_metric → metrics table → get_combination_scores → template display.
- **Read-only public mode**: `create_app()` locks every non-GET (except `results.explore`) and the admin/pipeline/new pages behind a session login with `PHYSCOM_ADMIN_TOKEN`. Only the dev server (`run()` → `create_app(open_access=True)`) is open, and only while no token is set. Templates use `is_admin()`; `body.readonly` hides every `form[method=post]` via CSS — a new write form needs no template guard, but a new public POST must be added to `PUBLIC_POST_ENDPOINTS`.
- **HTMX polling**: `_run_status.html` partial polls every 2s while run is pending/running; stops polling when terminal. - **HTMX polling**: `_run_status.html` partial polls every 2s while run is pending/running; stops polling when terminal.
## Data flow (pipeline passes) ## Data flow (pipeline passes)

View File

@@ -2,14 +2,22 @@ FROM python:3.13-slim AS base
WORKDIR /app WORKDIR /app
COPY pyproject.toml . COPY pyproject.toml README.md ./
COPY src/ src/ COPY src/ src/
RUN pip install --no-cache-dir ".[web,gemini]" RUN pip install --no-cache-dir ".[web,gemini]" \
&& useradd --create-home --uid 1000 physcom \
&& mkdir -p /app/data && chown physcom:physcom /app/data
USER physcom
VOLUME /app/data VOLUME /app/data
ENV PHYSCOM_DB=/app/data/physcom.db ENV PHYSCOM_DB=/app/data/physcom.db
ENV HOST=0.0.0.0
EXPOSE 5000 EXPOSE 5000
CMD ["python", "-m", "physcom_web"] HEALTHCHECK --interval=30s --timeout=5s --start-period=60s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/', timeout=4)"
# First start on an empty volume builds the demo data (~20s: seed + passes
# 1-3 for every domain). One gunicorn worker: pipeline runs are background
# threads inside the web process.
CMD ["sh", "-c", "physcom demo --if-empty && exec gunicorn --workers 1 --threads 8 --timeout 120 --bind 0.0.0.0:5000 'physcom_web.app:create_app()'"]

View File

@@ -55,6 +55,25 @@ Skipped until something forces them:
--- ---
## Suggested order ## Progress (2026-09-25)
1.1 → 1.5 → 1.2 → 1.3 → 1.4 → 1.6 → 1.7 → 1.8 → 2.3 → 2.1 → 2.4 → 2.5 → 2.6 → 3.1 → 3.3 → 2.2 (screenshots need the final UI) → 3.4 → 3.2. | Item | Status |
|------|--------|
| 1.1 gunicorn, debug off | Done. Dev server debug only with `FLASK_DEBUG=1`. |
| 1.2 read-only public mode | Done. Deviation: an unset token means *nobody* can write under gunicorn, instead of "localhost can write", because behind a reverse proxy every request looks like localhost. The dev server stays open until a token is set. |
| 1.3 cookie hardening | Done. `Secure` is opt-in via `PHYSCOM_SECURE_COOKIES=1` so plain-HTTP local Docker can still log in. |
| 1.4 explore | Done. Verified it never writes; it costs about 45 ms per call (measured over 168 combos). Non-finite inputs are now rejected. No app-level rate limit: add one at the proxy if needed. |
| 1.5 secret key | Done differently: instead of refusing to start, an unset key is generated once and saved next to the DB. |
| 1.6 container | Done: non-root, healthcheck. Base image **not** digest-pinned (no Docker available here to resolve one). **Container build is untested**, since Docker isn't installed on this machine. |
| 1.7 untrack local config | Done. Checked the history: no secrets. The repo was already public. |
| 1.8 tests | Done: `tests/test_web_access.py`. |
| 2.1 LICENSE | **Open. Your decision** (and your employer's). |
| 2.2 README | Done, apart from **screenshots**, which need a browser. |
| 2.3 CI | Done: `.github/workflows/test.yml` (Gitea Actions reads it). Unverified until a runner picks it up. |
| 2.4 metadata | Done. `license` is left unset until 2.1. |
| 2.5 compose parity | Done: Ollama vars, admin token, Postgres placeholder removed. |
| 2.6 route smoke tests | Done (in 1.8's file). |
| 3.1 demo data | Done differently: `physcom demo --if-empty` builds it on first start (about 20 s) instead of committing a snapshot that goes stale whenever the physics changes. |
| 3.2 host | **Open. Your call**: the README "Deploying publicly" section covers any host. |
| 3.3 pass-4 reviews | **Open.** Ollama wasn't running here. Run pass 4 locally, then snapshot export → import. |
| 3.4 landing page | Done: "Top Concepts" table, and the Run Pipeline button is hidden from visitors. |

View File

@@ -1,72 +1,68 @@
# Applied Combinatorics # Physical Combinatorics
### Innovation via Attribute Mixing ### Innovation via Attribute Mixing
This is an experimental repo which uses lists of physical attributes and recombines them to form new objects. These objects are then reviewed for comprehensibility and viability. [![tests](https://git.asimonson.com/andrew/physicalCombinatorics/actions/workflows/test.yml/badge.svg)](https://git.asimonson.com/andrew/physicalCombinatorics/actions)
Example: An experiment that takes lists of real physical attributes, recombines them into every possible object, and then sorts vaguely reasonable concepts from nonsense.
Let's identify some methods of getting from here to there: Let's identify some ways of getting from here to there:
- Car - Car
- Airplane - Airplane
- Train - Train
- Bicycle - Bicycle
- Walking with your legs - Walking with your legs
- Wheelchair
- Scooter
- Spaceship - Spaceship
- Teleportation or beaming technology
To build object 'car' you must select a power source. Power sources include: To build a car you must choose what pushes it and what it runs on:
- Gas/Internal Combustion Engine - Gas engine, electric motor, human pedalling, a solar sail, cannonfire recoil...
- Lithium Ion Batteries - Gasoline, lithium ion batteries, hydrogen, coal, sunlight, gunpowder...
- Hydrogen Combustion Engine
- Human pedalling
- Modular Nuclear Reactor
- Coal/steam locomotion
- the Sun via Solar Sail
- Cannonfire Recoil
- Pushed by a friend
Putting together lists 1 and 2 we can create 81 mostly novel forms of transportation, such as trains powered by solar sails or walking powered by tiny cannon recoil. Obviously some of these concepts are not as viable as others. While being pushed by a friend might work for those in a wheelchair, it is too slow for those in a car. Speed is therefore a target metric. Let's list some target metrics: Multiply those lists together and you get thousands of mostly novel forms of transportation: trains driven by solar sails, walking powered by tiny cannon recoil. Obviously some are more viable than others. Being pushed by a friend might work for a wheelchair, but it's far too slow for a car. So each concept is measured against target metrics (power density, cost, speed, range, cargo), weighted by what matters in a given **domain** (urban commuting cares about cost and speed; interplanetary travel cares about range).
- Speed The shortlist may include concepts that sound bizarre but are technically plausible. Bicycles, motorcycles and e-bikes all had their turn. Why not hydrogen-bikes?
- Cost efficiency
- Availability
- Safety
- Range (by fuel)
- Range (by platform degredation or maintenance)
Using these metrics this experiment intends to sift vaguely reasonable concepts from nonsense. Its shortlist may include concepts that sound bizarre but may be technically plausible. Bicycles, motorcycles, and e-bikes all had their turn. Why not hydrogen-bikes? The seed data is 11 platforms × 15 actuators × 18 energy storages = **2,970 combinations**, scored across 5 domains.
## How it works
Every combination goes through five passes:
1. **Constraints.** Each entity declares only its own physical envelope: what it `requires`, `provides` and `excludes`, plus numeric floors and ceilings on shared quantities like mass and footprint. The resolver cross-checks those generically across every pair. A nuclear reactor is blocked from a bicycle because its mass floor collides with the bicycle's mass ceiling, not because anyone wrote "nuclear + bicycle = no". Most of the combinatorial explosion dies here. ([why](LOGIC%20DOCS/002-guardrails-via-intrinsic-properties.md))
2. **Physics estimation.** A deterministic engine sizes each surviving combination from its entities' declared properties. It optimizes the platform/actuator/storage mass split, solves for drag-limited speed, and derives power density, range, cost and cargo. Domains can also define their own metrics as formulas.
3. **Scoring.** Raw values are log-normalized against each domain's bounds and combined with a weighted geometric mean. The geometric mean is deliberately harsh: one near-zero metric sinks the whole concept, which filters out things that are technically possible but pointless.
4. **LLM review (optional).** Top combinations get a plausibility verdict and a LOW/MEDIUM/HIGH rating from Gemini or a local Ollama model.
5. **Human review.** Annotate or approve results in the web UI.
Design reasoning lives in [`LOGIC DOCS/`](LOGIC%20DOCS/).
## Setup ## Setup
### Docker (recommended) ### Docker (recommended)
```bash ```bash
cp .env.example .env # set PHYSCOM_ADMIN_TOKEN to be able to edit
docker compose up web docker compose up web
``` ```
Then open [http://localhost:5000](http://localhost:5000). Open [http://localhost:5000](http://localhost:5000). On first start with an empty volume, the container seeds the transport example and scores every domain (about 20 seconds). Visitors are read-only; log in at `/login` with `PHYSCOM_ADMIN_TOKEN` to edit entities, run the pipeline or use the admin page.
Seed the database with the transport example: CLI inside the container:
```bash ```bash
docker compose run cli seed transport docker compose run --rm cli results urban_commuting --top 10
``` ```
### Local development ### Local development
```bash ```bash
pip install -e ".[dev,web]" pip install -e ".[dev,web]"
python -m physcom init python -m physcom demo # seed + run passes 1-3 for every domain
python -m physcom seed transport python -m physcom_web # localhost-only dev server, no login needed
python -m physcom_web
``` ```
Then open [http://localhost:5000](http://localhost:5000). Then open [http://localhost:5000](http://localhost:5000). Set `FLASK_DEBUG=1` for the Werkzeug debugger (never on a reachable host).
Run tests: Run tests:
@@ -74,9 +70,9 @@ Run tests:
python -m pytest tests/ -q python -m pytest tests/ -q
``` ```
### LLM integration (optional) ### LLM review (optional)
Pass 2 (physics estimation) is always the deterministic estimator — no LLM. Pass 2 (physics estimation) is always the deterministic estimator, with no LLM involved.
An LLM is only used for the optional pass 4 plausibility review. An LLM is only used for the optional pass 4 plausibility review.
Gemini: Gemini:
@@ -98,15 +94,32 @@ export LLM_PROVIDER=ollama
physcom run urban_commuting --passes 1,2,3,4 physcom run urban_commuting --passes 1,2,3,4
``` ```
Copy `.env.example` to `.env` and fill in your key for persistent configuration. Copy `.env.example` to `.env` to keep these settings.
--- ## Deploying publicly
a few notes: the thin atmosphere and the sun are obvious dependencies to the solar sail power source. Dependencies would include things such as scale of force (nuclear reactor vs pedalling obviously has an important force differential) and geographic requirements (walking requires ground and gravity). The project should include on every entity a list of dependencies. The viability tester will need to pull in all of these dependencies to ensure they do not contradict. The container is built to sit behind a TLS-terminating reverse proxy (Caddy, nginx, or a platform like Fly.io or Railway):
Additionally, metrics are expected to be extremely close to full points or none at all. The speed of a person pushing a car is effectively zero in its domain whereas a rocket powered car would easily reach the limits of speed in the domain. The resulting multiplication between metrics to get the viability score will be heavily logarithmic. This is expected and is intended to be a filter to eliminate technically plausible but completely pointless in practice concepts. - It serves with gunicorn (one worker, eight threads), runs as a non-root user and has a healthcheck.
Metric weights are therefore dependent on domain, which will also need to be defined. - Anonymous visitors can browse every result and use the mass-allocation explorer, and nothing else. Every write needs a login with `PHYSCOM_ADMIN_TOKEN`. If the token is unset, nobody can write.
- Set `PHYSCOM_SECURE_COOKIES=1` once it's served over HTTPS.
- Mount a persistent volume at `/app/data`. SQLite plus a single writer is plenty for a read-mostly demo.
- To publish LLM reviews without exposing an API key: run pass 4 locally against Ollama, export from `/admin` (or `physcom snapshot export`), and import that snapshot on the server.
First pass viability is physics such as force output, possibly generalized by LLM, last passes can include LLM and human review of social factors. Minimal Caddy example:
Attributes themselves are real (quality proven) and are thusly not garbage in the 'garbage in garbage out' risk - that risk is measured in how much nonsense the dimensional explosion generates that makes it past heuristic filters. ```
physcom.example.com {
reverse_proxy localhost:5000
}
```
## Project layout
```
src/physcom/ core engine: models, SQLite repository, constraint resolver,
physics estimator, scorer, pipeline, LLM providers, CLI
src/physcom_web/ Flask + HTMX web UI
tests/ pytest suite
LOGIC DOCS/ design decisions and the reasoning behind them
```

View File

@@ -1,3 +1,12 @@
x-env: &env
PHYSCOM_DB: /app/data/physcom.db
LLM_PROVIDER: ${LLM_PROVIDER:-}
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
GEMINI_MODEL: ${GEMINI_MODEL:-gemini-2.0-flash}
OLLAMA_MODEL: ${OLLAMA_MODEL:-qwen2.5:7b}
# Ollama running on the host machine, not in this container.
OLLAMA_HOST: ${OLLAMA_HOST:-http://host.docker.internal:11434}
services: services:
web: web:
build: . build: .
@@ -6,37 +15,24 @@ services:
volumes: volumes:
- physcom-data:/app/data - physcom-data:/app/data
environment: environment:
- PHYSCOM_DB=/app/data/physcom.db <<: *env
- FLASK_SECRET_KEY=${FLASK_SECRET_KEY:-} FLASK_SECRET_KEY: ${FLASK_SECRET_KEY:-}
- LLM_PROVIDER=${LLM_PROVIDER:-} # Visitors are read-only; log in at /login with this token to edit or run.
- GEMINI_API_KEY=${GEMINI_API_KEY:-} PHYSCOM_ADMIN_TOKEN: ${PHYSCOM_ADMIN_TOKEN:-}
- GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash} PHYSCOM_SECURE_COOKIES: ${PHYSCOM_SECURE_COOKIES:-0}
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped restart: unless-stopped
expose:
- 5000
cli: cli:
build: . build: .
volumes: volumes:
- physcom-data:/app/data - physcom-data:/app/data
environment: environment: *env
- PHYSCOM_DB=/app/data/physcom.db extra_hosts:
- LLM_PROVIDER=${LLM_PROVIDER:-} - "host.docker.internal:host-gateway"
- GEMINI_API_KEY=${GEMINI_API_KEY:-} entrypoint: ["physcom"]
- GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash}
entrypoint: ["python", "-m", "physcom"]
profiles: [cli] profiles: [cli]
# Future: replace SQLite with a dedicated DB service
# db:
# image: postgres:16
# volumes:
# - pgdata:/var/lib/postgresql/data
# environment:
# - POSTGRES_DB=physcom
# - POSTGRES_USER=physcom
# - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
volumes: volumes:
physcom-data: physcom-data:
# pgdata:

View File

@@ -6,7 +6,14 @@ build-backend = "setuptools.build_meta"
name = "physcom" name = "physcom"
version = "0.1.0" version = "0.1.0"
description = "Physical Combinatorics — innovation via attribute mixing" description = "Physical Combinatorics — innovation via attribute mixing"
requires-python = ">=3.10" readme = "README.md"
requires-python = ">=3.11"
authors = [{ name = "Andrew Simonson", email = "asimonson1125@gmail.com" }]
classifiers = [
"Programming Language :: Python :: 3",
"Framework :: Flask",
"Topic :: Scientific/Engineering :: Physics",
]
dependencies = [ dependencies = [
"click>=8.1", "click>=8.1",
] ]
@@ -17,11 +24,15 @@ dev = [
] ]
web = [ web = [
"flask>=3.0", "flask>=3.0",
"gunicorn>=22.0",
] ]
gemini = [ gemini = [
"google-genai>=1.0", "google-genai>=1.0",
] ]
[project.urls]
Repository = "https://git.asimonson.com/andrew/physicalCombinatorics"
[project.scripts] [project.scripts]
physcom = "physcom.cli:main" physcom = "physcom.cli:main"
physcom-web = "physcom_web.app:run" physcom-web = "physcom_web.app:run"

View File

@@ -19,7 +19,7 @@ def _get_repo(db_path: str | None = None) -> Repository:
@click.group() @click.group()
@click.option("--db", default=None, help="Path to SQLite database") @click.option("--db", default=None, envvar="PHYSCOM_DB", help="Path to SQLite database (or $PHYSCOM_DB)")
@click.pass_context @click.pass_context
def main(ctx, db): def main(ctx, db):
"""Physical Combinatorics — innovation via attribute mixing.""" """Physical Combinatorics — innovation via attribute mixing."""
@@ -49,6 +49,31 @@ def seed(ctx, seed_name):
click.echo(f"Unknown seed: {seed_name}. Available: transport") click.echo(f"Unknown seed: {seed_name}. Available: transport")
@main.command()
@click.option("--if-empty", is_flag=True, help="Do nothing if the DB already has entities")
@click.pass_context
def demo(ctx, if_empty):
"""Seed the transport example and run passes 1-3 for every domain."""
repo = _get_repo(ctx.obj["db"])
if if_empty and repo.list_entities():
click.echo("DB already has data; skipping demo build.")
return
from physcom.engine.constraint_resolver import ConstraintResolver
from physcom.engine.scorer import Scorer
from physcom.engine.pipeline import Pipeline
from physcom.seed.transport_example import load_transport_seed
load_transport_seed(repo)
dims = ["platform", "actuator", "energy_storage"]
for domain in repo.list_domains():
result = Pipeline(repo, ConstraintResolver(), Scorer(domain)).run(
domain, dims, score_threshold=0.1, passes=[1, 2, 3],
)
click.echo(f" {domain.name}: {result.pass3_above_threshold} of "
f"{result.total_generated} combos above threshold")
@main.group() @main.group()
def entity(): def entity():
"""Manage entities.""" """Manage entities."""

View File

@@ -2,11 +2,12 @@
from __future__ import annotations from __future__ import annotations
import hmac
import os import os
import secrets import secrets
from pathlib import Path from pathlib import Path
from flask import Flask, g from flask import Flask, abort, g, redirect, render_template, request, session, url_for
from physcom.db.schema import init_db from physcom.db.schema import init_db
from physcom.db.repository import Repository from physcom.db.repository import Repository
@@ -15,12 +16,41 @@ from physcom.units import format_quantity
DEFAULT_DB = Path("data/physcom.db") DEFAULT_DB = Path("data/physcom.db")
# Everything a read-only visitor may not reach. Writes (any non-GET) are
# locked separately, except the purely exploratory results.explore.
ADMIN_GET_ENDPOINTS = {"pipeline.pipeline_form", "entities.entity_new", "domains.domain_new"}
PUBLIC_POST_ENDPOINTS = {"results.explore", "login"}
def db_path() -> Path:
return Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))
def _secret_key() -> str:
"""FLASK_SECRET_KEY, else a key persisted next to the DB so admin
sessions survive restarts."""
key = os.environ.get("FLASK_SECRET_KEY")
if key:
return key
path = db_path().parent / ".secret_key"
try:
return path.read_text().strip()
except FileNotFoundError:
key = secrets.token_hex(32)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(key)
return key
def is_admin() -> bool:
from flask import current_app
return current_app.config["OPEN_ACCESS"] or session.get("admin", False)
def get_repo() -> Repository: def get_repo() -> Repository:
"""Return a Repository scoped to the current request.""" """Return a Repository scoped to the current request."""
if "repo" not in g: if "repo" not in g:
db_path = Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB))) conn = init_db(db_path())
conn = init_db(db_path)
g.repo = Repository(conn) g.repo = Repository(conn)
return g.repo return g.repo
@@ -31,9 +61,56 @@ def close_db(exc: BaseException | None = None) -> None:
repo.conn.close() repo.conn.close()
def create_app() -> Flask: def create_app(open_access: bool = False) -> Flask:
"""open_access=True (the localhost dev server) skips the admin lock
unless PHYSCOM_ADMIN_TOKEN is set. Anything else -- gunicorn in Docker --
is read-only to visitors; writes need a login with PHYSCOM_ADMIN_TOKEN
(no token set = no one can write)."""
app = Flask(__name__) app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32) app.secret_key = _secret_key()
admin_token = os.environ.get("PHYSCOM_ADMIN_TOKEN", "")
app.config.update(
OPEN_ACCESS=open_access and not admin_token,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=os.environ.get("PHYSCOM_SECURE_COOKIES") == "1",
)
app.jinja_env.globals["is_admin"] = is_admin
@app.before_request
def require_admin():
if is_admin() or request.endpoint in (None, "static"):
return None
blueprint = request.endpoint.split(".")[0]
if request.method in ("GET", "HEAD"):
if blueprint == "admin" or request.endpoint in ADMIN_GET_ENDPOINTS:
return redirect(url_for("login", next=request.path))
return None
if request.endpoint not in PUBLIC_POST_ENDPOINTS:
abort(403)
return None
@app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == "POST":
given = request.form.get("token", "")
if admin_token and hmac.compare_digest(given, admin_token):
session.clear()
session["admin"] = True
session.permanent = True
target = request.args.get("next", "")
# Only same-site relative paths, never "//evil.com".
if not target.startswith("/") or target.startswith("//"):
target = url_for("index")
return redirect(target)
error = "Wrong token." if admin_token else "Admin login is disabled (PHYSCOM_ADMIN_TOKEN not set)."
return render_template("login.html", error=error), (401 if error else 200)
@app.route("/logout", methods=["POST"])
def logout():
session.clear()
return redirect(url_for("index"))
app.jinja_env.filters["qty"] = format_quantity app.jinja_env.filters["qty"] = format_quantity
@@ -54,7 +131,6 @@ def create_app() -> Flask:
@app.route("/") @app.route("/")
def index(): def index():
from flask import render_template
repo = get_repo() repo = get_repo()
entities = repo.list_entities() entities = repo.list_entities()
dims = {e.dimension for e in entities} dims = {e.dimension for e in entities}
@@ -66,12 +142,21 @@ def create_app() -> Flask:
"domains": len(domains), "domains": len(domains),
"combinations": sum(status_counts.values()), "combinations": sum(status_counts.values()),
} }
return render_template("home.html", stats=stats) top_concepts = []
for d in domains:
top = repo.get_top_results(d.name, limit=1)
if top and top[0]["composite_score"]:
top_concepts.append((d, top[0]))
return render_template("home.html", stats=stats, top_concepts=top_concepts)
return app return app
def run() -> None: def run() -> None:
"""Entry point for `physcom-web` script.""" """Entry point for `physcom-web` script."""
app = create_app() app = create_app(open_access=True)
app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000"))) app.run(
host=os.environ.get("HOST", "127.0.0.1"),
debug=os.environ.get("FLASK_DEBUG") == "1",
port=int(os.environ.get("PORT", "5000")),
)

View File

@@ -3,9 +3,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import threading import threading
from pathlib import Path
from flask import Blueprint, flash, redirect, render_template, request, url_for from flask import Blueprint, flash, redirect, render_template, request, url_for
@@ -138,8 +136,8 @@ def pipeline_run():
run_id = repo.create_pipeline_run(domain.id, config) run_id = repo.create_pipeline_run(domain.id, config)
# Resolve DB path for the background thread # Resolve DB path for the background thread
from physcom_web.app import DEFAULT_DB from physcom_web.app import db_path as _db_path
db_path = str(Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB)))) db_path = str(_db_path())
# Start background thread # Start background thread
t = threading.Thread( t = threading.Thread(

View File

@@ -2,6 +2,8 @@
from __future__ import annotations from __future__ import annotations
import math
from flask import Blueprint, flash, redirect, render_template, request, url_for from flask import Blueprint, flash, redirect, render_template, request, url_for
from physcom.engine.constraint_resolver import ConstraintResolver from physcom.engine.constraint_resolver import ConstraintResolver
@@ -104,9 +106,10 @@ def explore(domain_name: str, combo_id: int):
if raw is None: if raw is None:
return None return None
try: try:
return float(raw) value = float(raw)
except ValueError: except ValueError:
return None return None
return value if math.isfinite(value) else None
explore_result = _run_evaluate( explore_result = _run_evaluate(
repo, domain, combo, repo, domain, combo,

View File

@@ -704,3 +704,14 @@ select option {
/* ── Google Fonts import ─────────────────────────────────── */ /* ── Google Fonts import ─────────────────────────────────── */
@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
/* Read-only public mode: hide every write control (the server rejects them anyway). */
body.readonly form[method="post"]:not(.public) { display: none; }
.nav-logout { display: inline; margin: 0; }
.nav-logout button {
background: none; border: none; cursor: pointer;
color: var(--text-secondary); font: inherit; font-size: 0.88rem; font-weight: 500;
padding: 0.4rem 0.75rem; border-radius: var(--radius);
}
.nav-logout button:hover { color: var(--text-primary); background: var(--bg-elevated); }

View File

@@ -8,7 +8,7 @@
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="https://unpkg.com/htmx.org@2.0.4"></script> <script src="https://unpkg.com/htmx.org@2.0.4"></script>
</head> </head>
<body> <body{% if not is_admin() %} class="readonly"{% endif %}>
<nav> <nav>
<a href="{{ url_for('index') }}" class="nav-brand"> <a href="{{ url_for('index') }}" class="nav-brand">
<img src="{{ url_for('static', filename='logo.svg') }}" alt=""> <img src="{{ url_for('static', filename='logo.svg') }}" alt="">
@@ -17,9 +17,14 @@
<ul> <ul>
<li><a href="{{ url_for('entities.entity_list') }}">Entities</a></li> <li><a href="{{ url_for('entities.entity_list') }}">Entities</a></li>
<li><a href="{{ url_for('domains.domain_list') }}">Domains</a></li> <li><a href="{{ url_for('domains.domain_list') }}">Domains</a></li>
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
<li><a href="{{ url_for('results.results_index') }}">Results</a></li> <li><a href="{{ url_for('results.results_index') }}">Results</a></li>
{% if is_admin() %}
<li><a href="{{ url_for('pipeline.pipeline_form') }}">Pipeline</a></li>
<li><a href="{{ url_for('admin.admin_index') }}">Admin</a></li> <li><a href="{{ url_for('admin.admin_index') }}">Admin</a></li>
{% if not config.OPEN_ACCESS %}
<li><form method="post" action="{{ url_for('logout') }}" class="nav-logout"><button type="submit">Log out</button></form></li>
{% endif %}
{% endif %}
</ul> </ul>
</nav> </nav>

View File

@@ -4,7 +4,7 @@
{% block content %} {% block content %}
<div class="page-header"> <div class="page-header">
<h1>Domains</h1> <h1>Domains</h1>
<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a> {% if is_admin() %}<a href="{{ url_for('domains.domain_new') }}" class="btn btn-primary">New Domain</a>{% endif %}
</div> </div>
{% if not domains %} {% if not domains %}

View File

@@ -4,7 +4,7 @@
{% block content %} {% block content %}
<div class="page-header"> <div class="page-header">
<h1>Entities</h1> <h1>Entities</h1>
<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a> {% if is_admin() %}<a href="{{ url_for('entities.entity_new') }}" class="btn btn-primary">+ Add Entity</a>{% endif %}
</div> </div>
{% if not grouped %} {% if not grouped %}

View File

@@ -14,11 +14,41 @@
entity combinations against real-world physics. entity combinations against real-world physics.
</p> </p>
<div class="hero-actions"> <div class="hero-actions">
{% if is_admin() %}
<a href="{{ url_for('pipeline.pipeline_form') }}" class="btn btn-primary">Run Pipeline</a> <a href="{{ url_for('pipeline.pipeline_form') }}" class="btn btn-primary">Run Pipeline</a>
<a href="{{ url_for('results.results_index') }}" class="btn">View Results</a> {% endif %}
<a href="{{ url_for('results.results_index') }}" class="btn{% if not is_admin() %} btn-primary{% endif %}">View Results</a>
</div> </div>
</div> </div>
{% if top_concepts %}
<!-- Best concept per domain -->
<h2 class="section-heading">Top Concepts</h2>
<p class="section-desc">
The highest-scoring surviving combination in each domain, out of
{{ stats.combinations }} generated.
</p>
<div class="card">
<table>
<thead><tr><th>Domain</th><th>Concept</th><th>Score</th><th></th></tr></thead>
<tbody>
{% for domain, r in top_concepts %}
<tr>
<td>{{ domain.name }}</td>
<td>{{ r.combination.entities|map(attribute='name')|join(' + ') }}</td>
<td class="score-cell">{{ "%.4f"|format(r.composite_score) }}</td>
<td>
<a href="{{ url_for('results.result_detail', domain_name=domain.name, combo_id=r.combination.id) }}"
class="btn btn-sm">View</a>
<a href="{{ url_for('results.results_domain', domain_name=domain.name) }}" class="btn btn-sm">All</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
<!-- How It Works --> <!-- How It Works -->
<h2 class="section-heading">How It Works</h2> <h2 class="section-heading">How It Works</h2>
<p class="section-desc"> <p class="section-desc">

View File

@@ -0,0 +1,16 @@
{% extends "base.html" %}
{% block title %}Admin login — PhysCom{% endblock %}
{% block content %}
<h1>Admin login</h1>
<div class="card">
{% if error %}<div class="flash flash-error">{{ error }}</div>{% endif %}
<form method="post" class="public">
<div class="form-group">
<label for="token">Admin token</label>
<input type="password" id="token" name="token" required autofocus autocomplete="current-password">
</div>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
{% endblock %}

View File

@@ -58,7 +58,7 @@
{% if status_filter or rating_filter %} {% if status_filter or rating_filter %}
<p class="empty">No results matching that filter in this domain.</p> <p class="empty">No results matching that filter in this domain.</p>
{% else %} {% else %}
<p class="empty">No results for this domain yet. <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.</p> <p class="empty">No results for this domain yet.{% if is_admin() %} <a href="{{ url_for('pipeline.pipeline_form') }}">Run the pipeline</a> first.{% endif %}</p>
{% endif %} {% endif %}
{% else %} {% else %}
<table> <table>

161
tests/test_web_access.py Normal file
View File

@@ -0,0 +1,161 @@
"""Web UI: read-only public mode, admin login, and a GET smoke test of every page."""
from __future__ import annotations
import pytest
from physcom.db.repository import Repository
from physcom.db.schema import init_db
from physcom.engine.constraint_resolver import ConstraintResolver
from physcom.engine.pipeline import Pipeline
from physcom.engine.scorer import Scorer
from physcom.seed.transport_example import load_transport_seed
TOKEN = "test-admin-token"
@pytest.fixture(scope="module")
def db_file(tmp_path_factory):
path = tmp_path_factory.mktemp("web") / "physcom.db"
repo = Repository(init_db(path))
load_transport_seed(repo)
domain = repo.get_domain("urban_commuting")
Pipeline(repo, ConstraintResolver(), Scorer(domain)).run(
domain, ["platform", "actuator", "energy_storage"],
score_threshold=0.01, passes=[1, 2, 3],
)
ids = {
"entity_id": repo.list_entities()[0].id,
"domain_id": domain.id,
"combo_id": next(
r["combination"].id for r in repo.get_all_results("urban_commuting")
if r["pass_reached"] >= 3
),
}
repo.conn.close()
return path, ids
def _app(monkeypatch, db_file, token: str | None, open_access: bool = False):
from physcom_web.app import create_app
monkeypatch.setenv("PHYSCOM_DB", str(db_file[0]))
monkeypatch.setenv("FLASK_SECRET_KEY", "test")
if token:
monkeypatch.setenv("PHYSCOM_ADMIN_TOKEN", token)
else:
monkeypatch.delenv("PHYSCOM_ADMIN_TOKEN", raising=False)
return create_app(open_access=open_access)
@pytest.fixture
def visitor(monkeypatch, db_file):
return _app(monkeypatch, db_file, TOKEN).test_client()
@pytest.fixture
def admin(monkeypatch, db_file):
client = _app(monkeypatch, db_file, TOKEN).test_client()
assert client.post("/login", data={"token": TOKEN}).status_code == 302
return client
def _public_pages(ids):
return [
"/", "/entities/", f"/entities/{ids['entity_id']}",
"/domains/", f"/domains/{ids['domain_id']}",
"/results/", "/results/urban_commuting",
f"/results/urban_commuting/{ids['combo_id']}",
"/login",
]
def _admin_pages():
return ["/admin/", "/pipeline/", "/entities/new", "/domains/new", "/admin/snapshot/export"]
def test_visitor_can_browse(visitor, db_file):
for url in _public_pages(db_file[1]):
assert visitor.get(url).status_code == 200, url
def test_visitor_cannot_reach_admin_pages(visitor):
for url in _admin_pages():
resp = visitor.get(url)
assert resp.status_code == 302 and "/login" in resp.location, url
def test_visitor_cannot_write(visitor, db_file):
ids = db_file[1]
for url in [
"/admin/wipe", "/admin/reseed", "/pipeline/run",
f"/entities/{ids['entity_id']}/delete", f"/domains/{ids['domain_id']}/delete",
"/results/urban_commuting/reset",
f"/results/urban_commuting/{ids['combo_id']}/review",
]:
assert visitor.post(url).status_code == 403, url
def test_visitor_can_explore(visitor, db_file):
url = f"/results/urban_commuting/{db_file[1]['combo_id']}/explore"
assert visitor.post(url, data={"platform_mass": "inf"}).status_code == 200
def test_home_lists_top_concept(visitor):
html = visitor.get("/").get_data(as_text=True)
assert "Top Concepts" in html and "urban_commuting" in html
def test_visitor_pages_hide_write_controls(visitor):
html = visitor.get("/").get_data(as_text=True)
assert 'class="readonly"' in html
assert "/admin/" not in html and "/pipeline/" not in html
def test_wrong_token_rejected(visitor):
assert visitor.post("/login", data={"token": "nope"}).status_code == 401
assert visitor.get("/admin/").status_code == 302
def test_no_token_means_no_login(monkeypatch, db_file):
client = _app(monkeypatch, db_file, None).test_client()
assert client.post("/login", data={"token": ""}).status_code == 401
assert client.post("/admin/wipe").status_code == 403
def test_login_redirect_stays_on_site(visitor):
resp = visitor.post("/login?next=//evil.example", data={"token": TOKEN})
assert resp.location == "/"
resp = visitor.post("/login?next=/admin/", data={"token": TOKEN})
assert resp.location == "/admin/"
def test_admin_can_reach_everything(admin, db_file):
for url in _public_pages(db_file[1]) + _admin_pages():
assert admin.get(url).status_code == 200, url
html = admin.get("/").get_data(as_text=True)
assert 'class="readonly"' not in html
def test_open_access_dev_server(monkeypatch, db_file):
app = _app(monkeypatch, db_file, None, open_access=True)
assert app.test_client().get("/admin/").status_code == 200
# Setting a token locks even the dev server.
app = _app(monkeypatch, db_file, TOKEN, open_access=True)
assert app.test_client().get("/admin/").status_code == 302
def test_debug_off_by_default(monkeypatch, db_file):
import physcom_web.app as web
seen = {}
monkeypatch.delenv("FLASK_DEBUG", raising=False)
monkeypatch.setenv("PHYSCOM_DB", str(db_file[0]))
monkeypatch.setattr("flask.Flask.run", lambda self, **kw: seen.update(kw))
web.run()
assert seen["debug"] is False and seen["host"] == "127.0.0.1"
def test_cli_demo_if_empty_skips_populated_db(db_file):
from click.testing import CliRunner
from physcom.cli import main
result = CliRunner().invoke(main, ["--db", str(db_file[0]), "demo", "--if-empty"])
assert result.exit_code == 0 and "skipping" in result.output