diff --git a/CLAUDE.md b/CLAUDE.md index d997a54..5bf57a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates ## Commands - **Install**: `pip install -e ".[dev,web]"` (editable install with test and web deps) -- **Tests (all)**: `python -m pytest tests/ -q` (48 tests, ~5s). Run after every change. +- **Tests (all)**: `python -m pytest tests/ -q` (134 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` diff --git a/Dockerfile b/Dockerfile index e5d5934..f7554ad 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,6 +9,7 @@ RUN pip install --no-cache-dir ".[web,gemini]" VOLUME /app/data ENV PHYSCOM_DB=/app/data/physcom.db +ENV HOST=0.0.0.0 EXPOSE 5000 CMD ["python", "-m", "physcom_web"] diff --git a/src/physcom/engine/formula.py b/src/physcom/engine/formula.py index 3bac6bb..84d13c1 100644 --- a/src/physcom/engine/formula.py +++ b/src/physcom/engine/formula.py @@ -12,7 +12,6 @@ from __future__ import annotations import ast import math import operator -from dataclasses import dataclass from typing import Callable @@ -50,12 +49,6 @@ DEFAULT_FUNCTIONS: dict[str, Callable[..., float]] = { } -@dataclass(frozen=True) -class CompiledFormula: - source: str - _tree: ast.Expression - - def _validate(tree: ast.AST) -> None: for node in ast.walk(tree): if not isinstance(node, _ALLOWED_NODES): @@ -73,13 +66,13 @@ def _validate(tree: ast.AST) -> None: raise FormulaError("only direct function calls are allowed") -def compile_formula(source: str) -> CompiledFormula: +def compile_formula(source: str) -> ast.Expression: try: tree = ast.parse(source, mode="eval") except SyntaxError as exc: raise FormulaError(f"invalid syntax in '{source}': {exc}") from exc _validate(tree) - return CompiledFormula(source=source, _tree=tree) + return tree def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Callable]): @@ -97,18 +90,12 @@ def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Calla raise FormulaError(f"unknown variable '{node.id}'") return variables[node.id] if isinstance(node, ast.BinOp): - op = _BINOPS.get(type(node.op)) - if op is None: - raise FormulaError(f"unsupported operator: {type(node.op).__name__}") - return op( + return _BINOPS[type(node.op)]( _eval(node.left, variables, functions), _eval(node.right, variables, functions), ) if isinstance(node, ast.UnaryOp): - op = _UNARYOPS.get(type(node.op)) - if op is None: - raise FormulaError(f"unsupported operator: {type(node.op).__name__}") - return op(_eval(node.operand, variables, functions)) + return _UNARYOPS[type(node.op)](_eval(node.operand, variables, functions)) if isinstance(node, ast.Call): fname = node.func.id # validated as ast.Name by _validate func = functions.get(fname) @@ -121,19 +108,17 @@ def _eval(node: ast.AST, variables: dict[str, float], functions: dict[str, Calla def evaluate_formula( - compiled: CompiledFormula, + compiled: ast.Expression, variables: dict[str, float], functions: dict[str, Callable] | None = None, ) -> float: effective_functions = {**DEFAULT_FUNCTIONS, **(functions or {})} try: - result = _eval(compiled._tree, variables, effective_functions) - except FormulaError: - raise + result = _eval(compiled, variables, effective_functions) except (TypeError, ValueError, ArithmeticError) as exc: - raise FormulaError(f"error evaluating '{compiled.source}': {exc}") from exc + raise FormulaError(f"error evaluating '{ast.unparse(compiled)}': {exc}") from exc if not isinstance(result, (int, float)) or isinstance(result, bool): raise FormulaError( - f"formula '{compiled.source}' did not evaluate to a number" + f"formula '{ast.unparse(compiled)}' did not evaluate to a number" ) return float(result) diff --git a/src/physcom/engine/pipeline.py b/src/physcom/engine/pipeline.py index e35be84..6eae826 100644 --- a/src/physcom/engine/pipeline.py +++ b/src/physcom/engine/pipeline.py @@ -10,14 +10,14 @@ from datetime import datetime, timezone from physcom.db.repository import Repository from physcom.engine.combinator import generate_combinations from physcom.engine.constraint_resolver import ConstraintResolver, ConstraintResult -from physcom.engine.scorer import Scorer, composite_score, normalize +from physcom.engine.scorer import Scorer, score_raw from physcom.llm.base import LLMProvider, LLMRateLimitError from physcom.llm.parsing import parse_rating from physcom.models.combination import Combination, ScoredResult from physcom.models.domain import Domain, MetricBound from physcom.models.entity import Entity -# Stub-estimator heuristics (used only when no LLM provider is configured). +# Pass-2 estimator heuristics. # Keyed by the same categorical vocabulary already used in seed data — never # by entity name, so new entities inherit sensible behavior automatically. @@ -72,8 +72,7 @@ INFRASTRUCTURE_AVAILABILITY: dict[tuple[str, str], float] = { } # Crude freight-capacity proxy: kg of cargo per kg of vehicle structural -# mass. Was 500 -- a magnitude error (500x cargo-to-structure has no real -# vehicle analog). Real cargo ships run deadweight/lightship ratios of +# mass. Real cargo ships run deadweight/lightship ratios of # roughly 1.5-4x depending on class; 2.5 is a reasonable general-cargo # midpoint for this domain-agnostic proxy. CARGO_KG_PER_STRUCTURAL_KG: float = 2.5 @@ -209,8 +208,7 @@ def _solve_achievable_speed_mps( (derivative 3*A*v^2 + B > 0 everywhere), so it has exactly one non-negative real root -- solved directly via Cardano's formula, no iteration needed. Falls back to the plain linear model (v = power/k_med) - when there's no drag coefficient for this medium, so ungraded media - behave exactly as before.""" + when there's no drag coefficient for this medium.""" if power_density <= 0 or k_med is None: return 0.0 if drag_coeff <= 0 or floor_total <= 0: @@ -245,8 +243,7 @@ AMBIENT_ENERGY_FORMS: set[str] = {"wind", "radiation_pressure", "gravitational"} # aircraft, hull drag for water. Keyed by the platform's declared `medium`, # not per-platform -- a real train's steel-wheel-on-rail is far more # efficient than a car's tire, both currently "ground" -- flagged as the -# coarsest approximation here, same spot the earlier LLM comparison found -# every model's range_fuel guess off by 10-25x from real vehicles. +# coarsest approximation here. SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = { "ground": 0.016 * 9.81, # combined rolling + aero "road load", Crr-equivalent ~ 0.016 "air": 9.81 / 10, # cruise flight, effective L/D ~ 10 @@ -257,42 +254,15 @@ SPECIFIC_ENERGY_CONSUMPTION_J_PER_KG_M: dict[str, float] = { # mass)" shape is the wrong model for them; real range is governed by the # rocket equation (delta-v = exhaust velocity * ln(mass ratio)), which this # pass does not implement. Space is deliberately left out of the dict above -# so it falls through to the old placeholder formula in the code below +# so it falls through to the placeholder formula in the code below # rather than silently claiming a resistance-based number that isn't real. # -# FORMERLY A KNOWN GAP, now fixed below: the table above is mass-proportional -# resistance only (rolling resistance, effectively) -- no aerodynamic drag -# term (force ~ frontal_area * velocity^2, independent of mass). That's a -# reasonable approximation for something car-scale, where rolling resistance -# genuinely dominates at typical speeds and this was validated against real -# car range. It badly overestimated range for light/human-scale vehicles, -# where drag is the dominant resistance term and doesn't scale down with -# mass the way this formula assumes -- confirmed on a real combo (Light -# Personal Vehicle + Electric Motor + Rechargeable Battery, #876): a sane -# 9kg battery on a realistic 31kg vehicle came out to ~1,977km, a 6-9x -# overestimate against real e-bikes on comparable battery energy (~50-80km -# on ~500Wh). It also meant an achieved-speed metric derived from power -# alone (see DRAG_POWER_COEFF_BY_MEDIUM / _solve_achievable_speed_mps below) -# had no ceiling at all -- without a v^2-scaling force to push back, more -# power always bought proportionally more speed, forever. -# -# DRAG_POWER_COEFF_BY_MEDIUM below adds that missing term: a mass-INDEPENDENT -# drag power coefficient (0.5 * air_density * drag_coefficient * frontal_area, -# W per (m/s)^3) added on top of the existing mass-proportional term. -# -# "air" was originally left out of this table on the reasoning that its -# L/D-based cruise model was already a reasonable velocity-roughly-linear -# approximation -- true for computing energy per meter during a normal -# cruise, but WRONG for the exact same reason ground was wrong: L/D-based -# drag force is also roughly velocity-independent within a design cruise -# band, so it's still just "resistance = mass-proportional constant" with -# no v^2 term, and inverting power/resistance for achieved speed still had -# no ceiling. Confirmed live: a Rotorcraft + Gas Turbine combo showed a -# "speed" of 3,127 m/s (Mach 9) with phi4's pass-4 review flagging it -# directly ("unrealistic for urban commuting, likely indicating an -# error"). Added below with an aircraft-like reference cross-section. -# Water hull drag would need its own (different) treatment rather than -# reusing either reference, so it's left as a known remaining gap. +# DRAG_POWER_COEFF_BY_MEDIUM adds the mass-INDEPENDENT aerodynamic drag term +# the table above lacks: 0.5 * air_density * drag_coefficient * frontal_area, +# W per (m/s)^3, added on top of the mass-proportional term. Without it, +# light vehicles (where drag dominates) get wildly overestimated range, and +# achieved speed derived from power has no ceiling. Water hull drag needs +# its own treatment and is a known remaining gap. DRAG_POWER_COEFF_BY_MEDIUM: dict[str, float] = { # 0.5 * rho_air(1.225 kg/m^3) * Cd(~0.3) * frontal_area(~2.2 m^2, small # car reference) -- sanity check: at 30 m/s (108 km/h) this alone costs @@ -340,8 +310,7 @@ HARDWARE_COST_PER_KG_BY_ENERGY_FORM: dict[str, float] = { # Consumable energy price, $ per MJ delivered. Ambient sources (sun, wind, # gravity) are genuinely free; food is a real recurring cost even though it # isn't range-limiting -- cost and range are different questions, see -# AMBIENT_ENERGY_FORMS above. Replaces the old flat $/m ENERGY_FORM_BASE_COST -# placeholder with a real energy-priced figure. +# AMBIENT_ENERGY_FORMS above. FUEL_PRICE_PER_MJ: dict[str, float] = { "wind": 0.0, "gravitational": 0.0, @@ -1126,8 +1095,7 @@ class Pipeline: return float(dep.value) return None - # Step 1: the required floor (same solve as before -- now a floor - # for the search below, not the final answer). + # Step 1: the required floor for the search below. min_accel = dep_value(ctx.platform, "min_effective_accel", "range_min") specific_thrust = dep_value(ctx.actuator, "specific_thrust", "provides") target_velocity = dep_value(ctx.platform, "target_velocity", "provides") @@ -1167,8 +1135,8 @@ class Pipeline: # space-medium platform paired with an actuator that declares # neither specific_thrust nor a usable target velocity) -- # fall back to bare floors, with the same near-zero-mass - # nominal reference used elsewhere so this doesn't silently - # degenerate to 0 power the way the original stub did. + # nominal reference used elsewhere so this doesn't + # degenerate to 0 power. required_actuator = ctx.a_min if ctx.a_min > 0.0 else 10.0 required_storage = ctx.s_min @@ -1222,17 +1190,7 @@ class Pipeline: bounds_by_name, units_by_name, platform_mass=platform_mass, ) - scores, weights = [], [] - for mb in bounds_by_name.values(): - val = raw.get(mb.metric_name) - if val is None: - continue - n = normalize(val, mb.norm_min, mb.norm_max) - if mb.lower_is_better: - n = 1.0 - n - scores.append(n) - weights.append(mb.weight) - return composite_score(scores, weights) + return score_raw(raw, bounds_by_name.values())[0] def best_at_platform(p: float, grid: int, rounds: int) -> tuple[float, float, float]: budget = min(ctx.p_max - p, p * CARGO_KG_PER_STRUCTURAL_KG) @@ -1332,10 +1290,8 @@ class Pipeline: Domains that declare their own metric_formulas (see _estimate_via_formulas) are estimated entirely by those domain-authored formulas instead -- this method's hardcoded - platform/actuator/energy_storage physics model below is additive, - not the only path: it's untouched and still runs unchanged for - every domain that declares no formulas (every existing transport - domain today). + platform/actuator/energy_storage physics model below runs for + every domain that declares no formulas. power_density, speed, range_fuel, cost_efficiency, and cargo_capacity/cargo_capacity_kg are all computed from the @@ -1344,8 +1300,8 @@ class Pipeline: comment above BIOLOGICAL_OPERATOR_MASS_KG for the full formula rationale. - safety/availability/reliability/environmental_impact are untouched - — these are judgment calls (regulatory, economic, qualitative), + safety/availability/reliability/environmental_impact are + judgment calls (regulatory, economic, qualitative), not physics, and stay on the categorical lookup-table heuristics below (actuator's thrust_profile and energy_form and the combo's infrastructure requirements). @@ -1373,8 +1329,7 @@ class Pipeline: bounds_by_name = {mb.metric_name: mb for mb in metric_bounds} raw: dict[str, float] = {m: 0.0 for m in metric_names} - # Extract intrinsic properties from entities (unchanged — still - # drives the untouched blocks below). + # Extract intrinsic properties from entities. power_density = 0.0 # W/kg energy_density = 0.0 # J/kg thrust_profile: str | None = None @@ -1448,8 +1403,8 @@ class Pipeline: Every formula (free-variable floor/ceiling, and each metric) is evaluated through the same safe engine.formula evaluator, given two - kinds of names to resolve: dep(key, constraint_type="provides", - agg=None) -- a declared entity property, aggregated across the + kinds of names to resolve: dep(key, constraint_type="provides") + -- a declared entity property, aggregated across the combo's entities via constraint_resolver.aggregate_dependency_value (the exact sum-vs-max rule ConstraintResolver itself already applies to mass/footprint) -- and any free variable already chosen @@ -1469,19 +1424,19 @@ class Pipeline: from physcom.engine.constraint_resolver import aggregate_dependency_value from physcom.engine.formula import FormulaError, compile_formula, evaluate_formula - def dep(key: str, constraint_type: str = "provides", agg: str | None = None) -> float: - key_aggregation = None if agg is None else {key: agg} - value = aggregate_dependency_value(combo, key, constraint_type, key_aggregation) + def dep(key: str, constraint_type: str = "provides") -> float: + value = aggregate_dependency_value(combo, key, constraint_type) return value if value is not None else 0.0 functions = {"dep": dep} + metric_names = [mf.metric_name for mf in domain.metric_formulas] compiled_metrics: dict[str, object] = {} for mf in domain.metric_formulas: try: compiled_metrics[mf.metric_name] = compile_formula(mf.formula) except FormulaError: - compiled_metrics[mf.metric_name] = None + continue compiled_vars: list[tuple[str, object, object]] = [] for fv in sorted(domain.free_variables, key=lambda v: v.sort_order): @@ -1492,33 +1447,17 @@ class Pipeline: except FormulaError: continue - bounds_by_name = {mb.metric_name: mb for mb in domain.metric_bounds} - def evaluate_metrics(resolved: dict[str, float]) -> dict[str, float]: - raw: dict[str, float] = {} + raw = dict.fromkeys(metric_names, 0.0) for name, compiled in compiled_metrics.items(): - if compiled is None: - raw[name] = 0.0 - continue try: raw[name] = evaluate_formula(compiled, resolved, functions) except FormulaError: - raw[name] = 0.0 + pass return raw def objective(resolved: dict[str, float]) -> float: - raw = evaluate_metrics(resolved) - scores, weights = [], [] - for mb in bounds_by_name.values(): - val = raw.get(mb.metric_name) - if val is None: - continue - n = normalize(val, mb.norm_min, mb.norm_max) - if mb.lower_is_better: - n = 1.0 - n - scores.append(n) - weights.append(mb.weight) - return composite_score(scores, weights) + return score_raw(evaluate_metrics(resolved), domain.metric_bounds)[0] resolved, _score, feasible = self._search_free_variables( compiled_vars, {}, functions, objective @@ -1656,18 +1595,7 @@ class Pipeline: platform_mass=p_mass, ) - normalized: dict[str, float] = {} - scores, weights = [], [] - for mb in domain.metric_bounds: - val = raw.get(mb.metric_name) - if val is None: - continue - n = normalize(val, mb.norm_min, mb.norm_max) - if mb.lower_is_better: - n = 1.0 - n - normalized[mb.metric_name] = n - scores.append(n) - weights.append(mb.weight) + composite, normalized = score_raw(raw, domain.metric_bounds) # Loose slider ceilings for the UI: how big this component could # get if platform and the other component sat at their own floors @@ -1697,5 +1625,5 @@ class Pipeline: "insufficient_structure": (a_mass + s_mass) > p_mass * CARGO_KG_PER_STRUCTURAL_KG, "raw_metrics": raw, "normalized_scores": normalized, - "composite_score": composite_score(scores, weights), + "composite_score": composite, } diff --git a/src/physcom/engine/scorer.py b/src/physcom/engine/scorer.py index 6727dce..e4672a9 100644 --- a/src/physcom/engine/scorer.py +++ b/src/physcom/engine/scorer.py @@ -3,6 +3,7 @@ from __future__ import annotations import math +from typing import Iterable from physcom.models.domain import Domain, MetricBound from physcom.models.combination import Combination, Score, ScoredResult @@ -42,50 +43,37 @@ def composite_score(scores: list[float], weights: list[float]) -> float: return result +def score_raw( + raw: dict[str, float], bounds: Iterable[MetricBound] +) -> tuple[float, dict[str, float]]: + """(composite, per-metric normalized) for raw values against bounds.""" + normalized: dict[str, float] = {} + weights: list[float] = [] + for mb in bounds: + val = raw.get(mb.metric_name) + if val is None: + continue + n = normalize(val, mb.norm_min, mb.norm_max) + normalized[mb.metric_name] = 1.0 - n if mb.lower_is_better else n + weights.append(mb.weight) + return composite_score(list(normalized.values()), weights), normalized + + class Scorer: """Scores combinations against a domain's metric bounds.""" def __init__(self, domain: Domain) -> None: self.domain = domain - self._bounds_by_name: dict[str, MetricBound] = { - mb.metric_name: mb for mb in domain.metric_bounds - } def score_combination( - self, - combination: Combination, - raw_metrics: dict[str, float], - estimation_method: str = "physics_calc", - confidence: float = 1.0, + self, combination: Combination, raw_metrics: dict[str, float] ) -> ScoredResult: - """Score a combination given raw metric values. - - raw_metrics maps metric_name -> raw estimated value. - """ - scores: list[Score] = [] - norm_scores: list[float] = [] - weights: list[float] = [] - - for mb in self.domain.metric_bounds: - raw = raw_metrics.get(mb.metric_name, 0.0) - normed = normalize(raw, mb.norm_min, mb.norm_max) - if mb.lower_is_better: - normed = 1.0 - normed - scores.append(Score( - metric_name=mb.metric_name, - raw_value=raw, - normalized_score=normed, - estimation_method=estimation_method, - confidence=confidence, - )) - norm_scores.append(normed) - weights.append(mb.weight) - - comp = composite_score(norm_scores, weights) - + """Score a combination given raw metric values; missing metrics count as 0.0.""" + raw = {mb.metric_name: raw_metrics.get(mb.metric_name, 0.0) for mb in self.domain.metric_bounds} + comp, normalized = score_raw(raw, self.domain.metric_bounds) return ScoredResult( combination_id=combination.id, domain_name=self.domain.name, - scores=scores, + scores=[Score(metric_name=m, raw_value=raw[m], normalized_score=n) for m, n in normalized.items()], composite_score=comp, ) diff --git a/src/physcom/snapshot.py b/src/physcom/snapshot.py index c12bca2..f68a9ed 100644 --- a/src/physcom/snapshot.py +++ b/src/physcom/snapshot.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import asdict from datetime import datetime, timezone from physcom.db.repository import Repository @@ -70,20 +71,8 @@ def export_snapshot(repo: Repository) -> dict: "key": dc.key, "allowed_values": dc.allowed_values, }) - fvs = [] - for fv in d.free_variables: - fvs.append({ - "name": fv.name, - "sort_order": fv.sort_order, - "floor_formula": fv.floor_formula, - "ceiling_formula": fv.ceiling_formula, - }) - mfs = [] - for mf in d.metric_formulas: - mfs.append({ - "metric_name": mf.metric_name, - "formula": mf.formula, - }) + fvs = [{k: v for k, v in asdict(fv).items() if k != "id"} for fv in d.free_variables] + mfs = [{k: v for k, v in asdict(mf).items() if k != "id"} for mf in d.metric_formulas] domain_list.append({ "name": d.name, "description": d.description, @@ -223,19 +212,8 @@ def import_snapshot(repo: Repository, data: dict, *, clear: bool = False) -> dic ) for dc in d_data.get("constraints", []) ] - fvs = [ - FreeVariable( - name=fv["name"], - floor_formula=fv["floor_formula"], - ceiling_formula=fv["ceiling_formula"], - sort_order=fv.get("sort_order", 0), - ) - for fv in d_data.get("free_variables", []) - ] - mfs = [ - MetricFormula(metric_name=mf["metric_name"], formula=mf["formula"]) - for mf in d_data.get("metric_formulas", []) - ] + fvs = [FreeVariable(**fv) for fv in d_data.get("free_variables", [])] + mfs = [MetricFormula(**mf) for mf in d_data.get("metric_formulas", [])] domain = Domain( name=d_data["name"], description=d_data.get("description", ""), diff --git a/src/physcom_web/app.py b/src/physcom_web/app.py index e148d4b..09557b1 100644 --- a/src/physcom_web/app.py +++ b/src/physcom_web/app.py @@ -14,29 +14,6 @@ from physcom.units import format_quantity DEFAULT_DB = Path("data/physcom.db") -_ENV_FILE = Path(".env") - - -def _load_or_generate_secret_key() -> str: - """Return FLASK_SECRET_KEY from env, .env file, or auto-generate and persist it.""" - key = os.environ.get("FLASK_SECRET_KEY", "").strip() - if key: - return key - - # Try to load from .env - if _ENV_FILE.exists(): - for line in _ENV_FILE.read_text().splitlines(): - line = line.strip() - if line.startswith("FLASK_SECRET_KEY="): - key = line[len("FLASK_SECRET_KEY="):].strip() - if key: - return key - - # Generate, persist, and return - key = secrets.token_hex(32) - with _ENV_FILE.open("a") as f: - f.write(f"FLASK_SECRET_KEY={key}\n") - return key def get_repo() -> Repository: @@ -56,7 +33,7 @@ def close_db(exc: BaseException | None = None) -> None: def create_app() -> Flask: app = Flask(__name__) - app.secret_key = _load_or_generate_secret_key() + app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32) app.jinja_env.filters["qty"] = format_quantity @@ -97,4 +74,4 @@ def create_app() -> Flask: def run() -> None: """Entry point for `physcom-web` script.""" app = create_app() - app.run(host="0.0.0.0", debug=True, port=int(os.environ.get("PORT", "5000"))) + app.run(host=os.environ.get("HOST", "127.0.0.1"), debug=True, port=int(os.environ.get("PORT", "5000"))) diff --git a/src/physcom_web/routes/domains.py b/src/physcom_web/routes/domains.py index 575e36b..c83bbfc 100644 --- a/src/physcom_web/routes/domains.py +++ b/src/physcom_web/routes/domains.py @@ -122,55 +122,50 @@ def metric_delete(domain_id: int, metric_id: int): # ── Free variable CRUD (HTMX partials) ─────────────────────── +def _render(domain_id: int, partial: str): + domain = get_repo().get_domain_by_id(domain_id) + return render_template(f"domains/{partial}", domain=domain) + + +def _fv_from_form() -> FreeVariable: + return FreeVariable( + name=request.form["name"].strip(), + floor_formula=request.form.get("floor_formula", "").strip(), + ceiling_formula=request.form.get("ceiling_formula", "").strip(), + sort_order=request.form.get("sort_order", 0, type=int), + ) + + +def _mf_from_form() -> MetricFormula: + return MetricFormula( + metric_name=request.form["metric_name"].strip(), + formula=request.form.get("formula", "").strip(), + ) + + @bp.route("//free-vars/add", methods=["POST"]) def free_var_add(domain_id: int): - repo = get_repo() - name = request.form["name"].strip() - floor_formula = request.form.get("floor_formula", "").strip() - ceiling_formula = request.form.get("ceiling_formula", "").strip() - try: - sort_order = int(request.form.get("sort_order", "0")) - except ValueError: - sort_order = 0 - if not name or not floor_formula or not ceiling_formula: + fv = _fv_from_form() + if not fv.name or not fv.floor_formula or not fv.ceiling_formula: flash("Name, floor formula, and ceiling formula are required.", "error") else: - fv = FreeVariable( - name=name, floor_formula=floor_formula, ceiling_formula=ceiling_formula, - sort_order=sort_order, - ) - repo.add_free_variable(domain_id, fv) - flash(f"Free variable '{name}' added.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_free_vars_table.html", domain=domain) + get_repo().add_free_variable(domain_id, fv) + flash(f"Free variable '{fv.name}' added.", "success") + return _render(domain_id, "_free_vars_table.html") @bp.route("//free-vars//edit", methods=["POST"]) def free_var_edit(domain_id: int, fv_id: int): - repo = get_repo() - try: - sort_order = int(request.form.get("sort_order", "0")) - except ValueError: - sort_order = 0 - fv = FreeVariable( - name=request.form["name"].strip(), - floor_formula=request.form.get("floor_formula", "").strip(), - ceiling_formula=request.form.get("ceiling_formula", "").strip(), - sort_order=sort_order, - ) - repo.update_free_variable(fv_id, fv) + get_repo().update_free_variable(fv_id, _fv_from_form()) flash("Free variable updated.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_free_vars_table.html", domain=domain) + return _render(domain_id, "_free_vars_table.html") @bp.route("//free-vars//delete", methods=["POST"]) def free_var_delete(domain_id: int, fv_id: int): - repo = get_repo() - repo.delete_free_variable(fv_id) + get_repo().delete_free_variable(fv_id) flash("Free variable removed.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_free_vars_table.html", domain=domain) + return _render(domain_id, "_free_vars_table.html") # ── Metric formula CRUD (HTMX partials) ────────────────────── @@ -178,35 +173,24 @@ def free_var_delete(domain_id: int, fv_id: int): @bp.route("//formulas/add", methods=["POST"]) def formula_add(domain_id: int): - repo = get_repo() - metric_name = request.form["metric_name"].strip() - formula = request.form.get("formula", "").strip() - if not metric_name or not formula: + mf = _mf_from_form() + if not mf.metric_name or not mf.formula: flash("Metric name and formula are required.", "error") else: - repo.add_metric_formula(domain_id, MetricFormula(metric_name=metric_name, formula=formula)) - flash(f"Formula for '{metric_name}' added.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_formulas_table.html", domain=domain) + get_repo().add_metric_formula(domain_id, mf) + flash(f"Formula for '{mf.metric_name}' added.", "success") + return _render(domain_id, "_formulas_table.html") @bp.route("//formulas//edit", methods=["POST"]) def formula_edit(domain_id: int, formula_id: int): - repo = get_repo() - mf = MetricFormula( - metric_name=request.form["metric_name"].strip(), - formula=request.form.get("formula", "").strip(), - ) - repo.update_metric_formula(formula_id, mf) + get_repo().update_metric_formula(formula_id, _mf_from_form()) flash("Formula updated.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_formulas_table.html", domain=domain) + return _render(domain_id, "_formulas_table.html") @bp.route("//formulas//delete", methods=["POST"]) def formula_delete(domain_id: int, formula_id: int): - repo = get_repo() - repo.delete_metric_formula(formula_id) + get_repo().delete_metric_formula(formula_id) flash("Formula removed.", "success") - domain = repo.get_domain_by_id(domain_id) - return render_template("domains/_formulas_table.html", domain=domain) + return _render(domain_id, "_formulas_table.html")