diff --git a/backend/api/app.py b/backend/api/app.py index 6e97a5b..7ecb313 100644 --- a/backend/api/app.py +++ b/backend/api/app.py @@ -45,6 +45,9 @@ def _warm_quick_match(): else: executor = ThreadPoolExecutor(max_workers=1) lock = threading.Lock() +from backend.blocks.opex import brainstorm as _opex_brainstorm # noqa: E402 + +_opex_brainstorm.STAGE_LOCK = lock # background AI results are written only between stages class Edit(BaseModel): @@ -406,9 +409,20 @@ def get(key: str, historical: bool = False, currency: str | None = None): if historical: return project_sizing_traces(project_assessment_identity(saved)) - return project_sizing_traces( + out = project_sizing_traces( project_assessment_identity(currency_view(view(saved), currency), saved) ) + out["opex_brainstorm"] = _opex_brainstorm.status(key, saved) + return out + + +@app.post("/api/assessments/{key}/opex-brainstorm", status_code=202) +def start_opex_brainstorm(key: str): + """Start (or restart after a change) the background AI OPEX brainstorm.""" + if not _opex_brainstorm.ai_available(): + raise HTTPException(409, "AI is not enabled on this server; reference defaults apply") + started = _opex_brainstorm.kick(store, key) + return {"started": started, "opex_brainstorm": _opex_brainstorm.status(key, store.get(key))} @app.patch("/api/assessments/{key}") diff --git a/backend/blocks/opex/brainstorm.py b/backend/blocks/opex/brainstorm.py new file mode 100644 index 0000000..893b00d --- /dev/null +++ b/backend/blocks/opex/brainstorm.py @@ -0,0 +1,272 @@ +"""Background OPEX brainstorm: the AI proposes OPEX inputs while the user works. + +Starts as soon as the engineering data is approved (and again whenever the +approved data changes), off the stage lock, so the user never waits for it and +never faces an empty OPEX page. The AI proposes materials, utilities, labour +roles and headcounts, other expenses and Garrett factors; Python still does all +arithmetic when the OPEX stage runs. + +Ownership rules (same as the reference defaults): + +* a field that is empty is filled with the AI proposal (origin "ai"); +* a value owned by the reference defaults may be refined by the AI, and an AI + factor is kept only inside its printed reference range; +* anything the user entered, selected or overrode, and anything an earlier AI + proposal wrote, is never replaced; a locked baseline is never touched. + +The result is written only while no stage is running (the caller's stage lock +is held for that short write), so a background write can never invalidate a +running calculation. +""" + +import copy +import threading +from contextvars import copy_context +from datetime import datetime, timezone +from decimal import Decimal + +VERSION = "opex-brainstorm-1" +STATUS = "AI proposal — needs review" +FIELDS = ("materials", "energy", "labour", "additional_expenses", "garrett_factors") + +_live = {} # key -> {"status": "running", "started_at": ..., "fingerprint": ...} +_guard = threading.Lock() +# The API replaces this with its stage lock so results are written only between stages. +STAGE_LOCK = threading.Lock() + + +def _now(): + return datetime.now(timezone.utc).isoformat() + + +def _recent(stamp, seconds=20): + try: + return (datetime.now(timezone.utc) - datetime.fromisoformat(stamp)).total_seconds() < seconds + except (TypeError, ValueError): + return False + + +def _report(state): + return ((state.get("stage_outputs") or {}).get("engineering_data") or {}).get("report") \ + or state.get("scoped_report") or state.get("effective_report") or (state.get("parsed") or {}).get("report") or {} + + +def fingerprint(state): + from backend.blocks.execution import _digest + + return _digest({"version": VERSION, "report": _report(state), "description": state.get("description", "")}) + + +def ai_available(): + try: + from backend.orchestration.provider import EngineeringProvider + + EngineeringProvider() + return True + except Exception: + return False + + +def wanted(state): + """True when approved data has no brainstorm for its current fingerprint.""" + from backend.blocks.stage_workflow import approved + + if not approved(state) or "operating_economics" in (state.get("locked") or []): + return False + return (state.get("opex_brainstorm") or {}).get("fingerprint") != fingerprint(state) + + +def status(key, state): + """Saved brainstorm record, overlaid with a live 'running' status.""" + live = _live.get(key) + saved = dict(state.get("opex_brainstorm") or {}) + if live and live.get("fingerprint") != saved.get("fingerprint"): + if live.get("status") == "saved": + # Saved just after this state was read: report "running" briefly so + # the page reads the study once more and picks up the proposals. + return {**saved, **live, "status": "running"} if _recent(live.get("finished_at")) else saved or None + return {**saved, **live} + return saved or None + + +# --- merge ----------------------------------------------------------------- + +def _in_range(category, fraction): + from backend.opex.reference_library import get_ranges + + rows = get_ranges(category, "garrett") + if not rows: + return False + try: + value = Decimal(str(fraction)) + except Exception: + return False + return any(Decimal(str(r["low"])) <= value <= Decimal(str(r["high"])) for r in rows) + + +def _ai(item): + return dict(copy.deepcopy(item), origin="ai", status=STATUS) + + +def _replaceable(entry): + return not entry or (isinstance(entry, dict) and entry.get("origin") == "reference_default") + + +def _refresh_questions(config): + """Drop reference-default questions the AI has now answered.""" + record = config.get("reference_defaults") + if not isinstance(record, dict): + return + items = {i.get("id"): i for root in ("energy", "materials") for i in config.get(root) or [] if isinstance(i, dict)} + kept = [] + for q in record.get("questions") or []: + ident = q.get("id") + if ident == "operating_labor": + if not config.get("labour"): + kept.append(q) + elif ident in items: + item = items[ident] + if item.get("tariff_per_kwh" if "tariff_per_kwh" in item else "unit_price") is None: + kept.append(q) + elif ident == "ref-specific-energy": + if not config.get("energy"): + kept.append(q) + else: + kept.append(q) + record["questions"] = kept + + +def merge(config, proposed): + """Fill gaps and refine reference defaults with the AI proposal. Returns (config, added).""" + config = copy.deepcopy(config or {}) + owners = config.setdefault("value_owners", {}) + added = [] + for field in FIELDS: + value = proposed.get(field) + if not value: + continue + current = config.get(field) + if field == "garrett_factors" and isinstance(value, dict): + factors = copy.deepcopy(current) if isinstance(current, dict) else {} + for category, choice in value.items(): + if not isinstance(choice, dict) or not _replaceable(factors.get(category)): + continue + documented = choice.get("override") and choice.get("override_reason") + if not documented and not _in_range(category, choice.get("fraction")): + continue # the AI may refine only inside the printed range + factors[category] = _ai(choice) + owners[f"garrett_factors.{category}"] = "ai" + added.append(f"garrett_factors.{category}") + config[field] = factors + elif isinstance(value, list): + items = current if isinstance(current, list) else [] + if items and not all(isinstance(i, dict) and i.get("origin") == "reference_default" for i in items): + continue # the user or an earlier AI proposal owns this list + if items: + # Keep reference-default items the AI did not cover (e.g. a feed). + covered = {i.get("stream_key") for i in value if isinstance(i, dict)} - {None} + keep = [i for i in items if i.get("stream_key") not in covered or not i.get("stream_key")] + if field == "energy": + keep = [i for i in keep if i.get("equipment_key") not in {v.get("equipment_key") for v in value}] + else: + keep = [] + new = [_ai(i) for i in value if isinstance(i, dict)] + config[field] = keep + new + for item in new: + owners[f"{field}.{item.get('id')}"] = "ai" + added.append(f"{field}.{item.get('id')}") + for field in ("price_basis", "operating", "assumption_date", "methodology"): + if not config.get(field) and proposed.get(field): + config[field] = copy.deepcopy(proposed[field]) + _refresh_questions(config) + return config, added + + +# --- background job ---------------------------------------------------------- + +def _propose(state, store, provider): + from backend.blocks.models import Context + from backend.blocks.shared import proposal + + engineering = (state.get("stage_outputs") or {}).get("engineering_data") or {} + ctx = Context(copy.deepcopy(state), _report(state), {"engineering_data": engineering}, store, None, provider, True) + sections = ("revenue", "opex") + values, meta = proposal(ctx, sections, basis_only=True, allow_missing_opex=True) + return values.get("operating_economics") or {}, meta + + +def save(store, key, record, stage_lock=None): + """Write the result while no stage runs; merge into the OPEX inputs.""" + with stage_lock or STAGE_LOCK: + for attempt in range(3): + state = store.get(key) + if record.get("fingerprint") != fingerprint(state): + return state # the approved data changed meanwhile; a new run follows + added = [] + if record.get("status") == "ready" and "operating_economics" not in (state.get("locked") or []): + plan = state.setdefault("plan", {}) + plan["operating_economics"], added = merge(plan.get("operating_economics"), record.get("proposal") or {}) + state["opex_brainstorm"] = {**record, "added": added} + try: + return store.put(state, state["revision"]) + except ValueError: + if attempt == 2: + raise # an edit outside the stage lock won the race three times + + +def run(store, key, stage_lock=None, provider=None): + state = store.get(key) + record = {"version": VERSION, "fingerprint": fingerprint(state), "started_at": _now()} + try: + from backend.orchestration.provider import EngineeringProvider + + proposed, meta = _propose(state, store, provider or EngineeringProvider()) + keep = {k: proposed[k] for k in (*FIELDS, "price_basis", "operating", "scope_notes") if k in proposed} + record.update(status="ready", proposal=keep, model=(meta or {}).get("model"), finished_at=_now()) + except Exception as exc: # recorded for the page; reference defaults still apply + record.update(status="failed", error=str(exc)[:300], finished_at=_now()) + # The live entry is never simply dropped: a reader that loaded the study just + # before the save must still see "running" (and poll again), not nothing. + outcome = {"status": "saved"} + try: + state = save(store, key, record, stage_lock) + if (state.get("opex_brainstorm") or {}).get("fingerprint") != record["fingerprint"]: + outcome = {"status": "superseded"} # the approved data changed meanwhile + return state + except Exception as exc: + outcome = {"status": "failed", "error": "Could not save AI proposals: " + str(exc)[:200]} + raise + finally: + with _guard: + if (_live.get(key) or {}).get("fingerprint") == record["fingerprint"]: + _live[key] = {**_live[key], **outcome, "finished_at": _now()} + + +def kick(store, key, stage_lock=None, provider=None, *, executor=None): + """Start a brainstorm if the approved data has none; never blocks the caller.""" + try: + state = store.get(key) + except Exception: + return False + if provider is None and not ai_available(): + return False + if not wanted(state): + return False + stamp = fingerprint(state) + with _guard: + if (_live.get(key) or {}).get("status") == "running": + return False # one brainstorm per study at a time + _live[key] = {"status": "running", "fingerprint": stamp, "started_at": _now(), "version": VERSION} + context = copy_context() + + def work(): + try: + run(store, key, stage_lock, provider) + except Exception: + pass # recorded in the live status for the page + + if executor is not None: + executor.submit(context.run, work) + else: + threading.Thread(target=context.run, args=(work,), name=f"opex-brainstorm-{key[:8]}", daemon=True).start() + return True diff --git a/backend/blocks/stage_workflow.py b/backend/blocks/stage_workflow.py index cc069d9..c9f3cde 100644 --- a/backend/blocks/stage_workflow.py +++ b/backend/blocks/stage_workflow.py @@ -51,7 +51,19 @@ def approve(store, key, revision): "fingerprint": _digest(state["stage_outputs"]["engineering_data"]), "approved_at": datetime.now(timezone.utc).isoformat(), } - return store.put(state, revision) + state = store.put(state, revision) + _brainstorm(store, key) + return state + + +def _brainstorm(store, key): + """Start the background OPEX brainstorm for newly approved data (AI only).""" + try: + from backend.blocks.opex.brainstorm import kick + + kick(store, key) + except Exception: + pass # the reference defaults still cover OPEX without the AI def queue(store, key, *, economic_only=False): @@ -62,6 +74,7 @@ def queue(store, key, *, economic_only=False): raise ValueError( "Review and approve Engineering Data before running downstream stages" ) + _brainstorm(store, key) order = ECONOMIC_ORDER if economic_only and fresh(state, "equipment") else ORDER store.version( key, diff --git a/backend/tests/test_opex_brainstorm.py b/backend/tests/test_opex_brainstorm.py new file mode 100644 index 0000000..0e9e754 --- /dev/null +++ b/backend/tests/test_opex_brainstorm.py @@ -0,0 +1,173 @@ +"""Background OPEX brainstorm: starts on approval, fills gaps, never overwrites.""" + +import threading +from io import BytesIO + +import openpyxl + +from backend.blocks.execution import run_stage +from backend.blocks.opex import brainstorm +from backend.blocks.stage_workflow import approve +from backend.opex.reference_defaults import propose +from backend.orchestration.store import Store + +LABOUR = [{"id": "electricians", "role": "Electricians", "category": "operating_labor", "behavior": "fixed", + "headcount_fte": 6, "annual_base_salary": 70000, "allocation_fraction": 1, + "rationale": "AI: two per shift for electrolyser stacks", "uncertainty": "AI estimate"}] + + +def _workbook(): + book = openpyxl.Workbook() + sheet = book.active + sheet.title = "Balance" + sheet.append(["Stream ID", "Description", "Mass flow (kg/h)", "Temperature (C)", "Pressure (bar)"]) + sheet.append(["S-1", "Feed water to Storage Tank T-1", 1000, 25, 1]) + sheet.append(["S-2", "Water from Storage Tank T-1 to Pump P-1", 1000, 25, 1]) + sheet.append(["S-3", "Water leaving Pump P-1", 1000, 25, 4]) + data = BytesIO() + book.save(data) + return data.getvalue() + + +def _extracted(tmp_path): + from fastapi.testclient import TestClient + + import backend.api.app as api + + store = Store(tmp_path / "a.sqlite") + original, api.store = api.store, store + try: + key = TestClient(api.app).post("/api/assessments", files={"file": ("b.xlsx", _workbook())}).json()["id"] + finally: + api.store = original + run_stage(store, key, "engineering_data", use_ai=False) + return store, key + + +class Now: + """Runs submitted work at once so the test can inspect the result.""" + + def submit(self, fn, *args): + fn(*args) + + +def test_merge_fills_labour_and_refines_reference_defaults_only(): + config, _ = propose({}, {"entities": [], "connections": []}) + config["garrett_factors"]["supervision"] = {"fraction": 0.12, "rationale": "User-selected factor", "origin": "user"} + ai = { + "labour": LABOUR, + "garrett_factors": { + "maintenance": {"fraction": 0.04, "rationale": "AI: clean water service"}, # inside 2–10 % + "taxes_insurance": {"fraction": 0.5, "rationale": "AI: out of range"}, # outside its range + "supervision": {"fraction": 0.2, "rationale": "AI tries to replace the user"}, + }, + } + merged, added = brainstorm.merge(config, ai) + assert merged["labour"][0]["headcount_fte"] == 6 and merged["labour"][0]["origin"] == "ai" + assert merged["garrett_factors"]["maintenance"]["fraction"] == 0.04 + assert merged["garrett_factors"]["maintenance"]["origin"] == "ai" + assert merged["garrett_factors"]["taxes_insurance"]["origin"] == "reference_default" # AI value rejected + assert merged["garrett_factors"]["supervision"] == config["garrett_factors"]["supervision"] + assert "labour.electricians" in added and "garrett_factors.supervision" not in added + assert merged["value_owners"]["labour.electricians"] == "ai" + # The labour question is answered; it no longer appears. + assert all(q["id"] != "operating_labor" for q in merged["reference_defaults"]["questions"]) + + +def test_merge_never_replaces_user_or_earlier_ai_lists(): + user = {"labour": [{"id": "ops", "role": "Operators", "headcount_fte": 3, "origin": "user"}]} + merged, added = brainstorm.merge(user, {"labour": LABOUR}) + assert merged["labour"] == user["labour"] and added == [] + earlier = {"labour": [dict(LABOUR[0], origin="ai")]} + merged, added = brainstorm.merge(earlier, {"labour": [dict(LABOUR[0], headcount_fte=9)]}) + assert merged["labour"][0]["headcount_fte"] == 6 and added == [] + + +def test_brainstorm_starts_on_approval_and_saves_into_the_gaps(tmp_path, monkeypatch): + store, key = _extracted(tmp_path) + calls = [] + + def fake(state, store_, provider): + calls.append(state["id"]) + return {"labour": LABOUR}, {"model": "test"} + + monkeypatch.setattr(brainstorm, "_propose", fake) + monkeypatch.setattr(brainstorm, "ai_available", lambda: True) + started = threading.Event() + real_kick = brainstorm.kick + monkeypatch.setattr(brainstorm, "kick", lambda s, k, *a, **kw: (started.set(), real_kick(s, k, provider=object(), executor=Now()))[1]) + state = approve(store, key, store.get(key)["revision"]) + assert started.is_set() and calls == [key] + state = store.get(key) + record = state["opex_brainstorm"] + assert record["status"] == "ready" and record["added"] == ["labour.electricians"] + assert state["plan"]["operating_economics"]["labour"][0]["role"] == "Electricians" + # Same approved data: no second AI call. + assert brainstorm.kick(store, key, provider=object(), executor=Now()) is False + assert calls == [key] + + +def test_ai_failure_is_recorded_and_changes_nothing(tmp_path, monkeypatch): + store, key = _extracted(tmp_path) + approve(store, key, store.get(key)["revision"]) + before = store.get(key)["plan"].get("operating_economics") + + def broken(*_): + raise RuntimeError("timeout") + + monkeypatch.setattr(brainstorm, "_propose", broken) + assert brainstorm.kick(store, key, provider=object(), executor=Now()) is True + state = store.get(key) + assert state["opex_brainstorm"]["status"] == "failed" and "timeout" in state["opex_brainstorm"]["error"] + assert state["plan"].get("operating_economics") == before + + +def test_no_ai_means_no_background_job(tmp_path, monkeypatch): + store, key = _extracted(tmp_path) + monkeypatch.setattr(brainstorm, "ai_available", lambda: False) + approve(store, key, store.get(key)["revision"]) + assert "opex_brainstorm" not in store.get(key) + assert brainstorm.status(key, store.get(key)) is None + + +def test_locked_operating_economics_is_never_touched(tmp_path, monkeypatch): + store, key = _extracted(tmp_path) + approve(store, key, store.get(key)["revision"]) + state = store.get(key) + state["locked"] = ["operating_economics"] + store.put(state, state["revision"]) + monkeypatch.setattr(brainstorm, "_propose", lambda *a: ({"labour": LABOUR}, {})) + assert brainstorm.kick(store, key, provider=object(), executor=Now()) is False + assert "labour" not in (store.get(key)["plan"].get("operating_economics") or {}) + + +def test_api_reports_live_status_while_running(tmp_path, monkeypatch): + store, key = _extracted(tmp_path) + approve(store, key, store.get(key)["revision"]) + gate = threading.Event() + + def slow(*_): + gate.wait(5) + return {"labour": LABOUR}, {} + + monkeypatch.setattr(brainstorm, "_propose", slow) + assert brainstorm.kick(store, key, provider=object()) is True + assert brainstorm.status(key, store.get(key))["status"] == "running" + gate.set() + for _ in range(100): + if (store.get(key).get("opex_brainstorm") or {}).get("status") == "ready": + break + threading.Event().wait(0.05) + assert store.get(key)["opex_brainstorm"]["status"] == "ready" + assert brainstorm.status(key, store.get(key))["status"] == "ready" + + +def test_a_read_taken_just_before_the_save_still_says_running(tmp_path, monkeypatch): + """A fast (cached) AI reply must not leave the page with nothing to poll for.""" + store, key = _extracted(tmp_path) + approve(store, key, store.get(key)["revision"]) + stale = store.get(key) # read before the brainstorm saves + monkeypatch.setattr(brainstorm, "_propose", lambda *a: ({"labour": LABOUR}, {})) + assert brainstorm.kick(store, key, provider=object(), executor=Now()) is True + assert brainstorm.status(key, stale)["status"] == "running" + assert brainstorm.status(key, store.get(key))["status"] == "ready" diff --git a/frontend/src/blocks/guided/flow.tsx b/frontend/src/blocks/guided/flow.tsx index b3bbd22..d3dcc30 100644 --- a/frontend/src/blocks/guided/flow.tsx +++ b/frontend/src/blocks/guided/flow.tsx @@ -12,6 +12,7 @@ import { obj, stageIndex, stageStatus, + text, type Row, type StageId, } from '@/lib/guided-flow'; @@ -35,9 +36,16 @@ export type Draft = { function useDraft(hook: AssessmentHook, section: string, fallback: T): Draft { const saved = (hook.state?.plan?.[section] ?? fallback) as T; const [value, setValue] = useState(saved); + const base = useRef(saved); + const study = useRef(hook.state?.id); useEffect(() => { - setValue(saved); - // Reset only when a new saved revision arrives. + // Take a new saved revision (e.g. background AI proposals) unless the user + // has unsaved edits on the same study; their edits are never discarded. + const sameStudy = study.current === hook.state?.id; + const previous = stableJson(base.current); // read now: the updater below runs later + study.current = hook.state?.id; + base.current = saved; + setValue((current) => (sameStudy && stableJson(current) !== previous ? current : saved)); // eslint-disable-next-line react-hooks/exhaustive-deps }, [hook.state?.id, hook.state?.revision]); const dirty = stableJson(value) !== stableJson(saved); @@ -132,6 +140,16 @@ export function GuidedFlow() { const state = hook.state, receipts = obj(state?.stage_runs), stages = obj(obj(state?.results).stages); + // Studies approved before background research existed: start it once on open. + const asked = useRef(''); + useEffect(() => { + const id = text(state?.id); + if (!id || !hook.aiEnabled || state?.engineering_data_approved !== true || obj(state).opex_brainstorm || asked.current === id) return; + asked.current = id; + void api(`assessments/${id}/opex-brainstorm`, post({})) + .then(() => hook.reload()) + .catch(() => {}); + }, [state, hook]); const props: StageProps = { hook, equipment, capex, operating, advance, go, aiSizing, setAiSizing }; const current = guidedStages[stageIndex(stage)]; return ( diff --git a/frontend/src/blocks/guided/guided.css b/frontend/src/blocks/guided/guided.css index 395d597..f6c9600 100644 --- a/frontend/src/blocks/guided/guided.css +++ b/frontend/src/blocks/guided/guided.css @@ -398,3 +398,14 @@ polyline.gf-tone-c { stroke: var(--gf-tone-c); } .gf-rev-effects { margin: 0 0 12px; font-size: 13px; } .gf-review { border-color: var(--gf-accent); } .gf-review-row .gf-line-actions { align-items: flex-end; flex-wrap: wrap; gap: 8px; } + +/* Background AI research notice on the OPEX page */ +.gf-brainstorm { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; } +.gf-brainstorm-failed { border-color: var(--gf-warn, #b45309); } +.gf-spinner { + width: 0.9rem; height: 0.9rem; border-radius: 50%; + border: 2px solid currentColor; border-right-color: transparent; + animation: gf-spin 0.8s linear infinite; flex: none; +} +@keyframes gf-spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .gf-spinner { animation: none; } } diff --git a/frontend/src/blocks/guided/opex-playground.tsx b/frontend/src/blocks/guided/opex-playground.tsx index a5afca3..4e654f4 100644 --- a/frontend/src/blocks/guided/opex-playground.tsx +++ b/frontend/src/blocks/guided/opex-playground.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useEffect, useState } from 'react'; -import { strings, compact, list, money, num, obj, opexHeadline, opexProgress, opexProposals, percent, text, words, type OpexProposal, type Row } from '@/lib/guided-flow'; +import { useEffect, useRef, useState } from 'react'; +import { brainstormNotice, stageStatus, strings, compact, list, money, num, obj, opexHeadline, opexProgress, opexProposals, percent, text, words, type OpexProposal, type Row } from '@/lib/guided-flow'; import { api, post } from './use-assessment'; import { Issues, OriginChip, Panel, RunBar, StageHeading, type StageProps } from './flow'; @@ -10,6 +10,14 @@ const groups = [ ['labour', 'Labour', ['headcount_fte', 'annual_base_salary', 'allocation_fraction']], ['additional_expenses', 'Additional expenses', ['amount', 'annual_amount', 'unit_price', 'quantity']], ] as const; +const EDIT_LABELS: Record = { + fraction: 'Edit (fraction)', + tariff_per_kwh: 'Tariff per kWh', + unit_price: 'Price per unit', + headcount_fte: 'Headcount (FTE)', + annual_amount: 'Annual amount', + amount: 'Amount', +}; const hidden = new Set(['id', 'stream_key', 'equipment_key', 'source_key', 'component', 'property', 'price_basis']); /** Value origin for an OPEX input, read from its own recorded source/status fields. */ @@ -73,15 +81,27 @@ export function OpexPlayground(props: StageProps) { } const items = list(config[p.root]); if (action === 'exclude') return set({ [p.root]: items.filter((i) => text(i.id) !== p.id) }); - const priceKey = p.root === 'energy' ? 'tariff_per_kwh' : 'unit_price'; set({ [p.root]: items.map((i) => text(i.id) !== p.id ? i - : { ...i, ...(action === 'edit' ? { [priceKey]: value } : {}), origin: 'user', status: action === 'edit' ? 'edited by user' : 'accepted by user' }, + : { ...i, ...(action === 'edit' ? { [p.editKey]: value } : {}), origin: 'user', status: action === 'edit' ? 'edited by user' : 'accepted by user' }, ), }); }; + const notice = brainstormNotice(obj(state).opex_brainstorm, hook.aiEnabled); + // Calculate on arrival: when CAPEX is current and OPEX is not (never run, or + // new background AI proposals made it stale), Python recalculates once. + const receipts = obj(state?.stage_runs); + const capexReady = stageStatus(receipts.capex, obj(obj(state?.results).stages).capex).tone === 'ready'; + const opexTone = stageStatus(receipts.opex, stage).tone; + const autoRan = useRef(''); + useEffect(() => { + const stamp = `${text(state?.id)}:${text(state?.revision)}`; + if (!state || state.running || hook.busy || operating.dirty || !capexReady || !['stale', 'idle'].includes(opexTone) || autoRan.current === stamp) return; + autoRan.current = stamp; + void hook.action(() => hook.runStage('opex')); + }, [state, hook, operating.dirty, capexReady, opexTone]); const questions = pending.filter((q) => !/categories priced/.test(q)); const shift = (id: string, amount: unknown) => (before && before[id] !== undefined && before[id] !== money(amount, '—') ? ` · was ${before[id]}` : ''); return ( @@ -133,17 +153,35 @@ export function OpexPlayground(props: StageProps) { {!stage.result &&

OPEX has not been calculated yet.

} + {notice && ( +

+ {notice.tone === 'running' &&

+ )} {proposals.length > 0 && (

Review {proposals.length} proposed assumption{proposals.length === 1 ? '' : 's'}

-

Proposed by Python from the reference library and your study data, without AI. Accept, edit or exclude each one.

+

Proposed by Python from the reference library and your study data, and by the AI researching in the background. Accept, edit or exclude each one.

    {proposals.map((p) => (
  • {p.label} - + {p.source} · {p.detail} @@ -157,7 +195,7 @@ export function OpexPlayground(props: StageProps) { Accept