- 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>
7.0 KiB
7.0 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this project is
PhysCom (Physical Combinatorics) — innovation discovery engine that generates entity combinations across dimensions (e.g. platform × power_source), filters by physical constraints, scores against domain-specific metrics, and ranks results. Includes a CLI, a Flask/HTMX web UI, and a 5-pass pipeline (constraints → estimation → scoring → LLM review → human review).
Commands
- Install:
pip install -e ".[dev,web]"(editable install with test and web deps) - 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(localhost, open access, debug only withFLASK_DEBUG=1) - CLI:
python -m physcom(orphyscomif installed) - Docker:
docker compose up web/docker compose run cli physcom seed - Demo data:
python -m physcom demoseeds + runs passes 1-3 for every domain (~20s). The Docker image does this on first start (--if-empty). DB isdata/physcom.dbor$PHYSCOM_DB.
Architecture
src/physcom/ # Core library (no web dependency)
models/ # Dataclasses: Entity, Dependency, Combination, Domain, MetricBound
db/schema.py # DDL (all CREATE TABLE statements)
db/repository.py # All DB access — single Repository class, sqlite3 row_factory=Row
engine/combinator.py # Cartesian product of entities across dimensions
engine/constraint_resolver.py # Pass 1: requires/excludes/mutex/range/force checks
engine/scorer.py # Pass 3: log-normalize raw→0-1, weighted geometric mean composite
engine/formula.py # Safe AST evaluator for domain-authored pass-2 formulas
engine/pipeline.py # Orchestrator: combo-first loop, incremental saves, resume, cancel
llm/base.py # LLMProvider ABC (review_plausibility — pass 4 only)
llm/registry.py # build_llm_provider() from LLM_PROVIDER env / web form
llm/providers/ # gemini.py, ollama.py, mock.py (tests)
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, 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
routes/domains.py # Domain CRUD: metrics, free variables, formulas
routes/admin.py # Reseed, wipe, JSON snapshot export/import
templates/ # Jinja2, extends base.html, uses HTMX for polling
static/style.css # Single stylesheet
tests/ # pytest, uses seeded_repo fixture from conftest.py
Key patterns
- Guardrails are emergent, not authored. Entities never reference each other by name. Each declares only its own intrinsic physical envelope (
requires/provides/excludesfor categorical fit,range_min/range_maxfor numeric floors/ceilings on shared keys likemass,footprint,energy_density).ConstraintResolvercross-checks these generically across every pair in a combo — a nuclear reactor is blocked from a bicycle becausemass range_mincollides withmass range_max, not because any code says "nuclear + bicycle = blocked." When adding physical realism to an entity, add a property to the entity — never a pairwise special case inConstraintResolver. A category missing a floor it should have is a silent guardrail hole (blocks nothing, looks fine). SeeLOGIC DOCS/002-guardrails-via-intrinsic-properties.md. - Repository is the only DB interface. No raw SQL outside
repository.py. - Pipeline is combo-first: each combo goes through all requested passes before the next combo starts. Progress is persisted per-combo (crash-safe, resumable).
pipeline_runstable tracks run lifecycle: pending → running → completed/failed/cancelled. The web route creates the record, then starts a background thread with its ownsqlite3.Connection.combination_resultshas rows for ALL combos including blocked ones (pass_reached=1, composite_score=0.0). Scored combos get pass_reached=3+.- Status guard:
update_combination_statusrefuses to downgradereviewed→scored. save_combinationloads existing status/block_reason on dedup (important for resume).ensure_metricbackfills 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 (exceptresults.explore) and the admin/pipeline/new pages behind a session login withPHYSCOM_ADMIN_TOKEN. Only the dev server (run()→create_app(open_access=True)) is open, and only while no token is set. Templates useis_admin();body.readonlyhides everyform[method=post]via CSS — a new write form needs no template guard, but a new public POST must be added toPUBLIC_POST_ENDPOINTS. - HTMX polling:
_run_status.htmlpartial polls every 2s while run is pending/running; stops polling when terminal.
Data flow (pipeline passes)
- Pass 1 — Constraints:
ConstraintResolver.resolve()→ blocked/conditional/valid. Blocked combos get a result row andcontinue. - Pass 2 — Estimation:
_estimate_physics()(deterministic physics engine; estimator-only, no LLM) → raw metric values. Saved immediately viasave_raw_estimates()(normalized_score=NULL). - Pass 3 — Scoring:
Scorer.score_combination()→ log-normalized scores + weighted geometric mean composite. Saves viasave_scores()+save_result(). - Pass 4 — LLM Review: Only for above-threshold combos with an LLM provider (Gemini or Ollama, via
llm/registry.py). - Pass 5 — Human Review: Manual via web UI results page.
Testing
- Tests use
seeded_repofixture (in-memory SQLite with the transport seed data). There's also a barerepofixture for tests that seed their own data. - Individual entity fixtures (walking, bicycle, spaceship, solar_sail, etc.) are defined in
conftest.py.
Conventions
- Python 3.11+,
from __future__ import annotationseverywhere. - Dataclasses for models, no ORM.
- Don't use
cdin Bash commands — run from the working directory so pre-approved permission patterns match. - Don't add docstrings/comments/type annotations to code you didn't change.
INSERT OR IGNOREwon't update existing rows — if adding a new column/field to seed data, also add an UPDATE for backfill.- Jinja2
0.0is falsy — useis not nonenotif valuewhen displaying scores that can legitimately be zero.