From 8171fc023eca5a3308a195a39abfdb2f30966e58 Mon Sep 17 00:00:00 2001
From: asimonson1125
Date: Fri, 25 Sep 2026 15:40:02 -0500
Subject: [PATCH] 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
---
.claude/settings.local.json | 15 --
.dockerignore | 2 +
.env.example | 9 +-
.github/workflows/test.yml | 19 +++
.gitignore | 3 +
CLAUDE.md | 7 +-
Dockerfile | 16 +-
IMPLEMENTATION_PLAN.md | 23 ++-
README.md | 95 ++++++-----
docker-compose.yml | 44 +++--
pyproject.toml | 13 +-
src/physcom/cli.py | 27 +++-
src/physcom_web/app.py | 103 ++++++++++--
src/physcom_web/routes/pipeline.py | 6 +-
src/physcom_web/routes/results.py | 5 +-
src/physcom_web/static/style.css | 11 ++
src/physcom_web/templates/base.html | 9 +-
src/physcom_web/templates/domains/list.html | 2 +-
src/physcom_web/templates/entities/list.html | 2 +-
src/physcom_web/templates/home.html | 32 +++-
src/physcom_web/templates/login.html | 16 ++
src/physcom_web/templates/results/list.html | 2 +-
tests/test_web_access.py | 161 +++++++++++++++++++
23 files changed, 510 insertions(+), 112 deletions(-)
delete mode 100644 .claude/settings.local.json
create mode 100644 .github/workflows/test.yml
create mode 100644 src/physcom_web/templates/login.html
create mode 100644 tests/test_web_access.py
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
deleted file mode 100644
index 6f17283..0000000
--- a/.claude/settings.local.json
+++ /dev/null
@@ -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:*)"
- ]
- }
-}
diff --git a/.dockerignore b/.dockerignore
index 7c3b477..f6e18b1 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -8,3 +8,5 @@ data/
.claude/
.venv/
*.md
+!README.md
+.env
diff --git a/.env.example b/.env.example
index 96f602a..6b97092 100644
--- a/.env.example
+++ b/.env.example
@@ -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=
+# 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)
# Supported: gemini, ollama
LLM_PROVIDER=
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..66eb0c3
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -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
diff --git a/.gitignore b/.gitignore
index a5bfdcc..e710393 100644
--- a/.gitignore
+++ b/.gitignore
@@ -178,3 +178,6 @@ cython_debug/
data/
.aider*
+
+# Local Claude Code settings
+.claude/settings.local.json
diff --git a/CLAUDE.md b/CLAUDE.md
index 4615143..79cfe1f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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.
- **Single test file**: `python -m pytest tests/test_scorer.py -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)
- **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
@@ -35,7 +35,7 @@ src/physcom/ # Core library (no web dependency)
seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains
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/results.py # Results browse, detail view, human review submission
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).
- **`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.
+- **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.
## Data flow (pipeline passes)
diff --git a/Dockerfile b/Dockerfile
index f7554ad..93429e1 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -2,14 +2,22 @@ FROM python:3.13-slim AS base
WORKDIR /app
-COPY pyproject.toml .
+COPY pyproject.toml README.md ./
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
ENV PHYSCOM_DB=/app/data/physcom.db
-ENV HOST=0.0.0.0
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()'"]
diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md
index ca0881a..313f351 100644
--- a/IMPLEMENTATION_PLAN.md
+++ b/IMPLEMENTATION_PLAN.md
@@ -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. |
diff --git a/README.md b/README.md
index 198afb5..f8a3899 100644
--- a/README.md
+++ b/README.md
@@ -1,72 +1,68 @@
-# Applied Combinatorics
+# Physical Combinatorics
### 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.
+[](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
- Airplane
- Train
- Bicycle
- Walking with your legs
- - Wheelchair
- - Scooter
- 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
- - Lithium Ion Batteries
- - Hydrogen Combustion Engine
- - Human pedalling
- - Modular Nuclear Reactor
- - Coal/steam locomotion
- - the Sun via Solar Sail
- - Cannonfire Recoil
- - Pushed by a friend
+ - Gas engine, electric motor, human pedalling, a solar sail, cannonfire recoil...
+ - Gasoline, lithium ion batteries, hydrogen, coal, sunlight, gunpowder...
-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
- - Cost efficiency
- - Availability
- - Safety
- - Range (by fuel)
- - Range (by platform degredation or maintenance)
+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?
- 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
### Docker (recommended)
```bash
+cp .env.example .env # set PHYSCOM_ADMIN_TOKEN to be able to edit
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
-docker compose run cli seed transport
+docker compose run --rm cli results urban_commuting --top 10
```
### Local development
```bash
pip install -e ".[dev,web]"
-python -m physcom init
-python -m physcom seed transport
-python -m physcom_web
+python -m physcom demo # seed + run passes 1-3 for every domain
+python -m physcom_web # localhost-only dev server, no login needed
```
-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:
@@ -74,9 +70,9 @@ Run tests:
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.
Gemini:
@@ -98,15 +94,32 @@ export LLM_PROVIDER=ollama
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.
-Metric weights are therefore dependent on domain, which will also need to be defined.
+- It serves with gunicorn (one worker, eight threads), runs as a non-root user and has a healthcheck.
+- 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.
\ No newline at end of file
+```
+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
+```
diff --git a/docker-compose.yml b/docker-compose.yml
index abb4247..b4a47b7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -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:
web:
build: .
@@ -6,37 +15,24 @@ services:
volumes:
- physcom-data:/app/data
environment:
- - PHYSCOM_DB=/app/data/physcom.db
- - FLASK_SECRET_KEY=${FLASK_SECRET_KEY:-}
- - LLM_PROVIDER=${LLM_PROVIDER:-}
- - GEMINI_API_KEY=${GEMINI_API_KEY:-}
- - GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash}
+ <<: *env
+ FLASK_SECRET_KEY: ${FLASK_SECRET_KEY:-}
+ # Visitors are read-only; log in at /login with this token to edit or run.
+ PHYSCOM_ADMIN_TOKEN: ${PHYSCOM_ADMIN_TOKEN:-}
+ PHYSCOM_SECURE_COOKIES: ${PHYSCOM_SECURE_COOKIES:-0}
+ extra_hosts:
+ - "host.docker.internal:host-gateway"
restart: unless-stopped
- expose:
- - 5000
cli:
build: .
volumes:
- physcom-data:/app/data
- environment:
- - PHYSCOM_DB=/app/data/physcom.db
- - LLM_PROVIDER=${LLM_PROVIDER:-}
- - GEMINI_API_KEY=${GEMINI_API_KEY:-}
- - GEMINI_MODEL=${GEMINI_MODEL:-gemini-2.0-flash}
- entrypoint: ["python", "-m", "physcom"]
+ environment: *env
+ extra_hosts:
+ - "host.docker.internal:host-gateway"
+ entrypoint: ["physcom"]
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:
physcom-data:
- # pgdata:
diff --git a/pyproject.toml b/pyproject.toml
index c27e7d1..ec955c8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -6,7 +6,14 @@ build-backend = "setuptools.build_meta"
name = "physcom"
version = "0.1.0"
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 = [
"click>=8.1",
]
@@ -17,11 +24,15 @@ dev = [
]
web = [
"flask>=3.0",
+ "gunicorn>=22.0",
]
gemini = [
"google-genai>=1.0",
]
+[project.urls]
+Repository = "https://git.asimonson.com/andrew/physicalCombinatorics"
+
[project.scripts]
physcom = "physcom.cli:main"
physcom-web = "physcom_web.app:run"
diff --git a/src/physcom/cli.py b/src/physcom/cli.py
index c9a0da4..022db3f 100644
--- a/src/physcom/cli.py
+++ b/src/physcom/cli.py
@@ -19,7 +19,7 @@ def _get_repo(db_path: str | None = None) -> Repository:
@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
def main(ctx, db):
"""Physical Combinatorics — innovation via attribute mixing."""
@@ -49,6 +49,31 @@ def seed(ctx, seed_name):
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()
def entity():
"""Manage entities."""
diff --git a/src/physcom_web/app.py b/src/physcom_web/app.py
index 09557b1..97a26c6 100644
--- a/src/physcom_web/app.py
+++ b/src/physcom_web/app.py
@@ -2,11 +2,12 @@
from __future__ import annotations
+import hmac
import os
import secrets
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.repository import Repository
@@ -15,12 +16,41 @@ from physcom.units import format_quantity
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:
"""Return a Repository scoped to the current request."""
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)
return g.repo
@@ -31,9 +61,56 @@ def close_db(exc: BaseException | None = None) -> None:
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.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
@@ -54,7 +131,6 @@ def create_app() -> Flask:
@app.route("/")
def index():
- from flask import render_template
repo = get_repo()
entities = repo.list_entities()
dims = {e.dimension for e in entities}
@@ -66,12 +142,21 @@ def create_app() -> Flask:
"domains": len(domains),
"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
def run() -> None:
"""Entry point for `physcom-web` script."""
- app = create_app()
- app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000")))
+ app = create_app(open_access=True)
+ 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")),
+ )
diff --git a/src/physcom_web/routes/pipeline.py b/src/physcom_web/routes/pipeline.py
index b2ac11f..fd9f2e6 100644
--- a/src/physcom_web/routes/pipeline.py
+++ b/src/physcom_web/routes/pipeline.py
@@ -3,9 +3,7 @@
from __future__ import annotations
import json
-import os
import threading
-from pathlib import Path
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)
# Resolve DB path for the background thread
- from physcom_web.app import DEFAULT_DB
- db_path = str(Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB))))
+ from physcom_web.app import db_path as _db_path
+ db_path = str(_db_path())
# Start background thread
t = threading.Thread(
diff --git a/src/physcom_web/routes/results.py b/src/physcom_web/routes/results.py
index afd43a9..ff7de66 100644
--- a/src/physcom_web/routes/results.py
+++ b/src/physcom_web/routes/results.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import math
+
from flask import Blueprint, flash, redirect, render_template, request, url_for
from physcom.engine.constraint_resolver import ConstraintResolver
@@ -104,9 +106,10 @@ def explore(domain_name: str, combo_id: int):
if raw is None:
return None
try:
- return float(raw)
+ value = float(raw)
except ValueError:
return None
+ return value if math.isfinite(value) else None
explore_result = _run_evaluate(
repo, domain, combo,
diff --git a/src/physcom_web/static/style.css b/src/physcom_web/static/style.css
index 99d5a0b..7c1369d 100644
--- a/src/physcom_web/static/style.css
+++ b/src/physcom_web/static/style.css
@@ -704,3 +704,14 @@ select option {
/* ── 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');
+
+/* 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); }
diff --git a/src/physcom_web/templates/base.html b/src/physcom_web/templates/base.html
index 88bddf5..af1087f 100644
--- a/src/physcom_web/templates/base.html
+++ b/src/physcom_web/templates/base.html
@@ -8,7 +8,7 @@
-
+
diff --git a/src/physcom_web/templates/domains/list.html b/src/physcom_web/templates/domains/list.html
index a52b85b..0837fe7 100644
--- a/src/physcom_web/templates/domains/list.html
+++ b/src/physcom_web/templates/domains/list.html
@@ -4,7 +4,7 @@
{% block content %}