diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ad80331 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +# Keep the backend build context to what the image needs. +.git +.venv +venv +**/__pycache__ +**/*.pyc +.pytest_cache +.mypy_cache +.ruff_cache +.env +.env.* +!.env.example +Extracted +frontend +docs +eval +tools +**/tests +conftest.py +*.log diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..07617e0 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{ts,tsx,js,jsx,json,yml,yaml,css,html}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab diff --git a/.env.example b/.env.example index 59690e5..219b4e0 100644 --- a/.env.example +++ b/.env.example @@ -10,27 +10,15 @@ DATABASE_URL=postgresql+asyncpg://keystone:keystone@localhost:5433/keystone # Sync variant for scripts / migrations that prefer psycopg2. DATABASE_URL_SYNC=postgresql://keystone:keystone@localhost:5433/keystone -# --- Google DeepMind (Gemini) --- -GEMINI_API_KEY=replace-me +# --- LLM --- +# Everything runs without a key: extraction falls back to rules and signal +# drafts to templates. LLM_PROVIDER picks the backend: gemini (default) or pioneer. +LLM_PROVIDER=gemini +GEMINI_API_KEY= GEMINI_FLASH_MODEL=gemini-2.5-flash GEMINI_PRO_MODEL=gemini-2.5-pro -GEMINI_EMBED_MODEL=text-embedding-004 - -# --- Tavily --- -TAVILY_API_KEY=replace-me - -# --- Entire (approval layer) --- -ENTIRE_API_KEY=replace-me -ENTIRE_BASE_URL=https://api.entire.example - -# --- Pioneer / Fastino (learning layer) --- -PIONEER_API_KEY=replace-me - -# --- Aikido (security scan badge) --- -AIKIDO_API_KEY=replace-me - -# --- Gradium (optional stretch TTS) --- -GRADIUM_API_KEY=replace-me +PIONEER_API_KEY= +PIONEER_MODEL=claude-sonnet-4-6 # --- IMAP (Phase 1 email ingestion) --- IMAP_HOST=imap.gmail.com @@ -42,5 +30,17 @@ IMAP_MAILBOX=INBOX # --- Slack webhook (Phase 2) --- SLACK_SIGNING_SECRET=replace-me -# --- Mock ERP (Phase 2) --- -MOCK_ERP_URL=http://localhost:8001 +# --- Featured property --- +# The property the UI opens first: a property UUID or any of its aliases. +# FEATURED_PROPERTY=EH-029 + +# --- Browser access --- +# Comma-separated origins allowed to call the API from a browser. The default +# (when unset) covers local frontends on ports 8080-8082, 5173, 4173 and 3000. +# KEYSTONE_CORS_ORIGINS=http://localhost:8080 + +# --- ERP payments feed --- +# Leave empty to disable the ERP poller. To try it locally run +# `uvicorn tools.mock_erp.main:app --port 8001` and set this to +# http://localhost:8001. +MOCK_ERP_URL= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7b31068 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,85 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + backend: + name: Backend (lint, types, tests) + runs-on: ubuntu-latest + services: + # The same image docker-compose.yml uses. The test fixtures apply the + # schema and migrations to the empty database themselves. + postgres: + image: postgres:16 + env: + POSTGRES_DB: keystone + POSTGRES_USER: keystone + POSTGRES_PASSWORD: keystone + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U keystone -d keystone" + --health-interval 3s + --health-timeout 3s + --health-retries 20 + env: + DATABASE_URL: postgresql+asyncpg://keystone:keystone@localhost:5432/keystone + DATABASE_URL_SYNC: postgresql://keystone:keystone@localhost:5432/keystone + # No LLM keys: tests that need one, or the private dataset, skip with a + # reason (shown by -rs). + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - name: Install + run: pip install -e ".[dev]" + - name: Ruff + run: | + ruff check . + ruff format --check . + - name: Sensitive data + run: python scripts/check_sensitive_data.py + - name: Mypy + run: mypy + - name: Pytest + run: pytest -rs + + frontend: + name: Frontend (lint, types, tests, build) + runs-on: ubuntu-latest + defaults: + run: + working-directory: frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + # Matches the build stage in frontend/Dockerfile. + node-version: "20" + cache: npm + cache-dependency-path: frontend/package-lock.json + - name: Install + run: npm ci + - name: Prettier + run: npm run format:check + - name: ESLint + run: npm run lint + - name: Typecheck + run: npm run typecheck + - name: Vitest + run: npm test + - name: Build + run: npm run build diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..a8249d4 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,27 @@ +# Install once with `pre-commit install`; run on everything with +# `pre-commit run --all-files`. CI runs the same checks (see +# .github/workflows/ci.yml), so a commit that passes here passes there. +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + # Keep in step with the ruff version installed by `pip install -e ".[dev]"`. + rev: v0.17.1 + hooks: + - id: ruff-check + - id: ruff-format + + - repo: local + hooks: + - id: prettier + name: prettier (frontend) + # Uses the prettier pinned in frontend/package.json; run `npm ci` in + # frontend/ first. + entry: npm --prefix frontend exec --no -- prettier --write --ignore-unknown --ignore-path frontend/.prettierignore + language: system + files: ^frontend/ + pass_filenames: true + + - id: sensitive-data + name: no blocked addresses, IBANs or Cloud Run URLs + entry: python scripts/check_sensitive_data.py + language: python + types: [text] diff --git a/DECISIONS.md b/DECISIONS.md deleted file mode 100644 index b57bf32..0000000 --- a/DECISIONS.md +++ /dev/null @@ -1,333 +0,0 @@ -# DECISIONS - -Running log of non-obvious judgment calls. Format per KEYSTONE.md Part XIII. - -## 2026-04-26 — Phase 12: materialize property/building/liegenschaft markdown into tables (instead of render-on-GET) -Context: KEYSTONE has rendered the canonical markdown live on every ``GET /properties/{id}/markdown`` since Phase 1. That kept the file "always fresh," but blocked two things the PM wanted: (1) a portfolio-wide *what-changed-since* feed for a live-update bell, which can't be built off render-on-GET because nothing remembers when each property's view last changed; and (2) propagation — a building-tier event needs to refresh every property file under that building, but render-on-GET fires only when *that* property is read, so a tenant who hasn't opened their unit's view sees stale facts. -Decision: Add three additive tables — ``property_files``, ``building_files``, ``liegenschaft_files`` — keyed on the scope id. Every fact write fans out to update the matching row(s) atomically with the write (see the propagation-cascade decision below). Reads of the existing ``/markdown`` endpoints check the table first and fall back to a live render on cache miss; the live render is now a fallback path, not the primary path. New top-level resource ``/property_files/{id}`` returns the full row including ``trigger_event_id`` and ``trigger_summary``; new ``/property_files/changes?since=&limit=N`` is the polling feed Phase 13 will wire to the bell. -Reason: The materialized layer enables both PM asks at the cost of three additive tables and one fan-out helper. Keeping the renderer untouched (the existing ``backend.pipeline.renderer.render_*`` functions are reused verbatim) means the LLM/non-LLM split stays clean — the renderer is deterministic, no LLM in the materialize step, no surprise spend. The "render on every read" cost we used to pay is now amortized: writes pay it once, reads serve from cache. -Revisit if: A renderer change starts producing materially different markdown that needs a re-materialize sweep. Bump ``GENERATION_VERSION`` in ``backend/pipeline/materializer.py`` and add a CLI flag (``materialize-all --re-render-stale-version``) that re-renders rows whose stored version is below the constant. Or if Cloud SQL row-write latency from the cascading propagation becomes a bottleneck — at that point, batch the upsert per scope tier instead of per row. - -## 2026-04-26 — Phase 12: three separate tables (property_files/building_files/liegenschaft_files), not one polymorphic ``files`` table -Context: A polymorphic ``files`` table with ``(scope_type TEXT, scope_id UUID, content_md, ...)`` is the obvious alternative — one schema, one set of indexes, one materialize function. Three tables means more SQL surface area. -Decision: Three tables. Each scope's PK is a typed FK to its parent (``properties.id`` / ``buildings.id`` / ``liegenschaften.id``) with ``ON DELETE CASCADE``; range scans like ``WHERE building_id = X`` for the propagation queries don't need a discriminator predicate. -Reason: Three reasons. (1) FK cascade-on-delete is per-table and per-typed-column — a polymorphic ``scope_id`` would need application-level cleanup on every delete, which is exactly the kind of subtle "we'll fix it later" landmine that breaks at the worst time. (2) The propagation queries are scope-specific — "every property under this building" reads cleaner against ``properties`` than against ``files WHERE scope_type='property'``. (3) Adding a fourth tier (e.g. portfolio_files for a future multi-customer roll-up) is one new table, not a new enum value with corresponding constraints across the codebase. -Revisit if: We add five+ tiers. At that point the duplication burden tips and the polymorphic table becomes worth the application-level deletion code. - -## 2026-04-26 — Phase 12: fact-write + materialize share one transaction (KEYSTONE invariant: files are never stale relative to facts) -Context: Two implementation choices for the propagation hook. (1) Sync — call ``propagate_after_fact_write`` inside the caller's session before commit; an exception in the renderer rolls back the whole write. (2) Async — enqueue a background job that re-materializes after the fact write has committed; cheaper write latency, but the cache can be momentarily stale. -Decision: Sync, in the caller's session. ``propagate_after_fact_write(session, ...)`` takes the existing ``AsyncSession`` and never opens its own; never commits; raises out on renderer failure. Caller commits or rolls back the whole transaction. -Reason: The PM's request was "the file reflects the facts always." Async propagation means a window — bounded but real — where ``GET /property_files/{id}`` returns content that disagrees with ``SELECT ... FROM facts``. That disagreement is the exact thing a markdown-as-source-of-truth product cannot have. The cost is paid in two places: (a) write latency now includes one renderer call per affected scope, (b) renderer bugs become fact-write bugs (the Phase 12 ``_fetch_facts_by_scope`` ``occurred_at`` bug was discovered exactly this way and surfaced as a clean rollback rather than a silent stale cache). Both costs are acceptable for the truthfulness guarantee. -Revisit if: A future renderer change makes per-scope render time exceed ~500 ms and the synchronous fan-out starts blocking ingest noticeably. At that point the right fix is to make the renderer faster (it's reading already-indexed tables — should always be fast), not to break the invariant. Only if that fails: introduce an async propagator with a strict "stale-tolerated, eventually-consistent" SLO and document that ``/property_files`` reads can lag by N seconds. - -## 2026-04-26 — Phase 12: 52-property liegenschaft propagation as the documented scaling boundary -Context: Buena's data is 1 WEG → 3 buildings → 52 properties. A single liegenschaft-tier event (Hausgeld payment, WEG invoice, modernization decision) propagates to *every* property under the WEG. That's 52 renderer calls in one transaction. -Decision: Accept the cost as the documented scaling boundary for Buena's volume. The renderer is deterministic; per-property render is ~5–10 ms reading already-indexed facts/events; total fan-out per WEG event is ~250–500 ms. Visible in VERIFY 3 logs (52 ``renderer.fetch`` calls per WEG fact write). -Reason: For Buena's actual volume — a few WEG-tier events per day, eclipsed by the hundred-plus per-property events — this is fine. Optimising prematurely (per-tier batched upsert, deferred render via job queue) would add code paths whose value can't be measured against the current volume. The cost is auditable in ``DECISIONS.md`` (here) and in the materializer's own ``log.info`` so anyone investigating a slow ingestion will see exactly where the time went. -Revisit if: A customer ships a Liegenschaft with 500+ properties (an entire residential block / Wohnungsgesellschaft), at which point the fan-out is 5+ seconds per WEG event. Fix path: batch the upsert across all properties under the WEG into a single ``INSERT ... ON CONFLICT`` with a ``UNNEST`` of ``(property_id, content_md, ...)`` rows; render concurrently with ``asyncio.gather``. This is a real optimisation worth doing, but only when there's a concrete customer on the bench needing it. - -## 2026-04-26 — Phase 12: frontend wiring deferred to Phase 13 -Context: The ``/property_files/changes`` feed is meant to power a frontend bell that polls "what changed since I last looked." Wiring that polling, plus replacing the "Extraction in progress" empty-state with a direct render of ``content_md`` from the materialized table, is a UI surface change. -Decision: Phase 12 ships the data layer only. Phase 13 will wire the frontend. -Reason: The user's plan explicitly fenced frontend wiring out of Phase 12 ("WHAT THIS DOES NOT INCLUDE: Frontend wiring (defer to Phase 13)"). Splitting the two phases gives Phase 12 a clean shape — schema + materialize + propagate + read endpoints, all backend, all verifiable via ``curl`` — and lets Phase 13 design the polling cadence + bell UX without Phase 12's deploy timing constraining it. -Revisit if: The user finds that a backend without a frontend wire-up of the feed is hard to reason about. The minimal Phase 13 surface is small: one ``useQuery`` against ``/property_files/changes`` polling at 30 s, one ``content_md`` rendering branch in ``PropertyDetail.tsx`` when ``/file`` returns empty sections — both straightforward additions to the existing UI patterns. - -## 2026-04-25 — Phase 10 Step 10.6: latent ``approval_log`` schema mismatch -Context: Verifying the existing ``POST /admin/rejected/{id}/override`` audit trail end-to-end (per the user's "you have this — verify it works" review note) failed at the first INSERT. Phase 9.2's override endpoint writes ``approval_log (actor, action, target_type, target_id, payload)`` — but Phase 5's original schema is ``(signal_id, user_id, decision, edits)``. The columns the Phase 9.2 INSERT references simply don't exist; the override path has been broken since 9.2 shipped, and no test exercised it before now because Phase 9.2's tests focused on the validator side, not the override side. -Decision: Migration 0008_approval_log_generic adds (actor, action, target_type, target_id, payload) as nullable columns alongside the original ones, plus drops NOT NULL on ``decision`` so signal-approvals (which still use it) and trust-layer actions can share the table cleanly. New endpoint (``POST /uncertainties/{id}/resolve``) and the existing override path now both write rows that round-trip correctly. Backward compatible — existing signal-approval INSERTs are untouched. -Reason: The shared-table approach beats either splitting tables (``trust_audit_log`` vs ``approval_log``) or rewriting the existing inserts to cram everything into ``edits``. One audit table for all human decisions matches the operator mental model — they're going to look in *one place* to find "who decided what and when." -Revisit if: We start needing per-decision-type indexes that don't fit the generic shape, or want decision-type FK constraints (e.g., ``target_id`` strictly typed as UUID per ``target_type``). At that point, switch to a discriminated union with ``CHECK`` constraints. - -## 2026-04-25 — Phase 10 Step 10.4: source links route through a redirect, not direct file URLs -Context: Source links in the rendered markdown (every ``[source: ]`` bullet) need to actually open the originating document. Naive choice: render ``/files/`` directly for PDFs and ``/events//raw`` for emails. Problem: the renderer doesn't know the source type per fact unless we widen ``FactRow`` to carry it everywhere, and even then, future source types (Slack pulls, ERP detail pages, web archives) would force renderer changes. -Decision: All fact-source links go to ``/events//source``, a redirect dispatcher that looks up the event and 307s to the right surface (``/files/`` for PDFs, ``/events//raw`` for emails, ``/events//detail`` for bank). The renderer never has to know which is which. -Reason: One stable link string in rendered markdown across source-type evolutions. The redirect indirection is also where path-traversal protection lives — if a future source captured a malicious ``original_path``, the ``/files`` route still refuses it. Cost: one extra HTTP hop per click. Benefit: the markdown stays valid forever even as source-type handling changes. -Revisit if: We start serving rendered markdown to a context where the redirect can't follow (e.g., a static export). At that point, render the resolved URL at write time and accept the renderer-knows-source coupling. - -## 2026-04-25 — Phase 10 Step 10.3: read-time briefing regen, no write-side hooks -Context: Plan called for caching the Gemini Pro briefing on ``properties.metadata.onboarding`` and regenerating on fact insertion or uncertainty resolution. Two implementation choices: hook into the worker's apply-time write path (regen runs synchronously after every fact write), or hash the latest mutation timestamps + regen lazily on the next read. -Decision: Hash-based read-time invalidation. Cache key = sha1(last_fact_at, last_uncertainty_at, last_rejection_at). Any mutation flips the hash; the next ``GET /admin/properties/{id}/onboarding`` regenerates; subsequent reads are free until the next mutation. -Reason: Write-path Gemini calls would push 24-second p50 onboarding latency onto every event ingestion — that's a ten-thousand-times worse trade than the alternative. Read-time regen pays the cost only when an operator actually opens the view, and only after something material changed. The cache invalidation is provably correct (any of the three mutation kinds bumps the hash). -Revisit if: We start sending push-style notifications when an onboarding briefing has gone stale (then we'd want to know *at write time* that an open view needs a refresh). At that point, add a ``LISTEN/NOTIFY`` channel on the cache key, not a synchronous regen. - -## 2026-04-25 — Phase 10 Step 10.3: briefing language matches property's source-event majority -Context: First live render against hero (WE 29 — German property) emitted a perfect 7-bullet briefing in *English* while the rest of the rendered markdown was German. The Gemini Pro prompt was English-only. -Decision: Two prompt templates (``ONBOARDING_PROMPT_DE`` and ``ONBOARDING_PROMPT_EN``); ``backend.services.onboarding.render_onboarding`` passes the property's detected language through. The German prompt uses ``Lücke:`` as the explicit gap-marker prefix (parallel to the English ``Gap:``). -Reason: A German property manager reading their own property's file in English breaks the demo's whole "this is your file" trust narrative. Cost: one extra prompt template to maintain. Benefit: native-language rendering for Buena's primary cohort, which is most of the demo's substance. -Revisit if: We add a third locale or someone reports a property whose source-event mix is bilingual. The detector falls back to English on ties — that's a deliberate "least surprise" choice but worth re-checking against real usage. - -## 2026-04-25 — Phase 10 IMAP: live transport remains untested offline -Context: User asked to verify live IMAP polling on real Buena-style emails before Phase 10 closes. The poller's ingestion path (parsing real German .eml, writing events idempotently on Message-ID, no-op safety when creds are missing) is fully tested with 4 tests against real ``Extracted/emails/`` files. The actual IMAP transport (``imapclient.IMAPClient`` connect/login/select/search/fetch loop in ``poll_once``) requires a live IMAP server. -Decision: Ship Phase 10 without an offline test of the transport. Document the gap. -Reason: ``imapclient`` is a mature library; the wrapper is ~10 lines of standard usage; the parsed payload it hands to ``_ingest`` *is* tested on real Buena .eml content. Spending the time to mock-IMAP-server everything would push other higher-impact work (operator action endpoints, document linking) without changing risk meaningfully. -Revisit if: We hit a real IMAP issue in production (charset edge case, OAuth instead of password, IDLE-mode push instead of polling). At that point, set up a containerised dovecot for integration tests rather than mocking imapclient internals. - -## 2026-04-25 — Phase 9 Step 9.1: defer ``POST /uncertainties/{id}/resolve`` to post-hackathon -Context: Step 9.1 ships uncertainty as first-class output — extractor emits ``uncertain[]``, validator's ``needs_review`` verdicts route here, sub-floor confidence (< 0.7) facts demote here, renderer surfaces a "Needs Review" / "Zu prüfen" subsection per section, and ``GET /admin/properties/{id}/uncertainties`` lists everything. The original plan also called for ``POST /uncertainties/{id}/resolve`` (promote to fact, dismiss with reason). -Decision: Ship the read-only path only. ``POST /resolve`` is **deferred** to post-hackathon. The validator's hard-reject path already has ``POST /admin/rejected/{id}/override`` from Step 9.2, so the override surface is demonstrable; the uncertainty surface is purely read-only for now. -Reason: Hackathon time discipline. The demo's value is in *seeing* the system render an honest "I noticed something I can't commit to" subsection — that's the trust-layer narrative. Judges won't click through to resolve uncertainties; they'll read the rendered markdown and move on. Building the resolution surface costs ~1 hour (write fact + audit log + state transitions + test) for zero demo lift. Phase 10 work has higher marginal return on the same hour. -Revisit if: Real users start consuming the uncertainty inbox in production, or the demo script grows a beat where a judge does click "resolve" on an uncertainty. The pattern from ``POST /rejected/{id}/override`` is directly transferable — the resolution endpoint is essentially the same shape. - -## 2026-04-25 — Phase 8 Step 6: stop, pivot to hero-property backfill, defer Steps 7-9 -Context: Step 6's full 6,546-email backfill silent-hung at minute 5:24 with `concurrency=4` after 251 events / 85 facts / 100 successful Gemini Pro calls / $0.4868 spent. All 4 worker tasks ended up blocked on simultaneous Pro calls that never returned (no 429, no exception, no log). DB state and cost ledger were both frozen at the moment of hang for >10 minutes before the silence-watchdog tripped and the kill ladder fired. Forensics in `eval/runs/2026-04-25-step6-partial.md`. -Decision: Do *not* restart at sequential. Take what we have — 251 events, 85 facts, three-tier routing working on real WEG topology, eval framework with measured 73 % category accuracy — as Phase 8 substance. Run a *targeted* hero-property backfill (`scripts/hero_backfill.py`) so the demo's onboarding view reads as rich. Skip Phase 8 Steps 7, 8, 9 entirely (Step 7+8 stayed staged on disk for post-hackathon, Step 9 is unstarted). Tag `phase-8-complete` and immediately start `phase-9/trust-layer` Step 9.2 (constraint validator). -Reason: Hackathon time discipline. Spending the next 6+ hours getting the rest of the 6,546 emails through (sequential rate is ~1 event / 12 s) displaces Phase 9 (trust layer) and Phase 10 (replay + onboarding) — both PM-prioritised. Volume isn't a demo requirement; the replay engine in Phase 10 reads directly from the `.eml` archive, not the DB. The hero property's *complete* coverage is what the demo actually needs. -Revisit if: Post-hackathon. The full backfill resumes cleanly from the existing $0.4868 / $20 ledger (or with `--reset-cost-ledger`); source-ref idempotency means already-processed events are skipped. Sequential re-run: ~6.5 h, ~$9.30 additional. Or address the silent-hang properly first — see the next DECISIONS entry. - -## 2026-04-25 — Phase 8 Step 6: 60-second timeout on `extract_facts` (silent-hang mitigation) -Context: The concurrency=4 hang above wasn't really *about* concurrency. A single Gemini Pro call can silent-hang too — the Google SDK's `generate_content` is a blocking call wrapped in `asyncio.to_thread`, and if the server-side response never arrives, that thread waits forever. Concurrency=4 just made the failure surface 4× faster. -Decision: Wrap the call site in `asyncio.wait_for(timeout=60.0)`. p99 latency observed in Step 6 was 37 s, so 60 s is comfortable headroom. On timeout the existing retry/exception path kicks in, and after `max_attempts=3` the rule fallback fires. Default is exposed as `GEMINI_EXTRACT_TIMEOUT_S` so future tuning is one-line. -Reason: Genuine product hygiene worth shipping regardless of phase. Without the timeout, *any* future production rollout — sequential, concurrent, scheduled, on-demand — has a "permanent freeze on a single bad call" failure mode. With it, the worst case is a 60 s pause on one event's attempt; the retry handles it; the operator sees one warning log and the pipeline keeps moving. -Revisit if: We see legitimate Gemini calls that need > 60 s (raise the ceiling per-call) or want to surface timeouts as `failed_events` rows for the admin inbox in Step 9 (currently the rule fallback runs and the event leaves the queue cleanly). - -## 2026-04-25 — Phase 8 Step 6: hero property = WE 29 (`509393da-6806-49ef-9e59-3da0213008cd`) -Context: Demo's onboarding view (Phase 10 Step 10.3) needs one property with rich extracted facts so the file-builds-itself beat reads as substantive. Among the 99 property-routed events from the partial Step 6 pass, top three candidates were GE 37 (9 events / 6 facts), WE 29 (8 events / 6 facts), and WE 50 (6 events / 7 facts). -Decision: **`KEYSTONE_DEMO_HERO_PROPERTY = 509393da-6806-49ef-9e59-3da0213008cd`** (`Immanuelkirchstraße 26 WE 29`). Most balanced cross-section of facts: maint=2 / lease=1 / fin=3, all sections populated. `scripts/hero_backfill.py` runs the targeted re-extraction filtered by the property's specific aliases (`EH-029`, `WE 29`, `4. OG mitte` — drops `HAUS-14` and the bare street prefix because they're building-wide, not unit-specific). -Reason: WE 29 has the cleanest narrative arc. GE 37 has higher event count but it's a `Gewerbe` (commercial unit) — most demo viewers will read "apartment" and connect more directly to a `WE` (Wohneinheit). WE 50 has highest fact density but only 6 events — less to visibly stream during the replay beat. WE 29 is the median story. -Revisit if: The hero backfill produces < 30 events (cut-off where the onboarding "60-second briefing" looks thin), in which case fall back to GE 37 with a one-line "kommerziell" framing in the narrative. Or if a richer property surfaces post-hackathon with the full backfill complete. - -## 2026-04-25 — Phase 8 Step 6: cost-ledger reset_label has no test-vs-prod separation (Phase 9+ hardening) -Context: While the live Buena backfill was running with label `step6_email_backfill`, I started `pytest connectors/tests/` to sanity-check Step 7+8 drafts. The cost-cap test calls `cost_ledger.reset_label('step6_email_backfill')` to set up its starting state — which would have **deleted the live ledger row** mid-run, causing the backfill's next `cost_ledger.charge` to raise `RuntimeError("cost_ledger has no row for label=…")` and crash with several thousand more emails to process. Caught and killed pytest before damage. Today's quick fix: tests monkeypatch the label to a per-test unique `step6_test_`, so concurrent runs are now isolated. -Decision: Quick fix landed today. Defer the structural fix — making `cost_ledger.reset_label()` refuse any label whose name doesn't start with a recognised test prefix (`test_*`, `_test_*`, etc.) at runtime — to Phase 9 hardening. Production labels (`step5_eval`, `step6_email_backfill`, `step7_incremental`, `pdf_doctype`) would be opt-in via `reset_label(..., allow_production=True)` with the friction-gated `y/N` prompt that already lives in the CLI. -Reason: Today's test isolation patch closes the immediate landmine. The structural guard is a real bug (any future test author can repeat the same near-miss) but isn't blocking Phase 8. Putting the guard in Phase 9 lets us land it next to the trust-layer / admin-overrides surface where the same "production data needs friction" theme is being designed. -Revisit if: Anyone — me, future contributors, or CI — touches `reset_label()` from a test file again. Or if Phase 9 ships before this guard does (move it forward). - -## 2026-04-25 — Phase 8 Step 6: backfill concurrency=4 with bounded cost-cap overshoot -Context: The Buena email archive is 6,546 .eml files. Sequential extraction at ~3 minutes per 50 emails meant ~6.5 hours for the full pass. Concurrent extraction is the obvious speedup, but `cost_ledger.charge` is a read-modify-write — naive parallelism could double-spend by reading the same `cumulative_usd` from two workers and both passing the cap check before either UPDATE lands. -Decision: Run 4 parallel extraction workers. Serialize `cost_ledger.charge` behind a single `asyncio.Lock` so the read-modify-write is atomic at the application level (Postgres `FOR UPDATE` already serializes at the DB level — the asyncio lock is belt-and-suspenders, and makes the contract obvious in the loader). Worst-case overshoot when the cap is breached mid-flight is bounded by `concurrency × max_call_cost`. With `concurrency=4` and `max_call_cost ≈ $0.005` (a Pro call on a long German email at ~3k prompt + 200 completion tokens), the bound is **$0.02**. The cap is $20.00, so the overshoot is < 0.1% — auditable. -Reason: 4× wall-clock improvement (≈1.5 h vs 6.5 h) for a $0.02 worst-case cost ceiling that's well within tolerance. Going higher (`concurrency=8`) would shave another ~30 min but doubles the overshoot bound and runs into Gemini per-minute rate-limit territory; we'll revisit if signal-discovery (Step 8) needs a faster-moving extraction pass. -Revisit if: Gemini publishes higher per-minute rate limits, OR the backfill needs to repeat under a tighter cost cap, OR a real concurrency bug surfaces (cost-ledger deadlock, double-charge in logs, race on the `failed_events` UPSERT that we missed). Per the launch directive, any concurrency-related surprise in the first 5 minutes triggers a kill-and-revert-to-sequential. - -## 2026-04-25 — Phase 8 Step 5: lease F1 = 0.62 driven by `lease.termination_notice` over-firing on owner-communication emails -Context: After Gemini Pro shipped on the German-first prompt, lease F1 was 0.62 — driven entirely by 5 spurious `lease.termination_notice` emissions on emails whose ground-truth category was `owner_communication` (sale intent, modernization consent, WEG governance). The model conflates "the relationship is changing" (owner side) with "the tenancy is ending" (lease side). -Decision: Ship as-is at 0.62, above the VERIFY 5 acceptance floor of 0.50. No prompt patch in Step 5; the residual is logged as a known limitation. -Reason: Step 5's quality bar is a floor, not a target — meeting it is the gate, exceeding it is gravy. Tightening the prompt today risks regressing other categories without a corresponding eval expansion to detect the regression. Better to leave the eval set as the witness and revisit when there's signal-discovery (Step 8) or production usage data showing this creates false signals. -Revisit if: Step 8 signal-discovery surfaces `lease.termination_notice` as a high-recall but low-precision rule, OR production usage shows owner-communication emails routinely triggering tenant-change downstream actions. Fix by adding to the German prompt: "Only emit `lease.termination_notice` when the *tenant* is signaling end of tenancy. Owner-side intent (sale, modernization, WEG governance) is `owner_communication`, not lease." - -## 2026-04-25 — Phase 8 Step 5: compliance ↔ owner_communication category bleed on WEG-related emails -Context: 2 of 30 ground-truth `compliance` emails (Brandschutznachweis, Mietpreisbremse-adjacent topics) classified as `owner_communication` because the prompt's section-mapping pulls WEG-touching topics toward owner_communication. Within the F1 = 1.00 band on `compliance` (the other 2 hit), but the category-accuracy miss is real. -Decision: Within the 70% category-accuracy band; not patched in Step 5. Logged as a Step 8 lookback item. -Reason: Same reasoning as the lease residual — the band is met, the failure mode is identifiable, and prompt-tuning without an expanded eval set risks unmeasured collateral. The category bleed is consistent (always pulls toward owner_communication, never the reverse), so it's tractable when we get to it. -Revisit if: Step 8 signal-discovery includes a compliance-class signal (Brandschutz, Bauamt deadlines, Mietpreisbremse review) AND owner-communication emails are bleeding into the trigger set. Fix in the German prompt by explicitly listing compliance triggers (Brandschutznachweis, Bauamt, Mietpreisbremse, Vermessungsprotokoll) above the WEG-governance triggers in the section-routing list. - -## 2026-04-25 — Phase 8 Step 5: value-string fidelity ~3 % (paraphrase, not source-quote) -Context: After the calibration metric was corrected to (section, field) match, the eval re-run showed 79 % observed accuracy in the 0.90–1.00 confidence bucket on key placement — but the per-section `value_match_rate` column is mostly 0.00 (max 0.40 on liegenschaft_financials). The model paraphrases the value: "Heizung defekt, kein Warmwasser seit gestern" becomes "Heating system malfunction reported; tenant lacks hot water since yesterday." Right slot, different words. -Decision: Accept for Phase 8. The key-placement accuracy is what the trust layer is built on; paraphrase is a Phase 9 concern when we surface facts in markdown to humans who'll want to see source-language verbatim quotes. -Reason: Phase 8 is product-quality on extraction; Phase 9 is the trust layer where source-fidelity becomes load-bearing (a fact rendered as paraphrase loses the auditability that the trust layer is selling). Forcing verbatim quotes today would either over-constrain the model (regressing recall) or require a post-hoc string-snap pass we don't have a primitive for yet. -Revisit if: Phase 9 trust-layer prompt-tuning: add a "value MUST be a verbatim substring of the source event when possible; only paraphrase when the source spans multiple sentences or contains markup that would corrupt the value field" clause. Validate by re-running the eval and watching `value_match_rate` rise (target ≥ 0.6 on the dense buckets). - -## 2026-04-25 — Phase 8.1 Step 3b: forward-looking PDF placeholder text ("awaiting extraction") -Context: The connectors emitted `[INVOICE: filename.pdf] (text not extracted)` for PDF events whose body wasn't parsed at backfill time (we deliberately skip pdfplumber on the 329 PDFs in Step 3 to keep the cost ledger free for Steps 4-6). The phrasing reads like an error to a human glancing at the WEG Context block. -Decision: The connectors now emit `Invoice {filename} — awaiting extraction` (or `Letter {filename} — …`) for the no-body case, and the renderer's `_context_body` reformats existing rows to the same wording when `metadata.head_chars == 0`. New ingest writes the new text directly; existing 194 invoice rows display via the renderer fix without a re-write. -Reason: Phase 9's trust-layer ethos says the system should be honest about its epistemic state. "Awaiting extraction" is forward-looking and accurate — we know there's content there, we haven't processed it yet. It's not a failure mode to apologise for. -Revisit if: We start extracting PDF text on backfill (Steps 4-6 may opt-in) — at that point the renderer will fall through to the snippet path automatically once `head_chars > 0`. - -## 2026-04-25 — Phase 8.1 Step 3b: 13 closed-lease MIE rows are *known acceptable* unrouted, not a routing bug -Context: After re-route, 13 events remain unrouted with the diagnostic `refs (none) kat=miete unresolved`. They are bank rows referencing `MIE-NNN` where the matching tenant has `mietende` set (lease ended). Step 2's loader correctly skipped the closed-lease tenant from `relationships(occupied_by)` because the active-only invariant — so the router can't resolve the `MIE-NNN` to a current property. -Decision: This is *expected* behaviour, not a routing miss. Logged here so a future operator reading the unrouted inbox doesn't waste cycles trying to fix it. If a property manager genuinely needs closed-lease historical routing, the right move is a Phase 9+ feature (e.g. an `historical_tenancies` table or an opt-in `include_closed=True` flag on the loader) — not loosening Step 2's invariant. -Reason: The active-only constraint protects the property markdown's "who lives here today" answer. Including closed-lease tenants in `occupied_by` would corrupt that for every per-property reader. Keeping 13 events unrouted is the cheapest, most honest representation. -Revisit if: A customer ships a meaningful number of historical-tenant events that need attribution to a unit (e.g. for late-payment reconstruction across tenancies) — at that point design a parallel `historical_occupied_by` edge that the router can consult after the active-only path misses. - -## 2026-04-25 — Phase 8.1 Step 3b: three-tier ownership hierarchy (Liegenschaft → Building → Property) -Context: After Step 3a shipped, the live verify revealed 100% of Buena invoices and 12.5% of bank rows landing unrouted. Investigation showed Buena's events span three ownership tiers (1 WEG → 3 Häuser → 52 units), but the schema only modelled per-property attribution. WEG-billed events have a *known* correct attribution; routing them to "unrouted" was hiding truth, not surfacing a gap. -Decision: Add `liegenschaften` table + `buildings.liegenschaft_id` FK + `events.{building_id, liegenschaft_id}` + `facts.{building_id, liegenschaft_id}` (additive migration `0002_liegenschaft_hierarchy`). Router gains precedence rules for HAUS-N alias → building and WEG keyword/kategorie/invoice → liegenschaft. Renderer ends property markdown with **Building Context** and **WEG Context** subsections; new `/buildings/{id}/markdown` and `/liegenschaften/{id}/markdown` endpoints. -Reason: Routing a WEG event to one Haus (Option 1: HAUS-12 as primary) is the same false-attribution mistake we rejected at the unit level. A junction table (Option 3) over-engineers a 1:N relationship and burdens every reader. Liegenschaft alongside building reflects German Hausverwaltung reality and is supported by `stammdaten.json::liegenschaft` directly. -Revisit if: Customer data shows a multi-Liegenschaft tenant — at that point `_default_liegenschaft` (which assumes a single WEG) needs a routing key like `metadata.liegenschaft_id` or a verwendungszweck-based heuristic. - -## 2026-04-25 — Phase 8.1 Step 3b: case-insensitive word-boundary WEG keyword matching -Context: Buena's `verwendungszweck` mixes capitalization freely — `Hausgeld`, `HAUSGELD`, `hausgeld` all appear in real rows. A naive substring or case-sensitive regex would either over-match (`hausgeldverordnung` shouldn't trigger if it ever appeared) or under-match (uppercase rows missed). -Decision: `_WEG_KEYWORD_RE = re.compile(rf"\b(?:{kws})\b", re.IGNORECASE)` over the keyword list. Word boundaries prevent substring traps; `re.IGNORECASE` covers casing variance. Keyword list is auditable: drawn from real Buena data + the German Hausverwaltung lexicon (Hausgeld, Verwaltergebühr/Verwaltergebuehr, Gemeinschaftskosten, Hausverwaltung, WEG, Sonderumlage, Instandhaltungsrücklage/Instandhaltungsruecklage, Kontoführungsgebühr). -Reason: Predictable matching across casing variants; auditable list of triggers; no third-party NLP dependency. -Revisit if: New customer data shows a token-overlap edge case (e.g. `WEG-` as a model number unrelated to Wohnungseigentümergemeinschaft) — at that point promote the heuristic to per-customer keyword sets. - -## 2026-04-25 — Phase 8.1 Step 3b: invoice → liegenschaft fallback (Buena invariant) -Context: Invoice PDFs in Buena's archive carry filename pattern `YYYYMMDD_DL-NNN_INV-NNN.pdf` — contractor + invoice number, never an EH-NNN or HAUS-NN. Filename heuristics + WEG-keyword matching both fail, but the events are unambiguously WEG bills. -Decision: Router accepts an `event_source` argument; when `event_source == "invoice"` and a single Liegenschaft exists, route there with `method='weg_invoice'`, `reason='invoice without per-unit attribution'`. Loaders pass `event_source` from the `ConnectorEvent.source` field. -Reason: Honest data-shape recognition: every invoice in Buena's archive IS a WEG bill. Customers with per-Haus invoice patterns (filenames containing `HAUS-NN`) hit precedence 4 first. Customers with per-unit invoices carry `EH-NNN` or `MIE-NNN` and hit precedence 1-3. -Revisit if: A customer ships per-property invoices that lack EH-NNN — at that point the rule needs a per-customer override. - -## 2026-04-25 — Phase 8.1 Step 3b: one-time re-route migration is documented, not permanent -Context: After Migration 0002 lands, already-ingested events need their `building_id` / `liegenschaft_id` populated via UPDATE. Running the original backfill skips them (idempotent on `(source, source_ref)`). -Decision: Ship `connectors.cli re-route` as a one-time migration step. Walks events with no scope set and re-evaluates routing using the current rules. Idempotent (re-running on already-routed events scans nothing). Documented as one-time in CLI help text and module docstring; not added to the scheduler or any auto-run path. Per-event live ingestion in `_ingest_one` already calls `route_structured` on each new row, so the rule changes apply automatically to new events. -Reason: Migration semantics belong in a dedicated CLI subcommand operators run intentionally, not in the live pipeline. The lack of automation makes it auditable: ledger-style record of "we ran this on date X" lives in DECISIONS.md. -Revisit if: We start needing recurring re-routes (e.g. when adding new keywords) — at that point the right tool is a SQL migration that backfills, not a Python loop. - -## 2026-04-25 — Phase 8 Step 3: structured router refuses to invent property attribution -Context: Invoices in Buena's archive (filename pattern `YYYYMMDD_DL-NNN_INV-NNN.pdf`) are billed to the WEG (building owners' association), not to a specific unit. The filename carries contractor (DL-NNN) and invoice number (INV-NNN), never an `EH-NNN`. Bank rows of `kategorie=dienstleister` are the same shape — payments to a contractor for shared services, not for one unit. -Decision: `backend.pipeline.router.route_structured` only accepts a property when `metadata.eh_id`, `metadata.mie_id`, or `metadata.invoice_ref` *resolves* to one. No token-overlap fallback for structured events; no inventing attribution for shared services. The result: invoice events land 100% unrouted, bank events land 12.5% unrouted (the contractor-payment subset). -Reason: Honest — the schema currently models attribution at the property level only. Sprinkling shared-service costs onto the first matching property would corrupt every per-property financial metric. The unrouted inbox (`GET /admin/unrouted`) makes the gap observable instead of hidden. -Revisit if: We add a `building_id` column to `events` (one-line additive migration) so building-level events have somewhere honest to land. Step 8 / 9 work could prompt this; documented as a follow-up rather than a Step 3 blocker. - -## 2026-04-25 — Phase 8 Step 3: per-month rent payments supersede the prior `last_rent_payment` -Context: A two-year bank archive holds 12-24 rent payments per active tenant. Writing each as its own immutable fact would clutter the renderer and obscure the "is this property current?" question. -Decision: `extract_bank_facts` writes `financials.last_rent_payment` superseding any prior fact for the same `(property_id, section, field)`. Each new payment becomes the current fact; the chain of superseded predecessors is the audit history (still queryable via `superseded_by`). Identical-value writes short-circuit so re-runs add nothing. -Reason: Matches KEYSTONE's "facts = current truth" rule (Part VI). 611 raw rent rows produced 26 current `last_rent_payment` facts after supersession — one per active tenant who has ever paid. -Revisit if: We add explicit financial activity timeline UI that wants every monthly row visible — the supersession history is already the data, just needs a different read path. - -## 2026-04-25 — Phase 8 Step 1: connectors/ as customer-agnostic ingestion layer -Context: Buena dropped 29 MB of partner data; the next customer will drop a different shape. Earlier plans treated Buena as a special path inside `seed/`; that bakes a customer name into a generic primitive. -Decision: `connectors/` is the new customer-agnostic module. `connectors/base.py` defines the `Connector` Protocol + `ConnectorEvent` dataclass; primitives (`csv_stammdaten`, `eml_archive`, `camt_bank`, `pdf_invoice_archive`, `pdf_letter_archive`) are reusable. Each customer ships a single composite (`connectors/_archive.py`) that knows their directory shape. PII redaction is centralized in `connectors/redact.py` and applied at ingestion. Cost ledger (`connectors/cost_ledger.py` + `cost_ledger` table via `connectors/migrations.py`) is durable across CLI invocations. -Reason: Treats Buena as the first customer of a real architecture, not an exception. Future customers add one composite + tests; the primitives + redaction + ledger don't change. -Revisit if: A customer's shape doesn't fit the primitives — at that point we extend a primitive (e.g. add a Slack-archive walker) rather than fork. - -## 2026-04-25 — Phase 8 Step 1: redact at ingestion, not at render -Context: Several places in the pipeline (renderer, MCP responses, SSE stream) read DB rows back out. Redacting at render means every reader has to know to scrub. -Decision: `connectors/redact.py` scrubs IBANs (→ `****`), full phones (→ `+CC *** **`), and email domains (→ `@example.com`) before yielding any `ConnectorEvent`. Tests assert no `r"DE\d{20}"` and no full E.164 phone survives a round-trip through any connector. Buena is treated as PII until anonymisation status is confirmed (TODO note in `redact.py`). -Reason: Single chokepoint; one module to audit; zero burden on readers; defence-in-depth (renderer can still scrub additionally without changing semantics). -Revisit if: Buena confirms the dataset is fully synthetic — even then, keep redaction on by default; flip a feature flag if specific demos need fuller display. - -## 2026-04-25 — Phase 8 Step 1: durable cost ledger persists across invocations -Context: A single `--max-total-cost-usd $20` cap should govern the entire Buena backfill, not just one CLI run. A per-run-only counter would let an operator hit Ctrl-C, restart, and silently spend another $20. -Decision: New `cost_ledger(source_label, cumulative_usd, cap_usd, hit_at)` table (additive `CREATE TABLE IF NOT EXISTS`, applied via `connectors/migrations.py`). Every Gemini call charges via `connectors.cost_ledger.charge`; on `>= cap` the row's `hit_at` is stamped and `CostCapExceeded` raised. Subsequent invocations read the row and abort immediately. Reset is friction-gated (`--reset-cost-ledger` + interactive `y/N`). -Reason: Spend-across-runs is the only definition that makes the cap real; defaults to "remember spend" so the operator never accidentally over-spends. -Revisit if: We add per-customer multi-tenancy and need per-customer caps — at that point use `source_label` to namespace per customer, which the schema already supports. - -## 2026-04-25 — Phase 8 Step 2: `_upsert_property` honours `prop.metadata` -Context: The Phase 0 `_upsert_property` hardcoded `metadata = {"seed_key": prop.key}`, which kept the Berliner seed simple but lost richer payload (`kaltmiete`, `lage`, `wohnflaeche_qm`, …) needed for Buena units. -Decision: When `prop.metadata` is non-empty, the upsert merges it under `seed_key` so both worlds coexist (`{"seed_key": "EH-014", "lage": "5. OG mitte", "wohnflaeche_qm": 85.0, …}`). Same pattern for `_upsert_tenant`. `PropertySeed.metadata` and `TenantSeed.metadata` default to `{}` so the hand-crafted Berliner seed continues bit-identically (no change to existing data). -Reason: Single ingestion path for *all* customer master data — Buena rows and Berliner rows travel through the same SQL. -Revisit if: We start needing schema-level richer fields (e.g. dedicated columns for kaltmiete) — at that point migrate columns out of JSONB rather than fork the upsert. - -## 2026-04-25 — Phase 8 Step 2: tenants with `mietende` set are skipped (active-only) -Context: Buena's `mieter.csv` includes 26 rows total but at least one has a populated `mietende` (lease ended). Including those as `occupied_by` edges would misrepresent current occupancy. -Decision: The Buena loader skips any tenant whose `metadata.active` is `False` (mietende set). Skipped count is reported in the summary (`tenants_skipped_inactive`). The 25 active tenants land with `occupied_by` edges; the 1 closed lease stays out of the relationship graph. -Reason: "Who lives here today" is a load-bearing question for the markdown / signals; including ex-tenants would confuse it. Closed leases should resurface only via lease history facts (Step 3+). -Revisit if: Lease-history reconstruction needs the closed-lease tenant rows in `tenants` — at that point insert them with a metadata flag and keep them out of `relationships(occupied_by)`. - -## 2026-04-24 — pgvector image: `pgvector/pgvector:pg15` (not `ankane/pgvector:pg15`) -Context: Part V specified `ankane/pgvector:pg15`, but that tag does not exist on Docker Hub — `ankane/pgvector` uses v-prefixed tags and the modern pg15 flavor has moved to the official `pgvector/pgvector` repo. -Decision: Use `pgvector/pgvector:pg15` in `docker-compose.yml`. -Reason: Unblocks Phase 0 without any behavior change; `pgvector/pgvector` is the canonical upstream image and pulls cleanly. Pinning the requested tag would have failed on `docker compose up`. -Revisit if: We standardize on a newer Postgres (pg16) or move to Railway-managed Postgres. - -## 2026-04-24 — Host port mapping `5433:5432` -Context: The dev box already runs a Homebrew `postgresql@15` on 127.0.0.1:5432, so publishing the container on 5432 leaves `localhost:5432` pointed at the host Postgres (where role `keystone` doesn't exist) and the seed script fails. -Decision: Expose Postgres on host port 5433, container 5432. `.env.example` DSNs updated in lockstep so no downstream code has to know. -Reason: Stopping the user's Brew service would be destructive to their environment. The port number isn't load-bearing — all application connections read `DATABASE_URL(_SYNC)` from `.env`. -Revisit if: We ship to Railway (ports irrelevant there) or the team wants to standardize on 5432 locally. - -## 2026-04-24 — Seed uses psycopg2 (sync), not SQLAlchemy async -Context: The seed needs to run schema DDL and ~100 upserts from a CLI. The production code uses SQLAlchemy async, but bringing up an event loop for a one-shot script adds complexity. -Decision: `seed/seed.py` connects with `psycopg2` directly (sync). Production request paths still use the async engine in `backend/db/session.py`. -Reason: Faster, simpler, identical semantics for a one-shot. `psycopg2-binary` is already a required dep for parity with APScheduler-backed jobs later. -Revisit if: We want to share upsert helpers between the seed and runtime (unlikely — seed data stays here). - -## 2026-04-24 — Idempotent seed via natural-key SELECT-then-INSERT -Context: The user asked for idempotent seed. `events` already has `UNIQUE (source, source_ref)`, but owners/buildings/contractors/properties/facts have no natural unique constraints in the canonical schema. -Decision: For each of those tables the seeder does `SELECT id WHERE ` first and only inserts if absent. Facts are matched on `(property_id, section, field, source_event_id)`. -Reason: Lets re-runs be safe without modifying the canonical schema (Part VI is verbatim). Keeps the seed understandable. -Revisit if: We start seeing drift between seeded and runtime-produced facts — in that case the differ/applier will own supersession and the seed should stop trying to be an authority. - -## 2026-04-24 — Fact confidence > 0.8 default for seed, lower for web/inferential -Context: Phase 0 seeds facts directly instead of going through Gemini extraction; we still want the `confidence` column to be meaningful for the demo. -Decision: Lease/tenant/financial facts sourced from a PDF carry 0.95–0.99; maintenance-from-email carry 0.85–0.94; Tavily/neighborhood facts carry 0.75–0.85. -Reason: Signals downstream are meant to key off confidence, and the demo markdown visibly prints the value. Gradient matches how a real extractor would score these sources. -Revisit if: Gemini extractor lands and its scores calibrate differently — re-seed and align. - -## 2026-04-24 — Phase 1: dual-path extractor (Gemini Flash + rule-based fallback) -Context: Part IV designates Gemini Flash as the extraction engine. The demo venue's wifi + Gemini's quota are both failure modes; Part XII explicitly lists "fallback to rule-based extraction for demo emails" as the mitigation. -Decision: `backend/pipeline/extractor.py` calls `backend.services.gemini.extract_facts` when `GEMINI_API_KEY` is set, otherwise runs a deterministic keyword-based extractor covering heating/leak/payment/lease/compliance shapes. Both paths return the same `ExtractionResult`. -Reason: Demo can't brick on a network issue, and the fallback also makes local dev / CI possible without burning Gemini quota. Gemini remains the production path — the fallback does **not** write lower-quality facts when Gemini is available. -Revisit if: Gemini throughput becomes reliable enough to drop the fallback, or we want to log calibration deltas between the two paths. - -## 2026-04-24 — Phase 1: seed events stamped `processed_at = received_at` -Context: Dropping seed events into the queue with `processed_at IS NULL` caused the Phase 1 worker to rerun the rule-based extractor over the hand-crafted dataset on first boot, producing spurious "Latest heating issue: Mietvertrag" facts. -Decision: `seed/seed.py` now writes `processed_at = received_at` for every seeded event, signalling to the worker that the hand-authored facts are authoritative. -Reason: Keeps the seeded markdown clean; the live pipeline only touches events that actually arrive post-boot. No schema change. -Revisit if: We start wanting the pipeline to *re-extract* over the seed (e.g. to verify Gemini output against ground truth) — in which case add a `--reprocess-seed` switch instead of flipping the default. - -## 2026-04-24 — Phase 5: Regulation watcher runs hourly, offline mode seeds canned headlines -Context: Part IV says "Regulation watcher cron — hourly for keywords like 'Berlin rent cap', 'Mietpreisbremse'." Demo must still show a `regulation_change` signal on a fresh DB even when `TAVILY_API_KEY` is absent (flaky wifi, missing key, etc.). -Decision: `backend/services/tavily.watch_regulations` polls Tavily for five canonical queries when the key is set; otherwise seeds three clearly-labelled "offline snapshot" headlines as `web` events tagged `metadata.regulation=true`. Every event is stamped `processed_at` so the extractor worker doesn't touch it — the `regulation_change` rule reads the events directly. Idempotent via `source_ref = tavily-reg:{query}:{hour}`. -Reason: Preserves the partner-visibility bar ("every partner tool visible somewhere in the demo") without lying about live data when offline, and the hourly cadence is what Part IV specifies. -Revisit if: We want streaming / diff-based regulation change detection — at that point store a `content_hash` per headline and only fire when it changes. - -## 2026-04-24 — Phase 5: Aikido badge reads live when keyed, otherwise local snapshot with git SHA -Context: Aikido is a scheduled scanner, not a mid-request API. The demo renders a "Security scan: passing" badge on Settings; we need it to be honest whether or not the CI scan has been hooked up. -Decision: `backend/services/aikido.get_badge` attempts a live GET when `AIKIDO_API_KEY` is present, falls back to a `local_snapshot` badge that surfaces the git SHA the demo is running on (via `git rev-parse --short HEAD`). The response payload tags `source` so the UI / judges know which mode. -Reason: "Passing" without context is a hand-wave. Showing the commit SHA + explicit source mode makes the fallback defensible and obvious. -Revisit if: CI starts publishing scan results somewhere (e.g., GitHub Actions artifact) — point the fetcher at that instead of Aikido's REST API. - -## 2026-04-24 — Phase 5: Pioneer approval-rate weighting computed locally -Context: Pioneer / Fastino may not expose a usable ranking endpoint in hackathon time. The Settings > Learning panel still needs to show Keystone is adapting to the human. -Decision: `backend/services/pioneer.compute_learning` reads `approval_log`, derives per-signal-type approval rates (edits count as 0.8 × approved), and maps them to priority weights in `[0.5, 1.5]` with sample-size shrinkage (< 5 proposals anchored to 1.0). The trend-line sentence highlights the top-weighted signal type ("Keystone is prioritizing cross_property_pattern based on your approval behavior (100% approved over 2 proposals)"). Interface is a plain dataclass so swapping in a real Pioneer call later is a one-function change. -Reason: Keeps the learning story true to what the system has observed, backs up the "Pioneer learning layer" pitch with verifiable numbers, and avoids overclaiming ML we haven't trained. -Revisit if: We start feeding live approval logs to Pioneer's training endpoint — replace `compute_learning` with a call that merges remote weights into the local snapshot. - -## 2026-04-24 — Phase 4: MCP server is a thin REST adapter, not a database client -Context: Part V says "MCP server is a thin adapter. All tools call the backend REST API." An alternative would be sharing SQLAlchemy sessions / pgvector access across both surfaces for speed. -Decision: `mcp_server/tools.py` wraps `httpx.AsyncClient` and hits the same REST endpoints the UI uses. Zero DB imports. Every schema change lands in exactly one place (the REST layer), and the MCP server can be pointed at a remote Keystone by flipping `KEYSTONE_BASE_URL`. -Reason: Matches the constitution, keeps the MCP surface under one pane of review, and means judges can reason about the MCP tools the same way they reason about the UI. -Revisit if: We later need streaming tool results (e.g., large markdown) where an HTTP round-trip is the bottleneck — then add an in-process shortcut, keeping the REST adapter as the fallback. - -## 2026-04-24 — Phase 4: Multi-term keyword search (no embeddings yet) -Context: Part VIII calls `search_properties` "semantic search". The schema has `vector(768)` columns on facts + events, but embedding generation hasn't been wired into the worker yet. -Decision: Ship a per-term LIKE search with weighted scoring (name/alias > address > fact-value, hit-count boost) and split the query on whitespace so `"heating Berlin"` still finds useful hits. Label the tool `search_properties` — not `semantic_search` — to stay honest. -Reason: Keeps the MCP surface working today without a Gemini round-trip per query, and aligns with the "reliability > sophistication" rule. Embedding-based search can slot in behind the same endpoint in Phase 5. -Revisit if: We ship the Gemini embedding pipeline — swap the SQL out for `ORDER BY embedding <=> :query_vec LIMIT :k` without changing the endpoint shape. - -## 2026-04-24 — Phase 4: `propose_action` writes a pending signal, never dispatches -Context: MCP tools can run without human approval. Part I Principle 3 ("System proposes. Human approves.") forbids letting an external AI close the loop end-to-end. -Decision: `POST /signals/propose` inserts a `status='pending'` signal tagged `payload.proposed_by='external_ai'`; approval still flows through `/signals/{id}/approve` and the Entire-compatible broker. -Reason: Keeps the human-in-the-loop invariant intact for MCP-originated actions and gives us an audit trail (the inbox shows "proposed by Claude Desktop"). -Revisit if: We later want first-class AI-co-signed actions — add a separate `ai_authorized` pathway rather than loosening this. - -## 2026-04-24 — Phase 3: portfolio-level signals use `property_id = NULL` -Context: `cross_property_pattern` fires across a building or an entire portfolio cohort; there's no single property to attach it to. -Decision: Persist those signals with `property_id = NULL`. The inbox filter `?property_id=X` still works for per-property signals; portfolio-level ones appear in the unfiltered listing and (Phase 4) will surface on the portfolio dashboard banner. -Reason: Keeps the schema as-is (Part VI). A synthetic "portfolio" property would distort every per-property query. -Revisit if: Portfolio UI needs more than one dimension of grouping — then add a `scope` column instead of overloading NULL. - -## 2026-04-24 — Phase 3: dedupe signals on `(property_id, type, payload.hint.{topic|subtype})` -Context: The evaluator runs every 30s; without dedupe it would insert a fresh pending signal for every pattern on every tick, flooding the inbox. -Decision: `_already_open` in `backend/signals/evaluator.py` checks for an existing `status='pending'` signal with the same `(property_id, type)` **and** matching `proposed_action.payload.hint.topic|subtype` — so `recurring_maintenance:heating` and `recurring_maintenance:water` on the same property remain distinct. -Reason: Matches the way rules author their output (each rule sets `action_hint.topic` or `subtype`), preserves re-fire on the next tick if a human approves/rejects/lets the signal resolve, and avoids a separate dedupe table. -Revisit if: A rule starts producing signals with the same `(property, type, topic)` but legitimately different evidence (e.g. a second-level failure after the first is resolved) — promote topic to a fact-level timestamp tiebreaker. - -## 2026-04-24 — Phase 3: Gemini Pro drafter with a four-part template fallback -Context: KEYSTONE's Signal Quality Bar ("expert speaking, not database emitting rows") is load-bearing for the demo. Gemini Pro produces that quality when available; a generic fallback must not embarrass us when it isn't. -Decision: `backend/signals/drafter.py` calls Gemini Pro when `GEMINI_API_KEY` is set, otherwise picks a deterministic template keyed on `candidate.type` and fills in action-hint values. Every template follows the **observation → risk → concrete next step → deadline** structure. -Reason: Keeps the demo honest without a Gemini dependency, and the structure is what the bar actually measures. -Revisit if: Template copy drifts out of date for a new rule — add a test asserting each template mentions a deadline and a concrete action. - -## 2026-04-24 — Phase 3: Entire-compatible broker via Protocol + local impl -Context: Part IV says "if their SDK isn't available in time, build the approval inbox natively with an EntireBroker interface that's easy to swap." -Decision: `backend/services/entire.py` defines a `runtime_checkable Protocol` and ships `LocalEntireBroker` that writes outbox rows. A `set_broker()` hook lets tests / the real SDK drop in without touching callers. -Reason: Honors the pitch line ("Entire-compatible approval layer") without overclaiming, and keeps the swap to one file. -Revisit if: Entire SDK lands — replace `LocalEntireBroker` with an adapter that delegates dispatch while still writing the outbox row for auditability. - -## 2026-04-24 — Phase 2: Tavily enrichment writes facts directly (not via worker) -Context: Phase 2 exit criterion requires "At least one fact on each property has a visible Tavily badge." Letting the worker extract facts from a generic "web enrichment" event would produce unreliable output (the rule-based extractor might route it to `compliance.note` or nothing, and real Gemini quality varies). -Decision: `enrich_property` in `backend/services/tavily.py` inserts the event **and** two seed facts (`overview.market_snapshot`, `compliance.regulation_watch`) in the same transaction, then stamps `processed_at` so the worker skips re-extraction. Idempotent — a second call returns `None` if any Tavily event already exists for the property. -Reason: Guarantees the demo badge appears, without precluding the worker from handling more nuanced web events later. Keeps the source-of-truth audit trail (event row + sourced facts) intact. -Revisit if: Tavily hits become rich enough that parsing them with Gemini Pro would outperform the canned summary — at that point route through the worker and drop the direct insert. - -## 2026-04-24 — Phase 2: Tavily offline fallback snapshot -Context: `TAVILY_API_KEY` won't be set on every dev box / CI run, and venue wifi could throttle. Part XII lists "flaky network" as a demo risk. -Decision: When the key is missing or `tavily.search` errors out, `enrich_property` falls back to a single canned "offline snapshot" fact set clearly labelled as such, rather than no enrichment at all. -Reason: The badge is a visible UI contract the demo depends on. Offline mode keeps the product surface honest (facts are labelled "offline snapshot (2026 Q1)") without lying to judges. -Revisit if: The canned copy drifts out of date or starts looking too generic — swap the wording seasonally or tie it to the property's region. - -## 2026-04-24 — Phase 2: Mock ERP reads data.json on every request -Context: The demo needs an ERP data source that's easy to edit live (Part II beat 1:00). A database or fake auth scheme would add friction. -Decision: `mock_erp/main.py` re-reads `data.json` on every GET. Editing the JSON file is the canonical "ERP got a new payment" gesture during the demo. -Reason: Minimum moving parts, max demo legibility. No state syncing, no restart needed. -Revisit if: We start needing filtering/aggregation that's too slow for the naive scan — unlikely under a few hundred rows. - -## 2026-04-24 — Phase 2: PDF source_ref = `{filename}:{sha256[:16]}` -Context: PDFs don't come with a Message-ID; we still need idempotency (`events.(source, source_ref)` is UNIQUE). -Decision: The `/uploads/pdf` endpoint hashes the file bytes (SHA-256) and concatenates with the filename to form `source_ref`. Reuploading the exact same PDF is a no-op; a renamed PDF is considered distinct. -Reason: Conservative — we'd rather accept a duplicate upload than miss a genuinely-new PDF with the same content. The filename prefix preserves human context in the events table. -Revisit if: We start ingesting thousands of PDFs where byte-identical duplicates should collapse even under different filenames. - -## 2026-04-24 — Phase 1: Postgres as the queue, not Redis/Kafka (reinforced) -Context: Phase 1 needed a queue for events. KEYSTONE Part III already forbids Redis/Kafka. -Decision: `backend/pipeline/worker.py` uses `SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1` per tick; `backend/scheduler.py` runs the worker every 2s via APScheduler. `/debug/trigger_event` also kicks a drain inline so `curl` POSTs see fresh markdown before they return. -Reason: Honors the spirit of the constitution (one system, visible SQL). SKIP LOCKED is safe under concurrency when we scale to multiple worker processes later. Inline drain on debug POSTs cuts perceived latency to ~20ms without altering the scheduled path. -Revisit if: We add a second backend instance and notice drift between the APScheduler ticks and the debug inline call (add LISTEN/NOTIFY then). - -## 2026-04-24 — Skip heavy deps (google-generativeai, pdfplumber, tavily-python, imapclient) for Phase 0 local boot -Context: `pyproject.toml` lists the full dep matrix, but Phase 0 only touches FastAPI + SQLAlchemy + pydantic + structlog + psycopg2 + asyncpg. -Decision: Installed only Phase 0 runtime deps into `.venv` locally to keep the first boot fast; `pip install -e ".[dev]"` still pulls the full tree for CI / Railway / Phase 1+. -Reason: Hackathon time discipline. The pyproject is the contract; the local venv is an optimization. -Revisit if: We add tests that import the partner services, or start Phase 1 — at that point run `pip install -e ".[dev]"`. diff --git a/DEMO_QA.md b/DEMO_QA.md deleted file mode 100644 index c3e00c6..0000000 --- a/DEMO_QA.md +++ /dev/null @@ -1,149 +0,0 @@ -# Keystone — Demo Q&A - -Answers to the five questions KEYSTONE Part XII tells us to be ready for. Each -answer leans on what's actually in the repo so you can show the file/path if a -judge presses. - ---- - -## 1. How does it scale? - -**Short answer:** Postgres is the queue, the worker is stateless, and the -critical path is one Gemini call per event. - -**Where it lives in the repo:** -- `backend/pipeline/worker.py` claims work with `SELECT ... FOR UPDATE SKIP - LOCKED LIMIT 1`. Two backend instances on the same DB are already safe — - no Redis, no Kafka. -- `events.UNIQUE (source, source_ref)` (`backend/db/schema.sql`) keeps re- - delivered messages idempotent across IMAP, Slack, PDF, ERP, and Tavily. -- `backend/scheduler.py` runs everything inside one APScheduler with - `coalesce=True, max_instances=1`, so a slow tick can never pile up. - -**Sketch for going wider:** -- One write replica + N read replicas of Postgres covers the dashboard / MCP - read path; pgvector indexes scale to millions of rows. -- More workers = more uvicorn pods pointed at the same DB. SKIP LOCKED keeps - them honest. -- LLM cost grows linearly with events; Gemini Flash on the hot path keeps the - per-event $/latency tight, and Gemini Pro only fires when a human is about - to read the draft (signal approval), so cost tracks engagement. - -**Throughput we measured locally (Phase 6):** 10× `/debug/trigger_event` runs -average **24 ms**, max **64 ms** end-to-end against a single Postgres on -:5433. The 10-second budget in KEYSTONE is comfortable headroom. - ---- - -## 2. What about privacy? - -**Short answer:** Every fact has a source, every signal has evidence, and no -action leaves the system without human approval. - -**Where it lives in the repo:** -- `facts` table tracks `source_event_id`, `confidence`, `valid_from/valid_to`, - `superseded_by` — the full provenance chain for any displayed claim. - See `backend/db/schema.sql` lines 79-93. -- `backend/pipeline/renderer.py` emits `[source: ]` next to every - fact line; the UI links them. Nothing is unsourced. -- The approval inbox (`backend/api/signals.py`) is the **only** path to the - `outbox` table. `LocalEntireBroker.dispatch` (`backend/services/entire.py`) - writes the outbox row on approve, never on signal creation. -- MCP `propose_action` (`backend/api/signals.py::propose_signal`) tags every - AI-authored signal with `payload.proposed_by='external_ai'` — the inbox - shows who suggested what, and a human still has to approve. -- `.env` ships with placeholder secrets. Nothing committed. -- Aikido scan badge (`/settings/security`) makes the security posture visible - on the Settings page. - -**What we don't ship:** Auth (one demo user — Part III), real email send -(outbox table only — Part III). Those are the next-level concerns; the -audit-trail design is in place to support them. - ---- - -## 3. What's the business model? - -**Short answer:** Per-property monthly subscription with usage-based add-ons -for the partner integrations. - -**Pricing shape we'd take into market:** -- **Core seat per property** — say €15/property/month — covers the living - context layer, the pipeline (email + Slack + PDF + ERP), and the approval - inbox. -- **Intelligence pack** — €5/property/month for the signals + portfolio - intelligence layer. Usage-priced because Gemini Pro is what makes the - Signal Quality Bar quality possible. -- **Enterprise / portfolio** — flat tier for portfolios over ~200 doors that - bundles Tavily regulation watch, Aikido security badge, Pioneer learning - layer, MCP, and SSO. - -**Why this works:** -- The unit of value is "operational decisions per property per month" — easy - to ROI against a property manager's labor cost (an hour a week per - property at €40/h = €170/month, so €15-20 for a system that prevents one - unnecessary truck-roll pays for itself). -- Partner integrations layer on revenue (and lock-in) without re-pricing the - core seat. - ---- - -## 4. How accurate is extraction? - -**Short answer:** Every fact carries a confidence score, comes from a -specific source, and competes against existing facts via a documented -resolution rule. We don't claim 100%; we claim "always sourced, always -contestable". - -**Where it lives in the repo:** -- `backend/services/gemini.py::EXTRACTION_SCHEMA` — Gemini Flash returns a - structured object including a per-fact `confidence` in [0, 1]. We never - free-text our way into facts. -- `backend/pipeline/differ.py::SOURCE_RANK` — when two sources disagree, the - rule is `pdf > erp > email > slack > web > debug`, with a confidence-delta - override for weaker sources (a high-confidence email can still beat a - stale PDF if the delta is ≥0.1). -- `backend/pipeline/applier.py` writes the new fact and stamps - `superseded_by` on the displaced one. The history is queryable; the UI - can show "this fact replaced this one on date X". -- Phase 1 mitigation (`backend/pipeline/extractor.py`): if Gemini errors out, - we fall back to a deterministic keyword extractor for the demo email - shapes. Worse extraction, same provenance contract. - -**Numbers we'd publish at GA:** precision/recall on a held-out set per -extraction category (`maintenance`, `lease`, `payment`, …). We have the -schema in place; producing the numbers is post-hackathon. - ---- - -## 5. What happens when it's wrong? - -**Short answer:** Three layers of containment — the human approval gate, the -fact supersession chain, and the per-rule re-fire on dedup. - -**Where it lives in the repo:** -- **Approval gate.** No external action happens without `POST - /signals/{id}/approve` (`backend/api/signals.py`). A bad signal can be - rejected (`/reject`) or edited (`/edit`); both paths write - `approval_log(decision)` rows so we can measure rule quality over time. -- **Fact supersession.** `backend/pipeline/applier.py` never destroys a fact; - it stamps `superseded_by` so the wrong-but-old version is still queryable - and replaceable. Re-process the original event after a fix and the chain - extends cleanly. -- **Pioneer learning loop.** `backend/services/pioneer.py::compute_learning` - reads `approval_log` and adjusts per-signal-type priority weights inside - a `[0.5, 1.5]` band, with sample-size shrinkage so a single wrong signal - doesn't flip a rule off. The trend line surfaces the change ("Keystone is - deprioritizing X based on your approval behavior"). -- **Idempotency.** Every event source uses a stable `source_ref` - (`Message-ID`, `payment_id`, `filename:sha256[:16]`, Slack - `team:channel:ts`). Replaying the world reproduces the same event ids; - there's no double-action risk after a bug fix. -- **Demo-day fallback.** Per Part XII: Gemini outage → rule-based extractor - fallback (`backend/pipeline/extractor.py::_rule_based`); Tavily outage → - offline snapshot fact (`backend/services/tavily.py::_offline_snapshot`); - IMAP outage → `POST /debug/trigger_event` (`backend/api/events.py`). - -**The framing we want to leave with judges:** wrong is observable, wrong is -reversible, and wrong gets the system smarter — because the approval log is -the training signal, not the model's opinion of itself. diff --git a/Dockerfile b/Dockerfile index bd50365..d4e7dd6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,24 +1,34 @@ -# Use the official Python 3.11 slim image -FROM python:3.11-slim - -# Set working directory -WORKDIR /app - -# Install system dependencies (if any are needed by pgvector/psycopg2) -RUN apt-get update && apt-get install -y \ - build-essential \ - libpq-dev \ - && rm -rf /var/lib/apt/lists/* +# Keystone backend image. +# +# Stage 1 installs only the runtime dependencies declared in pyproject.toml +# into a virtualenv; stage 2 copies that virtualenv and the source into a slim +# image that runs as an unprivileged user. Dev tools (pytest, ruff, mypy) are +# never installed. Every dependency ships manylinux wheels, so no compiler or +# system packages are needed. -# Copy project configuration files +FROM python:3.11-slim AS deps +ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 +WORKDIR /build COPY pyproject.toml ./ +RUN python -c "import tomllib; print('\n'.join(tomllib.load(open('pyproject.toml', 'rb'))['project']['dependencies']))" > requirements.txt \ + && python -m venv /opt/venv \ + && /opt/venv/bin/pip install -r requirements.txt -# Install project dependencies -RUN pip install --no-cache-dir -e ".[dev]" - -# Copy the rest of the application code -COPY . . - -# Run the seed script (applies base schema idempotently), then migrations, and start Uvicorn -# Cloud Run sets the PORT environment variable (default 8080) -CMD python -m seed.seed && python -c "from connectors.migrations import apply_all; apply_all()" && uvicorn backend.main:app --host 0.0.0.0 --port ${PORT:-8080} \ No newline at end of file +FROM python:3.11-slim +ENV PATH=/opt/venv/bin:$PATH \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 +RUN useradd --create-home --uid 10001 keystone +WORKDIR /app +COPY --from=deps /opt/venv /opt/venv +COPY --chown=keystone:keystone backend ./backend +COPY --chown=keystone:keystone connectors ./connectors +COPY --chown=keystone:keystone seed ./seed +COPY --chown=keystone:keystone mcp_server ./mcp_server +COPY --chown=keystone:keystone Extracted_demo ./Extracted_demo +COPY --chown=keystone:keystone scripts/entrypoint.sh ./scripts/entrypoint.sh +USER keystone +EXPOSE 8000 +HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=5 \ + CMD python -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ.get(\"PORT\", \"8000\")}/health', timeout=2)" +ENTRYPOINT ["./scripts/entrypoint.sh"] diff --git a/Extracted_demo/sample_events/featured_emails.json b/Extracted_demo/sample_events/featured_emails.json new file mode 100644 index 0000000..82c7747 --- /dev/null +++ b/Extracted_demo/sample_events/featured_emails.json @@ -0,0 +1,35 @@ +{ + "description": "Synthetic tenant emails for WE 29 (EH-029, the default FEATURED_PROPERTY), loaded by `python -m connectors.cli load-sample-events` so the featured property has a history on first start. The sender is the synthetic tenant MIE-017 from stammdaten/stammdaten.json. days_ago is counted back from load time.", + "events": [ + { + "source_ref": "sample-we29-01", + "days_ago": 110, + "raw_content": "From: Laura Schmitz \nSubject: Heizung ausgefallen\n\nGuten Tag,\n\ndie Heizung in WE 29 ist seit heute Morgen ausgefallen. Alle Heizkörper bleiben kalt.\n\nViele Grüße\nLaura Schmitz" + }, + { + "source_ref": "sample-we29-02", + "days_ago": 74, + "raw_content": "From: Laura Schmitz \nSubject: Heizung wieder kalt\n\nHallo,\n\ndie Heizung in WE 29 ist schon wieder ausgefallen, zum zweiten Mal in diesem Winter.\n\nViele Grüße\nLaura Schmitz" + }, + { + "source_ref": "sample-we29-03", + "days_ago": 40, + "raw_content": "From: Laura Schmitz \nSubject: Wasserschaden im Bad\n\nGuten Tag,\n\nin WE 29 tropft seit gestern Wasser von der Decke im Bad. Bitte schicken Sie schnell einen Handwerker.\n\nDanke und viele Grüße\nLaura Schmitz" + }, + { + "source_ref": "sample-we29-04", + "days_ago": 33, + "raw_content": "From: Laura Schmitz \nSubject: Mietminderung wegen Wasserschaden\n\nSehr geehrte Damen und Herren,\n\nwegen des Wasserschadens in WE 29 kündige ich eine Mietminderung von 10 % an, bis der Schaden behoben ist.\n\nMit freundlichen Grüßen\nLaura Schmitz" + }, + { + "source_ref": "sample-we29-05", + "days_ago": 12, + "raw_content": "From: Laura Schmitz \nSubject: Heizung zum dritten Mal ausgefallen\n\nHallo,\n\ndie Heizung in WE 29 ist zum dritten Mal ausgefallen. Bitte lassen Sie die Anlage grundsätzlich prüfen.\n\nViele Grüße\nLaura Schmitz" + }, + { + "source_ref": "sample-we29-06", + "days_ago": 5, + "raw_content": "From: Laura Schmitz \nSubject: Lärm im Treppenhaus\n\nGuten Tag,\n\nseit einer Woche gibt es nachts Lärm im Treppenhaus vor WE 29.\n\nViele Grüße\nLaura Schmitz" + } + ] +} diff --git a/Extracted_demo/stammdaten/stammdaten.json b/Extracted_demo/stammdaten/stammdaten.json index a3caa0c..db85132 100644 --- a/Extracted_demo/stammdaten/stammdaten.json +++ b/Extracted_demo/stammdaten/stammdaten.json @@ -1,9 +1,9 @@ { "liegenschaft": { "id": "LIE-001", - "name": "WEG Immanuelkirchstraße 26", - "strasse": "Immanuelkirchstraße 26", - "plz": "10405", + "name": "WEG Musterstraße 26", + "strasse": "Musterstraße 26", + "plz": "10115", "ort": "Berlin", "baujahr": 1928, "sanierung": 2008, diff --git a/KEYSTONE.md b/KEYSTONE.md deleted file mode 100644 index 00a1c7e..0000000 --- a/KEYSTONE.md +++ /dev/null @@ -1,970 +0,0 @@ -# KEYSTONE — Project Constitution - -## Git Hygiene - -- **Commit atomically.** One logical change per commit. Don't bundle unrelated fixes. -- **Commit format:** conventional commits — `feat:`, `fix:`, `chore:`, `refactor:`, `test:`, `docs:`. -- **Good messages:** `feat(pipeline): add Gemini extractor with JSON schema validation` — not `stuff` or `wip`. -- **Commit at natural breakpoints:** after a test passes, after a feature is demo-able, before switching context. Not on a timer. -- **Never commit secrets.** `.env` is gitignored. Double-check before every commit. -- **Tag at phase boundaries:** `git tag phase-1-complete` after each phase exit criterion is met. -- **Branch naming:** `phase-N/short-description` if you branch. Main is always demo-ready. - -## - -You are **Claude Code**, building **Keystone**: the winning submission for the **Buena track** at the hackathon. - -**Read this entire document before writing any code.** -**Re-read "The North Star" and "Scope Discipline" at the start of every session.** -**Update "Current Phase" at the end of every session.** - ---- - -# PART I — THE NORTH STAR - -## The Product in One Sentence - -**Keystone is the operational brain for property management.** -It turns fragmented communication (email, Slack, PDFs, ERPs, web) into a **living, trusted context layer per property**, and proactively suggests actions with human approval. - ---- - -## The Winning Insight - -Other teams will build: - -> Aggregate and summarize data. - -We build: - -> Detect patterns, raise signals, and propose decisions. - -**Pitch line (use verbatim):** - -> "Other teams built a better filing cabinet. We built the brain that runs the operation." - ---- - -## What Judges Must Feel - -By the end of the demo, each judge must think: - -1. **"It noticed something I wouldn't have."** -2. **"I trust where this came from."** -3. **"I would actually use this."** - -If any of these three is unclear, we lose. Every feature is evaluated against these three. - ---- - -## Four Core Principles - -### 1. Context = Source of Truth -Every fact has a source. Every fact has confidence. Every fact has history. No black-box outputs. - -### 2. Signals > Summaries -We don't just describe — we detect, prioritize, and recommend. - -### 3. Human-in-the-Loop -System proposes. Human approves. System learns patterns from the decisions. - -### 4. Intelligence Across Properties -Insights are portfolio-aware — not isolated, not reactive. - ---- - -## The Signal Quality Bar - -**Every signal must sound like an expert speaking, not a database emitting rows.** - -❌ **Bad:** *"Recommend inspection."* -✅ **Good:** *"3 heating complaints across units sharing the same boiler model in 6 weeks. High likelihood of imminent boiler failure. Schedule contractor visit within 48h. Notify owner Maria."* - -The difference between winning and losing is whether signals feel *smart*. - ---- - -# PART II — THE 2-MINUTE DEMO (BUILD ONLY FOR THIS) - -Build backwards from this demo. Every line of code must serve one of these seven beats. - -### (0:00) Portfolio View -Open Keystone: 4 properties, 3 active signals, 2 pending approvals. -**Line:** *"Keystone is the operational brain for property management."* - -### (0:15) Property Deep Dive -Zoom into **Berliner Strasse 12, Apt 4B**. Show: -- Living markdown with clickable sources -- Context panel: Owner → Building → Tenants → Contractor - -### (0:45) Live Event Trigger -Send email from phone: *"Heating not working in 4B"*. -Within ~8 seconds: activity feed updates, markdown gains a maintenance entry with a clickable source. - -### (1:00) The WOW Signal -A signal fires: -> *"3 heating complaints across units sharing the same boiler model. High risk of system failure. Schedule contractor inspection within 48h. Notify owner Maria."* - -### (1:15) Human Approval -Click **Approve**. Signal resolves. Outbox shows the "sent" message to the owner. - -### (1:30) MCP Integration -Open Claude Desktop on second screen. Ask: *"What's going on with apartment 4B?"* -Claude answers using Keystone context via MCP. -**Line:** *"Keystone becomes the memory layer any AI can use."* - -### (1:45) Portfolio Intelligence -Zoom to portfolio. Banner: -> *"Keystone detected: 3 pre-1990 boiler properties had heating issues this winter. Schedule portfolio-wide inspection?"* - -### (2:00) Close -> *"Other teams built a filing system. We built the system that runs operations."* - ---- - -# PART III — SCOPE DISCIPLINE (NON-NEGOTIABLE) - -Read this at the start of every session. - -### The Golden Question -Before adding anything: **"Does this show up in the 2-minute demo?"** If no, cut it. - -### Build Order Rule -**End-to-end first, polish later.** A working ugly pipeline beats a beautiful broken one. - -### What We Are NOT Building -- ❌ No authentication. One hardcoded demo user. -- ❌ No multi-tenancy. -- ❌ No real OAuth. IMAP app password + Slack webhook signing secret only. -- ❌ No message queue. **Postgres IS the queue** (`SELECT FOR UPDATE SKIP LOCKED`). -- ❌ No real email sending. Write to `outbox` table and show a toast. -- ❌ No real ERP. Mock JSON endpoint. -- ❌ No ML training. "Learning" is approval-rate statistics. -- ❌ No mobile app. -- ❌ No Kubernetes, Redis, Kafka, or microservice sprawl. - -### Reliability > Sophistication -A signal that fires reliably on cue beats a clever signal that might not fire. - -### If Unsure -Make the choice that **maximizes demo impact and minimizes risk**. Log the decision in `DECISIONS.md`. - ---- - -# PART IV — PARTNER TECHNOLOGIES - -Every partner must have a real, visible role. Bolt-ons are obvious to judges. - -## Google DeepMind (Gemini) — CORE -- `gemini-2.0-flash` for event extraction (speed-critical path) -- `gemini-2.0-pro` for signal action drafting (quality-critical path) -- `text-embedding-004` for embeddings -- **Use structured output (JSON schema) for all extraction calls. Non-negotiable.** -- All calls go through `backend/services/gemini.py` with retries + schema validation. - -## Lovable — CORE (entire UI) -- Frontend built in Lovable editor. Not in this repo. -- Backend exposes clean REST endpoints that Lovable consumes. - -## Tavily — HIGH (must be visible in UI) -Two uses: -1. **Property enrichment on creation** — neighborhood info, local regulations, recent news. Stored as facts with `source: 'web (tavily)'`. -2. **Regulation watcher cron** — hourly for keywords like "Berlin rent cap", "Mietpreisbremse". - -**UI requirement:** property detail page shows a "Updated from web sources" badge next to Tavily-sourced facts. This must be visible in the demo. - -## Entire — HIGH (approval layer) -- Powers the approval inbox. Every approved action brokers through Entire's SDK. -- If their SDK isn't available in time, build the approval inbox natively with an `EntireBroker` interface that's easy to swap. In the pitch, say *"Entire-compatible approval layer"* — never overclaim. - -## Pioneer (Fastino) — MEDIUM (learning layer) -- Track approval vs rejection rate per signal type. -- Display on dashboard: *"Keystone is prioritizing heating issues based on your behavior"*. -- If Pioneer exposes a self-training endpoint usable in hackathon time, feed the approval log to it for ranking. Otherwise implement locally with weighted thresholds adjusted from `approval_log` stats. - -## Aikido — LOW but visible (trust badge) -- Run Aikido scan on this repo. -- Display "Security scan: passing" badge on Settings page and property detail footer. -- Takes 30 minutes, buys real credibility. - -## Gradium — OPTIONAL STRETCH (voice briefing) -- Only if core is rock-solid by hour 40. -- Feature: "Morning briefing" — manager asks via mic, system responds via Gradium TTS with top signals. -- High-risk demo beat. Skip if anything else is unstable. - ---- - -# PART V — ARCHITECTURE - -## Services - -``` -/ -├── KEYSTONE.md # this file -├── DECISIONS.md # running log of judgment calls -├── README.md # setup + run instructions -├── docker-compose.yml # Postgres + pgvector + backend + mcp_server + mock_erp -├── .env.example # all required keys listed -├── pyproject.toml # ruff, mypy, pytest config -├── backend/ -│ ├── main.py # FastAPI entry -│ ├── config.py # pydantic Settings -│ ├── api/ -│ │ ├── properties.py -│ │ ├── events.py -│ │ ├── signals.py -│ │ ├── chat.py -│ │ ├── uploads.py -│ │ ├── webhooks.py # slack, debug/trigger_event -│ │ └── sse.py # server-sent events for live UI updates -│ ├── services/ -│ │ ├── gemini.py # ALL Gemini calls go through here -│ │ ├── tavily.py -│ │ ├── entire.py -│ │ ├── pioneer.py -│ │ ├── aikido.py -│ │ ├── imap_poller.py -│ │ ├── slack_webhook.py -│ │ └── pdf_extractor.py -│ ├── pipeline/ -│ │ ├── worker.py # async event processor -│ │ ├── router.py # event → property routing -│ │ ├── extractor.py # Gemini extraction -│ │ ├── differ.py # fact diff + resolution rules -│ │ ├── applier.py # write facts, supersede old ones -│ │ └── renderer.py # facts → markdown -│ ├── signals/ -│ │ ├── evaluator.py # runs all rules -│ │ ├── drafter.py # Gemini writes proposed_action messages -│ │ └── rules/ -│ │ ├── recurring_maintenance.py -│ │ ├── lease_expiring.py -│ │ ├── late_payment.py -│ │ ├── regulation_change.py -│ │ └── cross_property_pattern.py -│ ├── db/ -│ │ ├── schema.sql # canonical schema (see Part VI) -│ │ ├── session.py -│ │ └── models.py # SQLAlchemy models -│ ├── scheduler.py # APScheduler jobs: IMAP poll, signal eval, Tavily cron -│ └── tests/ -│ ├── test_pipeline_happy_path.py # MANDATORY -│ ├── test_router.py -│ ├── test_extractor.py -│ ├── test_differ.py -│ └── test_signals.py -├── mcp_server/ -│ ├── main.py -│ ├── tools.py -│ └── README.md # Claude Desktop install instructions -├── mock_erp/ -│ ├── main.py -│ └── data.json # edited by hand during demo -└── seed/ - ├── seed.py # populates 4 properties with history - └── realistic_data.py # pre-generated realistic content -``` - -## Processing Pipeline (Critical Path) - -Every event flows through a single async worker: - -1. **Route** — match property by regex/fuzzy over name + aliases. Unmatched → unrouted inbox. -2. **Extract** — Gemini Flash with JSON schema → `{category, priority, facts_to_update[], summary}`. -3. **Diff** — for each proposed fact, compare with current. Resolution: PDF > ERP > email > Slack; higher confidence wins; newer wins. -4. **Apply** — insert fact with `source_event_id`, supersede old ones. -5. **Render** — regenerate markdown (cached per property). -6. **Signal** — run rule set against updated property + portfolio. -7. **Embed** — event + new facts into pgvector. - -**Target latency: under 10 seconds end-to-end.** Achieve this by keeping prompts tight and avoiding more than one Gemini call per event on the hot path. - -## Idempotency Rule -Processing the same event twice **must not** double-insert facts. Use `source_event_id` deduplication. - ---- - -# PART VI — DATABASE SCHEMA (canonical) - -```sql --- Enable pgvector -CREATE EXTENSION IF NOT EXISTS vector; - -CREATE TABLE buildings ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - address TEXT NOT NULL, - year_built INT, - metadata JSONB DEFAULT '{}'::jsonb, - created_at TIMESTAMPTZ DEFAULT now() -); - -CREATE TABLE owners ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name TEXT NOT NULL, - email TEXT, - phone TEXT, - preferences JSONB DEFAULT '{}'::jsonb -); - -CREATE TABLE properties ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name TEXT NOT NULL, - address TEXT NOT NULL, - aliases TEXT[] DEFAULT '{}', -- for routing: ["4B", "Apt 4B", "Berliner 4B"] - owner_id UUID REFERENCES owners(id), - building_id UUID REFERENCES buildings(id), - metadata JSONB DEFAULT '{}'::jsonb, - created_at TIMESTAMPTZ DEFAULT now() -); - -CREATE TABLE tenants ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - property_id UUID REFERENCES properties(id) ON DELETE CASCADE, - name TEXT NOT NULL, - email TEXT, - phone TEXT, - move_in_date DATE, - metadata JSONB DEFAULT '{}'::jsonb -); - -CREATE TABLE contractors ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - name TEXT NOT NULL, - specialty TEXT, - rating FLOAT, - contact JSONB DEFAULT '{}'::jsonb -); - -CREATE TABLE relationships ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - from_type TEXT NOT NULL, -- 'property' | 'owner' | 'building' | 'tenant' | 'contractor' - from_id UUID NOT NULL, - to_type TEXT NOT NULL, - to_id UUID NOT NULL, - relationship_type TEXT NOT NULL, -- 'owned_by' | 'in_building' | 'serviced_by' | 'occupied_by' - metadata JSONB DEFAULT '{}'::jsonb -); -CREATE INDEX idx_rel_from ON relationships(from_type, from_id); -CREATE INDEX idx_rel_to ON relationships(to_type, to_id); - -CREATE TABLE events ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - source TEXT NOT NULL, -- 'email' | 'slack' | 'pdf' | 'erp' | 'web' | 'debug' - source_ref TEXT, -- message-id, filename, etc. (used for idempotency) - property_id UUID REFERENCES properties(id), - raw_content TEXT NOT NULL, - metadata JSONB DEFAULT '{}'::jsonb, - received_at TIMESTAMPTZ DEFAULT now(), - processed_at TIMESTAMPTZ, - processing_error TEXT, - embedding vector(768), - UNIQUE (source, source_ref) -); -CREATE INDEX idx_events_unprocessed ON events (received_at) WHERE processed_at IS NULL; -CREATE INDEX idx_events_property ON events (property_id, received_at DESC); - -CREATE TABLE facts ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - property_id UUID REFERENCES properties(id) ON DELETE CASCADE, - section TEXT NOT NULL, -- 'overview' | 'tenants' | 'lease' | 'maintenance' | 'financials' | 'compliance' | 'activity' | 'patterns' - field TEXT NOT NULL, - value TEXT NOT NULL, - source_event_id UUID REFERENCES events(id), - confidence FLOAT NOT NULL, - valid_from TIMESTAMPTZ DEFAULT now(), - valid_to TIMESTAMPTZ, - superseded_by UUID REFERENCES facts(id), - created_at TIMESTAMPTZ DEFAULT now(), - embedding vector(768) -); -CREATE INDEX idx_facts_current ON facts (property_id, section, field) WHERE superseded_by IS NULL; - -CREATE TABLE signals ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - property_id UUID REFERENCES properties(id), - type TEXT NOT NULL, -- rule name - severity TEXT NOT NULL, -- 'low' | 'medium' | 'high' | 'urgent' - message TEXT NOT NULL, - evidence JSONB DEFAULT '[]'::jsonb, -- list of event_ids/fact_ids supporting this signal - proposed_action JSONB, -- {type, payload, drafted_message} - status TEXT DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected' | 'resolved' - created_at TIMESTAMPTZ DEFAULT now(), - resolved_at TIMESTAMPTZ -); -CREATE INDEX idx_signals_pending ON signals (created_at DESC) WHERE status = 'pending'; - -CREATE TABLE approval_log ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - signal_id UUID REFERENCES signals(id), - user_id TEXT DEFAULT 'demo_user', - decision TEXT NOT NULL, -- 'approved' | 'rejected' | 'edited' - edits JSONB, - created_at TIMESTAMPTZ DEFAULT now() -); - -CREATE TABLE outbox ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - signal_id UUID REFERENCES signals(id), - channel TEXT NOT NULL, -- 'email' | 'slack' - recipient TEXT NOT NULL, - subject TEXT, - body TEXT NOT NULL, - sent_at TIMESTAMPTZ DEFAULT now() -); -``` - ---- - -# PART VII — GEMINI EXTRACTION (canonical) - -All extraction goes through `backend/services/gemini.py` with this schema + prompt. - -```python -EXTRACTION_SCHEMA = { - "type": "object", - "properties": { - "category": { - "type": "string", - "enum": ["maintenance", "lease", "payment", "complaint", - "compliance", "tenant_change", "owner_communication", "other"] - }, - "priority": {"type": "string", "enum": ["low", "medium", "high", "urgent"]}, - "facts_to_update": { - "type": "array", - "items": { - "type": "object", - "properties": { - "section": { - "type": "string", - "enum": ["overview", "tenants", "lease", "maintenance", - "financials", "compliance", "activity", "patterns"] - }, - "field": {"type": "string"}, - "value": {"type": "string"}, - "confidence": {"type": "number", "minimum": 0, "maximum": 1} - }, - "required": ["section", "field", "value", "confidence"] - } - }, - "summary": {"type": "string"} - }, - "required": ["category", "priority", "facts_to_update", "summary"] -} - -EXTRACTION_PROMPT = """You are processing an event for a property management context system. - -Property: {property_name} -Current relevant context: -{current_context_excerpt} - -New event from {source}: ---- -{raw_content} ---- - -Extract structured facts. Rules: -- `section` + `field` must be specific and stable (e.g. `section=lease, field=end_date`, not `section=info, field=stuff`) -- `value` should be self-contained and human-readable -- `confidence` reflects certainty given the source -- If the event doesn't warrant updates (e.g. chit-chat), return empty `facts_to_update` -- Always return a one-line `summary` for the activity feed - -Return ONLY valid JSON matching the schema.""" -``` - ---- - -# PART VIII — MCP SERVER (canonical tool set) - -The MCP server is a thin adapter. All tools call the backend REST API. - -``` -get_property_context(property_id: str) -> str - Returns the rendered markdown for the property. - -search_properties(query: str, limit: int = 5) -> list[dict] - Semantic search across all properties. Returns [{id, name, snippet, score}]. - -list_signals(property_id: str | None = None, severity: str | None = None) -> list[dict] - Returns pending signals, optionally filtered. - -get_activity(property_id: str, since: str | None = None) -> list[dict] - Returns recent events on a property. - -propose_action(property_id: str, action: dict) -> dict - Creates a pending signal from an external AI. Returns {signal_id, status}. -``` - -`mcp_server/README.md` must include the exact Claude Desktop JSON config block so anyone (including judges) can install it in under a minute. - ---- - -# PART IX — SIGNAL RULES - -Start with these three for the demo, add two more if time permits. - -## Rule 1: `recurring_maintenance` (the demo hero) -SQL: for a given property, count maintenance facts with similar keywords (e.g. "heat%") in the past 120 days. If ≥3, fire. -Action draft: Gemini Pro composes an owner notification + contractor dispatch recommendation with specific timeline. - -## Rule 2: `lease_expiring` -SQL: lease `end_date` facts with value < `now() + 60 days` and no active renewal signal. -Action draft: renewal proposal to owner with rent adjustment suggestion based on market facts from Tavily enrichment. - -## Rule 3: `cross_property_pattern` (the portfolio-intelligence closer) -SQL across portfolio: bucket properties by building year (pre-1990, 1990-2010, post-2010) and count properties with same issue category in past 90 days. If ≥3 in a bucket, fire a portfolio signal. -Action draft: portfolio-wide inspection recommendation. - -## Rules 4-5 (stretch): `late_payment_anomaly`, `regulation_change` (powered by Tavily cron). - ---- - -# PART X — PHASED BUILD PLAN - -Each phase has an **explicit exit criterion**. Do not start phase N+1 until phase N is verified. - -## Phase 0 — Setup (Hours 0–3) -**Build:** -- `docker-compose.yml` with Postgres + pgvector -- FastAPI skeleton (`backend/`) -- MCP server skeleton (`mcp_server/`) -- Mock ERP (`mock_erp/`) -- `.env.example` with every key -- `db/schema.sql` (from Part VI, runnable) -- `seed/seed.py` — 4 properties with rich realistic history (use Gemini to pre-generate emails, lease content, maintenance history) -- Deploy to Railway: Postgres + backend + MCP. Public URL. - -**Exit criterion:** `GET /properties` on the public URL returns 4 seeded properties with rendered markdown that looks like a real product. - -## Phase 1 — Demo Spine (Hours 3–12) — MUST WORK -**Build:** -- IMAP poller (APScheduler, every 10s) with app password auth -- `POST /debug/trigger_event` as IMAP backup (critical for demo resilience) -- Event insertion with idempotency via `(source, source_ref)` unique constraint -- Worker: route → extract (Gemini Flash) → diff → apply → re-render -- `GET /properties/{id}/markdown` + SSE `/properties/{id}/events` for live updates -- Activity feed endpoint - -**Exit criterion:** send an email to the demo inbox → within 10s the UI (or `curl`) shows the updated markdown with a new fact sourced from that event. **DO NOT PROCEED UNTIL STABLE.** - -## Phase 2 — Sources + Enrichment (Hours 12–20) -**Build:** -- Slack webhook with signature verification -- PDF upload → `pdfplumber` extract → event pipeline -- Mock ERP poller (every 30s) -- Tavily enrichment on property creation (runs once) -- "Updated from web sources" badge on Tavily-sourced facts - -**Exit criterion:** all four sources flow through the pipeline. PDF upload visibly updates markdown. At least one fact on each property has a visible Tavily badge. - -## Phase 3 — Intelligence + Approval (Hours 20–30) -**Build:** -- Signal rules 1, 2, 3 -- Gemini Pro `drafter.py` that writes expert-quality `proposed_action` messages (see Signal Quality Bar) -- Approval inbox endpoints: list, approve, reject, edit -- Entire integration (or `EntireBroker` interface with local impl) -- Outbox writes on approve -- Approval log updates - -**Exit criterion:** trigger a signal → proposed action appears in approval inbox → approve → outbox row + signal resolved. All visible in UI. - -## Phase 4 — MCP + Portfolio Intelligence (Hours 30–38) -**Build:** -- MCP server with all 5 tools wired to backend -- `mcp_server/README.md` with Claude Desktop config block, tested live -- Cross-property signal rule -- Context graph endpoint: `GET /properties/{id}/graph` returns nodes + edges -- Portfolio banner endpoint - -**Exit criterion:** open Claude Desktop, ask "What's going on with apartment 4B?", get a correct answer sourced from Keystone. Portfolio view shows at least one cross-property signal. - -## Phase 5 — Polish + Sponsor Visibility (Hours 38–44) -**Build:** -- Regulation watcher (Tavily cron) + signal rule 4 -- Aikido scan + badge -- Pioneer learning dashboard (approval-rate stats) -- Polish UI in Lovable -- Final seed data pass — ensure portfolio view is vivid -- Gradium voice briefing **only if everything above is solid** - -**Exit criterion:** every partner tool is visible somewhere in the demo flow. Settings page shows security + learning dashboards. - -## Phase 6 — Demo Lock (Hours 44–48) -**Build nothing new.** -- Rehearse 2-minute pitch 5+ times -- Test full demo flow 10x with real email from phone -- Record backup video -- Seed "starter signals" so portfolio is visibly alive at demo start -- Prepare 5 Q&A answers (how does it scale, what about privacy, what's the business model, how accurate is extraction, what happens when it's wrong) -- Sleep 4 hours minimum - -**Exit criterion:** 10 consecutive successful demo runs. Backup video saved. Laptop on charger. You are calm. - ---- - -# PART XI — CODE STANDARDS (enforce from line 1) - -- **Python 3.11+**, type hints everywhere. -- **Pydantic** for all schemas including Gemini structured outputs. -- **`ruff` + `mypy --strict`** pass before every commit. Enforce in `pyproject.toml`. -- **No global state.** Dependencies injected via FastAPI `Depends`. -- **Docstrings** on every service function: what it does, inputs, outputs, side effects. -- **Structured logging** with `structlog`. Every LLM call logs prompt hash + latency + token count. Judges notice production-grade logs. -- **Idempotent event processing.** Unique constraint on `(events.source, events.source_ref)`. -- **One integration test is mandatory:** `test_pipeline_happy_path.py` — insert email event → assert fact created with correct source linkage → assert markdown contains new fact. This test protects the demo. -- **Secrets only via env.** Never commit keys. `.env.example` lists all required keys with dummy values. -- **No dead code.** If a file isn't imported, delete it. Clean repo is a winning repo. - ---- - -# PART XII — RISK MITIGATION - -## Demo-day risks and counters - -| Risk | Counter | -|---|---| -| IMAP polling fails on venue Wi-Fi | `POST /debug/trigger_event` to inject the email payload directly | -| Gemini API slow/down | Cache last successful extraction per event type; fallback to rule-based extraction for demo emails | -| Claude Desktop config broken | Pre-recorded 20-second MCP demo in backup video | -| Lovable UI crashes | Keep a static HTML fallback of the property page | -| Live demo freezes | Backup video with voiceover, ready in <5 seconds | -| Aikido scan fails | Screenshot of passing scan from earlier run | - -## Demo stability checklist (hour 46) -- [ ] 10 consecutive `trigger_event` runs succeed in <10s each -- [ ] 10 consecutive real-email runs succeed in <15s each -- [ ] MCP works from Claude Desktop three times in a row -- [ ] Signal fires on cue with the pre-seeded "heating" events -- [ ] Backup video recorded and saved to two locations (laptop + cloud) -- [ ] Phone fully charged for email-sending -- [ ] Demo laptop on power, external display tested - ---- - -# PART XIII — `DECISIONS.md` PROTOCOL - -Every time you make a judgment call (picked one tech over another, mocked something, deferred a feature, chose a threshold), append to `DECISIONS.md`: - -``` -## [timestamp] - [short title] -Context: <1 sentence> -Decision: -Reason: -Revisit if: -``` - -This document becomes invaluable during Q&A. It also prevents oscillation across sessions. - ---- - -# PART XIV — CURRENT PHASE - -**[UPDATE THIS AT THE END OF EVERY SESSION]** - -**Current phase:** Phase 12 — Materialized property/building/liegenschaft files (**SHIPPED**; tag `phase-12-complete`). Phases 8 → 9 → 10 → 11 → 12 all closed; deployed live to Cloud Run revision `keystone-be-00019-kpn`. -**Next deliverable:** Phase 13 — frontend wiring of the materialized-file feed. Default candidates: poll `/property_files/changes` for the live update bell; render `content_md` directly when the structured `/file` view is empty (replaces the "Extraction in progress" fallback); deferred Phase 12 items — diff endpoints (`/property_files/{id}/history`), per-tier `/changes` feeds for buildings/liegenschaften, hero-property repoint on Cloud Run. -**Blockers:** None. - -**Phase 12 results (verified live, all six steps shipped, deployed to Cloud Run):** -- **Three new materialized tables** added in additive migration `0011_materialized_files`: `property_files` (PK `property_id`), `building_files` (PK `building_id`), `liegenschaft_files` (PK `liegenschaft_id`). Each row carries `content_md TEXT NOT NULL`, `fact_count INT`, `last_rendered_at TIMESTAMPTZ`, `trigger_event_id UUID`, `trigger_scope TEXT`, `trigger_summary TEXT`, `generation_version INT`. Indexes on `last_rendered_at DESC` per table for the `/changes` feeds. -- **Materializer module** (`backend/pipeline/materializer.py`) wraps the existing renderer (`render_markdown`, `render_building_markdown`, `render_liegenschaft_markdown`). Three async `materialize_*` upserts; one public fan-out helper `propagate_after_fact_write(session, ...)` operating in the caller's transaction; `materialize_all(session)` for the bootstrap path; sync wrapper `run_materialize_all()` for CLI use. -- **Propagation rule** (KEYSTONE invariant — fact writes and dependent file rows share one transaction): - - `property_id` set → property's file refreshed. - - `building_id` set → building's file refreshed AND every property under it gets `trigger_scope='building'`. - - `liegenschaft_id` set → WEG's file refreshed AND every building + every property under it gets `trigger_scope='liegenschaft'`. -- **Hooked fact-write paths** (every site that writes to `facts` calls `propagate_after_fact_write` before commit): `backend/pipeline/applier.py:apply` (LLM extractor batch), `backend/pipeline/structured_extractors.py:_write_or_supersede_fact` (bank/invoice deterministic facts at any tier), `backend/pipeline/worker.py` activity insert, `backend/api/properties.py:edit_fact` (operator override), `backend/api/admin.py` (rejection-override + uncertainty-resolve), `backend/services/tavily.py:enrich_property` (web facts). -- **Read endpoints**: - - Existing `GET /properties/{id}/markdown`, `GET /buildings/{id}/markdown`, `GET /liegenschaften/{id}/markdown` now read materialized rows first, fall back to live render on cache miss. - - New `GET /property_files/{property_id}` — full row shape. - - New `GET /property_files/changes?since=&limit=N` — recent regenerations across the portfolio, ordered by `last_rendered_at DESC`, joined with property name. Default limit 50, max 200. URL-encode the `+` in `+00:00` (or use `Z` suffix). - - New `GET /buildings/{id}/file`, `GET /liegenschaften/{id}/file` — full row shape per tier. -- **CLI bootstrap**: `python -m connectors.cli materialize-all` renders every property/building/liegenschaft and upserts the three tables. Idempotent. Used at Phase 12 backfill time and as the sole local recovery path if cache rows are deleted. -- **Cloud Run deploy**: revision `keystone-be-00019-kpn` (2026-04-26), 100% traffic. Migration auto-applied via Dockerfile `apply_all()` startup call. New endpoint `POST /admin/materialize-all` — operational HTTP equivalent of the CLI, used because the CLI can't reach Cloud SQL directly (Unix socket binding); idempotent. - -**Phase 12 verification (all gates passed):** -- VERIFY 2 (local bootstrap): `materialize-all` → `53 properties / 16 buildings / 1 liegenschaft`. Hero (`509393da`) materialized at 62,523 chars / 175 facts; median ~2,000 chars. -- VERIFY 3 (per-tier propagation): synthetic property fact → 1 row, scope=`property`. Synthetic building fact → 1 building_file + 18 property_files, **all 18 carrying same `trigger_event_id` and `trigger_scope='building'`**. Synthetic liegenschaft fact → 1 WEG_file + 3 building_files + **52 property_files**, all carrying same `trigger_event_id` and `trigger_scope='liegenschaft'`. -- VERIFY 4 (read endpoints): `GET /property_files/{hero}` returned full row + 62,523-char content_md; `GET /property_files/changes?since=<1h ago>&limit=10` returned 10 ordered rows; building-fact cascade visible as 1 building + 18 property entries with matched `trigger_event_id`. -- VERIFY 5 (deployed): Cloud Run `POST /admin/materialize-all` → `56 / 6 / 1`. `GET /property_files/36b4a9ee-…` returned 17 facts + 3,814-char substantive content_md (Stammdaten + Overview + sourced facts). `/changes` feed live. - -**Phase 12 curl patterns (against deployed URL):** -``` -URL=https://keystone-be-782665688317.europe-west10.run.app -# Bootstrap (one-shot after migration lands) -curl -X POST $URL/admin/materialize-all -# Single property file -curl $URL/property_files/ -# Recent changes feed (URL-encode the +) -curl "$URL/property_files/changes?since=2026-04-26T08:00:00Z&limit=20" -# Building / WEG materialized rows -curl $URL/buildings//file -curl $URL/liegenschaften//file -``` - -**Phase 11 results (verified live, complete):** -- **Operator fact override**: `PATCH /properties/{id}/facts/{fact_id}` inserts a new fact row with `human_edited=true`, supersedes the original, preserves `source_event_id` for the trace, fires SSE notification. Differ honors `human_edited` against future extractor proposals (skipped with reason `preserved_human_edit`). Migration 0009 added `facts.human_edited`, `edited_by`, `edited_at`. Frontend: hover-revealed pencil button on each fact (skipped on uncertainty rows); inline modal with autoFocus + character counter + change/empty guards; on save invalidates `property-file`, `properties`, `property-markdown` queries. -- **Stammdaten + WEG/Building Context in `/file` view**: Phase 12-adjacent bridge work — the structured `GET /properties/{id}/file` endpoint now emits a Stammdaten section (from `properties.metadata` + tenant master record) and a WEG/Building Context section (from `_recent_events_for_scope`) when the property has them, so a property with 0 extracted facts no longer renders as "Extraction in progress" — the master record + parent-tier activity show up instead. -- **Renderer bugfix surfaced by Phase 12**: `_fetch_facts_by_scope` was missing `occurred_at` on FactRow construction (silent bug since the time-bucketing change). Added two lines (select `e.received_at AS occurred_at`, pass through). Property markdown was unaffected; building/liegenschaft renders crashed on first call. Detected when `materialize-all` exercised all three render paths. - -**Phase 10 results (verified live, all five priorities shipped):** -- **10.2 reprocessing engine** — `backend/services/replay.py`. asyncio.Event pause/resume/stop, Postgres-durable progress (`replay_runs` table, migration 0007), `scheduled_pauses` for validator-beat checkpoints, `reset_property=True` wipes facts/uncertainties/rejections but preserves stammdaten. Six admin endpoints + `POST /admin/demo/replay` thin wrapper reading `KEYSTONE_DEMO_HERO_PROPERTY`. -- **10.3 onboarding view** — `GET /admin/properties/{id}/onboarding`, `backend/services/onboarding.py`. Five sections: stammdaten + counts (deterministic), open issues right now (deterministic), 5–7 bullet Gemini Pro briefing with `Gap:` / `Lücke:` markers in the property's language (cached on `properties.metadata.onboarding` keyed by latest fact/uncertainty/rejection timestamps), recurring-pattern watch, per-section pointer index. Live VERIFY (WE 29) — German briefing leads with urgent water leak, uses `Lücke:` for the vague rent uncertainty. -- **10.4 document linking** — `backend/api/files.py` + `backend/api/source_links.py`. `GET /files/` is realpath + commonpath protected (rejects absolute paths, NUL bytes, `..` escapes, symlink escapes — 9 tests). `GET /events/{id}/source` smart-redirects: invoice/letter PDFs → `/files/`, email → `/raw`, bank → `/detail`. Renderer + onboarding emit real URLs in every fact-source link instead of dead anchors. -- **10.6 trust-layer write surface** — `POST /admin/uncertainties/{id}/resolve` with `promote_to_fact` (writes fact at relevant_section/field, links via `resolved_to_fact_id`) or `dismiss`, both audit-logged. Verified existing `POST /admin/rejected/{id}/override` end-to-end. Surfaced a latent schema bug (Phase 9.2 INSERTs referenced columns Phase 5 schema didn't have); fixed via migration 0008_approval_log_generic. -- **IMAP verification** — 4 tests in `backend/tests/test_imap_ingestion.py`. `_ingest` parses real Buena German .eml (multipart, charset, umlauts), idempotent on Message-ID, `poll_once` is a safe no-op without creds. Transport gap (the `imapclient.IMAPClient` fetch loop itself) is documented in DECISIONS.md. - -**Phase 10 quality gates:** -- Full suite: **82 passed, 1 skipped** (4.1× the Phase 6 suite size). -- 30 new tests across replay, onboarding, file safety, source-link dispatch, trust actions, and IMAP path. -- Live render against hero property (WE 29) reads as a 60-second briefing in native German with honest gap-flagging. - -**Phase 8.1 Step 3b results (verified live):** -- Three-tier routing: 1417 events → property (78.2%), 0 → building, 383 → liegenschaft (21.1%), **13 truly unrouted (0.7%)** vs the 396 from Step 3a. -- All four miss-rate targets met: - - property-level miss rate **2.0%** (13/637 miete events) — target < 5% ✓ - - building-level miss rate **0%** (no per-Haus events in Buena's data) — target < 10% ✓ - - liegenschaft-level miss rate **0%** (all 383 WEG events routed) — target < 15% ✓ - - true unrouted **0.7%** (13/1813) — target < 3% ✓ -- 6/6 routing tests pass (`backend/tests/test_routing.py`). -- 54 of 55 tests passing (1 expected skip on the legacy Berliner integration test). -- Markdown spot-check: property markdown shows Financials + WEG Context block with 5 most recent WEG invoices, all source-linked. WEG markdown lists `liegenschaft_financials` (versorger / dienstleister / sonstige paid + received) and `liegenschaft_maintenance` (last contractor invoice). Building markdown shows WEG Context. -- Idempotency: re-running every backfill + re-route → 0 new events, 0 new facts. -**Last session notes (Phase 1):** -- `backend/services/gemini.py` is the single choke-point. Uses structured output (the Part VII JSON schema), 3× retries with backoff, and logs prompt hash + latency + token counts on every call. Raises `GeminiUnavailable` when `GEMINI_API_KEY` is unset or requests fail. -- `backend/pipeline/extractor.py` calls Gemini Flash when available, otherwise a deterministic keyword-based fallback (heating/leak/payment/lease/compliance) so the demo survives wifi/quota loss (Part XII mitigation). -- `backend/pipeline/router.py` resolves events to properties via alias substring match first (longest wins) and token-overlap fallback. Unrouted events are parked with `processing_error='unrouted'`. -- `backend/pipeline/differ.py` enforces source precedence (pdf > erp > email > slack > web > debug), confidence, and recency before returning a `DiffPlan`. -- `backend/pipeline/applier.py` writes new fact rows and stamps `superseded_by` on displaced predecessors. -- `backend/pipeline/events.py` owns idempotent event insertion (ON CONFLICT on `(source, source_ref)`) plus an in-process `EventBus` for SSE fan-out. -- `backend/pipeline/worker.py` uses `SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1` per tick, then routes → extracts → diffs → applies → stamps `processed_at` → publishes to the event bus. Errors are isolated in a fresh session so the lock is released cleanly. -- `backend/scheduler.py` runs the worker every 2s and IMAP poll every 10s via APScheduler, started in the FastAPI lifespan. -- `backend/services/imap_poller.py` polls unread messages and ingests each as an event (idempotent via RFC822 Message-ID). No-ops cleanly when `IMAP_PASSWORD` is the placeholder. -- `backend/api/events.py` exposes `POST /debug/trigger_event` as the demo-resilience path — inserts the event and drains the worker inline so `curl` POSTs return with updated markdown visible. Idempotent on `source_ref`. -- `backend/api/sse.py` exposes `GET /properties/{id}/events` with `text/event-stream` and a 15s heartbeat; `backend/api/properties.py` adds `GET /properties/{id}/activity`. -- `backend/tests/test_pipeline_happy_path.py` ingests an email event, runs the worker, asserts a sourced fact was written and shows up in the rendered markdown. Protects the demo. -- `seed/seed.py` now stamps `processed_at = received_at` on seeded events so the worker doesn't re-extract the hand-crafted dataset on boot. -- Local self-verify: `/health` → `/debug/trigger_event` → markdown update in **~25ms** (target 10 s). 10 consecutive trigger runs all under 25ms. SSE stream delivers a `fact_update` payload when a new event is processed. Integration test passes (`pytest backend/tests/test_pipeline_happy_path.py`). - -**Phase 2 session notes:** -- `mock_erp/main.py` is a one-file FastAPI service on `:8001` that re-reads `data.json` every request — edit the JSON live during the demo to fake a new payment. `GET /payments` supports `account` + `since` filters. -- `backend/services/erp_poller.py` drains that endpoint every 30s via APScheduler, inserting each payment row as an `erp` event keyed on `payment_id` (UNIQUE constraint enforces idempotency). -- `backend/services/pdf_extractor.py` wraps `pdfplumber` with a max-pages cap; `backend/api/uploads.py` exposes `POST /uploads/pdf` (multipart) with `source_ref = {filename}:{sha256[:16]}` for dedupe and an inline worker drain. -- `backend/services/slack_webhook.py` implements the canonical `v0:{ts}:{body}` HMAC-SHA256 verification with a 5-minute replay window; `backend/api/webhooks.py` mounts `POST /webhooks/slack` and answers the `url_verification` challenge. Bad signature → 401. -- `backend/services/tavily.py` wraps the `tavily-python` client and, on enrichment, writes the web event + two sourced facts (`overview.market_snapshot`, `compliance.regulation_watch`) in one transaction so the 🌐 badge is always present. Offline fallback kicks in when `TAVILY_API_KEY` is missing or errors, with a clearly-labelled "offline snapshot" value — the demo badge stays up on flaky wifi (Part XII mitigation). -- `backend/api/properties.py` now exposes `POST /properties` (creates + enriches) and `POST /properties/{id}/enrich` (idempotent admin utility for existing seeded rows). -- `backend/pipeline/renderer.py` joins facts with events to surface `source` and appends a 🌐 _Updated from web sources_ badge next to every web-sourced fact. -- `backend/scheduler.py` now runs three jobs: worker (2s), IMAP poll (10s), ERP poll (30s). -- Phase-2 self-verify: all four sources (email, Slack, PDF, ERP) land in the pipeline and show up in the activity feed for Apt 4B; every property has ≥2 web-badged facts after enrichment; Slack webhook 401s on bad signature; PDF upload turns into a fact within ~100ms; Phase 1 regression test still passes. - -**Phase 3 session notes:** -- `backend/signals/types.py` defines `SignalCandidate` (rule output) and `ProposedAction` (persisted JSONB on `signals.proposed_action`). -- `backend/signals/rules/recurring_maintenance.py` fires `urgent` per-property signals when ≥3 maintenance facts match `heat|boiler|water|leak|electric` keywords within 120 days. -- `backend/signals/rules/lease_expiring.py` parses `lease.end_date` values and fires `medium/high` signals when the end date is within 60 days (threshold constant so demo can widen it). -- `backend/signals/rules/cross_property_pattern.py` implements both demo beats: shared-building boiler signal (beat 1:00 "wow") and building-year-cohort portfolio signal (beat 1:45). Portfolio signals use `property_id=NULL`. -- `backend/signals/evaluator.py` runs every rule, dedupes against already-pending signals keyed on `(property_id, type, payload.hint.{topic|subtype})`, asks the drafter for a `ProposedAction`, and inserts into `signals`. Scheduler runs it every 30s; `POST /signals/evaluate` fires it on demand for demo determinism. -- `backend/services/gemini.py` gained a Pro `draft_action_message` path with 2x retries; `backend/signals/drafter.py` prefers it and falls back to a four-part template (observation → risk → concrete next step → deadline) so the Signal Quality Bar holds without Gemini. -- `backend/services/entire.py` ships a `runtime_checkable Protocol` + `LocalEntireBroker` that writes outbox rows. `get_broker/set_broker` let the real Entire SDK drop in without touching the signals API. -- `backend/api/signals.py` exposes `GET /signals`, `GET /signals/{id}`, `POST /signals/evaluate`, `POST /signals/{id}/approve|reject|edit`. Approve routes through `get_broker()`, writes `outbox` + `approval_log` (decision=`approved`), and flips status to `resolved`. Edit persists the subject/body diff into `approval_log` (decision=`edited`) for Pioneer's learning stats later. -- Phase-3 self-verify: evaluator fires 3 signals (recurring_maintenance × 2 + shared-boiler cross), repeat calls create 0 (dedupe OK), approve → outbox row + `approval_log` entry + `signals.status='resolved'`, reject writes log + status='rejected', edit writes `approval_log(decision='edited')` with before/after diff. Phase 1 integration test still green. - -**Phase 4 session notes:** -- Backend gained three new endpoints: `GET /properties/search?q=…` (multi-term weighted keyword search), `GET /properties/{id}/graph` (nodes + edges — owner, building, tenants, contractors), `GET /portfolio/banner` + `GET /portfolio/summary` (dashboard header + top-priority portfolio signal), and `POST /signals/propose` (external AI entry point that always writes `status='pending'` — humans approve in the inbox). -- `mcp_server/tools.py` wraps `httpx.AsyncClient` and pokes the REST backend (overridable via `KEYSTONE_BASE_URL`). Zero DB imports — Part V's "thin adapter" rule upheld. -- `mcp_server/main.py` registers the five canonical Part VIII tools (`get_property_context`, `search_properties`, `list_signals`, `get_activity`, `propose_action`) on a `FastMCP` instance. `python -m mcp_server.main` speaks the MCP stdio protocol. -- `mcp_server/README.md` ships a copy-pasteable Claude Desktop `claude_desktop_config.json` snippet + a smoke-test recipe. -- Phase 4 self-verify: all five MCP tools succeed end-to-end against a running backend, including a real stdio `initialize` → `list_tools` → `call_tool` handshake. Portfolio banner returns the shared-boiler cross-property signal. Search + graph endpoints return expected shapes. `POST /signals/propose` appears in the inbox tagged as AI-authored. - -**Phase 5 session notes:** -- `backend/services/tavily.py` gained `watch_regulations()` — polls Tavily for five rent-regulation queries when `TAVILY_API_KEY` is live, otherwise seeds three clearly-labelled offline headlines. Every event stamped `processed_at` so the extractor worker skips it; idempotent via `source_ref = tavily-reg:{query}:{hour}`. -- `backend/signals/rules/regulation_change.py` is rule #4. Portfolio-level (`property_id=NULL`), `medium` severity, reads `web` events tagged `metadata.regulation=true` inside a 14-day window. -- Evaluator + drafter + subject-line picker updated to recognize the new type; dedupe keys on `payload.hint.subtype = source_ref` so each distinct headline fires at most one pending signal. -- `backend/services/aikido.py` ships `get_badge()` — live Aikido REST when keyed, otherwise a `local_snapshot` badge carrying the current git SHA from `git rev-parse --short HEAD`. Response discloses `source` so the UI can honestly distinguish live vs fallback. -- `backend/services/pioneer.py` ships `compute_learning()` — reads `approval_log`, derives per-signal-type approval rates (edits = 0.8 × approved), maps to `[0.5, 1.5]` priority weights with sample-size shrinkage, emits a trend-line sentence suitable for the Settings > Learning panel. -- `backend/api/settings.py` exposes `GET /settings/security`, `GET /settings/learning`, and `POST /settings/regulation_watch` (manual trigger that runs the watcher + evaluator inline so fresh signals show up in the inbox immediately). -- `backend/scheduler.py` adds the `regulation_watch` job at 60-minute cadence; `backend/main.py` mounts the settings router. -- Phase 5 self-verify: `POST /settings/regulation_watch` → 3 events ingested + 3 regulation_change signals created; repeat calls → 0/0 (dedupe OK); `/settings/security` returns `passing` with commit SHA; `/settings/learning` produces a rich snapshot with trend line "Keystone is prioritizing **cross property pattern** based on your approval behavior (100% approved over 2 proposals)" after a mix of approve/edit/reject decisions. Phase 1 regression test still green. - -**Phase 6 session notes:** -- Added `seed/demo_bootstrap.py` — one-shot script that wipes a fresh DB to a visibly-alive demo state: schema → seed → Tavily-enrich every property → run regulation watcher → fire evaluator. Idempotent; safe to re-run between rehearsals. -- Added `DEMO_QA.md` — written answers to the five Part XII judge questions (scale, privacy, business model, extraction accuracy, what happens when it's wrong), each grounded in repo paths so we can show the file behind the answer. -- Phase XII stability checklist (automatable rows): - - **10× `/debug/trigger_event`** — 10/10 under 10 s; avg **24 ms**, max **64 ms**. - - **3× MCP stdio handshake** — 3/3 clean, all under **250 ms**, every run lists 5 tools and a `search_properties` call returns live JSON. - - **Signal fires on cue** — bootstrap → 6 pending signals (4 portfolio-level), portfolio banner returns the urgent shared-boiler signal. - - **Sponsor visibility** — every property has 2-4 🌐 web-badged facts, Aikido `passing` with current commit SHA, Pioneer trend line goes from neutral → "prioritizing cross_property_pattern" after one approval. - - **Phase 1 integration test** — passes in 0.17 s. -- Remaining checklist rows are human work: backup video, real-email run from a phone, calm pitch rehearsal, laptop on charger. - ---- - -# PART XV — NON-NEGOTIABLES - -Before submitting: - -1. ✅ 2-minute demo works end-to-end on real Wi-Fi. -2. ✅ Backup video exists. -3. ✅ At least 5 partner tools visible in the demo. -4. ✅ MCP works with Claude Desktop, live. -5. ✅ Every fact in the markdown has a clickable source. -6. ✅ No feature outside demo scope shipped. -7. ✅ Repo is clean: `ruff` + `mypy --strict` pass, no dead code, README explains setup in 5 steps. -8. ✅ `DECISIONS.md` reflects every non-obvious choice. - ---- - -# PART XVI — CONNECTOR ARCHITECTURE (Phase 8) - -Phase 8 introduces `connectors/` as the customer-agnostic ingestion -layer. **Buena is the first composer, not a special case.** Every new -customer integration is a new composite under `connectors/`; the -shape-handling primitives below are shared. - -## Contract - -Every connector satisfies one of these Protocols (`connectors/base.py`): - -```python -@runtime_checkable -class Connector(Protocol): - name: str - def pull(self) -> Iterator[ConnectorEvent]: ... - def stream(self) -> Iterator[ConnectorEvent]: ... -``` - -`ConnectorEvent` mirrors the keyword arguments of -`backend.pipeline.events.insert_event` so the call site is a one-liner. -Every event carries `source`, `source_ref`, `raw_content`, `metadata`, -`received_at`, and an optional pre-routed `property_id`. PDF-derived -events additionally carry `metadata.document_type` (Phase 9 constraints -read this). - -## Idempotency - -`(events.source, events.source_ref)` is `UNIQUE` (Part VI). Connectors -must produce the **same** `source_ref` on every re-run for the same -input. Concrete formulas: - -| Source | `source_ref` | -|---|---| -| Email (`.eml`) | `Message-ID` (fallback `sha256(From+Date+Subject)[:16]`) | -| Bank txn | `sha256(datum + betrag + verwendungszweck + buena_id)[:12]` | -| Invoice / letter PDF | `:` | -| Master data row | natural key (email / id / address) | - -## PII redaction at ingestion (not at render) - -`connectors/redact.py` is the **only** module that touches raw IBANs, -full phone numbers, or full email domains on the way *into* the -database. Every connector calls `redact.iban_last4`, `phone_last4`, -`email_redact`, or `scrub_text` before yielding a `ConnectorEvent`. -Tests assert no `r"DE\d{20}"` or full E.164 phone survives. - -PII contract: - -- IBAN → `****` (e.g. `****1349`) -- Phone → `+CC *** **` (country code preserved when present) -- Email → `@example.com` (local part kept; domain replaced) - -## Cost ledger - -Every LLM call charges `connectors/cost_ledger.py`. The ledger is a -durable Postgres table (`cost_ledger`, additive migration in -`connectors/migrations.py`) keyed on `source_label` so a single -`--max-total-cost-usd` cap governs the entire backfill across CLI -invocations. Subsequent runs read the persisted state and abort -immediately if the cap was already hit. Reset is friction-gated: -`--reset-cost-ledger` prompts `y/N`. - -Sub-labels share the same table — e.g. the PDF document-type -classifier (`pdf_doctype`) gets a `$2` sub-cap inside the broader -`buena_email` budget. - -## Composite layout - -`connectors/buena_archive.py` is the only module that knows Buena's -directory shape. It exposes `load_stammdaten(root)`, `iter_emails`, -`iter_bank`, `iter_invoices`, `iter_letters`, and -`iter_incremental_day(day)`. The next customer ships a sibling file -(`connectors/_archive.py`) and reuses the primitives. - -## Extending - -Adding a new customer: - -1. Verify their data shape — what files / formats / cardinalities. -2. Reuse existing primitives where possible - (`csv_stammdaten`, `eml_archive`, `camt_bank`, - `pdf_invoice_archive`, `pdf_letter_archive`). -3. Write a new composite `connectors/_archive.py`. -4. Add a `_archive` smoke test (skip when the dataset is - absent, like `connectors/tests/test_buena_archive.py`). -5. Wire a CLI subcommand under `connectors/cli.py` (Step 2+). - -## Three-tier ownership hierarchy (Phase 8.1) - -German property management models a three-tier hierarchy: - -``` -Liegenschaft (WEG) → Gebäude (Haus) → Einheit (unit / property) -``` - -Buena's dataset is **1 WEG → 3 Häuser → 52 units**. Events -billed at the WEG level (Hausgeld, Verwaltergebühr, shared -contractor invoices) belong to the Liegenschaft, not to a single -Haus or unit. Per-Haus events (e.g. roof repair) belong to the -building. Per-unit events (rent, individual maintenance) belong to -the property. - -Tables (`backend/db/schema.sql`): - -- `liegenschaften (id, name, buena_liegenschaft_id, metadata)` -- `buildings.liegenschaft_id` — FK -- `events.{property_id, building_id, liegenschaft_id}` — exactly one - set when routed; all three NULL for genuinely unrouted -- `facts.{property_id, building_id, liegenschaft_id}` — same shape - -Routing precedence in `backend/pipeline/router.route_structured`: - -1. `metadata.eh_id` → property -2. `metadata.mie_id` → tenant → property -3. `metadata.invoice_ref` → inherit attribution from a prior invoice -4. `metadata.haus_id` (or `HAUS-NN` in any text field) → building -5. Liegenschaft (WEG) when *any* of: - - `kategorie ∈ WEG_KATEGORIE` (`hausgeld | dienstleister | - versorger | sonstige`, with `hausgeld` only when no per-unit - ref upstream) - - free-text matches a WEG keyword (case-insensitive, - word-boundary): `Hausgeld | Verwaltergebühr | - Gemeinschaftskosten | Hausverwaltung | WEG | Sonderumlage | - Instandhaltungsrücklage | Kontoführungsgebühr` … - - `event_source == 'invoice'` (Buena invariant: every invoice in - the archive is a WEG bill) -6. Else `unrouted` with a precise reason string surfaced in - `GET /admin/unrouted`. - -The renderer follows the same hierarchy: - -- `GET /properties/{id}/markdown` ends with **Building Context** and - **WEG Context** subsections — most recent N events at the - parent tiers, source-linked. -- `GET /buildings/{id}/markdown` shows building-level facts + - **WEG Context**. -- `GET /liegenschaften/{id}/markdown` shows WEG-level facts. - -PII redaction (`connectors/redact.py`) still applies at every tier. - -A one-time `python -m connectors.cli re-route` walks events with no -scope set and re-evaluates routing using the current rules — used -once after the Phase 8.1 schema lands to retroactively populate -`building_id` / `liegenschaft_id` on already-ingested events. -Idempotent. - ---- - -# FINAL REMINDER - -Do not build the most complete system. Build the system that makes judges say: - -> **"This already feels like a real product."** - -Then stop. Then rehearse. Then win. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e7ff37f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pranav Mathad + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 03d3e94..5bb1e40 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,252 @@ # Keystone -> The operational brain for property management. Turns fragmented communication into a living, trusted context layer per property, and proactively surfaces signals for human approval. - -## Quick start (5 steps) - -1. **Clone + env** - ```bash - git clone keystone && cd keystone - cp .env.example .env - ``` - -2. **Python deps** (Python 3.11+ required) - ```bash - python -m venv .venv && source .venv/bin/activate - pip install -e ".[dev]" - ``` - -3. **Start Postgres + pgvector** - ```bash - docker compose up -d - ``` - -4. **Seed the demo dataset and apply migrations** (inserts properties and creates all required tables) - ```bash - python -m seed.seed - python -c "from connectors.migrations import apply_all; apply_all()" - ``` - -5. **Run the backend** - ```bash - uvicorn backend.main:app --reload - ``` - -## Verify - -```bash -curl http://localhost:8000/health -curl http://localhost:8000/properties -curl http://localhost:8000/properties//markdown +Keystone keeps one file per property for a property manager. It reads what +the manager already has (tenant email, bank statements, contractor invoices, +letters, the master-data spreadsheet), pulls the facts out, and writes each +one into the right property's file with a link to the message or document +it came from, a confidence score and its history. When it is not sure, the +item goes to a review inbox instead of the file. A few rules watch the files +for things worth acting on, such as a heating system that keeps failing or a +lease about to expire, and draft a message that a person has to approve +before it goes anywhere. + +I wrote the first version in a hackathon and have been cleaning it up since. +It runs without any API key: extraction falls back to a rule-based extractor +and signal drafts to templates. Give it a key and an LLM does the extraction, +answers questions about a property with citations, and drafts replies. + +| Portfolio | Property file | +|---|---| +| ![Portfolio](docs/img/portfolio.png) | ![Property file](docs/img/property-file.png) | +| **Approval inbox** | **Ask** | +| ![Approval inbox](docs/img/approval-inbox.png) | ![Ask](docs/img/ask-panel.png) | + +The screenshots are from a fresh `docker compose up` with no API key: the +sample data as it loads on first start, nothing added by hand. + +## How it works + +``` + email, bank CSV, PDFs, Slack, HTTP + | + v + connectors redact, then insert keyed on + | (source, source_ref); a re-run is a no-op + v + events (Postgres) Postgres is the queue + | + v + worker claims one row with SKIP LOCKED, then in + | one transaction: route, extract, diff, + | validate, apply, re-render the file + +--------+--------+ + | | + v v + facts and files review inbox + | + +----> REST API, SSE ----> React frontend + | \----> MCP server + | + +----> signal rules -----> approval inbox ----> outbox +``` + +A connector redacts IBANs, phone numbers and email domains before anything +is stored, and inserts the event keyed on `(source, source_ref)`, so +importing the same archive twice changes nothing. The worker claims events +with `FOR UPDATE SKIP LOCKED`; several workers can share one database and +there is no separate queue to run. + +For each event the worker looks for a property named in the text and marks +the event unrouted rather than guess. (The bulk email import also routes to +a building or an owners' association.) It extracts facts, diffs them +against what the file already says, runs eight rule constraints (a +building's address and year built never change, a rent change needs an +addendum, and so on) and, with a key, an LLM check for contradictions with +the current file. Anything under the confidence floor or flagged by a +constraint lands in the review inbox. A fact an operator edited by hand is +never overwritten. Old facts are kept and point at their replacement, so +the history of any field can be read back. The property's file is +re-rendered in the same transaction as the fact write, so nobody reads a +file that disagrees with its facts. + +Signals run on their own schedule over the current facts, so a slow rule +never holds up ingestion. A decision on a signal holds for a cooldown +period, so the same finding does not come back the next morning. + +The long version, with the data model and the concurrency story, is +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). Each non-obvious choice, the +alternatives that were rejected and the mistakes along the way are in +[docs/DECISIONS.md](docs/DECISIONS.md). + +## Running it + +You need Docker. + + cp .env.example .env + docker compose up + +Then: + + frontend http://localhost:8080 + API docs http://localhost:8000/docs + +The first start builds both images, applies the schema and loads the sample +data: 56 properties, and six tenant emails for the featured property (WE 29) +that go through the pipeline so its file has a history. All of it is +synthetic. Starting again is safe; every step is idempotent. + +To push an event through yourself: + + curl -X POST localhost:8000/debug/trigger_event \ + -H 'content-type: application/json' \ + -d '{"raw_content": "From: tenant@example.com\nSubject: Heizung\n\nDie Heizung in WE 29 ist ausgefallen."}' + +The property page picks the change up over the server-sent event stream. + +Without a key, extraction uses the rule-based path, signal drafts use +templates, and Ask and reply drafting return 503. To turn the LLM on, set +`GEMINI_API_KEY` in `.env`, or `LLM_PROVIDER=pioneer` and `PIONEER_API_KEY` +for an OpenAI-compatible gateway. Nothing else changes. + +## Running without Docker + +Python 3.11, Node 20 and Postgres 16. The compose file can provide just the +database, published on host port 5433 so it does not collide with one you +already run; the DSNs in `.env.example` point at it. + + docker compose up -d postgres + python3.11 -m venv .venv && source .venv/bin/activate + pip install -e ".[dev]" + (cd frontend && npm ci) + +Apply the schema and load the sample data, which is what the container +entrypoint does on start: + + python -m seed.seed + python -c "from connectors.migrations import apply_all; apply_all()" + EXTRACTED_ROOT=Extracted_demo python -m connectors.cli load-stammdaten --source buena + python -m connectors.cli materialize-all + python -m connectors.cli load-sample-events + +Then `./scripts/dev.sh` starts the API with reload on port 8000 and the Vite +dev server on 8080, and stops both on Ctrl-C. + +## Configuration + +Everything is read from the environment or `.env`. The example file lists +every variable with a comment, and the defaults are enough for a local run. +The ones worth knowing: + + DATABASE_URL asyncpg DSN; DATABASE_URL_SYNC is the psycopg2 one + LLM_PROVIDER gemini (default) or pioneer, and that provider's key + FEATURED_PROPERTY the property the UI opens first (default EH-029) + KEYSTONE_CORS_ORIGINS browser origins allowed to call the API + IMAP_HOST, IMAP_USER, mailbox to poll; the poller stays off until a + IMAP_PASSWORD real password is set + SLACK_SIGNING_SECRET the Slack webhook checks signatures once this is set + MOCK_ERP_URL payments feed to poll; empty turns the poller off + +## Tests and checks + +The Python tests need the Postgres from `docker compose up -d postgres` and +nothing else. API keys are blanked for every test, so a run never makes a +paid call, and a test that needs the private dataset skips and says so. + + pytest # backend, connectors, eval, mcp_server, scripts + cd frontend && npm test # Vitest + +`pre-commit install` adds ruff, prettier and a check that no real address, +IBAN or deployment URL gets committed. CI runs those plus mypy in strict +mode, ESLint, the TypeScript check, both test suites and the frontend +build, against an empty Postgres 16. See `.github/workflows/ci.yml`. + +## Evaluation + +The extractor is scored against 30 hand-labelled emails by +`python -m eval.runner --set emails_v1`. The LLM run and the keyless run +on the same set: + +| | Gemini | Rule-based, no key | +|---|---:|---:| +| Category accuracy | 73.3% | 63.3% | +| Routing accuracy | 93.3% | 93.3% | +| Fact extraction, micro F1 | 0.88 | 0.42 | +| Lease facts, F1 | 0.62 | 0.67 | +| Values matching the source wording | 3 of 26 | 0 of 11 | + +These are not numbers to leave unattended, and the set is too small to tell +two strong models apart. Lease precision is low because the model reads an +owner selling up as a tenant giving notice. Values come back paraphrased +rather than quoted. Nearly every LLM fact claims a confidence of 0.9 or +more while about one in five is in the wrong slot. The reports are +committed under `docs/eval-runs/` and discussed in +[docs/EVALUATION.md](docs/EVALUATION.md). Every number in this file is +traced to the command that produced it in +[docs/PROJECT_FACTS.md](docs/PROJECT_FACTS.md). + +## Command-line tools + +`python -m connectors.cli` loads master data and walks the bank, invoice and +email archives into events. The email backfill goes through the live +extraction pipeline, is resumable, and stops at a spend cap kept in a ledger +table (default $20), so a restart cannot double the bill. The archive +readers expect the private dataset under `Extracted/`, which is not in the +repository; `Extracted_demo/` holds synthetic master data and six sample +emails in the same shape. + +`python -m mcp_server.main` exposes five tools (property context, search, +pending signals, activity, propose an action) over MCP as a thin client of +the REST API. Install with `pip install -e ".[mcp]"` first. Wiring it into +Claude Desktop is described in [mcp_server/README.md](mcp_server/README.md). + +`uvicorn tools.mock_erp.main:app --port 8001` serves a stand-in payments +feed. Set `MOCK_ERP_URL=http://localhost:8001` to have the API poll it. + +## Layout + ``` +backend/ FastAPI app: api/, pipeline/, signals/, services/, db/ +connectors/ archive importers, redaction, cost ledger, migrations, CLI +eval/ ground truth, runner, metrics +mcp_server/ MCP adapter over the REST API +frontend/ React client; has its own README +seed/ schema bootstrap and hand-written sample data +scripts/ dev runner, container entrypoint, sensitive-data check, + demo-data synthesis, release helpers +tools/mock_erp/ stand-in ERP feed +docs/ architecture, decisions, evaluation, facts, eval runs +Extracted_demo/ synthetic master data and sample emails +``` + +Python side: FastAPI, SQLAlchemy 2 with asyncpg, pydantic, APScheduler, +structlog; pytest, ruff, mypy. Frontend: React 18, TypeScript, Vite, +TanStack Query, Tailwind, a few Radix primitives; Vitest. + +## Known problems + +There is no authentication. Do not put it on the internet as it is. + +Nothing is ever sent. An approved signal is written to an outbox table and +stops there. + +Scheduled jobs run in every API process, so with N instances the signal +evaluator and the pollers do their work N times. The worker itself is safe +to run in parallel. A leader lock would fix the rest. + +Redaction replaces the domain of an email address but keeps the local part, +so a name in an address survives. + +Bulk-imported emails skip the rule constraints and the contradiction check. +Live events get the full pipeline. + +Property search is keyword matching. The IMAP code is tested through +parsing real `.eml` files; the fetch loop against a live server is not. + +Extraction quality is measured on 30 emails, as above. + +The full list, with detail, is in +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#known-limitations). + +## License -See [KEYSTONE.md](KEYSTONE.md) for the project constitution and [DECISIONS.md](DECISIONS.md) for non-obvious calls. +MIT. See [LICENSE](LICENSE). diff --git a/backend/api/admin.py b/backend/api/admin.py deleted file mode 100644 index aae5623..0000000 --- a/backend/api/admin.py +++ /dev/null @@ -1,1339 +0,0 @@ -"""Admin surface — unrouted inbox, failed events, replay control. - -Step 3 ships ``GET /admin/unrouted`` so backfilled events that lacked -the IDs needed for routing surface as a real product UX (per Phase 8 -plan: this is *core* product, not demo polish). Steps 7 and 9 expand -the surface to include incremental-cursor controls and admin -overrides. -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any -from uuid import UUID - -import structlog -from fastapi import APIRouter, Depends, Query -from pydantic import BaseModel, Field -from sqlalchemy import text -from sqlalchemy.ext.asyncio import AsyncSession - -from backend.db.session import get_session -from backend.pipeline.materializer import ( - materialize_all, - propagate_after_fact_write, -) - -router = APIRouter(prefix="/admin", tags=["admin"]) -log = structlog.get_logger(__name__) - - -class UnroutedEvent(BaseModel): - """One row of the unrouted-inbox listing.""" - - event_id: UUID - source: str - source_ref: str | None = None - received_at: datetime - snippet: str = Field( - ..., - description="First ~120 chars of raw_content for human triage.", - ) - metadata: dict[str, Any] - suggested_alias: str | None = Field( - default=None, - description=( - "Best guess alias to look up — surfaces metadata.eh_id / mie_id / " - "invoice_ref so the operator knows what reference was tried." - ), - ) - - -class UnroutedResponse(BaseModel): - """Response envelope for ``GET /admin/unrouted``.""" - - total: int - by_source: dict[str, int] - events: list[UnroutedEvent] - - -def _suggested_alias(metadata: dict[str, Any]) -> str | None: - """Surface the strongest ID that the routing failed to resolve.""" - for key in ("eh_id", "mie_id", "invoice_ref", "buena_referenz_id"): - value = metadata.get(key) - if value: - return str(value) - return None - - -@router.get("/unrouted", response_model=UnroutedResponse) -async def list_unrouted( - source: str | None = Query( - default=None, - description="Filter by event source (e.g. 'bank' or 'invoice').", - ), - limit: int = Query(default=100, ge=1, le=500), - session: AsyncSession = Depends(get_session), -) -> UnroutedResponse: - """List events with ``property_id IS NULL`` for human triage. - - Includes a per-source breakdown so the operator can see at a glance - where the routing miss rate concentrates (e.g. shared-service bank - payments without an EH-/MIE- reference). - """ - breakdown_rows = ( - await session.execute( - text( - """ - SELECT source, COUNT(*) AS n - FROM events - WHERE property_id IS NULL - GROUP BY source - ORDER BY n DESC - """ - ) - ) - ).all() - by_source = {row.source: int(row.n) for row in breakdown_rows} - - params: dict[str, Any] = {"lim": limit} - where = "WHERE property_id IS NULL" - if source: - where += " AND source = :source" - params["source"] = source - - rows = ( - await session.execute( - text( - f""" - SELECT id, source, source_ref, received_at, raw_content, metadata - FROM events - {where} - ORDER BY received_at DESC - LIMIT :lim - """ - ), - params, - ) - ).all() - - events = [ - UnroutedEvent( - event_id=r.id, - source=r.source, - source_ref=r.source_ref, - received_at=r.received_at, - snippet=(r.raw_content or "")[:160], - metadata=dict(r.metadata or {}), - suggested_alias=_suggested_alias(dict(r.metadata or {})), - ) - for r in rows - ] - log.info( - "admin.unrouted", - total=sum(by_source.values()), - source_filter=source, - returned=len(events), - ) - return UnroutedResponse( - total=sum(by_source.values()), - by_source=by_source, - events=events, - ) - - -# ----------------------------------------------------------------------------- -# Step 7 — Buena incremental cursor -# ----------------------------------------------------------------------------- - - -class CursorStatus(BaseModel): - """Shape returned by the cursor endpoints.""" - - current_day: int - next_day: int | None - total_days: int - exhausted: bool - - -class AdvanceResponse(CursorStatus): - """Full advance-one-day result for the demo / admin UI.""" - - events_inserted: int = 0 - facts_written: int = 0 - routed_property: int = 0 - routed_building: int = 0 - routed_liegenschaft: int = 0 - unrouted: int = 0 - signals_fired: int = 0 - error_samples: list[str] = Field(default_factory=list) - - -@router.get("/buena/cursor_status", response_model=CursorStatus) -async def cursor_status() -> CursorStatus: - """Return the current Buena incremental-feed day cursor.""" - from connectors.incremental_runner import ( # noqa: PLC0415 — local import - get_cursor_status, - ) - - status = await get_cursor_status() - return CursorStatus(**status) - - -@router.post("/buena/advance_day", response_model=AdvanceResponse) -async def advance_day() -> AdvanceResponse: - """Advance the Buena cursor by one day and process that day's deltas. - - Latency budget: < 3 s. Each Buena day is a small batch (~6 events) - plus one signal-evaluator pass. Future customers with heavier days - can move ``evaluate_all`` to a background task without changing - the response shape. - """ - from connectors.incremental_runner import ( # noqa: PLC0415 - TOTAL_DAYS, - advance_one_day, - ) - - result = await advance_one_day() - return AdvanceResponse( - current_day=result.day, - next_day=result.day + 1 if result.day < TOTAL_DAYS else None, - total_days=TOTAL_DAYS, - exhausted=result.exhausted, - events_inserted=result.events_inserted, - facts_written=result.facts_written, - routed_property=result.routed_property, - routed_building=result.routed_building, - routed_liegenschaft=result.routed_liegenschaft, - unrouted=result.unrouted, - signals_fired=result.signals_fired, - error_samples=list(result.error_samples), - ) - - -@router.post("/buena/reset_cursor", response_model=CursorStatus) -async def reset_buena_cursor() -> CursorStatus: - """Reset the Buena cursor to ``0``. Used by demo-reset flows.""" - from connectors.incremental_runner import ( # noqa: PLC0415 - reset_cursor, - ) - - status = await reset_cursor() - return CursorStatus(**status) - - -# ----------------------------------------------------------------------------- -# Phase 12 — operational backfill of property/building/liegenschaft files -# ----------------------------------------------------------------------------- - - -class MaterializeAllResponse(BaseModel): - """Per-tier write counts returned by ``POST /admin/materialize-all``.""" - - properties: int - buildings: int - liegenschaften: int - - -@router.post("/materialize-all", response_model=MaterializeAllResponse) -async def materialize_all_endpoint( - session: AsyncSession = Depends(get_session), -) -> MaterializeAllResponse: - """Bootstrap the Phase 12 file cache. - - Mirrors ``python -m connectors.cli materialize-all`` but reachable - over HTTP — needed on Cloud Run where the CLI can't connect to - Cloud SQL directly. Idempotent: re-running just refreshes - ``last_rendered_at`` and ``content_md`` for every row. - - The applier hook propagates updates on every fact write going - forward, so this endpoint is meant to be called once after the - Phase 12 migration lands. - """ - counts = await materialize_all(session) - await session.commit() - log.info("admin.materialize_all", **counts) - return MaterializeAllResponse(**counts) - - -# ----------------------------------------------------------------------------- -# Phase 9 Step 9.2 — rejected_updates inbox -# ----------------------------------------------------------------------------- - - -class RejectedUpdate(BaseModel): - """One row of the rejected-updates inbox.""" - - rejection_id: UUID - event_id: UUID - property_id: UUID | None = None - proposed_section: str - proposed_field: str - proposed_value: str - proposed_confidence: float | None = None - constraint_name: str - reason: str - required_source_type: str | None = None - reviewed_status: str - created_at: datetime - snippet: str = Field( - default="", - description="First ~160 chars of the originating event's raw_content.", - ) - - -class RejectedUpdatesResponse(BaseModel): - """Response envelope for ``GET /properties/{id}/rejected``.""" - - total: int - by_status: dict[str, int] - rows: list[RejectedUpdate] - - -class InboxRejectedItem(BaseModel): - """Cross-property rejected-updates row for the global Inbox surface.""" - - rejection_id: UUID - event_id: UUID - property_id: UUID | None = None - property_name: str | None = None - proposed_section: str - proposed_field: str - proposed_value: str - constraint_name: str - reason: str - reviewed_status: str - created_at: datetime - snippet: str = "" - - -class InboxUncertaintyItem(BaseModel): - """Cross-property uncertainty row for the global Inbox surface.""" - - uncertainty_id: UUID - event_id: UUID - property_id: UUID | None = None - property_name: str | None = None - relevant_section: str | None = None - observation: str - hypothesis: str | None = None - reason_uncertain: str - source: str - status: str - created_at: datetime - - -class OverrideRequest(BaseModel): - """Body for ``POST /rejected/{id}/override``.""" - - reviewed_by: str = Field(..., min_length=1, max_length=200) - reason: str = Field(..., min_length=4, max_length=2000) - decision: str = Field( - default="overridden", - pattern=r"^(overridden|dismissed)$", - description=( - "``overridden`` applies the proposed update + writes an " - "approval_log entry. ``dismissed`` keeps the original fact " - "and marks the rejection closed." - ), - ) - - -class OverrideResponse(BaseModel): - """Result of an override action.""" - - rejection_id: UUID - decision: str - reviewed_status: str - reviewed_at: datetime - fact_written: bool - - -@router.get( - "/properties/{property_id}/rejected", - response_model=RejectedUpdatesResponse, -) -async def list_rejected_for_property( - property_id: UUID, - status_filter: str | None = Query( - default=None, - alias="status", - description="Filter by reviewed_status (pending / needs_review / overridden / dismissed).", - ), - limit: int = Query(default=100, ge=1, le=500), - session: AsyncSession = Depends(get_session), -) -> RejectedUpdatesResponse: - """List validator rejections targeted at one property, newest first.""" - breakdown = ( - await session.execute( - text( - """ - SELECT reviewed_status, COUNT(*) AS n - FROM rejected_updates - WHERE property_id = :pid - GROUP BY reviewed_status - """ - ), - {"pid": property_id}, - ) - ).all() - by_status = {row.reviewed_status: int(row.n) for row in breakdown} - - params: dict[str, Any] = {"pid": property_id, "lim": limit} - where = "WHERE r.property_id = :pid" - if status_filter: - where += " AND r.reviewed_status = :st" - params["st"] = status_filter - - rows = ( - await session.execute( - text( - f""" - SELECT - r.id, r.event_id, r.property_id, - r.proposed_section, r.proposed_field, r.proposed_value, - r.proposed_confidence, r.constraint_name, r.reason, - r.required_source_type, r.reviewed_status, r.created_at, - COALESCE(LEFT(e.raw_content, 160), '') AS snippet - FROM rejected_updates r - LEFT JOIN events e ON e.id = r.event_id - {where} - ORDER BY r.created_at DESC - LIMIT :lim - """ - ), - params, - ) - ).all() - - items = [ - RejectedUpdate( - rejection_id=r.id, - event_id=r.event_id, - property_id=r.property_id, - proposed_section=r.proposed_section, - proposed_field=r.proposed_field, - proposed_value=r.proposed_value, - proposed_confidence=( - float(r.proposed_confidence) - if r.proposed_confidence is not None - else None - ), - constraint_name=r.constraint_name, - reason=r.reason, - required_source_type=r.required_source_type, - reviewed_status=r.reviewed_status, - created_at=r.created_at, - snippet=str(r.snippet or ""), - ) - for r in rows - ] - log.info( - "admin.rejected.list", - property_id=str(property_id), - total=sum(by_status.values()), - returned=len(items), - ) - return RejectedUpdatesResponse( - total=sum(by_status.values()), - by_status=by_status, - rows=items, - ) - - -@router.post( - "/rejected/{rejection_id}/override", - response_model=OverrideResponse, -) -async def override_rejection( - rejection_id: UUID, - body: OverrideRequest, - session: AsyncSession = Depends(get_session), -) -> OverrideResponse: - """Operator override on a rejected update. - - On ``decision="overridden"`` the proposed fact is written + an - ``approval_log`` row records the audit trail (operator + reason). - On ``decision="dismissed"`` the rejection is closed without - writing the fact. Either way the ``rejected_updates`` row's - ``reviewed_status`` advances and the original rejection stays - visible for posterity. - """ - row = ( - await session.execute( - text( - """ - SELECT id, event_id, property_id, proposed_section, - proposed_field, proposed_value, proposed_confidence, - constraint_name, reason, reviewed_status - FROM rejected_updates - WHERE id = :rid - FOR UPDATE - """ - ), - {"rid": rejection_id}, - ) - ).first() - if row is None: - from fastapi import HTTPException # noqa: PLC0415 - - raise HTTPException(status_code=404, detail="rejection not found") - if row.reviewed_status not in {"pending", "needs_review"}: - from fastapi import HTTPException # noqa: PLC0415 - - raise HTTPException( - status_code=409, - detail=f"rejection is already {row.reviewed_status!r}", - ) - - fact_written = False - if body.decision == "overridden" and row.property_id is not None: - await session.execute( - text( - """ - INSERT INTO facts ( - property_id, section, field, value, source_event_id, - confidence, valid_from - ) VALUES ( - :pid, :section, :field, :value, :eid, :conf, now() - ) - """ - ), - { - "pid": row.property_id, - "section": row.proposed_section, - "field": row.proposed_field, - "value": row.proposed_value, - "eid": row.event_id, - "conf": ( - float(row.proposed_confidence) - if row.proposed_confidence is not None - else 0.7 - ), - }, - ) - fact_written = True - # Phase 12 — operator override that promotes a rejected - # proposal to a real fact must refresh the materialized file - # in the same transaction. - await propagate_after_fact_write( - session, - property_id=UUID(str(row.property_id)), - trigger_event_id=( - UUID(str(row.event_id)) if row.event_id else None - ), - trigger_summary=( - f"override of {row.constraint_name}: " - f"{row.proposed_section}.{row.proposed_field}" - ), - ) - - await session.execute( - text( - """ - INSERT INTO approval_log ( - actor, action, target_type, target_id, payload, created_at - ) VALUES ( - :actor, :action, 'rejected_update', :tid, CAST(:payload AS JSONB), now() - ) - """ - ), - { - "actor": body.reviewed_by, - "action": f"rejection.{body.decision}", - "tid": str(rejection_id), - "payload": _json( - { - "constraint_name": row.constraint_name, - "section": row.proposed_section, - "field": row.proposed_field, - "value": row.proposed_value, - "reason_for_override": body.reason, - "fact_written": fact_written, - } - ), - }, - ) - await session.execute( - text( - """ - UPDATE rejected_updates - SET reviewed_status = :st, - reviewed_at = now(), - reviewed_by = :by - WHERE id = :rid - RETURNING reviewed_at - """ - ), - {"st": body.decision, "by": body.reviewed_by, "rid": rejection_id}, - ) - new_row = ( - await session.execute( - text( - "SELECT reviewed_at FROM rejected_updates WHERE id = :rid" - ), - {"rid": rejection_id}, - ) - ).first() - await session.commit() - log.info( - "admin.rejected.override", - rejection_id=str(rejection_id), - decision=body.decision, - fact_written=fact_written, - reviewed_by=body.reviewed_by, - ) - return OverrideResponse( - rejection_id=rejection_id, - decision=body.decision, - reviewed_status=body.decision, - reviewed_at=new_row.reviewed_at if new_row else datetime.utcnow(), - fact_written=fact_written, - ) - - -def _json(value: dict[str, Any]) -> str: - """Serialize a small dict for SQL JSONB binding.""" - import json # noqa: PLC0415 - - return json.dumps(value) - - -# ----------------------------------------------------------------------------- -# Phase 10 Step 10.2 — replay engine -# ----------------------------------------------------------------------------- - - -class ScheduledPause(BaseModel): - """One ``scheduled_pauses`` checkpoint for a replay run.""" - - at_seconds: float = Field(..., ge=0) - message: str = Field(..., max_length=200) - - -class ReplayStartRequest(BaseModel): - """Body for ``POST /admin/replay/start``.""" - - property_id: UUID - speed_multiplier: int = Field(default=10, ge=1, le=10000) - source_filter: list[str] = Field(default_factory=lambda: ["email", "invoice", "bank"]) - start_date: datetime | None = None - end_date: datetime | None = None - scheduled_pauses: list[ScheduledPause] = Field(default_factory=list) - reset_property: bool = Field(default=False) - - -class ReplayRunStatus(BaseModel): - """Snapshot of one ``replay_runs`` row for the API.""" - - run_id: UUID - property_id: UUID - speed_multiplier: int - source_filter: list[str] - start_date: datetime | None = None - end_date: datetime | None = None - scheduled_pauses: list[dict[str, Any]] = Field(default_factory=list) - reset_property: bool = False - status: str - total_events: int - processed_events: int - last_error: str | None = None - started_at: datetime - paused_at: datetime | None = None - completed_at: datetime | None = None - - -@router.post("/replay/start", response_model=ReplayRunStatus) -async def replay_start(body: ReplayStartRequest) -> ReplayRunStatus: - """Spin up a replay run for ``property_id``. - - Streams events through the live pipeline at ``speed_multiplier`` × - real time. ``reset_property=True`` wipes facts / uncertainties / - rejections for that property first so the demo opens at "day zero". - Stammdaten links are preserved. - """ - from backend.services import replay # noqa: PLC0415 - - snapshot = await replay.start_run( - property_id=body.property_id, - speed_multiplier=body.speed_multiplier, - source_filter=list(body.source_filter), - start_date=body.start_date, - end_date=body.end_date, - scheduled_pauses=[p.model_dump() for p in body.scheduled_pauses], - reset_property=body.reset_property, - ) - return ReplayRunStatus(**snapshot) - - -@router.post("/replay/{run_id}/pause", response_model=ReplayRunStatus) -async def replay_pause(run_id: UUID) -> ReplayRunStatus: - """Pause a running replay; the in-flight event finishes first.""" - from backend.services import replay # noqa: PLC0415 - - return ReplayRunStatus(**await replay.pause_run(run_id)) - - -@router.post("/replay/{run_id}/resume", response_model=ReplayRunStatus) -async def replay_resume(run_id: UUID) -> ReplayRunStatus: - """Resume a paused replay.""" - from backend.services import replay # noqa: PLC0415 - - return ReplayRunStatus(**await replay.resume_run(run_id)) - - -@router.post("/replay/{run_id}/stop", response_model=ReplayRunStatus) -async def replay_stop(run_id: UUID) -> ReplayRunStatus: - """Stop a replay; durable status flips to ``stopped``.""" - from backend.services import replay # noqa: PLC0415 - - return ReplayRunStatus(**await replay.stop_run(run_id)) - - -@router.get("/replay/{run_id}/status", response_model=ReplayRunStatus) -async def replay_status(run_id: UUID) -> ReplayRunStatus: - """Read the current durable status of a replay run.""" - from backend.services import replay # noqa: PLC0415 - - try: - snapshot = await replay.get_run_status(run_id) - except LookupError as exc: - from fastapi import HTTPException # noqa: PLC0415 - - raise HTTPException(status_code=404, detail=str(exc)) from exc - return ReplayRunStatus(**snapshot) - - -@router.post("/demo/replay", response_model=ReplayRunStatus) -async def demo_replay() -> ReplayRunStatus: - """Thin wrapper that runs the canonical demo replay on the hero property. - - All parameters come from configuration: - - - ``KEYSTONE_DEMO_HERO_PROPERTY`` env var (default: WE 29 from - Step 6's hero pin) → ``property_id``. - - ``KEYSTONE_DEMO_SPEED_MULTIPLIER`` (default 10) → - ``speed_multiplier``. - - Hardcoded: ``source_filter=['email','invoice','bank']``, - ``reset_property=True``, and a single - ``scheduled_pauses[0] = {at_seconds: 50, message: 'validator beat'}`` - that drives the Phase 10 demo's Beat 3 (validator rejecting the - "8 floors" email live). - - Everything is configurable via :func:`replay.start_run` for ad-hoc - runs; this endpoint just removes the body so the demo button is a - one-click affair. - """ - from backend.config import get_settings # noqa: PLC0415 - from backend.services import replay # noqa: PLC0415 - - settings = get_settings() - snapshot = await replay.start_run( - property_id=UUID(settings.keystone_demo_hero_property), - speed_multiplier=settings.keystone_demo_speed_multiplier, - source_filter=["email", "invoice", "bank"], - scheduled_pauses=[ - {"at_seconds": 50.0, "message": "validator beat"}, - ], - reset_property=True, - ) - log.info( - "admin.demo_replay.started", - run_id=snapshot["run_id"], - property_id=snapshot["property_id"], - ) - return ReplayRunStatus(**snapshot) - - -# ----------------------------------------------------------------------------- -# Phase 9 Step 9.1 — uncertainty inbox (read-only for now) -# ----------------------------------------------------------------------------- - - -class UncertaintyItemModel(BaseModel): - """One open uncertainty row, ready for the admin UI.""" - - uncertainty_id: UUID - event_id: UUID - relevant_section: str | None = None - relevant_field: str | None = None - observation: str - hypothesis: str | None = None - reason_uncertain: str - source: str - status: str - created_at: datetime - - -class UncertaintyResponse(BaseModel): - """Response envelope for ``GET /admin/properties/{id}/uncertainties``.""" - - total: int - by_section: dict[str, int] - by_source: dict[str, int] - items: list[UncertaintyItemModel] - - -# ----------------------------------------------------------------------------- -# Phase 10 Step 10.3 — onboarding view -# ----------------------------------------------------------------------------- - - -class OnboardingResponse(BaseModel): - """``GET /admin/properties/{id}/onboarding`` envelope.""" - - property_id: UUID - markdown: str - cached: bool = Field( - ..., - description=( - "True when the briefing came from the metadata.onboarding cache. " - "False means Gemini Pro was invoked this request." - ), - ) - - -@router.get( - "/properties/{property_id}/onboarding", - response_model=OnboardingResponse, -) -async def get_property_onboarding( - property_id: UUID, - session: AsyncSession = Depends(get_session), -) -> OnboardingResponse: - """Render the first-time-read onboarding view for a property. - - Five sections: stammdaten + counts, open issues, Gemini Pro 12-month - briefing (the only LLM call), recurring patterns, pointer index. - The briefing is cached on ``properties.metadata.onboarding`` keyed by - a hash of the latest fact/uncertainty/rejection timestamp — so a - re-read is free, but any mutation invalidates. - """ - from backend.services import onboarding # noqa: PLC0415 - - last_fact, last_unc, last_rej = await onboarding._last_mutation_timestamps( - session, property_id - ) - cache_key = onboarding._cache_key(last_fact, last_unc, last_rej) - cached_briefing = await onboarding._read_cache(session, property_id, cache_key) - - try: - markdown = await onboarding.render_onboarding(session, property_id) - except ValueError as exc: - from fastapi import HTTPException # noqa: PLC0415 - - raise HTTPException(status_code=404, detail=str(exc)) from exc - - log.info( - "admin.onboarding.render", - property_id=str(property_id), - markdown_chars=len(markdown), - cached=cached_briefing is not None, - ) - return OnboardingResponse( - property_id=property_id, - markdown=markdown, - cached=cached_briefing is not None, - ) - - -@router.get( - "/properties/{property_id}/uncertainties", - response_model=UncertaintyResponse, -) -async def list_uncertainties_for_property( - property_id: UUID, - status_filter: str = Query( - default="open", - alias="status", - pattern=r"^(open|resolved|dismissed|all)$", - description="Filter by status; ``all`` returns every row.", - ), - limit: int = Query(default=200, ge=1, le=500), - session: AsyncSession = Depends(get_session), -) -> UncertaintyResponse: - """List the property's open uncertainty events. - - Phase 10 Step 10.6 added the write surface - (:func:`resolve_uncertainty`); this endpoint stays the read-side - pair so a UI can list → click → resolve in one round-trip. - """ - where = "WHERE property_id = :pid" - params: dict[str, Any] = {"pid": property_id, "lim": limit} - if status_filter != "all": - where += " AND status = :st" - params["st"] = status_filter - - breakdown_section = ( - await session.execute( - text( - f""" - SELECT COALESCE(relevant_section, '(unsectioned)') AS section, - COUNT(*) AS n - FROM uncertainty_events - {where} - GROUP BY COALESCE(relevant_section, '(unsectioned)') - """ - ), - params, - ) - ).all() - by_section = {row.section: int(row.n) for row in breakdown_section} - - breakdown_source = ( - await session.execute( - text( - f""" - SELECT source, COUNT(*) AS n - FROM uncertainty_events - {where} - GROUP BY source - """ - ), - params, - ) - ).all() - by_source = {row.source: int(row.n) for row in breakdown_source} - - rows = ( - await session.execute( - text( - f""" - SELECT id, event_id, relevant_section, relevant_field, - observation, hypothesis, reason_uncertain, - source, status, created_at - FROM uncertainty_events - {where} - ORDER BY created_at DESC - LIMIT :lim - """ - ), - params, - ) - ).all() - - items = [ - UncertaintyItemModel( - uncertainty_id=row.id, - event_id=row.event_id, - relevant_section=row.relevant_section, - relevant_field=row.relevant_field, - observation=str(row.observation or ""), - hypothesis=row.hypothesis, - reason_uncertain=str(row.reason_uncertain or ""), - source=str(row.source or "extractor"), - status=str(row.status), - created_at=row.created_at, - ) - for row in rows - ] - log.info( - "admin.uncertainties.list", - property_id=str(property_id), - status=status_filter, - total=sum(by_section.values()), - returned=len(items), - ) - return UncertaintyResponse( - total=sum(by_section.values()), - by_section=by_section, - by_source=by_source, - items=items, - ) - - -# ----------------------------------------------------------------------------- -# Phase 11 — cross-property inboxes for the Inbox page -# ----------------------------------------------------------------------------- - - -@router.get("/uncertainties", response_model=list[InboxUncertaintyItem]) -async def list_uncertainties_global( - status_filter: str = Query( - default="open", - alias="status", - pattern=r"^(open|resolved|dismissed|all)$", - ), - limit: int = Query(default=50, ge=1, le=200), - session: AsyncSession = Depends(get_session), -) -> list[InboxUncertaintyItem]: - """Cross-property uncertainty inbox. - - Same shape as ``GET /admin/properties/{id}/uncertainties`` minus the - by-section / by-source breakdowns, plus a ``property_name`` column - so the global Inbox can label each row. - """ - where = "" - params: dict[str, Any] = {"lim": limit} - if status_filter != "all": - where = "WHERE u.status = :st" - params["st"] = status_filter - - rows = ( - await session.execute( - text( - f""" - SELECT u.id AS uncertainty_id, - u.event_id, - u.property_id, - p.name AS property_name, - u.relevant_section, - u.observation, u.hypothesis, u.reason_uncertain, - u.source, u.status, u.created_at - FROM uncertainty_events u - LEFT JOIN properties p ON p.id = u.property_id - {where} - ORDER BY u.created_at DESC - LIMIT :lim - """ - ), - params, - ) - ).all() - - items = [ - InboxUncertaintyItem( - uncertainty_id=r.uncertainty_id, - event_id=r.event_id, - property_id=r.property_id, - property_name=r.property_name, - relevant_section=r.relevant_section, - observation=str(r.observation or ""), - hypothesis=r.hypothesis, - reason_uncertain=str(r.reason_uncertain or ""), - source=str(r.source or "extractor"), - status=str(r.status), - created_at=r.created_at, - ) - for r in rows - ] - log.info( - "admin.uncertainties.global", - status=status_filter, - returned=len(items), - ) - return items - - -@router.get("/rejected", response_model=list[InboxRejectedItem]) -async def list_rejected_global( - status_filter: str | None = Query( - default="pending", - alias="status", - ), - limit: int = Query(default=50, ge=1, le=200), - session: AsyncSession = Depends(get_session), -) -> list[InboxRejectedItem]: - """Cross-property rejected-updates inbox.""" - params: dict[str, Any] = {"lim": limit} - where = "" - if status_filter: - where = "WHERE r.reviewed_status = :st" - params["st"] = status_filter - - rows = ( - await session.execute( - text( - f""" - SELECT r.id AS rejection_id, - r.event_id, r.property_id, - p.name AS property_name, - r.proposed_section, r.proposed_field, r.proposed_value, - r.constraint_name, r.reason, - r.reviewed_status, r.created_at, - COALESCE(LEFT(e.raw_content, 160), '') AS snippet - FROM rejected_updates r - LEFT JOIN events e ON e.id = r.event_id - LEFT JOIN properties p ON p.id = r.property_id - {where} - ORDER BY r.created_at DESC - LIMIT :lim - """ - ), - params, - ) - ).all() - items = [ - InboxRejectedItem( - rejection_id=r.rejection_id, - event_id=r.event_id, - property_id=r.property_id, - property_name=r.property_name, - proposed_section=str(r.proposed_section), - proposed_field=str(r.proposed_field), - proposed_value=str(r.proposed_value), - constraint_name=str(r.constraint_name), - reason=str(r.reason), - reviewed_status=str(r.reviewed_status), - created_at=r.created_at, - snippet=str(r.snippet or ""), - ) - for r in rows - ] - log.info( - "admin.rejected.global", - status=status_filter, - returned=len(items), - ) - return items - - -# ----------------------------------------------------------------------------- -# Phase 10 Step 10.6 — uncertainty action endpoints -# ----------------------------------------------------------------------------- - - -class UncertaintyResolveRequest(BaseModel): - """Body for ``POST /admin/uncertainties/{id}/resolve``.""" - - action: str = Field( - ..., - pattern=r"^(promote_to_fact|dismiss)$", - description=( - "``promote_to_fact`` writes a fact at " - "(relevant_section, relevant_field) using ``value`` (or " - "``hypothesis`` as fallback) and marks the uncertainty " - "``resolved``. ``dismiss`` closes the uncertainty without " - "writing a fact." - ), - ) - value: str | None = Field( - default=None, - max_length=2000, - description=( - "Operator-supplied value to commit when promoting. Falls " - "back to ``hypothesis`` from the uncertainty row if omitted. " - "Required when promoting an uncertainty whose hypothesis is " - "NULL." - ), - ) - reason: str = Field(..., min_length=3, max_length=2000) - reviewed_by: str = Field(..., min_length=1, max_length=200) - - -class UncertaintyResolveResponse(BaseModel): - """Result of a resolve action.""" - - uncertainty_id: UUID - action: str - new_status: str - fact_id: UUID | None = None - resolved_at: datetime - - -@router.post( - "/uncertainties/{uncertainty_id}/resolve", - response_model=UncertaintyResolveResponse, -) -async def resolve_uncertainty( - uncertainty_id: UUID, - body: UncertaintyResolveRequest, - session: AsyncSession = Depends(get_session), -) -> UncertaintyResolveResponse: - """Promote an uncertainty to a fact, or dismiss it. - - Phase 10 Step 10.6: the trust layer's first write surface. Either - action transitions the uncertainty out of ``open`` and records an - ``approval_log`` entry naming the operator + reason — the audit - trail is the whole point. ``promote_to_fact`` requires the - uncertainty to carry both ``relevant_section`` and - ``relevant_field``; the value comes from ``body.value`` or, if - absent, from the uncertainty's ``hypothesis``. A 422 is returned - when neither is available. - - The fact is written with ``confidence=0.95`` and ``source_event_id`` - pointing at the uncertainty's originating event so the source link - keeps working. - """ - from fastapi import HTTPException # noqa: PLC0415 - - row = ( - await session.execute( - text( - """ - SELECT id, event_id, property_id, building_id, liegenschaft_id, - relevant_section, relevant_field, observation, - hypothesis, reason_uncertain, status - FROM uncertainty_events - WHERE id = :uid - FOR UPDATE - """ - ), - {"uid": uncertainty_id}, - ) - ).first() - if row is None: - raise HTTPException(status_code=404, detail="uncertainty not found") - if row.status != "open": - raise HTTPException( - status_code=409, - detail=f"uncertainty is already {row.status!r}", - ) - - fact_id: UUID | None = None - written_value: str | None = None - - if body.action == "promote_to_fact": - if not row.relevant_section or not row.relevant_field: - raise HTTPException( - status_code=422, - detail=( - "cannot promote — uncertainty is missing relevant_section " - "or relevant_field" - ), - ) - # Pick the value: explicit override wins, hypothesis second. - candidate = body.value if body.value not in (None, "") else row.hypothesis - if not candidate: - raise HTTPException( - status_code=422, - detail=( - "cannot promote — no value supplied and uncertainty has " - "no hypothesis to fall back on" - ), - ) - written_value = str(candidate) - - # Pick the scope column the fact should attach to. Property is the - # default surface; building / liegenschaft are honoured if the - # uncertainty was scoped that way. - scope_column = "property_id" - scope_value = row.property_id - if row.property_id is None and row.building_id is not None: - scope_column = "building_id" - scope_value = row.building_id - elif row.property_id is None and row.liegenschaft_id is not None: - scope_column = "liegenschaft_id" - scope_value = row.liegenschaft_id - if scope_value is None: - raise HTTPException( - status_code=422, - detail=( - "cannot promote — uncertainty has no property/building/" - "liegenschaft scope" - ), - ) - - fact_row = ( - await session.execute( - text( - f""" - INSERT INTO facts ( - {scope_column}, section, field, value, source_event_id, - confidence, valid_from - ) VALUES ( - :sid, :section, :field, :value, :eid, 0.95, now() - ) - RETURNING id - """ - ), - { - "sid": scope_value, - "section": row.relevant_section, - "field": row.relevant_field, - "value": written_value, - "eid": row.event_id, - }, - ) - ).first() - fact_id = UUID(str(fact_row.id)) - - await session.execute( - text( - """ - UPDATE uncertainty_events - SET status = 'resolved', - resolved_to_fact_id = :fid, - resolved_at = now() - WHERE id = :uid - """ - ), - {"fid": fact_id, "uid": uncertainty_id}, - ) - new_status = "resolved" - - # Phase 12 — promotion writes a real fact at the uncertainty's - # original scope; propagate to the matching tier (and cascade - # if it's a building or liegenschaft fact). - propagate_kwargs: dict[str, UUID | None] = { - "property_id": None, - "building_id": None, - "liegenschaft_id": None, - } - propagate_kwargs[scope_column] = UUID(str(scope_value)) - await propagate_after_fact_write( - session, - **propagate_kwargs, - trigger_event_id=( - UUID(str(row.event_id)) if row.event_id else None - ), - trigger_summary=( - f"uncertainty resolved → {row.relevant_section}." - f"{row.relevant_field}: {written_value}" - ), - ) - else: - await session.execute( - text( - """ - UPDATE uncertainty_events - SET status = 'dismissed', - resolved_at = now() - WHERE id = :uid - """ - ), - {"uid": uncertainty_id}, - ) - new_status = "dismissed" - - await session.execute( - text( - """ - INSERT INTO approval_log ( - actor, action, target_type, target_id, payload, created_at - ) VALUES ( - :actor, :action, 'uncertainty_event', :tid, - CAST(:payload AS JSONB), now() - ) - """ - ), - { - "actor": body.reviewed_by, - "action": f"uncertainty.{body.action}", - "tid": str(uncertainty_id), - "payload": _json( - { - "section": row.relevant_section, - "field": row.relevant_field, - "value_written": written_value, - "fact_id": str(fact_id) if fact_id else None, - "reason": body.reason, - "observation": str(row.observation or "")[:200], - } - ), - }, - ) - resolved_row = ( - await session.execute( - text("SELECT resolved_at FROM uncertainty_events WHERE id = :uid"), - {"uid": uncertainty_id}, - ) - ).first() - await session.commit() - log.info( - "admin.uncertainty.resolve", - uncertainty_id=str(uncertainty_id), - action=body.action, - fact_id=str(fact_id) if fact_id else None, - reviewed_by=body.reviewed_by, - ) - return UncertaintyResolveResponse( - uncertainty_id=uncertainty_id, - action=body.action, - new_status=new_status, - fact_id=fact_id, - resolved_at=( - resolved_row.resolved_at if resolved_row else datetime.utcnow() - ), - ) diff --git a/backend/api/admin/__init__.py b/backend/api/admin/__init__.py new file mode 100644 index 0000000..e76583d --- /dev/null +++ b/backend/api/admin/__init__.py @@ -0,0 +1,19 @@ +"""Admin API, assembled from one module per resource under ``/admin``.""" + +from fastapi import APIRouter + +from backend.api.admin import ( + feed, + materialize, + onboarding, + rejected, + replay, + uncertainties, + unrouted, +) + +router = APIRouter(prefix="/admin", tags=["admin"]) +for module in (unrouted, feed, materialize, rejected, replay, onboarding, uncertainties): + router.include_router(module.router) + +__all__ = ["router"] diff --git a/backend/api/admin/_shared.py b/backend/api/admin/_shared.py new file mode 100644 index 0000000..b6bca5a --- /dev/null +++ b/backend/api/admin/_shared.py @@ -0,0 +1,11 @@ +"""Helpers shared by the admin modules.""" + +from __future__ import annotations + +import json +from typing import Any + + +def json_param(value: dict[str, Any]) -> str: + """Serialize a small dict for a ``CAST(:param AS JSONB)`` bind parameter.""" + return json.dumps(value) diff --git a/backend/api/admin/feed.py b/backend/api/admin/feed.py new file mode 100644 index 0000000..9457205 --- /dev/null +++ b/backend/api/admin/feed.py @@ -0,0 +1,89 @@ +"""Incremental-feed controls: replay the sample dataset's ``incremental/`` days. + +A day cursor records which day was ingested last; advancing it ingests the +next day's emails, bank rows and invoices through the normal pipeline. +""" + +from __future__ import annotations + +import structlog +from fastapi import APIRouter +from pydantic import BaseModel, Field + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class CursorStatus(BaseModel): + """Shape returned by the cursor endpoints.""" + + current_day: int + next_day: int | None + total_days: int + exhausted: bool + + +class AdvanceResponse(CursorStatus): + """Full advance-one-day result for the admin UI.""" + + events_inserted: int = 0 + facts_written: int = 0 + routed_property: int = 0 + routed_building: int = 0 + routed_liegenschaft: int = 0 + unrouted: int = 0 + signals_fired: int = 0 + error_samples: list[str] = Field(default_factory=list) + + +@router.get("/buena/cursor_status", response_model=CursorStatus) +async def cursor_status() -> CursorStatus: + """Return the current incremental-feed day cursor.""" + from connectors.incremental_runner import ( # noqa: PLC0415 + get_cursor_status, + ) + + status = await get_cursor_status() + return CursorStatus(**status) + + +@router.post("/buena/advance_day", response_model=AdvanceResponse) +async def advance_day() -> AdvanceResponse: + """Advance the cursor by one day and process that day's deltas. + + Latency budget: < 3 s. Each day in the sample dataset is a small + batch (~6 events) plus one signal-evaluator pass. Feeds with heavier + days can move ``evaluate_all`` to a background task without changing + the response shape. + """ + from connectors.incremental_runner import ( # noqa: PLC0415 + TOTAL_DAYS, + advance_one_day, + ) + + result = await advance_one_day() + return AdvanceResponse( + current_day=result.day, + next_day=result.day + 1 if result.day < TOTAL_DAYS else None, + total_days=TOTAL_DAYS, + exhausted=result.exhausted, + events_inserted=result.events_inserted, + facts_written=result.facts_written, + routed_property=result.routed_property, + routed_building=result.routed_building, + routed_liegenschaft=result.routed_liegenschaft, + unrouted=result.unrouted, + signals_fired=result.signals_fired, + error_samples=list(result.error_samples), + ) + + +@router.post("/buena/reset_cursor", response_model=CursorStatus) +async def reset_buena_cursor() -> CursorStatus: + """Reset the cursor to ``0`` so the incremental feed replays from day 1.""" + from connectors.incremental_runner import ( # noqa: PLC0415 + reset_cursor, + ) + + status = await reset_cursor() + return CursorStatus(**status) diff --git a/backend/api/admin/materialize.py b/backend/api/admin/materialize.py new file mode 100644 index 0000000..2ba77a8 --- /dev/null +++ b/backend/api/admin/materialize.py @@ -0,0 +1,46 @@ +"""Backfill of the materialized property, building and Liegenschaft files.""" + +from __future__ import annotations + +import structlog +from fastapi import APIRouter, Depends +from pydantic import BaseModel +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session +from backend.pipeline.materializer import ( + materialize_all, +) + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class MaterializeAllResponse(BaseModel): + """Per-tier write counts returned by ``POST /admin/materialize-all``.""" + + properties: int + buildings: int + liegenschaften: int + + +@router.post("/materialize-all", response_model=MaterializeAllResponse) +async def materialize_all_endpoint( + session: AsyncSession = Depends(get_session), +) -> MaterializeAllResponse: + """Bootstrap the materialized file cache for every tier. + + Mirrors ``python -m connectors.cli materialize-all`` but reachable + over HTTP, for deployments where the CLI cannot reach the database + directly. Idempotent: re-running just refreshes + ``last_rendered_at`` and ``content_md`` for every row. + + The applier hook propagates updates on every fact write going + forward, so this endpoint only needs calling once: after the + ``*_files`` cache tables are created on an existing database, or + after a bulk load that bypassed the applier. + """ + counts = await materialize_all(session) + await session.commit() + log.info("admin.materialize_all", **counts) + return MaterializeAllResponse(**counts) diff --git a/backend/api/admin/onboarding.py b/backend/api/admin/onboarding.py new file mode 100644 index 0000000..584097a --- /dev/null +++ b/backend/api/admin/onboarding.py @@ -0,0 +1,72 @@ +"""Onboarding view: a briefing for someone opening a property for the first time.""" + +from __future__ import annotations + +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends +from pydantic import BaseModel, Field +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session +from backend.services.onboarding import BriefingSource + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class OnboardingResponse(BaseModel): + """``GET /admin/properties/{id}/onboarding`` envelope.""" + + property_id: UUID + markdown: str + briefing_source: BriefingSource = Field( + ..., + description=( + "Where the Key context briefing came from: 'llm' (written by the " + "configured provider on this request), 'cache' (metadata.onboarding) " + "or 'unavailable' (no provider configured or reachable; the section " + "is a one-line note and every other section is complete)." + ), + ) + cached: bool = Field(..., description="Same as briefing_source == 'cache'.") + + +@router.get( + "/properties/{property_id}/onboarding", + response_model=OnboardingResponse, +) +async def get_property_onboarding( + property_id: UUID, + session: AsyncSession = Depends(get_session), +) -> OnboardingResponse: + """Render the first-time-read onboarding view for a property. + + Five sections: stammdaten + counts, open issues, an LLM-written + 12-month briefing (the only LLM call), recurring patterns, pointer index. + The briefing is cached on ``properties.metadata.onboarding`` keyed by + a hash of the latest fact/uncertainty/rejection timestamp, so a + re-read is free, but any mutation invalidates. + """ + from backend.services import onboarding # noqa: PLC0415 + + try: + document = await onboarding.render_onboarding_document(session, property_id) + except ValueError as exc: + from fastapi import HTTPException # noqa: PLC0415 + + raise HTTPException(status_code=404, detail=str(exc)) from exc + + log.info( + "admin.onboarding.render", + property_id=str(property_id), + markdown_chars=len(document.markdown), + briefing_source=document.briefing_source, + ) + return OnboardingResponse( + property_id=property_id, + markdown=document.markdown, + briefing_source=document.briefing_source, + cached=document.briefing_source == "cache", + ) diff --git a/backend/api/admin/rejected.py b/backend/api/admin/rejected.py new file mode 100644 index 0000000..d22669b --- /dev/null +++ b/backend/api/admin/rejected.py @@ -0,0 +1,395 @@ +"""Rejected-update inbox: proposals a validator refused, and their override. + +Overriding writes the proposed fact, records who decided in ``approval_log``, +and re-renders the affected files in the same transaction. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.api.admin._shared import json_param +from backend.db.session import get_session +from backend.pipeline.materializer import ( + propagate_after_fact_write, +) + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class RejectedUpdate(BaseModel): + """One row of the rejected-updates inbox.""" + + rejection_id: UUID + event_id: UUID + property_id: UUID | None = None + proposed_section: str + proposed_field: str + proposed_value: str + proposed_confidence: float | None = None + constraint_name: str + reason: str + required_source_type: str | None = None + reviewed_status: str + created_at: datetime + snippet: str = Field( + default="", + description="First ~160 chars of the originating event's raw_content.", + ) + + +class RejectedUpdatesResponse(BaseModel): + """Response envelope for ``GET /properties/{id}/rejected``.""" + + total: int + by_status: dict[str, int] + rows: list[RejectedUpdate] + + +class InboxRejectedItem(BaseModel): + """Cross-property rejected-updates row for the global Inbox surface.""" + + rejection_id: UUID + event_id: UUID + property_id: UUID | None = None + property_name: str | None = None + proposed_section: str + proposed_field: str + proposed_value: str + constraint_name: str + reason: str + reviewed_status: str + created_at: datetime + snippet: str = "" + + +class OverrideRequest(BaseModel): + """Body for ``POST /rejected/{id}/override``.""" + + reviewed_by: str = Field(..., min_length=1, max_length=200) + reason: str = Field(..., min_length=4, max_length=2000) + decision: str = Field( + default="overridden", + pattern=r"^(overridden|dismissed)$", + description=( + "``overridden`` applies the proposed update + writes an " + "approval_log entry. ``dismissed`` keeps the original fact " + "and marks the rejection closed." + ), + ) + + +class OverrideResponse(BaseModel): + """Result of an override action.""" + + rejection_id: UUID + decision: str + reviewed_status: str + reviewed_at: datetime + fact_written: bool + + +@router.get( + "/properties/{property_id}/rejected", + response_model=RejectedUpdatesResponse, +) +async def list_rejected_for_property( + property_id: UUID, + status_filter: str | None = Query( + default=None, + alias="status", + description="Filter by reviewed_status (pending / needs_review / overridden / dismissed).", + ), + limit: int = Query(default=100, ge=1, le=500), + session: AsyncSession = Depends(get_session), +) -> RejectedUpdatesResponse: + """List validator rejections targeted at one property, newest first.""" + breakdown = ( + await session.execute( + text( + """ + SELECT reviewed_status, COUNT(*) AS n + FROM rejected_updates + WHERE property_id = :pid + GROUP BY reviewed_status + """ + ), + {"pid": property_id}, + ) + ).all() + by_status = {row.reviewed_status: int(row.n) for row in breakdown} + + params: dict[str, Any] = {"pid": property_id, "lim": limit} + where = "WHERE r.property_id = :pid" + if status_filter: + where += " AND r.reviewed_status = :st" + params["st"] = status_filter + + rows = ( + await session.execute( + text( + f""" + SELECT + r.id, r.event_id, r.property_id, + r.proposed_section, r.proposed_field, r.proposed_value, + r.proposed_confidence, r.constraint_name, r.reason, + r.required_source_type, r.reviewed_status, r.created_at, + COALESCE(LEFT(e.raw_content, 160), '') AS snippet + FROM rejected_updates r + LEFT JOIN events e ON e.id = r.event_id + {where} + ORDER BY r.created_at DESC + LIMIT :lim + """ + ), + params, + ) + ).all() + + items = [ + RejectedUpdate( + rejection_id=r.id, + event_id=r.event_id, + property_id=r.property_id, + proposed_section=r.proposed_section, + proposed_field=r.proposed_field, + proposed_value=r.proposed_value, + proposed_confidence=( + float(r.proposed_confidence) if r.proposed_confidence is not None else None + ), + constraint_name=r.constraint_name, + reason=r.reason, + required_source_type=r.required_source_type, + reviewed_status=r.reviewed_status, + created_at=r.created_at, + snippet=str(r.snippet or ""), + ) + for r in rows + ] + log.info( + "admin.rejected.list", + property_id=str(property_id), + total=sum(by_status.values()), + returned=len(items), + ) + return RejectedUpdatesResponse( + total=sum(by_status.values()), + by_status=by_status, + rows=items, + ) + + +@router.post( + "/rejected/{rejection_id}/override", + response_model=OverrideResponse, +) +async def override_rejection( + rejection_id: UUID, + body: OverrideRequest, + session: AsyncSession = Depends(get_session), +) -> OverrideResponse: + """Operator override on a rejected update. + + On ``decision="overridden"`` the proposed fact is written + an + ``approval_log`` row records the audit trail (operator + reason). + On ``decision="dismissed"`` the rejection is closed without + writing the fact. Either way the ``rejected_updates`` row's + ``reviewed_status`` advances and the original rejection stays + visible for posterity. + """ + row = ( + await session.execute( + text( + """ + SELECT id, event_id, property_id, proposed_section, + proposed_field, proposed_value, proposed_confidence, + constraint_name, reason, reviewed_status + FROM rejected_updates + WHERE id = :rid + FOR UPDATE + """ + ), + {"rid": rejection_id}, + ) + ).first() + if row is None: + from fastapi import HTTPException # noqa: PLC0415 + + raise HTTPException(status_code=404, detail="rejection not found") + if row.reviewed_status not in {"pending", "needs_review"}: + from fastapi import HTTPException # noqa: PLC0415 + + raise HTTPException( + status_code=409, + detail=f"rejection is already {row.reviewed_status!r}", + ) + + fact_written = False + if body.decision == "overridden" and row.property_id is not None: + await session.execute( + text( + """ + INSERT INTO facts ( + property_id, section, field, value, source_event_id, + confidence, valid_from + ) VALUES ( + :pid, :section, :field, :value, :eid, :conf, now() + ) + """ + ), + { + "pid": row.property_id, + "section": row.proposed_section, + "field": row.proposed_field, + "value": row.proposed_value, + "eid": row.event_id, + "conf": ( + float(row.proposed_confidence) if row.proposed_confidence is not None else 0.7 + ), + }, + ) + fact_written = True + # An operator override that promotes a rejected proposal to a + # real fact must refresh the materialized file in the same + # transaction, or the cached markdown would lag the facts table. + await propagate_after_fact_write( + session, + property_id=UUID(str(row.property_id)), + trigger_event_id=(UUID(str(row.event_id)) if row.event_id else None), + trigger_summary=( + f"override of {row.constraint_name}: {row.proposed_section}.{row.proposed_field}" + ), + ) + + await session.execute( + text( + """ + INSERT INTO approval_log ( + actor, action, target_type, target_id, payload, created_at + ) VALUES ( + :actor, :action, 'rejected_update', :tid, CAST(:payload AS JSONB), now() + ) + """ + ), + { + "actor": body.reviewed_by, + "action": f"rejection.{body.decision}", + "tid": str(rejection_id), + "payload": json_param( + { + "constraint_name": row.constraint_name, + "section": row.proposed_section, + "field": row.proposed_field, + "value": row.proposed_value, + "reason_for_override": body.reason, + "fact_written": fact_written, + } + ), + }, + ) + await session.execute( + text( + """ + UPDATE rejected_updates + SET reviewed_status = :st, + reviewed_at = now(), + reviewed_by = :by + WHERE id = :rid + RETURNING reviewed_at + """ + ), + {"st": body.decision, "by": body.reviewed_by, "rid": rejection_id}, + ) + new_row = ( + await session.execute( + text("SELECT reviewed_at FROM rejected_updates WHERE id = :rid"), + {"rid": rejection_id}, + ) + ).first() + await session.commit() + log.info( + "admin.rejected.override", + rejection_id=str(rejection_id), + decision=body.decision, + fact_written=fact_written, + reviewed_by=body.reviewed_by, + ) + return OverrideResponse( + rejection_id=rejection_id, + decision=body.decision, + reviewed_status=body.decision, + reviewed_at=new_row.reviewed_at if new_row else datetime.utcnow(), + fact_written=fact_written, + ) + + +@router.get("/rejected", response_model=list[InboxRejectedItem]) +async def list_rejected_global( + status_filter: str | None = Query( + default="pending", + alias="status", + ), + limit: int = Query(default=50, ge=1, le=200), + session: AsyncSession = Depends(get_session), +) -> list[InboxRejectedItem]: + """Cross-property rejected-updates inbox.""" + params: dict[str, Any] = {"lim": limit} + where = "" + if status_filter: + where = "WHERE r.reviewed_status = :st" + params["st"] = status_filter + + rows = ( + await session.execute( + text( + f""" + SELECT r.id AS rejection_id, + r.event_id, r.property_id, + p.name AS property_name, + r.proposed_section, r.proposed_field, r.proposed_value, + r.constraint_name, r.reason, + r.reviewed_status, r.created_at, + COALESCE(LEFT(e.raw_content, 160), '') AS snippet + FROM rejected_updates r + LEFT JOIN events e ON e.id = r.event_id + LEFT JOIN properties p ON p.id = r.property_id + {where} + ORDER BY r.created_at DESC + LIMIT :lim + """ + ), + params, + ) + ).all() + items = [ + InboxRejectedItem( + rejection_id=r.rejection_id, + event_id=r.event_id, + property_id=r.property_id, + property_name=r.property_name, + proposed_section=str(r.proposed_section), + proposed_field=str(r.proposed_field), + proposed_value=str(r.proposed_value), + constraint_name=str(r.constraint_name), + reason=str(r.reason), + reviewed_status=str(r.reviewed_status), + created_at=r.created_at, + snippet=str(r.snippet or ""), + ) + for r in rows + ] + log.info( + "admin.rejected.global", + status=status_filter, + returned=len(items), + ) + return items diff --git a/backend/api/admin/replay.py b/backend/api/admin/replay.py new file mode 100644 index 0000000..8fde419 --- /dev/null +++ b/backend/api/admin/replay.py @@ -0,0 +1,159 @@ +"""Replay engine controls: re-ingest a property's history at a chosen speed.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter +from pydantic import BaseModel, Field + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class ScheduledPause(BaseModel): + """One ``scheduled_pauses`` checkpoint for a replay run.""" + + at_seconds: float = Field(..., ge=0) + message: str = Field(..., max_length=200) + + +class ReplayStartRequest(BaseModel): + """Body for ``POST /admin/replay/start``.""" + + property_id: UUID + speed_multiplier: int = Field(default=10, ge=1, le=10000) + source_filter: list[str] = Field(default_factory=lambda: ["email", "invoice", "bank"]) + start_date: datetime | None = None + end_date: datetime | None = None + scheduled_pauses: list[ScheduledPause] = Field(default_factory=list) + reset_property: bool = Field(default=False) + + +class ReplayRunStatus(BaseModel): + """Snapshot of one ``replay_runs`` row for the API.""" + + run_id: UUID + property_id: UUID + speed_multiplier: int + source_filter: list[str] + start_date: datetime | None = None + end_date: datetime | None = None + scheduled_pauses: list[dict[str, Any]] = Field(default_factory=list) + reset_property: bool = False + status: str + total_events: int + processed_events: int + last_error: str | None = None + started_at: datetime + paused_at: datetime | None = None + completed_at: datetime | None = None + + +@router.post("/replay/start", response_model=ReplayRunStatus) +async def replay_start(body: ReplayStartRequest) -> ReplayRunStatus: + """Spin up a replay run for ``property_id``. + + Streams events through the live pipeline at ``speed_multiplier`` × + real time. ``reset_property=True`` wipes facts / uncertainties / + rejections for that property first so the replay rebuilds the + property file from "day zero". + Stammdaten links are preserved. + """ + from backend.services import replay # noqa: PLC0415 + + snapshot = await replay.start_run( + property_id=body.property_id, + speed_multiplier=body.speed_multiplier, + source_filter=list(body.source_filter), + start_date=body.start_date, + end_date=body.end_date, + scheduled_pauses=[p.model_dump() for p in body.scheduled_pauses], + reset_property=body.reset_property, + ) + return ReplayRunStatus(**snapshot) + + +@router.post("/replay/{run_id}/pause", response_model=ReplayRunStatus) +async def replay_pause(run_id: UUID) -> ReplayRunStatus: + """Pause a running replay; the in-flight event finishes first.""" + from backend.services import replay # noqa: PLC0415 + + return ReplayRunStatus(**await replay.pause_run(run_id)) + + +@router.post("/replay/{run_id}/resume", response_model=ReplayRunStatus) +async def replay_resume(run_id: UUID) -> ReplayRunStatus: + """Resume a paused replay.""" + from backend.services import replay # noqa: PLC0415 + + return ReplayRunStatus(**await replay.resume_run(run_id)) + + +@router.post("/replay/{run_id}/stop", response_model=ReplayRunStatus) +async def replay_stop(run_id: UUID) -> ReplayRunStatus: + """Stop a replay; durable status flips to ``stopped``.""" + from backend.services import replay # noqa: PLC0415 + + return ReplayRunStatus(**await replay.stop_run(run_id)) + + +@router.get("/replay/{run_id}/status", response_model=ReplayRunStatus) +async def replay_status(run_id: UUID) -> ReplayRunStatus: + """Read the current durable status of a replay run.""" + from backend.services import replay # noqa: PLC0415 + + try: + snapshot = await replay.get_run_status(run_id) + except LookupError as exc: + from fastapi import HTTPException # noqa: PLC0415 + + raise HTTPException(status_code=404, detail=str(exc)) from exc + return ReplayRunStatus(**snapshot) + + +@router.post("/replay/featured", response_model=ReplayRunStatus) +async def replay_featured_property() -> ReplayRunStatus: + """Replay the featured property's history with preset parameters. + + A body-free shortcut for :func:`replay.start_run`: + + - property: ``FEATURED_PROPERTY`` (UUID or alias, default ``EH-029``) + - speed: ``REPLAY_SPEED_MULTIPLIER`` (default 10) + - sources: email, invoice, bank; the property's facts are reset first + - one checkpoint pause at 50 s, where the replayed history reaches the + email that the floor-count constraint rejects + + Use ``POST /admin/replay/start`` for any other combination. + """ + from fastapi import HTTPException # noqa: PLC0415 + + from backend.config import get_settings # noqa: PLC0415 + from backend.db.session import get_sessionmaker # noqa: PLC0415 + from backend.services import replay # noqa: PLC0415 + from backend.services.featured import resolve_featured_property_id # noqa: PLC0415 + + settings = get_settings() + async with get_sessionmaker()() as session: + property_id = await resolve_featured_property_id(session) + if property_id is None: + raise HTTPException( + status_code=404, + detail=f"FEATURED_PROPERTY={settings.featured_property!r} matches no property", + ) + snapshot = await replay.start_run( + property_id=property_id, + speed_multiplier=settings.replay_speed_multiplier, + source_filter=["email", "invoice", "bank"], + scheduled_pauses=[{"at_seconds": 50.0, "message": "constraint checkpoint"}], + reset_property=True, + ) + log.info( + "admin.replay_featured.started", + run_id=snapshot["run_id"], + property_id=snapshot["property_id"], + ) + return ReplayRunStatus(**snapshot) diff --git a/backend/api/admin/uncertainties.py b/backend/api/admin/uncertainties.py new file mode 100644 index 0000000..34424ee --- /dev/null +++ b/backend/api/admin/uncertainties.py @@ -0,0 +1,485 @@ +"""Uncertainty inbox: observations the system would not commit to as facts. + +Operators read them per property or across the portfolio and resolve each one +by promoting it to a fact or dismissing it; both are audit-logged. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.api.admin._shared import json_param +from backend.db.session import get_session +from backend.pipeline.materializer import ( + propagate_after_fact_write, +) + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class InboxUncertaintyItem(BaseModel): + """Cross-property uncertainty row for the global Inbox surface.""" + + uncertainty_id: UUID + event_id: UUID + property_id: UUID | None = None + property_name: str | None = None + relevant_section: str | None = None + observation: str + hypothesis: str | None = None + reason_uncertain: str + source: str + status: str + created_at: datetime + + +class UncertaintyItemModel(BaseModel): + """One open uncertainty row, ready for the admin UI.""" + + uncertainty_id: UUID + event_id: UUID + relevant_section: str | None = None + relevant_field: str | None = None + observation: str + hypothesis: str | None = None + reason_uncertain: str + source: str + status: str + created_at: datetime + + +class UncertaintyResponse(BaseModel): + """Response envelope for ``GET /admin/properties/{id}/uncertainties``.""" + + total: int + by_section: dict[str, int] + by_source: dict[str, int] + items: list[UncertaintyItemModel] + + +@router.get( + "/properties/{property_id}/uncertainties", + response_model=UncertaintyResponse, +) +async def list_uncertainties_for_property( + property_id: UUID, + status_filter: str = Query( + default="open", + alias="status", + pattern=r"^(open|resolved|dismissed|all)$", + description="Filter by status; ``all`` returns every row.", + ), + limit: int = Query(default=200, ge=1, le=500), + session: AsyncSession = Depends(get_session), +) -> UncertaintyResponse: + """List the property's open uncertainty events. + + :func:`resolve_uncertainty` is the write side; this endpoint is + its read-side pair so a UI can list → click → resolve in one round-trip. + """ + where = "WHERE property_id = :pid" + params: dict[str, Any] = {"pid": property_id, "lim": limit} + if status_filter != "all": + where += " AND status = :st" + params["st"] = status_filter + + breakdown_section = ( + await session.execute( + text( + f""" + SELECT COALESCE(relevant_section, '(unsectioned)') AS section, + COUNT(*) AS n + FROM uncertainty_events + {where} + GROUP BY COALESCE(relevant_section, '(unsectioned)') + """ + ), + params, + ) + ).all() + by_section = {row.section: int(row.n) for row in breakdown_section} + + breakdown_source = ( + await session.execute( + text( + f""" + SELECT source, COUNT(*) AS n + FROM uncertainty_events + {where} + GROUP BY source + """ + ), + params, + ) + ).all() + by_source = {row.source: int(row.n) for row in breakdown_source} + + rows = ( + await session.execute( + text( + f""" + SELECT id, event_id, relevant_section, relevant_field, + observation, hypothesis, reason_uncertain, + source, status, created_at + FROM uncertainty_events + {where} + ORDER BY created_at DESC + LIMIT :lim + """ + ), + params, + ) + ).all() + + items = [ + UncertaintyItemModel( + uncertainty_id=row.id, + event_id=row.event_id, + relevant_section=row.relevant_section, + relevant_field=row.relevant_field, + observation=str(row.observation or ""), + hypothesis=row.hypothesis, + reason_uncertain=str(row.reason_uncertain or ""), + source=str(row.source or "extractor"), + status=str(row.status), + created_at=row.created_at, + ) + for row in rows + ] + log.info( + "admin.uncertainties.list", + property_id=str(property_id), + status=status_filter, + total=sum(by_section.values()), + returned=len(items), + ) + return UncertaintyResponse( + total=sum(by_section.values()), + by_section=by_section, + by_source=by_source, + items=items, + ) + + +@router.get("/uncertainties", response_model=list[InboxUncertaintyItem]) +async def list_uncertainties_global( + status_filter: str = Query( + default="open", + alias="status", + pattern=r"^(open|resolved|dismissed|all)$", + ), + limit: int = Query(default=50, ge=1, le=200), + session: AsyncSession = Depends(get_session), +) -> list[InboxUncertaintyItem]: + """Cross-property uncertainty inbox. + + Same shape as ``GET /admin/properties/{id}/uncertainties`` minus the + by-section / by-source breakdowns, plus a ``property_name`` column + so the global Inbox can label each row. + """ + where = "" + params: dict[str, Any] = {"lim": limit} + if status_filter != "all": + where = "WHERE u.status = :st" + params["st"] = status_filter + + rows = ( + await session.execute( + text( + f""" + SELECT u.id AS uncertainty_id, + u.event_id, + u.property_id, + p.name AS property_name, + u.relevant_section, + u.observation, u.hypothesis, u.reason_uncertain, + u.source, u.status, u.created_at + FROM uncertainty_events u + LEFT JOIN properties p ON p.id = u.property_id + {where} + ORDER BY u.created_at DESC + LIMIT :lim + """ + ), + params, + ) + ).all() + + items = [ + InboxUncertaintyItem( + uncertainty_id=r.uncertainty_id, + event_id=r.event_id, + property_id=r.property_id, + property_name=r.property_name, + relevant_section=r.relevant_section, + observation=str(r.observation or ""), + hypothesis=r.hypothesis, + reason_uncertain=str(r.reason_uncertain or ""), + source=str(r.source or "extractor"), + status=str(r.status), + created_at=r.created_at, + ) + for r in rows + ] + log.info( + "admin.uncertainties.global", + status=status_filter, + returned=len(items), + ) + return items + + +class UncertaintyResolveRequest(BaseModel): + """Body for ``POST /admin/uncertainties/{id}/resolve``.""" + + action: str = Field( + ..., + pattern=r"^(promote_to_fact|dismiss)$", + description=( + "``promote_to_fact`` writes a fact at " + "(relevant_section, relevant_field) using ``value`` (or " + "``hypothesis`` as fallback) and marks the uncertainty " + "``resolved``. ``dismiss`` closes the uncertainty without " + "writing a fact." + ), + ) + value: str | None = Field( + default=None, + max_length=2000, + description=( + "Operator-supplied value to commit when promoting. Falls " + "back to ``hypothesis`` from the uncertainty row if omitted. " + "Required when promoting an uncertainty whose hypothesis is " + "NULL." + ), + ) + reason: str = Field(..., min_length=3, max_length=2000) + reviewed_by: str = Field(..., min_length=1, max_length=200) + + +class UncertaintyResolveResponse(BaseModel): + """Result of a resolve action.""" + + uncertainty_id: UUID + action: str + new_status: str + fact_id: UUID | None = None + resolved_at: datetime + + +@router.post( + "/uncertainties/{uncertainty_id}/resolve", + response_model=UncertaintyResolveResponse, +) +async def resolve_uncertainty( + uncertainty_id: UUID, + body: UncertaintyResolveRequest, + session: AsyncSession = Depends(get_session), +) -> UncertaintyResolveResponse: + """Promote an uncertainty to a fact, or dismiss it. + + Either action transitions the uncertainty out of ``open`` and + records an ``approval_log`` entry naming the operator + reason. The + audit trail is the point: a human decision overrides the extractor, + so it must be attributable after the fact. ``promote_to_fact`` requires the + uncertainty to carry both ``relevant_section`` and + ``relevant_field``; the value comes from ``body.value`` or, if + absent, from the uncertainty's ``hypothesis``. A 422 is returned + when neither is available. + + The fact is written with ``confidence=0.95`` and ``source_event_id`` + pointing at the uncertainty's originating event so the source link + keeps working. + """ + from fastapi import HTTPException # noqa: PLC0415 + + row = ( + await session.execute( + text( + """ + SELECT id, event_id, property_id, building_id, liegenschaft_id, + relevant_section, relevant_field, observation, + hypothesis, reason_uncertain, status + FROM uncertainty_events + WHERE id = :uid + FOR UPDATE + """ + ), + {"uid": uncertainty_id}, + ) + ).first() + if row is None: + raise HTTPException(status_code=404, detail="uncertainty not found") + if row.status != "open": + raise HTTPException( + status_code=409, + detail=f"uncertainty is already {row.status!r}", + ) + + fact_id: UUID | None = None + written_value: str | None = None + + if body.action == "promote_to_fact": + if not row.relevant_section or not row.relevant_field: + raise HTTPException( + status_code=422, + detail=( + "cannot promote: uncertainty is missing relevant_section or relevant_field" + ), + ) + # Pick the value: explicit override wins, hypothesis second. + candidate = body.value if body.value not in (None, "") else row.hypothesis + if not candidate: + raise HTTPException( + status_code=422, + detail=( + "cannot promote: no value supplied and uncertainty has " + "no hypothesis to fall back on" + ), + ) + written_value = str(candidate) + + # Pick the scope column the fact should attach to. Property is the + # default surface; building / liegenschaft are honoured if the + # uncertainty was scoped that way. + scope_column = "property_id" + scope_value = row.property_id + if row.property_id is None and row.building_id is not None: + scope_column = "building_id" + scope_value = row.building_id + elif row.property_id is None and row.liegenschaft_id is not None: + scope_column = "liegenschaft_id" + scope_value = row.liegenschaft_id + if scope_value is None: + raise HTTPException( + status_code=422, + detail=("cannot promote: uncertainty has no property/building/liegenschaft scope"), + ) + + fact_row = ( + await session.execute( + text( + f""" + INSERT INTO facts ( + {scope_column}, section, field, value, source_event_id, + confidence, valid_from + ) VALUES ( + :sid, :section, :field, :value, :eid, 0.95, now() + ) + RETURNING id + """ + ), + { + "sid": scope_value, + "section": row.relevant_section, + "field": row.relevant_field, + "value": written_value, + "eid": row.event_id, + }, + ) + ).one() + fact_id = UUID(str(fact_row.id)) + + await session.execute( + text( + """ + UPDATE uncertainty_events + SET status = 'resolved', + resolved_to_fact_id = :fid, + resolved_at = now() + WHERE id = :uid + """ + ), + {"fid": fact_id, "uid": uncertainty_id}, + ) + new_status = "resolved" + + # Promotion writes a real fact at the uncertainty's + # original scope; propagate to the matching tier (and cascade + # if it's a building or liegenschaft fact). + propagate_kwargs: dict[str, UUID | None] = { + "property_id": None, + "building_id": None, + "liegenschaft_id": None, + } + propagate_kwargs[scope_column] = UUID(str(scope_value)) + await propagate_after_fact_write( + session, + **propagate_kwargs, + trigger_event_id=(UUID(str(row.event_id)) if row.event_id else None), + trigger_summary=( + f"uncertainty resolved → {row.relevant_section}." + f"{row.relevant_field}: {written_value}" + ), + ) + else: + await session.execute( + text( + """ + UPDATE uncertainty_events + SET status = 'dismissed', + resolved_at = now() + WHERE id = :uid + """ + ), + {"uid": uncertainty_id}, + ) + new_status = "dismissed" + + await session.execute( + text( + """ + INSERT INTO approval_log ( + actor, action, target_type, target_id, payload, created_at + ) VALUES ( + :actor, :action, 'uncertainty_event', :tid, + CAST(:payload AS JSONB), now() + ) + """ + ), + { + "actor": body.reviewed_by, + "action": f"uncertainty.{body.action}", + "tid": str(uncertainty_id), + "payload": json_param( + { + "section": row.relevant_section, + "field": row.relevant_field, + "value_written": written_value, + "fact_id": str(fact_id) if fact_id else None, + "reason": body.reason, + "observation": str(row.observation or "")[:200], + } + ), + }, + ) + resolved_row = ( + await session.execute( + text("SELECT resolved_at FROM uncertainty_events WHERE id = :uid"), + {"uid": uncertainty_id}, + ) + ).first() + await session.commit() + log.info( + "admin.uncertainty.resolve", + uncertainty_id=str(uncertainty_id), + action=body.action, + fact_id=str(fact_id) if fact_id else None, + reviewed_by=body.reviewed_by, + ) + return UncertaintyResolveResponse( + uncertainty_id=uncertainty_id, + action=body.action, + new_status=new_status, + fact_id=fact_id, + resolved_at=(resolved_row.resolved_at if resolved_row else datetime.utcnow()), + ) diff --git a/backend/api/admin/unrouted.py b/backend/api/admin/unrouted.py new file mode 100644 index 0000000..78bc3d1 --- /dev/null +++ b/backend/api/admin/unrouted.py @@ -0,0 +1,138 @@ +"""Unrouted inbox: events the router could not attribute to any scope. + +``GET /admin/unrouted`` lists them with a suggested alias, so an operator can +attach them by hand instead of the events silently dropping out of every +property file. Unrouted events are a normal outcome of ingesting a real +archive. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class UnroutedEvent(BaseModel): + """One row of the unrouted-inbox listing.""" + + event_id: UUID + source: str + source_ref: str | None = None + received_at: datetime + snippet: str = Field( + ..., + description="First ~120 chars of raw_content for human triage.", + ) + metadata: dict[str, Any] + suggested_alias: str | None = Field( + default=None, + description=( + "Best guess alias to look up; surfaces metadata.eh_id / mie_id / " + "invoice_ref so the operator knows what reference was tried." + ), + ) + + +class UnroutedResponse(BaseModel): + """Response envelope for ``GET /admin/unrouted``.""" + + total: int + by_source: dict[str, int] + events: list[UnroutedEvent] + + +def _suggested_alias(metadata: dict[str, Any]) -> str | None: + """Surface the strongest ID that the routing failed to resolve.""" + for key in ("eh_id", "mie_id", "invoice_ref", "buena_referenz_id"): + value = metadata.get(key) + if value: + return str(value) + return None + + +@router.get("/unrouted", response_model=UnroutedResponse) +async def list_unrouted( + source: str | None = Query( + default=None, + description="Filter by event source (e.g. 'bank' or 'invoice').", + ), + limit: int = Query(default=100, ge=1, le=500), + session: AsyncSession = Depends(get_session), +) -> UnroutedResponse: + """List events with ``property_id IS NULL`` for human triage. + + Includes a per-source breakdown so the operator can see at a glance + where the routing miss rate concentrates (e.g. shared-service bank + payments without an EH-/MIE- reference). + """ + breakdown_rows = ( + await session.execute( + text( + """ + SELECT source, COUNT(*) AS n + FROM events + WHERE property_id IS NULL + GROUP BY source + ORDER BY n DESC + """ + ) + ) + ).all() + by_source = {row.source: int(row.n) for row in breakdown_rows} + + params: dict[str, Any] = {"lim": limit} + where = "WHERE property_id IS NULL" + if source: + where += " AND source = :source" + params["source"] = source + + rows = ( + await session.execute( + text( + f""" + SELECT id, source, source_ref, received_at, raw_content, metadata + FROM events + {where} + ORDER BY received_at DESC + LIMIT :lim + """ + ), + params, + ) + ).all() + + events = [ + UnroutedEvent( + event_id=r.id, + source=r.source, + source_ref=r.source_ref, + received_at=r.received_at, + snippet=(r.raw_content or "")[:160], + metadata=dict(r.metadata or {}), + suggested_alias=_suggested_alias(dict(r.metadata or {})), + ) + for r in rows + ] + log.info( + "admin.unrouted", + total=sum(by_source.values()), + source_filter=source, + returned=len(events), + ) + return UnroutedResponse( + total=sum(by_source.values()), + by_source=by_source, + events=events, + ) diff --git a/backend/api/buildings.py b/backend/api/buildings.py index 03edfa9..ec47460 100644 --- a/backend/api/buildings.py +++ b/backend/api/buildings.py @@ -1,10 +1,10 @@ """Buildings + Liegenschaften (WEG) read API. -Phase 8.1 surfaced the two new ownership tiers introduced in -``connectors.migrations`` 0002. Both endpoints render the same +Serves the two ownership tiers above properties (buildings and +Liegenschaften), introduced in ``connectors.migrations`` 0002. Both endpoints render the same markdown shape the property view uses, with cross-tier context blocks. -Phase 12 — markdown reads now hit the materialized ``building_files`` +Markdown reads hit the materialized ``building_files`` and ``liegenschaft_files`` cache first (populated by the applier hook in :mod:`backend.pipeline.materializer`); live rendering remains as the fallback path. Per-tier ``/file`` endpoints expose the full row @@ -77,8 +77,7 @@ async def building_markdown( cached = ( await session.execute( text( - "SELECT content_md, last_rendered_at FROM building_files " - "WHERE building_id = :bid" + "SELECT content_md, last_rendered_at FROM building_files WHERE building_id = :bid" ), {"bid": building_id}, ) @@ -135,17 +134,13 @@ async def building_file( ) ).first() if row is None: - raise HTTPException( - status_code=404, detail="building file not materialized yet" - ) + raise HTTPException(status_code=404, detail="building file not materialized yet") return BuildingFileRow( building_id=UUID(str(row.building_id)), content_md=row.content_md, fact_count=int(row.fact_count or 0), last_rendered_at=row.last_rendered_at, - trigger_event_id=( - UUID(str(row.trigger_event_id)) if row.trigger_event_id else None - ), + trigger_event_id=(UUID(str(row.trigger_event_id)) if row.trigger_event_id else None), trigger_scope=row.trigger_scope, trigger_summary=row.trigger_summary, generation_version=int(row.generation_version or 1), @@ -229,17 +224,13 @@ async def liegenschaft_file( ) ).first() if row is None: - raise HTTPException( - status_code=404, detail="liegenschaft file not materialized yet" - ) + raise HTTPException(status_code=404, detail="liegenschaft file not materialized yet") return LiegenschaftFileRow( liegenschaft_id=UUID(str(row.liegenschaft_id)), content_md=row.content_md, fact_count=int(row.fact_count or 0), last_rendered_at=row.last_rendered_at, - trigger_event_id=( - UUID(str(row.trigger_event_id)) if row.trigger_event_id else None - ), + trigger_event_id=(UUID(str(row.trigger_event_id)) if row.trigger_event_id else None), trigger_scope=row.trigger_scope, trigger_summary=row.trigger_summary, generation_version=int(row.generation_version or 1), diff --git a/backend/api/draft_reply.py b/backend/api/draft_reply.py index a34d86f..5b418df 100644 --- a/backend/api/draft_reply.py +++ b/backend/api/draft_reply.py @@ -1,14 +1,13 @@ -"""``POST /draft-reply`` — context-aware reply drafter. +"""``POST /draft-reply``: context-aware reply drafting. -The frontend's DraftReply page submits an inbound email/Slack message; -this endpoint pulls the property's recent facts and events, asks -Pioneer (Claude) to draft a reply that cites prior context when -relevant, and returns the structured payload the page renders into -the "With Keystone — context-aware reply" panel. +The frontend's DraftReply page submits an inbound email or Slack message; +this endpoint pulls the property's recent facts and events, asks the +configured LLM provider to draft a reply that cites prior context where +relevant, and returns the structured payload the page renders. -The endpoint always returns 200 when the LLM call succeeds, even when -no relevant context exists (``knows_about_incident=false``, -``context=[]``). Pioneer transport failure is the only 5xx path. +The endpoint returns 200 whenever the LLM call succeeds, even when no +relevant context exists (``knows_about_incident=false``, ``context=[]``). +It returns 503 when no provider is configured or the call fails. """ from __future__ import annotations @@ -25,7 +24,7 @@ from backend.db.session import get_session from backend.services import draft_reply as draft_reply_service -from backend.services import pioneer_llm +from backend.services.llm import LLMUnavailableError router = APIRouter(prefix="/draft-reply", tags=["draft-reply"]) log = structlog.get_logger(__name__) @@ -85,7 +84,7 @@ async def _resolve_property( Returns ``(resolved_id, display_name)``. ``resolved_id`` may be ``None`` when the caller supplied only a name that doesn't match - any seeded property — in that case we still return the supplied + any seeded property; in that case we still return the supplied name so the LLM can draft a generic holding reply. """ if property_id is not None: @@ -211,11 +210,11 @@ async def draft_reply( recent_facts=facts, recent_events=events, ) - except pioneer_llm.PioneerUnavailable as exc: - log.warning("draft_reply.unavailable", error=str(exc)) + except LLMUnavailableError as exc: + log.warning("draft_reply.unavailable", error=str(exc)[:300]) raise HTTPException( status_code=503, - detail=f"draft service unavailable: {exc}", + detail=f"Reply drafting is unavailable: {exc}", ) from exc context_items = [ @@ -244,5 +243,5 @@ async def draft_reply( context=context_items, knows_about_incident=result["knows_about_incident"], elapsed_ms=elapsed_ms, - model=str(result.get("model") or pioneer_llm.PIONEER_DEFAULT_MODEL), + model=str(result.get("model") or ""), ) diff --git a/backend/api/events.py b/backend/api/events.py index d30fc18..4711b7a 100644 --- a/backend/api/events.py +++ b/backend/api/events.py @@ -1,8 +1,18 @@ -"""Debug + manual-trigger event endpoints. +"""Manual event injection. -``POST /debug/trigger_event`` is the demo-resilience backup when IMAP fails -on venue wifi. It accepts the same raw email payload the poller would -produce and inserts it idempotently. +``POST /debug/trigger_event`` inserts one event and runs it through the +pipeline synchronously, bypassing the queue. It is the way to feed the +system without a connector (no IMAP account, no archive) and the quickest +end-to-end check that routing, extraction and rendering work. + +Two request shapes are accepted: + +- ``raw_content``: the event text exactly as a connector would store it + in ``events.raw_content``. +- ``from`` / ``subject`` / ``body``: composed into the same + ``From:``/``Subject:``/body layout the IMAP poller produces. + +Insertion is idempotent on ``(source, source_ref)``. """ from __future__ import annotations @@ -12,7 +22,7 @@ import structlog from fastapi import APIRouter, Depends, HTTPException -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, model_validator from sqlalchemy.ext.asyncio import AsyncSession from backend.db.session import get_session @@ -24,20 +34,35 @@ class TriggerEventRequest(BaseModel): - """Payload for a manually injected event.""" + """Payload for a manually injected event: ``raw_content`` or ``body``.""" source: str = Field(default="email") source_ref: str | None = Field( default=None, description="Optional idempotency key. Auto-generated if omitted.", ) + raw_content: str | None = Field( + default=None, + description="Event text stored verbatim, as a connector would write it.", + ) from_: str | None = Field(default=None, alias="from") subject: str | None = None - body: str + body: str | None = Field( + default=None, + description="Email body; combined with 'from' and 'subject' into raw_content.", + ) metadata: dict[str, Any] = Field(default_factory=dict) model_config = {"populate_by_name": True} + @model_validator(mode="after") + def _exactly_one_content_field(self) -> TriggerEventRequest: + if (self.raw_content is None) == (self.body is None): + raise ValueError("provide exactly one of 'raw_content' or 'body'") + if self.raw_content is not None and (self.from_ or self.subject): + raise ValueError("'from' and 'subject' only apply together with 'body'") + return self + class TriggerEventResponse(BaseModel): """Response for the debug/trigger_event endpoint.""" @@ -48,7 +73,9 @@ class TriggerEventResponse(BaseModel): def _build_raw_content(req: TriggerEventRequest) -> str: - """Assemble the ``raw_content`` in the same shape IMAP produces.""" + """Return ``raw_content`` as given, or compose it the way IMAP does.""" + if req.raw_content is not None: + return req.raw_content from_line = f"From: {req.from_}\n" if req.from_ else "" subject_line = f"Subject: {req.subject}\n" if req.subject else "" return f"{from_line}{subject_line}\n{req.body}".strip() + "\n" @@ -59,14 +86,15 @@ async def trigger_event( payload: TriggerEventRequest, session: AsyncSession = Depends(get_session), ) -> TriggerEventResponse: - """Insert an event synchronously and process it end-to-end immediately. + """Insert an event and process it end-to-end before responding. - Bypasses the FIFO queue so the demo trigger lands its fact even - when the worker has hundreds of older Buena events still pending - (the queue clears in the background as the regular worker drains). + Processes this event directly instead of waiting for its turn in the + queue, so the response reflects its outcome even when older events + are still pending; the scheduled worker drains those independently. """ - if not payload.body.strip(): - raise HTTPException(status_code=400, detail="body must not be empty") + content = payload.raw_content if payload.raw_content is not None else payload.body + if not (content or "").strip(): + raise HTTPException(status_code=400, detail="event content must not be empty") source_ref = payload.source_ref or f"debug-{uuid.uuid4()}" event_id, inserted = await insert_event( @@ -86,6 +114,4 @@ async def trigger_event( inserted=inserted, processed=processed, ) - return TriggerEventResponse( - event_id=event_id, inserted=inserted, processed=processed - ) + return TriggerEventResponse(event_id=event_id, inserted=inserted, processed=processed) diff --git a/backend/api/files.py b/backend/api/files.py index d66eff8..4855497 100644 --- a/backend/api/files.py +++ b/backend/api/files.py @@ -1,13 +1,13 @@ -"""``GET /files/`` — serve a document from the configured root. +"""``GET /files/``: serve a document from the configured root. -Phase 10 Step 10.4. The renderer's ``[source: …]`` links resolve to -this endpoint for invoice / letter PDFs, so the trust mechanism only -holds if a click actually opens the original document. +The renderer's ``[source: …]`` links resolve to this endpoint for +invoice / letter PDFs, so the trust mechanism only holds if a click +actually opens the original document. Path safety is the only thing this module exists to enforce. The configured root is resolved via :func:`os.path.realpath` once at startup; every requested path is also realpath-resolved and required to start -with the root prefix. Anything else returns 403 — even legal-looking +with the root prefix. Anything else returns 403, even legal-looking relative paths that resolve to a sibling directory. """ @@ -59,10 +59,10 @@ def _find_by_basename(basename: str) -> str | None: Defends against connector-side path-relativity drift (an early ingest stored ``original_path`` relative to the connector's working - directory, not to the configured files root). The basename - includes the content sha-prefixed Buena filename - (e.g. ``20260102_DL-012_INV-00196.pdf``) which is unique enough for - a single match. We stop at the first match — operators clicking + directory, not to the configured files root). Document basenames in + the sample dataset embed a date and document IDs + (e.g. ``20260102_DL-012_INV-00196.pdf``), which is unique enough for + a single match. We stop at the first match: operators clicking "Open PDF" want a document, not a list. Logs the resolution so the operator can audit afterward. """ @@ -93,7 +93,7 @@ def _safe_resolve(relative_path: str) -> str: Steps: - 1. Reject absolute paths outright — only relative segments allowed. + 1. Reject absolute paths outright; only relative segments are allowed. 2. Reject any segment that contains a NUL byte (defense in depth). 3. Join + realpath; require the result to live under ``_allowed_root``. 4. Require the file to exist and be a regular file. diff --git a/backend/api/portfolio.py b/backend/api/portfolio.py index de077e4..dbc644e 100644 --- a/backend/api/portfolio.py +++ b/backend/api/portfolio.py @@ -33,7 +33,7 @@ class PortfolioSummary(BaseModel): """Dashboard counts used in the portfolio header. Time-bucketed counts (``events_last_hour`` / ``facts_today``) drive - the ActivityTicker pulse on the home page — pollable, cheap, and + the ActivityTicker pulse on the home page. They are pollable, cheap and purely numeric so the frontend can animate count-ups without needing the underlying rows. """ @@ -85,19 +85,13 @@ async def portfolio_banner( async def portfolio_summary( session: AsyncSession = Depends(get_session), ) -> PortfolioSummary: - """Return quick dashboard counts — properties, signals, portfolio signals.""" - props = ( - await session.execute(text("SELECT COUNT(*) FROM properties")) - ).scalar_one() + """Return quick dashboard counts: properties, signals, portfolio signals.""" + props = (await session.execute(text("SELECT COUNT(*) FROM properties"))).scalar_one() pending = ( - await session.execute( - text("SELECT COUNT(*) FROM signals WHERE status = 'pending'") - ) + await session.execute(text("SELECT COUNT(*) FROM signals WHERE status = 'pending'")) ).scalar_one() resolved = ( - await session.execute( - text("SELECT COUNT(*) FROM signals WHERE status = 'resolved'") - ) + await session.execute(text("SELECT COUNT(*) FROM signals WHERE status = 'resolved'")) ).scalar_one() portfolio = ( await session.execute( @@ -180,7 +174,7 @@ async def portfolio_activity( or the bare source label as a last resort. By default the result is filtered to events that **changed system - state** — wrote a fact or surfaced a signal. Routine events that + state**: wrote a fact or surfaced a signal. Routine events that just transit through the pipeline (bank settlements, auto-replies) are hidden so the activity feed reads as a signal feed rather than a tail of the events table. diff --git a/backend/api/properties.py b/backend/api/properties.py deleted file mode 100644 index d8960c8..0000000 --- a/backend/api/properties.py +++ /dev/null @@ -1,1465 +0,0 @@ -"""Properties API — listing, creation (with Tavily enrichment), markdown, activity.""" - -from __future__ import annotations - -from datetime import datetime -from uuid import UUID - -import structlog -from fastapi import APIRouter, Depends, HTTPException, Query -from fastapi.responses import PlainTextResponse -from pydantic import BaseModel, Field -from sqlalchemy import text -from sqlalchemy.ext.asyncio import AsyncSession - -from backend.db.session import get_session -from backend.pipeline.events import get_event_bus -from backend.pipeline.materializer import propagate_after_fact_write -from backend.pipeline.renderer import ( - CONTEXT_LABELS, - CONTEXT_LIMIT, - Stammdaten, - _building_for_property, - _context_body, - _detect_property_language, - _fetch_stammdaten, - _format_eur, - _liegenschaft_for_building, - _recent_events_for_scope, - render_markdown, -) -from backend.services import ask as ask_service -from backend.services import pioneer_llm -from backend.services.tavily import enrich_property - -router = APIRouter(prefix="/properties", tags=["properties"]) -log = structlog.get_logger(__name__) - - -class PropertySummary(BaseModel): - """Compact property record used by the portfolio listing. - - Counts are computed at query time from indexed property_id lookups on - ``events``, ``facts`` (current only — ``superseded_by IS NULL``), - ``uncertainty_events`` (``status='open'``), and ``signals`` - (``status='pending'``). At Buena's 56-property scale this is ~224 - index hits per request — single-digit ms total. - """ - - id: UUID - name: str - address: str - owner_name: str | None = None - building_year_built: int | None = None - events: int = 0 - facts: int = 0 - needs_review: int = 0 - open_issues: int = 0 - - -class PropertyCreateRequest(BaseModel): - """Payload for POST /properties.""" - - name: str = Field(..., min_length=1) - address: str = Field(..., min_length=1) - aliases: list[str] = Field(default_factory=list) - owner_id: UUID | None = None - building_id: UUID | None = None - - -class PropertyCreateResponse(BaseModel): - """Response for POST /properties.""" - - id: UUID - name: str - address: str - tavily_event_id: UUID | None - - -class EnrichmentResponse(BaseModel): - """Response for POST /properties/{id}/enrich.""" - - property_id: UUID - tavily_event_id: UUID | None - already_enriched: bool - - -class PropertySearchHit(BaseModel): - """One result from ``GET /properties/search``.""" - - id: UUID - name: str - address: str - snippet: str - score: float - - -class PropertyFileFact(BaseModel): - """One row in a property file section, shaped for the frontend. - - Mirrors the UI's ``Fact`` type (``value`` / ``source`` / ``date``) and - surfaces ``section`` / ``field`` / ``event_id`` so the renderer can - deep-link to the originating event when the user clicks ``[source]``. - ``fact_id`` is the canonical pointer the edit endpoint needs; - ``human_edited`` flips the source label so the UI can render - ``via operator`` instead of ``via email`` for hand-edited rows. - """ - - value: str - source: str - date: str - date_iso: str | None = None - confidence: float | None = None - urgent: bool = False - reason: str | None = None - section: str - field: str - event_id: str | None = None - fact_id: str | None = None - human_edited: bool = False - edited_by: str | None = None - - -class PropertyFileSection(BaseModel): - """Display section grouping facts under a single heading.""" - - title: str - facts: list[PropertyFileFact] - is_uncertain: bool = False - is_context: bool = False - - -class PropertyFile(BaseModel): - """Structured payload powering the PropertyDetail page.""" - - id: UUID - name: str - address: str - sections: list[PropertyFileSection] - - -class GraphNode(BaseModel): - """A node in the property context graph.""" - - id: str - type: str # 'property' | 'owner' | 'building' | 'tenant' | 'contractor' - label: str - metadata: dict[str, object] = {} - - -class GraphEdge(BaseModel): - """An edge in the property context graph.""" - - source: str - target: str - relationship: str - - -class PropertyGraph(BaseModel): - """Response for ``GET /properties/{id}/graph``.""" - - property_id: UUID - nodes: list[GraphNode] - edges: list[GraphEdge] - - -@router.get("", response_model=list[PropertySummary]) -async def list_properties( - session: AsyncSession = Depends(get_session), -) -> list[PropertySummary]: - """Return every seeded property, joined with owner + building context.""" - result = await session.execute( - text( - """ - SELECT p.id, p.name, p.address, - o.name AS owner_name, - b.year_built AS building_year_built, - (SELECT COUNT(*) FROM events - WHERE property_id = p.id) AS events, - (SELECT COUNT(*) FROM facts - WHERE property_id = p.id - AND superseded_by IS NULL) AS facts, - (SELECT COUNT(*) FROM uncertainty_events - WHERE property_id = p.id - AND status = 'open') AS needs_review, - (SELECT COUNT(*) FROM signals - WHERE property_id = p.id - AND status = 'pending') AS open_issues - FROM properties p - LEFT JOIN owners o ON o.id = p.owner_id - LEFT JOIN buildings b ON b.id = p.building_id - ORDER BY p.created_at ASC - """ - ) - ) - properties = [ - PropertySummary( - id=row.id, - name=row.name, - address=row.address, - owner_name=row.owner_name, - building_year_built=row.building_year_built, - events=int(row.events or 0), - facts=int(row.facts or 0), - needs_review=int(row.needs_review or 0), - open_issues=int(row.open_issues or 0), - ) - for row in result.all() - ] - log.info("properties.list", count=len(properties)) - return properties - - -@router.get("/search", response_model=list[PropertySearchHit]) -async def search_properties( - q: str = Query(..., min_length=1, description="Free-text search query"), - limit: int = Query(default=5, ge=1, le=25), - session: AsyncSession = Depends(get_session), -) -> list[PropertySearchHit]: - """Keyword search across property name, address, aliases, and current facts. - - Per-term scoring — the query is split on whitespace and each term - contributes independently, so ``"heating Berlin"`` picks up a heating - fact *and* a Berlin address rather than needing both words to appear - contiguously. - - Weights: - - direct name/alias term hit → 1.0 - - address term hit → 0.8 - - fact value term hit → 0.5 + min(count / 10, 0.45) - """ - terms = [t for t in q.lower().split() if t.strip()] or [q.lower()] - aggregated: dict[str, dict[str, Any]] = {} - for term in terms: - pattern = f"%{term}%" - result = await session.execute( - text( - """ - WITH fact_hits AS ( - SELECT f.property_id, - COUNT(*) AS hits, - (ARRAY_AGG(f.value ORDER BY f.created_at DESC))[1] - AS snippet - FROM facts f - WHERE f.superseded_by IS NULL - AND LOWER(f.value) LIKE :pat - GROUP BY f.property_id - ) - SELECT p.id, p.name, p.address, - COALESCE(fh.hits, 0) AS hits, - fh.snippet AS fact_snippet, - CASE - WHEN LOWER(p.name) LIKE :pat THEN 1.0 - WHEN EXISTS ( - SELECT 1 FROM UNNEST(p.aliases) a - WHERE LOWER(a) LIKE :pat - ) THEN 0.95 - WHEN LOWER(p.address) LIKE :pat THEN 0.8 - WHEN COALESCE(fh.hits, 0) > 0 - THEN 0.5 + LEAST(fh.hits::float / 10.0, 0.45) - ELSE 0.0 - END AS score - FROM properties p - LEFT JOIN fact_hits fh ON fh.property_id = p.id - """ - ), - {"pat": pattern}, - ) - for row in result.all(): - score = float(row.score) - if score <= 0: - continue - slot = aggregated.setdefault( - str(row.id), - { - "id": row.id, - "name": row.name, - "address": row.address, - "snippet": None, - "score": 0.0, - }, - ) - slot["score"] += score - if slot["snippet"] is None and row.fact_snippet: - slot["snippet"] = row.fact_snippet - - hits = sorted(aggregated.values(), key=lambda r: r["score"], reverse=True)[:limit] - log.info("properties.search", q=q, terms=len(terms), returned=len(hits)) - return [ - PropertySearchHit( - id=h["id"], - name=h["name"], - address=h["address"], - snippet=(h["snippet"] or f"{h['name']} — {h['address']}")[:220], - score=min(float(h["score"]), 1.0 * len(terms)), - ) - for h in hits - ] - - -@router.get("/{property_id}/graph", response_model=PropertyGraph) -async def property_graph( - property_id: UUID, - session: AsyncSession = Depends(get_session), -) -> PropertyGraph: - """Return the context graph for a property — owner, building, tenants, contractors.""" - prop_row = ( - await session.execute( - text( - """ - SELECT p.id, p.name, p.address, - o.id AS owner_id, o.name AS owner_name, o.email AS owner_email, - b.id AS building_id, b.address AS building_address, - b.year_built AS building_year - FROM properties p - LEFT JOIN owners o ON o.id = p.owner_id - LEFT JOIN buildings b ON b.id = p.building_id - WHERE p.id = :pid - """ - ), - {"pid": property_id}, - ) - ).first() - if prop_row is None: - raise HTTPException(status_code=404, detail="property not found") - - nodes: list[GraphNode] = [ - GraphNode( - id=str(prop_row.id), - type="property", - label=prop_row.name, - metadata={"address": prop_row.address}, - ) - ] - edges: list[GraphEdge] = [] - - if prop_row.owner_id is not None: - nodes.append( - GraphNode( - id=str(prop_row.owner_id), - type="owner", - label=prop_row.owner_name or "Owner", - metadata={"email": prop_row.owner_email or ""}, - ) - ) - edges.append( - GraphEdge( - source=str(prop_row.id), - target=str(prop_row.owner_id), - relationship="owned_by", - ) - ) - - if prop_row.building_id is not None: - nodes.append( - GraphNode( - id=str(prop_row.building_id), - type="building", - label=f"Building — {prop_row.building_address}", - metadata={ - "address": prop_row.building_address or "", - "year_built": prop_row.building_year, - }, - ) - ) - edges.append( - GraphEdge( - source=str(prop_row.id), - target=str(prop_row.building_id), - relationship="in_building", - ) - ) - - tenants = await session.execute( - text( - """ - SELECT id, name, email - FROM tenants - WHERE property_id = :pid - ORDER BY name - """ - ), - {"pid": property_id}, - ) - for tenant in tenants.all(): - nodes.append( - GraphNode( - id=str(tenant.id), - type="tenant", - label=tenant.name, - metadata={"email": tenant.email or ""}, - ) - ) - edges.append( - GraphEdge( - source=str(prop_row.id), - target=str(tenant.id), - relationship="occupied_by", - ) - ) - - contractors = await session.execute( - text( - """ - SELECT c.id, c.name, c.specialty, c.rating - FROM relationships r - JOIN contractors c ON c.id = r.to_id - WHERE r.from_id = :pid - AND r.from_type = 'property' - AND r.to_type = 'contractor' - AND r.relationship_type = 'serviced_by' - """ - ), - {"pid": property_id}, - ) - for contractor in contractors.all(): - nodes.append( - GraphNode( - id=str(contractor.id), - type="contractor", - label=contractor.name, - metadata={ - "specialty": contractor.specialty or "", - "rating": contractor.rating, - }, - ) - ) - edges.append( - GraphEdge( - source=str(prop_row.id), - target=str(contractor.id), - relationship="serviced_by", - ) - ) - - log.info( - "properties.graph", - property_id=str(property_id), - nodes=len(nodes), - edges=len(edges), - ) - return PropertyGraph(property_id=property_id, nodes=nodes, edges=edges) - - -@router.post("", response_model=PropertyCreateResponse, status_code=201) -async def create_property( - payload: PropertyCreateRequest, - session: AsyncSession = Depends(get_session), -) -> PropertyCreateResponse: - """Create a property and kick off Tavily enrichment (runs once, per Part IV).""" - result = await session.execute( - text( - """ - INSERT INTO properties (name, address, aliases, owner_id, building_id) - VALUES (:name, :addr, :aliases, :owner, :building) - RETURNING id - """ - ), - { - "name": payload.name, - "addr": payload.address, - "aliases": payload.aliases, - "owner": payload.owner_id, - "building": payload.building_id, - }, - ) - property_id: UUID = result.scalar_one() - await session.commit() - log.info("properties.create", property_id=str(property_id), name=payload.name) - - tavily_event_id = await enrich_property(property_id, payload.name, payload.address) - return PropertyCreateResponse( - id=property_id, - name=payload.name, - address=payload.address, - tavily_event_id=tavily_event_id, - ) - - -@router.post("/{property_id}/enrich", response_model=EnrichmentResponse) -async def enrich_existing_property( - property_id: UUID, - session: AsyncSession = Depends(get_session), -) -> EnrichmentResponse: - """Re-run Tavily enrichment for an existing (seeded) property. - - Idempotent — a second call is a no-op. Intended as an admin utility so - the seeded portfolio can show the "Updated from web sources" badge - without requiring a reseed. - """ - row = ( - await session.execute( - text("SELECT name, address FROM properties WHERE id = :pid"), - {"pid": property_id}, - ) - ).first() - if row is None: - raise HTTPException(status_code=404, detail="property not found") - before_count = ( - await session.execute( - text( - """ - SELECT COUNT(*) - FROM events - WHERE property_id = :pid AND source = 'web' - AND source_ref LIKE 'tavily:%' - """ - ), - {"pid": property_id}, - ) - ).scalar_one() - - event_id = await enrich_property(property_id, row.name, row.address) - return EnrichmentResponse( - property_id=property_id, - tavily_event_id=event_id, - already_enriched=event_id is None and int(before_count or 0) > 0, - ) - - -@router.get("/{property_id}/markdown", response_class=PlainTextResponse) -async def property_markdown( - property_id: UUID, - session: AsyncSession = Depends(get_session), -) -> PlainTextResponse: - """Return the canonical markdown document for a property. - - Phase 12 — reads the materialized ``property_files`` row when one - exists (the common path after the applier hook fired) and falls - back to a live render only when the cache is missing. The cache is - refreshed atomically on every fact write, so the materialized row - is guaranteed to reflect the current fact set. - - The fallback path does not write back from a GET handler; the next - fact write at this scope will populate it. ``materialize-all`` is - the explicit bootstrap path. 30-second public Cache-Control + ETag - based on ``last_rendered_at`` give browsers free perceived speed - without staleness risk (SSE / polling already invalidate on real - change). - """ - cached = ( - await session.execute( - text( - "SELECT content_md, last_rendered_at FROM property_files " - "WHERE property_id = :pid" - ), - {"pid": property_id}, - ) - ).first() - if cached is not None: - log.info( - "properties.markdown.cache_hit", - property_id=str(property_id), - length=len(cached.content_md), - ) - return PlainTextResponse( - content=cached.content_md, - media_type="text/markdown; charset=utf-8", - headers={ - "Cache-Control": "public, max-age=30", - "ETag": f'"{int(cached.last_rendered_at.timestamp())}"', - }, - ) - - try: - body = await render_markdown(session, property_id) - except ValueError as exc: - log.info("properties.markdown.not_found", property_id=str(property_id)) - raise HTTPException(status_code=404, detail=str(exc)) from exc - log.info( - "properties.markdown.cache_miss_render", - property_id=str(property_id), - length=len(body), - ) - return PlainTextResponse(content=body, media_type="text/markdown; charset=utf-8") - - -# Display labels per backend section enum. Keep in sync with the -# section names in ``backend.services.gemini.EXTRACTION_SCHEMA``. -_SECTION_LABELS: dict[str, str] = { - "overview": "Overview", - "tenants": "Tenants", - "lease": "Lease", - "maintenance": "Maintenance", - "financials": "Financials", - "compliance": "Compliance", - "activity": "Activity", - "patterns": "Patterns", - "building_financials": "Building Context", - "building_maintenance": "Building Context", - "building_compliance": "Building Context", - "liegenschaft_financials": "WEG Context", - "liegenschaft_maintenance": "WEG Context", - "liegenschaft_compliance": "WEG Context", -} - -# Sections that display under a "Context" heading rather than as a -# primary fact section — the frontend uses the ``isContext`` flag to -# render these with a quieter visual treatment. -_CONTEXT_SECTIONS: frozenset[str] = frozenset( - { - "building_financials", - "building_maintenance", - "building_compliance", - "liegenschaft_financials", - "liegenschaft_maintenance", - "liegenschaft_compliance", - } -) - -# Sources whose presence implies a fact came from an authoritative -# document rather than an email — surfaced verbatim in the UI's "via" -# label so PDFs read as "Mietvertrag.pdf" instead of just "letter". -_AUTHORITATIVE_DOCUMENT_TYPES: frozenset[str] = frozenset( - {"lease", "lease_addendum", "kaufvertrag", "structural_permit", "vermessungsprotokoll"} -) - - -def _build_stammdaten_section( - s: Stammdaten, lang: str -) -> PropertyFileSection | None: - """Emit a Stammdaten section mirroring the markdown view. - - Stammdaten lives outside the events/facts pipeline (it's the - authoritative lease/owner registry loaded at ingest), so each row - here carries ``source='stammdaten'`` and no ``fact_id`` — the edit - affordance stays hidden because there's no fact row to override. - """ - labels = CONTEXT_LABELS[lang] - rows: list[tuple[str, str]] = [] - - if s.unit_label: - rows.append((labels["unit"], s.unit_label)) - if s.lage: - rows.append(("Lage" if lang == "de" else "Location", s.lage)) - if s.size_qm is not None: - size_str = f"{s.size_qm:.1f} m²".replace(".0 ", " ") - rows.append((labels["size_qm"], size_str)) - if s.rooms is not None: - rooms_str = f"{s.rooms:.1f}".rstrip("0").rstrip(".") or "0" - rows.append((labels["rooms"], rooms_str)) - if s.owner_name: - rows.append((labels["owner"], s.owner_name)) - if s.tenant_name: - rows.append((labels["tenant"], s.tenant_name)) - if s.mietbeginn: - rows.append((labels["lease_start"], s.mietbeginn)) - rows.append( - ( - labels["lease_end"], - s.mietende if s.mietende else labels["lease_open_ended"], - ) - ) - kalt = _format_eur(s.kaltmiete) - if kalt: - rows.append((labels["rent_cold"], kalt)) - nk = _format_eur(s.nk_vorauszahlung) - if nk: - rows.append((labels["operating_costs"], nk)) - kaution = _format_eur(s.kaution) - if kaution: - rows.append((labels["deposit"], kaution)) - - facts: list[PropertyFileFact] = [] - if not s.tenant_name: - facts.append( - PropertyFileFact( - value=labels["no_active_tenant"], - source="stammdaten", - date="", - section="stammdaten", - field="tenant", - ) - ) - for label, value in rows: - facts.append( - PropertyFileFact( - value=f"{label}: {value}", - source="stammdaten", - date="", - section="stammdaten", - field=label.lower().replace(" ", "_"), - ) - ) - - if not facts: - return None - return PropertyFileSection( - title=labels["stammdaten"], - facts=facts, - is_context=False, - ) - - -def _build_context_section( - events: list[dict[str, str | int]], - *, - title: str, -) -> PropertyFileSection | None: - """Turn recent building/liegenschaft events into a context section. - - Each event becomes a read-only fact: source pill = the event source - (``email``/``bank``/``invoice``), event_id wires the source modal, - no ``fact_id`` (these aren't facts — they're parent-tier activity). - """ - facts: list[PropertyFileFact] = [] - for ev in events: - received_iso = str(ev.get("received_at") or "") - date_short = received_iso[:10] if received_iso else "" - facts.append( - PropertyFileFact( - value=_context_body(ev), - source=str(ev.get("source") or ""), - date=date_short, - date_iso=received_iso or None, - section="context", - field=str(ev.get("kategorie") or ""), - event_id=str(ev.get("id") or "") or None, - ) - ) - if not facts: - return None - return PropertyFileSection( - title=title, - facts=facts, - is_context=True, - ) - - -@router.get("/{property_id}/file", response_model=PropertyFile) -async def property_file( - property_id: UUID, - session: AsyncSession = Depends(get_session), -) -> PropertyFile: - """Return the structured property file — sections + facts + uncertainties. - - The frontend's ``PropertyDetail`` page renders one section per group - with a ``[source]`` button on each fact that opens the originating - event. Open ``uncertainty_events`` are appended as a ``Needs Review`` - section so the user sees gaps explicitly rather than silently. - - The view is a true superset of the markdown: Stammdaten, Building - Context, and WEG Context are surfaced here too so a property with - zero extracted facts still renders its master record + parent-tier - activity instead of an empty placeholder. - """ - meta_row = ( - await session.execute( - text( - """ - SELECT id, name, address - FROM properties - WHERE id = :pid - """ - ), - {"pid": property_id}, - ) - ).first() - if meta_row is None: - raise HTTPException(status_code=404, detail="property not found") - - fact_rows = ( - await session.execute( - text( - """ - SELECT f.id AS fact_id, - f.section, f.field, f.value, f.confidence, - f.created_at, - f.human_edited, f.edited_by, - e.source AS event_source, - e.received_at AS event_received_at, - e.metadata->>'document_type' AS document_type, - f.source_event_id - FROM facts f - LEFT JOIN events e ON e.id = f.source_event_id - WHERE f.property_id = :pid - AND f.superseded_by IS NULL - ORDER BY f.section ASC, f.created_at DESC - """ - ), - {"pid": property_id}, - ) - ).all() - - uncertainty_rows = ( - await session.execute( - text( - """ - SELECT observation, hypothesis, reason_uncertain, - relevant_section, created_at - FROM uncertainty_events - WHERE property_id = :pid - AND status = 'open' - ORDER BY created_at DESC - """ - ), - {"pid": property_id}, - ) - ).all() - - grouped: dict[str, list[PropertyFileFact]] = {} - title_order: list[str] = [] - context_titles: set[str] = set() - - for row in fact_rows: - title = _SECTION_LABELS.get(row.section, row.section.replace("_", " ").title()) - if title not in grouped: - grouped[title] = [] - title_order.append(title) - if row.section in _CONTEXT_SECTIONS: - context_titles.add(title) - - # Prefer the document type for source labels (so PDFs show as - # ``Mietvertrag`` rather than ``letter``); fall back to the raw - # event source; ``stammdaten`` for facts that were never linked - # to an event (master-data load). Hand-edited facts overshadow - # all of these — the human is the source of truth. - doc_type = (row.document_type or "").strip() - if row.human_edited: - source_label = "operator" - elif doc_type and doc_type in _AUTHORITATIVE_DOCUMENT_TYPES: - source_label = doc_type - elif row.event_source: - source_label = row.event_source - else: - source_label = "stammdaten" - - when = row.event_received_at or row.created_at - grouped[title].append( - PropertyFileFact( - value=row.value, - source=source_label, - date=when.date().isoformat(), - date_iso=when.isoformat() if when else None, - confidence=( - float(row.confidence) if row.confidence is not None else None - ), - section=row.section, - field=row.field, - event_id=str(row.source_event_id) if row.source_event_id else None, - fact_id=str(row.fact_id), - human_edited=bool(row.human_edited), - edited_by=row.edited_by, - ) - ) - - sections: list[PropertyFileSection] = [ - PropertyFileSection( - title=title, - facts=grouped[title], - is_context=title in context_titles, - ) - for title in title_order - ] - - if uncertainty_rows: - review_facts: list[PropertyFileFact] = [] - for u in uncertainty_rows: - value = u.observation - if u.hypothesis: - value = f"{u.observation} — {u.hypothesis}" - review_facts.append( - PropertyFileFact( - value=value, - source="extractor", - date=u.created_at.date().isoformat(), - date_iso=u.created_at.isoformat() if u.created_at else None, - reason=u.reason_uncertain, - section=u.relevant_section or "", - field="", - ) - ) - sections.append( - PropertyFileSection( - title="Needs Review (Zu prüfen)", - facts=review_facts, - is_uncertain=True, - ) - ) - - # Stammdaten + parent-tier context — same data the markdown view - # surfaces. Detect language once so labels match the property's - # dominant event language. - lang = await _detect_property_language(session, property_id) - - stammdaten = await _fetch_stammdaten(session, property_id) - stammdaten_section = ( - _build_stammdaten_section(stammdaten, lang) if stammdaten else None - ) - if stammdaten_section is not None: - # Stammdaten is the master record — prepend so it reads first. - sections.insert(0, stammdaten_section) - - building_id, _ = await _building_for_property(session, property_id) - if building_id is not None: - building_events = await _recent_events_for_scope( - session, - scope="building", - scope_id=building_id, - limit=CONTEXT_LIMIT, - ) - building_section = _build_context_section( - building_events, title=CONTEXT_LABELS[lang]["building_context"] - ) - if building_section is not None: - sections.append(building_section) - - liegenschaft_id, _ = await _liegenschaft_for_building(session, building_id) - if liegenschaft_id is not None: - weg_events = await _recent_events_for_scope( - session, - scope="liegenschaft", - scope_id=liegenschaft_id, - limit=CONTEXT_LIMIT, - ) - weg_section = _build_context_section( - weg_events, title=CONTEXT_LABELS[lang]["weg_context"] - ) - if weg_section is not None: - sections.append(weg_section) - - log.info( - "properties.file.render", - property_id=str(property_id), - sections=len(sections), - facts=sum(len(s.facts) for s in sections), - ) - return PropertyFile( - id=meta_row.id, - name=meta_row.name, - address=meta_row.address, - sections=sections, - ) - - -class FactEditRequest(BaseModel): - """Operator override of a fact value. - - ``edited_by`` defaults to ``operator``; pass a real user identifier - when the UI has one. The endpoint sets ``human_edited=true`` on the - new row, which the differ honors against future extractor proposals - (see ``backend/pipeline/differ.py`` resolution rules). - """ - - value: str = Field(..., min_length=1, max_length=4_000) - edited_by: str = Field(default="operator", min_length=1, max_length=120) - - -class FactEditResponse(BaseModel): - """Result of a fact override — both the new and the superseded id.""" - - fact_id: UUID - superseded_fact_id: UUID - property_id: UUID - section: str - field: str - value: str - edited_by: str - edited_at: datetime - - -@router.patch( - "/{property_id}/facts/{fact_id}", - response_model=FactEditResponse, -) -async def edit_fact( - property_id: UUID, - fact_id: UUID, - body: FactEditRequest, - session: AsyncSession = Depends(get_session), -) -> FactEditResponse: - """Operator override of a single fact. - - Inserts a new fact row carrying the operator's value with - ``human_edited=true`` and supersedes the existing row, preserving - the original ``source_event_id`` so the trace remains intact. The - extractor's resolution rules treat ``human_edited`` rows as sticky: - future proposals against the same ``(property_id, section, field)`` - coordinate are skipped with a ``preserved_human_edit`` reason. - - Broadcasts a ``fact_update`` payload on the event bus so the - portfolio bell + per-property SSE listeners refresh in place. - """ - current = ( - await session.execute( - text( - """ - SELECT id, property_id, section, field, value, - source_event_id, building_id, liegenschaft_id - FROM facts - WHERE id = :fid AND superseded_by IS NULL - """ - ), - {"fid": fact_id}, - ) - ).first() - if current is None: - raise HTTPException( - status_code=404, - detail="fact not found or already superseded", - ) - if current.property_id != property_id: - raise HTTPException( - status_code=400, - detail="fact does not belong to this property", - ) - - new_value = body.value.strip() - if not new_value: - raise HTTPException(status_code=400, detail="value must not be blank") - if new_value == current.value: - raise HTTPException(status_code=400, detail="value unchanged") - - inserted = ( - await session.execute( - text( - """ - INSERT INTO facts ( - property_id, section, field, value, source_event_id, - confidence, valid_from, building_id, liegenschaft_id, - human_edited, edited_by, edited_at - ) VALUES ( - :pid, :section, :field, :value, :src, 1.0, now(), - :bid, :lid, TRUE, :who, now() - ) - RETURNING id, edited_at - """ - ), - { - "pid": property_id, - "section": current.section, - "field": current.field, - "value": new_value, - "src": current.source_event_id, - "bid": current.building_id, - "lid": current.liegenschaft_id, - "who": body.edited_by, - }, - ) - ).first() - if inserted is None: # pragma: no cover — RETURNING always yields a row - raise HTTPException(status_code=500, detail="insert failed") - - await session.execute( - text( - """ - UPDATE facts - SET superseded_by = :new_id, valid_to = now() - WHERE id = :old_id - """ - ), - {"new_id": inserted.id, "old_id": current.id}, - ) - - edit_summary = f"{body.edited_by} edited {current.section}.{current.field}" - await propagate_after_fact_write( - session, - property_id=property_id, - building_id=current.building_id, - liegenschaft_id=current.liegenschaft_id, - trigger_event_id=current.source_event_id, - trigger_summary=edit_summary, - ) - await session.commit() - - log.info( - "properties.fact.edited", - property_id=str(property_id), - new_fact_id=str(inserted.id), - superseded_fact_id=str(current.id), - section=current.section, - field=current.field, - edited_by=body.edited_by, - ) - - await get_event_bus().publish( - property_id, - { - "event_id": None, - "property_id": str(property_id), - "category": "fact.edited", - "summary": f"{body.edited_by} edited {current.section}.{current.field}", - "facts_written": 1, - }, - ) - - return FactEditResponse( - fact_id=inserted.id, - superseded_fact_id=current.id, - property_id=property_id, - section=current.section, - field=current.field, - value=new_value, - edited_by=body.edited_by, - edited_at=inserted.edited_at, - ) - - -class ActivityItem(BaseModel): - """Activity feed row — a processed event + its one-line summary.""" - - event_id: UUID - source: str - received_at: datetime - processed_at: datetime | None - summary: str | None - facts_written: int - - -@router.get("/{property_id}/activity", response_model=list[ActivityItem]) -async def property_activity( - property_id: UUID, - limit: int = Query(default=50, ge=1, le=200), - session: AsyncSession = Depends(get_session), -) -> list[ActivityItem]: - """Return the ``limit`` most recent events + extraction summary for this property.""" - result = await session.execute( - text( - """ - SELECT e.id, e.source, e.received_at, e.processed_at, - sum.value AS summary, - (SELECT COUNT(*) FROM facts f WHERE f.source_event_id = e.id) AS facts_written - FROM events e - LEFT JOIN LATERAL ( - SELECT value FROM facts - WHERE source_event_id = e.id AND section = 'activity' - ORDER BY created_at ASC LIMIT 1 - ) sum ON TRUE - WHERE e.property_id = :pid - ORDER BY e.received_at DESC - LIMIT :lim - """ - ), - {"pid": property_id, "lim": limit}, - ) - items = [ - ActivityItem( - event_id=row.id, - source=row.source, - received_at=row.received_at, - processed_at=row.processed_at, - summary=row.summary, - facts_written=int(row.facts_written or 0), - ) - for row in result.all() - ] - log.info("properties.activity", property_id=str(property_id), count=len(items)) - return items - - -# ----------------------------------------------------------------------------- -# Phase 11 — property-scoped Q&A -# ----------------------------------------------------------------------------- - - -class AskRequest(BaseModel): - """Payload for ``POST /properties/{id}/ask``.""" - - question: str = Field(..., min_length=1, max_length=600) - - -class AskSourceItem(BaseModel): - """Source citation used by both ``answered`` and ``insufficient_context``.""" - - id: str - channel: str - date: str - snippet: str - - -class AskResponse(BaseModel): - """Q&A response with three status branches the frontend renders distinctly. - - Phase 9 trust-layer rule: an honest "I don't know" beats a confident - hallucination. The ``insufficient_context`` and ``out_of_scope`` - branches keep ``answer`` ``None`` and surface the partial-context - or out-of-scope reasoning explicitly. - """ - - status: str # 'answered' | 'insufficient_context' | 'out_of_scope' - answer: str | None - confidence: str - reasoning: str = "" - sources: list[AskSourceItem] = Field(default_factory=list) - partial_context: list[AskSourceItem] = Field(default_factory=list) - elapsed_ms: float - retrieved_count: int - model: str - - -async def _fetch_ask_context( - session: AsyncSession, property_id: UUID -) -> tuple[list[dict[str, Any]], dict[str, dict[str, str]]]: - """Pull recent events for citation + a lookup mapping event_id → citation shape. - - The canonical context for the LLM is the rendered property markdown - (fetched separately via :func:`render_markdown`). This helper only - returns the raw event snippets that let Pioneer quote source text - directly; the citation_lookup joins those event ids back to the - ``{id, channel, date, snippet}`` shape the frontend expects. - """ - event_rows = ( - await session.execute( - text( - """ - SELECT e.id, e.source, - COALESCE(e.received_at, e.processed_at, now()) AS rec, - LEFT(COALESCE(e.raw_content, ''), 320) AS snippet - FROM events e - WHERE e.property_id = :pid - AND COALESCE(e.received_at, e.processed_at) > now() - interval '90 days' - ORDER BY rec DESC - LIMIT 12 - """ - ), - {"pid": property_id}, - ) - ).all() - events: list[dict[str, Any]] = [] - citation_lookup: dict[str, dict[str, str]] = {} - for r in event_rows: - eid = str(r.id) - snippet = str(r.snippet or "").replace("\n", " ").strip() - events.append( - { - "id": eid, - "source": str(r.source), - "received_at": r.rec.isoformat() if r.rec else "", - "snippet": snippet, - } - ) - citation_lookup[eid] = { - "id": eid, - "channel": str(r.source), - "date": r.rec.date().isoformat() if r.rec else "", - "snippet": snippet[:240], - } - return events, citation_lookup - - -@router.post("/{property_id}/ask", response_model=AskResponse) -async def property_ask( - property_id: UUID, - payload: AskRequest, - session: AsyncSession = Depends(get_session), -) -> AskResponse: - """Answer a question scoped to one property's facts + recent events.""" - meta_row = ( - await session.execute( - text("SELECT name FROM properties WHERE id = :pid"), - {"pid": property_id}, - ) - ).first() - if meta_row is None: - raise HTTPException(status_code=404, detail="property not found") - - events, citation_lookup = await _fetch_ask_context(session, property_id) - try: - property_file_markdown = await render_markdown(session, property_id) - except ValueError as exc: - # Should be unreachable — the property existence check above - # already 404s — but guard anyway so we never feed a half-built - # prompt to Pioneer. - log.warning("properties.ask.render_failed", error=str(exc)) - raise HTTPException(status_code=404, detail="property not found") from exc - - try: - result = await ask_service.answer_question( - property_name=str(meta_row.name), - question=payload.question, - property_file_markdown=property_file_markdown, - recent_events=events, - ) - except pioneer_llm.PioneerUnavailable as exc: - log.warning("properties.ask.unavailable", error=str(exc)) - raise HTTPException( - status_code=503, - detail=f"ask service unavailable: {exc}", - ) from exc - - sources: list[AskSourceItem] = [] - partial_context: list[AskSourceItem] = [] - for eid in result["cited_event_ids"]: - cite = citation_lookup.get(eid) - if cite is not None: - sources.append(AskSourceItem(**cite)) - for eid in result["partial_context_event_ids"]: - cite = citation_lookup.get(eid) - if cite is not None: - partial_context.append(AskSourceItem(**cite)) - - log.info( - "properties.ask.respond", - property_id=str(property_id), - status=result["status"], - sources=len(sources), - partial=len(partial_context), - retrieved=len(events), - ) - - return AskResponse( - status=result["status"], - answer=result["answer"], - confidence=result["confidence"], - reasoning=result["reasoning"], - sources=sources, - partial_context=partial_context, - elapsed_ms=float(result["latency_ms"]), - retrieved_count=len(events), - model=str(result["model"]), - ) - - -# ----------------------------------------------------------------------------- -# Phase 11 — raw inbox view for Compare page ("today: search the inbox") -# ----------------------------------------------------------------------------- - - -class InboxEmail(BaseModel): - """One raw email row for the "before Keystone" Compare view.""" - - event_id: UUID - date: str - sender: str - subject: str - preview: str - relevant: bool = Field( - default=False, - description=( - "True when the search keyword(s) appeared in the raw body. " - "Used to highlight matching rows visually." - ), - ) - - -class InboxResponse(BaseModel): - """Response for ``GET /properties/{id}/inbox``.""" - - rows: list[InboxEmail] - total_inbox_size: int = Field( - ..., - description="Total email events for this property (the haystack size).", - ) - relevant_count: int - keyword: str | None - - -def _extract_subject_and_from(raw: str) -> tuple[str, str]: - """Cheap RFC-822-ish subject/from parser. Falls back to first line.""" - subject = "" - sender = "" - for line in raw.splitlines(): - lower = line.lower() - if not subject and lower.startswith("subject:"): - subject = line.split(":", 1)[1].strip() - elif not sender and lower.startswith("from:"): - sender = line.split(":", 1)[1].strip() - if subject and sender: - break - if not subject: - subject = raw.strip().split("\n", 1)[0][:80] - return subject, sender - - -@router.get("/{property_id}/inbox", response_model=InboxResponse) -async def property_inbox( - property_id: UUID, - q: str | None = Query( - default=None, - description="Optional keyword. Rows whose raw body matches are flagged ``relevant=True``.", - ), - limit: int = Query(default=20, ge=1, le=100), - session: AsyncSession = Depends(get_session), -) -> InboxResponse: - """Email-style inbox view for the Compare page's "before" panel. - - Returns the property's most-recent email events with a parsed - ``subject`` / ``from`` / ``preview``. When ``q`` is supplied the - LIKE filter highlights matches but the list still shows the - surrounding noise — that's the point of the comparison: the - operator scrolls through everything, Keystone returns one answer. - """ - total = ( - await session.execute( - text( - """ - SELECT COUNT(*) FROM events - WHERE property_id = :pid AND source = 'email' - """ - ), - {"pid": property_id}, - ) - ).scalar_one() - - pattern = f"%{q}%" if q else None - relevant_count = 0 - if pattern: - relevant_count = ( - await session.execute( - text( - """ - SELECT COUNT(*) FROM events - WHERE property_id = :pid AND source = 'email' - AND raw_content ILIKE :pat - """ - ), - {"pid": property_id, "pat": pattern}, - ) - ).scalar_one() - - rows = ( - await session.execute( - text( - """ - SELECT id, - COALESCE(received_at, processed_at) AS dt, - LEFT(COALESCE(raw_content, ''), 600) AS body, - (CASE WHEN CAST(:pat AS text) IS NOT NULL - AND raw_content ILIKE CAST(:pat AS text) - THEN TRUE ELSE FALSE END) AS is_relevant - FROM events - WHERE property_id = :pid AND source = 'email' - ORDER BY COALESCE(received_at, processed_at) DESC - LIMIT :lim - """ - ), - {"pid": property_id, "pat": pattern, "lim": limit}, - ) - ).all() - - items: list[InboxEmail] = [] - for r in rows: - body = str(r.body or "") - subject, sender = _extract_subject_and_from(body) - body_text = body - # Strip headers from preview - for hdr in ("From:", "Subject:", "Date:", "To:", "Message-ID:"): - for line in body_text.splitlines(): - if line.lower().startswith(hdr.lower()): - body_text = body_text.replace(line + "\n", "") - preview = body_text.replace("\n", " ").strip()[:120] - items.append( - InboxEmail( - event_id=r.id, - date=r.dt.date().isoformat() if r.dt else "", - sender=sender or "(unknown)", - subject=subject or "(no subject)", - preview=preview, - relevant=bool(r.is_relevant), - ) - ) - - log.info( - "properties.inbox", - property_id=str(property_id), - q=q, - returned=len(items), - total=int(total), - relevant=int(relevant_count), - ) - return InboxResponse( - rows=items, - total_inbox_size=int(total), - relevant_count=int(relevant_count), - keyword=q, - ) diff --git a/backend/api/properties/__init__.py b/backend/api/properties/__init__.py new file mode 100644 index 0000000..619b3c6 --- /dev/null +++ b/backend/api/properties/__init__.py @@ -0,0 +1,15 @@ +"""Properties API, assembled from one module per resource under ``/properties``.""" + +from fastapi import APIRouter + +from backend.api.properties import activity, ask, facts, file, graph, inbox, listing + +router = APIRouter(tags=["properties"]) +# The prefix goes on each include rather than on ``router``: FastAPI refuses +# to include the listing route (path "") under an empty prefix. +# Listing and search first: their static paths are matched before the +# /{property_id}/... routes, as in the original single module. +for module in (listing, graph, file, facts, activity, ask, inbox): + router.include_router(module.router, prefix="/properties") + +__all__ = ["router"] diff --git a/backend/api/properties/activity.py b/backend/api/properties/activity.py new file mode 100644 index 0000000..c778f74 --- /dev/null +++ b/backend/api/properties/activity.py @@ -0,0 +1,69 @@ +"""Recent activity feed for one property.""" + +from __future__ import annotations + +from datetime import datetime +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class ActivityItem(BaseModel): + """Activity feed row: a processed event + its one-line summary.""" + + event_id: UUID + source: str + received_at: datetime + processed_at: datetime | None + summary: str | None + facts_written: int + + +@router.get("/{property_id}/activity", response_model=list[ActivityItem]) +async def property_activity( + property_id: UUID, + limit: int = Query(default=50, ge=1, le=200), + session: AsyncSession = Depends(get_session), +) -> list[ActivityItem]: + """Return the ``limit`` most recent events + extraction summary for this property.""" + result = await session.execute( + text( + """ + SELECT e.id, e.source, e.received_at, e.processed_at, + sum.value AS summary, + (SELECT COUNT(*) FROM facts f WHERE f.source_event_id = e.id) AS facts_written + FROM events e + LEFT JOIN LATERAL ( + SELECT value FROM facts + WHERE source_event_id = e.id AND section = 'activity' + ORDER BY created_at ASC LIMIT 1 + ) sum ON TRUE + WHERE e.property_id = :pid + ORDER BY e.received_at DESC + LIMIT :lim + """ + ), + {"pid": property_id, "lim": limit}, + ) + items = [ + ActivityItem( + event_id=row.id, + source=row.source, + received_at=row.received_at, + processed_at=row.processed_at, + summary=row.summary, + facts_written=int(row.facts_written or 0), + ) + for row in result.all() + ] + log.info("properties.activity", property_id=str(property_id), count=len(items)) + return items diff --git a/backend/api/properties/ask.py b/backend/api/properties/ask.py new file mode 100644 index 0000000..1f06fac --- /dev/null +++ b/backend/api/properties/ask.py @@ -0,0 +1,182 @@ +"""Property-scoped questions answered from the property file, with citations.""" + +from __future__ import annotations + +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session +from backend.pipeline.renderer import ( + render_markdown, +) +from backend.services import ask as ask_service +from backend.services.llm import LLMUnavailableError + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class AskRequest(BaseModel): + """Payload for ``POST /properties/{id}/ask``.""" + + question: str = Field(..., min_length=1, max_length=600) + + +class AskSourceItem(BaseModel): + """Source citation used by both ``answered`` and ``insufficient_context``.""" + + id: str + channel: str + date: str + snippet: str + + +class AskResponse(BaseModel): + """Q&A response with three status branches the frontend renders distinctly. + + Trust rule: an honest "I don't know" beats a confident + hallucination, because an operator acting on a wrong answer costs + more than one who goes and checks. The ``insufficient_context`` and ``out_of_scope`` + branches keep ``answer`` ``None`` and surface the partial-context + or out-of-scope reasoning explicitly. + """ + + status: str # 'answered' | 'insufficient_context' | 'out_of_scope' + answer: str | None + confidence: str + reasoning: str = "" + sources: list[AskSourceItem] = Field(default_factory=list) + partial_context: list[AskSourceItem] = Field(default_factory=list) + elapsed_ms: float + retrieved_count: int + model: str + + +async def _fetch_ask_context( + session: AsyncSession, property_id: UUID +) -> tuple[list[dict[str, Any]], dict[str, dict[str, str]]]: + """Pull recent events for citation + a lookup mapping event_id → citation shape. + + The canonical context for the LLM is the rendered property markdown + (fetched separately via :func:`render_markdown`). This helper only + returns the raw event snippets that let Pioneer quote source text + directly; the citation_lookup joins those event ids back to the + ``{id, channel, date, snippet}`` shape the frontend expects. + """ + event_rows = ( + await session.execute( + text( + """ + SELECT e.id, e.source, + COALESCE(e.received_at, e.processed_at, now()) AS rec, + LEFT(COALESCE(e.raw_content, ''), 320) AS snippet + FROM events e + WHERE e.property_id = :pid + AND COALESCE(e.received_at, e.processed_at) > now() - interval '90 days' + ORDER BY rec DESC + LIMIT 12 + """ + ), + {"pid": property_id}, + ) + ).all() + events: list[dict[str, Any]] = [] + citation_lookup: dict[str, dict[str, str]] = {} + for r in event_rows: + eid = str(r.id) + snippet = str(r.snippet or "").replace("\n", " ").strip() + events.append( + { + "id": eid, + "source": str(r.source), + "received_at": r.rec.isoformat() if r.rec else "", + "snippet": snippet, + } + ) + citation_lookup[eid] = { + "id": eid, + "channel": str(r.source), + "date": r.rec.date().isoformat() if r.rec else "", + "snippet": snippet[:240], + } + return events, citation_lookup + + +@router.post("/{property_id}/ask", response_model=AskResponse) +async def property_ask( + property_id: UUID, + payload: AskRequest, + session: AsyncSession = Depends(get_session), +) -> AskResponse: + """Answer a question scoped to one property's facts + recent events.""" + meta_row = ( + await session.execute( + text("SELECT name FROM properties WHERE id = :pid"), + {"pid": property_id}, + ) + ).first() + if meta_row is None: + raise HTTPException(status_code=404, detail="property not found") + + events, citation_lookup = await _fetch_ask_context(session, property_id) + try: + property_file_markdown = await render_markdown(session, property_id) + except ValueError as exc: + # Should be unreachable: the property existence check above + # already 404s, but guard anyway so a half-built prompt is never sent. + log.warning("properties.ask.render_failed", error=str(exc)) + raise HTTPException(status_code=404, detail="property not found") from exc + + try: + result = await ask_service.answer_question( + property_name=str(meta_row.name), + question=payload.question, + property_file_markdown=property_file_markdown, + recent_events=events, + ) + except LLMUnavailableError as exc: + # Covers both "no provider configured" (the message names the missing + # variable) and "provider call failed". + log.warning("properties.ask.unavailable", error=str(exc)[:300]) + raise HTTPException( + status_code=503, + detail=f"Ask is unavailable: {exc}", + ) from exc + + sources: list[AskSourceItem] = [] + partial_context: list[AskSourceItem] = [] + for eid in result["cited_event_ids"]: + cite = citation_lookup.get(eid) + if cite is not None: + sources.append(AskSourceItem(**cite)) + for eid in result["partial_context_event_ids"]: + cite = citation_lookup.get(eid) + if cite is not None: + partial_context.append(AskSourceItem(**cite)) + + log.info( + "properties.ask.respond", + property_id=str(property_id), + status=result["status"], + sources=len(sources), + partial=len(partial_context), + retrieved=len(events), + ) + + return AskResponse( + status=result["status"], + answer=result["answer"], + confidence=result["confidence"], + reasoning=result["reasoning"], + sources=sources, + partial_context=partial_context, + elapsed_ms=float(result["latency_ms"]), + retrieved_count=len(events), + model=str(result["model"]), + ) diff --git a/backend/api/properties/facts.py b/backend/api/properties/facts.py new file mode 100644 index 0000000..72de22b --- /dev/null +++ b/backend/api/properties/facts.py @@ -0,0 +1,182 @@ +"""Operator corrections to individual facts.""" + +from __future__ import annotations + +from datetime import datetime +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session +from backend.pipeline.events import get_event_bus +from backend.pipeline.materializer import propagate_after_fact_write + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class FactEditRequest(BaseModel): + """Operator override of a fact value. + + ``edited_by`` defaults to ``operator``; pass a real user identifier + when the UI has one. The endpoint sets ``human_edited=true`` on the + new row, which the differ honors against future extractor proposals + (see ``backend/pipeline/differ.py`` resolution rules). + """ + + value: str = Field(..., min_length=1, max_length=4_000) + edited_by: str = Field(default="operator", min_length=1, max_length=120) + + +class FactEditResponse(BaseModel): + """Result of a fact override: both the new and the superseded id.""" + + fact_id: UUID + superseded_fact_id: UUID + property_id: UUID + section: str + field: str + value: str + edited_by: str + edited_at: datetime + + +@router.patch( + "/{property_id}/facts/{fact_id}", + response_model=FactEditResponse, +) +async def edit_fact( + property_id: UUID, + fact_id: UUID, + body: FactEditRequest, + session: AsyncSession = Depends(get_session), +) -> FactEditResponse: + """Operator override of a single fact. + + Inserts a new fact row carrying the operator's value with + ``human_edited=true`` and supersedes the existing row, preserving + the original ``source_event_id`` so the trace remains intact. The + extractor's resolution rules treat ``human_edited`` rows as sticky: + future proposals against the same ``(property_id, section, field)`` + coordinate are skipped with a ``preserved_human_edit`` reason. + + Broadcasts a ``fact_update`` payload on the event bus so the + portfolio bell + per-property SSE listeners refresh in place. + """ + current = ( + await session.execute( + text( + """ + SELECT id, property_id, section, field, value, + source_event_id, building_id, liegenschaft_id + FROM facts + WHERE id = :fid AND superseded_by IS NULL + """ + ), + {"fid": fact_id}, + ) + ).first() + if current is None: + raise HTTPException( + status_code=404, + detail="fact not found or already superseded", + ) + if current.property_id != property_id: + raise HTTPException( + status_code=400, + detail="fact does not belong to this property", + ) + + new_value = body.value.strip() + if not new_value: + raise HTTPException(status_code=400, detail="value must not be blank") + if new_value == current.value: + raise HTTPException(status_code=400, detail="value unchanged") + + inserted = ( + await session.execute( + text( + """ + INSERT INTO facts ( + property_id, section, field, value, source_event_id, + confidence, valid_from, building_id, liegenschaft_id, + human_edited, edited_by, edited_at + ) VALUES ( + :pid, :section, :field, :value, :src, 1.0, now(), + :bid, :lid, TRUE, :who, now() + ) + RETURNING id, edited_at + """ + ), + { + "pid": property_id, + "section": current.section, + "field": current.field, + "value": new_value, + "src": current.source_event_id, + "bid": current.building_id, + "lid": current.liegenschaft_id, + "who": body.edited_by, + }, + ) + ).first() + if inserted is None: # pragma: no cover (RETURNING always yields a row) + raise HTTPException(status_code=500, detail="insert failed") + + await session.execute( + text( + """ + UPDATE facts + SET superseded_by = :new_id, valid_to = now() + WHERE id = :old_id + """ + ), + {"new_id": inserted.id, "old_id": current.id}, + ) + + edit_summary = f"{body.edited_by} edited {current.section}.{current.field}" + await propagate_after_fact_write( + session, + property_id=property_id, + building_id=current.building_id, + liegenschaft_id=current.liegenschaft_id, + trigger_event_id=current.source_event_id, + trigger_summary=edit_summary, + ) + await session.commit() + + log.info( + "properties.fact.edited", + property_id=str(property_id), + new_fact_id=str(inserted.id), + superseded_fact_id=str(current.id), + section=current.section, + field=current.field, + edited_by=body.edited_by, + ) + + await get_event_bus().publish( + property_id, + { + "event_id": None, + "property_id": str(property_id), + "category": "fact.edited", + "summary": f"{body.edited_by} edited {current.section}.{current.field}", + "facts_written": 1, + }, + ) + + return FactEditResponse( + fact_id=inserted.id, + superseded_fact_id=current.id, + property_id=property_id, + section=current.section, + field=current.field, + value=new_value, + edited_by=body.edited_by, + edited_at=inserted.edited_at, + ) diff --git a/backend/api/properties/file.py b/backend/api/properties/file.py new file mode 100644 index 0000000..6442dd1 --- /dev/null +++ b/backend/api/properties/file.py @@ -0,0 +1,294 @@ +"""The property file: rendered markdown and the structured, sectioned view.""" + +from __future__ import annotations + +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, HTTPException +from fastapi.responses import PlainTextResponse +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.api.properties.file_sections import ( + _AUTHORITATIVE_DOCUMENT_TYPES, + _CONTEXT_SECTIONS, + _SECTION_LABELS, + PropertyFile, + PropertyFileFact, + PropertyFileSection, + _build_context_section, + _build_stammdaten_section, +) +from backend.db.session import get_session +from backend.pipeline.renderer import ( + CONTEXT_LABELS, + CONTEXT_LIMIT, + _building_for_property, + _detect_property_language, + _fetch_stammdaten, + _liegenschaft_for_building, + _recent_events_for_scope, + render_markdown, +) + +router = APIRouter() +log = structlog.get_logger(__name__) + + +@router.get("/{property_id}/markdown", response_class=PlainTextResponse) +async def property_markdown( + property_id: UUID, + session: AsyncSession = Depends(get_session), +) -> PlainTextResponse: + """Return the canonical markdown document for a property. + + Reads the materialized ``property_files`` row when one + exists (the common path after the applier hook fired) and falls + back to a live render only when the cache is missing. The cache is + refreshed atomically on every fact write, so the materialized row + is guaranteed to reflect the current fact set. + + The fallback path does not write back from a GET handler; the next + fact write at this scope will populate it. ``materialize-all`` is + the explicit bootstrap path. 30-second public Cache-Control + ETag + based on ``last_rendered_at`` give browsers free perceived speed + without staleness risk (SSE / polling already invalidate on real + change). + """ + cached = ( + await session.execute( + text( + "SELECT content_md, last_rendered_at FROM property_files WHERE property_id = :pid" + ), + {"pid": property_id}, + ) + ).first() + if cached is not None: + log.info( + "properties.markdown.cache_hit", + property_id=str(property_id), + length=len(cached.content_md), + ) + return PlainTextResponse( + content=cached.content_md, + media_type="text/markdown; charset=utf-8", + headers={ + "Cache-Control": "public, max-age=30", + "ETag": f'"{int(cached.last_rendered_at.timestamp())}"', + }, + ) + + try: + body = await render_markdown(session, property_id) + except ValueError as exc: + log.info("properties.markdown.not_found", property_id=str(property_id)) + raise HTTPException(status_code=404, detail=str(exc)) from exc + log.info( + "properties.markdown.cache_miss_render", + property_id=str(property_id), + length=len(body), + ) + return PlainTextResponse(content=body, media_type="text/markdown; charset=utf-8") + + +@router.get("/{property_id}/file", response_model=PropertyFile) +async def property_file( + property_id: UUID, + session: AsyncSession = Depends(get_session), +) -> PropertyFile: + """Return the structured property file: sections + facts + uncertainties. + + The frontend's ``PropertyDetail`` page renders one section per group + with a ``[source]`` button on each fact that opens the originating + event. Open ``uncertainty_events`` are appended as a ``Needs Review`` + section so the user sees gaps explicitly rather than silently. + + The view is a true superset of the markdown: Stammdaten, Building + Context, and WEG Context are surfaced here too so a property with + zero extracted facts still renders its master record + parent-tier + activity instead of an empty placeholder. + """ + meta_row = ( + await session.execute( + text( + """ + SELECT id, name, address + FROM properties + WHERE id = :pid + """ + ), + {"pid": property_id}, + ) + ).first() + if meta_row is None: + raise HTTPException(status_code=404, detail="property not found") + + fact_rows = ( + await session.execute( + text( + """ + SELECT f.id AS fact_id, + f.section, f.field, f.value, f.confidence, + f.created_at, + f.human_edited, f.edited_by, + e.source AS event_source, + e.received_at AS event_received_at, + e.metadata->>'document_type' AS document_type, + f.source_event_id + FROM facts f + LEFT JOIN events e ON e.id = f.source_event_id + WHERE f.property_id = :pid + AND f.superseded_by IS NULL + ORDER BY f.section ASC, f.created_at DESC + """ + ), + {"pid": property_id}, + ) + ).all() + + uncertainty_rows = ( + await session.execute( + text( + """ + SELECT observation, hypothesis, reason_uncertain, + relevant_section, created_at + FROM uncertainty_events + WHERE property_id = :pid + AND status = 'open' + ORDER BY created_at DESC + """ + ), + {"pid": property_id}, + ) + ).all() + + grouped: dict[str, list[PropertyFileFact]] = {} + title_order: list[str] = [] + context_titles: set[str] = set() + + for row in fact_rows: + title = _SECTION_LABELS.get(row.section, row.section.replace("_", " ").title()) + if title not in grouped: + grouped[title] = [] + title_order.append(title) + if row.section in _CONTEXT_SECTIONS: + context_titles.add(title) + + # Prefer the document type for source labels (so PDFs show as + # ``Mietvertrag`` rather than ``letter``); fall back to the raw + # event source; ``stammdaten`` for facts that were never linked + # to an event (master-data load). Hand-edited facts overshadow + # all of these: the human is the source of truth. + doc_type = (row.document_type or "").strip() + if row.human_edited: + source_label = "operator" + elif doc_type and doc_type in _AUTHORITATIVE_DOCUMENT_TYPES: + source_label = doc_type + elif row.event_source: + source_label = row.event_source + else: + source_label = "stammdaten" + + when = row.event_received_at or row.created_at + grouped[title].append( + PropertyFileFact( + value=row.value, + source=source_label, + date=when.date().isoformat(), + date_iso=when.isoformat() if when else None, + confidence=(float(row.confidence) if row.confidence is not None else None), + section=row.section, + field=row.field, + event_id=str(row.source_event_id) if row.source_event_id else None, + fact_id=str(row.fact_id), + human_edited=bool(row.human_edited), + edited_by=row.edited_by, + ) + ) + + sections: list[PropertyFileSection] = [ + PropertyFileSection( + title=title, + facts=grouped[title], + is_context=title in context_titles, + ) + for title in title_order + ] + + if uncertainty_rows: + review_facts: list[PropertyFileFact] = [] + for u in uncertainty_rows: + value = u.observation + if u.hypothesis: + value = f"{u.observation} (hypothesis: {u.hypothesis})" + review_facts.append( + PropertyFileFact( + value=value, + source="extractor", + date=u.created_at.date().isoformat(), + date_iso=u.created_at.isoformat() if u.created_at else None, + reason=u.reason_uncertain, + section=u.relevant_section or "", + field="", + ) + ) + sections.append( + PropertyFileSection( + title="Needs Review (Zu prüfen)", + facts=review_facts, + is_uncertain=True, + ) + ) + + # Stammdaten + parent-tier context: same data the markdown view + # surfaces. Detect language once so labels match the property's + # dominant event language. + lang = await _detect_property_language(session, property_id) + + stammdaten = await _fetch_stammdaten(session, property_id) + stammdaten_section = _build_stammdaten_section(stammdaten, lang) if stammdaten else None + if stammdaten_section is not None: + # Stammdaten is the master record; prepend so it reads first. + sections.insert(0, stammdaten_section) + + building_id, _ = await _building_for_property(session, property_id) + if building_id is not None: + building_events = await _recent_events_for_scope( + session, + scope="building", + scope_id=building_id, + limit=CONTEXT_LIMIT, + ) + building_section = _build_context_section( + building_events, title=CONTEXT_LABELS[lang]["building_context"] + ) + if building_section is not None: + sections.append(building_section) + + liegenschaft_id, _ = await _liegenschaft_for_building(session, building_id) + if liegenschaft_id is not None: + weg_events = await _recent_events_for_scope( + session, + scope="liegenschaft", + scope_id=liegenschaft_id, + limit=CONTEXT_LIMIT, + ) + weg_section = _build_context_section( + weg_events, title=CONTEXT_LABELS[lang]["weg_context"] + ) + if weg_section is not None: + sections.append(weg_section) + + log.info( + "properties.file.render", + property_id=str(property_id), + sections=len(sections), + facts=sum(len(s.facts) for s in sections), + ) + return PropertyFile( + id=meta_row.id, + name=meta_row.name, + address=meta_row.address, + sections=sections, + ) diff --git a/backend/api/properties/file_sections.py b/backend/api/properties/file_sections.py new file mode 100644 index 0000000..46586da --- /dev/null +++ b/backend/api/properties/file_sections.py @@ -0,0 +1,208 @@ +"""Response models and section builders for the structured property file.""" + +from __future__ import annotations + +from uuid import UUID + +from pydantic import BaseModel + +from backend.pipeline.renderer import ( + CONTEXT_LABELS, + Stammdaten, + _context_body, + _format_eur, +) + + +class PropertyFileFact(BaseModel): + """One row in a property file section, shaped for the frontend. + + Mirrors the UI's ``Fact`` type (``value`` / ``source`` / ``date``) and + surfaces ``section`` / ``field`` / ``event_id`` so the renderer can + deep-link to the originating event when the user clicks ``[source]``. + ``fact_id`` is the canonical pointer the edit endpoint needs; + ``human_edited`` flips the source label so the UI can render + ``via operator`` instead of ``via email`` for hand-edited rows. + """ + + value: str + source: str + date: str + date_iso: str | None = None + confidence: float | None = None + urgent: bool = False + reason: str | None = None + section: str + field: str + event_id: str | None = None + fact_id: str | None = None + human_edited: bool = False + edited_by: str | None = None + + +class PropertyFileSection(BaseModel): + """Display section grouping facts under a single heading.""" + + title: str + facts: list[PropertyFileFact] + is_uncertain: bool = False + is_context: bool = False + + +class PropertyFile(BaseModel): + """Structured payload powering the PropertyDetail page.""" + + id: UUID + name: str + address: str + sections: list[PropertyFileSection] + + +# Display labels per backend section enum. Keep in sync with the +# section names in ``backend.services.llm.extraction.EXTRACTION_SCHEMA``. +_SECTION_LABELS: dict[str, str] = { + "overview": "Overview", + "tenants": "Tenants", + "lease": "Lease", + "maintenance": "Maintenance", + "financials": "Financials", + "compliance": "Compliance", + "activity": "Activity", + "patterns": "Patterns", + "building_financials": "Building Context", + "building_maintenance": "Building Context", + "building_compliance": "Building Context", + "liegenschaft_financials": "WEG Context", + "liegenschaft_maintenance": "WEG Context", + "liegenschaft_compliance": "WEG Context", +} + +# Sections that display under a "Context" heading rather than as a +# primary fact section; the frontend uses the ``isContext`` flag to +# render these with a quieter visual treatment. +_CONTEXT_SECTIONS: frozenset[str] = frozenset( + { + "building_financials", + "building_maintenance", + "building_compliance", + "liegenschaft_financials", + "liegenschaft_maintenance", + "liegenschaft_compliance", + } +) + +# Sources whose presence implies a fact came from an authoritative +# document rather than an email. Surfaced verbatim in the UI's "via" +# label so PDFs read as "Mietvertrag.pdf" instead of just "letter". +_AUTHORITATIVE_DOCUMENT_TYPES: frozenset[str] = frozenset( + {"lease", "lease_addendum", "kaufvertrag", "structural_permit", "vermessungsprotokoll"} +) + + +def _build_stammdaten_section(s: Stammdaten, lang: str) -> PropertyFileSection | None: + """Emit a Stammdaten section mirroring the markdown view. + + Stammdaten lives outside the events/facts pipeline (it's the + authoritative lease/owner registry loaded at ingest), so each row + here carries ``source='stammdaten'`` and no ``fact_id``; the edit + affordance stays hidden because there's no fact row to override. + """ + labels = CONTEXT_LABELS[lang] + rows: list[tuple[str, str]] = [] + + if s.unit_label: + rows.append((labels["unit"], s.unit_label)) + if s.lage: + rows.append(("Lage" if lang == "de" else "Location", s.lage)) + if s.size_qm is not None: + size_str = f"{s.size_qm:.1f} m²".replace(".0 ", " ") + rows.append((labels["size_qm"], size_str)) + if s.rooms is not None: + rooms_str = f"{s.rooms:.1f}".rstrip("0").rstrip(".") or "0" + rows.append((labels["rooms"], rooms_str)) + if s.owner_name: + rows.append((labels["owner"], s.owner_name)) + if s.tenant_name: + rows.append((labels["tenant"], s.tenant_name)) + if s.mietbeginn: + rows.append((labels["lease_start"], s.mietbeginn)) + rows.append( + ( + labels["lease_end"], + s.mietende if s.mietende else labels["lease_open_ended"], + ) + ) + kalt = _format_eur(s.kaltmiete) + if kalt: + rows.append((labels["rent_cold"], kalt)) + nk = _format_eur(s.nk_vorauszahlung) + if nk: + rows.append((labels["operating_costs"], nk)) + kaution = _format_eur(s.kaution) + if kaution: + rows.append((labels["deposit"], kaution)) + + facts: list[PropertyFileFact] = [] + if not s.tenant_name: + facts.append( + PropertyFileFact( + value=labels["no_active_tenant"], + source="stammdaten", + date="", + section="stammdaten", + field="tenant", + ) + ) + for label, value in rows: + facts.append( + PropertyFileFact( + value=f"{label}: {value}", + source="stammdaten", + date="", + section="stammdaten", + field=label.lower().replace(" ", "_"), + ) + ) + + if not facts: + return None + return PropertyFileSection( + title=labels["stammdaten"], + facts=facts, + is_context=False, + ) + + +def _build_context_section( + events: list[dict[str, str | int]], + *, + title: str, +) -> PropertyFileSection | None: + """Turn recent building/liegenschaft events into a context section. + + Each event becomes a read-only fact: source pill = the event source + (``email``/``bank``/``invoice``), event_id wires the source modal, + no ``fact_id`` (these aren't facts; they're parent-tier activity). + """ + facts: list[PropertyFileFact] = [] + for ev in events: + received_iso = str(ev.get("received_at") or "") + date_short = received_iso[:10] if received_iso else "" + facts.append( + PropertyFileFact( + value=_context_body(ev), + source=str(ev.get("source") or ""), + date=date_short, + date_iso=received_iso or None, + section="context", + field=str(ev.get("kategorie") or ""), + event_id=str(ev.get("id") or "") or None, + ) + ) + if not facts: + return None + return PropertyFileSection( + title=title, + facts=facts, + is_context=True, + ) diff --git a/backend/api/properties/graph.py b/backend/api/properties/graph.py new file mode 100644 index 0000000..1d90525 --- /dev/null +++ b/backend/api/properties/graph.py @@ -0,0 +1,185 @@ +"""The property's relationship graph: owner, building, tenants, contractors.""" + +from __future__ import annotations + +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class GraphNode(BaseModel): + """A node in the property context graph.""" + + id: str + type: str # 'property' | 'owner' | 'building' | 'tenant' | 'contractor' + label: str + metadata: dict[str, object] = {} + + +class GraphEdge(BaseModel): + """An edge in the property context graph.""" + + source: str + target: str + relationship: str + + +class PropertyGraph(BaseModel): + """Response for ``GET /properties/{id}/graph``.""" + + property_id: UUID + nodes: list[GraphNode] + edges: list[GraphEdge] + + +@router.get("/{property_id}/graph", response_model=PropertyGraph) +async def property_graph( + property_id: UUID, + session: AsyncSession = Depends(get_session), +) -> PropertyGraph: + """Return the context graph for a property: owner, building, tenants, contractors.""" + prop_row = ( + await session.execute( + text( + """ + SELECT p.id, p.name, p.address, + o.id AS owner_id, o.name AS owner_name, o.email AS owner_email, + b.id AS building_id, b.address AS building_address, + b.year_built AS building_year + FROM properties p + LEFT JOIN owners o ON o.id = p.owner_id + LEFT JOIN buildings b ON b.id = p.building_id + WHERE p.id = :pid + """ + ), + {"pid": property_id}, + ) + ).first() + if prop_row is None: + raise HTTPException(status_code=404, detail="property not found") + + nodes: list[GraphNode] = [ + GraphNode( + id=str(prop_row.id), + type="property", + label=prop_row.name, + metadata={"address": prop_row.address}, + ) + ] + edges: list[GraphEdge] = [] + + if prop_row.owner_id is not None: + nodes.append( + GraphNode( + id=str(prop_row.owner_id), + type="owner", + label=prop_row.owner_name or "Owner", + metadata={"email": prop_row.owner_email or ""}, + ) + ) + edges.append( + GraphEdge( + source=str(prop_row.id), + target=str(prop_row.owner_id), + relationship="owned_by", + ) + ) + + if prop_row.building_id is not None: + nodes.append( + GraphNode( + id=str(prop_row.building_id), + type="building", + label=f"Building: {prop_row.building_address}", + metadata={ + "address": prop_row.building_address or "", + "year_built": prop_row.building_year, + }, + ) + ) + edges.append( + GraphEdge( + source=str(prop_row.id), + target=str(prop_row.building_id), + relationship="in_building", + ) + ) + + tenants = await session.execute( + text( + """ + SELECT id, name, email + FROM tenants + WHERE property_id = :pid + ORDER BY name + """ + ), + {"pid": property_id}, + ) + for tenant in tenants.all(): + nodes.append( + GraphNode( + id=str(tenant.id), + type="tenant", + label=tenant.name, + metadata={"email": tenant.email or ""}, + ) + ) + edges.append( + GraphEdge( + source=str(prop_row.id), + target=str(tenant.id), + relationship="occupied_by", + ) + ) + + contractors = await session.execute( + text( + """ + SELECT c.id, c.name, c.specialty, c.rating + FROM relationships r + JOIN contractors c ON c.id = r.to_id + WHERE r.from_id = :pid + AND r.from_type = 'property' + AND r.to_type = 'contractor' + AND r.relationship_type = 'serviced_by' + """ + ), + {"pid": property_id}, + ) + for contractor in contractors.all(): + nodes.append( + GraphNode( + id=str(contractor.id), + type="contractor", + label=contractor.name, + metadata={ + "specialty": contractor.specialty or "", + "rating": contractor.rating, + }, + ) + ) + edges.append( + GraphEdge( + source=str(prop_row.id), + target=str(contractor.id), + relationship="serviced_by", + ) + ) + + log.info( + "properties.graph", + property_id=str(property_id), + nodes=len(nodes), + edges=len(edges), + ) + return PropertyGraph(property_id=property_id, nodes=nodes, edges=edges) diff --git a/backend/api/properties/inbox.py b/backend/api/properties/inbox.py new file mode 100644 index 0000000..777cd6e --- /dev/null +++ b/backend/api/properties/inbox.py @@ -0,0 +1,167 @@ +"""The property's raw message inbox, searchable by keyword (used by the Compare page).""" + +from __future__ import annotations + +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class InboxEmail(BaseModel): + """One raw email row for the "before Keystone" Compare view.""" + + event_id: UUID + date: str + sender: str + subject: str + preview: str + relevant: bool = Field( + default=False, + description=( + "True when the search keyword(s) appeared in the raw body. " + "Used to highlight matching rows visually." + ), + ) + + +class InboxResponse(BaseModel): + """Response for ``GET /properties/{id}/inbox``.""" + + rows: list[InboxEmail] + total_inbox_size: int = Field( + ..., + description="Total email events for this property (the haystack size).", + ) + relevant_count: int + keyword: str | None + + +def _extract_subject_and_from(raw: str) -> tuple[str, str]: + """Cheap RFC-822-ish subject/from parser. Falls back to first line.""" + subject = "" + sender = "" + for line in raw.splitlines(): + lower = line.lower() + if not subject and lower.startswith("subject:"): + subject = line.split(":", 1)[1].strip() + elif not sender and lower.startswith("from:"): + sender = line.split(":", 1)[1].strip() + if subject and sender: + break + if not subject: + subject = raw.strip().split("\n", 1)[0][:80] + return subject, sender + + +@router.get("/{property_id}/inbox", response_model=InboxResponse) +async def property_inbox( + property_id: UUID, + q: str | None = Query( + default=None, + description="Optional keyword. Rows whose raw body matches are flagged ``relevant=True``.", + ), + limit: int = Query(default=20, ge=1, le=100), + session: AsyncSession = Depends(get_session), +) -> InboxResponse: + """Email-style inbox view for the Compare page's "before" panel. + + Returns the property's most-recent email events with a parsed + ``subject`` / ``from`` / ``preview``. When ``q`` is supplied the + LIKE filter highlights matches but the list still shows the + surrounding noise. The Compare page sets this manual workflow, where + the operator scrolls through everything, beside the single answer + the property file gives. + """ + total = ( + await session.execute( + text( + """ + SELECT COUNT(*) FROM events + WHERE property_id = :pid AND source = 'email' + """ + ), + {"pid": property_id}, + ) + ).scalar_one() + + pattern = f"%{q}%" if q else None + relevant_count = 0 + if pattern: + relevant_count = ( + await session.execute( + text( + """ + SELECT COUNT(*) FROM events + WHERE property_id = :pid AND source = 'email' + AND raw_content ILIKE :pat + """ + ), + {"pid": property_id, "pat": pattern}, + ) + ).scalar_one() + + rows = ( + await session.execute( + text( + """ + SELECT id, + COALESCE(received_at, processed_at) AS dt, + LEFT(COALESCE(raw_content, ''), 600) AS body, + (CASE WHEN CAST(:pat AS text) IS NOT NULL + AND raw_content ILIKE CAST(:pat AS text) + THEN TRUE ELSE FALSE END) AS is_relevant + FROM events + WHERE property_id = :pid AND source = 'email' + ORDER BY COALESCE(received_at, processed_at) DESC + LIMIT :lim + """ + ), + {"pid": property_id, "pat": pattern, "lim": limit}, + ) + ).all() + + items: list[InboxEmail] = [] + for r in rows: + body = str(r.body or "") + subject, sender = _extract_subject_and_from(body) + body_text = body + # Strip headers from preview + for hdr in ("From:", "Subject:", "Date:", "To:", "Message-ID:"): + for line in body_text.splitlines(): + if line.lower().startswith(hdr.lower()): + body_text = body_text.replace(line + "\n", "") + preview = body_text.replace("\n", " ").strip()[:120] + items.append( + InboxEmail( + event_id=r.id, + date=r.dt.date().isoformat() if r.dt else "", + sender=sender or "(unknown)", + subject=subject or "(no subject)", + preview=preview, + relevant=bool(r.is_relevant), + ) + ) + + log.info( + "properties.inbox", + property_id=str(property_id), + q=q, + returned=len(items), + total=int(total), + relevant=int(relevant_count), + ) + return InboxResponse( + rows=items, + total_inbox_size=int(total), + relevant_count=int(relevant_count), + keyword=q, + ) diff --git a/backend/api/properties/listing.py b/backend/api/properties/listing.py new file mode 100644 index 0000000..6271fb3 --- /dev/null +++ b/backend/api/properties/listing.py @@ -0,0 +1,233 @@ +"""Property listing, keyword search and creation.""" + +from __future__ import annotations + +from typing import Any +from uuid import UUID + +import structlog +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, Field +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.db.session import get_session +from backend.services.featured import resolve_featured_property_id + +router = APIRouter() +log = structlog.get_logger(__name__) + + +class PropertySummary(BaseModel): + """Compact property record used by the portfolio listing. + + Counts are computed at query time from indexed property_id lookups on + ``events``, ``facts`` (current only: ``superseded_by IS NULL``), + ``uncertainty_events`` (``status='open'``), and ``signals`` + (``status='pending'``). At the sample dataset's 56 properties this is + ~224 index hits per request, single-digit ms total. + """ + + id: UUID + name: str + address: str + owner_name: str | None = None + building_year_built: int | None = None + events: int = 0 + facts: int = 0 + needs_review: int = 0 + open_issues: int = 0 + #: True for the property named by ``FEATURED_PROPERTY``. + is_hero: bool = False + + +class PropertyCreateRequest(BaseModel): + """Payload for POST /properties.""" + + name: str = Field(..., min_length=1) + address: str = Field(..., min_length=1) + aliases: list[str] = Field(default_factory=list) + owner_id: UUID | None = None + building_id: UUID | None = None + + +class PropertyCreateResponse(BaseModel): + """Response for POST /properties.""" + + id: UUID + name: str + address: str + + +class PropertySearchHit(BaseModel): + """One result from ``GET /properties/search``.""" + + id: UUID + name: str + address: str + snippet: str + score: float + + +@router.get("", response_model=list[PropertySummary]) +async def list_properties( + session: AsyncSession = Depends(get_session), +) -> list[PropertySummary]: + """Return every property with owner, building and count context.""" + featured_id = await resolve_featured_property_id(session) + result = await session.execute( + text( + """ + SELECT p.id, p.name, p.address, + o.name AS owner_name, + b.year_built AS building_year_built, + (SELECT COUNT(*) FROM events + WHERE property_id = p.id) AS events, + (SELECT COUNT(*) FROM facts + WHERE property_id = p.id + AND superseded_by IS NULL) AS facts, + (SELECT COUNT(*) FROM uncertainty_events + WHERE property_id = p.id + AND status = 'open') AS needs_review, + (SELECT COUNT(*) FROM signals + WHERE property_id = p.id + AND status = 'pending') AS open_issues + FROM properties p + LEFT JOIN owners o ON o.id = p.owner_id + LEFT JOIN buildings b ON b.id = p.building_id + ORDER BY p.created_at ASC + """ + ) + ) + properties = [ + PropertySummary( + id=row.id, + name=row.name, + address=row.address, + owner_name=row.owner_name, + building_year_built=row.building_year_built, + events=int(row.events or 0), + facts=int(row.facts or 0), + needs_review=int(row.needs_review or 0), + open_issues=int(row.open_issues or 0), + is_hero=featured_id is not None and str(row.id) == str(featured_id), + ) + for row in result.all() + ] + log.info("properties.list", count=len(properties)) + return properties + + +@router.get("/search", response_model=list[PropertySearchHit]) +async def search_properties( + q: str = Query(..., min_length=1, description="Free-text search query"), + limit: int = Query(default=5, ge=1, le=25), + session: AsyncSession = Depends(get_session), +) -> list[PropertySearchHit]: + """Keyword search across property name, address, aliases, and current facts. + + Per-term scoring: the query is split on whitespace and each term + contributes independently, so ``"heating Berlin"`` picks up a heating + fact *and* a Berlin address rather than needing both words to appear + contiguously. + + Weights: + - direct name/alias term hit → 1.0 + - address term hit → 0.8 + - fact value term hit → 0.5 + min(count / 10, 0.45) + """ + terms = [t for t in q.lower().split() if t.strip()] or [q.lower()] + aggregated: dict[str, dict[str, Any]] = {} + for term in terms: + pattern = f"%{term}%" + result = await session.execute( + text( + """ + WITH fact_hits AS ( + SELECT f.property_id, + COUNT(*) AS hits, + (ARRAY_AGG(f.value ORDER BY f.created_at DESC))[1] + AS snippet + FROM facts f + WHERE f.superseded_by IS NULL + AND LOWER(f.value) LIKE :pat + GROUP BY f.property_id + ) + SELECT p.id, p.name, p.address, + COALESCE(fh.hits, 0) AS hits, + fh.snippet AS fact_snippet, + CASE + WHEN LOWER(p.name) LIKE :pat THEN 1.0 + WHEN EXISTS ( + SELECT 1 FROM UNNEST(p.aliases) a + WHERE LOWER(a) LIKE :pat + ) THEN 0.95 + WHEN LOWER(p.address) LIKE :pat THEN 0.8 + WHEN COALESCE(fh.hits, 0) > 0 + THEN 0.5 + LEAST(fh.hits::float / 10.0, 0.45) + ELSE 0.0 + END AS score + FROM properties p + LEFT JOIN fact_hits fh ON fh.property_id = p.id + """ + ), + {"pat": pattern}, + ) + for row in result.all(): + score = float(row.score) + if score <= 0: + continue + slot = aggregated.setdefault( + str(row.id), + { + "id": row.id, + "name": row.name, + "address": row.address, + "snippet": None, + "score": 0.0, + }, + ) + slot["score"] += score + if slot["snippet"] is None and row.fact_snippet: + slot["snippet"] = row.fact_snippet + + hits = sorted(aggregated.values(), key=lambda r: r["score"], reverse=True)[:limit] + log.info("properties.search", q=q, terms=len(terms), returned=len(hits)) + return [ + PropertySearchHit( + id=h["id"], + name=h["name"], + address=h["address"], + snippet=(h["snippet"] or f"{h['name']}, {h['address']}")[:220], + score=min(float(h["score"]), 1.0 * len(terms)), + ) + for h in hits + ] + + +@router.post("", response_model=PropertyCreateResponse, status_code=201) +async def create_property( + payload: PropertyCreateRequest, + session: AsyncSession = Depends(get_session), +) -> PropertyCreateResponse: + """Create a property.""" + result = await session.execute( + text( + """ + INSERT INTO properties (name, address, aliases, owner_id, building_id) + VALUES (:name, :addr, :aliases, :owner, :building) + RETURNING id + """ + ), + { + "name": payload.name, + "addr": payload.address, + "aliases": payload.aliases, + "owner": payload.owner_id, + "building": payload.building_id, + }, + ) + property_id: UUID = result.scalar_one() + await session.commit() + log.info("properties.create", property_id=str(property_id), name=payload.name) + return PropertyCreateResponse(id=property_id, name=payload.name, address=payload.address) diff --git a/backend/api/property_files.py b/backend/api/property_files.py index 4859284..f0c6cc8 100644 --- a/backend/api/property_files.py +++ b/backend/api/property_files.py @@ -1,16 +1,16 @@ """Materialized property file API. -Phase 12 — exposes the cached, propagation-aware ``property_files`` -table as a first-class resource (separate from ``/properties/{id}`` -which is the master-record + structured-card surface). +Exposes the cached, propagation-aware ``property_files`` table as a +first-class resource (separate from ``/properties/{id}``, which is the +master-record + structured-card surface). Two endpoints: -- ``GET /property_files/{property_id}`` — full row shape for a single +- ``GET /property_files/{property_id}``: full row shape for a single property's materialized markdown. -- ``GET /property_files/changes?since=&limit=50`` — recent - regenerations across the portfolio. The frontend (Phase 13) can - poll this to drive a "live update" feed without subscribing to +- ``GET /property_files/changes?since=&limit=50``: recent + regenerations across the portfolio. A frontend or external consumer + can poll this to drive a "live update" feed without subscribing to the in-process event bus. Ordering is ``last_rendered_at DESC``; ``trigger_*`` columns let consumers attribute each row to the fact write that triggered it. @@ -40,6 +40,7 @@ def _cache_headers(response: Response, last_rendered_at: datetime) -> None: response.headers["Cache-Control"] = "public, max-age=30" response.headers["ETag"] = f'"{int(last_rendered_at.timestamp())}"' + router = APIRouter(prefix="/property_files", tags=["property_files"]) log = structlog.get_logger(__name__) @@ -83,8 +84,8 @@ async def list_changes( ) -> list[PropertyFileChangeRow]: """Return recent property-file regenerations. - Phase 13 will use this as the polling target for a "what changed" - feed; Phase 12 ships only the data layer. + Intended as the polling target for a "what changed" feed. No + first-party client consumes it yet; it is the data layer only. """ if since is None: rows = ( @@ -140,9 +141,7 @@ async def list_changes( last_rendered_at=r.last_rendered_at, trigger_scope=r.trigger_scope, trigger_summary=r.trigger_summary, - trigger_event_id=( - UUID(str(r.trigger_event_id)) if r.trigger_event_id else None - ), + trigger_event_id=(UUID(str(r.trigger_event_id)) if r.trigger_event_id else None), ) for r in rows ] @@ -170,18 +169,14 @@ async def get_property_file( ) ).first() if row is None: - raise HTTPException( - status_code=404, detail="property file not materialized yet" - ) + raise HTTPException(status_code=404, detail="property file not materialized yet") _cache_headers(response, row.last_rendered_at) return PropertyFileRow( property_id=UUID(str(row.property_id)), content_md=row.content_md, fact_count=int(row.fact_count or 0), last_rendered_at=row.last_rendered_at, - trigger_event_id=( - UUID(str(row.trigger_event_id)) if row.trigger_event_id else None - ), + trigger_event_id=(UUID(str(row.trigger_event_id)) if row.trigger_event_id else None), trigger_scope=row.trigger_scope, trigger_summary=row.trigger_summary, generation_version=int(row.generation_version or 1), @@ -191,7 +186,7 @@ async def get_property_file( class PropertyFileIndex(BaseModel): """Structured index emitted alongside the markdown. - Same data the frontmatter summarizes — exposed here as typed JSON + Same data the frontmatter summarizes, exposed here as typed JSON so an AI agent or a cross-property dashboard can read the file's shape (section counts, conflicts, coverage, low-confidence count) without parsing the markdown body. @@ -210,7 +205,7 @@ async def get_property_file_index( ) -> PropertyFileIndex: """Return the structured ``content_index`` for one property. - Phase 12+ — the typed shape an LLM agent ingests in one tool call + The typed shape an LLM agent ingests in one tool call instead of re-parsing the markdown body. Cache-headered the same way ``/property_files/{id}`` is. """ @@ -227,9 +222,7 @@ async def get_property_file_index( ) ).first() if row is None: - raise HTTPException( - status_code=404, detail="property file not materialized yet" - ) + raise HTTPException(status_code=404, detail="property file not materialized yet") _cache_headers(response, row.last_rendered_at) return PropertyFileIndex( property_id=UUID(str(row.property_id)), diff --git a/backend/api/settings.py b/backend/api/settings.py index 88326df..9a73397 100644 --- a/backend/api/settings.py +++ b/backend/api/settings.py @@ -1,8 +1,7 @@ -"""Settings surface — security badge, learning dashboard, regulation trigger.""" +"""Settings surface: approval-rate statistics.""" from __future__ import annotations -from datetime import datetime from typing import Any import structlog @@ -11,29 +10,12 @@ from sqlalchemy.ext.asyncio import AsyncSession from backend.db.session import get_session -from backend.services.aikido import get_badge -from backend.services.pioneer import compute_learning, snapshot_to_json -from backend.services.tavily import watch_regulations -from backend.signals.evaluator import evaluate_all +from backend.services.approval_stats import compute_learning, snapshot_to_json router = APIRouter(prefix="/settings", tags=["settings"]) log = structlog.get_logger(__name__) -class SecurityBadgeOut(BaseModel): - """Response for ``GET /settings/security``.""" - - status: str - scanner: str - last_scan_at: datetime | None - commit_sha: str | None - critical: int - high: int - medium: int - details_url: str | None - source: str - - class LearningStatsOut(BaseModel): """Response for ``GET /settings/learning``.""" @@ -43,55 +25,10 @@ class LearningStatsOut(BaseModel): signal_types: list[dict[str, Any]] -class WatchResponse(BaseModel): - """Response for ``POST /settings/regulation_watch``.""" - - ingested_events: int - new_signals: int - - -@router.get("/security", response_model=SecurityBadgeOut) -async def security_badge() -> SecurityBadgeOut: - """Return the Aikido security-scan badge rendered by the Settings page.""" - badge = await get_badge() - return SecurityBadgeOut( - status=badge.status, - scanner=badge.scanner, - last_scan_at=badge.last_scan_at, - commit_sha=badge.commit_sha, - critical=badge.critical, - high=badge.high, - medium=badge.medium, - details_url=badge.details_url, - source=badge.source, - ) - - @router.get("/learning", response_model=LearningStatsOut) async def learning_dashboard( session: AsyncSession = Depends(get_session), ) -> LearningStatsOut: - """Return the Pioneer / Fastino-compatible approval-rate snapshot.""" + """Return approval rates and priority weights per signal type.""" snapshot = await compute_learning(session) return LearningStatsOut(**snapshot_to_json(snapshot)) - - -@router.post("/regulation_watch", response_model=WatchResponse) -async def run_regulation_watch( - session: AsyncSession = Depends(get_session), -) -> WatchResponse: - """Manually fire the Tavily regulation watcher for demo determinism. - - Runs the watcher, then evaluates the rule set once so any fresh - regulation events that warrant signals are visible in the inbox - immediately (instead of waiting for the 30s scheduler tick). - """ - inserted = await watch_regulations() - created = await evaluate_all(session) - await session.commit() - log.info( - "settings.regulation_watch", - inserted=inserted, - signals_created=created, - ) - return WatchResponse(ingested_events=inserted, new_signals=created) diff --git a/backend/api/signals.py b/backend/api/signals.py index 67d94e4..6923c1a 100644 --- a/backend/api/signals.py +++ b/backend/api/signals.py @@ -1,15 +1,15 @@ -"""Approval inbox — list / approve / reject / edit / evaluate. - -Shape matches what the Lovable UI will bind to: - -- ``GET /signals`` — list with filters (``status``, ``severity``, ``type``). -- ``GET /signals/{id}`` — single signal with its proposed_action + evidence. -- ``POST /signals/evaluate`` — manually fire the rule evaluator (demo trigger). -- ``POST /signals/{id}/approve`` — dispatch via the Entire-compatible broker, - write outbox row + approval log entry, flip status to ``resolved``. -- ``POST /signals/{id}/reject`` — log rejection, flip status to ``rejected``. -- ``POST /signals/{id}/edit`` — allow the human to edit the drafted message - before approval; writes an ``approval_log`` row with ``decision='edited'``. +"""Approval inbox: list, inspect, evaluate, approve, reject and edit signals. + +- ``GET /signals``: list with filters (``status``, ``severity``, ``type``). +- ``GET /signals/{id}``: one signal with its proposed action and evidence. +- ``POST /signals/evaluate``: run the rule evaluator now instead of waiting + for the next scheduled run. +- ``POST /signals/{id}/approve``: dispatch through the approval broker + (``backend.services.approval``), write the outbox row and an + ``approval_log`` entry, and set the status to ``resolved``. +- ``POST /signals/{id}/reject``: log the rejection and set ``rejected``. +- ``POST /signals/{id}/edit``: edit the drafted message before approval; + writes an ``approval_log`` row with ``decision='edited'``. """ from __future__ import annotations @@ -26,7 +26,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from backend.db.session import get_session -from backend.services.entire import get_broker +from backend.services.approval import get_broker from backend.signals.evaluator import evaluate_all router = APIRouter(prefix="/signals", tags=["signals"]) @@ -88,7 +88,7 @@ class EvaluateResponse(BaseModel): class ProposeRequest(BaseModel): - """Payload for ``POST /signals/propose`` — MCP / external-AI entry point.""" + """Payload for ``POST /signals/propose``: MCP / external-AI entry point.""" property_id: UUID | None = None type: str = Field(..., min_length=1) @@ -178,10 +178,12 @@ async def propose_signal( ) -> ProposeResponse: """Insert a pending signal authored by an external AI (Claude via MCP). - The human always approves before any outbox side effect — this endpoint + The human always approves before any outbox side effect; this endpoint deliberately does not dispatch. """ - severity = payload.severity if payload.severity in {"low", "medium", "high", "urgent"} else "medium" + severity = ( + payload.severity if payload.severity in {"low", "medium", "high", "urgent"} else "medium" + ) action: dict[str, Any] = dict(payload.action) action.setdefault("type", "owner_notification") action.setdefault("channel", "email") @@ -227,7 +229,11 @@ async def propose_signal( async def evaluate_now( session: AsyncSession = Depends(get_session), ) -> EvaluateResponse: - """Manually fire the rule evaluator. Useful for demo determinism.""" + """Run the rule evaluator now instead of waiting for the next scheduled run. + + Lets an operator (or a test) see the signals for freshly ingested + data immediately and at a known point in time. + """ created = await evaluate_all(session) await session.commit() log.info("signals.evaluate", created=created) @@ -280,9 +286,7 @@ async def edit_signal( if row is None: raise HTTPException(status_code=404, detail="signal not found") if row.status not in {"pending", "approved"}: - raise HTTPException( - status_code=409, detail=f"cannot edit signal in status={row.status}" - ) + raise HTTPException(status_code=409, detail=f"cannot edit signal in status={row.status}") action = row.proposed_action or {} if isinstance(action, str): @@ -326,7 +330,7 @@ async def approve_signal( signal_id: UUID, session: AsyncSession = Depends(get_session), ) -> ActionResponse: - """Dispatch via the Entire-compatible broker, log, and resolve.""" + """Dispatch through the approval broker, log the decision, resolve the signal.""" row = ( await session.execute( text( @@ -341,9 +345,7 @@ async def approve_signal( if row is None: raise HTTPException(status_code=404, detail="signal not found") if row.status != "pending": - raise HTTPException( - status_code=409, detail=f"signal is {row.status}, cannot approve" - ) + raise HTTPException(status_code=409, detail=f"signal is {row.status}, cannot approve") action = row.proposed_action or {} if isinstance(action, str): diff --git a/backend/api/source_links.py b/backend/api/source_links.py index 75d9c1b..ae0f36c 100644 --- a/backend/api/source_links.py +++ b/backend/api/source_links.py @@ -1,6 +1,6 @@ -"""``/events//...`` — resolve a fact's source link to the original document. +"""``/events//...``: resolve a fact's source link to the original document. -Phase 10 Step 10.4. The renderer emits ``[source: ](/events//source)`` +The renderer emits ``[source: ](/events//source)`` for every fact and uncertainty line. This router dispatches based on the event's ``source`` field: @@ -85,7 +85,7 @@ async def event_source( original_path=original_path, ) return RedirectResponse(url=f"/files/{original_path}", status_code=307) - # No path captured — fall through to raw so the operator sees + # No path captured: fall through to raw so the operator sees # something rather than a dead link. if source == "bank": @@ -95,9 +95,7 @@ async def event_source( source=source, target="detail", ) - return RedirectResponse( - url=f"/events/{event_id}/detail", status_code=307 - ) + return RedirectResponse(url=f"/events/{event_id}/detail", status_code=307) log.info( "events.source.redirect", @@ -116,15 +114,13 @@ async def event_raw( """Return the event's ``raw_content`` as ``text/plain``. Used for emails and as a fallback for unknown source types. PDFs - redirect through ``/source`` to ``/files`` — calling ``/raw`` + redirect through ``/source`` to ``/files``; calling ``/raw`` directly on a PDF event returns the redacted body text the extractor saw, which is occasionally useful for triage. """ row = ( await session.execute( - text( - "SELECT raw_content, source FROM events WHERE id = :eid" - ), + text("SELECT raw_content, source FROM events WHERE id = :eid"), {"eid": event_id}, ) ).first() diff --git a/backend/api/sse.py b/backend/api/sse.py index 60b99e1..ec1ba43 100644 --- a/backend/api/sse.py +++ b/backend/api/sse.py @@ -1,11 +1,11 @@ """Server-sent events for live markdown updates. ``GET /properties/{id}/events`` streams JSON envelopes whenever the worker -finishes processing an event attached to that property. The browser / Lovable -front-end re-fetches the markdown on each push. +finishes processing an event attached to that property. The browser +frontend re-fetches the markdown on each push. -``GET /portfolio/events`` is the same stream with no property filter — the -Layout subscribes to it once so a portfolio-wide toast can fire whenever +``GET /portfolio/events`` is the same stream with no property filter. The +frontend layout subscribes to it once so a portfolio-wide toast can fire whenever any property's file gets a new fact. """ @@ -30,7 +30,7 @@ async def _event_stream(property_id: UUID | None) -> AsyncIterator[bytes]: """Yield SSE-formatted lines for one subscriber. - ``property_id=None`` subscribes to the global feed — the EventBus + ``property_id=None`` subscribes to the global feed: the EventBus fans every publish to ``None`` subscribers in addition to the property-specific ones. """ @@ -43,7 +43,7 @@ async def _event_stream(property_id: UUID | None) -> AsyncIterator[bytes]: while True: try: payload = await asyncio.wait_for(queue.get(), timeout=15.0) - except asyncio.TimeoutError: + except TimeoutError: # Heartbeat keeps intermediaries (nginx, etc.) from closing. yield b": keep-alive\n\n" continue @@ -51,9 +51,7 @@ async def _event_stream(property_id: UUID | None) -> AsyncIterator[bytes]: yield b"event: fact_update\ndata: " + body + b"\n\n" finally: await bus.unsubscribe(property_id, queue) - log.info( - "sse.unsubscribe", property_id=str(property_id) if property_id else "*" - ) + log.info("sse.unsubscribe", property_id=str(property_id) if property_id else "*") @router.get("/{property_id}/events") @@ -68,11 +66,9 @@ async def property_events(property_id: UUID) -> StreamingResponse: @portfolio_router.get("/events") async def portfolio_events() -> StreamingResponse: - """Portfolio-wide live stream — every fact update across all properties.""" + """Portfolio-wide live stream: every fact update across all properties.""" return StreamingResponse( _event_stream(None), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) - - diff --git a/backend/api/uploads.py b/backend/api/uploads.py index 5cbfac9..8874a07 100644 --- a/backend/api/uploads.py +++ b/backend/api/uploads.py @@ -1,4 +1,4 @@ -"""PDF upload endpoint — drop a PDF, get a pipeline event.""" +"""PDF upload endpoint: drop a PDF, get a pipeline event.""" from __future__ import annotations @@ -39,7 +39,9 @@ async def upload_pdf( ) -> PdfUploadResponse: """Parse the PDF, insert an event, drain the worker once.""" if file.content_type not in {"application/pdf", "application/x-pdf", None}: - raise HTTPException(status_code=415, detail=f"unsupported content-type: {file.content_type}") + raise HTTPException( + status_code=415, detail=f"unsupported content-type: {file.content_type}" + ) data = await file.read() if not data: @@ -47,7 +49,7 @@ async def upload_pdf( try: body = extract_text(data) - except Exception as exc: # noqa: BLE001 — surface extractor errors as 400s + except Exception as exc: # noqa: BLE001 (surface extractor errors as 400s) log.exception("pdf.extract.failed", filename=file.filename) raise HTTPException(status_code=400, detail=f"could not parse PDF: {exc}") from exc diff --git a/backend/api/webhooks.py b/backend/api/webhooks.py index 992957b..70a0e03 100644 --- a/backend/api/webhooks.py +++ b/backend/api/webhooks.py @@ -1,4 +1,4 @@ -"""External-system webhooks. Phase 2 ships the Slack ingestion endpoint.""" +"""External-system webhooks. Currently only Slack event ingestion.""" from __future__ import annotations diff --git a/backend/config.py b/backend/config.py index 0a2d72d..5785512 100644 --- a/backend/config.py +++ b/backend/config.py @@ -1,6 +1,6 @@ """Typed application configuration loaded from the environment. -All settings are read via `pydantic-settings`. No module-level side effects — +All settings are read via `pydantic-settings`. No module-level side effects: callers must instantiate :func:`get_settings` (cached) to obtain a `Settings` object. This keeps configuration testable and free of global state. """ @@ -8,6 +8,7 @@ from __future__ import annotations from functools import lru_cache +from typing import Literal from pydantic import Field from pydantic_settings import BaseSettings, SettingsConfigDict @@ -16,9 +17,10 @@ class Settings(BaseSettings): """Application settings backed by environment variables / ``.env``. - Only keys that are already used in Phase 0 carry real defaults; keys for - later phases are declared here with placeholder defaults so that the - application still boots when they are absent. + Keys needed to run locally (database, app, CORS) carry working + defaults. Credentials and integration endpoints default to empty + placeholders so the application still boots when they are absent; + each feature that needs one disables itself or falls back. """ model_config = SettingsConfigDict( @@ -36,65 +38,59 @@ class Settings(BaseSettings): database_url: str = Field( default="postgresql+asyncpg://keystone:keystone@localhost:5432/keystone" ) - database_url_sync: str = Field( - default="postgresql://keystone:keystone@localhost:5432/keystone" - ) + database_url_sync: str = Field(default="postgresql://keystone:keystone@localhost:5432/keystone") - # --- Gemini --- + # --- LLM --- + # Which backend serves every LLM call (see backend/services/llm/). With no + # key for the selected provider, features use their deterministic + # fallbacks; Ask and reply drafting return 503. + llm_provider: Literal["gemini", "pioneer"] = Field(default="gemini") gemini_api_key: str = Field(default="") - # Model defaults updated 2026-04-25 — Phase 8.1. The previous - # ``gemini-2.0-{flash,pro}`` names were retired for new API users. - # Pinning explicit versions makes eval/runs reproducible across - # weeks; flip to ``gemini-flash-latest`` if we explicitly want - # tracking-the-edge behavior. + # Explicit model versions keep eval runs comparable over time. gemini_flash_model: str = Field(default="gemini-2.5-flash") gemini_pro_model: str = Field(default="gemini-2.5-pro") - gemini_embed_model: str = Field(default="text-embedding-004") - - # --- Partners --- - tavily_api_key: str = Field(default="") - entire_api_key: str = Field(default="") - entire_base_url: str = Field(default="https://api.entire.example") pioneer_api_key: str = Field(default="") - aikido_api_key: str = Field(default="") - gradium_api_key: str = Field(default="") + pioneer_model: str = Field(default="claude-sonnet-4-6") - # --- IMAP / Slack / Mock ERP (used by later phases) --- + # --- IMAP / Slack / Mock ERP connectors --- imap_host: str = Field(default="imap.gmail.com") imap_port: int = Field(default=993) imap_user: str = Field(default="") imap_password: str = Field(default="") imap_mailbox: str = Field(default="INBOX") slack_signing_secret: str = Field(default="") - mock_erp_url: str = Field(default="http://localhost:8001") - - # --- Phase 10 demo --- - # Hero property the no-arg ``POST /admin/demo/replay`` runs against. - # Default: WE 29 (Step 6 hero, see DECISIONS.md). Override via env when - # a different property has richer coverage post-hackathon. - keystone_demo_hero_property: str = Field( - default="509393da-6806-49ef-9e59-3da0213008cd" - ) - # Replay engine speed multiplier the demo uses by default. - keystone_demo_speed_multiplier: int = Field(default=10) - # ``hand_crafted`` falls back to the Berliner 4B beats for safety; - # ``buena`` is the primary file-builds-itself replay. - keystone_demo_mode: str = Field(default="buena") - - # --- Phase 10 Step 10.4 — document linking --- + # Base URL of an ERP payments feed (see tools/mock_erp). Empty disables + # the ERP poller entirely, so a default install makes no outbound calls. + mock_erp_url: str = Field(default="") + + # --- Signals --- + # After a signal is approved or rejected, the evaluator will not raise + # the same finding (same natural key) again for this many days. + signal_resolution_cooldown_days: int = Field(default=7, ge=0) + + # --- Featured property --- + # The property the UI opens first and POST /admin/replay/featured targets: + # a property UUID or any of its aliases. UUIDs differ per database, so the + # default is a unit alias present in the sample data. + featured_property: str = Field(default="EH-029") + # Replay speed for the featured-property replay (1 = real time). + replay_speed_multiplier: int = Field(default=10, ge=1) + + # --- Document linking --- # Filesystem root that ``GET /files/`` is allowed to serve. Any # path that, after ``realpath`` resolution, escapes this root is - # refused with 403. Default points at the gitignored Buena dump so - # the dev environment "just works"; production deployments must - # set an absolute path explicitly. + # refused with 403. The default is the gitignored sample-dataset + # directory, relative to the working directory, so a local checkout + # works without configuration; production deployments must set an + # absolute path explicitly. keystone_files_root: str = Field(default="Extracted") - # --- Phase 11 — frontend CORS --- - # Comma-separated allow-list for browser origins. Default covers - # local Vite dev (``5173``), Vite preview (``4173``), and the - # legacy CRA-style ``3000``. Production deployments append the - # Cloud Run frontend origin, e.g. - # ``KEYSTONE_CORS_ORIGINS=https://app.keystone.example,http://localhost:5173``. + # --- Browser access (CORS) --- + # Comma-separated allow-list of browser origins; the only source of CORS + # origins. The default covers local frontends: the Vite dev server + # (8080 as configured, 5173 Vite's default), Vite preview (4173) and + # 3000. Deployments set their frontend origin explicitly, e.g. + # ``KEYSTONE_CORS_ORIGINS=https://app.example.com``. keystone_cors_origins: str = Field( default=( "http://localhost:5173,http://localhost:4173,http://localhost:3000," @@ -102,6 +98,10 @@ class Settings(BaseSettings): ) ) + def cors_origin_list(self) -> list[str]: + """``keystone_cors_origins`` split on commas, blanks dropped.""" + return [o.strip() for o in self.keystone_cors_origins.split(",") if o.strip()] + @lru_cache(maxsize=1) def get_settings() -> Settings: diff --git a/backend/db/schema.sql b/backend/db/schema.sql index b9be294..3c23a88 100644 --- a/backend/db/schema.sql +++ b/backend/db/schema.sql @@ -1,5 +1,3 @@ --- Enable pgvector -CREATE EXTENSION IF NOT EXISTS vector; CREATE TABLE buildings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -68,7 +66,6 @@ CREATE TABLE events ( received_at TIMESTAMPTZ DEFAULT now(), processed_at TIMESTAMPTZ, processing_error TEXT, - embedding vector(768), UNIQUE (source, source_ref) ); CREATE INDEX idx_events_unprocessed ON events (received_at) WHERE processed_at IS NULL; @@ -85,8 +82,7 @@ CREATE TABLE facts ( valid_from TIMESTAMPTZ DEFAULT now(), valid_to TIMESTAMPTZ, superseded_by UUID REFERENCES facts(id), - created_at TIMESTAMPTZ DEFAULT now(), - embedding vector(768) + created_at TIMESTAMPTZ DEFAULT now() ); CREATE INDEX idx_facts_current ON facts (property_id, section, field) WHERE superseded_by IS NULL; @@ -123,7 +119,7 @@ CREATE TABLE outbox ( sent_at TIMESTAMPTZ DEFAULT now() ); --- Phase 8.1 — Liegenschaft (WEG) tier above buildings. +-- Liegenschaft (WEG) tier above buildings. -- One liegenschaft can own multiple Häuser; events billed at WEG level -- (Hausgeld, Verwaltergebühr, shared contractor fees) attach here, not -- to a specific Haus. Routing precedence in route_structured(): @@ -154,9 +150,9 @@ CREATE INDEX IF NOT EXISTS idx_facts_building_current CREATE INDEX IF NOT EXISTS idx_facts_liegenschaft_current ON facts (liegenschaft_id, section, field) WHERE superseded_by IS NULL; --- Phase 8 — durable LLM-spend ledger. +-- Durable LLM-spend ledger. -- Persists across CLI invocations so a single budget cap (e.g. $20) --- governs the entire Buena backfill, not just one run. Sub-labels +-- governs an entire backfill of the sample dataset, not just one run. Sub-labels -- (e.g. 'pdf_doctype' at $2 sub-cap) share the same row family. CREATE TABLE IF NOT EXISTS cost_ledger ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), diff --git a/backend/db/session.py b/backend/db/session.py index 6e2bcb4..80fef7d 100644 --- a/backend/db/session.py +++ b/backend/db/session.py @@ -2,7 +2,7 @@ A single engine is created lazily on first use. FastAPI routes should obtain sessions via the :func:`get_session` dependency rather than touching the -factory directly — this keeps transactional lifecycles tied to request scope. +factory directly; this keeps transactional lifecycles tied to request scope. """ from __future__ import annotations diff --git a/backend/logging.py b/backend/logging.py index 27bf063..2941171 100644 --- a/backend/logging.py +++ b/backend/logging.py @@ -24,6 +24,9 @@ def configure_logging() -> None: stream=sys.stdout, level=level, ) + # APScheduler logs every job run at INFO (the worker runs every 2 s); + # keep its warnings and errors only. + logging.getLogger("apscheduler").setLevel(max(level, logging.WARNING)) shared_processors: list[structlog.types.Processor] = [ structlog.contextvars.merge_contextvars, diff --git a/backend/main.py b/backend/main.py index 8dac63d..88fe978 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,8 +1,9 @@ """FastAPI entry point. -Phase 1 wires the event-triggering + SSE routers alongside the Phase 0 -properties API, and starts the APScheduler worker/IMAP jobs during the -lifespan context so a single ``uvicorn backend.main:app`` boots the demo. +Mounts every router, configures CORS from ``KEYSTONE_CORS_ORIGINS``, and runs +the background scheduler (event worker, IMAP poller, signal evaluator, optional +ERP poller) inside the app's lifespan, so ``uvicorn backend.main:app`` is the +whole backend. """ from __future__ import annotations @@ -13,11 +14,12 @@ import structlog from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import PlainTextResponse from backend.api.admin import router as admin_router from backend.api.buildings import ( building_router as buildings_router, +) +from backend.api.buildings import ( liegenschaft_router as liegenschaften_router, ) from backend.api.draft_reply import router as draft_reply_router @@ -31,6 +33,8 @@ from backend.api.source_links import router as source_links_router from backend.api.sse import ( portfolio_router as sse_portfolio_router, +) +from backend.api.sse import ( router as sse_router, ) from backend.api.uploads import router as uploads_router @@ -38,6 +42,7 @@ from backend.config import get_settings from backend.logging import configure_logging from backend.scheduler import build_scheduler +from backend.services.llm import log_configuration as log_llm_configuration @asynccontextmanager @@ -49,6 +54,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: scheduler = build_scheduler() scheduler.start() log.info("keystone.startup", env=settings.app_env, jobs=len(scheduler.get_jobs())) + log_llm_configuration() try: yield finally: @@ -63,25 +69,11 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: lifespan=lifespan, ) -_cors_origins = [ - origin.strip() - for origin in get_settings().keystone_cors_origins.split(",") - if origin.strip() -] - -# Always allow Lovable origins -_cors_origins.extend([ - "https://keystone-insight.lovable.app", - "https://preview--keystone-insight.lovable.app", - "https://keystone-insight.lovable.app", - "https://preview--keystone-insight.lovable.app", - "https://e014e01e-3cc6-4aff-8939-c1bc4f248e09.lovableproject.com", -]) - +# KEYSTONE_CORS_ORIGINS is the only source of allowed browser origins: no +# hardcoded hosts and no wildcard patterns, since credentials are allowed. app.add_middleware( CORSMiddleware, - allow_origins=_cors_origins, - allow_origin_regex=r"https://.*\.(lovable\.app|lovableproject\.com)", + allow_origins=get_settings().cors_origin_list(), allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -109,9 +101,3 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: async def health() -> dict[str, str]: """Liveness probe used by Docker / Railway and local smoke tests.""" return {"status": "ok"} - - -@app.get("/aikido.txt", response_class=PlainTextResponse, tags=["system"]) -async def aikido_verification() -> str: - """Serve the Aikido domain verification string.""" - return "validation.aikido.e29d600660a740cc0f0e7cabb18d4b0a" diff --git a/backend/pipeline/applier.py b/backend/pipeline/applier.py index a5d2c7b..79140d3 100644 --- a/backend/pipeline/applier.py +++ b/backend/pipeline/applier.py @@ -1,15 +1,14 @@ """Apply a :class:`DiffPlan` to the facts table. Writes new fact rows and flags any superseded predecessor. The fact table's -``superseded_by`` column points at the replacement row (bottom-up chain) — +``superseded_by`` column points at the replacement row (bottom-up chain); this is what :func:`render_markdown` relies on via ``superseded_by IS NULL``. -Phase 9 Step 9.1 expands the applier surface: alongside committing -facts, it persists a parallel list of uncertainty items (from the -extractor's ``uncertain[]`` field, the confidence-floor demotion path, -and the validator's ``needs_review`` verdicts). Both writes live -in the same transaction so a row in ``uncertainty_events`` is always -linked to a real ``events`` row. +Alongside committing facts, the applier also persists a parallel list +of uncertainty items (from the extractor's ``uncertain[]`` field, the +confidence-floor demotion path, and the validator's ``needs_review`` +verdicts). Both writes live in the same transaction so a row in +``uncertainty_events`` is always linked to a real ``events`` row. """ from __future__ import annotations @@ -37,8 +36,8 @@ async def apply( ) -> int: """Persist every decision in ``plan``; return how many facts were written. - Phase 12 — after the write loop, fan out a materialization update - for the property scope. The propagation runs in the same session + After the write loop, fan out a materialization update for the + property scope. The propagation runs in the same session so it shares this transaction: if rendering fails, every fact write rolls back too, which preserves the "files are never stale relative to facts" invariant. @@ -82,7 +81,7 @@ async def apply( if written > 0: # Trigger summary defaults to the first decision's value when the - # caller didn't pass one — gives a human-readable label on the + # caller didn't pass one. That gives a human-readable label on the # ``/property_files/changes`` feed without leaking too much. summary = trigger_summary if summary is None and plan.decisions: @@ -152,9 +151,7 @@ async def apply_uncertainties( "section": str(item.get("relevant_section") or "") or None, "field": str(item.get("relevant_field") or "") or None, "observation": observation[:1000], - "hypothesis": ( - str(item.get("hypothesis") or "")[:1000] or None - ), + "hypothesis": (str(item.get("hypothesis") or "")[:1000] or None), "reason": str(item.get("reason_uncertain") or "(no reason given)")[:500], "src": str(item.get("source") or "extractor"), }, diff --git a/backend/pipeline/constraints/__init__.py b/backend/pipeline/constraints/__init__.py index 33c18f9..2014a4f 100644 --- a/backend/pipeline/constraints/__init__.py +++ b/backend/pipeline/constraints/__init__.py @@ -1,4 +1,4 @@ -"""Phase 9 Step 9.2 — constraint definitions. +"""Constraint definitions for the rule-based validator. Importing this package registers every constraint into :data:`backend.pipeline.validator.REGISTRY`. The validator looks up @@ -18,7 +18,7 @@ from __future__ import annotations -from backend.pipeline.constraints import ( # noqa: F401 — import for side-effect +from backend.pipeline.constraints import ( # noqa: F401 (import for side-effect) building_address_immutable, building_floor_count_immutable, building_year_built_immutable, diff --git a/backend/pipeline/constraints/building_address_immutable.py b/backend/pipeline/constraints/building_address_immutable.py index 994e992..68b20cb 100644 --- a/backend/pipeline/constraints/building_address_immutable.py +++ b/backend/pipeline/constraints/building_address_immutable.py @@ -21,7 +21,6 @@ values_differ, ) - _AUTHORITATIVE_DOC_TYPES = { "structural_permit", "vermessungsprotokoll", @@ -36,7 +35,7 @@ class BuildingAddressImmutable: Strict mode: when no prior fact exists, fall back to ``buildings.address`` (loaded as ``stammdaten.building.address``). A claim that contradicts the stammdaten value is rejected even on - the first write — buildings don't relocate because someone typed a + the first write; buildings don't relocate because someone typed a different street into an email. """ @@ -52,8 +51,7 @@ def check( ) -> ValidationResult: stammdaten_value = event_stammdaten(event, "building").get("address") is_authoritative_pdf = ( - event_source(event) == "pdf" - and event_document_type(event) in _AUTHORITATIVE_DOC_TYPES + event_source(event) == "pdf" and event_document_type(event) in _AUTHORITATIVE_DOC_TYPES ) if current is None: @@ -69,7 +67,7 @@ def check( return ValidationResult.rejected( "building address contradicts stammdaten " f"({stammdaten_value!r} on file, event claims " - f"{proposed.value!r}) — only an authoritative document " + f"{proposed.value!r}): only an authoritative document " f"({_REQUIRED_DOC_LIST}) can revise a building's address", required_source_type=_REQUIRED_DOC_LIST, ) @@ -83,7 +81,7 @@ def check( ) return ValidationResult.rejected( - "building address is immutable from free-text events — " + "building address is immutable from free-text events; " "an authoritative document (structural_permit, " "vermessungsprotokoll, or kaufvertrag) is required", required_source_type=_REQUIRED_DOC_LIST, diff --git a/backend/pipeline/constraints/building_floor_count_immutable.py b/backend/pipeline/constraints/building_floor_count_immutable.py index 3d2bd8d..f6dfbed 100644 --- a/backend/pipeline/constraints/building_floor_count_immutable.py +++ b/backend/pipeline/constraints/building_floor_count_immutable.py @@ -1,7 +1,7 @@ """Building floor count is immutable post-stammdaten (PM's stated example). Once the stammdaten loader sets a building's floor count, that value -is a physical property of the building — emails, Slack messages, and +is a physical property of the building: emails, Slack messages, and free-text events cannot change it. The only legitimate source for a revision is a structural permit PDF (``document_type=structural_permit``) that documents an actual conversion. @@ -28,7 +28,7 @@ class BuildingFloorCountImmutable: Strict mode: when no prior fact exists, fall back to ``buildings.metadata.etagen`` (loaded as ``stammdaten.building. floor_count`` by the worker). A claim that contradicts the - stammdaten value is rejected even on the very first write — the + stammdaten value is rejected even on the very first write; the physical building doesn't grow new floors because a tenant emails about ``7. Stockwerk``. """ @@ -45,14 +45,11 @@ def check( ) -> ValidationResult: stammdaten_value = event_stammdaten(event, "building").get("floor_count") is_permit_pdf = ( - event_source(event) == "pdf" - and event_document_type(event) == "structural_permit" + event_source(event) == "pdf" and event_document_type(event) == "structural_permit" ) if current is None: - if stammdaten_value is not None and values_differ( - proposed.value, stammdaten_value - ): + if stammdaten_value is not None and values_differ(proposed.value, stammdaten_value): if is_permit_pdf: return ValidationResult.needs_review( "building floor count change vs stammdaten " @@ -64,7 +61,7 @@ def check( return ValidationResult.rejected( "building floor count contradicts stammdaten " f"({stammdaten_value} on file, event claims " - f"{proposed.value}) — only a structural_permit PDF " + f"{proposed.value}): only a structural_permit PDF " "can revise a physical building property", required_source_type="structural_permit", ) @@ -79,7 +76,7 @@ def check( return ValidationResult.rejected( "building floor count is immutable; a free-text event " - "cannot change a physical building property — a " + "cannot change a physical building property; a " "structural_permit PDF is required", required_source_type="structural_permit", ) diff --git a/backend/pipeline/constraints/building_year_built_immutable.py b/backend/pipeline/constraints/building_year_built_immutable.py index a8d9b27..7aed8f3 100644 --- a/backend/pipeline/constraints/building_year_built_immutable.py +++ b/backend/pipeline/constraints/building_year_built_immutable.py @@ -2,7 +2,7 @@ A building only has one year built; this is a Bauamt fact, not a free-text fact. We reject *any* attempt to change it after the -stammdaten load — even structural permits don't change the year +stammdaten load; even structural permits don't change the year built. Corrections are an admin action via the override endpoint with a written audit reason. """ @@ -41,13 +41,11 @@ def check( ) -> ValidationResult: stammdaten_value = event_stammdaten(event, "building").get("year_built") if current is None: - if stammdaten_value is not None and values_differ( - proposed.value, stammdaten_value - ): + if stammdaten_value is not None and values_differ(proposed.value, stammdaten_value): return ValidationResult.rejected( "building year-built contradicts stammdaten " f"({stammdaten_value} on file, event claims " - f"{proposed.value}) — corrections require an explicit " + f"{proposed.value}): corrections require an explicit " "admin override with audit reason", ) return ValidationResult.passed("no prior fact, seeding") diff --git a/backend/pipeline/constraints/compliance_facts_require_authoritative_source.py b/backend/pipeline/constraints/compliance_facts_require_authoritative_source.py index e00a175..5791db0 100644 --- a/backend/pipeline/constraints/compliance_facts_require_authoritative_source.py +++ b/backend/pipeline/constraints/compliance_facts_require_authoritative_source.py @@ -1,7 +1,7 @@ """Compliance facts require an authoritative source (web or PDF). -Compliance state — Brandschutznachweis, Mietpreisbremse status, Bauamt -deadlines, fire-safety certificates — must come from the authority +Compliance state (Brandschutznachweis, Mietpreisbremse status, Bauamt +deadlines, fire-safety certificates) must come from the authority itself or its public web record. An email forwarding rumour-of-fact is not sufficient evidence to mutate a compliance fact, even when the email is internally consistent and confidently extracted. @@ -24,7 +24,6 @@ register, ) - _AUTHORITATIVE_PDF_TYPES: frozenset[str] = frozenset( {"structural_permit", "vermessungsprotokoll", "kaufvertrag"} ) @@ -33,10 +32,10 @@ class ComplianceFactsRequireAuthoritativeSource: """Email/Slack-sourced compliance proposals are rejected. - Web-sourced (Tavily) and PDF-with-recognised-document-type + Web-sourced and PDF-with-recognised-document-type proposals pass without review since the source itself carries weight. PDFs whose document_type is ``other`` or unset land in - needs_review — we know there's a document, we don't know if it's + needs_review: we know there's a document, we don't know if it's the right one. """ @@ -54,7 +53,7 @@ def check( doctype = event_document_type(event) if source == "web": - # Tavily / authority-page lookup. Trust the source. + # Web lookup (e.g. an authority page). Trust the source. return ValidationResult.passed("web source, authoritative") if source == "pdf": @@ -68,18 +67,18 @@ def check( "document_type; classify the PDF before applying", required_source_type="structural_permit | vermessungsprotokoll | kaufvertrag", ) - # Doctype like 'invoice' / 'mahnung' / 'lease' — wrong kind. + # Doctype like 'invoice' / 'mahnung' / 'lease': wrong kind. return ValidationResult.rejected( f"compliance proposal from a PDF whose document_type is " - f"{doctype!r} — that is not an authoritative source for " + f"{doctype!r}: that is not an authoritative source for " f"compliance facts", required_source_type="structural_permit | vermessungsprotokoll | kaufvertrag", ) - # email, slack, debug, or unknown — reject. + # email, slack, debug, or unknown: reject. return ValidationResult.rejected( f"compliance facts require an authoritative source " - f"(web lookup or an authority PDF) — a {source or 'unknown'}-" + f"(web lookup or an authority PDF): a {source or 'unknown'}-" f"sourced event is not sufficient", required_source_type="web | structural_permit | vermessungsprotokoll | kaufvertrag", ) diff --git a/backend/pipeline/constraints/owner_change_requires_kaufvertrag.py b/backend/pipeline/constraints/owner_change_requires_kaufvertrag.py index 5b1f1b8..2460fa9 100644 --- a/backend/pipeline/constraints/owner_change_requires_kaufvertrag.py +++ b/backend/pipeline/constraints/owner_change_requires_kaufvertrag.py @@ -38,7 +38,7 @@ def check( if event_source(event) == "pdf" and event_document_type(event) == "kaufvertrag": return ValidationResult.needs_review( "owner change with Kaufvertrag PDF; human confirmation " - "required before applying — Grundbuch should be " + "required before applying; the Grundbuch should be " "cross-checked", required_source_type="kaufvertrag", ) diff --git a/backend/pipeline/constraints/property_square_meters_tolerance.py b/backend/pipeline/constraints/property_square_meters_tolerance.py index a2d4143..dc2621c 100644 --- a/backend/pipeline/constraints/property_square_meters_tolerance.py +++ b/backend/pipeline/constraints/property_square_meters_tolerance.py @@ -2,7 +2,7 @@ A unit's ``wohnflaeche_qm`` lives in stammdaten and is occasionally re-measured. Routine corrections of < 5 % (e.g. "we re-measured the -balcony") pass; a swing > 5 % is suspicious — either a typo, a +balcony") pass; a swing > 5 % is suspicious: either a typo, a miscount of a different unit, or a real conversion that needs a ``vermessungsprotokoll`` to substantiate. """ @@ -61,7 +61,7 @@ def check( prior_qm = _parse_qm(str(current.get("value", ""))) new_qm = _parse_qm(proposed.value) if prior_qm is None or new_qm is None or prior_qm == 0: - # Couldn't parse — let the differ-skipped path handle it. + # Couldn't parse: let the differ-skipped path handle it. return ValidationResult.passed("could not parse qm; deferring") delta_pct = abs(new_qm - prior_qm) / prior_qm * 100.0 diff --git a/backend/pipeline/constraints/rent_amount_change_requires_addendum.py b/backend/pipeline/constraints/rent_amount_change_requires_addendum.py index d657c0d..81885dc 100644 --- a/backend/pipeline/constraints/rent_amount_change_requires_addendum.py +++ b/backend/pipeline/constraints/rent_amount_change_requires_addendum.py @@ -1,9 +1,9 @@ """Rent amount changes require a lease-addendum PDF. -Step 5's eval surfaced the failure mode directly: an owner-side email +The extraction eval surfaced the failure mode directly: an owner-side email saying "we might need to look at the rent at some point" produced a spurious ``financials.rent_amount`` proposal. Even high-confidence -free-text events shouldn't move the recorded rent — the only legal +free-text events shouldn't move the recorded rent; the only legal instrument that changes a tenancy's rent is an addendum to the Mietvertrag. """ @@ -35,13 +35,12 @@ def check( event: dict[str, Any], ) -> ValidationResult: if current is None: - # First-time set — likely from stammdaten or initial lease. + # First-time set, likely from stammdaten or initial lease. return ValidationResult.passed("no prior fact, seeding") if event_source(event) == "pdf" and event_document_type(event) == "lease_addendum": return ValidationResult.needs_review( - "rent change with lease_addendum PDF; needs human " - "confirmation before applying", + "rent change with lease_addendum PDF; needs human confirmation before applying", required_source_type="lease_addendum", ) diff --git a/backend/pipeline/constraints/tenant_identity_change_requires_mietvertrag.py b/backend/pipeline/constraints/tenant_identity_change_requires_mietvertrag.py index 565815c..bebf1f5 100644 --- a/backend/pipeline/constraints/tenant_identity_change_requires_mietvertrag.py +++ b/backend/pipeline/constraints/tenant_identity_change_requires_mietvertrag.py @@ -1,6 +1,6 @@ """Tenant identity changes require a Mietvertrag PDF. -A new tenant moving in is a binding legal change — Buena's stammdaten +A new tenant moving in is a binding legal change; Buena's stammdaten records ``current_tenant`` per unit, and free-text events are not sufficient evidence to mutate it. An incoming Mietvertrag PDF (``document_type=lease``) routes through the validator with diff --git a/backend/pipeline/coverage.py b/backend/pipeline/coverage.py index b5a9470..571a812 100644 --- a/backend/pipeline/coverage.py +++ b/backend/pipeline/coverage.py @@ -1,12 +1,13 @@ """Schema-completeness scorecard for a property file. -Phase 12+ — judges look at our markdown and ask "what's missing?". Today -the file shows what we know (facts + uncertainties); the *absence* of -data is invisible. This module declares per-section expected-fact -coordinates so the renderer can emit a compact ``## Coverage`` block -naming what's present (✓) and what's absent (⨯). - -The expected-field lists are intentionally short and demo-focused — we +A reader of a property file needs to know what's missing as well as +what's known. The file itself shows what we know (facts + +uncertainties); the *absence* of data is invisible. This module +declares per-section expected-fact coordinates so the renderer can +emit a compact ``## Coverage`` block naming what's present (✓) and +what's absent (⨯). + +The expected-field lists are intentionally short: we favour "the operator would notice if this were missing" over a complete catalog. Add fields here as new fact-discovery rules ship; the absence report grows naturally. @@ -88,9 +89,7 @@ def compute_coverage( sections: dict[str, list[tuple[str, bool]]] = {} for section, field, label_en, label_de in _EXPECTED_FACTS: label = label_de if lang == "de" else label_en - sections.setdefault(section, []).append( - (label, (section, field) in fact_keys) - ) + sections.setdefault(section, []).append((label, (section, field) in fact_keys)) total_present = sum(1 for _, ok in stamm_rows if ok) + sum( 1 for rows in sections.values() for _, ok in rows if ok @@ -111,15 +110,13 @@ def render_coverage_block(report: CoverageReport, *, lang: str = "en") -> list[s Empty areas are skipped so the block stays tight. """ title = "Abdeckung" if lang == "de" else "Coverage" - stamm_label = "Stammdaten" + stamm_label = "Stammdaten" if lang == "de" else "Master data" lines: list[str] = [f"## {title}", ""] if report.stammdaten: - joined = " · ".join( - f"{'✓' if ok else '⨯'} {label}" for label, ok in report.stammdaten - ) - lines.append(f"- **{stamm_label}** — {joined}") + joined = " · ".join(f"{'✓' if ok else '⨯'} {label}" for label, ok in report.stammdaten) + lines.append(f"- **{stamm_label}**: {joined}") section_titles_de = { "lease": "Mietvertrag", @@ -136,11 +133,9 @@ def render_coverage_block(report: CoverageReport, *, lang: str = "en") -> list[s titles = section_titles_de if lang == "de" else section_titles_en for section, rows in report.sections.items(): - joined = " · ".join( - f"{'✓' if ok else '⨯'} {label}" for label, ok in rows - ) + joined = " · ".join(f"{'✓' if ok else '⨯'} {label}" for label, ok in rows) title_label = titles.get(section, section.replace("_", " ").title()) - lines.append(f"- **{title_label}** — {joined}") + lines.append(f"- **{title_label}**: {joined}") lines.append("") return lines @@ -149,13 +144,9 @@ def render_coverage_block(report: CoverageReport, *, lang: str = "en") -> list[s def coverage_to_index(report: CoverageReport) -> dict[str, object]: """Return a JSON-friendly dict for the ``content_index`` JSONB column.""" return { - "stammdaten": [ - {"label": label, "present": ok} for label, ok in report.stammdaten - ], + "stammdaten": [{"label": label, "present": ok} for label, ok in report.stammdaten], "sections": { - section: [ - {"label": label, "present": ok} for label, ok in rows - ] + section: [{"label": label, "present": ok} for label, ok in rows] for section, rows in report.sections.items() }, "total_present": report.total_present, diff --git a/backend/pipeline/differ.py b/backend/pipeline/differ.py index 2cf7c9f..56d0076 100644 --- a/backend/pipeline/differ.py +++ b/backend/pipeline/differ.py @@ -1,7 +1,7 @@ """Reconcile proposed facts against the current fact table. -Resolution rules (KEYSTONE Part V): -1. **Source precedence:** ``pdf > erp > email > slack > web > debug`` — a +Resolution rules: +1. **Source precedence:** ``pdf > erp > email > slack > web > debug``. A proposed fact from a weaker source cannot displace a stronger one unless it raises confidence materially (+0.1). 2. **Confidence:** higher confidence wins between equal-source facts. @@ -43,7 +43,7 @@ class FactDecision: value: str confidence: float supersedes_id: UUID | None - # Diagnostic only — why this decision was made. + # Diagnostic only: why this decision was made. reason: str @@ -104,7 +104,8 @@ def _should_replace( if new_rank == old_rank and new_confidence < existing["confidence"]: return False, "lower_confidence" - return True, f"replace ({new_source}@{new_confidence:.2f} > {existing['source']}@{existing['confidence']:.2f})" + old = f"{existing['source']}@{existing['confidence']:.2f}" + return True, f"replace ({new_source}@{new_confidence:.2f} > {old})" async def diff( @@ -113,7 +114,7 @@ async def diff( property_id: UUID, event_source: str, proposals: list[dict[str, Any]], - now: datetime | None = None, # noqa: ARG001 — reserved for future recency logic + now: datetime | None = None, # noqa: ARG001 (reserved for future recency logic) ) -> DiffPlan: """Compute a :class:`DiffPlan` for the proposed facts.""" current = await load_current_facts(session, property_id) @@ -128,15 +129,13 @@ async def diff( key = (section, field) if key in current: - # Phase 11 — human edits are sticky. The brief's - # "surgically updated without destroying human edits" - # rule means an extractor proposal cannot overwrite a - # fact a property manager has hand-corrected. Override - # is still possible via the API's force=true path. + # Human edits are sticky: a property file must be + # updated surgically without destroying human edits, so + # an extractor proposal cannot overwrite a fact a + # property manager has hand-corrected. Override is still + # possible via the API's force=true path. if current[key].get("human_edited"): - skipped.append( - (f"{section}.{field}", "preserved_human_edit") - ) + skipped.append((f"{section}.{field}", "preserved_human_edit")) continue replace, reason = _should_replace(event_source, confidence, current[key], value) if not replace: diff --git a/backend/pipeline/events.py b/backend/pipeline/events.py index 2789788..6783629 100644 --- a/backend/pipeline/events.py +++ b/backend/pipeline/events.py @@ -4,8 +4,8 @@ the same two primitives: insert an event idempotently, and notify anything listening on the property's SSE stream when a new fact lands. -The notification layer is a plain in-process ``asyncio.Queue`` fan-out — no -Redis, no Kafka (Part III: Postgres is the queue). +The notification layer is a plain in-process ``asyncio.Queue`` fan-out with +no Redis and no Kafka: Postgres is the queue, so there is no separate broker. """ from __future__ import annotations @@ -26,9 +26,7 @@ class EventBus: """Per-property in-memory fan-out. Subscribers get a queue; publishers broadcast.""" - subscribers: dict[UUID | None, set[asyncio.Queue[dict[str, Any]]]] = field( - default_factory=dict - ) + subscribers: dict[UUID | None, set[asyncio.Queue[dict[str, Any]]]] = field(default_factory=dict) _lock: asyncio.Lock = field(default_factory=asyncio.Lock) async def subscribe(self, property_id: UUID | None) -> asyncio.Queue[dict[str, Any]]: @@ -112,6 +110,6 @@ async def insert_event( def _json_or_none(value: dict[str, Any] | None) -> str | None: """Tiny helper to keep SQL bind params JSON-ready.""" - import json # noqa: PLC0415 — local import, hot path is rare + import json # noqa: PLC0415 (local import, hot path is rare) return None if value is None else json.dumps(value) diff --git a/backend/pipeline/extractor.py b/backend/pipeline/extractor.py index 382fdcb..f449669 100644 --- a/backend/pipeline/extractor.py +++ b/backend/pipeline/extractor.py @@ -1,17 +1,16 @@ """Extract structured facts from an event. -Phase 8 Step 5 reshapes this module: - -- Detect the event language with :mod:`backend.services.lang` and - dispatch to the matching prompt template (German vs English). -- Default extractor model is **Gemini Pro** (per Step 5: extraction - quality matters more than throughput on the email path). Flash is - reserved for the auxiliary category-classification fallback below. -- Rule fallback consults :mod:`backend.pipeline.lexicon` so the - keyword set lives in one place and covers German + English. - -Both paths return the same :class:`ExtractionResult` so downstream -stages don't need to branch. +- The event language is detected with :mod:`backend.services.lang` and + selects the German or English prompt. +- The configured LLM provider (:mod:`backend.services.llm`) runs the shared + extraction prompt and schema. Without a configured provider, or after its + retries fail, a deterministic extractor built on + :mod:`backend.pipeline.lexicon` (German and English keywords) runs instead. +- Either way, facts below :data:`CONFIDENCE_FLOOR` are moved to + ``uncertain[]``, so a low-confidence guess never becomes a fact. + +Both paths return the same :class:`ExtractionResult`, so downstream stages +do not branch on which one ran. """ from __future__ import annotations @@ -32,30 +31,18 @@ TENANT_CHANGE, WATER, WINDOW_DOOR, - Topic, categorize, ) -from backend.services.gemini import ( - ExtractionResult, - GeminiUnavailable, - extract_facts as gemini_extract, - is_available as gemini_available, -) from backend.services.lang import detect_language -from backend.services.pioneer_llm import ( - PioneerUnavailable, - extract_facts as pioneer_extract, - is_available as pioneer_available, -) +from backend.services.llm import ExtractionResult, LLMUnavailableError, get_provider log = structlog.get_logger(__name__) -# Phase 9 Step 9.1 — confidence floor. Facts the extractor produced -# below this threshold are demoted to ``uncertain[]`` regardless of -# whether the model itself flagged them, so the applier never writes -# a low-confidence fact into the canonical ``facts`` table. -# Hardcoded for now; a per-section config table is a Phase 9+ item. +# Facts the extractor produced below this confidence are demoted to +# ``uncertain[]`` whether or not the model flagged them, so the applier never +# writes a low-confidence fact into ``facts``. One global value for now; a +# per-section threshold would need calibration data per section. CONFIDENCE_FLOOR: float = 0.7 @@ -66,10 +53,10 @@ def _apply_confidence_floor(result: ExtractionResult) -> ExtractionResult: """Demote sub-floor facts to ``uncertain[]`` so they don't reach the applier. - The extractor (Gemini *or* rule fallback) sometimes emits facts at - confidence 0.6 — high enough to be worth surfacing, low enough to - not warrant overwriting a canonical fact. Step 9.1's contract is - that those land in ``uncertainty_events`` instead of ``facts``. + The extractor (LLM provider or rule fallback) sometimes emits facts at + confidence 0.6: high enough to be worth surfacing, low enough to + not warrant overwriting a canonical fact. Those land in + ``uncertainty_events`` instead of ``facts``. """ keep: list[dict[str, Any]] = [] demoted: list[dict[str, Any]] = [] @@ -127,23 +114,21 @@ def _extract_subject(raw: str) -> str: # Field names align with the field_vocabulary.json contract so the rule # fallback's output isn't penalised by the eval scorer just for naming. _TOPIC_DISPATCH: dict[str, tuple[str, str, str, str]] = { - HEATING.name: ("maintenance", "high", "maintenance", "open_heating_issue"), - WATER.name: ("maintenance", "urgent", "maintenance", "open_water_leak"), - KEY_LOSS.name: ("maintenance", "medium", "maintenance", "key_lost"), - WINDOW_DOOR.name: ("maintenance", "medium", "maintenance", "defective_window"), - LEASE.name: ("lease", "medium", "lease", "renewal_discussion"), - TENANT_CHANGE.name: ("tenant_change","medium","lease", "termination_notice"), - PAYMENT.name: ("payment", "medium", "financials", "payment_mention"), - OWNER_COMM.name: ("owner_communication", "medium", "overview", "sale_intent"), - COMPLAINT.name: ("maintenance", "medium", "maintenance", "noise_complaint"), - COMPLIANCE.name: ("compliance", "medium", "compliance", "regulatory_mention"), + HEATING.name: ("maintenance", "high", "maintenance", "open_heating_issue"), + WATER.name: ("maintenance", "urgent", "maintenance", "open_water_leak"), + KEY_LOSS.name: ("maintenance", "medium", "maintenance", "key_lost"), + WINDOW_DOOR.name: ("maintenance", "medium", "maintenance", "defective_window"), + LEASE.name: ("lease", "medium", "lease", "renewal_discussion"), + TENANT_CHANGE.name: ("tenant_change", "medium", "lease", "termination_notice"), + PAYMENT.name: ("payment", "medium", "financials", "payment_mention"), + OWNER_COMM.name: ("owner_communication", "medium", "overview", "sale_intent"), + COMPLAINT.name: ("maintenance", "medium", "maintenance", "noise_complaint"), + COMPLIANCE.name: ("compliance", "medium", "compliance", "regulatory_mention"), } -def _rule_based( - *, source: str, raw_content: str, lang: str -) -> ExtractionResult: - """Deterministic fallback when Gemini is unavailable or errors out. +def _rule_based(*, source: str, raw_content: str, lang: str) -> ExtractionResult: + """Deterministic fallback when no LLM provider is configured or it fails. Uses :mod:`backend.pipeline.lexicon` for the keyword set so the German + English vocabularies coexist. Only emits a fact when one @@ -170,8 +155,11 @@ def _rule_based( category, priority, section, field = _TOPIC_DISPATCH[topic.name] note = f"{subject}" if sender_hint: - note = f"{subject} (gemeldet via {source} von {sender_hint})" if lang == "de" \ + note = ( + f"{subject} (gemeldet via {source} von {sender_hint})" + if lang == "de" else f"{subject} (reported via {source} from {sender_hint})" + ) return ExtractionResult( category=category, priority=priority, @@ -196,23 +184,17 @@ async def extract( source: str, raw_content: str, ) -> ExtractionResult: - """Run an LLM extractor if possible; otherwise fall back to the lexicon rules. + """Run the configured LLM extractor, or the lexicon rules when it is unavailable. - Pioneer (Claude Sonnet 4.6 via the OpenAI-compatible gateway) is the - primary path — Phase 11 made it the production extractor after the - Gemini free-tier quota became unreliable. Gemini stays as a - secondary so a working ``GEMINI_API_KEY`` still gets exercised. The - lexicon-based rule fallback is the last line of defence and never - talks to a remote model. - - ``lang`` is detected from ``raw_content`` and threaded into every - path so the prompt + lexicon align with the email body's language. + ``lang`` is detected from ``raw_content`` and used by both paths, so the + prompt and the lexicon match the event's language. """ lang = detect_language(raw_content) - if pioneer_available(): + provider = get_provider() + if provider is not None: try: - result = await pioneer_extract( + result = await provider.extract_facts( property_name=property_name, current_context_excerpt=current_context_excerpt, source=source, @@ -220,23 +202,10 @@ async def extract( lang=lang, ) return _apply_confidence_floor(result) - except PioneerUnavailable as exc: - log.warning("extractor.pioneer_unavailable", error=str(exc), lang=lang) + except LLMUnavailableError as exc: + log.warning("extractor.llm_unavailable", provider=provider.name, error=str(exc)[:300]) - if gemini_available(): - try: - result = await gemini_extract( - property_name=property_name, - current_context_excerpt=current_context_excerpt, - source=source, - raw_content=raw_content, - lang=lang, - ) - return _apply_confidence_floor(result) - except GeminiUnavailable as exc: - log.warning("extractor.gemini_unavailable", error=str(exc), lang=lang) - - log.info("extractor.fallback.rule_based", source=source, lang=lang) - return _apply_confidence_floor( - _rule_based(source=source, raw_content=raw_content, lang=lang) - ) + # Expected on a keyless install, so only worth a debug line there. + log_fallback = log.info if provider is not None else log.debug + log_fallback("extractor.fallback.rule_based", source=source, lang=lang) + return _apply_confidence_floor(_rule_based(source=source, raw_content=raw_content, lang=lang)) diff --git a/backend/pipeline/lexicon.py b/backend/pipeline/lexicon.py index 266b497..a2df25b 100644 --- a/backend/pipeline/lexicon.py +++ b/backend/pipeline/lexicon.py @@ -1,11 +1,13 @@ """Per-category keyword lexicon for the rule-based extractor fallback. -Step 5 promotes the previously-inlined regex set to a single source of -truth. Each ``Topic`` carries a German + English keyword pattern; both -match case-insensitively with word boundaries. - -The lexicon is also surfaced to Step 8's signal_discovery notebook so -keyword analysis runs against the same vocabulary the extractor uses. +This module is the single source of truth for the keyword regexes that +used to be inlined in the extractor. Each ``Topic`` carries a German + +English keyword pattern; both match case-insensitively with word +boundaries. + +The lexicon is also used by the signal-discovery notebook +(``eval/notebooks/signal_discovery.py``) so keyword analysis runs +against the same vocabulary the extractor uses. """ from __future__ import annotations @@ -14,7 +16,7 @@ from dataclasses import dataclass from typing import Final -# A keyword family — one pattern per language. The patterns use Python +# A keyword family: one pattern per language. The patterns use Python # alternation (``a|b|c``); ``compile`` builds the case-insensitive, # word-boundary regex. _TopicPattern = tuple[str, str] # (de_pattern, en_pattern) @@ -30,7 +32,7 @@ class Topic: def matches(self, text: str, *, lang: str | None = None) -> str | None: """Return the matched substring, or ``None`` if neither pattern fires.""" - for code, regex in self._dispatch(lang): + for _code, regex in self._dispatch(lang): m = regex.search(text) if m: return m.group(0) @@ -49,11 +51,11 @@ def _compile(pat: str) -> re.Pattern[str]: return re.compile(rf"\b(?:{pat})\b", re.IGNORECASE) -# Topic patterns drawn from real Buena bodies + ground truth + Phase 1's -# regex set. Each pattern is intentionally narrow — over-broad keywords -# (``mahnung`` for example) are out of this lexicon and live in -# ``router.WEG_KEYWORDS`` instead, where the precedence rules can keep -# them from over-matching. +# Topic patterns drawn from real email bodies in the sample dataset, the +# eval ground truth, and the original inline regex set. Each pattern is +# intentionally narrow; over-broad keywords (``mahnung`` for example) +# are out of this lexicon and live in ``router.WEG_KEYWORDS`` instead, +# where the precedence rules can keep them from over-matching. HEATING: Final = Topic( name="heating", de=_compile("heiz|heizung|kalt|warmwasser|frost|thermostat|heizungsausfall"), @@ -79,8 +81,7 @@ def _compile(pat: str) -> re.Pattern[str]: "nachmieter|untermiete|mieterwechsel|mietende|wohnungsuebergabe" ), en=_compile( - "lease|tenancy|termination|renewal|sub[- ]let|tenant[- ]change|" - "move[- ]out|hand[- ]over" + "lease|tenancy|termination|renewal|sub[- ]let|tenant[- ]change|move[- ]out|hand[- ]over" ), ) COMPLIANCE: Final = Topic( @@ -89,10 +90,7 @@ def _compile(pat: str) -> re.Pattern[str]: "mietpreisbremse|verordnung|prüfung|abnahme|brandschutz|" "modernisierung|baugenehmigung|brandschutznachweis" ), - en=_compile( - "regulation|inspection|approval|fire[- ]safety|modernization|" - "building[- ]permit" - ), + en=_compile("regulation|inspection|approval|fire[- ]safety|modernization|building[- ]permit"), ) COMPLAINT: Final = Topic( name="complaint", @@ -112,12 +110,10 @@ def _compile(pat: str) -> re.Pattern[str]: TENANT_CHANGE: Final = Topic( name="tenant_change", de=_compile( - "kuendigung|kündigung|mieterwechsel|nachmieter|" - "wohnungsuebergabe|wohnungsübergabe|kaution" + "kuendigung|kündigung|mieterwechsel|nachmieter|wohnungsuebergabe|wohnungsübergabe|kaution" ), en=_compile( - "lease[- ]termination|tenant[- ]change|new[- ]tenant|" - "hand[- ]over|deposit[- ]return" + "lease[- ]termination|tenant[- ]change|new[- ]tenant|hand[- ]over|deposit[- ]return" ), ) OWNER_COMM: Final = Topic( @@ -126,13 +122,11 @@ def _compile(pat: str) -> re.Pattern[str]: "verkaufsabsicht|sonderumlage|hausverwaltung|eigentuemer|" "eigentümer|etv|beirat|bescheinigung" ), - en=_compile( - "sale[- ]intent|owner[- ]assembly|board[- ]member|certificate" - ), + en=_compile("sale[- ]intent|owner[- ]assembly|board[- ]member|certificate"), ) -# Ordered list — categorize() returns the first match. +# Ordered list: categorize() returns the first match. TOPICS: tuple[Topic, ...] = ( OWNER_COMM, TENANT_CHANGE, diff --git a/backend/pipeline/materializer.py b/backend/pipeline/materializer.py index 6ccc29b..186dd87 100644 --- a/backend/pipeline/materializer.py +++ b/backend/pipeline/materializer.py @@ -1,12 +1,12 @@ """Materialize rendered markdown into the per-scope file tables. -Phase 12 — every fact write fans out to update the file rows for the +Every fact write fans out to update the file rows for the fact's scope plus all dependent scopes. A property fact regenerates the property's file. A building fact regenerates the building's file plus every property file under that building. A liegenschaft fact cascades through buildings and their properties. The materialize step runs in the same transaction as the fact write, so file rows are -never stale relative to facts (KEYSTONE Part XIV invariant). +never stale relative to facts. LLM-free by design: the renderer is deterministic markdown. Keeping LLM calls out of this layer guarantees the materialize step burns no @@ -17,7 +17,6 @@ import asyncio import json -from typing import Any from uuid import UUID import structlog @@ -89,7 +88,7 @@ async def materialize_property( ) -> int: """Render and upsert the property's markdown + content_index row. - Phase 12+ — calls :func:`render_property_full` so the materialized + Calls :func:`render_property_full` so the materialized row carries both ``content_md`` (human/agent reading) and ``content_index`` (typed JSON for programmatic consumers). Returns 1 on write, 0 if the property doesn't exist. @@ -260,7 +259,8 @@ async def materialize_all(session: AsyncSession) -> dict[str, int]: """Bootstrap every property/building/liegenschaft file row. Used by ``connectors.cli materialize-all`` after the migration runs - (and by Cloud Run's startup script) to fill the cache up front. + (and by ``POST /admin/materialize-all`` in deployments without CLI + access) to fill the cache up front. Caller commits the surrounding transaction. """ properties_written = 0 @@ -273,7 +273,7 @@ async def materialize_all(session: AsyncSession) -> dict[str, int]: session, UUID(str(r.id)), trigger_scope="bootstrap", - trigger_summary="Initial materialization (Phase 12 backfill)", + trigger_summary="Initial materialization", ) rows = (await session.execute(text("SELECT id FROM buildings"))).all() @@ -282,7 +282,7 @@ async def materialize_all(session: AsyncSession) -> dict[str, int]: session, UUID(str(r.id)), trigger_scope="bootstrap", - trigger_summary="Initial materialization (Phase 12 backfill)", + trigger_summary="Initial materialization", ) rows = (await session.execute(text("SELECT id FROM liegenschaften"))).all() @@ -291,7 +291,7 @@ async def materialize_all(session: AsyncSession) -> dict[str, int]: session, UUID(str(r.id)), trigger_scope="bootstrap", - trigger_summary="Initial materialization (Phase 12 backfill)", + trigger_summary="Initial materialization", ) log.info( @@ -318,10 +318,11 @@ async def propagate_after_fact_write( ) -> dict[str, int]: """Fan out materialization for a single fact write. - Operates inside the caller's transaction — no session creation, no - commit. The Phase 12 invariant (KEYSTONE Part XIV) is that the - fact write and every dependent file row update share one - transaction, so an exception here rolls the whole write back. + Operates inside the caller's transaction: no session creation, no + commit. The invariant is that file rows are never stale relative + to facts, so the fact write and every dependent file row update + share one transaction and an exception here rolls the whole write + back. Cascade rules: - ``property_id`` set → property's file refreshed. @@ -330,10 +331,10 @@ async def propagate_after_fact_write( - ``liegenschaft_id`` set → WEG's file refreshed AND every building + property under it gets ``trigger_scope='liegenschaft'``. - Scaling note: a single liegenschaft fact in Buena's data - propagates to ~52 property files. Acceptable for Buena volume; + Scaling note: a single liegenschaft fact in the sample dataset + propagates to ~52 property files. Acceptable at that volume; the renderer is deterministic and fast (median 2 KB markdown). - Documented as the scaling boundary in DECISIONS.md. + Documented as the scaling boundary in docs/DECISIONS.md. """ counts: dict[str, int] = {"properties": 0, "buildings": 0, "liegenschaften": 0} diff --git a/backend/pipeline/renderer.py b/backend/pipeline/renderer.py index b7d1c17..f0fd71f 100644 --- a/backend/pipeline/renderer.py +++ b/backend/pipeline/renderer.py @@ -1,8 +1,7 @@ """Render a property / building / Liegenschaft's current facts into markdown. -The renderer is the canonical read path. Phase 8.1 widens it from -"property only" to the three-tier hierarchy -(:func:`render_markdown` for property, +The renderer is the canonical read path. It covers the three-tier +hierarchy (:func:`render_markdown` for property, :func:`render_building_markdown` for Haus, :func:`render_liegenschaft_markdown` for WEG). @@ -10,17 +9,17 @@ recent N events for its building) and a **WEG Context** block (most recent N for its Liegenschaft). Walking up the hierarchy honours the PM mental model that a unit is part of a building, which is part of a -WEG — and events at higher tiers genuinely affect the unit even when +WEG, and events at higher tiers genuinely affect the unit even when not directly attributed to it. Every fact line carries the inline ``[source: ]`` link. -Web-sourced facts (Tavily) get a 🌐 badge. +Facts from web-sourced events get a 🌐 badge. """ from __future__ import annotations from dataclasses import dataclass -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from uuid import UUID import structlog @@ -57,7 +56,7 @@ } #: German section titles surfaced when a property's source-event language -#: majority is German (Phase 8 Step 5). +#: majority is German. SECTION_TITLES_DE: dict[str, str] = { "overview": "Überblick", "tenants": "Mieter", @@ -84,7 +83,7 @@ "open_building": "Open building view", "open_weg": "Open WEG view", "needs_review": "Needs Review", - "stammdaten": "Stammdaten", + "stammdaten": "Master data", "stammdaten_subtitle": "Master record from the lease/owner registry", "unit": "Unit", "tenant": "Current tenant", @@ -99,7 +98,7 @@ "rooms": "Rooms", "no_active_tenant": "No active tenant on file", "older_label": "Older entries", - "older_subtitle": "Compact pointers — click any item to open the original", + "older_subtitle": "Compact pointers: click any item to open the original", }, "de": { "building_context": "Hauskontext", @@ -124,7 +123,7 @@ "rooms": "Zimmer", "no_active_tenant": "Kein aktiver Mieter erfasst", "older_label": "Ältere Einträge", - "older_subtitle": "Kompakte Verweise — anklicken öffnet das Original", + "older_subtitle": "Kompakte Verweise: anklicken öffnet das Original", }, } @@ -132,15 +131,15 @@ CONTEXT_LIMIT: int = 5 -#: Three-tier bucketing thresholds (Phase 12+). +#: Three-tier bucketing thresholds. #: - Active (≤ ACTIVE_DAYS): full detail, confidence inline, full source link. #: - Recent (ACTIVE_DAYS < age ≤ RECENT_DAYS): tight one-liner with date + truncated value. -#: - Archive (> RECENT_DAYS): not rendered per-fact at all — collapsed into a -#: single per-year roll-up block per section ("2024 — 12 entries; last: …"). +#: - Archive (> RECENT_DAYS): not rendered per-fact at all; collapsed into a +#: single per-year roll-up line per section (year, entry count, latest entry). #: #: Picked so a property with decades of history stays bounded: an active -#: window of 90 days keeps the demo's "what's happening this quarter" beat -#: dense, while everything older compresses into a few summary lines. +#: window of 90 days keeps the current quarter's activity in full detail, +#: while everything older compresses into a few summary lines. ACTIVE_DAYS: int = 90 RECENT_DAYS: int = 365 @@ -152,7 +151,7 @@ #: is one click away via the source link. COMPACT_VALUE_PREVIEW_CHARS: int = 100 -#: The activity section is chronological — every processed event writes +#: The activity section is chronological: every processed event writes #: a bullet there. Without a per-section cap, a property with 1000 #: events produces a 200 KB markdown body even when most of those #: events landed today (so date-based bucketing doesn't compress them). @@ -160,7 +159,7 @@ #: into the per-year archive roll-up alongside truly old facts. ACTIVITY_ACTIVE_LIMIT: int = 15 -#: Sections subject to ``ACTIVITY_ACTIVE_LIMIT``. Keep this list short — +#: Sections subject to ``ACTIVITY_ACTIVE_LIMIT``. Keep this list short: #: fact-bearing sections (lease, financials, compliance) should never #: silently drop facts; activity is the only chronological log section. _CAPPED_SECTIONS: frozenset[str] = frozenset({"activity"}) @@ -187,7 +186,7 @@ class FactRow: source_event_id: UUID | None confidence: float source: str | None - # ``occurred_at`` is the original event's ``received_at`` — the moment + # ``occurred_at`` is the original event's ``received_at``: the moment # the fact came into the world, NOT when extraction happened. The # renderer buckets on this so a 20-year-old letter extracted today # still gets the compact render. @@ -198,7 +197,7 @@ class FactRow: class Stammdaten: """Master-record snapshot for a property. - Stammdaten lives outside the events/facts pipeline — it's the + Stammdaten lives outside the events/facts pipeline; it's the authoritative lease/owner registry loaded once at ingest. Surfacing it in the markdown closes the gap where a freshly-onboarded property has no extracted facts yet but still has a real tenant, @@ -271,9 +270,7 @@ async def _fetch_header(session: AsyncSession, property_id: UUID) -> PropertyHea return PropertyHeader(name=row.name, address=row.address) -async def _fetch_stammdaten( - session: AsyncSession, property_id: UUID -) -> Stammdaten | None: +async def _fetch_stammdaten(session: AsyncSession, property_id: UUID) -> Stammdaten | None: """Pull the master-record snapshot for a property. Joins ``properties.metadata`` (unit dimensions), the active row in @@ -441,15 +438,15 @@ def _classify_tier(fact: FactRow, *, now: datetime | None = None) -> FactTier: """Bucket a fact into ``active`` / ``recent`` / ``archive``. Facts with no ``occurred_at`` (manual writes, master-data backfill) - are treated as ``active`` — operators want them visible and + are treated as ``active``: operators want them visible and editable rather than buried in an archive roll-up. """ occurred = fact.occurred_at if occurred is None: return "active" if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) - reference = now or datetime.now(timezone.utc) + occurred = occurred.replace(tzinfo=UTC) + reference = now or datetime.now(UTC) age = reference - occurred if age <= timedelta(days=ACTIVE_DAYS): return "active" @@ -462,7 +459,7 @@ def _is_compact(fact: FactRow, *, now: datetime | None = None) -> bool: """Backward-compat predicate kept for the legacy two-tier callers. True for anything outside the active window (i.e., ``recent`` *or* - ``archive``). The Phase 12 renderer uses :func:`_classify_tier` + ``archive``). The three-tier renderer uses :func:`_classify_tier` directly; this stays so external callers that imported the old name don't break. """ @@ -470,8 +467,8 @@ def _is_compact(fact: FactRow, *, now: datetime | None = None) -> bool: if occurred is None: return False if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) - reference = now or datetime.now(timezone.utc) + occurred = occurred.replace(tzinfo=UTC) + reference = now or datetime.now(UTC) return (reference - occurred) > timedelta(days=ACTIVE_CUTOFF_DAYS) @@ -486,19 +483,15 @@ def _truncate(text_value: str, *, limit: int = COMPACT_VALUE_PREVIEW_CHARS) -> s def _format_fact_line_active(fact: FactRow) -> str: """Detailed render for facts inside the active window. - Same shape as the original Phase 10 line — value verbatim, - confidence inline, full source link + optional web badge. + Value verbatim, confidence inline, full source link + optional + web badge. """ source = ( f"[source: {fact.source_event_id}](/events/{fact.source_event_id}/source)" if fact.source_event_id is not None else "[source: unknown]" ) - badge = ( - " 🌐 _Updated from web sources_" - if (fact.source or "").lower() == "web" - else "" - ) + badge = " 🌐 _Updated from web sources_" if (fact.source or "").lower() == "web" else "" return ( f"- **{_format_field(fact.field)}:** {fact.value} " f"_(confidence {fact.confidence:.2f})_ {source}{badge}" @@ -508,14 +501,15 @@ def _format_fact_line_active(fact: FactRow) -> str: def _format_fact_line_compact(fact: FactRow) -> str: """Tight one-liner used for the **recent** tier (90 d–1 y). - Reads as ``YYYY-MM — Field name: short preview… [open detail](link)``. + Reads as the ``YYYY-MM`` date, the field name, a short preview and + an ``[open detail](link)``. The ``[open detail]`` link points to the source-resolving endpoint so an operator can read the original event without leaving the file. """ if fact.occurred_at is not None: occurred = fact.occurred_at if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) + occurred = occurred.replace(tzinfo=UTC) date_str = occurred.strftime("%Y-%m") else: date_str = "unknown" @@ -526,16 +520,13 @@ def _format_fact_line_compact(fact: FactRow) -> str: else "_(no source on file)_" ) preview = _truncate(fact.value) - return ( - f"- *{date_str}* — **{_format_field(fact.field)}:** {preview} " - f"{detail_link}" - ) + return f"- *{date_str}* · **{_format_field(fact.field)}:** {preview} {detail_link}" def _format_archive_block(facts: list[FactRow], *, lang: str) -> list[str]: """Per-year roll-up for the **archive** tier (> 1 y). - Twelve invoices from 2024 collapse to a single line — operators get + Twelve invoices from 2024 collapse to a single line: operators get the count + a click-through to the most recent of those archive events, instead of twelve bullets pushing the file size past 60 KB. """ @@ -547,7 +538,7 @@ def _format_archive_block(facts: list[FactRow], *, lang: str) -> list[str]: continue occurred = fact.occurred_at if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) + occurred = occurred.replace(tzinfo=UTC) by_year.setdefault(str(occurred.year), []).append(fact) if not by_year: return [] @@ -558,8 +549,7 @@ def _format_archive_block(facts: list[FactRow], *, lang: str) -> list[str]: # Newest in the year, by occurred_at, drives the link target. latest = max( rows, - key=lambda f: f.occurred_at # type: ignore[arg-type,return-value] - or datetime.min.replace(tzinfo=timezone.utc), + key=lambda f: f.occurred_at or datetime.min.replace(tzinfo=UTC), ) link = ( f"[open detail](/events/{latest.source_event_id}/source)" @@ -570,8 +560,7 @@ def _format_archive_block(facts: list[FactRow], *, lang: str) -> list[str]: entries_label = "Einträge" if lang == "de" else "entries" latest_summary = _truncate(latest.value, limit=60) out.append( - f"- **{year}** — {len(rows)} {entries_label} " - f"({last_label}: {latest_summary}) {link}" + f"- **{year}**: {len(rows)} {entries_label} ({last_label}: {latest_summary}) {link}" ) return out @@ -673,10 +662,10 @@ async def _recent_events_for_scope( def _context_body(event: dict[str, str | int]) -> str: """Render the human-facing body of a context event. - For PDF sources whose text hasn't been extracted yet we use the - forward-looking phrasing ``"Invoice — awaiting - extraction"`` (Phase 9 trust-layer ethos: honest about epistemic - state). Once text is extracted (``head_chars > 0``) the snippet + For PDF sources whose text hasn't been extracted yet we say the + invoice is awaiting extraction rather than implying its contents + are known, so the file is honest about what has and hasn't been + read. Once text is extracted (``head_chars > 0``) the snippet drives the display normally. """ source = str(event.get("source") or "") @@ -685,7 +674,7 @@ def _context_body(event: dict[str, str | int]) -> str: if source in {"invoice", "letter"} and head_chars == 0 and filename: label = "Invoice" if source == "invoice" else "Letter" - return f"{label} {filename} — awaiting extraction" + return f"{label} {filename} (awaiting extraction)" snippet = str(event.get("snippet") or "") return snippet[:90] or "(no body)" @@ -695,7 +684,7 @@ def _format_context_event(event: dict[str, str | int]) -> str: """Render one per-tier context event as a markdown bullet with source link.""" when = str(event.get("received_at") or "")[:10] if event.get("received_at") else "?" return ( - f"- *{when}* · `{event['source']}`/{event['kategorie']} — " + f"- *{when}* · `{event['source']}`/{event['kategorie']}: " f"{_context_body(event)} " f"[source: {event['id']}](/events/{event['id']}/source)" ) @@ -714,9 +703,7 @@ async def _fetch_facts_by_scope( "liegenschaft": "liegenschaft_id", }[scope] other_columns = ["property_id", "building_id", "liegenschaft_id"] - other_clauses = " AND ".join( - f"f.{col} IS NULL" for col in other_columns if col != column - ) + other_clauses = " AND ".join(f"f.{col} IS NULL" for col in other_columns if col != column) sql = f""" SELECT f.section, f.field, f.value, f.source_event_id, f.confidence, f.created_at, e.source AS source, @@ -795,7 +782,7 @@ def _format_uncertainty_line(item: UncertaintyRow) -> str: if len(snippet) > 160: snippet = snippet[:157].rstrip() + "…" return ( - f"- _Unclear: {snippet} — {item.reason_uncertain}_ " + f"- _Unclear: {snippet} ({item.reason_uncertain})_ " f"[source: event {item.event_id}](/events/{item.event_id}/source)" ) @@ -814,13 +801,11 @@ class RejectionRow: occurred_at: datetime | None -async def _fetch_pending_rejections( - session: AsyncSession, property_id: UUID -) -> list[RejectionRow]: +async def _fetch_pending_rejections(session: AsyncSession, property_id: UUID) -> list[RejectionRow]: """Pull every ``reviewed_status='pending'`` rejection for a property. The renderer surfaces these inline, beneath the active fact at the - same ``(section, field)`` coordinate, as ⚠ conflict markers — so an + same ``(section, field)`` coordinate, as ⚠ conflict markers, so an operator reading the file sees both the accepted fact and the proposal the validator rejected, with a one-click review link. """ @@ -866,21 +851,19 @@ def _format_conflict_line(rej: RejectionRow, *, lang: str) -> str: if rej.occurred_at is not None: occurred = rej.occurred_at if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) + occurred = occurred.replace(tzinfo=UTC) when = f" ({occurred.strftime('%Y-%m-%d')})" label = "Konflikt" if lang == "de" else "Conflict" review = "Überprüfen" if lang == "de" else "Review" preview = _truncate(rej.proposed_value, limit=80) return ( - f" - ⚠ **{label}:** {preview}{when} — flagged by " + f" - ⚠ **{label}:** {preview}{when}, flagged by " f"`{rej.constraint_name}`. " f"[{review} →](/admin/rejected/{rej.id})" ) -def _format_open_conflicts_block( - unmatched: list[RejectionRow], *, lang: str -) -> list[str]: +def _format_open_conflicts_block(unmatched: list[RejectionRow], *, lang: str) -> list[str]: """Standalone block listing rejections that don't pair to a current fact. These are typically validator-rejected proposals at scopes that @@ -891,11 +874,7 @@ def _format_open_conflicts_block( """ if not unmatched: return [] - title = ( - "Offene Konflikte zur Überprüfung" - if lang == "de" - else "Open conflicts pending review" - ) + title = "Offene Konflikte zur Überprüfung" if lang == "de" else "Open conflicts pending review" review = "Überprüfen" if lang == "de" else "Review" out: list[str] = [f"## {title}", ""] for rej in unmatched: @@ -903,16 +882,14 @@ def _format_open_conflicts_block( if rej.occurred_at is not None: occurred = rej.occurred_at if occurred.tzinfo is None: - occurred = occurred.replace(tzinfo=timezone.utc) + occurred = occurred.replace(tzinfo=UTC) when = f" ({occurred.strftime('%Y-%m-%d')})" preview = _truncate(rej.proposed_value, limit=100) section_label = _format_field(rej.section) field_label = _format_field(rej.field) if rej.field else "" - coord = ( - f"{section_label} · {field_label}" if field_label else section_label - ) + coord = f"{section_label} · {field_label}" if field_label else section_label out.append( - f"- ⚠ **{coord}:** {preview}{when} — flagged by " + f"- ⚠ **{coord}:** {preview}{when}, flagged by " f"`{rej.constraint_name}`. " f"[{review} →](/admin/rejected/{rej.id})" ) @@ -930,12 +907,13 @@ def _emit_sections( ) -> dict[str, dict[str, int]]: """Append one ``## Section`` block per non-empty section to ``lines``. - Three-tier render (Phase 12+): - * **Active** (≤ 90 d): full bullet — value verbatim, confidence inline, - full source link, optional 🌐 web badge. - * **Recent** (90 d–1 y): tight one-liner — ``YYYY-MM · field: preview… [open detail]``. - * **Archive** (> 1 y): collapses to a per-year roll-up - (``2024 — 12 entries; last: …``) under an ``### Archive`` heading. + Three-tier render: + * **Active** (≤ 90 d): full bullet with the value verbatim, confidence + inline, full source link, optional 🌐 web badge. + * **Recent** (90 d–1 y): tight one-liner with month, field, preview + and an ``[open detail]`` link. + * **Archive** (> 1 y): collapses to a per-year roll-up (entry count + and latest entry) under an ``### Archive`` heading. When a pending ``rejected_updates`` row exists at the same ``(section, field)`` coordinate as an active fact, an indented @@ -950,11 +928,11 @@ def _emit_sections( needs_review_label = labels["needs_review"] archive_label = "Archiv" if lang == "de" else "Archive" archive_subtitle = ( - "Ältere Einträge gruppiert nach Jahr — anklicken öffnet das Original" + "Ältere Einträge gruppiert nach Jahr: anklicken öffnet das Original" if lang == "de" - else "Older entries grouped by year — click any line to open the original" + else "Older entries grouped by year: click any line to open the original" ) - now = datetime.now(timezone.utc) + now = datetime.now(UTC) def _title(section: str) -> str: label = titles.get(section) @@ -998,13 +976,11 @@ def _render(section: str) -> None: # with 1000 events processed today doesn't blow up the file. # Active rows are sorted newest-first; rows beyond the limit # fold straight into the archive tier where they collapse to - # one per-year roll-up bullet (``2026 — 135 entries``) instead + # one per-year roll-up bullet (2026, 135 entries) instead # of 135 separate lines. if section in _CAPPED_SECTIONS and len(active_rows) > ACTIVITY_ACTIVE_LIMIT: active_rows.sort( - key=lambda f: ( - f.occurred_at or datetime.min.replace(tzinfo=timezone.utc) - ), + key=lambda f: f.occurred_at or datetime.min.replace(tzinfo=UTC), reverse=True, ) overflow = active_rows[ACTIVITY_ACTIVE_LIMIT:] @@ -1012,9 +988,7 @@ def _render(section: str) -> None: archive_rows = overflow + archive_rows recent_rows.sort( - key=lambda f: ( - f.occurred_at or datetime.min.replace(tzinfo=timezone.utc) - ), + key=lambda f: f.occurred_at or datetime.min.replace(tzinfo=UTC), reverse=True, ) @@ -1086,9 +1060,9 @@ def _format_frontmatter( ) -> list[str]: """Emit the YAML frontmatter block at the top of every property file. - Stays *deterministic* — same fact set + same coverage answers, same + Stays *deterministic*: same fact set + same coverage answers, same frontmatter. Trigger metadata (``trigger_event_id`` / ``trigger_summary``) - is intentionally **not** in the frontmatter — it lives on the + is intentionally **not** in the frontmatter; it lives on the ``property_files`` row's columns instead. Mixing them in here would make the markdown body churn on every fact write even when content didn't change. @@ -1106,7 +1080,7 @@ def _format_frontmatter( f"property_id: {property_id}", f"name: {name}", f"address: {address}", - f"tier: property", + "tier: property", f"language: {lang}", f"as_of: {rendered_at.strftime('%Y-%m-%dT%H:%M:%SZ')}", f"fact_count: {len(facts)}", @@ -1133,25 +1107,23 @@ def _format_frontmatter( @dataclass(frozen=True) class RenderResult: - """Returned by :func:`render_property_full` — markdown + structured index.""" + """Returned by :func:`render_property_full`: markdown + structured index.""" markdown: str content_index: dict[str, object] -async def render_property_full( - session: AsyncSession, property_id: UUID -) -> RenderResult: +async def render_property_full(session: AsyncSession, property_id: UUID) -> RenderResult: """Render the living markdown + structured ``content_index`` together. - Three new responsibilities (Phase 12+): - 1. **YAML frontmatter** at the top — stable, agent-readable. + On top of the plain markdown render this adds: + 1. **YAML frontmatter** at the top: stable, agent-readable. 2. **Three-tier bucketing** in section emit (active / recent / archive). 3. **⚠ Conflict markers** beneath active facts when a pending rejected proposal exists at the same coordinate. - 4. **## Coverage** scorecard — what's known, what's missing. + 4. **## Coverage** scorecard: what's known, what's missing. """ - from backend.pipeline.coverage import ( # noqa: PLC0415 — local import + from backend.pipeline.coverage import ( # noqa: PLC0415 (local import) compute_coverage, coverage_to_index, render_coverage_block, @@ -1172,11 +1144,9 @@ async def render_property_full( liegenschaft_id: UUID | None = None liegenschaft_name: str | None = None if building_id is not None: - liegenschaft_id, liegenschaft_name = await _liegenschaft_for_building( - session, building_id - ) + liegenschaft_id, liegenschaft_name = await _liegenschaft_for_building(session, building_id) - rendered_at = datetime.now(timezone.utc) + rendered_at = datetime.now(UTC) coverage = compute_coverage(stammdaten, facts, lang=lang) log.debug( @@ -1204,29 +1174,20 @@ async def render_property_full( # this, building/liegenschaft-scope rejections attached to the # property would never surface in the property's markdown. fact_keys = {(f.section, f.field) for f in facts} - unmatched_rejections = [ - r for r in rejections if (r.section, r.field) not in fact_keys - ] + unmatched_rejections = [r for r in rejections if (r.section, r.field) not in fact_keys] body_lines.extend(_format_open_conflicts_block(unmatched_rejections, lang=lang)) body_lines.extend(render_coverage_block(coverage, lang=lang)) # Building Context if building_id is not None: - events = await _recent_events_for_scope( - session, scope="building", scope_id=building_id - ) + events = await _recent_events_for_scope(session, scope="building", scope_id=building_id) if events: body_lines.append(f"## {labels['building_context']}") body_lines.append("") - body_lines.append( - f"_{labels['building_subtitle']} — " - f"{building_address or building_id}_" - ) + body_lines.append(f"_{labels['building_subtitle']}: {building_address or building_id}_") body_lines.append("") body_lines.extend(_format_context_event(ev) for ev in events) - body_lines.append( - f"\n[{labels['open_building']}](/buildings/{building_id}/markdown)\n" - ) + body_lines.append(f"\n[{labels['open_building']}](/buildings/{building_id}/markdown)\n") # WEG Context if liegenschaft_id is not None: @@ -1236,15 +1197,11 @@ async def render_property_full( if events: body_lines.append(f"## {labels['weg_context']}") body_lines.append("") - body_lines.append( - f"_{labels['weg_subtitle']} — " - f"{liegenschaft_name or liegenschaft_id}_" - ) + body_lines.append(f"_{labels['weg_subtitle']}: {liegenschaft_name or liegenschaft_id}_") body_lines.append("") body_lines.extend(_format_context_event(ev) for ev in events) body_lines.append( - f"\n[{labels['open_weg']}](/liegenschaften/" - f"{liegenschaft_id}/markdown)\n" + f"\n[{labels['open_weg']}](/liegenschaften/{liegenschaft_id}/markdown)\n" ) frontmatter = _format_frontmatter( @@ -1304,11 +1261,11 @@ async def render_property_full( async def render_markdown(session: AsyncSession, property_id: UUID) -> str: - """Backward-compat wrapper — returns just the markdown body. + """Backward-compat wrapper that returns just the markdown body. Existing callers (``GET /properties/{id}/markdown`` fallback, ``test_pipeline_happy_path``) keep their string contract; the - Phase 12 materializer should use :func:`render_property_full` + materializer should use :func:`render_property_full` so it can populate the ``content_index`` JSONB column too. Raises: @@ -1317,9 +1274,7 @@ async def render_markdown(session: AsyncSession, property_id: UUID) -> str: return (await render_property_full(session, property_id)).markdown -async def render_building_markdown( - session: AsyncSession, building_id: UUID -) -> str: +async def render_building_markdown(session: AsyncSession, building_id: UUID) -> str: """Render the living markdown for a building (Haus).""" row = ( await session.execute( @@ -1337,9 +1292,7 @@ async def render_building_markdown( if row is None: raise ValueError(f"Building {building_id} not found") - facts = await _fetch_facts_by_scope( - session, scope="building", scope_id=building_id - ) + facts = await _fetch_facts_by_scope(session, scope="building", scope_id=building_id) lines: list[str] = [ f"# Building {row.address}", "", @@ -1355,22 +1308,14 @@ async def render_building_markdown( if events: lines.append("## WEG Context") lines.append("") - lines.append( - f"_Recent activity at the WEG — " - f"{row.lname or row.liegenschaft_id}_" - ) + lines.append(f"_Recent activity at the WEG: {row.lname or row.liegenschaft_id}_") lines.append("") lines.extend(_format_context_event(ev) for ev in events) - lines.append( - f"\n[Open WEG view](/liegenschaften/" - f"{row.liegenschaft_id}/markdown)\n" - ) + lines.append(f"\n[Open WEG view](/liegenschaften/{row.liegenschaft_id}/markdown)\n") return "\n".join(lines).rstrip() + "\n" -async def render_liegenschaft_markdown( - session: AsyncSession, liegenschaft_id: UUID -) -> str: +async def render_liegenschaft_markdown(session: AsyncSession, liegenschaft_id: UUID) -> str: """Render the living markdown for a Liegenschaft (WEG).""" row = ( await session.execute( @@ -1381,11 +1326,9 @@ async def render_liegenschaft_markdown( if row is None: raise ValueError(f"Liegenschaft {liegenschaft_id} not found") - facts = await _fetch_facts_by_scope( - session, scope="liegenschaft", scope_id=liegenschaft_id - ) + facts = await _fetch_facts_by_scope(session, scope="liegenschaft", scope_id=liegenschaft_id) lines: list[str] = [ - f"# WEG — {row.name}", + f"# WEG: {row.name}", "", f"_Liegenschaft UUID {liegenschaft_id}_", "", diff --git a/backend/pipeline/router.py b/backend/pipeline/router.py index 28b4a0e..7002ad5 100644 --- a/backend/pipeline/router.py +++ b/backend/pipeline/router.py @@ -18,7 +18,7 @@ occupied property. 3. ``metadata.invoice_ref`` → events with ``source='invoice'`` whose filename contains that INV-NNN → that event's resolved property. - (Sequencing matters — invoices need to be loaded before bank rows + (Sequencing matters: invoices need to be loaded before bank rows for this path to be useful; until then it's a documented miss.) Unmatched events stay with ``property_id IS NULL`` and surface in the @@ -40,8 +40,17 @@ _TOKEN_RE = re.compile(r"[A-Za-zÄÖÜäöüß0-9]{2,}") _STOPWORDS = { - "apt", "apartment", "the", "and", "for", "with", "from", "this", - "that", "strasse", "str", + "apt", + "apartment", + "the", + "and", + "for", + "with", + "from", + "this", + "that", + "strasse", + "str", } @@ -64,9 +73,7 @@ async def _load_routing_corpus( session: AsyncSession, ) -> list[tuple[UUID, str, list[str]]]: """Return ``(property_id, name, aliases_including_name)`` for all properties.""" - result = await session.execute( - text("SELECT id, name, aliases FROM properties") - ) + result = await session.execute(text("SELECT id, name, aliases FROM properties")) corpus: list[tuple[UUID, str, list[str]]] = [] for row in result.all(): aliases = list(row.aliases or []) @@ -82,13 +89,13 @@ async def route( *, min_score: float = 0.3, ) -> PropertyRoute | None: - """Property-only text router — alias substring + token-overlap fallback. + """Property-only text router: alias substring + token-overlap fallback. Returns ``None`` when nothing matches; callers then escalate to :func:`route_text_event` to apply the WEG keyword heuristics. - Kept as a focused primitive so existing tests + Phase 1 worker - paths continue to work bit-identically. + Kept as a focused primitive so existing tests + the worker's + property-only path continue to work bit-identically. """ haystack = raw_content.lower() corpus = await _load_routing_corpus(session) @@ -173,9 +180,9 @@ async def route_text_event( This is intentionally before the property attempt: a Mahnung from an insurer or a Bauamt Brandschutz request should land at the WEG even though the body mentions the building's - ``Immanuelkirchstraße 26`` address (which the property + ``Musterstraße 26`` address (which the property token-overlap fallback would otherwise greedily claim). - 2. :func:`route` — alias substring + token-overlap → property. + 2. :func:`route`: alias substring + token-overlap → property. 3. ``HAUS-NN`` mention in the body → building. 4. WEG keyword (with a unit ref present, or after #2 missed) → Liegenschaft as a last-resort fallback. @@ -230,7 +237,7 @@ async def route_text_event( ) # 4. WEG-keyword last-resort (a unit ref was present but the - # property router still missed — degenerate case; we'd rather + # property router still missed; degenerate case, we'd rather # route to WEG than leave it stranded) if keyword_match: liegenschaft_id = await _default_liegenschaft(session) @@ -263,8 +270,8 @@ async def route_text_event( # ----------------------------------------------------------------------------- -# Phase 8.1 — keyword set for liegenschaft (WEG) routing. The list is -# drawn from real Buena verwendungszweck strings + email subjects/bodies; +# Keyword set for liegenschaft (WEG) routing. The list is drawn from +# real verwendungszweck strings + email subjects/bodies in the sample dataset; # matching is case-insensitive with word boundaries because the dataset # mixes ``Hausgeld / HAUSGELD / hausgeld`` freely. WEG_KEYWORDS: tuple[str, ...] = ( @@ -281,7 +288,7 @@ async def route_text_event( # Accounting / banking "kontofuehrungsgebuehr", "kontoführungsgebühr", - # External parties typically billing the WEG (Step 4 baseline added) + # External parties typically billing the WEG "mahnung", "rechnung", "jahresabrechnung", @@ -296,15 +303,13 @@ async def route_text_event( "brandschutz", "brandschutznachweis", ) -WEG_KATEGORIE: frozenset[str] = frozenset( - {"hausgeld", "dienstleister", "versorger", "sonstige"} -) +WEG_KATEGORIE: frozenset[str] = frozenset({"hausgeld", "dienstleister", "versorger", "sonstige"}) _WEG_KEYWORD_RE = re.compile( r"\b(?:" + "|".join(re.escape(k) for k in WEG_KEYWORDS) + r")\b", re.IGNORECASE, ) _HAUS_RE = re.compile(r"\bHAUS-\d+\b", re.IGNORECASE) -# Per-unit reference markers — used by route_text_event to decide when a +# Per-unit reference markers, used by route_text_event to decide when a # WEG keyword genuinely indicates WEG attribution vs. a per-unit note # that happens to mention "Mahnung" or "Rechnung" alongside an EH-/WE-/GE-. _UNIT_REF_RE = re.compile( @@ -326,23 +331,20 @@ class StructuredRoute: building_id: UUID | None = None liegenschaft_id: UUID | None = None method: str = "unrouted" # 'eh_alias' | 'mie_to_eh' | 'invoice_ref' - # | 'haus_alias' | 'weg_keyword' - # | 'weg_kategorie' | 'inherit_from_invoice' - # | 'unrouted' + # | 'haus_alias' | 'weg_keyword' + # | 'weg_kategorie' | 'inherit_from_invoice' + # | 'unrouted' reason: str = "" @property def is_routed(self) -> bool: """True iff at least one of the three scope IDs is set.""" return any( - x is not None - for x in (self.property_id, self.building_id, self.liegenschaft_id) + x is not None for x in (self.property_id, self.building_id, self.liegenschaft_id) ) -async def _route_by_eh_alias( - session: AsyncSession, eh_id: str -) -> UUID | None: +async def _route_by_eh_alias(session: AsyncSession, eh_id: str) -> UUID | None: """Look up a property whose ``aliases`` array contains ``eh_id``.""" row = ( await session.execute( @@ -359,9 +361,7 @@ async def _route_by_eh_alias( return UUID(str(row.id)) if row else None -async def _route_by_mie_id( - session: AsyncSession, mie_id: str -) -> UUID | None: +async def _route_by_mie_id(session: AsyncSession, mie_id: str) -> UUID | None: """``MIE-NNN`` → tenant.metadata.buena_mie_id → occupied property.""" row = ( await session.execute( @@ -385,7 +385,7 @@ async def _route_by_invoice_ref( """Inherit attribution from a prior invoice event referenced by ``invoice_ref``. Returns ``(property_id, building_id, liegenschaft_id)`` from the - invoice — at most one is set; all three None means the invoice + invoice; at most one is set; all three None means the invoice exists but lacks attribution itself. """ row = ( @@ -415,9 +415,7 @@ async def _route_by_invoice_ref( ) -async def _route_by_haus_alias( - session: AsyncSession, haus_id: str -) -> UUID | None: +async def _route_by_haus_alias(session: AsyncSession, haus_id: str) -> UUID | None: """``HAUS-NN`` → buildings table via ``metadata->>'buena_haus_id'``.""" row = ( await session.execute( @@ -438,15 +436,12 @@ async def _default_liegenschaft(session: AsyncSession) -> UUID | None: """Return the WEG when there is exactly one in the database. The liegenschaft-keyword + kategorie heuristics know an event is - WEG-level but Buena doesn't carry a per-Liegenschaft identifier in - bank rows. With only one Liegenschaft loaded the choice is - unambiguous; multi-Liegenschaft tenants will need a richer matcher. + WEG-level but the sample dataset doesn't carry a per-Liegenschaft + identifier in bank rows. With only one Liegenschaft loaded the + choice is unambiguous; multi-Liegenschaft tenants will need a + richer matcher. """ - row = ( - await session.execute( - text("SELECT id FROM liegenschaften LIMIT 2") - ) - ).all() + row = (await session.execute(text("SELECT id FROM liegenschaften LIMIT 2"))).all() if len(row) == 1: return UUID(str(row[0].id)) return None @@ -460,7 +455,7 @@ async def route_structured( ) -> StructuredRoute: """Pick the scope a structured event belongs to using metadata IDs only. - Phase 8.1 precedence — first match wins: + Precedence (first match wins): 1. ``eh_id`` → property (unit) 2. ``mie_id`` → tenant → property @@ -471,9 +466,9 @@ async def route_structured( - ``verwendungszweck`` (or any text field on the event) matches a WEG keyword (case-insensitive, word-boundary), or - ``event_source == 'invoice'`` *and* a single Liegenschaft exists - (Buena invariant: every invoice in the archive is a WEG bill — - filenames carry contractor + invoice number but no per-unit - attribution) + (invariant of the sample dataset: every invoice in the archive + is a WEG bill; filenames carry contractor + invoice number + but no per-unit attribution) Reasons surfaced in ``StructuredRoute.reason`` are kept short + stable so the ``GET /admin/unrouted`` diagnostic is skim-friendly. @@ -485,8 +480,7 @@ async def route_structured( kategorie = (metadata.get("kategorie") or "").lower().strip() verwendungszweck = str(metadata.get("verwendungszweck") or "") raw_text = " ".join( - str(metadata.get(k) or "") - for k in ("verwendungszweck", "filename", "subject", "from") + str(metadata.get(k) or "") for k in ("verwendungszweck", "filename", "subject", "from") ) # 1. Property (unit) @@ -536,7 +530,7 @@ async def route_structured( reason=f"matched {haus_id}", ) - # 5. Liegenschaft (WEG) — kategorie / keyword / source heuristics + # 5. Liegenschaft (WEG): kategorie / keyword / source heuristics is_weg_kategorie = kategorie in WEG_KATEGORIE and kategorie != "hausgeld" # `hausgeld` as a kategorie is per-unit (verwendungszweck has EH-NNN); # it only collapses to WEG when EH-/MIE-/HAUS- all missed above and @@ -567,12 +561,10 @@ async def route_structured( reason="invoice without per-unit attribution", ) - # Unrouted — produce a precise diagnostic + # Unrouted: produce a precise diagnostic if not any((eh_id, mie_id, invoice_ref, haus_id, kategorie)): reason = "no EH-/MIE-/INV-/HAUS-/kategorie in metadata" else: seen = ", ".join(s for s in (eh_id, mie_id, invoice_ref, haus_id) if s) - reason = ( - f"refs {seen or '(none)'} kat={kategorie or '(none)'} unresolved" - ) + reason = f"refs {seen or '(none)'} kat={kategorie or '(none)'} unresolved" return StructuredRoute(method="unrouted", reason=reason) diff --git a/backend/pipeline/semantic_validator.py b/backend/pipeline/semantic_validator.py index 0659b48..192809f 100644 --- a/backend/pipeline/semantic_validator.py +++ b/backend/pipeline/semantic_validator.py @@ -1,23 +1,23 @@ -"""Phase 11 — semantic event validator. +"""Semantic event validator. The rule-based validator (:mod:`backend.pipeline.validator`) catches known immutable-field contradictions (floor count, address, year built, …) using hand-coded constraints. The semantic validator -complements it: it asks Pioneer/Claude to read the **canonical -property file** and the **new event** side-by-side and surface every -claim that contradicts what we already know — not just the dozen -fields someone hardcoded. +complements it: it asks the configured LLM provider to read the +**canonical property file** and the **new event** side by side and +surface every claim that contradicts what we already know, not just +the dozen fields someone hardcoded. Why both layers exist: - Rule-based constraints are **deterministic**: same input, same - verdict, no Pioneer cost. They guard the high-stakes immutable + verdict, no LLM cost. They guard the high-stakes immutable fields with explicit reasons and required-source-type metadata. - The semantic validator is **general**: it covers fields nobody thought to write a constraint for ("event mentions a 7th floor in a 4-floor building", "event names a different tenant than stammdaten", "event claims rent of €5000 when the lease says €1100"). It costs - one Pioneer call per event, runs after extraction, and emits the + one LLM call per event, runs after extraction, and emits the same :class:`Rejection` shape so the existing rejected_updates inbox surfaces both kinds uniformly. @@ -27,24 +27,20 @@ from __future__ import annotations -import json -import time from dataclasses import dataclass from typing import Any -import httpx import structlog -from backend.config import get_settings from backend.pipeline.validator import Rejection -from backend.services import pioneer_llm +from backend.services.llm import require_provider log = structlog.get_logger(__name__) SYSTEM_HINT = ( "You audit a new property-management event against the property's " - "canonical record. You only surface CONTRADICTIONS — facts in the " + "canonical record. You only surface CONTRADICTIONS: facts in the " "event that disagree with what's already on file. Novel information " "(new maintenance issues, new payments, new requests) is fine and " "must NOT be flagged. Respond with a single JSON object that " @@ -56,7 +52,7 @@ record for a property. Your output decides whether each claim in the event is consistent with what's already on file. -PROPERTY FILE (canonical, condensed record — Stammdaten at top, then +PROPERTY FILE (canonical, condensed record: Stammdaten at top, then sectioned facts with confidence and source links): \"\"\" {property_file} @@ -82,14 +78,14 @@ "Anna Schmidt" • event claims rent €5000 when stammdaten says kaltmiete €1100 • event refers to address "Hauptstraße 12" when the property file - shows "Immanuelkirchstraße 26" + shows "Musterstraße 26" - "Novel" information (new maintenance issue, new bank payment, new email request) is NOT a contradiction. Do not flag novel claims. - "Stammdaten" entries (master record at top of the file) are - authoritative — only an authoritative document can revise them. + authoritative: only an authoritative document can revise them. Free-text events that contradict stammdaten are HARD rejections. - A current fact with confidence ≥ 0.9 is also strong; contradictions - there are HARD rejections. Lower-confidence facts are SOFT — flag + there are HARD rejections. Lower-confidence facts are SOFT: flag them as needs_review. SEVERITY @@ -100,7 +96,7 @@ document_type that *could* legitimately revise the record (e.g. structural_permit for floor count). These need a human review. -Always be conservative. If a claim is ambiguous, don't flag it — +Always be conservative. If a claim is ambiguous, don't flag it; returning "all_consistent" is the default. JSON SCHEMA @@ -111,7 +107,8 @@ {{ "claim": "", "conflict_with": "", - "section": "", + "section": "", "field": "", "severity": "hard" | "soft", "reason": "" @@ -137,7 +134,7 @@ def has_contradictions(self) -> bool: def _format_proposed_block(facts: list[dict[str, Any]]) -> str: """Bullet-list extracted proposals so the LLM can also rule on them.""" if not facts: - return " (no proposed facts — the extractor only saw novel/maintenance content)" + return " (no proposed facts: the extractor only saw novel/maintenance content)" lines: list[str] = [] for f in facts[:20]: lines.append( @@ -158,7 +155,7 @@ def _to_rejection(item: dict[str, Any]) -> Rejection | None: severity = str(item.get("severity") or "soft").strip().lower() if not claim or not reason: - # Be defensive — skip malformed rows the model emitted. + # Be defensive: skip malformed rows the model emitted. return None rendered_value = claim if not conflict else f"{claim} (file says: {conflict})" @@ -166,7 +163,7 @@ def _to_rejection(item: dict[str, Any]) -> Rejection | None: section=section, field=field, proposed_value=rendered_value[:1000], - proposed_confidence=0.0, # synthetic — surfaced by the auditor, not the extractor + proposed_confidence=0.0, # synthetic, surfaced by the auditor, not the extractor constraint_name="semantic_consistency", reason=reason[:500], required_source_type=None, @@ -181,22 +178,19 @@ async def semantic_validate( event_source: str, proposed_facts: list[dict[str, Any]], timeout_s: float = 30.0, - model_name: str | None = None, ) -> SemanticVerdict: """Audit one event against the canonical property file. - Returns a verdict whose ``rejections`` tuple is ready to merge into - the worker's existing rule-based rejection list. Empty tuple ⇒ - nothing contradicts. + Returns a verdict whose ``rejections`` tuple is ready to merge into the + worker's rule-based rejection list; an empty tuple means nothing + contradicts. - Raises :class:`pioneer_llm.PioneerUnavailable` when Pioneer can't - be reached. Callers should treat that as "skip semantic validation - for this event" rather than failing the whole pipeline — the - rule-based constraints still run and are still authoritative. + Raises :class:`LLMNotConfiguredError` when no provider is configured and + :class:`LLMUnavailableError` when the call fails. Callers treat both as + "skip semantic validation for this event": the rule-based constraints + still run and remain authoritative. """ - settings = get_settings() - if not pioneer_llm.is_available(): - raise pioneer_llm.PioneerUnavailable("PIONEER_API_KEY not set") + provider = require_provider() prompt = PROMPT_TEMPLATE.format( property_file=property_file_markdown.strip() or "(empty property file)", @@ -205,57 +199,24 @@ async def semantic_validate( proposed_block=_format_proposed_block(proposed_facts), ) - model = model_name or pioneer_llm.PIONEER_DEFAULT_MODEL - headers = { - "Authorization": f"Bearer {settings.pioneer_api_key}", - "Content-Type": "application/json", - } - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": SYSTEM_HINT}, - {"role": "user", "content": prompt}, - ], - "temperature": 0.0, - "response_format": {"type": "json_object"}, - } - log.info( "semantic_validator.start", - model=model, + provider=provider.name, + model=provider.model, prompt_chars=len(prompt), proposed_count=len(proposed_facts), event_source=event_source, ) - start = time.perf_counter() - try: - async with httpx.AsyncClient(timeout=timeout_s) as client: - response = await client.post( - f"{pioneer_llm.PIONEER_BASE_URL}/chat/completions", - headers=headers, - json=body, - ) - response.raise_for_status() - payload = response.json() - text = payload["choices"][0]["message"].get("content") or "" - data = pioneer_llm._parse_json_payload(text) - except httpx.HTTPError as exc: - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "semantic_validator.error", - model=model, - latency_ms=round(latency_ms, 1), - error=str(exc)[:200], - ) - raise pioneer_llm.PioneerUnavailable( - f"semantic_validate failed: {exc!r}" - ) from exc - - latency_ms = (time.perf_counter() - start) * 1000 + completion = await provider.complete_json( + system=SYSTEM_HINT, prompt=prompt, temperature=0.0, timeout_s=timeout_s + ) + data = completion.data + latency_ms = completion.latency_ms + model = completion.model verdict_raw = str(data.get("verdict") or "").strip() if verdict_raw not in {"all_consistent", "has_contradictions"}: - # Tolerate model mistakes — treat as consistent rather than + # Tolerate model mistakes: treat as consistent rather than # auto-rejecting everything. verdict_raw = "all_consistent" diff --git a/backend/pipeline/structured_extractors.py b/backend/pipeline/structured_extractors.py index 7ccddaf..905eee5 100644 --- a/backend/pipeline/structured_extractors.py +++ b/backend/pipeline/structured_extractors.py @@ -67,34 +67,23 @@ async def _write_or_supersede_fact( """Write a fact unless an identical scope+(section, field, value) is current. Exactly one of ``property_id`` / ``building_id`` / ``liegenschaft_id`` - must be set — the scope is the natural key for the + must be set; the scope is the natural key for the ``superseded_by IS NULL`` lookup. Re-writes with identical values short-circuit; differing values stamp ``superseded_by`` on the predecessor. """ if sum(x is not None for x in (property_id, building_id, liegenschaft_id)) != 1: - raise ValueError( - "exactly one of property_id / building_id / liegenschaft_id required" - ) + raise ValueError("exactly one of property_id / building_id / liegenschaft_id required") if property_id is not None: - scope_clause = ( - "property_id = :scope_id " - "AND building_id IS NULL AND liegenschaft_id IS NULL" - ) + scope_clause = "property_id = :scope_id AND building_id IS NULL AND liegenschaft_id IS NULL" scope_id = property_id elif building_id is not None: - scope_clause = ( - "building_id = :scope_id " - "AND property_id IS NULL AND liegenschaft_id IS NULL" - ) + scope_clause = "building_id = :scope_id AND property_id IS NULL AND liegenschaft_id IS NULL" scope_id = building_id else: assert liegenschaft_id is not None - scope_clause = ( - "liegenschaft_id = :scope_id " - "AND property_id IS NULL AND building_id IS NULL" - ) + scope_clause = "liegenschaft_id = :scope_id AND property_id IS NULL AND building_id IS NULL" scope_id = liegenschaft_id current = ( @@ -151,7 +140,7 @@ async def _write_or_supersede_fact( {"new_id": new_id, "old_id": current.id}, ) - # Phase 12 — propagate to the materialized files. Bank/invoice are + # Propagate to the materialized files. Bank/invoice are # the only paths that write building- or liegenschaft-scoped facts, # so the cascade rule lives here too. Same session = same # transaction = atomic with the fact write. @@ -177,7 +166,7 @@ async def extract_bank_facts( ) -> int: """Write deterministic facts for one bank event. Returns count written. - Phase 8.1: scope is whichever of ``property_id`` / ``building_id`` / + Scope is whichever of ``property_id`` / ``building_id`` / ``liegenschaft_id`` is set. No-op when all three are None (the event is genuinely unrouted). @@ -190,11 +179,7 @@ async def extract_bank_facts( typ = (metadata.get("typ") or "").upper() amount = metadata.get("betrag") valuta = metadata.get("valuta") - formatted = ( - f"{_format_amount(amount)} on {valuta}" - if valuta - else _format_amount(amount) - ) + formatted = f"{_format_amount(amount)} on {valuta}" if valuta else _format_amount(amount) if property_id is not None: section = "financials" @@ -243,10 +228,7 @@ async def extract_bank_facts( **scope_kwargs, section=section, field=f"last_{kategorie}_{verb}", - value=( - f"{formatted} ({verb}, kategorie={kategorie}, " - f"source=bank)" - ), + value=(f"{formatted} ({verb}, kategorie={kategorie}, source=bank)"), confidence=0.95, source_event_id=event_id, ) @@ -259,9 +241,7 @@ async def extract_bank_facts( # ----------------------------------------------------------------------------- -async def _resolve_contractor_id( - session: AsyncSession, dl_id: str | None -) -> UUID | None: +async def _resolve_contractor_id(session: AsyncSession, dl_id: str | None) -> UUID | None: """Look up a Buena DL-XXX in the contractors table via ``contact->>'buena_dl_id'``.""" if not dl_id: return None @@ -325,16 +305,14 @@ async def extract_invoice_facts( ) -> int: """Write deterministic facts for one invoice event. - Phase 8.1: an invoice routes at one of three tiers; the section name + An invoice routes at one of three tiers; the section name follows the scope. """ dl_id = metadata.get("dl_id") or _dl_id_from_filename(metadata.get("filename")) contractor_id = await _resolve_contractor_id(session, dl_id) if contractor_id is not None and property_id is not None: - await _ensure_serviced_by( - session, property_id=property_id, contractor_id=contractor_id - ) + await _ensure_serviced_by(session, property_id=property_id, contractor_id=contractor_id) if property_id is not None: section = "maintenance" @@ -356,10 +334,7 @@ async def extract_invoice_facts( **scope_kwargs, section=section, field="last_contractor_invoice", - value=( - f"{doctype} from contractor " - f"{dl_id or '(unknown)'} — {filename}" - ), + value=(f"{doctype} from contractor {dl_id or '(unknown)'} ({filename})"), confidence=0.9, source_event_id=event_id, ) @@ -371,7 +346,8 @@ def _dl_id_from_filename(filename: str | None) -> str | None: """Pull a ``DL-NNN`` token out of a Buena invoice filename.""" if not filename: return None - import re # noqa: PLC0415 — local import keeps regex hot path cheap + import re # noqa: PLC0415 (local import keeps regex hot path cheap) + match = re.search(r"\b(DL-\d{3,})\b", filename) return match.group(1) if match else None diff --git a/backend/pipeline/validator.py b/backend/pipeline/validator.py index acb9f6d..12338a7 100644 --- a/backend/pipeline/validator.py +++ b/backend/pipeline/validator.py @@ -1,9 +1,9 @@ -"""Phase 9 Step 9.2 — constraint validator. +"""Rule-based constraint validator. Sits between :mod:`backend.pipeline.differ` and :mod:`backend.pipeline.applier`. The differ already filtered proposals on source-precedence / confidence / recency; the validator adds *semantic* gates that are -hard to express as numbers — "the building's floor count is +hard to express as numbers: "the building's floor count is immutable", "a rent change requires a lease addendum PDF", "a compliance fact must come from an authoritative source". @@ -65,9 +65,7 @@ def rejected(cls, reason: str, required_source_type: str | None = None) -> Valid ) @classmethod - def needs_review( - cls, reason: str, required_source_type: str | None = None - ) -> ValidationResult: + def needs_review(cls, reason: str, required_source_type: str | None = None) -> ValidationResult: return cls( status="needs_review", reason=reason, @@ -82,9 +80,14 @@ class Constraint(Protocol): guards. ``field=None`` means *every field in this section*. """ - name: str - section: str - field: str | None + @property + def name(self) -> str: ... + + @property + def section(self) -> str: ... + + @property + def field(self) -> str | None: ... def check( self, @@ -162,7 +165,7 @@ def constraints_for(section: str, field: str) -> list[Constraint]: def clear_registry() -> None: - """Test helper — empty the registry between tests.""" + """Test helper: empty the registry between tests.""" REGISTRY.clear() @@ -182,7 +185,7 @@ def validate( Args: plan: The :class:`DiffPlan` from the differ. event: Event-level context. Must include ``source`` (str) and - ``metadata`` (dict) — constraints read + ``metadata`` (dict); constraints read ``metadata.document_type``. current_facts: Map of ``(section, field) → current fact dict``, shaped like the output of @@ -218,9 +221,7 @@ def validate( field=decision.field, proposed_value=decision.value, proposed_confidence=decision.confidence, - constraint_name=( - verdict_constraint.name if verdict_constraint else "unknown" - ), + constraint_name=(verdict_constraint.name if verdict_constraint else "unknown"), reason=verdict.reason, required_source_type=verdict.required_source_type, needs_review=verdict.status == "needs_review", @@ -336,7 +337,7 @@ def event_stammdaten(event: dict[str, Any], scope: str) -> dict[str, Any]: attaches them to the event dict before calling :func:`validate` so constraints can compare proposed values against the master record without each one re-running its own SQL. Returns ``{}`` when nothing - was loaded — constraints must treat that as "no ground truth, fall + was loaded; constraints must treat that as "no ground truth, fall through to default behaviour". """ snap = event.get("stammdaten") or {} @@ -362,7 +363,7 @@ def values_differ(proposed: object, stammdaten_value: object) -> bool: Used by every immutable-field constraint when checking strict mode (``current is None``). Comparisons normalise whitespace, casing, and - trivial numeric formatting differences — anything else counts as a + trivial numeric formatting differences; anything else counts as a real contradiction worth rejecting. """ if stammdaten_value in (None, ""): diff --git a/backend/pipeline/worker.py b/backend/pipeline/worker.py index 9c831fe..a3debad 100644 --- a/backend/pipeline/worker.py +++ b/backend/pipeline/worker.py @@ -1,21 +1,21 @@ -"""Async event worker — the critical path. +"""Async event worker: the critical path. -One tick of :func:`process_one` does: - -1. ``SELECT ... FOR UPDATE SKIP LOCKED`` the oldest unprocessed event. -2. If the event lacks a ``property_id``, run the router. -3. Build a short context excerpt, call the extractor. -4. Run the differ + applier. -5. Stamp ``processed_at``, commit, publish an SSE notification. +One tick of :func:`process_one` claims the oldest unprocessed event with +``SELECT ... FOR UPDATE SKIP LOCKED`` and runs it through +:func:`_process_event_body`: route (if the event has no property), extract, +diff against current facts, rule validation, semantic check, store review +items, apply, add the activity entry, stamp ``processed_at`` and commit, then +publish an SSE notification. Each step is its own function below. The scheduler calls :func:`process_batch` on a tight loop. Postgres is the -queue (Part III: no Redis, no Kafka) — SKIP LOCKED keeps concurrent workers -safe if we ever scale horizontally. +queue; there is no separate broker such as Redis or Kafka. SKIP LOCKED keeps +concurrent workers safe if we ever scale horizontally. """ from __future__ import annotations import time +from collections.abc import Sequence from typing import Any from uuid import UUID @@ -23,10 +23,15 @@ from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession +# Importing the constraints package registers every constraint in +# the validator's REGISTRY at module load. The validator only uses +# whatever is registered; silent omission is the failure mode we'd +# never want, so this import is non-optional. +import backend.pipeline.constraints # noqa: F401 from backend.db.session import get_sessionmaker from backend.pipeline.applier import apply as apply_plan from backend.pipeline.applier import apply_uncertainties -from backend.pipeline.differ import diff, load_current_facts +from backend.pipeline.differ import DiffPlan, diff, load_current_facts from backend.pipeline.events import get_event_bus from backend.pipeline.extractor import extract from backend.pipeline.materializer import propagate_after_fact_write @@ -38,26 +43,19 @@ persist_rejections, validate, ) -from backend.services import pioneer_llm - -# Importing the constraints package registers every constraint in -# the validator's REGISTRY at module load. The validator only uses -# whatever is registered — silent omission is the failure mode we'd -# never want, so this import is non-optional. -import backend.pipeline.constraints # noqa: F401 +from backend.services.llm import ExtractionResult, LLMNotConfiguredError, LLMUnavailableError def _needs_review_to_uncertainty(rejection: Rejection) -> dict[str, Any]: """Map a validator ``needs_review`` Rejection into an uncertainty item. The constraint emitted "this proposal *might* be valid but needs a - human to confirm" — that's exactly the uncertainty inbox semantic, + human to confirm"; that's exactly the uncertainty inbox semantic, so we land it there instead of in ``rejected_updates``. """ return { "observation": ( - f"proposed {rejection.section}.{rejection.field} = " - f"{rejection.proposed_value!r}" + f"proposed {rejection.section}.{rejection.field} = {rejection.proposed_value!r}" ), "hypothesis": rejection.proposed_value, "reason_uncertain": rejection.reason, @@ -66,6 +64,7 @@ def _needs_review_to_uncertainty(rejection: Rejection) -> dict[str, Any]: "source": f"validator_needs_review:{rejection.constraint_name}", } + log = structlog.get_logger(__name__) @@ -124,7 +123,7 @@ async def _load_event_stammdaten( The validator's strict-mode constraints (floor count, address, year built, square meters) compare proposed values against this snapshot, so an email claim that contradicts master data gets - rejected even when no fact row exists yet. Empty dicts are safe — + rejected even when no fact row exists yet. Empty dicts are safe: constraints fall back to legacy "current is None → seed" behaviour when stammdaten is missing. """ @@ -157,9 +156,9 @@ async def _load_event_stammdaten( building_snap["address"] = row.building_address if row.building_year_built is not None: building_snap["year_built"] = row.building_year_built - # Buena's loader stores floor count as ``etagen`` in - # buildings.metadata; the legacy seed path uses ``floors``. Read - # both so either ingest path works. + # The sample-dataset loader (``connectors.buena_loader``) stores + # floor count as ``etagen`` in buildings.metadata; the legacy seed + # path uses ``floors``. Read both so either ingest path works. floors = b_meta.get("etagen") or b_meta.get("floors") if floors is not None: building_snap["floor_count"] = floors @@ -204,9 +203,7 @@ async def process_one(session: AsyncSession) -> UUID | None: return await _process_event_body(session, event) -async def _claim_specific( - session: AsyncSession, event_id: UUID -) -> dict[str, Any] | None: +async def _claim_specific(session: AsyncSession, event_id: UUID) -> dict[str, Any] | None: """Lock and return a specific event by id, regardless of queue position. Used by :func:`process_specific` so the debug trigger can extract a @@ -257,181 +254,47 @@ async def process_specific(event_id: UUID) -> bool: return True -async def _process_event_body( - session: AsyncSession, event: dict[str, Any] -) -> UUID: - """Shared end-to-end pipeline for a claimed event row. +async def _process_event_body(session: AsyncSession, event: dict[str, Any]) -> UUID: + """Run one claimed event through the pipeline, in a single transaction. - Extracted from :func:`process_one` so :func:`process_specific` can - reuse the same routing → extract → diff → validate → apply → - publish flow without copying it. Caller owns the session and must - have already claimed the row (``FOR UPDATE``). + Shared by :func:`process_one` and :func:`process_specific`. The caller owns + the session and has already locked the row (``FOR UPDATE``). Any exception + rolls the transaction back and records the error on the event in a fresh + session, so the lock is released and the worker moves on. """ start = time.perf_counter() event_id: UUID = event["id"] property_id: UUID | None = event["property_id"] try: + property_id = property_id or await _route(session, event) if property_id is None: - match = await route(session, event["raw_content"]) - if match is None: - log.info("worker.unrouted", event_id=str(event_id)) - await _mark_processed( - session, event_id, property_id=None, error="unrouted" - ) - await session.commit() - return event_id - property_id = match.property_id - - property_name = await _property_name(session, property_id) - excerpt = await _context_excerpt(session, property_id) - - result = await extract( - property_name=property_name, - current_context_excerpt=excerpt, - source=event["source"], - raw_content=event["raw_content"], - ) + await _mark_processed(session, event_id, property_id=None, error="unrouted") + await session.commit() + return event_id - plan = await diff( + result = await _extract(session, event, property_id) + diff_plan = await diff( session, property_id=property_id, event_source=event["source"], proposals=result.facts_to_update, ) - - current_facts = await load_current_facts(session, property_id) - stammdaten_snapshot = await _load_event_stammdaten(session, property_id) - validated_plan, rejections = validate( - plan, - event={ - "source": event["source"], - "metadata": event.get("metadata") or {}, - "stammdaten": stammdaten_snapshot, - }, - current_facts=current_facts, + plan, rejections = await _validate(session, event, property_id, diff_plan) + plan, rejections = await _semantic_check(session, event, property_id, plan, rejections) + hard_rejections, uncertainties_written = await _record_review_items( + session, event_id, property_id, result, rejections ) - - # Semantic auditor — Pioneer reads the canonical property file - # and the new event side-by-side, surfaces every claim that - # contradicts what's already on file. Catches contradictions - # the rule-based validator wasn't pre-coded for. Failures here - # never block the pipeline: if Pioneer is unreachable we keep - # the rule-based verdict and move on. - try: - property_file_md = await render_markdown(session, property_id) - semantic = await semantic_validate( - property_file_markdown=property_file_md, - event_body=event["raw_content"], - event_source=event["source"], - proposed_facts=[ - { - "section": d.section, - "field": d.field, - "value": d.value, - "confidence": d.confidence, - } - for d in validated_plan.decisions - ], - ) - if semantic.has_contradictions: - log.info( - "worker.semantic_rejections", - event_id=str(event_id), - count=len(semantic.rejections), - ) - rejections = list(rejections) + list(semantic.rejections) - # Drop validated decisions whose (section, field) the - # auditor flagged as a hard contradiction. Soft ones - # stay in the plan; the rejection ride-along is the - # human-review trail. - hard_keys = { - (r.section, r.field) - for r in semantic.rejections - if not r.needs_review - } - if hard_keys: - validated_plan = type(validated_plan)( - decisions=[ - d - for d in validated_plan.decisions - if (d.section, d.field) not in hard_keys - ], - skipped=validated_plan.skipped, - ) - except pioneer_llm.PioneerUnavailable as exc: - log.warning( - "worker.semantic_skipped", - event_id=str(event_id), - error=str(exc)[:200], - ) - - hard_rejections = [r for r in rejections if not r.needs_review] - needs_review_uncertainties = [ - _needs_review_to_uncertainty(r) for r in rejections if r.needs_review - ] - if hard_rejections: - await persist_rejections( - session, - event_id=event_id, - property_id=property_id, - building_id=None, - liegenschaft_id=None, - rejections=hard_rejections, - ) - - uncertainty_items: list[dict[str, Any]] = ( - list(result.uncertain) + needs_review_uncertainties - ) - uncertainties_written = 0 - if uncertainty_items: - uncertainties_written = await apply_uncertainties( - session, - event_id=event_id, - property_id=property_id, - items=uncertainty_items, - ) - written = await apply_plan( session, property_id=property_id, source_event_id=event_id, - plan=validated_plan, + plan=plan, trigger_summary=result.summary, ) - - if result.summary: - await session.execute( - text( - """ - INSERT INTO facts - (property_id, section, field, value, source_event_id, - confidence, valid_from) - VALUES (:pid, 'activity', :field, :value, :eid, :conf, now()) - """ - ), - { - "pid": property_id, - "field": f"event_{event_id}", - "value": result.summary, - "eid": event_id, - "conf": max(0.5, min(0.95, 0.7 + len(plan.decisions) * 0.05)), - }, - ) - # Phase 12 — re-render after the activity row lands so the - # cached markdown's "Activity" section reflects the just- - # processed event. Cheap when the applier already - # propagated for this property in the same transaction - # (renderer reads facts table, idempotent). - await propagate_after_fact_write( - session, - property_id=property_id, - trigger_event_id=event_id, - trigger_summary=result.summary, - ) - + await _record_activity(session, event_id, property_id, result, len(diff_plan.decisions)) await _mark_processed(session, event_id, property_id=property_id) await session.commit() - latency_ms = (time.perf_counter() - start) * 1000 + log.info( "worker.processed", event_id=str(event_id), @@ -439,9 +302,9 @@ async def _process_event_body( category=result.category, facts_written=written, uncertainties_written=uncertainties_written, - hard_rejections=len(hard_rejections), + hard_rejections=hard_rejections, extractor=result.source, - latency_ms=round(latency_ms, 1), + latency_ms=round((time.perf_counter() - start) * 1000, 1), ) await get_event_bus().publish( property_id, @@ -454,17 +317,185 @@ async def _process_event_body( }, ) return event_id - except Exception as exc: # noqa: BLE001 — swallow, mark event, keep worker alive + except Exception as exc: # noqa: BLE001 (swallow, mark event, keep worker alive) await session.rollback() log.exception("worker.error", event_id=str(event_id)) async with get_sessionmaker()() as fresh: - await _mark_processed( - fresh, event_id, property_id=property_id, error=str(exc)[:500] - ) + await _mark_processed(fresh, event_id, property_id=property_id, error=str(exc)[:500]) await fresh.commit() return event_id +async def _route(session: AsyncSession, event: dict[str, Any]) -> UUID | None: + """Match an event without a property to one by alias; ``None`` if nothing matches.""" + match = await route(session, event["raw_content"]) + if match is None: + log.info("worker.unrouted", event_id=str(event["id"])) + return None + return match.property_id + + +async def _extract( + session: AsyncSession, event: dict[str, Any], property_id: UUID +) -> ExtractionResult: + """Extract facts, giving the model the property's name and current file excerpt.""" + return await extract( + property_name=await _property_name(session, property_id), + current_context_excerpt=await _context_excerpt(session, property_id), + source=event["source"], + raw_content=event["raw_content"], + ) + + +async def _validate( + session: AsyncSession, event: dict[str, Any], property_id: UUID, plan: DiffPlan +) -> tuple[DiffPlan, list[Rejection]]: + """Apply the rule constraints against current facts and master data.""" + validated, rejections = validate( + plan, + event={ + "source": event["source"], + "metadata": event.get("metadata") or {}, + "stammdaten": await _load_event_stammdaten(session, property_id), + }, + current_facts=await load_current_facts(session, property_id), + ) + return validated, list(rejections) + + +async def _semantic_check( + session: AsyncSession, + event: dict[str, Any], + property_id: UUID, + plan: DiffPlan, + rejections: list[Rejection], +) -> tuple[DiffPlan, list[Rejection]]: + """Ask the LLM for contradictions between the event and the current file. + + Covers fields no rule constraint was written for. It never blocks the + pipeline: without a provider (logged once at startup) or when the call + fails, the rule-based verdict stands. + """ + try: + semantic = await semantic_validate( + property_file_markdown=await render_markdown(session, property_id), + event_body=event["raw_content"], + event_source=event["source"], + proposed_facts=[ + { + "section": d.section, + "field": d.field, + "value": d.value, + "confidence": d.confidence, + } + for d in plan.decisions + ], + ) + except LLMNotConfiguredError: + return plan, rejections + except LLMUnavailableError as exc: + log.warning("worker.semantic_failed", event_id=str(event["id"]), error=str(exc)[:200]) + return plan, rejections + if not semantic.has_contradictions: + return plan, rejections + log.info( + "worker.semantic_rejections", event_id=str(event["id"]), count=len(semantic.rejections) + ) + return ( + _drop_hard_contradictions(plan, semantic.rejections), + rejections + list(semantic.rejections), + ) + + +def _drop_hard_contradictions(plan: DiffPlan, contradictions: Sequence[Rejection]) -> DiffPlan: + """Remove decisions whose slot has a hard contradiction; soft ones stay. + + Soft contradictions keep their decision in the plan and travel on as + review items, so a human sees both the written fact and the doubt. + """ + hard_keys = {(r.section, r.field) for r in contradictions if not r.needs_review} + if not hard_keys: + return plan + return DiffPlan( + decisions=[d for d in plan.decisions if (d.section, d.field) not in hard_keys], + skipped=plan.skipped, + ) + + +async def _record_review_items( + session: AsyncSession, + event_id: UUID, + property_id: UUID, + result: ExtractionResult, + rejections: list[Rejection], +) -> tuple[int, int]: + """Store hard rejections and uncertainties; return how many of each.""" + hard = [r for r in rejections if not r.needs_review] + if hard: + await persist_rejections( + session, + event_id=event_id, + property_id=property_id, + building_id=None, + liegenschaft_id=None, + rejections=hard, + ) + items: list[dict[str, Any]] = list(result.uncertain) + [ + _needs_review_to_uncertainty(r) for r in rejections if r.needs_review + ] + written = 0 + if items: + written = await apply_uncertainties( + session, event_id=event_id, property_id=property_id, items=items + ) + return len(hard), written + + +async def _record_activity( + session: AsyncSession, + event_id: UUID, + property_id: UUID, + result: ExtractionResult, + proposed_count: int, +) -> None: + """Add the event's one-line summary to the activity section and re-render. + + One activity entry per event: NOT EXISTS makes a replayed or recovered + event a no-op here, as the differ already makes it for extracted facts. + """ + if not result.summary: + return + await session.execute( + text( + """ + INSERT INTO facts + (property_id, section, field, value, source_event_id, + confidence, valid_from) + SELECT :pid, 'activity', :field, :value, :eid, :conf, now() + WHERE NOT EXISTS ( + SELECT 1 FROM facts + WHERE source_event_id = :eid AND section = 'activity' + ) + """ + ), + { + "pid": property_id, + "field": f"event_{event_id}", + "value": result.summary, + "eid": event_id, + "conf": max(0.5, min(0.95, 0.7 + proposed_count * 0.05)), + }, + ) + # Re-render so the materialized file's activity section includes this + # event; cheap when the applier already propagated in this transaction. + await propagate_after_fact_write( + session, + property_id=property_id, + trigger_event_id=event_id, + trigger_summary=result.summary, + ) + + async def process_batch(max_events: int = 20) -> int: """Drain up to ``max_events`` events; return how many were touched.""" factory = get_sessionmaker() diff --git a/backend/scheduler.py b/backend/scheduler.py index 4ca999d..010d8f7 100644 --- a/backend/scheduler.py +++ b/backend/scheduler.py @@ -1,35 +1,35 @@ -"""APScheduler setup — worker ticks + IMAP poll. +"""APScheduler setup: worker ticks + IMAP poll. Called from the FastAPI lifespan. The scheduler runs: - worker_tick every 2s: drains the events queue -- imap_poll every 10s: fetches new mail -- erp_poll every 30s +- imap_poll every 10s: fetches new mail (only when IMAP is configured) +- erp_poll every 30s (only when MOCK_ERP_URL is set) - signal_eval every 30s -- regulation_watch every 60m All jobs are coalescing + no-overlap. """ from __future__ import annotations -from datetime import datetime, timezone +from datetime import UTC, datetime import structlog from apscheduler.schedulers.asyncio import AsyncIOScheduler +from backend.config import get_settings from backend.pipeline.worker import process_batch from backend.services.erp_poller import poll_once as erp_poll_once +from backend.services.imap_poller import is_configured as imap_is_configured from backend.services.imap_poller import poll_once as imap_poll_once -from backend.services.tavily import watch_regulations from backend.signals.evaluator import evaluate_all as evaluate_signals log = structlog.get_logger(__name__) -def _now(): +def _now() -> datetime: """Return current UTC time for immediate scheduling.""" - return datetime.now(timezone.utc) + return datetime.now(UTC) def build_scheduler() -> AsyncIOScheduler: @@ -47,27 +47,30 @@ def build_scheduler() -> AsyncIOScheduler: next_run_time=_now(), ) - # IMAP poller - scheduler.add_job( - imap_poll_once, - "interval", - seconds=10, - id="imap_poll", - coalesce=True, - max_instances=1, - next_run_time=_now(), - ) - - # ERP poller - scheduler.add_job( - erp_poll_once, - "interval", - seconds=30, - id="erp_poll", - coalesce=True, - max_instances=1, - next_run_time=_now(), - ) + # IMAP poller: only registered when credentials are configured. + if imap_is_configured(): + scheduler.add_job( + imap_poll_once, + "interval", + seconds=10, + id="imap_poll", + coalesce=True, + max_instances=1, + next_run_time=_now(), + ) + + # ERP poller: only registered when a feed is configured, so an unset + # MOCK_ERP_URL produces no job and no connection errors in the log. + if get_settings().mock_erp_url: + scheduler.add_job( + erp_poll_once, + "interval", + seconds=30, + id="erp_poll", + coalesce=True, + max_instances=1, + next_run_time=_now(), + ) # Signal evaluator scheduler.add_job( @@ -80,16 +83,5 @@ def build_scheduler() -> AsyncIOScheduler: next_run_time=_now(), ) - # Regulation watcher - scheduler.add_job( - watch_regulations, - "interval", - minutes=60, - id="regulation_watch", - coalesce=True, - max_instances=1, - next_run_time=_now(), - ) - log.info("scheduler.built", jobs=[job.id for job in scheduler.get_jobs()]) - return scheduler \ No newline at end of file + return scheduler diff --git a/backend/services/aikido.py b/backend/services/aikido.py deleted file mode 100644 index c2ff5f3..0000000 --- a/backend/services/aikido.py +++ /dev/null @@ -1,127 +0,0 @@ -"""Aikido security-scan badge. - -Aikido runs as a GitHub App / CI integration — there's no lightweight -API we can hit mid-demo to re-scan. Per KEYSTONE Part IV ("Run Aikido -scan on this repo. Display 'Security scan: passing' badge on Settings -page ... Takes 30 minutes, buys real credibility") we treat the badge -as slow-moving metadata: - -- If ``AIKIDO_API_KEY`` is set we reach out to their REST API to pull - the latest scan status. -- Otherwise we return a local snapshot seeded from the most recent - ``git`` commit (the demo is evaluated against a specific SHA). - -Either way the endpoint exposes the same ``SecurityBadge`` shape so the -Settings page binding never changes. -""" - -from __future__ import annotations - -import subprocess -from dataclasses import dataclass -from datetime import datetime, timezone -from pathlib import Path - -import httpx -import structlog - -from backend.config import get_settings - -log = structlog.get_logger(__name__) - - -@dataclass(frozen=True) -class SecurityBadge: - """Shape the Settings page binds against.""" - - status: str # 'passing' | 'warning' | 'failing' | 'unknown' - scanner: str - last_scan_at: datetime | None - commit_sha: str | None - critical: int - high: int - medium: int - details_url: str | None - source: str # 'aikido_api' | 'local_snapshot' | 'offline' - - -def _git_commit_sha() -> str | None: - """Return the currently checked-out commit SHA, or ``None`` if unavailable.""" - repo_root = Path(__file__).resolve().parents[2] - try: - out = subprocess.run( - ["git", "rev-parse", "--short", "HEAD"], - cwd=repo_root, - capture_output=True, - text=True, - timeout=2, - check=False, - ) - except (FileNotFoundError, subprocess.SubprocessError): - return None - if out.returncode != 0: - return None - return out.stdout.strip() or None - - -async def _fetch_live_badge(api_key: str) -> SecurityBadge | None: - """Attempt to read scan status from the Aikido API; return None on failure.""" - try: - async with httpx.AsyncClient(timeout=5.0) as client: - response = await client.get( - "https://app.aikido.dev/api/public/v1/scan-status", - headers={"Authorization": f"Bearer {api_key}"}, - ) - response.raise_for_status() - payload = response.json() - except Exception as exc: # noqa: BLE001 — any failure collapses to fallback - log.warning("aikido.live_fetch_failed", error=str(exc)) - return None - - status = str(payload.get("status", "passing")).lower() - return SecurityBadge( - status=status, - scanner="Aikido", - last_scan_at=_parse_iso(payload.get("last_scan_at")), - commit_sha=str(payload.get("commit_sha") or _git_commit_sha() or ""), - critical=int(payload.get("critical") or 0), - high=int(payload.get("high") or 0), - medium=int(payload.get("medium") or 0), - details_url=str(payload.get("details_url") or "https://app.aikido.dev"), - source="aikido_api", - ) - - -def _parse_iso(value: object) -> datetime | None: - """Parse an ISO-8601 timestamp, returning ``None`` on bad input.""" - if not value or not isinstance(value, str): - return None - try: - return datetime.fromisoformat(value.replace("Z", "+00:00")) - except ValueError: - return None - - -async def get_badge() -> SecurityBadge: - """Return the security badge the Settings page renders.""" - settings = get_settings() - key = settings.aikido_api_key.strip() - if key and key != "replace-me": - live = await _fetch_live_badge(key) - if live is not None: - log.info("aikido.badge.live", status=live.status) - return live - - badge = SecurityBadge( - status="passing", - scanner="Aikido", - last_scan_at=datetime.now(timezone.utc), - commit_sha=_git_commit_sha(), - critical=0, - high=0, - medium=0, - details_url="https://app.aikido.dev", - source="local_snapshot", - ) - log.info("aikido.badge.local", status=badge.status, commit=badge.commit_sha) - return badge diff --git a/backend/services/entire.py b/backend/services/approval.py similarity index 62% rename from backend/services/entire.py rename to backend/services/approval.py index e32efda..a7727db 100644 --- a/backend/services/entire.py +++ b/backend/services/approval.py @@ -1,10 +1,11 @@ -"""Entire-compatible approval layer. - -Per KEYSTONE Part IV, the approval inbox is "Entire-powered". Until the -Entire SDK is available (or swapped in), we ship a Protocol-based -``EntireBroker`` interface and a ``LocalEntireBroker`` reference -implementation that writes to Postgres. Callers (the signals API) depend on -the Protocol, so adding a real Entire adapter is a one-file change. +"""Approval broker: what happens to a signal's message once a human approves it. + +The signals API depends only on the :class:`ApprovalBroker` protocol. The +shipped implementation, :class:`LocalApprovalBroker`, records the message in +the ``outbox`` table and sends nothing; a broker that actually delivers email +or Slack messages can be installed with :func:`set_broker` without touching +callers. Whatever the implementation, it should still write the outbox row so +every approved action stays auditable. """ from __future__ import annotations @@ -32,8 +33,8 @@ class DispatchResult: @runtime_checkable -class EntireBroker(Protocol): - """Swap-in point for the real Entire SDK when we have the keys.""" +class ApprovalBroker(Protocol): + """Dispatches the message of an approved signal.""" name: str @@ -47,19 +48,18 @@ async def dispatch( subject: str | None, body: str, ) -> DispatchResult: - """Broker the message after the human approves the signal.""" + """Deliver (or record) the message for an approved signal.""" ... -class LocalEntireBroker: - """Reference implementation — writes to the ``outbox`` table. +class LocalApprovalBroker: + """Writes the message to ``outbox`` in the caller's transaction; sends nothing. - The pitch line stays accurate ("Entire-compatible approval layer") because - the signature + semantics mirror what the real SDK would do: atomically - persist a message and return a reference for it. + Runs inside the approval request's session, so the outbox row, the status + change and the ``approval_log`` entry commit together. """ - name = "local-entire-broker" + name = "local-outbox" async def dispatch( self, @@ -90,7 +90,7 @@ async def dispatch( ) row = result.one() log.info( - "entire.dispatch.local", + "approval.dispatch.local", signal_id=str(signal_id), channel=channel, recipient=recipient, @@ -104,15 +104,15 @@ async def dispatch( ) -_broker: EntireBroker = LocalEntireBroker() +_broker: ApprovalBroker = LocalApprovalBroker() -def get_broker() -> EntireBroker: - """Return the configured broker. Single-source-of-truth for dep injection.""" +def get_broker() -> ApprovalBroker: + """Return the installed broker.""" return _broker -def set_broker(broker: EntireBroker) -> None: - """Install a different broker. Intended for tests / the real SDK swap.""" +def set_broker(broker: ApprovalBroker) -> None: + """Install a different broker, e.g. a test double or a delivering implementation.""" global _broker _broker = broker diff --git a/backend/services/pioneer.py b/backend/services/approval_stats.py similarity index 89% rename from backend/services/pioneer.py rename to backend/services/approval_stats.py index 3645ba1..e0af36f 100644 --- a/backend/services/pioneer.py +++ b/backend/services/approval_stats.py @@ -1,11 +1,12 @@ -"""Pioneer / Fastino learning layer. - -Phase 5 implements the self-contained version: we read the -``approval_log`` table, compute per-signal-type approval rates, and turn -those into priority weights the UI surfaces ("Keystone is prioritizing -heating issues based on your behavior"). The interface is shaped so a -real Pioneer / Fastino integration can replace the local calc by -swapping :func:`compute_learning` — the dashboard endpoint doesn't care. +"""Approval-rate statistics per signal type. + +Reads ``approval_log``, computes how often operators approve, edit or reject +each signal type, and maps that to a priority weight in ``[0.5, 1.5]`` +(with fewer than five proposals, the weight is pulled toward 1.0 in +proportion to the sample size). ``GET /settings/learning`` serves the result. +This is descriptive statistics over observed decisions, not a trained model; +a learned ranker could replace :func:`compute_learning` without changing the +endpoint. """ from __future__ import annotations @@ -64,7 +65,7 @@ def _trend_line(stats: list[SignalTypeStats]) -> str: top = max(stats, key=lambda s: s.priority_weight) if top.priority_weight <= 1.0 + 1e-6: return ( - "Keystone has not yet re-prioritized — approval rates are still " + "Keystone has not yet re-prioritized; approval rates are still " "near baseline across signal types." ) pretty = top.type.replace("_", " ") @@ -140,7 +141,7 @@ async def compute_learning(session: AsyncSession) -> LearningSnapshot: sample_size=sample_size, ) log.info( - "pioneer.learning", + "approval_stats.computed", types=len(stats), samples=sample_size, top=snapshot.top_priority, diff --git a/backend/services/ask.py b/backend/services/ask.py index f79e2d8..6df63d9 100644 --- a/backend/services/ask.py +++ b/backend/services/ask.py @@ -1,17 +1,17 @@ """Property-scoped Q&A service. -Powers ``POST /properties/{id}/ask``. Per Phase 9 trust-layer rules, -the answer must say "I don't know" when the context doesn't support a -confident answer — confabulation is the failure mode this whole -project pushes back against. +Powers ``POST /properties/{id}/ask``. The answer must say "I don't know" +when the context does not support a confident answer: a fluent but +unsupported answer is the failure mode the whole trust layer exists to +prevent. The LLM picks one of three statuses: -- ``answered`` — context contains the answer; ``cited_event_ids`` +- ``answered``: context contains the answer; ``cited_event_ids`` identifies the supporting events. -- ``insufficient_context`` — related context exists but doesn't answer +- ``insufficient_context``: related context exists but doesn't answer the question; ``partial_context_event_ids`` lists what we do know. -- ``out_of_scope`` — the question is about data Keystone doesn't +- ``out_of_scope``: the question is about data Keystone doesn't track (ERP-side: exact rent payment dates, IBAN, tax IDs, …). The API layer maps the cited IDs back to full source records so the @@ -20,16 +20,12 @@ from __future__ import annotations -import json -import time from dataclasses import dataclass from typing import Any -import httpx import structlog -from backend.config import get_settings -from backend.services import pioneer_llm +from backend.services.llm import require_provider log = structlog.get_logger(__name__) @@ -44,11 +40,11 @@ class _EventRef: SYSTEM_HINT = ( "You answer questions about a German Hausverwaltung property using " - "only the facts and events provided. Honesty over completeness — " + "only the facts and events provided. Honesty over completeness: " "if the context doesn't support a confident answer, say so. " "Respond with a single JSON object that strictly matches the schema. " - "No prose, no markdown fences — only the JSON object. " - "Inside text fields (answer, reasoning), use plain prose only — no " + "No prose, no markdown fences: only the JSON object. " + "Inside text fields (answer, reasoning), use plain prose only, no " "markdown formatting (**, *, _, `, #), no headings, no bullet " "points, no markdown links. Text will be displayed as plain text in " "the UI; markdown markers leak through and look broken to the user." @@ -63,14 +59,14 @@ class _EventRef: \"\"\" PROPERTY FILE (the canonical, condensed markdown record for this -property — Stammdaten at top, then sectioned facts with confidence and +property: Stammdaten at top, then sectioned facts with confidence and source links, then Building / WEG context. This is your primary source: everything Keystone knows about this property is here.) \"\"\" {property_file} \"\"\" -RECENT EVENTS (last 90 days, newest first — raw snippets to support +RECENT EVENTS (last 90 days, newest first; raw snippets to support direct quotation. The event ids match the [source: ...] links in the PROPERTY FILE above. Cite these ids in cited_event_ids.) {events_block} @@ -86,11 +82,11 @@ class _EventRef: did find. Set ``reasoning`` to one sentence explaining why the context falls short. - "out_of_scope": the question is about data Keystone doesn't track - in this layer — exact rent payment dates, IBAN, bank balances, tax + in this layer: exact rent payment dates, IBAN, bank balances, tax IDs, full lease termination logic. ``answer`` MUST be null. ``reasoning`` names what would be needed (e.g. "lives in the ERP"). -LANGUAGE — STRICT MATCH +LANGUAGE: STRICT MATCH Detect the language of the QUESTION above. Then write BOTH ``answer`` and ``reasoning`` in that exact language. - If the question is in German, both fields are in German. Quote @@ -114,8 +110,6 @@ class _EventRef: }}""" - - def _format_events_block(events: list[_EventRef]) -> str: if not events: return " (no recent events)" @@ -132,28 +126,23 @@ async def answer_question( question: str, property_file_markdown: str, recent_events: list[dict[str, Any]], - model_name: str | None = None, timeout_s: float = 30.0, ) -> dict[str, Any]: - """Ask Claude (via Pioneer) a property-scoped question. + """Ask the configured LLM provider a property-scoped question. - The model reads the canonical rendered markdown for the property - (stammdaten + sectioned facts + uncertainties + parent-tier - context) plus a small block of raw recent-event snippets that - enable direct quotation. Whatever the markdown contains is - answerable; whatever it doesn't, the model says "I don't know". + The model reads the rendered property file (master data, sectioned facts, + uncertainties, parent-tier context) plus a short block of recent raw event + snippets it can quote. Whatever the file contains is answerable; whatever + it does not, the model must say it does not know. - Returns parsed JSON dict with status/answer/confidence/reasoning - plus the cited / partial-context event-id lists. The API layer - joins those IDs back to event records. + Returns the parsed answer: status, answer, confidence and reasoning plus + the cited and partial-context event ids, which the API layer joins back + to event records. - Raises :class:`pioneer_llm.PioneerUnavailable` when Pioneer can't - be reached or every attempt fails. + Raises :class:`LLMNotConfiguredError` when no provider is configured and + :class:`LLMUnavailableError` when the call fails. """ - settings = get_settings() - if not pioneer_llm.is_available(): - raise pioneer_llm.PioneerUnavailable("PIONEER_API_KEY not set") - + provider = require_provider() events = [_EventRef(**e) for e in recent_events] prompt = PROMPT_TEMPLATE.format( @@ -163,59 +152,26 @@ async def answer_question( events_block=_format_events_block(events), ) - model = model_name or pioneer_llm.PIONEER_DEFAULT_MODEL - headers = { - "Authorization": f"Bearer {settings.pioneer_api_key}", - "Content-Type": "application/json", - } - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": SYSTEM_HINT}, - {"role": "user", "content": prompt}, - ], - "temperature": 0.1, - "response_format": {"type": "json_object"}, - } - log.info( "ask.start", - model=model, + provider=provider.name, + model=provider.model, property=property_name, prompt_chars=len(prompt), property_file_chars=len(property_file_markdown), event_count=len(events), ) - start = time.perf_counter() - try: - async with httpx.AsyncClient(timeout=timeout_s) as client: - response = await client.post( - f"{pioneer_llm.PIONEER_BASE_URL}/chat/completions", - headers=headers, - json=body, - ) - response.raise_for_status() - payload = response.json() - choice = payload["choices"][0] - text = choice["message"].get("content") or "" - data = pioneer_llm._parse_json_payload(text) - except httpx.HTTPError as exc: - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "ask.error", - model=model, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - raise pioneer_llm.PioneerUnavailable(f"ask failed: {exc!r}") from exc - - latency_ms = (time.perf_counter() - start) * 1000 - usage = payload.get("usage") or {} + completion = await provider.complete_json( + system=SYSTEM_HINT, prompt=prompt, temperature=0.1, timeout_s=timeout_s + ) + data = completion.data + model = completion.model + latency_ms = completion.latency_ms status = str(data.get("status") or "").strip() if status not in {"answered", "insufficient_context", "out_of_scope"}: - # Treat unknown statuses as insufficient_context — safer than + # Treat unknown statuses as insufficient_context; safer than # surfacing a possibly hallucinated answer. status = "insufficient_context" @@ -223,8 +179,8 @@ async def answer_question( "ask.ok", model=model, latency_ms=round(latency_ms, 1), - prompt_tokens=usage.get("prompt_tokens"), - completion_tokens=usage.get("completion_tokens"), + prompt_tokens=completion.prompt_tokens, + completion_tokens=completion.completion_tokens, status=status, cited=len(data.get("cited_event_ids") or []), partial=len(data.get("partial_context_event_ids") or []), diff --git a/backend/services/draft_reply.py b/backend/services/draft_reply.py index 94205df..3b90d71 100644 --- a/backend/services/draft_reply.py +++ b/backend/services/draft_reply.py @@ -1,7 +1,7 @@ """Inbound-reply drafting service. -Powers ``POST /draft-reply``. Distinct from ``draft_action_message`` -(``backend.services.gemini``) which drafts *outbound* signal messages — +Powers ``POST /draft-reply``. Distinct from the signal drafter +(``backend.signals.drafter``), which drafts *outbound* signal messages: this module drafts replies to *inbound* tenant/owner messages, citing prior facts and events as context. @@ -11,23 +11,17 @@ - input: ``{property_id?, property_name?, channel, tone, subject?, body}`` - output: ``{subject, body, context[], knows_about_incident, elapsed_ms}`` -The LLM call routes through Pioneer (Claude) by default — Phase 11 -parked extraction on Pioneer while Gemini Pro quota is exhausted, and -keeping the drafter on the same backbone avoids two LLM dependencies. +The call goes to the configured LLM provider (:mod:`backend.services.llm`). """ from __future__ import annotations -import json -import time from dataclasses import dataclass from typing import Any -import httpx import structlog -from backend.config import get_settings -from backend.services import pioneer_llm +from backend.services.llm import require_provider log = structlog.get_logger(__name__) @@ -52,9 +46,9 @@ class _EventRef: "You are drafting a reply on behalf of a German property manager " "(Hausverwaltung). Respond with a single JSON object that strictly " "matches the schema described in the user message. No prose, no " - "markdown fences — only the JSON object. Match the language of the " + "markdown fences: only the JSON object. Match the language of the " "inbound message in the reply body. Inside text fields (subject, " - "body, why_relevant, snippet), use plain prose only — no markdown " + "body, why_relevant, snippet), use plain prose only, no markdown " "formatting (**, *, _, `, #), no markdown links, no bullet markers. " "The reply body will be sent verbatim to a tenant or owner via " "email/Slack; markdown markers look broken to the recipient." @@ -73,7 +67,7 @@ class _EventRef: DESIRED TONE: {tone} -PROPERTY CONTEXT — {property_name} +PROPERTY CONTEXT: {property_name} Current facts (most recent first): {facts_block} @@ -86,7 +80,7 @@ class _EventRef: inbound message. Set ``knows_about_incident`` accordingly. 2. If yes, list the relevant items in ``context`` with a one-sentence ``why_relevant`` and use them to inform the reply body. Reference - them concretely (dates, amounts, parties) — no vague gestures. + them concretely (dates, amounts, parties): no vague gestures. 3. If no, draft a short holding reply ("we will look into this and come back within X working days") with an empty ``context`` array. 4. Write the reply body in the same language as the inbound message @@ -140,23 +134,17 @@ async def draft_inbound_reply( tone: str, recent_facts: list[dict[str, Any]], recent_events: list[dict[str, Any]], - model_name: str | None = None, timeout_s: float = 30.0, ) -> dict[str, Any]: - """Run the draft-reply prompt against Claude via Pioneer. + """Draft a reply to an inbound message with the configured LLM provider. - ``recent_facts`` and ``recent_events`` come from the API layer's - Postgres queries — this service stays SQL-free so it's easy to - unit-test with fixture data. + ``recent_facts`` and ``recent_events`` come from the API layer's queries; + this service stays SQL-free so it is easy to test with fixture data. - Returns the parsed JSON dict. Raises - :class:`pioneer_llm.PioneerUnavailable` when Pioneer cannot be - used or every attempt failed. + Returns the parsed draft. Raises :class:`LLMNotConfiguredError` when no + provider is configured and :class:`LLMUnavailableError` when the call fails. """ - settings = get_settings() - if not pioneer_llm.is_available(): - raise pioneer_llm.PioneerUnavailable("PIONEER_API_KEY not set") - + provider = require_provider() facts = [_Fact(**f) for f in recent_facts] events = [_EventRef(**e) for e in recent_events] @@ -170,24 +158,10 @@ async def draft_inbound_reply( events_block=_format_events_block(events), ) - model = model_name or pioneer_llm.PIONEER_DEFAULT_MODEL - headers = { - "Authorization": f"Bearer {settings.pioneer_api_key}", - "Content-Type": "application/json", - } - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": SYSTEM_HINT}, - {"role": "user", "content": prompt}, - ], - "temperature": 0.2, - "response_format": {"type": "json_object"}, - } - log.info( "draft_reply.start", - model=model, + provider=provider.name, + model=provider.model, channel=inbound_channel, property=property_name, prompt_chars=len(prompt), @@ -195,45 +169,24 @@ async def draft_inbound_reply( event_count=len(events), ) - start = time.perf_counter() - try: - async with httpx.AsyncClient(timeout=timeout_s) as client: - response = await client.post( - f"{pioneer_llm.PIONEER_BASE_URL}/chat/completions", - headers=headers, - json=body, - ) - response.raise_for_status() - payload = response.json() - choice = payload["choices"][0] - text = choice["message"].get("content") or "" - data = pioneer_llm._parse_json_payload(text) - except httpx.HTTPError as exc: - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "draft_reply.error", - model=model, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - raise pioneer_llm.PioneerUnavailable( - f"draft_reply failed: {exc!r}" - ) from exc - - latency_ms = (time.perf_counter() - start) * 1000 - usage = payload.get("usage") or {} + completion = await provider.complete_json( + system=SYSTEM_HINT, prompt=prompt, temperature=0.2, timeout_s=timeout_s + ) + data = completion.data + model = completion.model + latency_ms = completion.latency_ms log.info( "draft_reply.ok", model=model, latency_ms=round(latency_ms, 1), - prompt_tokens=usage.get("prompt_tokens"), - completion_tokens=usage.get("completion_tokens"), + prompt_tokens=completion.prompt_tokens, + completion_tokens=completion.completion_tokens, knows_about_incident=bool(data.get("knows_about_incident")), context_count=len(data.get("context") or []), ) - # Defensive shape coercion — Pioneer returns the schema almost - # always, but we don't want a stray missing field to 500 the API. + # Coerce defensively: models return the schema almost always, but a + # missing field must not turn into a 500. return { "subject": str(data.get("subject") or ""), "body": str(data.get("body") or ""), diff --git a/backend/services/erp_poller.py b/backend/services/erp_poller.py index 0c30824..dbf0910 100644 --- a/backend/services/erp_poller.py +++ b/backend/services/erp_poller.py @@ -1,7 +1,7 @@ """Poll the mock ERP and ingest new payments as events. -The poller runs on APScheduler every ~30s (Phase 2). State is kept entirely -in Postgres — each poll asks the mock ERP for ``payments`` and inserts each +The poller runs on APScheduler every ~30s. State is kept entirely +in Postgres: each poll asks the mock ERP for ``payments`` and inserts each new row as an ``erp`` event keyed on its ``payment_id``. The ``(source, source_ref)`` unique constraint on the events table keeps the call idempotent. """ diff --git a/backend/services/featured.py b/backend/services/featured.py new file mode 100644 index 0000000..647d7bd --- /dev/null +++ b/backend/services/featured.py @@ -0,0 +1,31 @@ +"""Resolve the featured property from configuration. + +``FEATURED_PROPERTY`` names the property the UI opens first and the one-click +replay targets. It accepts either a property UUID or any of the property's +aliases. Property UUIDs are generated per database, so the default is an alias +(the unit ID ``EH-029``) that resolves on every install of the sample data. +""" + +from __future__ import annotations + +from uuid import UUID + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.config import get_settings + + +async def resolve_featured_property_id(session: AsyncSession) -> UUID | None: + """Return the featured property's id, or ``None`` if the reference matches nothing.""" + ref = get_settings().featured_property.strip() + if not ref: + return None + params: dict[str, object] + try: + query, params = "SELECT id FROM properties WHERE id = :ref", {"ref": UUID(ref)} + except ValueError: + query = "SELECT id FROM properties WHERE :ref = ANY(aliases) ORDER BY created_at LIMIT 1" + params = {"ref": ref} + row = (await session.execute(text(query), params)).first() + return UUID(str(row.id)) if row else None diff --git a/backend/services/gemini.py b/backend/services/gemini.py deleted file mode 100644 index 45ecda3..0000000 --- a/backend/services/gemini.py +++ /dev/null @@ -1,650 +0,0 @@ -"""Single choke-point for every Gemini call. - -Part IV of KEYSTONE is emphatic: **all** Gemini calls go through this module, -with structured output (JSON schema), retries, and production-grade logging. -Judges notice logs that include prompt hash + latency + token counts. - -The module gracefully degrades: if ``GEMINI_API_KEY`` is unset the client -raises :class:`GeminiUnavailable`, and callers (e.g. the extractor) switch -to a rule-based fallback. This is explicitly noted in Part XII as the -demo-day mitigation for Gemini outages. -""" - -from __future__ import annotations - -import asyncio -import hashlib -import json -import time -from dataclasses import dataclass, field -from functools import lru_cache -from pathlib import Path -from typing import Any - -import structlog - -from backend.config import get_settings - -log = structlog.get_logger(__name__) - - -class GeminiUnavailable(RuntimeError): - """Raised when Gemini cannot be used (no key, import failure, hard error).""" - - -# ----------------------------------------------------------------------------- -# Extraction schema + prompt (Part VII canonical) -# ----------------------------------------------------------------------------- - -# Gemini's ``response_schema`` accepts a strict OpenAPI 3.0 subset — -# ``minimum`` / ``maximum`` / ``$defs`` are rejected. We lean on the -# prompt to enforce the [0, 1] range on ``confidence``; downstream code -# clamps it defensively. -EXTRACTION_SCHEMA: dict[str, Any] = { - "type": "object", - "properties": { - "category": { - "type": "string", - "enum": [ - "maintenance", - "lease", - "payment", - "complaint", - "compliance", - "tenant_change", - "owner_communication", - "other", - ], - }, - "priority": {"type": "string", "enum": ["low", "medium", "high", "urgent"]}, - "facts_to_update": { - "type": "array", - "items": { - "type": "object", - "properties": { - "section": { - "type": "string", - "enum": [ - "overview", - "tenants", - "lease", - "maintenance", - "financials", - "compliance", - "activity", - "patterns", - "building_financials", - "building_maintenance", - "building_compliance", - "liegenschaft_financials", - "liegenschaft_maintenance", - "liegenschaft_compliance", - ], - }, - "field": {"type": "string"}, - "value": {"type": "string"}, - "confidence": {"type": "number"}, - }, - "required": ["section", "field", "value", "confidence"], - }, - }, - "uncertain": { - "type": "array", - "description": ( - "Items the extractor noticed but cannot commit to as a fact. " - "Vague mentions, ambiguous references, hearsay, second-hand " - "claims. The user prefers 'I noticed something unclear' over " - "'I think this is true.'" - ), - "items": { - "type": "object", - "properties": { - "observation": { - "type": "string", - "description": "What was noticed, quoted or near-quoted from the source.", - }, - "hypothesis": { - "type": "string", - "description": ( - "Optional candidate value if there is one; leave " - "empty when only the observation matters." - ), - }, - "reason_uncertain": { - "type": "string", - "description": "Why this didn't become a fact (vague, hearsay, ambiguous reference, …).", - }, - "relevant_section": { - "type": "string", - "description": ( - "Best guess at the section a future fact would land " - "in (overview, tenants, lease, maintenance, financials, " - "compliance, building_*, liegenschaft_*)." - ), - }, - "relevant_field": { - "type": "string", - "description": "Optional best guess at the field name.", - }, - }, - "required": ["observation", "reason_uncertain", "relevant_section"], - }, - }, - "summary": {"type": "string"}, - }, - "required": ["category", "priority", "facts_to_update", "summary"], -} - -_PROMPT_DIR = Path(__file__).resolve().parent / "prompts" -_VOCABULARY_PATH = _PROMPT_DIR / "field_vocabulary.json" - - -@lru_cache(maxsize=4) -def _load_prompt_template(lang: str) -> str: - """Read the per-language Markdown prompt with file-system caching.""" - name = "extraction_de.md" if lang == "de" else "extraction_en.md" - path = _PROMPT_DIR / name - if not path.is_file(): - raise FileNotFoundError(f"missing prompt template: {path}") - return path.read_text(encoding="utf-8") - - -@lru_cache(maxsize=1) -def _vocabulary_block() -> str: - """Render the JSON vocabulary into a markdown block for the prompts. - - Result example:: - - - **maintenance** (4 fields) - - `open_water_damage` — e.g. "Wasserschaden + Schimmel WE 32 …" - - `key_lost` — e.g. "Mieter WE 02 hat Wohnungsschlüssel verloren …" - - `defective_window` — e.g. "Küchenfenster WE 50 schließt nicht mehr …" - - **financials** (3 fields) - - … - """ - if not _VOCABULARY_PATH.is_file(): - return "_(no vocabulary file present — emit conservative field names)_" - payload = json.loads(_VOCABULARY_PATH.read_text(encoding="utf-8")) - lines: list[str] = [] - for section, body in payload.get("sections", {}).items(): - fields = body.get("fields", []) - if not fields: - lines.append(f"- **{section}** (0 fields — section reserved)") - continue - lines.append(f"- **{section}** ({len(fields)} fields)") - for f in fields: - example = "" - if f.get("examples"): - example = f' — e.g. "{f["examples"][0]}"' - lines.append(f" - `{f['name']}`{example}") - return "\n".join(lines) - - -def render_extraction_prompt( - *, - property_name: str, - current_context_excerpt: str, - source: str, - raw_content: str, - lang: str, -) -> str: - """Build the prompt fed to ``GenerativeModel.generate_content``.""" - template = _load_prompt_template(lang) - return template.format( - property_name=property_name, - current_context_excerpt=current_context_excerpt or "(no prior context)", - source=source, - raw_content=raw_content, - vocabulary_block=_vocabulary_block(), - ) - - -@dataclass -class ExtractionResult: - """Parsed Gemini extraction response. - - Token counts are surfaced so callers (notably ``eval.runner``) can - attribute spend to the cost ledger. ``None`` when the rule fallback - fired and no LLM call was made. - """ - - category: str - priority: str - facts_to_update: list[dict[str, Any]] - summary: str - # Phase 9 Step 9.1 — items noticed but not committed to as facts. - # Each entry shape: {observation, hypothesis?, reason_uncertain, - # relevant_section, relevant_field?}. Empty list means the - # extractor had nothing it wanted to flag. - uncertain: list[dict[str, Any]] = field(default_factory=list) - raw: dict[str, Any] = field(default_factory=dict) - latency_ms: float = 0.0 - model: str = "" - source: str = "gemini" - prompt_tokens: int | None = None - completion_tokens: int | None = None - - -# ----------------------------------------------------------------------------- -# Gemini client -# ----------------------------------------------------------------------------- - - -def _prompt_hash(prompt: str) -> str: - """Short stable digest for log correlation (no PII leakage).""" - return hashlib.sha1(prompt.encode("utf-8")).hexdigest()[:10] - - -def is_available() -> bool: - """Return True iff a usable Gemini API key is configured.""" - key = get_settings().gemini_api_key.strip() - return bool(key) and key not in {"replace-me", "disabled"} - - -def _configure_client() -> Any: - """Lazily import + configure ``google.generativeai`` so tests can stub it.""" - if not is_available(): - raise GeminiUnavailable("GEMINI_API_KEY not set") - try: - import google.generativeai as genai # noqa: PLC0415 — lazy import - except ImportError as exc: # pragma: no cover — dep is required - raise GeminiUnavailable("google-generativeai is not installed") from exc - genai.configure(api_key=get_settings().gemini_api_key) - return genai - - -# Per-call deadline for the Gemini extraction. Bigger than p99 latency -# observed in Step 6 (≈ 37 s on Pro under concurrency=4), small enough -# that a silent hang surfaces as a normal exception inside one event -# rather than freezing the whole pipeline. Configurable per-call so -# the rule-fallback path can still take over when an extraction -# legitimately needs longer. -GEMINI_EXTRACT_TIMEOUT_S: float = 60.0 - - -async def extract_facts( - *, - property_name: str, - current_context_excerpt: str, - source: str, - raw_content: str, - lang: str = "en", - model_name: str | None = None, - max_attempts: int = 3, - timeout_s: float = GEMINI_EXTRACT_TIMEOUT_S, -) -> ExtractionResult: - """Run the canonical extraction prompt against Gemini. - - Args: - property_name: Display name of the matched property (for prompt context). - current_context_excerpt: A short excerpt of the rendered markdown the - model can reference when deciding if a fact is new. - source: Event source — ``"email" | "slack" | "pdf" | ...``. - raw_content: The event text. - lang: ISO-639-1 language code; selects the per-language prompt. - model_name: Override the configured Pro model (Step 5: default is - ``gemini_pro_model`` for extraction quality; pass - ``gemini_flash_model`` for the auxiliary category-classifier - path or for cheap retries). - max_attempts: Retries with exponential backoff on transient errors. - - Returns: - Parsed :class:`ExtractionResult`. - - Raises: - GeminiUnavailable: if the client is not configured or every attempt - fails — callers should fall back to the rule-based path. - """ - settings = get_settings() - model = model_name or settings.gemini_pro_model - prompt = render_extraction_prompt( - property_name=property_name, - current_context_excerpt=current_context_excerpt, - source=source, - raw_content=raw_content, - lang=lang, - ) - digest = _prompt_hash(prompt) - log.info( - "gemini.extract.start", - model=model, - prompt_hash=digest, - source=source, - lang=lang, - prompt_chars=len(prompt), - ) - - last_error: Exception | None = None - for attempt in range(1, max_attempts + 1): - start = time.perf_counter() - try: - genai = _configure_client() - gen_model = genai.GenerativeModel(model) - # Wrap the blocking SDK call in an asyncio.wait_for so a - # silent server-side hang (which Step 6 surfaced under - # concurrency=4 — 4 in-flight calls, no 429, just no return) - # raises asyncio.TimeoutError inside this attempt instead of - # freezing the worker forever. The retry path below handles - # the timeout like any other transient error. - response = await asyncio.wait_for( - asyncio.to_thread( - gen_model.generate_content, - prompt, - generation_config={ - "response_mime_type": "application/json", - "response_schema": EXTRACTION_SCHEMA, - "temperature": 0.1, - }, - ), - timeout=timeout_s, - ) - latency_ms = (time.perf_counter() - start) * 1000 - text = (response.text or "").strip() - data = json.loads(text) if text else {} - usage = getattr(response, "usage_metadata", None) - log.info( - "gemini.extract.ok", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - prompt_tokens=getattr(usage, "prompt_token_count", None), - completion_tokens=getattr(usage, "candidates_token_count", None), - fact_count=len(data.get("facts_to_update", [])), - ) - return ExtractionResult( - category=data.get("category", "other"), - priority=data.get("priority", "low"), - facts_to_update=list(data.get("facts_to_update", [])), - uncertain=list(data.get("uncertain", [])), - summary=data.get("summary", ""), - raw=data, - latency_ms=latency_ms, - model=model, - source="gemini", - prompt_tokens=getattr(usage, "prompt_token_count", None), - completion_tokens=getattr(usage, "candidates_token_count", None), - ) - except GeminiUnavailable: - raise - except Exception as exc: # noqa: BLE001 — retry on any transient error - last_error = exc - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "gemini.extract.retry", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - if attempt < max_attempts: - await asyncio.sleep(0.4 * attempt) - - raise GeminiUnavailable( - f"extract_facts failed after {max_attempts} attempts: {last_error!r}" - ) - - -# ----------------------------------------------------------------------------- -# Drafting (Pro path) -# ----------------------------------------------------------------------------- - - -DRAFT_PROMPT_TEMPLATE = """You are drafting an operational message for a property manager. - -Tone: crisp, specific, expert. Avoid vague softeners like 'maybe', 'might'. -Open with the observation and the risk. End with a concrete next step and a -deadline. 4-6 sentences, no signature block, no greetings. - -Signal type: {signal_type} -Severity: {severity} -Property context: -{context} - -Evidence summary: -{evidence_summary} - -Write the message body now.""" - - -async def draft_action_message( - *, - signal_type: str, - severity: str, - context: str, - evidence_summary: str, - model_name: str | None = None, - max_attempts: int = 2, -) -> str: - """Ask Gemini Pro to write a ``proposed_action.drafted_message``. - - Returns the drafted text. Raises :class:`GeminiUnavailable` when the API - is not configured or every attempt fails — callers should fall back to a - deterministic template. - """ - settings = get_settings() - model = model_name or settings.gemini_pro_model - prompt = DRAFT_PROMPT_TEMPLATE.format( - signal_type=signal_type, - severity=severity, - context=context or "(no prior context)", - evidence_summary=evidence_summary or "(no evidence)", - ) - digest = _prompt_hash(prompt) - log.info( - "gemini.draft.start", - model=model, - prompt_hash=digest, - signal_type=signal_type, - ) - - last_error: Exception | None = None - for attempt in range(1, max_attempts + 1): - start = time.perf_counter() - try: - genai = _configure_client() - gen_model = genai.GenerativeModel(model) - response = await asyncio.to_thread( - gen_model.generate_content, - prompt, - generation_config={"temperature": 0.3}, - ) - latency_ms = (time.perf_counter() - start) * 1000 - text = (response.text or "").strip() - usage = getattr(response, "usage_metadata", None) - log.info( - "gemini.draft.ok", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - prompt_tokens=getattr(usage, "prompt_token_count", None), - completion_tokens=getattr(usage, "candidates_token_count", None), - chars=len(text), - ) - if text: - return text - last_error = RuntimeError("empty response") - except GeminiUnavailable: - raise - except Exception as exc: # noqa: BLE001 — broad retry policy for drafting - last_error = exc - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "gemini.draft.retry", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - if attempt < max_attempts: - await asyncio.sleep(0.4 * attempt) - - raise GeminiUnavailable( - f"draft_action_message failed after {max_attempts} attempts: {last_error!r}" - ) - - -# ----------------------------------------------------------------------------- -# Onboarding briefing (Phase 10 Step 10.3) -# ----------------------------------------------------------------------------- - - -ONBOARDING_PROMPT_EN = """You are briefing a property manager who is reading {property_name} for the first time. - -Write 5 to 7 bullets. Each bullet is ≤ 25 words. The reader has 60 seconds. - -HARD RULES: -- Honesty over completeness. If a key piece is missing, say so plainly. - Use the literal prefix "Gap:" and name what is missing. -- Do not invent dates, amounts, names, or facts. If something is uncertain, - treat it as a gap, not as a fact. -- Lead with what is operationally relevant TODAY (open issues, recent - changes), then context, then risks to watch. -- Plain text, no headings, no preamble like "Here is the briefing". -- One bullet per line, prefix each with "- ". -- Write in English. - -CURRENT FACTS (authoritative — already validated): -{facts_summary} - -OPEN UNCERTAINTIES (noticed but not committed — call out as gaps): -{uncertainties_summary} - -VALIDATOR REJECTIONS (proposed but rejected — note as known conflicts): -{rejections_summary} - -RECENT EVENT ACTIVITY (last 12 months, by category): -{activity_summary} - -Write the bullets now.""" - - -ONBOARDING_PROMPT_DE = """Du briefst eine:n Hausverwalter:in, die:der {property_name} zum ersten Mal liest. - -Schreibe 5 bis 7 Stichpunkte. Jeder Stichpunkt ≤ 25 Wörter. Der Leser hat 60 Sekunden. - -HARTE REGELN: -- Ehrlichkeit vor Vollständigkeit. Fehlt etwas Wichtiges, sage es klar. - Verwende dafür das wörtliche Präfix "Lücke:" und benenne, was fehlt. -- Keine erfundenen Daten, Beträge, Namen oder Fakten. Was unsicher ist, - ist eine Lücke — kein Fakt. -- Beginne mit dem operativ Wichtigsten HEUTE (offene Punkte, jüngste - Änderungen), dann Kontext, dann Risiken zur Beobachtung. -- Reiner Text, keine Überschriften, keine Einleitung wie "Hier ist das Briefing". -- Ein Stichpunkt pro Zeile, jeweils mit "- " beginnen. -- Schreibe auf Deutsch. - -AKTUELLE FAKTEN (validiert, autoritativ): -{facts_summary} - -OFFENE UNSICHERHEITEN (bemerkt, aber nicht als Fakt festgeschrieben — als Lücken nennen): -{uncertainties_summary} - -VALIDATOR-ABLEHNUNGEN (vorgeschlagen, aber abgelehnt — als bekannte Konflikte vermerken): -{rejections_summary} - -LETZTE EREIGNISAKTIVITÄT (12 Monate, nach Quelle): -{activity_summary} - -Schreibe jetzt die Stichpunkte.""" - - -async def draft_onboarding_briefing( - *, - property_name: str, - facts_summary: str, - uncertainties_summary: str, - rejections_summary: str, - activity_summary: str, - lang: str = "en", - model_name: str | None = None, - max_attempts: int = 2, - timeout_s: float = 45.0, -) -> str: - """Render the "Key context" briefing for the onboarding view. - - Five-to-seven bullet narrative, hard-instructed to mention gaps as - "Gap: …" / "Lücke: …" rather than inventing. ``lang`` selects the - German (``"de"``) or English (``"en"``) prompt so the output - matches the surrounding markdown's tongue. Returns the bullet - block as plain markdown (no surrounding heading). Raises - :class:`GeminiUnavailable` if every attempt fails — callers fall - back to a deterministic placeholder so the rest of the onboarding - view still renders. - """ - settings = get_settings() - model = model_name or settings.gemini_pro_model - template = ONBOARDING_PROMPT_DE if lang == "de" else ONBOARDING_PROMPT_EN - no_facts = "(noch keine Fakten)" if lang == "de" else "(no facts yet)" - none_label = "(keine)" if lang == "de" else "(none)" - no_activity = ( - "(keine jüngste Aktivität)" if lang == "de" else "(no recent activity)" - ) - prompt = template.format( - property_name=property_name, - facts_summary=facts_summary or no_facts, - uncertainties_summary=uncertainties_summary or none_label, - rejections_summary=rejections_summary or none_label, - activity_summary=activity_summary or no_activity, - ) - digest = _prompt_hash(prompt) - log.info( - "gemini.onboarding.start", - model=model, - prompt_hash=digest, - property=property_name, - prompt_chars=len(prompt), - ) - - last_error: Exception | None = None - for attempt in range(1, max_attempts + 1): - start = time.perf_counter() - try: - genai = _configure_client() - gen_model = genai.GenerativeModel(model) - response = await asyncio.wait_for( - asyncio.to_thread( - gen_model.generate_content, - prompt, - generation_config={"temperature": 0.2}, - ), - timeout=timeout_s, - ) - latency_ms = (time.perf_counter() - start) * 1000 - text = (response.text or "").strip() - usage = getattr(response, "usage_metadata", None) - log.info( - "gemini.onboarding.ok", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - prompt_tokens=getattr(usage, "prompt_token_count", None), - completion_tokens=getattr(usage, "candidates_token_count", None), - chars=len(text), - ) - if text: - return text - last_error = RuntimeError("empty response") - except GeminiUnavailable: - raise - except Exception as exc: # noqa: BLE001 — broad retry policy for drafting - last_error = exc - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "gemini.onboarding.retry", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - if attempt < max_attempts: - await asyncio.sleep(0.4 * attempt) - - raise GeminiUnavailable( - f"draft_onboarding_briefing failed after {max_attempts} attempts: {last_error!r}" - ) diff --git a/backend/services/imap_poller.py b/backend/services/imap_poller.py index fa3da18..b84f44c 100644 --- a/backend/services/imap_poller.py +++ b/backend/services/imap_poller.py @@ -1,7 +1,7 @@ """IMAP inbox poller. -Polls the configured mailbox every tick (APScheduler, ~10s per KEYSTONE -Phase 1). Each new message becomes an ``email`` event, idempotent on +Polls the configured mailbox every tick (APScheduler, ~10s). Each new +message becomes an ``email`` event, idempotent on ``Message-ID`` so replaying the inbox after a restart is safe. """ @@ -21,20 +21,10 @@ log = structlog.get_logger(__name__) -def _imap_configured() -> bool: - """Return True when IMAP env is real enough to attempt a connection.""" +def is_configured() -> bool: + """True when IMAP host, user and a real password are set.""" s = get_settings() - configured = bool( - s.imap_host and s.imap_user and s.imap_password - ) and s.imap_password != "replace-me" - - log.info( - "imap.config.check", - host=s.imap_host, - user=s.imap_user, - configured=configured, - ) - return configured + return bool(s.imap_host and s.imap_user and s.imap_password) and s.imap_password != "replace-me" def _flatten_body(msg: Message) -> str: @@ -43,13 +33,11 @@ def _flatten_body(msg: Message) -> str: parts: list[str] = [] for part in msg.walk(): if part.get_content_type() == "text/plain" and not part.is_multipart(): - payload = part.get_payload(decode=True) or b"" + payload = part.get_payload(decode=True) + if not isinstance(payload, bytes): + continue try: - parts.append( - payload.decode( - part.get_content_charset() or "utf-8", "replace" - ) - ) + parts.append(payload.decode(part.get_content_charset() or "utf-8", "replace")) except LookupError: parts.append(payload.decode("utf-8", "replace")) if parts: @@ -57,9 +45,7 @@ def _flatten_body(msg: Message) -> str: payload = msg.get_payload(decode=True) or b"" if isinstance(payload, bytes): - return payload.decode( - msg.get_content_charset() or "utf-8", "replace" - ).strip() + return payload.decode(msg.get_content_charset() or "utf-8", "replace").strip() return str(payload) @@ -113,11 +99,12 @@ async def _ingest(message_id: str, raw: bytes) -> bool: async def poll_once() -> int: """Fetch new messages once.""" - log.info("imap.poll.start") - - if not _imap_configured(): - log.warning("imap.skip", reason="not_configured") + if not is_configured(): + # The scheduler only registers this job when IMAP is configured, so + # reaching here means a manual call; nothing to report. + log.debug("imap.skip", reason="not_configured") return 0 + log.debug("imap.poll.start") settings = get_settings() inserted = 0 @@ -180,4 +167,4 @@ async def poll_once() -> int: return 0 log.info("imap.poll.done", inserted=inserted) - return inserted \ No newline at end of file + return inserted diff --git a/backend/services/lang.py b/backend/services/lang.py index d17e8e3..7359263 100644 --- a/backend/services/lang.py +++ b/backend/services/lang.py @@ -29,7 +29,7 @@ def detect_language(text: str) -> str: Defaults to :data:`DEFAULT_LANG` when the text is too short or detection fails. We also pin a deterministic seed so two runs of - the eval pick the same language label for the same input — + the eval pick the same language label for the same input, because ``langdetect`` is non-deterministic by default. """ if not text or len(text) < MIN_DETECT_CHARS: @@ -39,7 +39,7 @@ def detect_language(text: str) -> str: DetectorFactory.seed = 0 code = str(detect(text)).lower() - except Exception as exc: # noqa: BLE001 — collapse to default on any error + except Exception as exc: # noqa: BLE001 (collapse to default on any error) log.debug("lang.detect_failed", error=str(exc)) return DEFAULT_LANG if code in {"de", "en"}: diff --git a/backend/services/llm/__init__.py b/backend/services/llm/__init__.py new file mode 100644 index 0000000..b301992 --- /dev/null +++ b/backend/services/llm/__init__.py @@ -0,0 +1,93 @@ +"""LLM access for every feature, behind one provider interface. + +``LLM_PROVIDER`` selects the backend (``gemini``, the default, or +``pioneer``). :func:`get_provider` returns it when its API key is set and +``None`` otherwise; features then use their deterministic fallback (rule-based +extraction, template drafts, a briefing notice) or, for Ask and reply +drafting, answer 503 with :func:`not_configured_message`. There is no silent +cross-provider fallback: the configured provider is the one that runs. +""" + +from __future__ import annotations + +import structlog + +from backend.config import get_settings +from backend.services.llm.base import ( + JsonCompletion, + LLMNotConfiguredError, + LLMProvider, + LLMUnavailableError, +) +from backend.services.llm.extraction import ExtractionResult +from backend.services.llm.gemini import GeminiProvider +from backend.services.llm.pioneer import PioneerProvider + +log = structlog.get_logger(__name__) + +_PROVIDERS: dict[str, type[GeminiProvider] | type[PioneerProvider]] = { + "gemini": GeminiProvider, + "pioneer": PioneerProvider, +} +_KEY_FOR = {"gemini": "GEMINI_API_KEY", "pioneer": "PIONEER_API_KEY"} + + +def get_provider() -> LLMProvider | None: + """The configured provider, or ``None`` when its API key is missing.""" + provider = _PROVIDERS[get_settings().llm_provider]() + return provider if provider.is_configured() else None + + +def require_provider() -> LLMProvider: + """Like :func:`get_provider`, but raise :class:`LLMNotConfiguredError` instead of ``None``.""" + provider = get_provider() + if provider is None: + raise LLMNotConfiguredError(not_configured_message()) + return provider + + +def not_configured_message() -> str: + """Explain which variable is missing, suitable for an API error body.""" + selected = get_settings().llm_provider + return ( + f"No LLM provider is configured: LLM_PROVIDER={selected} requires " + f"{_KEY_FOR[selected]}. Set it (or choose another provider with LLM_PROVIDER)." + ) + + +def log_configuration() -> None: + """Log the LLM setup once at startup, so missing keys are visible without per-event noise.""" + settings = get_settings() + provider = get_provider() + if provider is not None: + log.info("llm.provider", provider=provider.name, model=provider.model) + return + others = [name for name, cls in _PROVIDERS.items() if name != settings.llm_provider] + configured_others = [name for name in others if _PROVIDERS[name]().is_configured()] + log.warning( + "llm.provider.not_configured", + provider=settings.llm_provider, + missing=_KEY_FOR[settings.llm_provider], + effect=( + "rule-based extraction, template signal drafts, semantic check skipped, " + "briefing notice; Ask and reply drafting return 503" + ), + hint=( + f"{', '.join(configured_others)} is configured; set LLM_PROVIDER to use it" + if configured_others + else None + ), + ) + + +__all__ = [ + "ExtractionResult", + "JsonCompletion", + "LLMNotConfiguredError", + "LLMProvider", + "LLMUnavailableError", + "get_provider", + "log_configuration", + "not_configured_message", + "require_provider", +] diff --git a/backend/services/llm/base.py b/backend/services/llm/base.py new file mode 100644 index 0000000..0b5d97a --- /dev/null +++ b/backend/services/llm/base.py @@ -0,0 +1,179 @@ +"""Provider-neutral LLM interface. + +Every feature that calls a model (extraction, signal drafting, onboarding +briefings, Ask, reply drafting, the semantic validator) depends on +:class:`LLMProvider`, never on a vendor SDK. A provider offers three calls: + +- :meth:`LLMProvider.extract_facts`: the extraction prompt and schema shared by + all providers (``backend.services.llm.extraction``), returning an + :class:`~backend.services.llm.extraction.ExtractionResult`. +- :meth:`LLMProvider.complete_json`: a system and user prompt in, one parsed + JSON object out. +- :meth:`LLMProvider.complete_text`: a prompt in, plain text out. + +Failures are reported as :class:`LLMUnavailableError`; :class:`LLMNotConfiguredError` is +the subclass for "no API key for the selected provider". Callers treat either +as a reason to use their deterministic fallback, so a missing or failing +provider degrades features instead of breaking them. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import re +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, runtime_checkable + +import structlog + +if TYPE_CHECKING: + from backend.services.llm.extraction import ExtractionResult + +log = structlog.get_logger(__name__) + +T = TypeVar("T") + +#: Backoff between retry attempts is ``RETRY_BACKOFF_S * attempt``. +RETRY_BACKOFF_S = 0.4 + + +class LLMUnavailableError(RuntimeError): + """No usable provider, or every attempt failed. Callers should fall back.""" + + +class LLMNotConfiguredError(LLMUnavailableError): + """The selected provider has no API key configured.""" + + +@dataclass(frozen=True) +class JsonCompletion: + """A parsed JSON response plus the metadata worth logging.""" + + data: dict[str, Any] + model: str + latency_ms: float + prompt_tokens: int | None = None + completion_tokens: int | None = None + + +@runtime_checkable +class LLMProvider(Protocol): + """What every LLM backend implements.""" + + #: Short identifier, also written to ``ExtractionResult.source``. + name: str + #: Model used for every call. + model: str + + def is_configured(self) -> bool: + """True when the provider has the credentials it needs.""" + ... + + async def extract_facts( + self, + *, + property_name: str, + current_context_excerpt: str, + source: str, + raw_content: str, + lang: str, + ) -> ExtractionResult: + """Run the shared extraction prompt (3 attempts, 60 s timeout each).""" + ... + + async def complete_json( + self, + *, + system: str, + prompt: str, + temperature: float = 0.1, + timeout_s: float = 30.0, + max_attempts: int = 1, + ) -> JsonCompletion: + """Return the model's reply parsed as one JSON object.""" + ... + + async def complete_text( + self, + *, + system: str | None, + prompt: str, + temperature: float = 0.2, + timeout_s: float = 45.0, + max_attempts: int = 2, + ) -> str: + """Return the model's reply as plain text (non-empty).""" + ... + + +def prompt_hash(prompt: str) -> str: + """Short, stable identifier for a prompt, for correlating log lines.""" + return hashlib.sha1(prompt.encode("utf-8")).hexdigest()[:10] + + +_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL) + + +def parse_json_payload(text: str) -> dict[str, Any]: + """Parse one JSON object from a model reply. + + Accepts a bare object, an object inside a Markdown code fence, or an object + surrounded by stray prose, because models occasionally add either even when + asked for JSON only. + """ + text = text.strip() + try: + parsed = json.loads(text) + except json.JSONDecodeError: + fence = _JSON_FENCE_RE.search(text) + if fence: + parsed = json.loads(fence.group(1)) + else: + start, end = text.find("{"), text.rfind("}") + if start < 0 or end <= start: + raise ValueError(f"no JSON object in response: {text[:200]!r}") from None + parsed = json.loads(text[start : end + 1]) + if not isinstance(parsed, dict): + raise ValueError(f"expected a JSON object, got {type(parsed).__name__}") + return parsed + + +async def with_retries( + call: Callable[[], Awaitable[T]], + *, + max_attempts: int, + timeout_s: float, + event: str, + **log_fields: Any, +) -> T: + """Run ``call`` with a per-attempt timeout and linear backoff. + + Each attempt is bounded by ``asyncio.wait_for``: a provider call that never + returns (observed with a blocking SDK call) becomes a timeout instead of a + frozen worker. :class:`LLMNotConfiguredError` is raised immediately; any other + error is logged and retried. After the last attempt the error is wrapped in + :class:`LLMUnavailableError`. + """ + last_error: Exception | None = None + for attempt in range(1, max_attempts + 1): + start = time.perf_counter() + try: + return await asyncio.wait_for(call(), timeout=timeout_s) + except LLMNotConfiguredError: + raise + except Exception as exc: # noqa: BLE001 - any provider error is retryable + last_error = exc + log.warning( + f"{event}.retry", + attempt=attempt, + latency_ms=round((time.perf_counter() - start) * 1000, 1), + error=str(exc)[:300], + **log_fields, + ) + if attempt < max_attempts: + await asyncio.sleep(RETRY_BACKOFF_S * attempt) + raise LLMUnavailableError(f"{event} failed after {max_attempts} attempt(s): {last_error!r}") diff --git a/backend/services/llm/extraction.py b/backend/services/llm/extraction.py new file mode 100644 index 0000000..99da522 --- /dev/null +++ b/backend/services/llm/extraction.py @@ -0,0 +1,206 @@ +"""Extraction contract shared by every LLM provider. + +The JSON schema, the per-language prompt templates +(``backend/services/prompts/extraction_{de,en}.md``) and the controlled field +vocabulary (``field_vocabulary.json``) live here so that Gemini, Pioneer and +any future provider extract into exactly the same ``(section, field)`` space, +and the eval harness measures one contract regardless of backend. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from functools import lru_cache +from pathlib import Path +from typing import Any + +# Gemini's ``response_schema`` accepts a strict OpenAPI 3.0 subset: +# ``minimum`` / ``maximum`` / ``$defs`` are rejected. We lean on the +# prompt to enforce the [0, 1] range on ``confidence``; downstream code +# clamps it defensively. +EXTRACTION_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "category": { + "type": "string", + "enum": [ + "maintenance", + "lease", + "payment", + "complaint", + "compliance", + "tenant_change", + "owner_communication", + "other", + ], + }, + "priority": {"type": "string", "enum": ["low", "medium", "high", "urgent"]}, + "facts_to_update": { + "type": "array", + "items": { + "type": "object", + "properties": { + "section": { + "type": "string", + "enum": [ + "overview", + "tenants", + "lease", + "maintenance", + "financials", + "compliance", + "activity", + "patterns", + "building_financials", + "building_maintenance", + "building_compliance", + "liegenschaft_financials", + "liegenschaft_maintenance", + "liegenschaft_compliance", + ], + }, + "field": {"type": "string"}, + "value": {"type": "string"}, + "confidence": {"type": "number"}, + }, + "required": ["section", "field", "value", "confidence"], + }, + }, + "uncertain": { + "type": "array", + "description": ( + "Items the extractor noticed but cannot commit to as a fact. " + "Vague mentions, ambiguous references, hearsay, second-hand " + "claims. The user prefers 'I noticed something unclear' over " + "'I think this is true.'" + ), + "items": { + "type": "object", + "properties": { + "observation": { + "type": "string", + "description": "What was noticed, quoted or near-quoted from the source.", + }, + "hypothesis": { + "type": "string", + "description": ( + "Optional candidate value if there is one; leave " + "empty when only the observation matters." + ), + }, + "reason_uncertain": { + "type": "string", + "description": ( + "Why this didn't become a fact " + "(vague, hearsay, ambiguous reference, ...)." + ), + }, + "relevant_section": { + "type": "string", + "description": ( + "Best guess at the section a future fact would land " + "in (overview, tenants, lease, maintenance, financials, " + "compliance, building_*, liegenschaft_*)." + ), + }, + "relevant_field": { + "type": "string", + "description": "Optional best guess at the field name.", + }, + }, + "required": ["observation", "reason_uncertain", "relevant_section"], + }, + }, + "summary": {"type": "string"}, + }, + "required": ["category", "priority", "facts_to_update", "summary"], +} + +_PROMPT_DIR = Path(__file__).resolve().parents[1] / "prompts" +_VOCABULARY_PATH = _PROMPT_DIR / "field_vocabulary.json" + + +@lru_cache(maxsize=4) +def _load_prompt_template(lang: str) -> str: + """Read the per-language Markdown prompt with file-system caching.""" + name = "extraction_de.md" if lang == "de" else "extraction_en.md" + path = _PROMPT_DIR / name + if not path.is_file(): + raise FileNotFoundError(f"missing prompt template: {path}") + return path.read_text(encoding="utf-8") + + +@lru_cache(maxsize=1) +def _vocabulary_block() -> str: + """Render the JSON vocabulary into a markdown block for the prompts. + + Result example:: + + - **maintenance** (4 fields) + - `open_water_damage`: e.g. "Wasserschaden + Schimmel WE 32 …" + - `key_lost`: e.g. "Mieter WE 02 hat Wohnungsschlüssel verloren …" + - `defective_window`: e.g. "Küchenfenster WE 50 schließt nicht mehr …" + - **financials** (3 fields) + - … + """ + if not _VOCABULARY_PATH.is_file(): + return "_(no vocabulary file present: emit conservative field names)_" + payload = json.loads(_VOCABULARY_PATH.read_text(encoding="utf-8")) + lines: list[str] = [] + for section, body in payload.get("sections", {}).items(): + fields = body.get("fields", []) + if not fields: + lines.append(f"- **{section}** (0 fields: section reserved)") + continue + lines.append(f"- **{section}** ({len(fields)} fields)") + for f in fields: + example = "" + if f.get("examples"): + example = f': e.g. "{f["examples"][0]}"' + lines.append(f" - `{f['name']}`{example}") + return "\n".join(lines) + + +def render_extraction_prompt( + *, + property_name: str, + current_context_excerpt: str, + source: str, + raw_content: str, + lang: str, +) -> str: + """Fill the per-language extraction template with event and context.""" + template = _load_prompt_template(lang) + return template.format( + property_name=property_name, + current_context_excerpt=current_context_excerpt or "(no prior context)", + source=source, + raw_content=raw_content, + vocabulary_block=_vocabulary_block(), + ) + + +@dataclass +class ExtractionResult: + """Structured output of one extraction, from any provider or the rules. + + ``source`` names what produced it (``gemini``, ``pioneer`` or ``rule``). + Token counts let callers such as ``eval.runner`` attribute spend; they are + ``None`` when no model was called. + """ + + category: str + priority: str + facts_to_update: list[dict[str, Any]] + summary: str + # Items noticed but not committed to as facts. Each entry: + # {observation, hypothesis?, reason_uncertain, relevant_section, + # relevant_field?}. Empty when nothing needed flagging. + uncertain: list[dict[str, Any]] = field(default_factory=list) + raw: dict[str, Any] = field(default_factory=dict) + latency_ms: float = 0.0 + model: str = "" + source: str = "rule" + prompt_tokens: int | None = None + completion_tokens: int | None = None diff --git a/backend/services/llm/gemini.py b/backend/services/llm/gemini.py new file mode 100644 index 0000000..5b2120b --- /dev/null +++ b/backend/services/llm/gemini.py @@ -0,0 +1,226 @@ +"""Google Gemini provider. + +Uses the ``google-generativeai`` SDK. Its ``generate_content`` call is +blocking, so every call runs in a worker thread under the shared retry helper's +timeout; a hung request becomes a retryable timeout rather than a frozen +event loop. Extraction passes ``EXTRACTION_SCHEMA`` as ``response_schema`` so +Gemini returns schema-conformant JSON natively. + +Model: ``GEMINI_PRO_MODEL`` for every call. ``GEMINI_FLASH_MODEL`` is used only +by the PDF document-type classifier (``connectors/document_type.py``), which +calls :func:`configure_client` directly. +""" + +from __future__ import annotations + +import asyncio +import json +import time +from typing import Any + +import structlog + +from backend.config import get_settings +from backend.services.llm.base import ( + JsonCompletion, + LLMNotConfiguredError, + parse_json_payload, + prompt_hash, + with_retries, +) +from backend.services.llm.extraction import ( + EXTRACTION_SCHEMA, + ExtractionResult, + render_extraction_prompt, +) + +log = structlog.get_logger(__name__) + +#: Per-attempt deadline for extraction: above the 37 s p99 observed during the +#: email backfill, low enough that a silent hang fails one attempt quickly. +EXTRACT_TIMEOUT_S = 60.0 +EXTRACT_ATTEMPTS = 3 + + +def is_configured() -> bool: + """True when a usable ``GEMINI_API_KEY`` is set.""" + key = get_settings().gemini_api_key.strip() + return bool(key) and key not in {"replace-me", "disabled"} + + +def configure_client() -> Any: + """Import and configure ``google.generativeai``; raise if no key is set.""" + if not is_configured(): + raise LLMNotConfiguredError("GEMINI_API_KEY is not set") + import google.generativeai as genai # noqa: PLC0415 - optional at import time + + genai.configure(api_key=get_settings().gemini_api_key) # type: ignore[attr-defined] + return genai + + +def _usage(response: Any) -> tuple[int | None, int | None]: + usage = getattr(response, "usage_metadata", None) + return ( + getattr(usage, "prompt_token_count", None), + getattr(usage, "candidates_token_count", None), + ) + + +class GeminiProvider: + """:class:`~backend.services.llm.base.LLMProvider` backed by Gemini.""" + + name = "gemini" + + def __init__(self, model: str | None = None) -> None: + self.model = model or get_settings().gemini_pro_model + + def is_configured(self) -> bool: + return is_configured() + + async def _generate( + self, + prompt: str, + *, + system: str | None, + generation_config: dict[str, Any], + ) -> Any: + genai = configure_client() + kwargs: dict[str, Any] = {"system_instruction": system} if system else {} + model = genai.GenerativeModel(self.model, **kwargs) + return await asyncio.to_thread( + model.generate_content, prompt, generation_config=generation_config + ) + + async def extract_facts( + self, + *, + property_name: str, + current_context_excerpt: str, + source: str, + raw_content: str, + lang: str, + ) -> ExtractionResult: + prompt = render_extraction_prompt( + property_name=property_name, + current_context_excerpt=current_context_excerpt, + source=source, + raw_content=raw_content, + lang=lang, + ) + digest = prompt_hash(prompt) + log.info("gemini.extract.start", model=self.model, prompt_hash=digest, lang=lang) + + async def call() -> ExtractionResult: + start = time.perf_counter() + response = await self._generate( + prompt, + system=None, + generation_config={ + "response_mime_type": "application/json", + "response_schema": EXTRACTION_SCHEMA, + "temperature": 0.1, + }, + ) + latency_ms = (time.perf_counter() - start) * 1000 + text = (response.text or "").strip() + data = json.loads(text) if text else {} + prompt_tokens, completion_tokens = _usage(response) + log.info( + "gemini.extract.ok", + model=self.model, + prompt_hash=digest, + latency_ms=round(latency_ms, 1), + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + fact_count=len(data.get("facts_to_update", [])), + ) + return ExtractionResult( + category=data.get("category", "other"), + priority=data.get("priority", "low"), + facts_to_update=list(data.get("facts_to_update", [])), + uncertain=list(data.get("uncertain", [])), + summary=data.get("summary", ""), + raw=data, + latency_ms=latency_ms, + model=self.model, + source=self.name, + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + ) + + return await with_retries( + call, + max_attempts=EXTRACT_ATTEMPTS, + timeout_s=EXTRACT_TIMEOUT_S, + event="gemini.extract", + model=self.model, + prompt_hash=digest, + ) + + async def complete_json( + self, + *, + system: str, + prompt: str, + temperature: float = 0.1, + timeout_s: float = 30.0, + max_attempts: int = 1, + ) -> JsonCompletion: + digest = prompt_hash(prompt) + + async def call() -> JsonCompletion: + start = time.perf_counter() + response = await self._generate( + prompt, + system=system, + generation_config={ + "response_mime_type": "application/json", + "temperature": temperature, + }, + ) + prompt_tokens, completion_tokens = _usage(response) + return JsonCompletion( + data=parse_json_payload(response.text or ""), + model=self.model, + latency_ms=(time.perf_counter() - start) * 1000, + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + ) + + return await with_retries( + call, + max_attempts=max_attempts, + timeout_s=timeout_s, + event="gemini.complete_json", + model=self.model, + prompt_hash=digest, + ) + + async def complete_text( + self, + *, + system: str | None, + prompt: str, + temperature: float = 0.2, + timeout_s: float = 45.0, + max_attempts: int = 2, + ) -> str: + digest = prompt_hash(prompt) + + async def call() -> str: + response = await self._generate( + prompt, system=system, generation_config={"temperature": temperature} + ) + text = (response.text or "").strip() + if not text: + raise ValueError("empty response") + return text + + return await with_retries( + call, + max_attempts=max_attempts, + timeout_s=timeout_s, + event="gemini.complete_text", + model=self.model, + prompt_hash=digest, + ) diff --git a/backend/services/llm/pioneer.py b/backend/services/llm/pioneer.py new file mode 100644 index 0000000..0b2a631 --- /dev/null +++ b/backend/services/llm/pioneer.py @@ -0,0 +1,212 @@ +"""Pioneer provider: an OpenAI-compatible chat-completions gateway. + +Calls ``POST {PIONEER_BASE_URL}/chat/completions`` over ``httpx`` with +``PIONEER_API_KEY``; the model is ``PIONEER_MODEL`` (default +``claude-sonnet-4-6``). The gateway has no native schema enforcement, so +extraction embeds ``EXTRACTION_SCHEMA`` in the user message, requests +``response_format=json_object``, and parses defensively. +""" + +from __future__ import annotations + +import json +import time +from typing import Any + +import httpx +import structlog + +from backend.config import get_settings +from backend.services.llm.base import ( + JsonCompletion, + LLMNotConfiguredError, + parse_json_payload, + prompt_hash, + with_retries, +) +from backend.services.llm.extraction import ( + EXTRACTION_SCHEMA, + ExtractionResult, + render_extraction_prompt, +) + +log = structlog.get_logger(__name__) + +PIONEER_BASE_URL = "https://api.pioneer.ai/v1" +EXTRACT_TIMEOUT_S = 60.0 +EXTRACT_ATTEMPTS = 3 + +_EXTRACTION_SYSTEM = ( + "You are a structured-extraction worker for a property-management " + "platform. Respond with a single JSON object that strictly matches " + "the schema described in the user message. No prose, no markdown " + "fences, only the JSON object." +) + + +def is_configured() -> bool: + """True when a usable ``PIONEER_API_KEY`` is set.""" + key = get_settings().pioneer_api_key.strip() + return bool(key) and key not in {"replace-me", "disabled"} + + +class PioneerProvider: + """:class:`~backend.services.llm.base.LLMProvider` backed by the Pioneer gateway.""" + + name = "pioneer" + + def __init__(self, model: str | None = None) -> None: + self.model = model or get_settings().pioneer_model + + def is_configured(self) -> bool: + return is_configured() + + async def _chat( + self, + *, + system: str | None, + prompt: str, + temperature: float, + json_mode: bool, + ) -> tuple[str, dict[str, Any], float]: + """One chat-completions request; returns (content, usage, latency_ms).""" + if not is_configured(): + raise LLMNotConfiguredError("PIONEER_API_KEY is not set") + messages = [{"role": "system", "content": system}] if system else [] + messages.append({"role": "user", "content": prompt}) + body: dict[str, Any] = { + "model": self.model, + "messages": messages, + "temperature": temperature, + } + if json_mode: + body["response_format"] = {"type": "json_object"} + start = time.perf_counter() + async with httpx.AsyncClient(timeout=None) as client: + response = await client.post( + f"{PIONEER_BASE_URL}/chat/completions", + headers={"Authorization": f"Bearer {get_settings().pioneer_api_key}"}, + json=body, + ) + response.raise_for_status() + payload = response.json() + content = payload["choices"][0]["message"].get("content") or "" + return content, payload.get("usage") or {}, (time.perf_counter() - start) * 1000 + + async def extract_facts( + self, + *, + property_name: str, + current_context_excerpt: str, + source: str, + raw_content: str, + lang: str, + ) -> ExtractionResult: + prompt = render_extraction_prompt( + property_name=property_name, + current_context_excerpt=current_context_excerpt, + source=source, + raw_content=raw_content, + lang=lang, + ) + user_message = ( + prompt + "\n\nReturn one JSON object matching this schema (top-level keys: " + "category, priority, facts_to_update[], uncertain[], summary):\n" + + json.dumps(EXTRACTION_SCHEMA, indent=2) + ) + digest = prompt_hash(prompt) + log.info("pioneer.extract.start", model=self.model, prompt_hash=digest, lang=lang) + + async def call() -> ExtractionResult: + content, usage, latency_ms = await self._chat( + system=_EXTRACTION_SYSTEM, prompt=user_message, temperature=0.1, json_mode=True + ) + data = parse_json_payload(content) + log.info( + "pioneer.extract.ok", + model=self.model, + prompt_hash=digest, + latency_ms=round(latency_ms, 1), + prompt_tokens=usage.get("prompt_tokens"), + completion_tokens=usage.get("completion_tokens"), + fact_count=len(data.get("facts_to_update", [])), + ) + return ExtractionResult( + category=data.get("category", "other"), + priority=data.get("priority", "low"), + facts_to_update=list(data.get("facts_to_update", [])), + uncertain=list(data.get("uncertain", [])), + summary=data.get("summary", ""), + raw=data, + latency_ms=latency_ms, + model=self.model, + source=self.name, + prompt_tokens=usage.get("prompt_tokens"), + completion_tokens=usage.get("completion_tokens"), + ) + + return await with_retries( + call, + max_attempts=EXTRACT_ATTEMPTS, + timeout_s=EXTRACT_TIMEOUT_S, + event="pioneer.extract", + model=self.model, + prompt_hash=digest, + ) + + async def complete_json( + self, + *, + system: str, + prompt: str, + temperature: float = 0.1, + timeout_s: float = 30.0, + max_attempts: int = 1, + ) -> JsonCompletion: + async def call() -> JsonCompletion: + content, usage, latency_ms = await self._chat( + system=system, prompt=prompt, temperature=temperature, json_mode=True + ) + return JsonCompletion( + data=parse_json_payload(content), + model=self.model, + latency_ms=latency_ms, + prompt_tokens=usage.get("prompt_tokens"), + completion_tokens=usage.get("completion_tokens"), + ) + + return await with_retries( + call, + max_attempts=max_attempts, + timeout_s=timeout_s, + event="pioneer.complete_json", + model=self.model, + prompt_hash=prompt_hash(prompt), + ) + + async def complete_text( + self, + *, + system: str | None, + prompt: str, + temperature: float = 0.2, + timeout_s: float = 45.0, + max_attempts: int = 2, + ) -> str: + async def call() -> str: + content, _usage, _latency = await self._chat( + system=system, prompt=prompt, temperature=temperature, json_mode=False + ) + text = content.strip() + if not text: + raise ValueError("empty response") + return text + + return await with_retries( + call, + max_attempts=max_attempts, + timeout_s=timeout_s, + event="pioneer.complete_text", + model=self.model, + prompt_hash=prompt_hash(prompt), + ) diff --git a/backend/services/onboarding.py b/backend/services/onboarding.py index 2493b70..7e6f51b 100644 --- a/backend/services/onboarding.py +++ b/backend/services/onboarding.py @@ -1,24 +1,24 @@ -"""Onboarding view — the "first-time read" surface for a property. +"""Onboarding view: the "first-time read" surface for a property. A property manager who's never seen this property before should be able to read this document in 60 seconds and know: 1. Stammdaten + how much we already know (deterministic). -2. What's open right now — uncertainties, pending rejections, active +2. What's open right now: uncertainties, pending rejections, active maintenance facts (deterministic). 3. A 5-to-7-bullet briefing of the last 12 months, hard-instructed to - call out gaps rather than invent (Gemini Pro). -4. What patterns the validator and inbox have noticed — recurring + call out gaps rather than invent (the configured LLM provider). +4. What patterns the validator and inbox have noticed: recurring conflicts, watch-out items (deterministic). -5. Where to look for more — pointer index by section with the most +5. Where to look for more: pointer index by section with the most recent source events linked. Section 3 is the only LLM call. It is cached on ``properties.metadata.onboarding`` keyed by a hash of the last-fact / last-uncertainty / last-rejection timestamps so a re-read is free; mutating any of those three invalidates the cache on the -next render. We do *not* hook regen onto fact insertion — that would -push Gemini latency onto the write path. Read-time regen is the +next render. We do *not* hook regen onto fact insertion; that would +push LLM latency onto the write path. Read-time regen is the right trade. """ @@ -28,7 +28,7 @@ import json from dataclasses import dataclass from datetime import UTC, datetime -from typing import Any +from typing import Any, Literal from uuid import UUID import structlog @@ -40,13 +40,53 @@ _fetch_current_facts, _fetch_open_uncertainties, ) -from backend.services import gemini, pioneer_llm +from backend.services.llm import LLMUnavailableError, get_provider log = structlog.get_logger(__name__) +# The briefing is written for the operator, who reads English, so it is +# always English even when the property's sources and headings are German. +BRIEFING_SYSTEM_HINT = ( + "You are briefing a property-management operator who is opening a " + "property for the first time. Plain prose only: no markdown formatting " + "(**, *, _, `, #), no headings, no markdown links. Output one bullet per " + "line, prefix each with '- '. Always write in English regardless of the " + "source-event language." +) + +BRIEFING_PROMPT = """You are briefing a property manager who is reading {property_name} +for the first time. + +Write 5 to 7 bullets. Each bullet is ≤ 25 words. The reader has 60 seconds. + +HARD RULES: +- Honesty over completeness. If a key piece is missing, say so plainly. + Use the literal prefix "Gap:" and name what is missing. +- Do not invent dates, amounts, names, or facts. If something is uncertain, + treat it as a gap, not as a fact. +- Lead with what is operationally relevant TODAY (open issues, recent + changes), then context, then risks to watch. +- Plain text, no headings, no preamble like "Here is the briefing". +- One bullet per line, prefix each with "- ". +- Write in English. + +CURRENT FACTS (authoritative, already validated): +{facts_summary} + +OPEN UNCERTAINTIES (noticed but not committed; call out as gaps): +{uncertainties_summary} + +VALIDATOR REJECTIONS (proposed but rejected; note as known conflicts): +{rejections_summary} + +RECENT EVENT ACTIVITY (last 12 months, by category): +{activity_summary} + +Write the bullets now.""" + # How many bullets per "open issues" / "watch out" subsection. The -# briefing aims for 60-second readability — if the deterministic +# briefing aims for 60-second readability; if the deterministic # sections sprawl, the reader bounces. Ship-quality, not coverage. TOP_N: int = 3 TOP_N_PATTERNS: int = 5 @@ -89,9 +129,7 @@ class _RejectionRow: # ----------------------------------------------------------------------------- -async def _load_header( - session: AsyncSession, property_id: UUID -) -> _PropertyHeader | None: +async def _load_header(session: AsyncSession, property_id: UUID) -> _PropertyHeader | None: """Load property + building + Liegenschaft in one round-trip.""" row = ( await session.execute( @@ -121,17 +159,13 @@ async def _load_header( metadata=dict(row.metadata or {}), building_id=UUID(str(row.building_id)) if row.building_id else None, building_address=row.building_address, - liegenschaft_id=( - UUID(str(row.liegenschaft_id)) if row.liegenschaft_id else None - ), + liegenschaft_id=(UUID(str(row.liegenschaft_id)) if row.liegenschaft_id else None), liegenschaft_name=row.liegenschaft_name, ) -async def _load_pending_rejections( - session: AsyncSession, property_id: UUID -) -> list[_RejectionRow]: - """Pending or needs_review rejections — newest first.""" +async def _load_pending_rejections(session: AsyncSession, property_id: UUID) -> list[_RejectionRow]: + """Pending or needs_review rejections, newest first.""" rows = ( await session.execute( text( @@ -186,9 +220,7 @@ async def _load_activity_histogram( return {str(r.source): int(r.n) for r in rows} -async def _load_total_event_count( - session: AsyncSession, property_id: UUID -) -> int: +async def _load_total_event_count(session: AsyncSession, property_id: UUID) -> int: """All-time event count for the property.""" row = ( await session.execute( @@ -199,9 +231,7 @@ async def _load_total_event_count( return int(row.n) if row else 0 -async def _load_active_tenant( - session: AsyncSession, property_id: UUID -) -> str | None: +async def _load_active_tenant(session: AsyncSession, property_id: UUID) -> str | None: """Best-guess current tenant name from the tenants table.""" row = ( await session.execute( @@ -222,7 +252,7 @@ async def _load_active_tenant( async def _last_mutation_timestamps( session: AsyncSession, property_id: UUID ) -> tuple[datetime | None, datetime | None, datetime | None]: - """Newest fact / uncertainty / rejection timestamps — feeds the cache key.""" + """Newest fact / uncertainty / rejection timestamps; feeds the cache key.""" row = ( await session.execute( text( @@ -269,9 +299,7 @@ def _cache_key( return hashlib.sha1("|".join(parts).encode("utf-8")).hexdigest()[:16] -async def _read_cache( - session: AsyncSession, property_id: UUID, key: str -) -> str | None: +async def _read_cache(session: AsyncSession, property_id: UUID, key: str) -> str | None: """Return the cached briefing text if its key matches ``key``.""" row = ( await session.execute( @@ -367,18 +395,14 @@ def _render_property_in_60s( if header.address: parent_bits.append(f"_{header.address}_") if header.building_address: - parent_bits.append( - f"Building: {header.building_address}" - ) + parent_bits.append(f"Building: {header.building_address}") if header.liegenschaft_name: parent_bits.append(f"WEG: {header.liegenschaft_name}") if parent_bits: lines.append(" · ".join(parent_bits)) lines.append("") - section_title = ( - "## Property in 60 seconds" if lang == "en" else "## Objekt in 60 Sekunden" - ) + section_title = "## Property in 60 seconds" if lang == "en" else "## Objekt in 60 Sekunden" lines.append(section_title) lines.append("") @@ -440,18 +464,14 @@ def _render_open_issues( *, lang: str, ) -> list[str]: - """Top-N open issues, deterministic — ordered by impact + recency.""" + """Top-N open issues, deterministic, ordered by impact + recency.""" title = "## Open issues right now" if lang == "en" else "## Offene Punkte jetzt" lines: list[str] = [title, ""] rendered_anything = False if active_maintenance: - sub = ( - "### Active maintenance" - if lang == "en" - else "### Aktuelle Wartung" - ) + sub = "### Active maintenance" if lang == "en" else "### Aktuelle Wartung" lines.append(sub) lines.append("") for fact in active_maintenance[:TOP_N]: @@ -466,11 +486,7 @@ def _render_open_issues( rendered_anything = True if uncertainties: - sub = ( - "### Top open uncertainties" - if lang == "en" - else "### Top offene Unsicherheiten" - ) + sub = "### Top open uncertainties" if lang == "en" else "### Top offene Unsicherheiten" lines.append(sub) lines.append("") for u in uncertainties[:TOP_N]: @@ -478,7 +494,7 @@ def _render_open_issues( if len(obs) > 140: obs = obs[:137].rstrip() + "…" lines.append( - f"- _{u.section}_ — {obs} " + f"- _{u.section}_: {obs} " f"(_{u.reason_uncertain}_) " f"[source: event {u.event_id}](/events/{u.event_id}/source)" ) @@ -486,11 +502,7 @@ def _render_open_issues( rendered_anything = True if rejections: - sub = ( - "### Pending rejections" - if lang == "en" - else "### Offene Ablehnungen" - ) + sub = "### Pending rejections" if lang == "en" else "### Offene Ablehnungen" lines.append(sub) lines.append("") for r in rejections[:TOP_N]: @@ -498,8 +510,8 @@ def _render_open_issues( if len(value) > 80: value = value[:77].rstrip() + "…" lines.append( - f"- `{r.constraint_name}` — proposed " - f"**{r.section}.{r.field}** = `{value}` — {r.reason} " + f"- `{r.constraint_name}`: proposed " + f"**{r.section}.{r.field}** = `{value}`: {r.reason} " f"[source: event {r.event_id}](/events/{r.event_id}/source)" ) lines.append("") @@ -507,9 +519,9 @@ def _render_open_issues( if not rendered_anything: msg = ( - "No open issues — nothing waiting on you right now." + "No open issues: nothing waiting on you right now." if lang == "en" - else "Keine offenen Punkte — derzeit nichts zu erledigen." + else "Keine offenen Punkte: derzeit nichts zu erledigen." ) lines.append(f"_{msg}_") lines.append("") @@ -522,34 +534,26 @@ def _render_watch_out_for( *, lang: str, ) -> list[str]: - """Recurring patterns — what to keep an eye on.""" + """Recurring patterns: what to keep an eye on.""" title = "## Watch out for" if lang == "en" else "## Worauf achten" lines: list[str] = [title, ""] constraint_counts: dict[str, int] = {} for r in rejections_all: - constraint_counts[r.constraint_name] = constraint_counts.get( - r.constraint_name, 0 - ) + 1 - constraint_top = sorted( - constraint_counts.items(), key=lambda x: -x[1] - )[:TOP_N_PATTERNS] + constraint_counts[r.constraint_name] = constraint_counts.get(r.constraint_name, 0) + 1 + constraint_top = sorted(constraint_counts.items(), key=lambda x: -x[1])[:TOP_N_PATTERNS] constraint_top = [c for c in constraint_top if c[1] >= 2] section_unc_counts: dict[str, int] = {} for u in uncertainties: section_unc_counts[u.section] = section_unc_counts.get(u.section, 0) + 1 - unc_top = sorted( - section_unc_counts.items(), key=lambda x: -x[1] - )[:TOP_N_PATTERNS] + unc_top = sorted(section_unc_counts.items(), key=lambda x: -x[1])[:TOP_N_PATTERNS] unc_top = [u for u in unc_top if u[1] >= 2] rendered_anything = False if constraint_top: sub = ( - "### Recurring rejected updates" - if lang == "en" - else "### Häufig abgelehnte Änderungen" + "### Recurring rejected updates" if lang == "en" else "### Häufig abgelehnte Änderungen" ) lines.append(sub) lines.append("") @@ -567,15 +571,15 @@ def _render_watch_out_for( lines.append(sub) lines.append("") for section, n in unc_top: - lines.append(f"- _{section}_ — {n} unresolved") + lines.append(f"- _{section}_: {n} unresolved") lines.append("") rendered_anything = True if not rendered_anything: msg = ( - "No recurring patterns yet — too little history to draw conclusions." + "No recurring patterns yet: too little history to draw conclusions." if lang == "en" - else "Noch keine wiederkehrenden Muster — zu wenig Historie." + else "Noch keine wiederkehrenden Muster: zu wenig Historie." ) lines.append(f"_{msg}_") lines.append("") @@ -589,11 +593,7 @@ def _render_pointer_index( lang: str, ) -> list[str]: """Per-section pointer index: where to look for more on each topic.""" - title = ( - "## Where to look for more" - if lang == "en" - else "## Wo mehr zu finden ist" - ) + title = "## Where to look for more" if lang == "en" else "## Wo mehr zu finden ist" lines: list[str] = [title, ""] by_section: dict[str, list[Any]] = {} @@ -601,9 +601,9 @@ def _render_pointer_index( by_section.setdefault(f.section, []).append(f) if not by_section: msg = ( - "No facts on file yet — once events stream in, source links will appear here." + "No facts on file yet: once events stream in, source links will appear here." if lang == "en" - else "Noch keine Fakten — sobald Ereignisse einlaufen, erscheinen hier Quellverweise." + else "Noch keine Fakten: sobald Ereignisse einlaufen, erscheinen hier Quellverweise." ) lines.append(f"_{msg}_") lines.append("") @@ -628,24 +628,20 @@ def _render_pointer_index( if lang == "en" else f"Hausansicht öffnen ({header.building_address or header.building_id})" ) - lines.append( - f"- [{link_label}](/buildings/{header.building_id}/markdown)" - ) + lines.append(f"- [{link_label}](/buildings/{header.building_id}/markdown)") if header.liegenschaft_id: link_label = ( f"Open WEG view ({header.liegenschaft_name or header.liegenschaft_id})" if lang == "en" else f"WEG-Ansicht öffnen ({header.liegenschaft_name or header.liegenschaft_id})" ) - lines.append( - f"- [{link_label}](/liegenschaften/{header.liegenschaft_id}/markdown)" - ) + lines.append(f"- [{link_label}](/liegenschaften/{header.liegenschaft_id}/markdown)") lines.append("") return lines # ----------------------------------------------------------------------------- -# Section renderer — Gemini Pro briefing (cached) +# Section renderer: LLM briefing (cached) # ----------------------------------------------------------------------------- @@ -655,18 +651,13 @@ def _summarise_facts(facts: list[Any], *, max_lines: int = 30) -> str: return "" bullets: list[str] = [] for f in facts[:max_lines]: - bullets.append( - f"- {f.section}.{f.field} = {f.value} " - f"(confidence {f.confidence:.2f})" - ) + bullets.append(f"- {f.section}.{f.field} = {f.value} (confidence {f.confidence:.2f})") if len(facts) > max_lines: bullets.append(f"- (+{len(facts) - max_lines} more facts not shown)") return "\n".join(bullets) -def _summarise_uncertainties( - uncertainties: list[UncertaintyRow], *, max_lines: int = 12 -) -> str: +def _summarise_uncertainties(uncertainties: list[UncertaintyRow], *, max_lines: int = 12) -> str: """Compact bullet list of open uncertainties for the briefing prompt.""" if not uncertainties: return "" @@ -675,19 +666,13 @@ def _summarise_uncertainties( obs = u.observation if len(obs) > 160: obs = obs[:157].rstrip() + "…" - bullets.append( - f"- {u.section}: {obs} (reason: {u.reason_uncertain})" - ) + bullets.append(f"- {u.section}: {obs} (reason: {u.reason_uncertain})") if len(uncertainties) > max_lines: - bullets.append( - f"- (+{len(uncertainties) - max_lines} more uncertainties not shown)" - ) + bullets.append(f"- (+{len(uncertainties) - max_lines} more uncertainties not shown)") return "\n".join(bullets) -def _summarise_rejections( - rejections: list[_RejectionRow], *, max_lines: int = 8 -) -> str: +def _summarise_rejections(rejections: list[_RejectionRow], *, max_lines: int = 8) -> str: """Compact bullet list of pending rejections for the briefing prompt.""" if not rejections: return "" @@ -697,8 +682,7 @@ def _summarise_rejections( if len(value) > 80: value = value[:77].rstrip() + "…" bullets.append( - f"- {r.constraint_name}: rejected {r.section}.{r.field}={value} " - f"(reason: {r.reason})" + f"- {r.constraint_name}: rejected {r.section}.{r.field}={value} (reason: {r.reason})" ) return "\n".join(bullets) @@ -708,11 +692,24 @@ def _summarise_activity(activity: dict[str, int]) -> str: if not activity: return "" return "\n".join( - f"- {src}: {n} events" - for src, n in sorted(activity.items(), key=lambda x: -x[1]) + f"- {src}: {n} events" for src, n in sorted(activity.items(), key=lambda x: -x[1]) ) +# Where the "Key context" briefing came from: written by the LLM on this +# request, read from the metadata cache, or not available (no provider +# configured or reachable; the section is then a one-line note). +BriefingSource = Literal["llm", "cache", "unavailable"] + + +@dataclass(frozen=True) +class OnboardingDocument: + """The rendered onboarding markdown and where its briefing came from.""" + + markdown: str + briefing_source: BriefingSource + + async def _render_key_context( session: AsyncSession, property_id: UUID, @@ -724,8 +721,8 @@ async def _render_key_context( *, lang: str, cache_key: str, -) -> list[str]: - """The Gemini-Pro 5–7 bullet briefing, cached on properties.metadata.""" +) -> tuple[list[str], BriefingSource]: + """The LLM-written 5 to 7 bullet briefing, cached on ``properties.metadata``.""" title = ( "## Key context (last 12 months)" if lang == "en" @@ -739,7 +736,7 @@ async def _render_key_context( property_id=str(property_id), cache_key=cache_key, ) - return [title, "", cached, ""] + return [title, "", cached, ""], "cache" facts_summary = _summarise_facts(facts) uncertainties_summary = _summarise_uncertainties(uncertainties) @@ -747,62 +744,40 @@ async def _render_key_context( activity_summary = _summarise_activity(activity) briefing: str | None = None - - # Pioneer (Claude) is the primary path. The briefing always renders - # in English — Pioneer's prompt enforces that regardless of how the - # source events are written. - if pioneer_llm.is_available(): - try: - briefing = await pioneer_llm.draft_onboarding_briefing( - property_name=header.name, - facts_summary=facts_summary, - uncertainties_summary=uncertainties_summary, - rejections_summary=rejections_summary, - activity_summary=activity_summary, - ) - except pioneer_llm.PioneerUnavailable as exc: - log.warning( - "onboarding.briefing.pioneer_unavailable", - property_id=str(property_id), - error=str(exc)[:200], - ) - - # Gemini is a fallback for environments where Pioneer is missing. - if briefing is None and gemini.is_available(): + provider = get_provider() + if provider is not None: + prompt = BRIEFING_PROMPT.format( + property_name=header.name, + facts_summary=facts_summary or "(no facts yet)", + uncertainties_summary=uncertainties_summary or "(none)", + rejections_summary=rejections_summary or "(none)", + activity_summary=activity_summary or "(no recent activity)", + ) try: - briefing = await gemini.draft_onboarding_briefing( - property_name=header.name, - facts_summary=facts_summary, - uncertainties_summary=uncertainties_summary, - rejections_summary=rejections_summary, - activity_summary=activity_summary, - lang="en", - ) - except gemini.GeminiUnavailable as exc: + briefing = await provider.complete_text(system=BRIEFING_SYSTEM_HINT, prompt=prompt) + except LLMUnavailableError as exc: log.warning( - "onboarding.briefing.gemini_unavailable", + "onboarding.briefing.llm_unavailable", property_id=str(property_id), + provider=provider.name, error=str(exc)[:200], ) if briefing is None: msg = ( - "Briefing unavailable — neither Pioneer nor Gemini is " - "reachable. All deterministic sections above are still " - "complete." + "Briefing unavailable: no LLM provider is configured or reachable. " + "All deterministic sections above are still complete." ) - return [title, "", msg, ""] + return [title, "", msg, ""], "unavailable" - await _write_cache( - session, property_id, key=cache_key, briefing=briefing - ) + await _write_cache(session, property_id, key=cache_key, briefing=briefing) log.info( "onboarding.briefing.generated", property_id=str(property_id), cache_key=cache_key, chars=len(briefing), ) - return [title, "", briefing, ""] + return [title, "", briefing, ""], "llm" # ----------------------------------------------------------------------------- @@ -810,20 +785,25 @@ async def _render_key_context( # ----------------------------------------------------------------------------- -async def render_onboarding( +async def render_onboarding(session: AsyncSession, property_id: UUID) -> str: + """Render the onboarding markdown; see :func:`render_onboarding_document`.""" + return (await render_onboarding_document(session, property_id)).markdown + + +async def render_onboarding_document( session: AsyncSession, property_id: UUID -) -> str: +) -> OnboardingDocument: """Render the full onboarding markdown for a property. Five sections, in reading order: - 1. Property in 60 seconds — stammdaten, what we know. - 2. Open issues right now — uncertainties, rejections, active maintenance. - 3. Key context (last 12 months) — Gemini Pro briefing, cached. - 4. Watch out for — recurring patterns. - 5. Where to look for more — pointer index. + 1. Property in 60 seconds: stammdaten, what we know. + 2. Open issues right now: uncertainties, rejections, active maintenance. + 3. Key context (last 12 months): LLM briefing, cached. + 4. Watch out for: recurring patterns. + 5. Where to look for more: pointer index. - Section 3 is the only LLM call; if Gemini is unavailable the + Section 3 is the only LLM call; if no provider is available the section degrades to a one-line note and the rest of the document still renders. Re-rendering is free unless facts / uncertainties / rejections have moved since the last render (cache key invalidates). @@ -834,7 +814,7 @@ async def render_onboarding( # Briefings always render in English regardless of the property's # source-event majority. The briefing is read by the Hausverwaltung - # operator (English-speaking team), not by the tenant — keeping the + # operator (English-speaking team), not by the tenant; keeping the # output language fixed avoids confusing a new property manager who # opens a German-only property file and gets a German briefing. # The original event-language detection still drives the property @@ -847,9 +827,7 @@ async def render_onboarding( activity = await _load_activity_histogram(session, property_id) total_events = await _load_total_event_count(session, property_id) active_tenant = await _load_active_tenant(session, property_id) - last_fact, last_unc, last_rej = await _last_mutation_timestamps( - session, property_id - ) + last_fact, last_unc, last_rej = await _last_mutation_timestamps(session, property_id) cache_key = _cache_key(last_fact, last_unc, last_rej) @@ -884,30 +862,23 @@ async def render_onboarding( lang=lang, ) ) - lines.extend( - _render_open_issues( - uncertainties, rejections, active_maintenance, lang=lang - ) - ) - lines.extend( - await _render_key_context( - session, - property_id, - header, - facts, - uncertainties, - rejections, - activity, - lang=lang, - cache_key=cache_key, - ) + lines.extend(_render_open_issues(uncertainties, rejections, active_maintenance, lang=lang)) + key_context, briefing_source = await _render_key_context( + session, + property_id, + header, + facts, + uncertainties, + rejections, + activity, + lang=lang, + cache_key=cache_key, ) + lines.extend(key_context) # "Watch out for" wants ALL rejections (resolved + pending) for pattern- - # spotting — load a separate cohort for it. + # spotting, so load a separate cohort for it. rejections_all = await _load_all_rejections(session, property_id) - lines.extend( - _render_watch_out_for(rejections_all, uncertainties, lang=lang) - ) + lines.extend(_render_watch_out_for(rejections_all, uncertainties, lang=lang)) lines.extend(_render_pointer_index(facts, header, lang=lang)) log.info( @@ -919,14 +890,15 @@ async def render_onboarding( rejections=len(rejections), events=total_events, cache_key=cache_key, + briefing_source=briefing_source, + ) + return OnboardingDocument( + markdown="\n".join(lines).rstrip() + "\n", briefing_source=briefing_source ) - return "\n".join(lines).rstrip() + "\n" -async def _load_all_rejections( - session: AsyncSession, property_id: UUID -) -> list[_RejectionRow]: - """Every rejection ever recorded — pattern recognition wants the full set.""" +async def _load_all_rejections(session: AsyncSession, property_id: UUID) -> list[_RejectionRow]: + """Every rejection ever recorded; pattern recognition wants the full set.""" rows = ( await session.execute( text( diff --git a/backend/services/pioneer_llm.py b/backend/services/pioneer_llm.py deleted file mode 100644 index 98fb13d..0000000 --- a/backend/services/pioneer_llm.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Pioneer LLM gateway — Anthropic Claude via OpenAI-compatible API. - -Drop-in alternative to :func:`backend.services.gemini.extract_facts` for -Phase 11 Step 1 vocab-fix verification while Gemini Pro quota is exhausted. - -NOT wired into the production extractor (``backend.pipeline.extractor``). -Phase 8 Step 5 pinned Gemini Pro for production extraction; switching the -production path requires a DECISIONS.md entry plus an eval re-run to -confirm precision did not regress. - -Naming note: ``backend.services.pioneer`` already exists as the Phase 5 -approval-learning layer (a different partner subsystem with the same -sponsor name). This module is the LLM gateway and is intentionally a -separate file so callers ``import`` only what they need. - -The extraction schema, prompt template, and ``ExtractionResult`` dataclass -are reused verbatim from :mod:`backend.services.gemini` so callers swap -one import. The OpenAI-compatible Pioneer gateway is reached over plain -HTTPS using ``httpx``; no new dependency needed. -""" - -from __future__ import annotations - -import asyncio -import hashlib -import json -import re -import time -from typing import Any - -import httpx -import structlog - -from backend.config import get_settings -from backend.services.gemini import ( - EXTRACTION_SCHEMA, - ExtractionResult, - render_extraction_prompt, -) - -log = structlog.get_logger(__name__) - - -PIONEER_BASE_URL = "https://api.pioneer.ai/v1" -PIONEER_DEFAULT_MODEL = "claude-sonnet-4-6" -PIONEER_EXTRACT_TIMEOUT_S: float = 60.0 - - -class PioneerUnavailable(RuntimeError): - """Raised when Pioneer cannot be used (no key, transport error, hard error).""" - - -def _prompt_hash(prompt: str) -> str: - return hashlib.sha1(prompt.encode("utf-8")).hexdigest()[:10] - - -def is_available() -> bool: - """Return True iff a usable Pioneer API key is configured.""" - key = get_settings().pioneer_api_key.strip() - return bool(key) and key not in {"replace-me", "disabled"} - - -_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL) - - -def _parse_json_payload(text: str) -> dict[str, Any]: - """Best-effort JSON extraction from a model response. - - The OpenAI-compatible gateway honors ``response_format=json_object`` for - Anthropic models, but a defensive parser keeps the verifier working - even if the gateway echoes a markdown fence or a leading apology line. - """ - text = text.strip() - try: - return json.loads(text) - except json.JSONDecodeError: - pass - fence = _JSON_FENCE_RE.search(text) - if fence: - return json.loads(fence.group(1)) - start = text.find("{") - end = text.rfind("}") - if start >= 0 and end > start: - return json.loads(text[start : end + 1]) - raise ValueError(f"could not parse JSON from response (head 200): {text[:200]!r}") - - -SYSTEM_HINT = ( - "You are a structured-extraction worker for a property-management " - "platform. Respond with a single JSON object that strictly matches " - "the schema described in the user message. No prose, no markdown " - "fences — only the JSON object." -) - - -async def extract_facts( - *, - property_name: str, - current_context_excerpt: str, - source: str, - raw_content: str, - lang: str = "en", - model_name: str | None = None, - max_attempts: int = 3, - timeout_s: float = PIONEER_EXTRACT_TIMEOUT_S, -) -> ExtractionResult: - """Run the canonical extraction prompt against Claude via Pioneer. - - Same call shape as :func:`backend.services.gemini.extract_facts` so - callers can swap one import. Returns an :class:`ExtractionResult` with - ``source="pioneer"`` — the verifier already routes its cost-ledger - branch on this field, so Pioneer calls do not charge the Gemini - ledger. - """ - settings = get_settings() - if not is_available(): - raise PioneerUnavailable("PIONEER_API_KEY not set") - - model = model_name or PIONEER_DEFAULT_MODEL - prompt = render_extraction_prompt( - property_name=property_name, - current_context_excerpt=current_context_excerpt, - source=source, - raw_content=raw_content, - lang=lang, - ) - digest = _prompt_hash(prompt) - schema_block = ( - "\n\nReturn one JSON object matching this schema " - "(top-level keys: category, priority, facts_to_update[], " - "uncertain[], summary):\n" - + json.dumps(EXTRACTION_SCHEMA, indent=2) - ) - user_message = prompt + schema_block - - headers = { - "Authorization": f"Bearer {settings.pioneer_api_key}", - "Content-Type": "application/json", - } - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": SYSTEM_HINT}, - {"role": "user", "content": user_message}, - ], - "temperature": 0.1, - "response_format": {"type": "json_object"}, - } - - log.info( - "pioneer_llm.extract.start", - model=model, - prompt_hash=digest, - source=source, - lang=lang, - prompt_chars=len(user_message), - ) - - last_error: Exception | None = None - for attempt in range(1, max_attempts + 1): - start = time.perf_counter() - try: - async with httpx.AsyncClient(timeout=timeout_s) as client: - response = await client.post( - f"{PIONEER_BASE_URL}/chat/completions", - headers=headers, - json=body, - ) - response.raise_for_status() - payload = response.json() - latency_ms = (time.perf_counter() - start) * 1000 - choice = payload["choices"][0] - text = choice["message"].get("content") or "" - data = _parse_json_payload(text) - usage = payload.get("usage") or {} - log.info( - "pioneer_llm.extract.ok", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - prompt_tokens=usage.get("prompt_tokens"), - completion_tokens=usage.get("completion_tokens"), - fact_count=len(data.get("facts_to_update", [])), - ) - return ExtractionResult( - category=data.get("category", "other"), - priority=data.get("priority", "low"), - facts_to_update=list(data.get("facts_to_update", [])), - uncertain=list(data.get("uncertain", [])), - summary=data.get("summary", ""), - raw=data, - latency_ms=latency_ms, - model=model, - source="pioneer", - prompt_tokens=usage.get("prompt_tokens"), - completion_tokens=usage.get("completion_tokens"), - ) - except PioneerUnavailable: - raise - except Exception as exc: # noqa: BLE001 — retry on any transient error - last_error = exc - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "pioneer_llm.extract.retry", - model=model, - prompt_hash=digest, - attempt=attempt, - latency_ms=round(latency_ms, 1), - error=str(exc), - ) - if attempt < max_attempts: - await asyncio.sleep(0.4 * attempt) - - raise PioneerUnavailable( - f"extract_facts failed after {max_attempts} attempts: {last_error!r}" - ) - - -# ----------------------------------------------------------------------------- -# Onboarding briefing -# ----------------------------------------------------------------------------- - - -_BRIEFING_SYSTEM_HINT = ( - "You are briefing a Hausverwaltung operator who is opening a property " - "for the first time. Plain prose only — no markdown formatting " - "(**, *, _, `, #), no headings, no markdown links. Output one bullet " - "per line, prefix each with '- '. Always write in English regardless " - "of the source-event language; the operator team reads English." -) - - -_BRIEFING_PROMPT = """You are briefing a property manager who is reading {property_name} for the first time. - -Write 5 to 7 bullets. Each bullet is at most 25 words. The reader has 60 seconds. - -HARD RULES -- Honesty over completeness. If a key piece is missing, say so plainly. Use the literal prefix "Gap:" and name what is missing. -- Do not invent dates, amounts, names, or facts. If something is uncertain, treat it as a gap, not as a fact. -- Lead with what is operationally relevant TODAY (open issues, recent changes), then context, then risks to watch. -- Plain prose, no markdown formatting, no preamble like "Here is the briefing". -- One bullet per line, prefix each with "- ". -- Always write in English, even when the underlying facts are in German. You may quote short German phrases (proper nouns, "Kaltmiete", street names) verbatim, but the surrounding prose is English. - -CURRENT FACTS (authoritative — already validated) -{facts_summary} - -OPEN UNCERTAINTIES (noticed but not committed — call out as gaps) -{uncertainties_summary} - -VALIDATOR REJECTIONS (proposed but rejected — note as known conflicts) -{rejections_summary} - -RECENT EVENT ACTIVITY (last 12 months, by category) -{activity_summary} - -Write the bullets now.""" - - -async def draft_onboarding_briefing( - *, - property_name: str, - facts_summary: str, - uncertainties_summary: str, - rejections_summary: str, - activity_summary: str, - model_name: str | None = None, - max_attempts: int = 2, - timeout_s: float = 45.0, -) -> str: - """Render the onboarding briefing bullets via Claude (Pioneer). - - Always English regardless of source-event language — the briefing - is read by the operator, not the tenant. Returns the bullet block - as plain text (one ``- `` line per bullet, no markdown formatting, - no surrounding heading). - - Raises :class:`PioneerUnavailable` if every attempt fails so the - caller can fall back to a deterministic placeholder. - """ - settings = get_settings() - if not is_available(): - raise PioneerUnavailable("PIONEER_API_KEY not set") - - model = model_name or PIONEER_DEFAULT_MODEL - no_facts = "(no facts yet)" - none_label = "(none)" - no_activity = "(no recent activity)" - prompt = _BRIEFING_PROMPT.format( - property_name=property_name, - facts_summary=facts_summary or no_facts, - uncertainties_summary=uncertainties_summary or none_label, - rejections_summary=rejections_summary or none_label, - activity_summary=activity_summary or no_activity, - ) - digest = _prompt_hash(prompt) - - headers = { - "Authorization": f"Bearer {settings.pioneer_api_key}", - "Content-Type": "application/json", - } - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": _BRIEFING_SYSTEM_HINT}, - {"role": "user", "content": prompt}, - ], - "temperature": 0.2, - } - - last_error: Exception | None = None - for attempt in range(1, max_attempts + 1): - start = time.perf_counter() - try: - log.info( - "pioneer_llm.briefing.start", - model=model, - attempt=attempt, - prompt_hash=digest, - prompt_chars=len(prompt), - ) - async with httpx.AsyncClient(timeout=timeout_s) as client: - response = await client.post( - f"{PIONEER_BASE_URL}/chat/completions", - headers=headers, - json=body, - ) - response.raise_for_status() - payload = response.json() - text = payload["choices"][0]["message"].get("content") or "" - text = text.strip() - if not text: - raise PioneerUnavailable("empty briefing response") - latency_ms = (time.perf_counter() - start) * 1000 - log.info( - "pioneer_llm.briefing.ok", - model=model, - latency_ms=round(latency_ms, 1), - attempt=attempt, - chars=len(text), - prompt_hash=digest, - ) - return text - except PioneerUnavailable: - raise - except Exception as exc: # noqa: BLE001 — retry on transient errors - last_error = exc - latency_ms = (time.perf_counter() - start) * 1000 - log.warning( - "pioneer_llm.briefing.retry", - model=model, - attempt=attempt, - latency_ms=round(latency_ms, 1), - error=str(exc)[:200], - prompt_hash=digest, - ) - if attempt < max_attempts: - await asyncio.sleep(0.4 * attempt) - - raise PioneerUnavailable( - f"draft_onboarding_briefing failed after {max_attempts} attempts: " - f"{last_error!r}" - ) diff --git a/backend/services/prompts/__init__.py b/backend/services/prompts/__init__.py index 52bf393..c7a98f8 100644 --- a/backend/services/prompts/__init__.py +++ b/backend/services/prompts/__init__.py @@ -1 +1 @@ -"""Prompt templates loaded by :mod:`backend.services.gemini`.""" +"""Extraction prompts and field vocabulary, read by ``backend.services.llm.extraction``.""" diff --git a/backend/services/prompts/extraction_de.md b/backend/services/prompts/extraction_de.md index fc59fec..1ab9c4e 100644 --- a/backend/services/prompts/extraction_de.md +++ b/backend/services/prompts/extraction_de.md @@ -1,4 +1,4 @@ -# Keystone Extraction — Deutsch +# Keystone Extraction: Deutsch Du extrahierst strukturierte Fakten aus einem Ereignis innerhalb eines Property-Management-Kontextsystems. @@ -50,15 +50,15 @@ Liefere ein einziges JSON-Objekt im vorgegebenen Schema. Ohne Kommentar, ohne Ma ### Unsicherheits-Regeln (`uncertain[]`) -Wenn dir etwas potentiell Relevantes auffällt, du dich aber **nicht auf einen konkreten Fakt festlegen kannst** (vage Andeutung, mehrdeutige Referenz, Hörensagen, "ich denke wir sollten mal...", "vielleicht", "irgendwann"), trage es in `uncertain[]` ein — **nicht** in `facts_to_update`. +Wenn dir etwas potentiell Relevantes auffällt, du dich aber **nicht auf einen konkreten Fakt festlegen kannst** (vage Andeutung, mehrdeutige Referenz, Hörensagen, "ich denke wir sollten mal...", "vielleicht", "irgendwann"), trage es in `uncertain[]` ein: **nicht** in `facts_to_update`. - **Nicht erfinden. Nicht raten.** Der Nutzer bevorzugt klar "Ich habe etwas Unklares bemerkt" gegenüber falsch-zuversichtlichem "Ich denke das ist so". - Format: `{{observation, hypothesis?, reason_uncertain, relevant_section, relevant_field?}}`. - - `observation` — was wurde beobachtet (möglichst nahe am Originaltext zitiert). - - `hypothesis` — falls ein Kandidatenwert erkennbar ist; sonst leer lassen. - - `reason_uncertain` — kurz auf Deutsch, warum es kein Fakt geworden ist (z. B. "vage Andeutung ohne Zeitbezug", "Eigentümer äußert Absicht, kein Beschluss", "Hörensagen über andere Einheit"). - - `relevant_section` — beste Schätzung der Section, in der ein zukünftiger Fakt landen würde. - - `relevant_field` — optional, beste Schätzung des Feldnamens. + - `observation`: was wurde beobachtet (möglichst nahe am Originaltext zitiert). + - `hypothesis`: falls ein Kandidatenwert erkennbar ist; sonst leer lassen. + - `reason_uncertain`: kurz auf Deutsch, warum es kein Fakt geworden ist (z. B. "vage Andeutung ohne Zeitbezug", "Eigentümer äußert Absicht, kein Beschluss", "Hörensagen über andere Einheit"). + - `relevant_section`: beste Schätzung der Section, in der ein zukünftiger Fakt landen würde. + - `relevant_field`: optional, beste Schätzung des Feldnamens. - Beispiele für `uncertain[]`-Kandidaten: "Wir sollten mal über die Miete reden", "vielleicht später kündigen", "Nachbar hat angeblich ein Problem", "irgendwann müssen wir das Dach machen". Liefere nur valides JSON, das dem Schema entspricht. diff --git a/backend/services/prompts/extraction_en.md b/backend/services/prompts/extraction_en.md index 41ba9f4..67570c6 100644 --- a/backend/services/prompts/extraction_en.md +++ b/backend/services/prompts/extraction_en.md @@ -1,4 +1,4 @@ -# Keystone Extraction — English +# Keystone Extraction: English You extract structured facts from an event in a property-management context system. The dataset is German Hausverwaltung; some events appear in English. @@ -50,15 +50,15 @@ Return a single JSON object matching the response schema. No commentary, no Mark ### Uncertainty rules (`uncertain[]`) -If you noticed something potentially relevant but **cannot commit to a specific fact** (vague mention, ambiguous reference, hearsay, "we should at some point…", "maybe", "I think"), put it in `uncertain[]` — **not** in `facts_to_update`. +If you noticed something potentially relevant but **cannot commit to a specific fact** (vague mention, ambiguous reference, hearsay, "we should at some point…", "maybe", "I think"), put it in `uncertain[]`: **not** in `facts_to_update`. - **Do not invent. Do not guess.** The user prefers a clear "I noticed something unclear" over a confidently wrong "I think this is true." - Shape: `{{observation, hypothesis?, reason_uncertain, relevant_section, relevant_field?}}`. - - `observation` — what was noticed (quoted or near-quoted from the source). - - `hypothesis` — optional candidate value if one is implied; leave empty otherwise. - - `reason_uncertain` — short reason why this didn't become a fact (e.g. "vague mention without timeframe", "owner expresses intent, no decision", "hearsay about another unit"). - - `relevant_section` — your best guess at the section a future fact would land in. - - `relevant_field` — optional best guess at the field name. + - `observation`: what was noticed (quoted or near-quoted from the source). + - `hypothesis`: optional candidate value if one is implied; leave empty otherwise. + - `reason_uncertain`: short reason why this didn't become a fact (e.g. "vague mention without timeframe", "owner expresses intent, no decision", "hearsay about another unit"). + - `relevant_section`: your best guess at the section a future fact would land in. + - `relevant_field`: optional best guess at the field name. - Examples of `uncertain[]` candidates: "We should talk about rent at some point", "might give notice later", "the neighbour allegedly has an issue", "we'll need to do the roof eventually". Return only valid JSON matching the schema. diff --git a/backend/services/prompts/field_vocabulary.json b/backend/services/prompts/field_vocabulary.json index 65a12c4..de18229 100644 --- a/backend/services/prompts/field_vocabulary.json +++ b/backend/services/prompts/field_vocabulary.json @@ -168,7 +168,7 @@ { "name": "brandschutz_request", "examples": [ - "Bauamt Berlin-Mitte fordert aktuellen Brandschutznachweis für Immanuelkirchstraße 26." + "Bauamt Berlin-Mitte fordert aktuellen Brandschutznachweis für Musterstraße 26." ] } ] diff --git a/backend/services/replay.py b/backend/services/replay.py index 894ed47..3e9aef1 100644 --- a/backend/services/replay.py +++ b/backend/services/replay.py @@ -1,13 +1,13 @@ -"""Phase 10 Step 10.2 — sequential replay engine. +"""Sequential replay engine. The replay reads existing events for a property and re-streams them -through the live pipeline at a configurable speed multiplier so the -demo can show the file building itself in real time. Idempotency is -guaranteed by the existing ``events.UNIQUE (source, source_ref)`` -constraint plus the optional ``reset_property`` flag — the engine -isn't generating new events; it's re-running already-ingested ones -through the worker after deleting the property's facts and -uncertainty rows. +through the live pipeline at a configurable speed multiplier so an +operator can watch the property file rebuild itself event by event in +real time. Idempotency is guaranteed by the existing +``events.UNIQUE (source, source_ref)`` constraint plus the optional +``reset_property`` flag: the engine isn't generating new events; it's +re-running already-ingested ones through the worker after deleting the +property's facts and uncertainty rows. Key design calls: @@ -18,12 +18,12 @@ - **scheduled_pauses** is a list of ``{at_seconds, message}`` items. When the elapsed seconds since stream start cross a checkpoint the engine halts, sets ``status='paused'``, and emits a control event. - The operator (or the demo wrapper) calls ``resume_run`` to continue. + The operator (or a scripted driver) calls ``resume_run`` to continue. - **In-process state** lives in :data:`_RUNS` keyed by run id. Postgres carries the *durable* state for the UI; ``_RUNS`` carries the asyncio event handles a single process needs to pause/resume. Restarting the API server cancels in-flight runs cleanly because - the asyncio handles vanish — durable rows then sit at + the asyncio handles vanish; durable rows then sit at ``status='running'`` until an operator manually flips them to ``stopped``. - **Live worker reuse.** Each event re-streamed runs through @@ -53,7 +53,7 @@ # Each ``scheduled_pauses`` entry has this shape; we keep validation -# loose here so future demo scripts can stuff extra hint fields the UI +# loose here so future replay scripts can stuff extra hint fields the UI # wants to render without a migration. _REQUIRED_PAUSE_KEYS = frozenset({"at_seconds", "message"}) @@ -139,7 +139,7 @@ async def start_run( "total": total, }, ) - ).first() + ).one() await session.commit() run_id: UUID = row.id @@ -183,7 +183,7 @@ async def start_run( async def pause_run(run_id: UUID) -> dict[str, Any]: - """Pause a running stream — the worker loop will block until resume.""" + """Pause a running stream; the worker loop will block until resume.""" handle = _RUNS.get(run_id) if handle is not None: handle.pause_event.clear() @@ -214,7 +214,7 @@ async def stop_run(run_id: UUID) -> dict[str, Any]: if handle.task is not None and not handle.task.done(): try: await asyncio.wait_for(handle.task, timeout=5.0) - except asyncio.TimeoutError: + except TimeoutError: handle.task.cancel() await _set_status(run_id, "stopped") await _publish_control(run_id, "replay.stopped", {"reason": "operator"}) @@ -411,9 +411,7 @@ async def _set_status( await session.commit() -async def _publish_control( - run_id: UUID, kind: str, payload: dict[str, Any] -) -> None: +async def _publish_control(run_id: UUID, kind: str, payload: dict[str, Any]) -> None: """Push a control message onto the event bus so SSE subscribers see it. Replay control events fan out under the property's bus channel @@ -460,9 +458,7 @@ async def _drive_run( while pauses_pending and pauses_pending[0]["at_seconds"] <= elapsed: pause = pauses_pending.pop(0) handle.pause_event.clear() - await _set_status( - handle.run_id, "paused", with_paused_at=True - ) + await _set_status(handle.run_id, "paused", with_paused_at=True) await _publish_control( handle.run_id, "replay.scheduled_pause", @@ -506,17 +502,15 @@ async def _drive_run( # Pace the stream: target one historical day per real # second when speed=10 (i.e. 86,400× faster than wall-clock - # would replay the archive). For Buena's data the + # would replay the archive). For the sample dataset the # inter-event budget collapses to "as fast as the worker # runs" because the archive spans months but the Pro # extractor takes ~12 s per call. We add a small floor so # the SSE stream doesn't flood the client. await asyncio.sleep(max(0.02, 1.0 / handle.speed_multiplier)) - except Exception as exc: # noqa: BLE001 — surface the failure cleanly + except Exception as exc: # noqa: BLE001 (surface the failure cleanly) log.exception("replay.drive.error", run_id=str(handle.run_id)) - await _set_status( - handle.run_id, "failed", last_error=f"{type(exc).__name__}: {exc}"[:500] - ) + await _set_status(handle.run_id, "failed", last_error=f"{type(exc).__name__}: {exc}"[:500]) await _publish_control( handle.run_id, "replay.failed", diff --git a/backend/services/slack_webhook.py b/backend/services/slack_webhook.py index 5e115c8..d857f7d 100644 --- a/backend/services/slack_webhook.py +++ b/backend/services/slack_webhook.py @@ -13,6 +13,7 @@ import hashlib import hmac import time +from typing import Any import structlog @@ -31,7 +32,7 @@ def verify_signature( ) -> bool: """Return True iff the request is a legitimate Slack delivery. - The function is safe to call with missing secrets / headers — it simply + The function is safe to call with missing secrets / headers; it simply returns ``False``. Callers should respond with HTTP 401 in that case. """ if not signing_secret or not timestamp or not signature: @@ -51,7 +52,7 @@ def verify_signature( return hmac.compare_digest(expected, signature) -def format_slack_event(payload: dict) -> tuple[str, str]: +def format_slack_event(payload: dict[str, Any]) -> tuple[str, str]: """Turn a Slack ``event_callback`` payload into ``(source_ref, raw_content)``. Uses ``{team_id}:{channel}:{ts}`` as the idempotency key and renders a @@ -65,8 +66,5 @@ def format_slack_event(payload: dict) -> tuple[str, str]: user = str(event.get("user", "unknown")) text = str(event.get("text", "")).strip() - raw_content = ( - f"From: Slack user {user} in channel {channel}\n" - f"Subject: Slack message\n\n{text}" - ) + raw_content = f"From: Slack user {user} in channel {channel}\nSubject: Slack message\n\n{text}" return source_ref, raw_content diff --git a/backend/services/tavily.py b/backend/services/tavily.py deleted file mode 100644 index 942837a..0000000 --- a/backend/services/tavily.py +++ /dev/null @@ -1,352 +0,0 @@ -"""Tavily enrichment. - -Phase 2 uses Tavily for **property enrichment on creation** (neighborhood -snapshot, rent benchmarks, relevant regulations). Phase 5 reuses the same -client for the regulation-watcher cron. - -When ``TAVILY_API_KEY`` is absent / placeholder the service runs in an -offline mode that emits a single pre-canned "demo snapshot" event per -property so the 'Updated from web sources' badge always shows in the UI — -this is the Part XII fallback for flaky venue wifi. -""" - -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime, timezone -from typing import Any -from uuid import UUID, uuid4 - -import structlog - -from backend.config import get_settings -from backend.db.session import get_sessionmaker -from backend.pipeline.events import insert_event -from backend.pipeline.materializer import propagate_after_fact_write - -log = structlog.get_logger(__name__) - - -@dataclass(frozen=True) -class TavilyResult: - """Flattened result from Tavily's search API.""" - - title: str - content: str - url: str - - -def _available() -> bool: - """Return True iff a usable Tavily key is configured.""" - key = get_settings().tavily_api_key.strip() - return bool(key) and key not in {"replace-me", "disabled"} - - -async def _search(query: str, *, max_results: int = 3) -> list[TavilyResult]: - """Run a Tavily search; swallow errors and return an empty list on failure.""" - if not _available(): - return [] - try: - from tavily import TavilyClient # noqa: PLC0415 — lazy import - except ImportError as exc: - log.warning("tavily.import_failed", error=str(exc)) - return [] - - try: - client = TavilyClient(api_key=get_settings().tavily_api_key) - raw = client.search(query=query, search_depth="basic", max_results=max_results) - except Exception as exc: # noqa: BLE001 — network / auth / rate limit all collapse here - log.warning("tavily.search_failed", error=str(exc), query=query) - return [] - - out: list[TavilyResult] = [] - for hit in raw.get("results", []) or []: - out.append( - TavilyResult( - title=str(hit.get("title") or "").strip(), - content=str(hit.get("content") or "").strip(), - url=str(hit.get("url") or "").strip(), - ) - ) - log.info("tavily.search", query=query, hits=len(out)) - return out - - -def _offline_snapshot(property_name: str, address: str) -> str: - """Canned enrichment body used when the Tavily key is unavailable. - - Intentionally generic — the goal is the badge, not a lie; the body is - clearly marked as an offline snapshot. - """ - return ( - "Web-sources enrichment (offline snapshot)\n" - f"Property: {property_name} — {address}\n" - "Median 2BR cold rent and Mietspiegel trends referenced from regional\n" - "real-estate indices (Immowelt / Immoscout 2026 Q1 summary).\n" - "Regulatory note: local Mietpreisbremse remains in force; pre-1990\n" - "buildings tracked for annual boiler inspection cadence.\n" - ) - - -def _build_raw_content(property_name: str, address: str, hits: list[TavilyResult]) -> str: - """Format Tavily results into the extractor's expected raw_content shape.""" - lines = [ - "Web-sources enrichment (via Tavily)", - f"Property: {property_name} — {address}", - "", - ] - for hit in hits: - if hit.content: - lines.append(f"- {hit.title}: {hit.content[:400]} [{hit.url}]") - return "\n".join(lines) - - -async def enrich_property(property_id: UUID, name: str, address: str) -> UUID | None: - """Fetch a Tavily snapshot for the property and persist it as a sourced fact set. - - Returns the event id when enrichment wrote new state, ``None`` when the - property already had a Tavily enrichment recorded (idempotency via - ``metadata.tavily_snapshot_id``). The resulting facts are tagged so the - renderer can show the "Updated from web sources" badge next to them. - """ - from sqlalchemy import text # noqa: PLC0415 — kept local to avoid coupling - - query = f"{address} neighborhood rent benchmarks Mietspiegel regulations 2026" - hits = await _search(query, max_results=3) - if hits: - raw_content = _build_raw_content(name, address, hits) - metadata: dict[str, Any] = { - "tavily": True, - "mode": "live", - "query": query, - "hits": [{"title": h.title, "url": h.url} for h in hits], - } - summary_value = hits[0].content[:220].strip() if hits else _offline_snapshot_summary() - else: - raw_content = _offline_snapshot(name, address) - metadata = {"tavily": False, "mode": "offline", "query": query} - summary_value = _offline_snapshot_summary() - - source_ref = f"tavily:{property_id}:{uuid4().hex[:8]}" - factory = get_sessionmaker() - async with factory() as session: - # Idempotency: if any web-source event already exists for this property - # with tavily metadata, don't re-enrich. - already = ( - await session.execute( - text( - """ - SELECT 1 FROM events - WHERE property_id = :pid - AND source = 'web' - AND (metadata->>'tavily')::boolean IS NOT FALSE - AND source_ref LIKE 'tavily:%' - LIMIT 1 - """ - ), - {"pid": property_id}, - ) - ).first() - if already: - log.info("tavily.skip", property_id=str(property_id), reason="already_enriched") - return None - - event_id, inserted = await insert_event( - session, - source="web", - source_ref=source_ref, - raw_content=raw_content, - property_id=property_id, - metadata=metadata, - ) - - # Persist the snapshot as facts so the renderer always has a - # web-sourced row to hang the badge on, and stamp the event as - # processed so the live worker skips re-extraction. - await session.execute( - text( - """ - INSERT INTO facts - (property_id, section, field, value, source_event_id, - confidence, valid_from) - VALUES - (:pid, 'overview', 'market_snapshot', :value, :eid, 0.82, now()), - (:pid, 'compliance', 'regulation_watch', :reg, :eid, 0.78, now()) - """ - ), - { - "pid": property_id, - "eid": event_id, - "value": summary_value, - "reg": ( - "Keystone is watching local regulations via Tavily: " - "Mietpreisbremse status, Mietspiegel adjustments, and " - "any building-code changes affecting this property." - ), - }, - ) - await session.execute( - text( - "UPDATE events SET processed_at = now() WHERE id = :eid" - ), - {"eid": event_id}, - ) - - # Phase 12 — refresh the materialized property file so the - # web-sourced market_snapshot + regulation_watch facts land in - # the cached markdown atomically with the inserts. - await propagate_after_fact_write( - session, - property_id=property_id, - trigger_event_id=event_id, - trigger_summary="Tavily enrichment: market snapshot + regulation watch", - ) - await session.commit() - - log.info( - "tavily.enriched", - property_id=str(property_id), - event_id=str(event_id), - inserted=inserted, - mode=metadata["mode"], - ) - return event_id - - -def _offline_snapshot_summary() -> str: - """One-liner used as a fact value when no Tavily hits are available.""" - return ( - "Regional rent index within Mietspiegel bounds; Mietpreisbremse " - "remains in force in this market (offline snapshot, 2026 Q1)." - ) - - -# ----------------------------------------------------------------------------- -# Regulation watcher (Phase 5 cron) -# ----------------------------------------------------------------------------- - -REGULATION_QUERIES: list[str] = [ - "Berlin Mietpreisbremse 2026 update", - "Germany Mietspiegel adjustment 2026", - "Berlin rent cap decision 2026", - "Hamburg Bezirksamt facade inspection rules 2026", - "Munich Mietpreisbremse extension 2026", -] - -OFFLINE_REGULATION_HEADLINES: list[tuple[str, str]] = [ - ( - "Mietpreisbremse extended through 2029 — federal cabinet", - "Bundesregierung confirms Mietpreisbremse extension through 2029; " - "existing local enforcement zones unchanged. Owners should budget " - "rent adjustments within CPI + 1.5% for pre-1990 stock.", - ), - ( - "Berlin Mietspiegel 2026 Q2 refresh scheduled", - "Berlin housing authority publishes Mietspiegel 2026 Q2 tables on " - "May 12. Wilmersdorf median 2BR cold rent expected to tick up ~1.8%.", - ), - ( - "Hamburg Altona facade inspection cadence revised", - "Bezirksamt Altona revises facade inspection guidance: waterfront " - "properties now inspected every 24 months (down from 36). Budget " - "any overdue inspections for the May inspection window.", - ), -] - - -async def watch_regulations() -> int: - """Poll Tavily for rent-regulation signals and persist new ``web`` events. - - Called by the scheduler once an hour (per KEYSTONE Part IV). Returns the - number of newly inserted events; repeat runs within the same hour are - idempotent thanks to the ``(source, source_ref)`` unique constraint. - """ - from sqlalchemy import text # noqa: PLC0415 — local import - - factory = get_sessionmaker() - now_key = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H") # hourly bucket - inserted = 0 - - if _available(): - for query in REGULATION_QUERIES: - hits = await _search(query, max_results=3) - if not hits: - continue - title = hits[0].title[:160] or query - body_lines = [ - "Regulation watch — Tavily snapshot", - f"Query: {query}", - "", - ] - for hit in hits: - body_lines.append( - f"- {hit.title}: {hit.content[:320]} [{hit.url}]" - ) - raw_content = "\n".join(body_lines) - source_ref = f"tavily-reg:{query}:{now_key}" - metadata = { - "tavily": True, - "regulation": True, - "query": query, - "headline": title, - "hits": [{"title": h.title, "url": h.url} for h in hits], - } - async with factory() as session: - _, new = await insert_event( - session, - source="web", - source_ref=source_ref, - raw_content=raw_content, - metadata=metadata, - ) - if new: - inserted += 1 - # Stamp processed so the extractor worker leaves it alone. - await session.execute( - text( - "UPDATE events SET processed_at = now() " - "WHERE source = 'web' AND source_ref = :ref" - ), - {"ref": source_ref}, - ) - await session.commit() - else: - # Offline path: insert a clearly-labelled canned headline so the - # demo still shows a regulation signal on a fresh DB. - for title, body in OFFLINE_REGULATION_HEADLINES: - source_ref = f"tavily-reg:offline:{title}" - metadata = { - "tavily": False, - "offline": True, - "regulation": True, - "headline": title, - } - async with factory() as session: - _, new = await insert_event( - session, - source="web", - source_ref=source_ref, - raw_content=( - "Regulation watch (offline snapshot)\n" - f"Headline: {title}\n\n{body}" - ), - metadata=metadata, - ) - if new: - inserted += 1 - await session.execute( - text( - "UPDATE events SET processed_at = now() " - "WHERE source = 'web' AND source_ref = :ref" - ), - {"ref": source_ref}, - ) - await session.commit() - - log.info( - "tavily.regulation_watch", - inserted=inserted, - live=_available(), - queries=len(REGULATION_QUERIES) if _available() else 0, - ) - return inserted diff --git a/backend/signals/drafter.py b/backend/signals/drafter.py index f695ed8..840087d 100644 --- a/backend/signals/drafter.py +++ b/backend/signals/drafter.py @@ -1,9 +1,10 @@ """Turn a :class:`SignalCandidate` into a :class:`ProposedAction`. -Uses Gemini Pro when ``GEMINI_API_KEY`` is configured — the Signal Quality -Bar in KEYSTONE Part I calls out "expert speaking, not a database emitting -rows" — and falls back to a deterministic template that still hits the -four-part structure: observation, risk, concrete next step, deadline. +A signal is only useful if its message reads like an expert's recommendation +rather than a database row. The configured LLM provider writes the message +when available; otherwise a deterministic template per signal type does, +following the same four-part structure: observation, risk, concrete next +step, deadline. """ from __future__ import annotations @@ -15,19 +16,29 @@ from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession -from backend.services.gemini import ( - GeminiUnavailable, - draft_action_message, - is_available as gemini_available, -) +from backend.services.llm import LLMUnavailableError, get_provider from backend.signals.types import ProposedAction, SignalCandidate log = structlog.get_logger(__name__) +DRAFT_PROMPT_TEMPLATE = """You are drafting an operational message for a property manager. -async def _owner_context( - session: AsyncSession, property_id: UUID | None -) -> dict[str, Any]: +Tone: crisp, specific, expert. Avoid vague softeners like 'maybe', 'might'. +Open with the observation and the risk. End with a concrete next step and a +deadline. 4-6 sentences, no signature block, no greetings. + +Signal type: {signal_type} +Severity: {severity} +Property context: +{context} + +Evidence summary: +{evidence_summary} + +Write the message body now.""" + + +async def _owner_context(session: AsyncSession, property_id: UUID | None) -> dict[str, Any]: """Look up the owner/recipient details for the drafted action.""" if property_id is None: return { @@ -70,11 +81,8 @@ def _subject(candidate: SignalCandidate) -> str: if sub == "shared_boiler": return "[Urgent] Shared-boiler failure risk across building" if sub == "year_cohort": - return "[Portfolio] Heating pattern in building cohort — inspection proposal" + return "[Portfolio] Heating pattern in building cohort: inspection proposal" return "[Portfolio] Cross-property pattern detected" - if candidate.type == "regulation_change": - headline = candidate.action_hint.get("headline", "regulation update") - return f"[Regulation] {headline[:80]}" return f"[Keystone] {candidate.type} signal" @@ -85,7 +93,7 @@ def _template_fallback(candidate: SignalCandidate, owner_name: str) -> str: return ( f"{owner_name}, Keystone has logged {hint.get('occurrences', 'multiple')} " f"{hint.get('topic', 'maintenance')} incidents at " - f"{hint.get('property_name', 'the property')} over the last four months — " + f"{hint.get('property_name', 'the property')} over the last four months; " "the cluster points to an underlying system failure rather than one-off " "complaints. We recommend dispatching the building's primary contractor " "for a full inspection within 48 hours and briefing the tenants in " @@ -95,7 +103,7 @@ def _template_fallback(candidate: SignalCandidate, owner_name: str) -> str: if candidate.type == "lease_expiring": return ( f"{owner_name}, the lease at {hint.get('property_name', 'the property')} " - f"expires {hint.get('end_date', 'soon')} — " + f"expires {hint.get('end_date', 'soon')}, " f"{hint.get('days_left', '?')} days out. We recommend proposing a " "renewal this week at the current Mietspiegel-bounded rent and asking " "the tenant for a decision inside ten business days so we can plan for " @@ -105,7 +113,7 @@ def _template_fallback(candidate: SignalCandidate, owner_name: str) -> str: if hint.get("subtype") == "shared_boiler": return ( f"Two or more units at {hint.get('building_address', 'the building')} " - f"have logged heating incidents this winter — the pattern points at " + f"have logged heating incidents this winter; the pattern points at " "the shared central boiler rather than any single unit. Recommend " "scheduling a building-wide boiler inspection within 48 hours and " "briefing every occupant so tenants aren't blindsided. Approve to " @@ -113,20 +121,11 @@ def _template_fallback(candidate: SignalCandidate, owner_name: str) -> str: ) return ( f"{hint.get('cohort', 'Multiple')} properties had heating issues this " - "winter — the correlation suggests shared equipment age rather than " + "winter; the correlation suggests shared equipment age rather than " "unit-level failures. Recommend a portfolio-wide boiler inspection " "within two weeks and budgeting for any units at end-of-life. Approve " "to line up contractors across the cohort." ) - if candidate.type == "regulation_change": - headline = hint.get("headline", "a regulatory update") - return ( - f"Tavily flagged a regulatory change: \"{headline}\". The update is " - "likely to touch rent adjustments, inspection cadence, or compliance " - "filings across the portfolio — we should review exposure inside the " - "next seven days and queue any tenant communications that fall out of " - "the change. Approve to circulate a short impact brief." - ) return ( f"{owner_name}, Keystone has flagged a {candidate.type} pattern requiring " "attention. See evidence below and approve to dispatch the recommended " @@ -134,29 +133,27 @@ def _template_fallback(candidate: SignalCandidate, owner_name: str) -> str: ) -async def draft( - session: AsyncSession, candidate: SignalCandidate -) -> ProposedAction: +async def draft(session: AsyncSession, candidate: SignalCandidate) -> ProposedAction: """Build the :class:`ProposedAction` for a candidate, Gemini Pro preferred.""" recipient = await _owner_context(session, candidate.property_id) subject = _subject(candidate) - evidence_summary = ( - candidate.context_excerpt - or "\n".join(f"- {item}" for item in candidate.evidence[:5]) + evidence_summary = candidate.context_excerpt or "\n".join( + f"- {item}" for item in candidate.evidence[:5] ) drafted_message: str | None = None - if gemini_available(): + provider = get_provider() + if provider is not None: + prompt = DRAFT_PROMPT_TEMPLATE.format( + signal_type=candidate.type, + severity=candidate.severity, + context=candidate.message or "(no prior context)", + evidence_summary=evidence_summary or "(no evidence)", + ) try: - drafted_message = await draft_action_message( - signal_type=candidate.type, - severity=candidate.severity, - context=candidate.message, - evidence_summary=evidence_summary, - ) - except GeminiUnavailable as exc: - log.warning("drafter.gemini_unavailable", error=str(exc)) - drafted_message = None + drafted_message = await provider.complete_text(system=None, prompt=prompt) + except LLMUnavailableError as exc: + log.warning("drafter.llm_unavailable", provider=provider.name, error=str(exc)[:300]) if not drafted_message: drafted_message = _template_fallback(candidate, recipient["name"]) diff --git a/backend/signals/evaluator.py b/backend/signals/evaluator.py index 6426dc3..e484732 100644 --- a/backend/signals/evaluator.py +++ b/backend/signals/evaluator.py @@ -1,33 +1,42 @@ """Evaluate every signal rule and persist candidates. The evaluator is the single scheduled entry point for the signal system. -It calls each rule's ``evaluate(session)``, dedupes the results against -already-open pending signals for the same ``(property_id, type)``, then: - -1. Asks :mod:`backend.signals.drafter` to author a :class:`ProposedAction`. -2. Inserts a row into ``signals`` with ``status='pending'``. - -The scheduler runs this every 30s; Phase 3 API endpoints expose a manual -``POST /signals/evaluate`` trigger for demo determinism. +It calls each rule's ``evaluate(session)`` and, for every candidate: + +1. Computes its natural key, ``type|property_id|subtype`` (see + :func:`natural_key`), the identity of "the same finding" across ticks. +2. Skips it if a signal with that key is still pending, or was approved or + rejected within ``signal_resolution_cooldown_days``. Rules are stateless + and keep matching the same facts, so without the cooldown a decision + made by a human would be undone on the next tick. +3. Otherwise asks :mod:`backend.signals.drafter` for a + :class:`ProposedAction` and inserts a ``pending`` row. The check in + step 2 is not atomic, so the insert also relies on the unique index + ``uq_signals_pending_natural_key``: when another evaluator (e.g. a + second API instance) inserted the same key in between, the insert is a + no-op. + +The scheduler runs this every 30 seconds; ``POST /signals/evaluate`` runs +it on demand. """ from __future__ import annotations import json -from typing import Protocol +from typing import Any, Protocol from uuid import UUID import structlog from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession +from backend.config import get_settings from backend.db.session import get_sessionmaker from backend.signals import drafter from backend.signals.rules import ( cross_property_pattern, lease_expiring, recurring_maintenance, - regulation_change, ) from backend.signals.types import SignalCandidate @@ -44,57 +53,63 @@ async def evaluate(self, session: AsyncSession) -> list[SignalCandidate]: ... recurring_maintenance, lease_expiring, cross_property_pattern, - regulation_change, ] -async def _already_open( - session: AsyncSession, - property_id: UUID | None, - signal_type: str, - action_hint: dict, -) -> bool: - """Return True if a pending signal with the same natural key already exists. - - Natural key is ``(property_id, type, action_hint.subtype)`` for cross- - property signals (so ``shared_boiler`` and ``year_cohort`` are distinct) - and ``(property_id, type)`` for per-property rules. +def natural_key(property_id: UUID | None, signal_type: str, action_hint: dict[str, Any]) -> str: + """Return the key that identifies one finding across evaluator ticks. + + ``type||``. The subtype + keeps findings that share a rule apart, e.g. ``shared_boiler`` vs + ``year_cohort`` for cross-property patterns, or ``heating`` vs ``water`` + for recurring maintenance on one property. """ - subtype = action_hint.get("subtype") or action_hint.get("topic") - params: dict[str, object] = {"type": signal_type} - clauses = ["type = :type", "status = 'pending'"] - if property_id is None: - clauses.append("property_id IS NULL") - else: - clauses.append("property_id = :pid") - params["pid"] = property_id - if subtype: - # proposed_action is {...top, payload: {hint: {topic|subtype: ...}}}. - clauses.append( - "(proposed_action->'payload'->'hint'->>'subtype' = :sub " - "OR proposed_action->'payload'->'hint'->>'topic' = :sub)" + subtype = action_hint.get("subtype") or action_hint.get("topic") or "" + scope = str(property_id) if property_id is not None else "portfolio" + return f"{signal_type}|{scope}|{subtype}" + + +async def _already_raised(session: AsyncSession, key: str, cooldown_days: int) -> bool: + """True if ``key`` is pending, or was resolved within the cooldown window.""" + row = ( + await session.execute( + text( + """ + SELECT 1 FROM signals + WHERE natural_key = :key + AND (status = 'pending' + OR resolved_at > now() - make_interval(days => :days)) + LIMIT 1 + """ + ), + {"key": key, "days": cooldown_days}, ) - params["sub"] = subtype - query = f"SELECT 1 FROM signals WHERE {' AND '.join(clauses)} LIMIT 1" - row = (await session.execute(text(query), params)).first() + ).first() return row is not None async def _persist( session: AsyncSession, candidate: SignalCandidate, -) -> UUID: - """Draft + insert a candidate. Returns the new ``signals.id``.""" + key: str, +) -> UUID | None: + """Draft + insert a candidate. Returns the new ``signals.id``. + + Returns ``None`` when a pending signal with ``key`` already exists, + which happens only when a concurrent evaluator inserted it after + :func:`_already_raised` ran. + """ action = await drafter.draft(session, candidate) result = await session.execute( text( """ INSERT INTO signals (property_id, type, severity, message, evidence, - proposed_action, status, created_at) + proposed_action, status, created_at, natural_key) VALUES (:pid, :type, :sev, :msg, CAST(:evd AS JSONB), - CAST(:act AS JSONB), 'pending', now()) + CAST(:act AS JSONB), 'pending', now(), :key) + ON CONFLICT (natural_key) WHERE status = 'pending' DO NOTHING RETURNING id """ ), @@ -105,9 +120,13 @@ async def _persist( "msg": candidate.message, "evd": json.dumps(candidate.evidence), "act": json.dumps(action.as_json()), + "key": key, }, ) - signal_id: UUID = result.scalar_one() + signal_id: UUID | None = result.scalar_one_or_none() + if signal_id is None: + log.info("signal.concurrent_duplicate_skipped", natural_key=key) + return None log.info( "signal.created", signal_id=str(signal_id), @@ -121,7 +140,7 @@ async def _persist( async def evaluate_all(session: AsyncSession | None = None) -> int: """Run every rule and persist new candidates. Returns how many fired. - ``session`` is optional — if omitted (the usual scheduler path) a fresh + ``session`` is optional; if omitted (the usual scheduler path) a fresh session is opened from the global sessionmaker. """ if session is not None: @@ -135,16 +154,16 @@ async def evaluate_all(session: AsyncSession | None = None) -> int: async def _run(session: AsyncSession) -> int: """Drive the rule set against ``session`` and persist new signals.""" + cooldown_days = get_settings().signal_resolution_cooldown_days created = 0 for module in _RULES: candidates = await module.evaluate(session) for candidate in candidates: - if await _already_open( - session, candidate.property_id, candidate.type, candidate.action_hint - ): + key = natural_key(candidate.property_id, candidate.type, candidate.action_hint) + if await _already_raised(session, key, cooldown_days): continue - await _persist(session, candidate) - created += 1 + if await _persist(session, candidate, key) is not None: + created += 1 if created: log.info("signal.batch", created=created) return created diff --git a/backend/signals/rules/_incidents.py b/backend/signals/rules/_incidents.py new file mode 100644 index 0000000..2ee04bb --- /dev/null +++ b/backend/signals/rules/_incidents.py @@ -0,0 +1,36 @@ +"""Shared definition of a maintenance *incident* for the signal rules. + +An incident is one reporting event. Rules count incidents, not facts: + +- Every matching maintenance fact counts, superseded or not. The extractor + files repeat reports of one issue under the same field, so each new report + supersedes the previous fact; counting only current facts would never see + more than one. +- Each source event counts once. An operator edit keeps its fact's source + event, so editing a fact does not add an incident. A fact without an event + counts once on its own. +- The time window applies to when the incident was reported (the event's + ``received_at``), not to when the fact row was written, which can be much + later for a backfill or a seed. +""" + +from __future__ import annotations + +# A CTE named ``incidents`` with one row per incident: property_id, id (the +# newest matching fact of the incident), source_event_id, value, reported_at. +# Parameters: ``:window`` (days, as text) and ``:pattern`` (a regex matched +# case-insensitively against the fact's value or field). +INCIDENTS_CTE = """ +incidents AS ( + SELECT DISTINCT ON (f.property_id, COALESCE(f.source_event_id, f.id)) + f.property_id, f.id, f.source_event_id, f.value, + COALESCE(e.received_at, f.created_at) AS reported_at + FROM facts f + LEFT JOIN events e ON e.id = f.source_event_id + WHERE f.section = 'maintenance' + AND COALESCE(e.received_at, f.created_at) + >= now() - (:window || ' days')::interval + AND (f.value ~* :pattern OR f.field ~* :pattern) + ORDER BY f.property_id, COALESCE(f.source_event_id, f.id), f.created_at DESC +) +""" diff --git a/backend/signals/rules/cross_property_pattern.py b/backend/signals/rules/cross_property_pattern.py index 0ae7c53..ce73011 100644 --- a/backend/signals/rules/cross_property_pattern.py +++ b/backend/signals/rules/cross_property_pattern.py @@ -1,26 +1,33 @@ -"""Rule 3 — ``cross_property_pattern`` (the portfolio-intelligence closer). +"""Rule 3: ``cross_property_pattern``, issues that span several properties. -Two flavors from Part IX + the demo script (beats 1:00 and 1:45): +Two flavors: A. **Shared building.** If ≥2 properties inside a single building each carry recurring heating facts in the last 120 days, fire a portfolio-level - signal keyed on the building — this is the "3 heating complaints across - units sharing the same boiler" beat. + signal keyed on the building. Three heating complaints from units that + share a boiler point at the shared system, not at the individual units. B. **Building-year cohort.** Group properties by year bucket (``pre-1990``, ``1990-2010``, ``post-2010``) and if ≥3 properties in the same bucket have heating issues inside the window, fire a portfolio-wide - inspection recommendation — this is beat 1:45. + inspection recommendation: buildings of a similar age tend to have + heating systems of a similar vintage, so a cluster of failures in one + cohort is a reason to inspect the rest of it. Both cases emit a ``property_id=None`` portfolio signal so the UI can -render it in the portfolio view instead of under a single property. +render it in the portfolio view instead of under a single property. Both +count incidents (one per reporting event) as defined in +:mod:`backend.signals.rules._incidents`. """ from __future__ import annotations +from typing import Any + import structlog from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession +from backend.signals.rules._incidents import INCIDENTS_CTE from backend.signals.types import SignalCandidate log = structlog.get_logger(__name__) @@ -30,7 +37,7 @@ def _year_bucket(year: int | None) -> str | None: - """Classify a building's year_built into a demo-friendly cohort label.""" + """Classify a building's year_built into a human-readable cohort label.""" if year is None: return None if year < 1990: @@ -41,27 +48,24 @@ def _year_bucket(year: int | None) -> str | None: async def _shared_building(session: AsyncSession) -> list[SignalCandidate]: - """Flavor A — buildings where multiple units share the same issue.""" + """Flavor A: buildings where multiple units share the same issue.""" result = await session.execute( text( - """ + f""" + WITH {INCIDENTS_CTE} SELECT b.id AS building_id, b.address, b.year_built, - COUNT(DISTINCT f.property_id) AS affected_properties, + COUNT(DISTINCT i.property_id) AS affected_properties, COUNT(*) AS total_incidents, ARRAY_AGG(DISTINCT p.name) AS property_names, - ARRAY_AGG(f.id::text ORDER BY f.created_at) AS fact_ids, - ARRAY_AGG(f.source_event_id::text ORDER BY f.created_at) + ARRAY_AGG(i.id::text ORDER BY i.reported_at) AS fact_ids, + ARRAY_AGG(i.source_event_id::text ORDER BY i.reported_at) AS event_ids - FROM facts f - JOIN properties p ON p.id = f.property_id + FROM incidents i + JOIN properties p ON p.id = i.property_id JOIN buildings b ON b.id = p.building_id - WHERE f.section = 'maintenance' - AND f.superseded_by IS NULL - AND f.created_at >= now() - (:window || ' days')::interval - AND (f.value ~* :pattern OR f.field ~* :pattern) GROUP BY b.id, b.address, b.year_built - HAVING COUNT(DISTINCT f.property_id) >= 2 + HAVING COUNT(DISTINCT i.property_id) >= 2 AND COUNT(*) >= 3 """ ), @@ -75,7 +79,7 @@ async def _shared_building(session: AsyncSession) -> list[SignalCandidate]: context_excerpt = ( f"Building: {row.address}\n" f"Year built: {row.year_built} ({bucket or 'unknown'})\n" - f"Units affected: {row.affected_properties} — {names}\n" + f"Units affected: {row.affected_properties} ({names})\n" f"Heating incidents (last {WINDOW_DAYS}d): {row.total_incidents}" ) evidence = [ @@ -91,7 +95,7 @@ async def _shared_building(session: AsyncSession) -> list[SignalCandidate]: message=( f"{row.total_incidents} heating complaints across " f"{row.affected_properties} units sharing the same " - f"{row.address} boiler — system failure likely." + f"{row.address} boiler: system failure likely." ), evidence=evidence, context_excerpt=context_excerpt, @@ -110,31 +114,28 @@ async def _shared_building(session: AsyncSession) -> list[SignalCandidate]: async def _building_year_cohort(session: AsyncSession) -> list[SignalCandidate]: - """Flavor B — portfolio-wide alert on a building-year cohort.""" + """Flavor B: portfolio-wide alert on a building-year cohort.""" result = await session.execute( text( - """ + f""" + WITH {INCIDENTS_CTE} SELECT b.id AS building_id, b.year_built, p.id AS property_id, p.name AS property_name, COUNT(*) AS incidents, - ARRAY_AGG(f.id::text) AS fact_ids, - ARRAY_AGG(f.source_event_id::text) AS event_ids - FROM facts f - JOIN properties p ON p.id = f.property_id + ARRAY_AGG(i.id::text) AS fact_ids, + ARRAY_AGG(i.source_event_id::text) AS event_ids + FROM incidents i + JOIN properties p ON p.id = i.property_id JOIN buildings b ON b.id = p.building_id - WHERE f.section = 'maintenance' - AND f.superseded_by IS NULL - AND f.created_at >= now() - (:window || ' days')::interval - AND (f.value ~* :pattern OR f.field ~* :pattern) GROUP BY b.id, b.year_built, p.id, p.name """ ), {"window": str(WINDOW_DAYS), "pattern": HEAT_PATTERN}, ) - buckets: dict[str, dict[str, list]] = {} + buckets: dict[str, dict[str, Any]] = {} for row in result.all(): bucket = _year_bucket(row.year_built) if bucket is None: @@ -157,14 +158,12 @@ async def _building_year_cohort(session: AsyncSession) -> list[SignalCandidate]: names = ", ".join(data["properties"]) context_excerpt = ( f"Year bucket: {bucket}\n" - f"Affected properties: {affected} — {names}\n" + f"Affected properties: {affected} ({names})\n" f"Heating incidents (last {WINDOW_DAYS}d): {data['incidents']}" ) evidence = [ {"event_id": ev, "fact_id": fid} - for ev, fid in zip( - data["event_ids"], data["fact_ids"], strict=False - ) + for ev, fid in zip(data["event_ids"], data["fact_ids"], strict=False) if ev or fid ] out.append( @@ -174,7 +173,7 @@ async def _building_year_cohort(session: AsyncSession) -> list[SignalCandidate]: property_id=None, message=( f"Keystone detected: {affected} {bucket} boiler " - f"properties had heating issues this winter — schedule " + f"properties had heating issues this winter: schedule " f"portfolio-wide inspection?" ), evidence=evidence, diff --git a/backend/signals/rules/late_payment.py b/backend/signals/rules/late_payment.py deleted file mode 100644 index 73768fb..0000000 --- a/backend/signals/rules/late_payment.py +++ /dev/null @@ -1 +0,0 @@ -"""late_payment_anomaly rule. Implemented in Phase 5.""" diff --git a/backend/signals/rules/lease_expiring.py b/backend/signals/rules/lease_expiring.py index 42276b9..f49c691 100644 --- a/backend/signals/rules/lease_expiring.py +++ b/backend/signals/rules/lease_expiring.py @@ -1,14 +1,14 @@ -"""Rule 2 — ``lease_expiring``. +"""Rule 2: ``lease_expiring``. Fires when a property's ``lease.end_date`` fact parses to a date within the -next 60 days. The window is intentionally configurable so the demo can -widen it when no real lease is imminent (``LEASE_WINDOW_DAYS``). +next 60 days. The window is a module constant (``LEASE_WINDOW_DAYS``) so it +can be widened when running against data in which no lease is imminent. """ from __future__ import annotations import re -from datetime import date, datetime, timedelta, timezone +from datetime import UTC, date, datetime import structlog from sqlalchemy import text @@ -36,8 +36,7 @@ def _parse_end_date(value: str) -> date | None: async def evaluate(session: AsyncSession) -> list[SignalCandidate]: """Return one candidate per property with a lease expiring in the window.""" - today = datetime.now(timezone.utc).date() - horizon = today + timedelta(days=LEASE_WINDOW_DAYS) + today = datetime.now(UTC).date() result = await session.execute( text( @@ -74,7 +73,7 @@ async def evaluate(session: AsyncSession) -> list[SignalCandidate]: property_id=row.property_id, message=( f"Lease on {row.property_name} expires in {days_left} days " - f"({end.isoformat()}) — renewal decision needed." + f"({end.isoformat()}): renewal decision needed." ), evidence=[ { diff --git a/backend/signals/rules/recurring_maintenance.py b/backend/signals/rules/recurring_maintenance.py index a3d2d29..9189a8b 100644 --- a/backend/signals/rules/recurring_maintenance.py +++ b/backend/signals/rules/recurring_maintenance.py @@ -1,10 +1,11 @@ -"""Rule 1 — ``recurring_maintenance`` (the demo hero). +"""Rule 1: ``recurring_maintenance``, sustained failures on a single unit. -Fires when a single property has ≥3 maintenance facts containing a shared -issue keyword (``heat``, ``boiler``, ``water``, ``leak``) within the past -120 days. This is the sustained-failure pattern judges recognize at a -glance: three heating complaints on the same unit → something is about to -break. +Fires when a single property has ≥3 maintenance incidents with a shared +issue keyword (``heat``, ``boiler``, ``water``, ``leak``) reported within the +past 120 days. An incident is one reporting event; see +:mod:`backend.signals.rules._incidents`. This is a sustained-failure pattern +a property manager recognizes at a glance: three heating complaints on the +same unit → something is about to break. """ from __future__ import annotations @@ -13,6 +14,7 @@ from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession +from backend.signals.rules._incidents import INCIDENTS_CTE from backend.signals.types import SignalCandidate log = structlog.get_logger(__name__) @@ -20,7 +22,7 @@ WINDOW_DAYS = 120 MIN_OCCURRENCES = 3 -# (keyword regex, topic label) — topic is what we key the dedupe on. +# (keyword regex, topic label); topic is what we key the dedupe on. KEYWORD_TOPICS: list[tuple[str, str]] = [ (r"heat|boiler|radiator|hot water", "heating"), (r"leak|water damage|p-?trap|drip", "water"), @@ -34,20 +36,17 @@ async def evaluate(session: AsyncSession) -> list[SignalCandidate]: for pattern, topic in KEYWORD_TOPICS: result = await session.execute( text( - """ - SELECT f.property_id, p.name AS property_name, + f""" + WITH {INCIDENTS_CTE} + SELECT i.property_id, p.name AS property_name, COUNT(*) AS occurrences, - ARRAY_AGG(f.id::text ORDER BY f.created_at) AS fact_ids, - ARRAY_AGG(f.source_event_id::text ORDER BY f.created_at) + ARRAY_AGG(i.id::text ORDER BY i.reported_at) AS fact_ids, + ARRAY_AGG(i.source_event_id::text ORDER BY i.reported_at) AS event_ids, - ARRAY_AGG(f.value ORDER BY f.created_at) AS values - FROM facts f - JOIN properties p ON p.id = f.property_id - WHERE f.section = 'maintenance' - AND f.superseded_by IS NULL - AND f.created_at >= now() - (:window || ' days')::interval - AND (f.value ~* :pattern OR f.field ~* :pattern) - GROUP BY f.property_id, p.name + ARRAY_AGG(i.value ORDER BY i.reported_at) AS values + FROM incidents i + JOIN properties p ON p.id = i.property_id + GROUP BY i.property_id, p.name HAVING COUNT(*) >= :min_count """ ), @@ -77,7 +76,7 @@ async def evaluate(session: AsyncSession) -> list[SignalCandidate]: property_id=row.property_id, message=( f"{occurrences} {topic} incidents on {row.property_name} " - f"in the last {WINDOW_DAYS} days — sustained failure pattern." + f"in the last {WINDOW_DAYS} days: sustained failure pattern." ), evidence=evidence, context_excerpt=context_excerpt, diff --git a/backend/signals/rules/regulation_change.py b/backend/signals/rules/regulation_change.py deleted file mode 100644 index 08c9f67..0000000 --- a/backend/signals/rules/regulation_change.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Rule 4 — ``regulation_change``. - -Fires when the Tavily regulation watcher ingests a ``web`` event tagged -``metadata.regulation=true`` that hasn't been signaled yet. Signals are -portfolio-level (``property_id=NULL``) — the UI renders them on the portfolio -view next to the other `cross_property_pattern` banners. -""" - -from __future__ import annotations - -import structlog -from sqlalchemy import text -from sqlalchemy.ext.asyncio import AsyncSession - -from backend.signals.types import SignalCandidate - -log = structlog.get_logger(__name__) - -WINDOW_DAYS = 14 # only surface regulation changes from the last two weeks - - -async def evaluate(session: AsyncSession) -> list[SignalCandidate]: - """Scan recent regulation events and emit one candidate per novel headline.""" - result = await session.execute( - text( - """ - SELECT id, source_ref, - COALESCE(metadata->>'headline', left(raw_content, 120)) - AS headline, - received_at, - metadata - FROM events - WHERE source = 'web' - AND (metadata->>'regulation')::boolean IS TRUE - AND received_at >= now() - (:window || ' days')::interval - ORDER BY received_at DESC - """ - ), - {"window": str(WINDOW_DAYS)}, - ) - - candidates: list[SignalCandidate] = [] - for row in result.all(): - headline = row.headline or "Regulation update" - context_excerpt = ( - f"Headline: {headline}\n" - f"Source: Tavily web watcher ({row.source_ref})\n" - f"Ingested: {row.received_at.isoformat()}" - ) - candidates.append( - SignalCandidate( - type="regulation_change", - severity="medium", - property_id=None, - message=( - f"Regulation update detected: {headline} — " - "review for portfolio impact." - ), - evidence=[{"event_id": str(row.id), "fact_id": ""}], - context_excerpt=context_excerpt, - action_hint={ - "type": "regulation_review", - "subtype": str(row.source_ref), - "headline": headline, - "source_ref": row.source_ref, - }, - ) - ) - - log.info("rule.regulation_change", candidates=len(candidates)) - return candidates diff --git a/backend/signals/types.py b/backend/signals/types.py index 3f62358..d9e34b3 100644 --- a/backend/signals/types.py +++ b/backend/signals/types.py @@ -16,13 +16,13 @@ class SignalCandidate: """A rule's proposal before drafting + persistence. Attributes: - type: Rule name — this doubles as the ``signals.type`` column so the + type: Rule name; this doubles as the ``signals.type`` column so the dedupe key ``(property_id, type, status='pending')`` works. property_id: Property the signal applies to. ``None`` for portfolio-level signals (cross_property_pattern fires one of these). severity: ``low | medium | high | urgent``. message: Human-readable one-liner used in the inbox listing. - evidence: ``[{"event_id": ..., "fact_id": ...}]`` — the provenance the + evidence: ``[{"event_id": ..., "fact_id": ...}]``, the provenance the UI renders under the signal. context_excerpt: A short summary the drafter can use in its prompt. action_hint: Rule-provided scaffolding the drafter can expand diff --git a/backend/tests/test_api_routes.py b/backend/tests/test_api_routes.py new file mode 100644 index 0000000..07f390b --- /dev/null +++ b/backend/tests/test_api_routes.py @@ -0,0 +1,55 @@ +"""The HTTP surface stays stable when routers are reorganized.""" + +from __future__ import annotations + +from backend.main import app + +ADMIN_OPERATIONS = { + ("get", "/admin/unrouted"), + ("get", "/admin/buena/cursor_status"), + ("post", "/admin/buena/advance_day"), + ("post", "/admin/buena/reset_cursor"), + ("post", "/admin/materialize-all"), + ("get", "/admin/properties/{property_id}/rejected"), + ("post", "/admin/rejected/{rejection_id}/override"), + ("get", "/admin/rejected"), + ("get", "/admin/properties/{property_id}/uncertainties"), + ("get", "/admin/uncertainties"), + ("post", "/admin/uncertainties/{uncertainty_id}/resolve"), + ("get", "/admin/properties/{property_id}/onboarding"), + ("post", "/admin/replay/start"), + ("post", "/admin/replay/{run_id}/pause"), + ("post", "/admin/replay/{run_id}/resume"), + ("post", "/admin/replay/{run_id}/stop"), + ("get", "/admin/replay/{run_id}/status"), + ("post", "/admin/replay/featured"), +} + +PROPERTIES_OPERATIONS = { + ("get", "/properties"), + ("post", "/properties"), + ("get", "/properties/search"), + ("get", "/properties/{property_id}/activity"), + ("post", "/properties/{property_id}/ask"), + ("get", "/properties/{property_id}/events"), + ("patch", "/properties/{property_id}/facts/{fact_id}"), + ("get", "/properties/{property_id}/file"), + ("get", "/properties/{property_id}/graph"), + ("get", "/properties/{property_id}/inbox"), + ("get", "/properties/{property_id}/markdown"), +} + + +def _operations(prefix: str) -> set[tuple[str, str]]: + paths = app.openapi()["paths"] + return { + (method, path) for path, ops in paths.items() if path.startswith(prefix) for method in ops + } + + +def test_admin_operations_are_unchanged() -> None: + assert _operations("/admin") == ADMIN_OPERATIONS + + +def test_properties_operations_are_unchanged() -> None: + assert _operations("/properties") == PROPERTIES_OPERATIONS diff --git a/backend/tests/test_cors.py b/backend/tests/test_cors.py new file mode 100644 index 0000000..f21e3db --- /dev/null +++ b/backend/tests/test_cors.py @@ -0,0 +1,45 @@ +"""CORS origins come only from KEYSTONE_CORS_ORIGINS.""" + +from __future__ import annotations + +import httpx +import pytest + +from backend.config import Settings + + +def _preflight(origin: str) -> httpx.Request: + return httpx.Request( + "OPTIONS", + "http://test/health", + headers={"Origin": origin, "Access-Control-Request-Method": "GET"}, + ) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("http://a.test, http://b.test ,", ["http://a.test", "http://b.test"]), + ("", []), + ], +) +def test_origin_list_parsing(raw: str, expected: list[str]) -> None: + assert Settings(keystone_cors_origins=raw).cors_origin_list() == expected + + +@pytest.mark.parametrize( + ("origin", "allowed"), + [ + ("http://localhost:8080", True), + ("https://keystone-insight.lovable.app", False), + ("https://anything.lovableproject.com", False), + ("https://evil.example", False), + ], +) +async def test_only_configured_origins_pass_preflight(origin: str, allowed: bool) -> None: + from backend.main import app # noqa: PLC0415 + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) as client: + response = await client.send(_preflight(origin)) + + assert (response.headers.get("access-control-allow-origin") == origin) is allowed diff --git a/backend/tests/test_differ.py b/backend/tests/test_differ.py index 30aaf30..516ea82 100644 --- a/backend/tests/test_differ.py +++ b/backend/tests/test_differ.py @@ -1 +1,5 @@ -"""Differ tests. Implemented in Phase 1.""" +"""Differ unit tests (none yet). + +The differ is currently covered end to end by +``test_pipeline_happy_path.py``, which runs an event through the worker. +""" diff --git a/backend/tests/test_erp_poller.py b/backend/tests/test_erp_poller.py new file mode 100644 index 0000000..9b5f35b --- /dev/null +++ b/backend/tests/test_erp_poller.py @@ -0,0 +1,50 @@ +"""ERP poller is opt-in: no URL means no scheduled job and no HTTP calls.""" + +from __future__ import annotations + +import pytest + +from backend import scheduler +from backend.config import Settings +from backend.services import erp_poller + + +def _settings(url: str) -> Settings: + return Settings(mock_erp_url=url) + + +async def test_poll_once_is_noop_without_url(monkeypatch: pytest.MonkeyPatch) -> None: + async def _fail(_: str) -> list[dict[str, object]]: + raise AssertionError("poller must not call the ERP when MOCK_ERP_URL is unset") + + monkeypatch.setattr(erp_poller, "get_settings", lambda: _settings("")) + monkeypatch.setattr(erp_poller, "_fetch_payments", _fail) + + assert await erp_poller.poll_once() == 0 + + +def test_scheduler_omits_erp_job_without_url(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(scheduler, "get_settings", lambda: _settings("")) + + job_ids = {job.id for job in scheduler.build_scheduler().get_jobs()} + + assert "erp_poll" not in job_ids + assert "worker_tick" in job_ids + + +def test_scheduler_registers_erp_job_with_url(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(scheduler, "get_settings", lambda: _settings("http://erp.test")) + + job_ids = {job.id for job in scheduler.build_scheduler().get_jobs()} + + assert "erp_poll" in job_ids + + +def test_format_payment_carries_routing_hint() -> None: + raw = erp_poller._format_payment( + {"account": "ACC-1", "property_hint": "EH-029", "amount_eur": 950, "late_days": 3} + ) + + assert "Property: EH-029" in raw + assert "Amount: 950 EUR" in raw + assert "Late by: 3 days" in raw diff --git a/backend/tests/test_extractor.py b/backend/tests/test_extractor.py index d2b94eb..e65ef69 100644 --- a/backend/tests/test_extractor.py +++ b/backend/tests/test_extractor.py @@ -1 +1,5 @@ -"""Extractor tests. Implemented in Phase 1.""" +"""Extractor unit tests (none yet). + +The extractor is currently covered end to end by +``test_pipeline_happy_path.py``, which runs an event through the worker. +""" diff --git a/backend/tests/test_featured_property.py b/backend/tests/test_featured_property.py new file mode 100644 index 0000000..8419fb3 --- /dev/null +++ b/backend/tests/test_featured_property.py @@ -0,0 +1,75 @@ +"""FEATURED_PROPERTY resolves by alias or UUID and drives the is_hero flag.""" + +from __future__ import annotations + +import uuid +from collections.abc import AsyncIterator + +import httpx +import pytest +from sqlalchemy import text + +from backend.config import get_settings +from backend.db.session import get_sessionmaker + + +def _client() -> httpx.AsyncClient: + from backend.main import app # noqa: PLC0415 + + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") + + +@pytest.fixture +async def unit(db: None) -> AsyncIterator[tuple[uuid.UUID, str]]: + alias = f"EH-T{uuid.uuid4().hex[:6]}" + async with get_sessionmaker()() as session: + pid = ( + await session.execute( + text( + "INSERT INTO properties (name, address, aliases) " + "VALUES (:n, 'Featured test', ARRAY[:a]) RETURNING id" + ), + {"n": f"Featured {alias}", "a": alias}, + ) + ).scalar_one() + await session.commit() + yield pid, alias + async with get_sessionmaker()() as session: + await session.execute(text("DELETE FROM properties WHERE id = :p"), {"p": pid}) + await session.commit() + + +async def _heroes(monkeypatch: pytest.MonkeyPatch, ref: str) -> list[str]: + monkeypatch.setenv("FEATURED_PROPERTY", ref) + get_settings.cache_clear() + async with _client() as client: + response = await client.get("/properties") + assert response.status_code == 200 + return [p["id"] for p in response.json() if p["is_hero"]] + + +async def test_featured_property_by_alias( + unit: tuple[uuid.UUID, str], monkeypatch: pytest.MonkeyPatch +) -> None: + pid, alias = unit + + assert await _heroes(monkeypatch, alias) == [str(pid)] + + +async def test_featured_property_by_uuid( + unit: tuple[uuid.UUID, str], monkeypatch: pytest.MonkeyPatch +) -> None: + pid, _ = unit + + assert await _heroes(monkeypatch, str(pid)) == [str(pid)] + + +@pytest.mark.usefixtures("db") +async def test_unmatched_reference_features_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + assert await _heroes(monkeypatch, "EH-does-not-exist") == [] + + async with _client() as client: + response = await client.post("/admin/replay/featured") + + assert response.status_code == 404 + assert "EH-does-not-exist" in response.json()["detail"] diff --git a/backend/tests/test_files.py b/backend/tests/test_files.py index fb5713e..9d50187 100644 --- a/backend/tests/test_files.py +++ b/backend/tests/test_files.py @@ -1,4 +1,4 @@ -"""Tests for Phase 10 Step 10.4 — ``GET /files/``. +"""Tests for ``GET /files/``. Path safety is the only thing this endpoint exists to enforce, so the tests focus on traversal attempts (`..`, absolute paths, NUL bytes, @@ -8,6 +8,7 @@ from __future__ import annotations import os +from collections.abc import Iterator from pathlib import Path import pytest @@ -19,11 +20,9 @@ @pytest.fixture() -def isolated_root(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: +def isolated_root(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Iterator[Path]: """Point the files router at a tmp dir + reset its lru_cache.""" - monkeypatch.setattr( - get_settings(), "keystone_files_root", str(tmp_path), raising=True - ) + monkeypatch.setattr(get_settings(), "keystone_files_root", str(tmp_path), raising=True) files_api._allowed_root.cache_clear() yield tmp_path files_api._allowed_root.cache_clear() @@ -98,7 +97,7 @@ def test_endpoint_serves_file_via_test_client(isolated_root: Path) -> None: target = isolated_root / "letter.pdf" target.write_bytes(b"%PDF-1.7 a real-looking doc") - from backend.main import app # noqa: PLC0415 — heavy import + from backend.main import app # noqa: PLC0415 (heavy import) client = TestClient(app) resp = client.get("/files/letter.pdf") diff --git a/backend/tests/test_idempotency.py b/backend/tests/test_idempotency.py new file mode 100644 index 0000000..199cd35 --- /dev/null +++ b/backend/tests/test_idempotency.py @@ -0,0 +1,100 @@ +"""Delivering or processing the same event twice must not duplicate facts.""" + +from __future__ import annotations + +import uuid +from collections.abc import AsyncIterator + +import pytest +from sqlalchemy import text + +from backend.db.session import get_sessionmaker +from backend.pipeline.events import insert_event +from backend.pipeline.worker import process_specific + + +@pytest.fixture +async def property_alias(db: None) -> AsyncIterator[str]: + alias = f"Testweg {uuid.uuid4().hex[:6]} Apt 5D" + async with get_sessionmaker()() as session: + pid = ( + await session.execute( + text( + "INSERT INTO properties (name, address, aliases) " + "VALUES (:a, :a, ARRAY[:a]) RETURNING id" + ), + {"a": alias}, + ) + ).scalar_one() + await session.commit() + yield alias + async with get_sessionmaker()() as session: + await session.execute(text("DELETE FROM facts WHERE property_id = :p"), {"p": pid}) + await session.execute( + text("DELETE FROM events WHERE property_id = :p OR source_ref LIKE 'test-idem-%'"), + {"p": pid}, + ) + await session.execute(text("DELETE FROM properties WHERE id = :p"), {"p": pid}) + await session.commit() + + +async def _insert(alias: str, ref: str) -> tuple[uuid.UUID, bool]: + async with get_sessionmaker()() as session: + event_id, inserted = await insert_event( + session, + source="email", + source_ref=ref, + raw_content=f"Subject: Heizung\n\nDie Heizung in {alias} ist ausgefallen.", + ) + await session.commit() + return event_id, inserted + + +async def _facts_for(event_id: uuid.UUID) -> list[tuple[str, str, str]]: + async with get_sessionmaker()() as session: + rows = ( + await session.execute( + text( + "SELECT section, field, value FROM facts " + "WHERE source_event_id = :e ORDER BY section, field" + ), + {"e": event_id}, + ) + ).all() + return [(r.section, r.field, r.value) for r in rows] + + +async def test_redelivered_event_is_not_inserted_twice(property_alias: str) -> None: + ref = f"test-idem-{uuid.uuid4().hex[:8]}" + first_id, first_inserted = await _insert(property_alias, ref) + second_id, second_inserted = await _insert(property_alias, ref) + + assert first_inserted is True + assert second_inserted is False + assert second_id == first_id + + +async def test_processed_event_is_not_processed_again(property_alias: str) -> None: + event_id, _ = await _insert(property_alias, f"test-idem-{uuid.uuid4().hex[:8]}") + assert await process_specific(event_id) is True + facts = await _facts_for(event_id) + assert facts + + assert await process_specific(event_id) is False + assert await _facts_for(event_id) == facts + + +async def test_reprocessing_the_same_event_adds_no_facts(property_alias: str) -> None: + """Forced replay (processed_at cleared, as a replay or recovery would) is a no-op.""" + event_id, _ = await _insert(property_alias, f"test-idem-{uuid.uuid4().hex[:8]}") + await process_specific(event_id) + facts = await _facts_for(event_id) + + async with get_sessionmaker()() as session: + await session.execute( + text("UPDATE events SET processed_at = NULL WHERE id = :e"), {"e": event_id} + ) + await session.commit() + assert await process_specific(event_id) is True + + assert await _facts_for(event_id) == facts diff --git a/backend/tests/test_imap_ingestion.py b/backend/tests/test_imap_ingestion.py index fee1852..bb67b58 100644 --- a/backend/tests/test_imap_ingestion.py +++ b/backend/tests/test_imap_ingestion.py @@ -2,7 +2,7 @@ The user explicitly asked us to verify live IMAP polling before moving on. We can't reach a real IMAP server from a unit test, but -:func:`backend.services.imap_poller._ingest` is the choke-point — +:func:`backend.services.imap_poller._ingest` is the choke-point: once an IMAP fetch succeeds it hands raw bytes + a Message-ID to that function. If ``_ingest`` parses real Buena German .eml files cleanly and the downstream worker extracts a fact, the live path works end @@ -25,7 +25,6 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker from backend.services.imap_poller import _ingest, _render_event_text from connectors.migrations import apply_all as ensure_migrations @@ -33,24 +32,6 @@ pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - def _pick_buena_eml() -> Path | None: """Return a real Buena .eml path or ``None`` if the archive is absent.""" candidates = list(Path("Extracted/emails").rglob("*.eml")) @@ -60,8 +41,6 @@ def _pick_buena_eml() -> Path | None: async def _setup_or_skip() -> Path: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") ensure_migrations() eml = _pick_buena_eml() if eml is None: @@ -74,6 +53,7 @@ async def _setup_or_skip() -> Path: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_render_event_text_handles_german_eml() -> None: """A real German .eml flattens to ``From:\\nSubject:\\n\\n``.""" eml_path = await _setup_or_skip() @@ -96,15 +76,11 @@ async def test_render_event_text_handles_german_eml() -> None: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_ingest_inserts_real_buena_eml() -> None: """Calling _ingest with real .eml bytes lands a routable event.""" eml_path = await _setup_or_skip() raw = eml_path.read_bytes() - - import email # noqa: PLC0415 - - parsed = email.message_from_bytes(raw) - message_id = parsed.get("Message-ID", f"test-{eml_path.stem}").strip("<>").strip() # Insert with a unique source_ref to keep the test self-contained. test_ref = f"test-imap-{eml_path.stem}" @@ -152,6 +128,7 @@ async def test_ingest_inserts_real_buena_eml() -> None: await session.commit() +@pytest.mark.usefixtures("db") async def test_ingest_is_idempotent_on_message_id() -> None: """Re-calling _ingest with the same source_ref does not double-insert.""" eml_path = await _setup_or_skip() @@ -175,9 +152,7 @@ async def test_ingest_is_idempotent_on_message_id() -> None: async with factory() as session: n = ( await session.execute( - text( - "SELECT COUNT(*) FROM events WHERE source_ref = :ref" - ), + text("SELECT COUNT(*) FROM events WHERE source_ref = :ref"), {"ref": test_ref}, ) ).scalar() @@ -199,10 +174,10 @@ async def test_ingest_is_idempotent_on_message_id() -> None: async def test_poll_once_is_safe_noop_when_not_configured( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Without IMAP creds, ``poll_once`` returns 0 cleanly — the scheduler + """Without IMAP creds, ``poll_once`` returns 0 cleanly; the scheduler relies on this so a missing IMAP env doesn't crash the worker loop.""" from backend.services import imap_poller # noqa: PLC0415 - monkeypatch.setattr(imap_poller, "_imap_configured", lambda: False) + monkeypatch.setattr(imap_poller, "is_configured", lambda: False) inserted = await imap_poller.poll_once() assert inserted == 0 diff --git a/backend/tests/test_incident_rules.py b/backend/tests/test_incident_rules.py new file mode 100644 index 0000000..666159a --- /dev/null +++ b/backend/tests/test_incident_rules.py @@ -0,0 +1,195 @@ +"""Maintenance signal rules count reported incidents, not currently valid facts.""" + +from __future__ import annotations + +import uuid +from collections.abc import AsyncIterator +from dataclasses import dataclass +from uuid import UUID + +import pytest +from sqlalchemy import text + +from backend.db.session import get_sessionmaker +from backend.signals.rules import cross_property_pattern, recurring_maintenance + +_REF_PREFIX = "test-recurring-" + + +@dataclass +class Unit: + """A throwaway property; ``last_fact`` is the current heating fact, if any.""" + + id: UUID + last_fact: UUID | None = None + + +@pytest.fixture +async def unit(db: None) -> AsyncIterator[Unit]: + name = f"Testweg {uuid.uuid4().hex[:6]} Apt 1" + async with get_sessionmaker()() as session: + pid = ( + await session.execute( + text("INSERT INTO properties (name, address) VALUES (:n, :n) RETURNING id"), + {"n": name}, + ) + ).scalar_one() + await session.commit() + yield Unit(id=pid) + async with get_sessionmaker()() as session: + await session.execute( + text("UPDATE facts SET superseded_by = NULL WHERE property_id = :p"), {"p": pid} + ) + await session.execute(text("DELETE FROM facts WHERE property_id = :p"), {"p": pid}) + await session.execute( + text("DELETE FROM events WHERE source_ref LIKE :prefix"), + {"prefix": f"{_REF_PREFIX}%"}, + ) + await session.execute(text("DELETE FROM properties WHERE id = :p"), {"p": pid}) + await session.commit() + + +async def _report(unit: Unit, *, days_ago: int, event_id: UUID | None = None) -> UUID: + """Record one heating fact, superseding the unit's current one, as the differ does. + + Without ``event_id`` a new incident (event) is created ``days_ago`` days + back; with it, the fact belongs to that existing event (an operator edit). + """ + async with get_sessionmaker()() as session: + if event_id is None: + event_id = ( + await session.execute( + text( + "INSERT INTO events (source, source_ref, property_id, raw_content, " + "received_at, processed_at) VALUES ('email', :ref, :p, 'Heizung kalt', " + "now() - make_interval(days => :d), now()) RETURNING id" + ), + {"ref": f"{_REF_PREFIX}{uuid.uuid4().hex}", "p": unit.id, "d": days_ago}, + ) + ).scalar_one() + fact_id = ( + await session.execute( + text( + "INSERT INTO facts (property_id, section, field, value, source_event_id, " + "confidence) VALUES (:p, 'maintenance', 'open_heating_issue', " + "'Heizung ausgefallen', :e, 0.8) RETURNING id" + ), + {"p": unit.id, "e": event_id}, + ) + ).scalar_one() + if unit.last_fact is not None: + await session.execute( + text("UPDATE facts SET superseded_by = :new WHERE id = :old"), + {"new": fact_id, "old": unit.last_fact}, + ) + await session.commit() + unit.last_fact = fact_id + return event_id + + +async def _heating_occurrences(unit: Unit) -> int | None: + """Occurrences in the unit's heating candidate, or None if it did not fire.""" + async with get_sessionmaker()() as session: + candidates = await recurring_maintenance.evaluate(session) + for c in candidates: + if c.property_id == unit.id and c.action_hint["topic"] == "heating": + return int(c.action_hint["occurrences"]) + return None + + +async def test_three_reports_of_one_issue_fire_although_each_supersedes_the_last( + unit: Unit, +) -> None: + """The extractor reuses the field, so only the newest fact is current.""" + for days_ago in (90, 40, 5): + await _report(unit, days_ago=days_ago) + + assert await _heating_occurrences(unit) == 3 + + +async def test_an_operator_edit_is_not_a_new_incident(unit: Unit) -> None: + await _report(unit, days_ago=30) + second = await _report(unit, days_ago=10) + await _report(unit, days_ago=0, event_id=second) # the edit keeps the event + + assert await _heating_occurrences(unit) is None + + +async def test_the_window_uses_when_the_incident_was_reported(unit: Unit) -> None: + """A report from 200 days ago, processed today, is outside the 120-day window.""" + for days_ago in (200, 20, 2): + await _report(unit, days_ago=days_ago) + + assert await _heating_occurrences(unit) is None + + +@pytest.fixture +async def building_units(db: None) -> AsyncIterator[tuple[UUID, Unit, Unit]]: + """A pre-1990 test building with two units sharing its boiler.""" + tag = uuid.uuid4().hex[:6] + async with get_sessionmaker()() as session: + bid = ( + await session.execute( + text("INSERT INTO buildings (address, year_built) VALUES (:a, 1962) RETURNING id"), + {"a": f"Testweg {tag}, 10115 Berlin"}, + ) + ).scalar_one() + pids = [ + ( + await session.execute( + text( + "INSERT INTO properties (name, address, building_id) " + "VALUES (:n, :n, :b) RETURNING id" + ), + {"n": f"Testweg {tag} Apt {apt}", "b": bid}, + ) + ).scalar_one() + for apt in ("1", "2") + ] + await session.commit() + yield bid, Unit(id=pids[0]), Unit(id=pids[1]) + async with get_sessionmaker()() as session: + for pid in pids: + await session.execute( + text("UPDATE facts SET superseded_by = NULL WHERE property_id = :p"), {"p": pid} + ) + await session.execute(text("DELETE FROM facts WHERE property_id = :p"), {"p": pid}) + await session.execute( + text("DELETE FROM events WHERE source_ref LIKE :prefix"), + {"prefix": f"{_REF_PREFIX}%"}, + ) + for pid in pids: + await session.execute(text("DELETE FROM properties WHERE id = :p"), {"p": pid}) + await session.execute(text("DELETE FROM buildings WHERE id = :b"), {"b": bid}) + await session.commit() + + +async def _shared_boiler_incidents(building_id: UUID) -> int | None: + async with get_sessionmaker()() as session: + candidates = await cross_property_pattern.evaluate(session) + for c in candidates: + if c.action_hint.get("building_id") == str(building_id): + return int(c.action_hint["incidents"]) + return None + + +async def test_shared_boiler_counts_superseded_reports_across_units( + building_units: tuple[UUID, Unit, Unit], +) -> None: + building_id, first, second = building_units + await _report(first, days_ago=60) + await _report(first, days_ago=20) # supersedes the first unit's earlier fact + await _report(second, days_ago=10) + + assert await _shared_boiler_incidents(building_id) == 3 + + +async def test_shared_boiler_ignores_reports_outside_the_window( + building_units: tuple[UUID, Unit, Unit], +) -> None: + building_id, first, second = building_units + await _report(first, days_ago=200) + await _report(first, days_ago=20) + await _report(second, days_ago=10) + + assert await _shared_boiler_incidents(building_id) is None diff --git a/backend/tests/test_llm_features.py b/backend/tests/test_llm_features.py new file mode 100644 index 0000000..06b1728 --- /dev/null +++ b/backend/tests/test_llm_features.py @@ -0,0 +1,216 @@ +"""Ask, reply drafting and the semantic check work with Gemini alone, and degrade cleanly. + +Before the provider interface these three features called Pioneer directly: +with only GEMINI_API_KEY set, Ask returned 503 "PIONEER_API_KEY not set" and +the worker logged a skipped semantic check for every event. +""" + +from __future__ import annotations + +import uuid +from collections.abc import AsyncIterator +from typing import Any + +import httpx +import pytest +from sqlalchemy import text +from structlog.testing import capture_logs + +from backend.config import get_settings +from backend.db.session import get_sessionmaker +from backend.pipeline import semantic_validator +from backend.pipeline.events import insert_event +from backend.pipeline.worker import process_specific +from backend.services import llm +from backend.services.llm.base import JsonCompletion, LLMNotConfiguredError +from backend.services.llm.gemini import GeminiProvider + + +def _client() -> httpx.AsyncClient: + from backend.main import app # noqa: PLC0415 + + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") + + +@pytest.fixture +def gemini_only(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """Configure Gemini (and nothing else) and record its JSON calls.""" + monkeypatch.setenv("GEMINI_API_KEY", "test-key") + get_settings.cache_clear() + calls: list[dict[str, Any]] = [] + replies: dict[str, dict[str, Any]] = { + "ask": { + "status": "answered", + "answer": "The heating was reported broken.", + "confidence": "high", + "reasoning": "One email reports it.", + "cited_event_ids": [], + "partial_context_event_ids": [], + }, + "draft": {"subject": "Re: Heating", "body": "We are on it.", "knows_about_incident": False}, + "audit": { + "verdict": "has_contradictions", + "contradictions": [ + { + "section": "overview", + "field": "floor_count", + "claim": "tenant lives on the 7th floor", + "conflict_with": "building has 4 floors", + "severity": "hard", + "reason": "Building has 4 floors.", + } + ], + }, + } + + async def fake_complete_json(self: GeminiProvider, **kwargs: Any) -> JsonCompletion: + calls.append(kwargs) + system = kwargs["system"].lower() + key = "audit" if "audit" in system else "draft" if "repl" in system else "ask" + return JsonCompletion(data=replies[key], model=self.model, latency_ms=1.0) + + monkeypatch.setattr(GeminiProvider, "complete_json", fake_complete_json) + return calls + + +@pytest.fixture +async def property_id(db: None) -> AsyncIterator[uuid.UUID]: + suffix = uuid.uuid4().hex[:6] + factory = get_sessionmaker() + async with factory() as session: + bid = ( + await session.execute( + text("INSERT INTO buildings (address) VALUES (:a) RETURNING id"), + {"a": f"LLM test {suffix}"}, + ) + ).scalar_one() + pid = ( + await session.execute( + text( + "INSERT INTO properties (name, address, building_id, aliases) " + "VALUES (:n, :a, :b, ARRAY[:n]) RETURNING id" + ), + {"n": f"Testweg {suffix} Apt 3C", "a": f"Testweg {suffix}", "b": bid}, + ) + ).scalar_one() + await session.commit() + yield pid + async with factory() as session: + await session.execute(text("DELETE FROM facts WHERE property_id = :p"), {"p": pid}) + await session.execute(text("DELETE FROM events WHERE property_id = :p"), {"p": pid}) + await session.execute(text("DELETE FROM properties WHERE id = :p"), {"p": pid}) + await session.execute(text("DELETE FROM buildings WHERE id = :b"), {"b": bid}) + await session.commit() + + +async def test_ask_answers_with_gemini_only( + property_id: uuid.UUID, gemini_only: list[dict[str, Any]] +) -> None: + async with _client() as client: + response = await client.post( + f"/properties/{property_id}/ask", json={"question": "Is the heating fixed?"} + ) + + assert response.status_code == 200, response.text + assert response.json()["status"] == "answered" + assert len(gemini_only) == 1 + + +async def test_ask_without_provider_returns_503_naming_the_key(property_id: uuid.UUID) -> None: + async with _client() as client: + response = await client.post( + f"/properties/{property_id}/ask", json={"question": "Is the heating fixed?"} + ) + + assert response.status_code == 503 + assert "GEMINI_API_KEY" in response.json()["detail"] + + +async def test_draft_reply_with_gemini_only( + property_id: uuid.UUID, gemini_only: list[dict[str, Any]] +) -> None: + async with _client() as client: + response = await client.post( + "/draft-reply", + json={"property_id": str(property_id), "body": "The heating is broken."}, + ) + + assert response.status_code == 200, response.text + assert response.json()["body"] == "We are on it." + + +async def test_draft_reply_without_provider_returns_503(property_id: uuid.UUID) -> None: + async with _client() as client: + response = await client.post( + "/draft-reply", + json={"property_id": str(property_id), "body": "The heating is broken."}, + ) + + assert response.status_code == 503 + assert "GEMINI_API_KEY" in response.json()["detail"] + + +async def test_semantic_check_runs_on_gemini_only(gemini_only: list[dict[str, Any]]) -> None: + verdict = await semantic_validator.semantic_validate( + property_file_markdown="Building: 4 floors", + event_body="I live on the 7th floor.", + event_source="email", + proposed_facts=[], + ) + + assert verdict.has_contradictions + assert verdict.rejections[0].field == "floor_count" + + +async def test_semantic_check_without_provider_raises_not_configured() -> None: + with pytest.raises(LLMNotConfiguredError): + await semantic_validator.semantic_validate( + property_file_markdown="", event_body="x", event_source="email", proposed_facts=[] + ) + + +async def test_worker_logs_nothing_per_event_without_provider(property_id: uuid.UUID) -> None: + factory = get_sessionmaker() + async with factory() as session: + name = ( + await session.execute( + text("SELECT name FROM properties WHERE id = :p"), {"p": property_id} + ) + ).scalar_one() + event_id, _ = await insert_event( + session, + source="email", + source_ref=f"test-llm-{uuid.uuid4().hex[:8]}", + raw_content=f"Subject: Heizung\n\nDie Heizung in {name} ist kalt.", + ) + await session.commit() + + with capture_logs() as logs: + assert await process_specific(event_id) is True + + assert not [e for e in logs if "semantic" in e["event"]] + + +def test_startup_logs_missing_provider_once() -> None: + with capture_logs() as logs: + llm.log_configuration() + + assert [e["event"] for e in logs] == ["llm.provider.not_configured"] + assert logs[0]["missing"] == "GEMINI_API_KEY" + + +def test_startup_logs_the_configured_provider(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GEMINI_API_KEY", "test-key") + get_settings.cache_clear() + + with capture_logs() as logs: + llm.log_configuration() + + assert logs == [ + { + "event": "llm.provider", + "log_level": "info", + "provider": "gemini", + "model": get_settings().gemini_pro_model, + } + ] diff --git a/backend/tests/test_llm_provider.py b/backend/tests/test_llm_provider.py new file mode 100644 index 0000000..3360ca9 --- /dev/null +++ b/backend/tests/test_llm_provider.py @@ -0,0 +1,142 @@ +"""LLM provider selection, the extractor's use of it, and the shared retry helper.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from backend.config import get_settings +from backend.pipeline import extractor +from backend.services import llm +from backend.services.llm.base import ( + LLMNotConfiguredError, + LLMUnavailableError, + parse_json_payload, + with_retries, +) +from backend.services.llm.extraction import ExtractionResult +from backend.services.llm.gemini import GeminiProvider +from backend.services.llm.pioneer import PioneerProvider + + +def _configure(monkeypatch: pytest.MonkeyPatch, **env: str) -> None: + for key, value in env.items(): + monkeypatch.setenv(key, value) + get_settings.cache_clear() + + +def test_no_provider_without_a_key() -> None: + assert llm.get_provider() is None + with pytest.raises(LLMNotConfiguredError, match="GEMINI_API_KEY"): + llm.require_provider() + + +def test_gemini_is_the_default_provider(monkeypatch: pytest.MonkeyPatch) -> None: + _configure(monkeypatch, GEMINI_API_KEY="test-key") + + provider = llm.get_provider() + + assert isinstance(provider, GeminiProvider) + assert provider.model == get_settings().gemini_pro_model + + +def test_llm_provider_selects_pioneer(monkeypatch: pytest.MonkeyPatch) -> None: + _configure(monkeypatch, LLM_PROVIDER="pioneer", PIONEER_API_KEY="test-key") + + assert isinstance(llm.get_provider(), PioneerProvider) + + +def test_no_silent_fallback_to_the_other_provider(monkeypatch: pytest.MonkeyPatch) -> None: + _configure(monkeypatch, LLM_PROVIDER="pioneer", GEMINI_API_KEY="test-key") + + assert llm.get_provider() is None + assert "PIONEER_API_KEY" in llm.not_configured_message() + + +class _FakeProvider: + name = "fake" + model = "fake-1" + + def __init__(self, fail: bool = False) -> None: + self.fail = fail + + async def extract_facts(self, **_: Any) -> ExtractionResult: + if self.fail: + raise LLMUnavailableError("provider down") + return ExtractionResult( + category="maintenance", + priority="high", + facts_to_update=[ + {"section": "maintenance", "field": "x", "value": "y", "confidence": 0.95} + ], + summary="from provider", + source=self.name, + ) + + +async def test_extractor_uses_the_configured_provider(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(extractor, "get_provider", lambda: _FakeProvider()) + + result = await extractor.extract( + property_name="P", current_context_excerpt="", source="email", raw_content="Heizung kalt" + ) + + assert result.source == "fake" + assert result.summary == "from provider" + + +async def test_extractor_falls_back_to_rules_when_provider_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(extractor, "get_provider", lambda: _FakeProvider(fail=True)) + + result = await extractor.extract( + property_name="P", + current_context_excerpt="", + source="email", + raw_content="Subject: Heizung\n\nDie Heizung ist kalt.", + ) + + assert result.source == "rule" + + +async def test_with_retries_turns_a_hang_into_unavailable() -> None: + calls = 0 + + async def hang() -> str: + nonlocal calls + calls += 1 + await asyncio.sleep(10) + return "never" + + with pytest.raises(LLMUnavailableError, match="2 attempt"): + await with_retries(hang, max_attempts=2, timeout_s=0.01, event="test.call") + assert calls == 2 + + +async def test_with_retries_does_not_retry_missing_configuration() -> None: + calls = 0 + + async def unconfigured() -> str: + nonlocal calls + calls += 1 + raise LLMNotConfiguredError("no key") + + with pytest.raises(LLMNotConfiguredError): + await with_retries(unconfigured, max_attempts=3, timeout_s=1, event="test.call") + assert calls == 1 + + +@pytest.mark.parametrize( + "text", + ['{"a": 1}', '```json\n{"a": 1}\n```', 'Sure, here it is: {"a": 1} Thanks.'], +) +def test_parse_json_payload_accepts_common_wrappings(text: str) -> None: + assert parse_json_payload(text) == {"a": 1} + + +def test_parse_json_payload_rejects_non_objects() -> None: + with pytest.raises(ValueError): + parse_json_payload("[1, 2]") diff --git a/backend/tests/test_onboarding.py b/backend/tests/test_onboarding.py index 915adbc..8370b2e 100644 --- a/backend/tests/test_onboarding.py +++ b/backend/tests/test_onboarding.py @@ -1,49 +1,38 @@ -"""Tests for Phase 10 Step 10.3 — onboarding view. +"""Tests for the onboarding view. -The onboarding view has one Gemini call (the 12-month briefing) and -four deterministic sections. We monkeypatch the Gemini choke-point so -tests are offline + deterministic; the deterministic sections are +The onboarding view has one LLM call (the 12-month briefing) and +four deterministic sections. We monkeypatch the provider lookup +(``onboarding.get_provider``) so tests are offline + deterministic; the deterministic sections are exercised end-to-end against a real DB row, so cleanup matters. """ from __future__ import annotations +from datetime import UTC from typing import Any from uuid import UUID, uuid4 +import httpx import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker -from backend.services import gemini, onboarding -from connectors.migrations import apply_all as ensure_migrations +from backend.services import onboarding pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 +class _StubProvider: + """Stands in for an LLM provider; delegates complete_text to a test function.""" - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() + name = "stub" + model = "stub" + def __init__(self, draft: Any) -> None: + self._draft = draft -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - -async def _setup_or_skip() -> None: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") - ensure_migrations() + async def complete_text(self, **kwargs: Any) -> str: + return str(await self._draft(**kwargs)) async def _seed_property( @@ -55,12 +44,9 @@ async def _seed_property( async with factory() as session: b = ( await session.execute( - text( - "INSERT INTO buildings (address) VALUES " - "('Onboarding Test Bldg') RETURNING id" - ) + text("INSERT INTO buildings (address) VALUES ('Onboarding Test Bldg') RETURNING id") ) - ).first() + ).one() p = ( await session.execute( text( @@ -76,7 +62,7 @@ async def _seed_property( "meta": _json(metadata or {}), }, ) - ).first() + ).one() await session.commit() return b.id, p.id @@ -105,12 +91,8 @@ async def _cleanup(building_id: UUID, property_id: UUID) -> None: text("DELETE FROM events WHERE property_id = :pid"), {"pid": property_id}, ) - await session.execute( - text("DELETE FROM properties WHERE id = :id"), {"id": property_id} - ) - await session.execute( - text("DELETE FROM buildings WHERE id = :id"), {"id": building_id} - ) + await session.execute(text("DELETE FROM properties WHERE id = :id"), {"id": property_id}) + await session.execute(text("DELETE FROM buildings WHERE id = :id"), {"id": building_id}) await session.commit() @@ -121,9 +103,9 @@ async def _cleanup(building_id: UUID, property_id: UUID) -> None: async def test_cache_key_stable_for_same_inputs() -> None: """Identical timestamps → identical cache key.""" - from datetime import datetime, timezone + from datetime import datetime - ts = datetime(2026, 4, 1, 12, 0, tzinfo=timezone.utc) + ts = datetime(2026, 4, 1, 12, 0, tzinfo=UTC) a = onboarding._cache_key(ts, ts, ts) b = onboarding._cache_key(ts, ts, ts) assert a == b @@ -131,10 +113,10 @@ async def test_cache_key_stable_for_same_inputs() -> None: async def test_cache_key_changes_when_any_timestamp_moves() -> None: """A shift in any of the three timestamps changes the cache key.""" - from datetime import datetime, timezone + from datetime import datetime - ts = datetime(2026, 4, 1, 12, 0, tzinfo=timezone.utc) - later = datetime(2026, 4, 1, 12, 0, 1, tzinfo=timezone.utc) + ts = datetime(2026, 4, 1, 12, 0, tzinfo=UTC) + later = datetime(2026, 4, 1, 12, 0, 1, tzinfo=UTC) base = onboarding._cache_key(ts, ts, ts) assert onboarding._cache_key(later, ts, ts) != base assert onboarding._cache_key(ts, later, ts) != base @@ -150,13 +132,13 @@ async def test_cache_key_handles_none_inputs() -> None: # ---------------------------------------------------------------------------- -# DB integration — empty property renders gracefully +# DB integration: empty property renders gracefully # ---------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_render_onboarding_empty_property(monkeypatch: pytest.MonkeyPatch) -> None: """A bare property with no facts/events still produces all 5 sections.""" - await _setup_or_skip() bid, pid = await _seed_property( metadata={ "kaltmiete": "1100 EUR", @@ -164,8 +146,8 @@ async def test_render_onboarding_empty_property(monkeypatch: pytest.MonkeyPatch) } ) try: - # Force the Gemini-unavailable path so we don't hit the network. - monkeypatch.setattr(gemini, "is_available", lambda: False, raising=True) + # No LLM provider: the briefing degrades to a notice, nothing hits the network. + monkeypatch.setattr(onboarding, "get_provider", lambda: None) factory = get_sessionmaker() async with factory() as session: @@ -182,26 +164,26 @@ async def test_render_onboarding_empty_property(monkeypatch: pytest.MonkeyPatch) assert "Where to look for more" in md # No-issues message. assert "No open issues" in md - # Briefing degraded message present. - assert "Briefing skipped" in md + # With no LLM reachable the briefing degrades to an explicit notice. + assert "Briefing unavailable" in md finally: await _cleanup(bid, pid) # ---------------------------------------------------------------------------- -# DB integration — open issues surface +# DB integration: open issues surface # ---------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_render_onboarding_surfaces_open_issues( monkeypatch: pytest.MonkeyPatch, ) -> None: """A property with an active leak fact + open uncertainty + pending rejection shows all three under "Open issues right now".""" - await _setup_or_skip() bid, pid = await _seed_property() try: - monkeypatch.setattr(gemini, "is_available", lambda: False, raising=True) + monkeypatch.setattr(onboarding, "get_provider", lambda: None) factory = get_sessionmaker() async with factory() as session: @@ -218,7 +200,7 @@ async def test_render_onboarding_surfaces_open_issues( ), {"ref": ref, "pid": pid}, ) - ).first() + ).one() await session.execute( text( """ @@ -288,17 +270,16 @@ async def test_render_onboarding_surfaces_open_issues( # ---------------------------------------------------------------------------- -# DB integration — Gemini briefing path with cache +# DB integration: LLM briefing path with cache # ---------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_briefing_caches_on_metadata(monkeypatch: pytest.MonkeyPatch) -> None: - """First render calls Gemini; second render reuses the cached briefing.""" - await _setup_or_skip() + """First render calls the LLM; second render reuses the cached briefing.""" bid, pid = await _seed_property() try: - # Force "available" + stub the Gemini drafter so the test stays offline. - monkeypatch.setattr(gemini, "is_available", lambda: True, raising=True) + # A stub provider keeps the test offline while exercising the LLM path. call_count = {"n": 0} async def _stub_draft(**kwargs: Any) -> str: @@ -309,9 +290,7 @@ async def _stub_draft(**kwargs: Any) -> str: "- Gap: no rent history captured." ) - monkeypatch.setattr( - gemini, "draft_onboarding_briefing", _stub_draft, raising=True - ) + monkeypatch.setattr(onboarding, "get_provider", lambda: _StubProvider(_stub_draft)) factory = get_sessionmaker() async with factory() as session: @@ -327,28 +306,71 @@ async def _stub_draft(**kwargs: Any) -> str: await _cleanup(bid, pid) +@pytest.mark.usefixtures("db") +async def test_briefing_source_says_how_the_briefing_was_produced( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """No provider: 'unavailable'; then the LLM writes it ('llm'); then 'cache'.""" + bid, pid = await _seed_property() + try: + factory = get_sessionmaker() + monkeypatch.setattr(onboarding, "get_provider", lambda: None) + async with factory() as session: + keyless = await onboarding.render_onboarding_document(session, pid) + assert keyless.briefing_source == "unavailable" + assert "Briefing unavailable" in keyless.markdown + + async def _stub_draft(**kwargs: Any) -> str: + return "- Gap: no rent history captured." + + monkeypatch.setattr(onboarding, "get_provider", lambda: _StubProvider(_stub_draft)) + async with factory() as session: + written = await onboarding.render_onboarding_document(session, pid) + async with factory() as session: + reread = await onboarding.render_onboarding_document(session, pid) + assert written.briefing_source == "llm" + assert reread.briefing_source == "cache" + finally: + await _cleanup(bid, pid) + + +@pytest.mark.usefixtures("db") +async def test_onboarding_endpoint_reports_a_keyless_briefing() -> None: + """With no LLM key the API must not present the briefing as LLM-written.""" + from backend.main import app # noqa: PLC0415 + + bid, pid = await _seed_property() + try: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + response = await client.get(f"/admin/properties/{pid}/onboarding") + assert response.status_code == 200 + body = response.json() + assert body["briefing_source"] == "unavailable" + assert body["cached"] is False + finally: + await _cleanup(bid, pid) + + +@pytest.mark.usefixtures("db") async def test_cache_invalidates_on_new_fact(monkeypatch: pytest.MonkeyPatch) -> None: - """Inserting a new fact bumps last-fact timestamp → cache key flips → Gemini called again.""" - await _setup_or_skip() + """A new fact changes the cache key, so the next render calls the LLM again.""" bid, pid = await _seed_property() try: - monkeypatch.setattr(gemini, "is_available", lambda: True, raising=True) call_count = {"n": 0} async def _stub_draft(**kwargs: Any) -> str: call_count["n"] += 1 return f"- Briefing call #{call_count['n']}.\n- Gap: ongoing." - monkeypatch.setattr( - gemini, "draft_onboarding_briefing", _stub_draft, raising=True - ) + monkeypatch.setattr(onboarding, "get_provider", lambda: _StubProvider(_stub_draft)) factory = get_sessionmaker() async with factory() as session: await onboarding.render_onboarding(session, pid) assert call_count["n"] == 1 - # Insert a fact — moves last_fact and flips the cache key. + # Insert a fact: moves last_fact and flips the cache key. async with factory() as session: ref = f"cache-{uuid4().hex[:8]}" ev = ( @@ -362,7 +384,7 @@ async def _stub_draft(**kwargs: Any) -> str: ), {"ref": ref, "pid": pid}, ) - ).first() + ).one() await session.execute( text( """ @@ -387,19 +409,19 @@ async def _stub_draft(**kwargs: Any) -> str: # ---------------------------------------------------------------------------- -# DB integration — recurring patterns surface in "Watch out for" +# DB integration: recurring patterns surface in "Watch out for" # ---------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_watch_out_surfaces_recurring_constraint( monkeypatch: pytest.MonkeyPatch, ) -> None: """A constraint that has triggered ≥2 times on this property surfaces under 'Watch out for'. Single-trigger constraints do not (noise filter).""" - await _setup_or_skip() bid, pid = await _seed_property() try: - monkeypatch.setattr(gemini, "is_available", lambda: False, raising=True) + monkeypatch.setattr(onboarding, "get_provider", lambda: None) factory = get_sessionmaker() async with factory() as session: @@ -419,7 +441,7 @@ async def test_watch_out_surfaces_recurring_constraint( ), {"ref": ref, "pid": pid}, ) - ).first() + ).one() await session.execute( text( """ @@ -448,9 +470,9 @@ async def test_watch_out_surfaces_recurring_constraint( await _cleanup(bid, pid) +@pytest.mark.usefixtures("db") async def test_render_onboarding_404s_for_missing_property() -> None: """A missing property surfaces a clean ValueError from the renderer.""" - await _setup_or_skip() factory = get_sessionmaker() async with factory() as session: with pytest.raises(ValueError, match="not found"): diff --git a/backend/tests/test_pipeline_happy_path.py b/backend/tests/test_pipeline_happy_path.py index 057d240..31e593a 100644 --- a/backend/tests/test_pipeline_happy_path.py +++ b/backend/tests/test_pipeline_happy_path.py @@ -1,15 +1,20 @@ -"""Mandatory integration test — protects the demo spine. +"""End-to-end pipeline test: email event in, sourced fact and markdown out. Flow under test: -- Insert an email event mentioning Apt 4B. -- Run the worker once. -- Assert the event now has ``processed_at``, a fact row was written with - ``source_event_id`` pointing at that event, and the rendered markdown - contains the new fact alongside an ``[source: ]`` link. - -The test talks to the real dev Postgres on :5433 (same one the seeder uses). -It is auto-skipped when the DB is unreachable so CI without Docker doesn't -fail spuriously. + +- Create a throwaway property whose alias the email mentions. +- Insert an email event without a ``property_id`` so the router has to + resolve it. +- Process that one event through the worker (route, extract, diff, + validate, apply, materialize). +- Assert the event is marked processed against the right property, at + least one fact carries ``source_event_id`` = the event, and the rendered + markdown links that event id. + +The test uses :func:`process_specific` rather than draining the queue, so it +never touches other pending events in the database it runs against. It runs +without API keys: the rule-based extractor handles the heating complaint. +Everything it creates is deleted in ``finally``. """ from __future__ import annotations @@ -19,102 +24,109 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker from backend.pipeline.events import insert_event from backend.pipeline.renderer import render_markdown -from backend.pipeline.worker import process_batch - -pytestmark = pytest.mark.asyncio +from backend.pipeline.worker import process_specific - -async def _db_reachable() -> bool: - """Return True if we can SELECT 1 from the configured database.""" - try: - factory = get_sessionmaker() - async with factory() as session: - await session.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 — any failure = skip - return False +pytestmark = [pytest.mark.asyncio, pytest.mark.usefixtures("db")] -async def _pick_berlin_4b_id() -> uuid.UUID | None: - """Look up the seeded Berliner 4B property id, if present.""" +async def _create_property(alias: str) -> tuple[uuid.UUID, uuid.UUID]: factory = get_sessionmaker() async with factory() as session: - row = ( + building_id = ( + await session.execute( + text("INSERT INTO buildings (address) VALUES (:a) RETURNING id"), + {"a": f"{alias} building"}, + ) + ).scalar_one() + property_id = ( await session.execute( text( - "SELECT id FROM properties WHERE name = :name" + """ + INSERT INTO properties (name, address, building_id, aliases) + VALUES (:name, :addr, :bid, ARRAY[:alias]) + RETURNING id + """ ), - {"name": "Berliner Strasse 12, Apt 4B"}, + { + "name": alias, + "addr": f"{alias}, 10115 Berlin", + "bid": building_id, + "alias": alias, + }, ) - ).first() - return uuid.UUID(str(row.id)) if row else None + ).scalar_one() + await session.commit() + return building_id, property_id -async def test_happy_path_email_creates_sourced_fact() -> None: - """End-to-end: event insert → worker → sourced fact → markdown render.""" - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") - - property_id = await _pick_berlin_4b_id() - if property_id is None: - pytest.skip("seed dataset not loaded — run `python -m seed.seed` first") - - source_ref = f"test-{uuid.uuid4()}" - raw_content = ( - "From: lukas.weber@tenant.demo\n" - "Subject: Heating completely out in Apt 4B again\n\n" - "The radiators are cold this morning and the boiler is rattling " - "louder than ever. Fourth time this winter." - ) - +async def _delete_created_rows( + building_id: uuid.UUID, property_id: uuid.UUID, source_ref: str +) -> None: factory = get_sessionmaker() async with factory() as session: - event_id, inserted = await insert_event( - session, - source="email", - source_ref=source_ref, - raw_content=raw_content, + await session.execute( + text("DELETE FROM facts WHERE property_id = :pid"), {"pid": property_id} + ) + await session.execute( + text("DELETE FROM events WHERE source = 'email' AND source_ref = :ref"), + {"ref": source_ref}, ) + await session.execute(text("DELETE FROM properties WHERE id = :pid"), {"pid": property_id}) + await session.execute(text("DELETE FROM buildings WHERE id = :bid"), {"bid": building_id}) await session.commit() - assert inserted is True - processed = await process_batch(max_events=10) - assert processed >= 1 - async with factory() as session: - event_row = ( - await session.execute( - text( - "SELECT processed_at, property_id, processing_error " - "FROM events WHERE id = :id" - ), - {"id": event_id}, - ) - ).one() - assert event_row.processed_at is not None - assert event_row.processing_error is None - assert uuid.UUID(str(event_row.property_id)) == property_id +async def test_happy_path_email_creates_sourced_fact() -> None: + """Event insert → worker → sourced fact → markdown render.""" + suffix = uuid.uuid4().hex[:6] + alias = f"Testweg {suffix} Apt 9Q" + source_ref = f"test-happy-path-{suffix}" + building_id, property_id = await _create_property(alias) + try: + raw_content = ( + "From: tenant@example.com\n" + f"Subject: Heating completely out in {alias} again\n\n" + "The radiators are cold this morning and the boiler is rattling " + "louder than ever. Fourth time this winter." + ) - facts = ( - await session.execute( - text( - """ - SELECT id, section, field, value, confidence - FROM facts - WHERE source_event_id = :eid - ORDER BY section, field - """ - ), - {"eid": event_id}, + factory = get_sessionmaker() + async with factory() as session: + event_id, inserted = await insert_event( + session, source="email", source_ref=source_ref, raw_content=raw_content ) - ).all() - assert facts, "expected at least one fact written for the event" + await session.commit() + assert inserted is True - markdown = await render_markdown(session, property_id) + assert await process_specific(event_id) is True - # Markdown must reference the event id inline for the sourcing UI. - assert str(event_id) in markdown, "rendered markdown is missing the source event id" + async with factory() as session: + event_row = ( + await session.execute( + text( + "SELECT processed_at, property_id, processing_error " + "FROM events WHERE id = :id" + ), + {"id": event_id}, + ) + ).one() + assert event_row.processing_error is None + assert event_row.processed_at is not None + assert uuid.UUID(str(event_row.property_id)) == property_id + + facts = ( + await session.execute( + text("SELECT section, field FROM facts WHERE source_event_id = :eid"), + {"eid": event_id}, + ) + ).all() + assert facts, "expected at least one fact written for the event" + + markdown = await render_markdown(session, property_id) + + assert str(event_id) in markdown, "rendered markdown is missing the source event id" + finally: + await _delete_created_rows(building_id, property_id, source_ref) diff --git a/backend/tests/test_replay.py b/backend/tests/test_replay.py index 1c7d471..6ac85c1 100644 --- a/backend/tests/test_replay.py +++ b/backend/tests/test_replay.py @@ -1,4 +1,4 @@ -"""Tests for Phase 10 Step 10.2 — sequential replay engine. +"""Tests for the sequential replay engine. The engine drives :func:`backend.pipeline.worker.process_one`, so we monkeypatch that to keep tests offline + fast. Pause / resume / stop @@ -15,50 +15,21 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker from backend.services import replay -from connectors.migrations import apply_all as ensure_migrations pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - -async def _setup_or_skip() -> None: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") - ensure_migrations() - - async def _seed_property_with_events(n_events: int = 3) -> tuple[UUID, list[UUID]]: """Insert one property + N events for the replay run to chew on.""" factory = get_sessionmaker() async with factory() as session: b = ( await session.execute( - text( - "INSERT INTO buildings (address) VALUES " - "('Test Replay Bldg') RETURNING id" - ) + text("INSERT INTO buildings (address) VALUES ('Test Replay Bldg') RETURNING id") ) - ).first() + ).one() p = ( await session.execute( text( @@ -70,7 +41,7 @@ async def _seed_property_with_events(n_events: int = 3) -> tuple[UUID, list[UUID ), {"bid": b.id}, ) - ).first() + ).one() event_ids: list[UUID] = [] for i in range(n_events): ref = f"replay-{uuid4().hex[:8]}" @@ -92,7 +63,7 @@ async def _seed_property_with_events(n_events: int = 3) -> tuple[UUID, list[UUID "pid": p.id, }, ) - ).first() + ).one() event_ids.append(e.id) await session.commit() return p.id, event_ids @@ -124,29 +95,23 @@ async def _cleanup(property_id: UUID) -> None: # Building lookup via property no longer possible after delete; we # just clean the test row by name. await session.execute( - text( - "DELETE FROM properties WHERE id = :pid " - ), + text("DELETE FROM properties WHERE id = :pid "), {"pid": property_id}, ) - await session.execute( - text("DELETE FROM buildings WHERE address = 'Test Replay Bldg'") - ) + await session.execute(text("DELETE FROM buildings WHERE address = 'Test Replay Bldg'")) await session.commit() +@pytest.mark.usefixtures("db") async def test_pause_resume_stop_full_cycle(monkeypatch: pytest.MonkeyPatch) -> None: """Start → pause → resume → stop hits every state and the durable row tracks it.""" - await _setup_or_skip() pid, _ = await _seed_property_with_events(n_events=3) try: # Replace process_one with a fast no-op so the test doesn't hit Gemini. async def _noop_process_one(_session: Any) -> UUID | None: return None - monkeypatch.setattr( - replay, "process_one", _noop_process_one, raising=True - ) + monkeypatch.setattr(replay, "process_one", _noop_process_one, raising=True) snapshot = await replay.start_run( property_id=pid, @@ -172,19 +137,18 @@ async def _noop_process_one(_session: Any) -> UUID | None: await _cleanup(pid) +@pytest.mark.usefixtures("db") async def test_scheduled_pause_fires_at_checkpoint( monkeypatch: pytest.MonkeyPatch, ) -> None: """A scheduled pause at at_seconds=0 puts the run into ``paused`` immediately.""" - await _setup_or_skip() pid, _ = await _seed_property_with_events(n_events=2) try: + async def _noop_process_one(_session: Any) -> UUID | None: return None - monkeypatch.setattr( - replay, "process_one", _noop_process_one, raising=True - ) + monkeypatch.setattr(replay, "process_one", _noop_process_one, raising=True) snapshot = await replay.start_run( property_id=pid, @@ -214,11 +178,11 @@ async def _noop_process_one(_session: Any) -> UUID | None: await _cleanup(pid) +@pytest.mark.usefixtures("db") async def test_reset_property_wipes_facts_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """``reset_property=True`` clears facts but leaves stammdaten / events.""" - await _setup_or_skip() pid, event_ids = await _seed_property_with_events(n_events=1) try: # Pre-seed a fact so reset has something to delete. @@ -243,9 +207,7 @@ async def test_reset_property_wipes_facts_only( async def _noop_process_one(_session: Any) -> UUID | None: return None - monkeypatch.setattr( - replay, "process_one", _noop_process_one, raising=True - ) + monkeypatch.setattr(replay, "process_one", _noop_process_one, raising=True) snapshot = await replay.start_run( property_id=pid, @@ -263,17 +225,13 @@ async def _noop_process_one(_session: Any) -> UUID | None: async with factory() as session: facts_left = ( await session.execute( - text( - "SELECT COUNT(*) FROM facts WHERE property_id = :pid" - ), + text("SELECT COUNT(*) FROM facts WHERE property_id = :pid"), {"pid": pid}, ) ).scalar() events_left = ( await session.execute( - text( - "SELECT COUNT(*) FROM events WHERE property_id = :pid" - ), + text("SELECT COUNT(*) FROM events WHERE property_id = :pid"), {"pid": pid}, ) ).scalar() @@ -292,7 +250,7 @@ async def _noop_process_one(_session: Any) -> UUID | None: async def test_normalise_pauses_validates_and_sorts() -> None: """``_normalise_pauses`` drops bad rows and sorts by ``at_seconds``.""" - raw = [ + raw: list[Any] = [ {"at_seconds": 30.0, "message": "second"}, {"at_seconds": 10.0, "message": "first"}, {"at_seconds": "not_a_number", "message": "drop me"}, diff --git a/backend/tests/test_router.py b/backend/tests/test_router.py index 3b6be6a..5910fa9 100644 --- a/backend/tests/test_router.py +++ b/backend/tests/test_router.py @@ -1 +1,5 @@ -"""Router tests. Implemented in Phase 1.""" +"""Router unit tests (none yet). + +The structured router is covered by ``test_routing.py``, and the worker's +routing step end to end by ``test_pipeline_happy_path.py``. +""" diff --git a/backend/tests/test_routing.py b/backend/tests/test_routing.py index 59f5691..b6bc2f7 100644 --- a/backend/tests/test_routing.py +++ b/backend/tests/test_routing.py @@ -1,4 +1,8 @@ -"""Tests for the structured router (Phase 8.1). +"""Tests for the structured router. + +The structured router resolves an event to a property, a building or a +Liegenschaft (WEG) from explicit references: EH / MIE unit ids, HAUS +ids, the bank ``kategorie`` and German WEG keywords. These exercise the live routing precedence against a fresh DB seeded with the Buena Stammdaten loader. Skipped when the dev Postgres or @@ -10,59 +14,33 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker from backend.pipeline.router import ( - StructuredRoute, WEG_KEYWORDS, + StructuredRoute, route_structured, ) -from connectors import buena_archive, buena_loader -from connectors.base import DataMissing +from connectors import buena_loader +from connectors.base import DataMissingError from connectors.migrations import apply_all as ensure_migrations pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - """Drop the cached async engine + sessionmaker so the test gets a fresh loop. - - pytest-asyncio runs every coroutine test under its own event loop. The - engine cached in ``backend.db.session.get_engine`` binds to the first - loop it sees; later tests reach a dead loop unless we reset. - """ - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - def _ensure_buena_stammdaten() -> None: - """Idempotent loader call — costs nothing if data is already loaded.""" + """Idempotent loader call; costs nothing if data is already loaded.""" try: buena_loader.load_from_disk() - except DataMissing as exc: - pytest.skip(f"Buena dataset not available — {exc}") + except DataMissingError as exc: + pytest.skip(f"Buena dataset not available: {exc}") async def _setup_or_skip() -> None: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") ensure_migrations() _ensure_buena_stammdaten() +@pytest.mark.usefixtures("db") async def test_unit_event_routes_to_property() -> None: """``EH-NNN`` in metadata routes to the matching property.""" await _setup_or_skip() @@ -71,10 +49,7 @@ async def test_unit_event_routes_to_property() -> None: # Pick any property and use its EH alias row = ( await session.execute( - text( - "SELECT id, aliases FROM properties " - "WHERE 'EH-005' = ANY(aliases) LIMIT 1" - ) + text("SELECT id, aliases FROM properties WHERE 'EH-005' = ANY(aliases) LIMIT 1") ) ).first() if row is None: @@ -94,6 +69,7 @@ async def test_unit_event_routes_to_property() -> None: assert result.liegenschaft_id is None +@pytest.mark.usefixtures("db") async def test_haus_only_event_routes_to_building() -> None: """``HAUS-NN`` in raw_text with no unit ref routes to the building.""" await _setup_or_skip() @@ -101,10 +77,7 @@ async def test_haus_only_event_routes_to_building() -> None: async with factory() as session: row = ( await session.execute( - text( - "SELECT id FROM buildings " - "WHERE metadata->>'buena_haus_id' = 'HAUS-12'" - ) + text("SELECT id FROM buildings WHERE metadata->>'buena_haus_id' = 'HAUS-12'") ) ).first() if row is None: @@ -122,6 +95,7 @@ async def test_haus_only_event_routes_to_building() -> None: assert result.liegenschaft_id is None +@pytest.mark.usefixtures("db") async def test_weg_kategorie_routes_to_liegenschaft() -> None: """``kategorie=dienstleister`` with no EH/MIE/HAUS → Liegenschaft.""" await _setup_or_skip() @@ -131,7 +105,7 @@ async def test_weg_kategorie_routes_to_liegenschaft() -> None: session, metadata={ "kategorie": "dienstleister", - "verwendungszweck": "Rechnung R20240184 Sanitaer Schulze GmbH", + "verwendungszweck": "Rechnung R20240184 Sanitaer Demo GmbH", }, ) assert result.method == "weg_kategorie" @@ -140,6 +114,7 @@ async def test_weg_kategorie_routes_to_liegenschaft() -> None: assert result.building_id is None +@pytest.mark.usefixtures("db") async def test_weg_keyword_case_insensitive_word_boundary() -> None: """German WEG keyword matching is case-insensitive + word-boundary.""" await _setup_or_skip() @@ -160,6 +135,7 @@ async def test_weg_keyword_case_insensitive_word_boundary() -> None: assert result.method in {"weg_keyword", "weg_kategorie"} +@pytest.mark.usefixtures("db") async def test_unknown_event_is_unrouted() -> None: """No EH/MIE/HAUS/INV/kategorie/keyword → unrouted with reason.""" await _setup_or_skip() @@ -175,7 +151,7 @@ async def test_unknown_event_is_unrouted() -> None: async def test_weg_keyword_set_includes_german_lexicon() -> None: - """Sanity check on the keyword list — full Hausverwaltung vocabulary.""" + """Sanity check on the keyword list: full Hausverwaltung vocabulary.""" expected = { "hausgeld", "verwaltergebühr", diff --git a/backend/tests/test_scheduler.py b/backend/tests/test_scheduler.py new file mode 100644 index 0000000..39bac09 --- /dev/null +++ b/backend/tests/test_scheduler.py @@ -0,0 +1,28 @@ +"""Optional pollers are only scheduled when configured.""" + +from __future__ import annotations + +import pytest + +from backend import scheduler +from backend.config import get_settings + + +def _job_ids() -> set[str]: + return {job.id for job in scheduler.build_scheduler().get_jobs()} + + +def test_default_install_schedules_only_core_jobs(monkeypatch: pytest.MonkeyPatch) -> None: + for key in ("IMAP_USER", "IMAP_PASSWORD", "MOCK_ERP_URL"): + monkeypatch.setenv(key, "") + get_settings.cache_clear() + + assert _job_ids() == {"worker_tick", "signal_eval"} + + +def test_imap_job_registered_when_credentials_are_set(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("IMAP_USER", "inbox@example.com") + monkeypatch.setenv("IMAP_PASSWORD", "app-password") + get_settings.cache_clear() + + assert "imap_poll" in _job_ids() diff --git a/backend/tests/test_schema.py b/backend/tests/test_schema.py new file mode 100644 index 0000000..587127f --- /dev/null +++ b/backend/tests/test_schema.py @@ -0,0 +1,25 @@ +"""The schema runs on plain PostgreSQL: no extension-specific column types.""" + +from __future__ import annotations + +import psycopg2 +import pytest + +from backend.config import get_settings + + +@pytest.mark.usefixtures("db") +def test_no_columns_need_an_extension() -> None: + with psycopg2.connect(get_settings().database_url_sync) as conn, conn.cursor() as cur: + cur.execute( + """ + SELECT table_name, column_name, udt_name + FROM information_schema.columns + WHERE table_schema = 'public' + AND (column_name = 'embedding' OR data_type = 'USER-DEFINED') + """ + ) + rows = cur.fetchall() + conn.close() + + assert rows == [] diff --git a/backend/tests/test_signals.py b/backend/tests/test_signals.py index 4cd9efd..326a389 100644 --- a/backend/tests/test_signals.py +++ b/backend/tests/test_signals.py @@ -1 +1,252 @@ -"""Signal rule tests. Implemented in Phase 3.""" +"""Signal evaluator: dedupe by natural key, and no re-raising after a decision. + +A fake rule stands in for the real rule set so each test controls exactly +which candidate fires and touches no other signals in the database. Approve +and reject go through the HTTP API, so the status transitions under test are +the ones operators trigger. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator +from dataclasses import dataclass +from typing import Any +from uuid import UUID, uuid4 + +import httpx +import psycopg2 +import pytest +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from backend.config import get_settings +from backend.db.session import get_sessionmaker +from backend.signals import drafter, evaluator +from backend.signals.evaluator import natural_key +from backend.signals.types import ProposedAction, SignalCandidate +from connectors.migrations import _MIGRATIONS + + +@dataclass(frozen=True) +class Finding: + property_id: UUID + key: str + + +class _FixedRule: + """Rule double that always reports the same finding.""" + + def __init__(self, candidate: SignalCandidate) -> None: + self.candidate = candidate + + async def evaluate(self, session: AsyncSession) -> list[SignalCandidate]: + return [self.candidate] + + +async def _fake_draft(session: AsyncSession, candidate: SignalCandidate) -> ProposedAction: + return ProposedAction( + type="owner_notification", + channel="email", + recipient="owner@example.com", + subject="Heating keeps failing", + drafted_message="Three heating complaints in four months.", + payload={"hint": candidate.action_hint}, + ) + + +@pytest.fixture +async def finding(db: None, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[Finding]: + """A throwaway property with one recurring finding wired into the evaluator.""" + factory = get_sessionmaker() + async with factory() as session: + building_id = ( + await session.execute( + text("INSERT INTO buildings (address) VALUES ('Test Signals Bldg') RETURNING id") + ) + ).scalar_one() + property_id = ( + await session.execute( + text( + "INSERT INTO properties (name, address, building_id) " + "VALUES (:n, 'Test Signals 1', :bid) RETURNING id" + ), + {"n": f"Test Signals {uuid4().hex[:6]}", "bid": building_id}, + ) + ).scalar_one() + await session.commit() + + hint = {"type": "dispatch_contractor", "topic": "heating"} + candidate = SignalCandidate( + type="recurring_maintenance", + severity="urgent", + message="3 heating complaints in 120 days", + property_id=property_id, + action_hint=hint, + ) + monkeypatch.setattr(evaluator, "_RULES", [_FixedRule(candidate)]) + monkeypatch.setattr(drafter, "draft", _fake_draft) + + try: + yield Finding( + property_id=property_id, + key=natural_key(property_id, "recurring_maintenance", hint), + ) + finally: + async with factory() as session: + ids = "SELECT id FROM signals WHERE property_id = :pid" + await session.execute( + text(f"DELETE FROM outbox WHERE signal_id IN ({ids})"), {"pid": property_id} + ) + await session.execute( + text(f"DELETE FROM approval_log WHERE signal_id IN ({ids})"), {"pid": property_id} + ) + await session.execute( + text("DELETE FROM signals WHERE property_id = :pid"), {"pid": property_id} + ) + await session.execute( + text("DELETE FROM properties WHERE id = :pid"), {"pid": property_id} + ) + await session.execute( + text("DELETE FROM buildings WHERE id = :bid"), {"bid": building_id} + ) + await session.commit() + + +async def _signals(finding: Finding) -> list[Any]: + """Every signal raised for the test property, oldest first.""" + async with get_sessionmaker()() as session: + return list( + ( + await session.execute( + text( + "SELECT id, status, natural_key FROM signals " + "WHERE property_id = :pid ORDER BY created_at" + ), + {"pid": finding.property_id}, + ) + ).all() + ) + + +def _client() -> httpx.AsyncClient: + from backend.main import app # noqa: PLC0415 + + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") + + +def test_natural_key_separates_scope_and_subtype() -> None: + pid = uuid4() + + assert natural_key(pid, "recurring_maintenance", {"topic": "heating"}) != natural_key( + pid, "recurring_maintenance", {"topic": "water"} + ) + assert natural_key(None, "cross_property_pattern", {"subtype": "shared_boiler"}) == ( + "cross_property_pattern|portfolio|shared_boiler" + ) + + +async def test_pending_signal_is_not_duplicated(finding: Finding) -> None: + assert await evaluator.evaluate_all() == 1 + assert await evaluator.evaluate_all() == 0 + + signals = await _signals(finding) + assert [s.status for s in signals] == ["pending"] + assert signals[0].natural_key == finding.key + + +async def test_approved_signal_is_not_raised_again(finding: Finding) -> None: + await evaluator.evaluate_all() + [signal] = await _signals(finding) + async with _client() as client: + response = await client.post(f"/signals/{signal.id}/approve") + assert response.status_code == 200 + + assert await evaluator.evaluate_all() == 0 + assert await evaluator.evaluate_all() == 0 + + assert [s.status for s in await _signals(finding)] == ["resolved"] + + +async def test_rejected_signal_is_not_raised_again(finding: Finding) -> None: + await evaluator.evaluate_all() + [signal] = await _signals(finding) + async with _client() as client: + response = await client.post(f"/signals/{signal.id}/reject") + assert response.status_code == 200 + + assert await evaluator.evaluate_all() == 0 + + assert [s.status for s in await _signals(finding)] == ["rejected"] + + +async def test_finding_is_raised_again_after_cooldown(finding: Finding) -> None: + await evaluator.evaluate_all() + [signal] = await _signals(finding) + async with _client() as client: + await client.post(f"/signals/{signal.id}/approve") + async with get_sessionmaker()() as session: + await session.execute( + text("UPDATE signals SET resolved_at = now() - interval '8 days' WHERE id = :sid"), + {"sid": signal.id}, + ) + await session.commit() + + assert await evaluator.evaluate_all() == 1 + + assert [s.status for s in await _signals(finding)] == ["resolved", "pending"] + + +async def test_concurrent_evaluators_raise_one_signal( + finding: Finding, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two evaluators that both pass the pending check still insert one row. + + This is the multi-instance race: each API instance runs the evaluator, + and both can see "nothing pending" before either commits. + """ + + async def nothing_raised(session: AsyncSession, key: str, cooldown_days: int) -> bool: + return False + + monkeypatch.setattr(evaluator, "_already_raised", nothing_raised) + + results = await asyncio.gather(evaluator.evaluate_all(), evaluator.evaluate_all()) + + assert sorted(results) == [0, 1] + assert [s.status for s in await _signals(finding)] == ["pending"] + + +async def test_migration_keeps_the_oldest_pending_duplicate(finding: Finding) -> None: + """Duplicates from before the unique index are superseded, not deleted. + + Runs inside one transaction that is rolled back, so the dropped index + and the inserted rows never reach the shared database. + """ + migration = dict(_MIGRATIONS)["0015_signal_pending_unique"] + conn = psycopg2.connect(get_settings().database_url_sync) + try: + with conn.cursor() as cur: + cur.execute("DROP INDEX uq_signals_pending_natural_key") + for days_old in (3, 2, 1): + cur.execute( + "INSERT INTO signals " + "(property_id, type, severity, message, status, created_at, natural_key) " + "VALUES (%s, 'recurring_maintenance', 'urgent', 'duplicate', 'pending', " + "now() - make_interval(days => %s), %s)", + (str(finding.property_id), days_old, finding.key), + ) + cur.execute(migration) + cur.execute( + "SELECT status FROM signals WHERE property_id = %s ORDER BY created_at", + (str(finding.property_id),), + ) + statuses = [row[0] for row in cur.fetchall()] + cur.execute("SELECT to_regclass('uq_signals_pending_natural_key') IS NOT NULL") + index_row = cur.fetchone() + finally: + conn.rollback() + conn.close() + + assert statuses == ["pending", "superseded", "superseded"] + assert index_row == (True,) diff --git a/backend/tests/test_source_links.py b/backend/tests/test_source_links.py index 14dd4ab..c04dea5 100644 --- a/backend/tests/test_source_links.py +++ b/backend/tests/test_source_links.py @@ -1,4 +1,4 @@ -"""Tests for Phase 10 Step 10.4 — ``/events//{source,raw,detail}``. +"""Tests for ``/events//{source,raw,detail}``. These exercise the source-link dispatcher: an invoice/letter event redirects to ``/files/``, an email event to ``/raw``, @@ -16,37 +16,11 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker -from connectors.migrations import apply_all as ensure_migrations pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - -async def _setup_or_skip() -> None: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") - ensure_migrations() - - async def _seed_event( *, source: str, @@ -72,7 +46,7 @@ async def _seed_event( "meta": json.dumps(metadata or {}), }, ) - ).first() + ).one() await session.commit() return UUID(str(row.id)) @@ -80,9 +54,7 @@ async def _seed_event( async def _cleanup_event(event_id: UUID) -> None: factory = get_sessionmaker() async with factory() as session: - await session.execute( - text("DELETE FROM events WHERE id = :eid"), {"eid": event_id} - ) + await session.execute(text("DELETE FROM events WHERE id = :eid"), {"eid": event_id}) await session.commit() @@ -95,9 +67,7 @@ def _async_client() -> httpx.AsyncClient: """ from backend.main import app # noqa: PLC0415 - return httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://testserver" - ) + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") # --------------------------------------------------------------------------- @@ -105,9 +75,9 @@ def _async_client() -> httpx.AsyncClient: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_invoice_source_redirects_to_files() -> None: """An invoice event with original_path → 307 to /files/.""" - await _setup_or_skip() eid = await _seed_event( source="invoice", metadata={"original_path": "invoices/2024/HG-INV-001.pdf"}, @@ -121,9 +91,9 @@ async def test_invoice_source_redirects_to_files() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_letter_source_redirects_to_files() -> None: """A letter event with original_path → 307 to /files/.""" - await _setup_or_skip() eid = await _seed_event( source="letter", metadata={"original_path": "letters/2025/mahnung_001.pdf"}, @@ -137,9 +107,9 @@ async def test_letter_source_redirects_to_files() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_email_source_redirects_to_raw() -> None: """An email event → 307 to /events//raw.""" - await _setup_or_skip() eid = await _seed_event(source="email", raw_content="Subject: hi\n\nBody") try: async with _async_client() as client: @@ -150,9 +120,9 @@ async def test_email_source_redirects_to_raw() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_bank_source_redirects_to_detail() -> None: """A bank event → 307 to /events//detail (JSON envelope).""" - await _setup_or_skip() eid = await _seed_event( source="bank", metadata={"betrag": "1100.00", "kategorie": "miete"}, @@ -166,9 +136,9 @@ async def test_bank_source_redirects_to_detail() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_invoice_without_original_path_falls_through_to_raw() -> None: """If a PDF event lost its original_path, /source still redirects somewhere.""" - await _setup_or_skip() eid = await _seed_event(source="invoice", metadata={}) try: async with _async_client() as client: @@ -180,9 +150,9 @@ async def test_invoice_without_original_path_falls_through_to_raw() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_source_404_for_missing_event() -> None: """An unknown event_id returns 404, not a redirect.""" - await _setup_or_skip() async with _async_client() as client: resp = await client.get(f"/events/{uuid4()}/source", follow_redirects=False) assert resp.status_code == 404 @@ -193,9 +163,9 @@ async def test_source_404_for_missing_event() -> None: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_raw_returns_text_plain() -> None: """The /raw endpoint returns the raw_content as text/plain.""" - await _setup_or_skip() body = "From: a@b\nSubject: test\n\nThis is the body" eid = await _seed_event(source="email", raw_content=body) try: @@ -208,9 +178,9 @@ async def test_raw_returns_text_plain() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_detail_returns_json_envelope() -> None: """The /detail endpoint returns id + source + metadata + snippet.""" - await _setup_or_skip() eid = await _seed_event( source="bank", metadata={"betrag": "1100.00", "kategorie": "miete"}, @@ -229,9 +199,9 @@ async def test_detail_returns_json_envelope() -> None: await _cleanup_event(eid) +@pytest.mark.usefixtures("db") async def test_raw_404_for_missing_event() -> None: """An unknown event id returns 404 from /raw.""" - await _setup_or_skip() async with _async_client() as client: resp = await client.get(f"/events/{uuid4()}/raw") assert resp.status_code == 404 diff --git a/backend/tests/test_trigger_event.py b/backend/tests/test_trigger_event.py new file mode 100644 index 0000000..e4c5423 --- /dev/null +++ b/backend/tests/test_trigger_event.py @@ -0,0 +1,97 @@ +"""POST /debug/trigger_event accepts raw_content or from/subject/body.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from uuid import uuid4 + +import httpx +import pytest +from sqlalchemy import text + +from backend.db.session import get_sessionmaker + +_REF_PREFIX = "test-trigger-" + + +def _client() -> httpx.AsyncClient: + from backend.main import app # noqa: PLC0415 + + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") + + +@pytest.fixture +async def source_ref(db: None) -> AsyncIterator[str]: + ref = f"{_REF_PREFIX}{uuid4().hex[:8]}" + yield ref + async with get_sessionmaker()() as session: + ids = "SELECT id FROM events WHERE source_ref = :ref" + await session.execute( + text(f"DELETE FROM facts WHERE source_event_id IN ({ids})"), {"ref": ref} + ) + await session.execute(text("DELETE FROM events WHERE source_ref = :ref"), {"ref": ref}) + await session.commit() + + +async def _stored_raw_content(ref: str) -> str: + async with get_sessionmaker()() as session: + return str( + ( + await session.execute( + text("SELECT raw_content FROM events WHERE source_ref = :ref"), {"ref": ref} + ) + ).scalar_one() + ) + + +async def test_raw_content_is_stored_verbatim(source_ref: str) -> None: + raw = "From: tenant@example.com\nSubject: Leak\n\nWater is dripping from the ceiling." + async with _client() as client: + response = await client.post( + "/debug/trigger_event", json={"source_ref": source_ref, "raw_content": raw} + ) + + assert response.status_code == 200, response.text + assert response.json()["inserted"] is True + assert await _stored_raw_content(source_ref) == raw + + +async def test_subject_and_body_are_composed_like_imap(source_ref: str) -> None: + async with _client() as client: + response = await client.post( + "/debug/trigger_event", + json={ + "source_ref": source_ref, + "from": "tenant@example.com", + "subject": "Leak", + "body": "Water is dripping from the ceiling.", + }, + ) + + assert response.status_code == 200, response.text + assert await _stored_raw_content(source_ref) == ( + "From: tenant@example.com\nSubject: Leak\n\nWater is dripping from the ceiling.\n" + ) + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"raw_content": "a", "body": "b"}, + {"raw_content": "a", "subject": "s"}, + ], + ids=["neither", "both", "subject-with-raw-content"], +) +async def test_ambiguous_payloads_are_rejected(payload: dict[str, str]) -> None: + async with _client() as client: + response = await client.post("/debug/trigger_event", json=payload) + + assert response.status_code == 422 + + +async def test_blank_content_is_rejected() -> None: + async with _client() as client: + response = await client.post("/debug/trigger_event", json={"raw_content": " "}) + + assert response.status_code == 400 diff --git a/backend/tests/test_trust_actions.py b/backend/tests/test_trust_actions.py index b663e9c..3accf80 100644 --- a/backend/tests/test_trust_actions.py +++ b/backend/tests/test_trust_actions.py @@ -1,12 +1,14 @@ -"""Tests for Phase 10 Step 10.6 — trust-layer action endpoints. +"""Tests for the trust-layer action endpoints. Two write surfaces: -1. ``POST /admin/uncertainties/{id}/resolve`` — promote-to-fact / +1. ``POST /admin/uncertainties/{id}/resolve``: promote-to-fact or dismiss, both audit-logged. -2. ``POST /admin/rejected/{id}/override`` — already shipped in Phase - 9.2; we re-verify here that the audit trail (approval_log) is - actually written, since the user explicitly asked us to verify. +2. ``POST /admin/rejected/{id}/override``: the reviewer's decision on a + validator rejection. We check end to end that every decision also + writes an ``approval_log`` row, because a human override without an + audit trail would undermine the provenance the rest of the system + relies on. Both use httpx.AsyncClient + ASGITransport so the route's asyncpg session shares the test's event loop. @@ -22,44 +24,16 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker -from connectors.migrations import apply_all as ensure_migrations pytestmark = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - -async def _setup_or_skip() -> None: - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") - ensure_migrations() - - def _async_client() -> httpx.AsyncClient: - """ASGI-transport client — see test_source_links for rationale.""" + """ASGI-transport client; see test_source_links for rationale.""" from backend.main import app # noqa: PLC0415 - return httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://testserver" - ) + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") # --------------------------------------------------------------------------- @@ -73,12 +47,9 @@ async def _seed_property() -> tuple[UUID, UUID, UUID]: async with factory() as session: b = ( await session.execute( - text( - "INSERT INTO buildings (address) VALUES " - "('Trust Action Test') RETURNING id" - ) + text("INSERT INTO buildings (address) VALUES ('Trust Action Test') RETURNING id") ) - ).first() + ).one() p = ( await session.execute( text( @@ -90,7 +61,7 @@ async def _seed_property() -> tuple[UUID, UUID, UUID]: ), {"bid": b.id}, ) - ).first() + ).one() ref = f"trust-{uuid4().hex[:8]}" e = ( await session.execute( @@ -103,7 +74,7 @@ async def _seed_property() -> tuple[UUID, UUID, UUID]: ), {"ref": ref, "pid": p.id}, ) - ).first() + ).one() await session.commit() return b.id, p.id, e.id @@ -145,7 +116,7 @@ async def _seed_uncertainty( "field": field, }, ) - ).first() + ).one() await session.commit() return UUID(str(row.id)) @@ -175,7 +146,7 @@ async def _seed_rejection( ), {"eid": event_id, "pid": property_id}, ) - ).first() + ).one() await session.commit() return UUID(str(row.id)) @@ -184,10 +155,12 @@ async def _cleanup(building_id: UUID, property_id: UUID) -> None: factory = get_sessionmaker() async with factory() as session: await session.execute( - text("DELETE FROM approval_log WHERE target_id IN (" - "SELECT id::text FROM uncertainty_events WHERE property_id = :pid" - " UNION SELECT id::text FROM rejected_updates WHERE property_id = :pid" - ")"), + text( + "DELETE FROM approval_log WHERE target_id IN (" + "SELECT id::text FROM uncertainty_events WHERE property_id = :pid" + " UNION SELECT id::text FROM rejected_updates WHERE property_id = :pid" + ")" + ), {"pid": property_id}, ) await session.execute( @@ -205,12 +178,8 @@ async def _cleanup(building_id: UUID, property_id: UUID) -> None: text("DELETE FROM events WHERE property_id = :pid"), {"pid": property_id}, ) - await session.execute( - text("DELETE FROM properties WHERE id = :id"), {"id": property_id} - ) - await session.execute( - text("DELETE FROM buildings WHERE id = :id"), {"id": building_id} - ) + await session.execute(text("DELETE FROM properties WHERE id = :id"), {"id": property_id}) + await session.execute(text("DELETE FROM buildings WHERE id = :id"), {"id": building_id}) await session.commit() @@ -219,9 +188,9 @@ async def _cleanup(building_id: UUID, property_id: UUID) -> None: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_promote_uses_explicit_value_when_provided() -> None: """A POST with action=promote_to_fact + value writes the explicit value as a fact.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() uid = await _seed_uncertainty(property_id=pid, event_id=eid) try: @@ -254,7 +223,7 @@ async def test_promote_uses_explicit_value_when_provided() -> None: ), {"fid": body["fact_id"]}, ) - ).first() + ).one() assert fact is not None assert fact.section == "financials" assert fact.field == "rent_amount" @@ -272,7 +241,7 @@ async def test_promote_uses_explicit_value_when_provided() -> None: ), {"uid": uid}, ) - ).first() + ).one() assert unc.status == "resolved" assert unc.resolved_to_fact_id == UUID(body["fact_id"]) assert unc.resolved_at is not None @@ -293,20 +262,20 @@ async def test_promote_uses_explicit_value_when_provided() -> None: assert audit is not None assert audit.actor == "ops@keystone.test" assert audit.action == "uncertainty.promote_to_fact" - payload = audit.payload if isinstance(audit.payload, dict) else json.loads(audit.payload) + payload = ( + audit.payload if isinstance(audit.payload, dict) else json.loads(audit.payload) + ) assert payload["value_written"] == "1450 EUR" assert payload["reason"] == "tenant confirmed by phone today" finally: await _cleanup(bid, pid) +@pytest.mark.usefixtures("db") async def test_promote_falls_back_to_hypothesis_when_no_value() -> None: """Omitting ``value`` falls back to the uncertainty's hypothesis.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() - uid = await _seed_uncertainty( - property_id=pid, event_id=eid, hypothesis="1250 EUR" - ) + uid = await _seed_uncertainty(property_id=pid, event_id=eid, hypothesis="1250 EUR") try: async with _async_client() as client: resp = await client.post( @@ -327,19 +296,17 @@ async def test_promote_falls_back_to_hypothesis_when_no_value() -> None: text("SELECT value FROM facts WHERE id = :fid"), {"fid": fact_id}, ) - ).first() + ).one() assert fact.value == "1250 EUR" finally: await _cleanup(bid, pid) +@pytest.mark.usefixtures("db") async def test_promote_422s_when_no_value_and_no_hypothesis() -> None: """An uncertainty with NULL hypothesis + no body.value cannot be promoted.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() - uid = await _seed_uncertainty( - property_id=pid, event_id=eid, hypothesis=None - ) + uid = await _seed_uncertainty(property_id=pid, event_id=eid, hypothesis=None) try: async with _async_client() as client: resp = await client.post( @@ -361,9 +328,9 @@ async def test_promote_422s_when_no_value_and_no_hypothesis() -> None: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_dismiss_does_not_write_a_fact_but_audit_logs() -> None: """``action=dismiss`` flips status without a fact + writes approval_log.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() uid = await _seed_uncertainty(property_id=pid, event_id=eid) try: @@ -372,7 +339,7 @@ async def test_dismiss_does_not_write_a_fact_but_audit_logs() -> None: f"/admin/uncertainties/{uid}/resolve", json={ "action": "dismiss", - "reason": "off-topic — not actually about this property", + "reason": "off-topic: not actually about this property", "reviewed_by": "ops@keystone.test", }, ) @@ -416,9 +383,9 @@ async def test_dismiss_does_not_write_a_fact_but_audit_logs() -> None: # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_resolve_404_for_missing_uncertainty() -> None: """An unknown uncertainty id returns 404.""" - await _setup_or_skip() async with _async_client() as client: resp = await client.post( f"/admin/uncertainties/{uuid4()}/resolve", @@ -431,9 +398,9 @@ async def test_resolve_404_for_missing_uncertainty() -> None: assert resp.status_code == 404 +@pytest.mark.usefixtures("db") async def test_double_resolve_409s() -> None: """Resolving a non-open uncertainty fails with 409.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() uid = await _seed_uncertainty(property_id=pid, event_id=eid) try: @@ -461,13 +428,13 @@ async def test_double_resolve_409s() -> None: # --------------------------------------------------------------------------- -# Existing rejected/override path — verify it audit-logs end-to-end +# Rejected/override path: verify it audit-logs end-to-end # --------------------------------------------------------------------------- +@pytest.mark.usefixtures("db") async def test_rejected_override_writes_fact_and_audit() -> None: """``decision=overridden`` writes a fact + an approval_log entry.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() rid = await _seed_rejection(property_id=pid, event_id=eid) try: @@ -530,9 +497,9 @@ async def test_rejected_override_writes_fact_and_audit() -> None: await _cleanup(bid, pid) +@pytest.mark.usefixtures("db") async def test_rejected_dismiss_does_not_write_fact() -> None: """``decision=dismissed`` records the audit trail but writes no fact.""" - await _setup_or_skip() bid, pid, eid = await _seed_property() rid = await _seed_rejection(property_id=pid, event_id=eid) try: @@ -564,10 +531,7 @@ async def test_rejected_dismiss_does_not_write_fact() -> None: audit_action = ( await session.execute( - text( - "SELECT action FROM approval_log " - "WHERE target_id = :tid" - ), + text("SELECT action FROM approval_log WHERE target_id = :tid"), {"tid": str(rid)}, ) ).scalar() diff --git a/backend/tests/test_uncertainty.py b/backend/tests/test_uncertainty.py index 82dd6de..c632ac7 100644 --- a/backend/tests/test_uncertainty.py +++ b/backend/tests/test_uncertainty.py @@ -1,19 +1,20 @@ -"""Tests for Phase 9 Step 9.1 — uncertainty as first-class output. +"""Tests for uncertainty as a first-class pipeline output. Coverage: * ``_apply_confidence_floor`` demotes sub-floor facts and preserves the rest. -* The Gemini schema's new ``uncertain[]`` round-trips into +* The extraction schema's ``uncertain[]`` list round-trips into ``ExtractionResult.uncertain``. * The validator's ``needs_review`` rejections route to ``uncertainty_events`` (via the worker helper) and are *not* written to ``rejected_updates``. * End-to-end DB integration: a vague-rent email lands in ``uncertainty_events``, not in ``facts``. -* Step 9.2 regression: a building floor-count change from email - still ends up in ``rejected_updates`` (hard-reject path), not in - ``uncertainty_events``. +* Hard-reject regression: routing ``needs_review`` rejections to the + uncertainty inbox must not divert hard rejections. A building + floor-count change from email still ends up in ``rejected_updates``, + not in ``uncertainty_events``. """ from __future__ import annotations @@ -24,12 +25,10 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker -from backend.pipeline import constraints # noqa: F401 — registers constraints -from backend.pipeline.applier import apply as apply_plan +from backend.pipeline import constraints # noqa: F401 (registers constraints) from backend.pipeline.applier import apply_uncertainties -from backend.pipeline.differ import DiffPlan, FactDecision, diff, load_current_facts +from backend.pipeline.differ import DiffPlan, FactDecision, load_current_facts from backend.pipeline.extractor import ( CONFIDENCE_FLOOR, _apply_confidence_floor, @@ -40,32 +39,14 @@ validate, ) from backend.pipeline.worker import _needs_review_to_uncertainty -from backend.services.gemini import ExtractionResult +from backend.services.llm import ExtractionResult from connectors.migrations import apply_all as ensure_migrations pytestmark_async = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - # ---------------------------------------------------------------------------- -# Confidence floor — pure unit tests +# Confidence floor: pure unit tests # ---------------------------------------------------------------------------- @@ -154,9 +135,7 @@ def test_confidence_floor_threshold_is_inclusive_floor() -> None: def test_extraction_result_uncertain_default_empty() -> None: """An ExtractionResult without explicit uncertain[] defaults to [].""" - r = ExtractionResult( - category="other", priority="low", facts_to_update=[], summary="" - ) + r = ExtractionResult(category="other", priority="low", facts_to_update=[], summary="") assert r.uncertain == [] @@ -237,15 +216,14 @@ def test_validate_returns_both_kinds_separately() -> None: # ---------------------------------------------------------------------------- -# DB integration — vague rent email roundtrips through the pipeline +# DB integration: vague rent email roundtrips through the pipeline # ---------------------------------------------------------------------------- @pytest.mark.asyncio +@pytest.mark.usefixtures("db") async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> None: """The applier helper inserts a row whose columns mirror the input dict.""" - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") ensure_migrations() factory = get_sessionmaker() @@ -253,11 +231,10 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non b = ( await session.execute( text( - "INSERT INTO buildings (address) VALUES " - "('Test Uncertainty Bldg') RETURNING id" + "INSERT INTO buildings (address) VALUES ('Test Uncertainty Bldg') RETURNING id" ) ) - ).first() + ).one() p = ( await session.execute( text( @@ -269,7 +246,7 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non ), {"bid": b.id}, ) - ).first() + ).one() ref = f"test-uncertainty-{uuid4().hex[:8]}" e = ( await session.execute( @@ -282,7 +259,7 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non ), {"ref": ref, "pid": p.id}, ) - ).first() + ).one() await session.commit() items = [ @@ -297,9 +274,7 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non ] async with factory() as session: - n = await apply_uncertainties( - session, event_id=e.id, property_id=p.id, items=items - ) + n = await apply_uncertainties(session, event_id=e.id, property_id=p.id, items=items) await session.commit() assert n == 1 @@ -316,7 +291,7 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non ), {"eid": e.id}, ) - ).first() + ).one() assert row is not None assert row.relevant_section == "financials" assert row.relevant_field == "rent_amount" @@ -331,42 +306,36 @@ async def test_uncertainty_event_lands_in_table_via_apply_uncertainties() -> Non {"eid": e.id}, ) await session.execute(text("DELETE FROM events WHERE id = :id"), {"id": e.id}) - await session.execute( - text("DELETE FROM properties WHERE id = :id"), {"id": p.id} - ) + await session.execute(text("DELETE FROM properties WHERE id = :id"), {"id": p.id}) await session.execute(text("DELETE FROM buildings WHERE id = :id"), {"id": b.id}) await session.commit() @pytest.mark.asyncio -async def test_floor_count_email_still_hard_rejects_after_step91() -> None: - """Step 9.2 regression: a free-text floor-count change still goes to rejected_updates.""" - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") +@pytest.mark.usefixtures("db") +async def test_floor_count_email_still_hard_rejects_with_uncertainty_routing() -> None: + """A free-text floor-count change is still a hard reject, not an uncertainty.""" ensure_migrations() factory = get_sessionmaker() async with factory() as session: b = ( await session.execute( - text( - "INSERT INTO buildings (address) VALUES " - "('Test 9.1 Regression') RETURNING id" - ) + text("INSERT INTO buildings (address) VALUES ('Test Floor Bldg') RETURNING id") ) - ).first() + ).one() p = ( await session.execute( text( """ INSERT INTO properties (name, address, building_id, aliases) - VALUES ('Test 9.1 Prop', 'addr', :bid, ARRAY['x']) + VALUES ('Test Floor Prop', 'addr', :bid, ARRAY['x']) RETURNING id """ ), {"bid": b.id}, ) - ).first() + ).one() # Pre-existing floor_count fact so the constraint sees a current value. ref0 = f"seed-{uuid4().hex[:8]}" e0 = ( @@ -380,7 +349,7 @@ async def test_floor_count_email_still_hard_rejects_after_step91() -> None: ), {"ref": ref0, "pid": p.id}, ) - ).first() + ).one() await session.execute( text( """ @@ -408,7 +377,7 @@ async def test_floor_count_email_still_hard_rejects_after_step91() -> None: ), {"ref": ref, "pid": p.id}, ) - ).first() + ).one() await session.commit() plan = DiffPlan( @@ -460,16 +429,14 @@ async def test_floor_count_email_still_hard_rejects_after_step91() -> None: ), {"eid": e.id}, ) - ).first() + ).one() assert rej is not None assert rej.proposed_field == "floor_count" assert rej.constraint_name == "building_floor_count_immutable" assert rej.reviewed_status == "pending" unc_count = ( await session.execute( - text( - "SELECT COUNT(*) FROM uncertainty_events WHERE event_id = :eid" - ), + text("SELECT COUNT(*) FROM uncertainty_events WHERE event_id = :eid"), {"eid": e.id}, ) ).scalar() @@ -480,17 +447,11 @@ async def test_floor_count_email_still_hard_rejects_after_step91() -> None: text("DELETE FROM rejected_updates WHERE event_id IN (:eid, :seed)"), {"eid": e.id, "seed": e0.id}, ) - await session.execute( - text("DELETE FROM facts WHERE property_id = :pid"), {"pid": p.id} - ) + await session.execute(text("DELETE FROM facts WHERE property_id = :pid"), {"pid": p.id}) await session.execute( text("DELETE FROM events WHERE id IN (:eid, :seed)"), {"eid": e.id, "seed": e0.id}, ) - await session.execute( - text("DELETE FROM properties WHERE id = :pid"), {"pid": p.id} - ) - await session.execute( - text("DELETE FROM buildings WHERE id = :bid"), {"bid": b.id} - ) + await session.execute(text("DELETE FROM properties WHERE id = :pid"), {"pid": p.id}) + await session.execute(text("DELETE FROM buildings WHERE id = :bid"), {"bid": b.id}) await session.commit() diff --git a/backend/tests/test_validator.py b/backend/tests/test_validator.py index b2abd16..da973a5 100644 --- a/backend/tests/test_validator.py +++ b/backend/tests/test_validator.py @@ -1,4 +1,4 @@ -"""Tests for Phase 9 Step 9.2 — constraint validator. +"""Tests for the rule-based constraint validator. Pure-function tests on each constraint (no DB) plus an end-to-end ``validate()`` test on a representative DiffPlan. Persistence to the @@ -14,13 +14,10 @@ import pytest from sqlalchemy import text -from backend.config import get_settings from backend.db.session import get_sessionmaker -from backend.pipeline import constraints # noqa: F401 — registers everything +from backend.pipeline import constraints # noqa: F401 (registers everything) from backend.pipeline.differ import DiffPlan, FactDecision from backend.pipeline.validator import ( - REGISTRY, - ValidationResult, constraints_for, persist_rejections, validate, @@ -216,7 +213,7 @@ def test_out_of_tolerance_with_vermessung_passes(self) -> None: class TestComplianceWildcard: def test_email_rejected_any_field(self) -> None: - # Wildcard — should fire on any field under 'compliance'. + # Wildcard: should fire on any field under 'compliance'. cs = constraints_for("compliance", "brandschutznachweis") assert cs, "compliance wildcard not loaded" c = cs[0] @@ -301,41 +298,20 @@ def test_validate_first_match_wins() -> None: filtered, rejections = validate(plan, event=_email(), current_facts={}) assert filtered.decisions == [] assert len(rejections) == 1 - assert rejections[0].constraint_name.endswith( - "compliance_facts_require_authoritative_source" - ) + assert rejections[0].constraint_name.endswith("compliance_facts_require_authoritative_source") # ---------------------------------------------------------------------------- -# persist_rejections — DB roundtrip +# persist_rejections: DB roundtrip # ---------------------------------------------------------------------------- pytestmark_db = pytest.mark.asyncio -def _reset_session_cache() -> None: - from backend.db import session as session_module # noqa: PLC0415 - - session_module.get_engine.cache_clear() - session_module.get_sessionmaker.cache_clear() - - -async def _db_reachable() -> bool: - _reset_session_cache() - try: - factory = get_sessionmaker() - async with factory() as conn: - await conn.execute(text("SELECT 1")) - return True - except Exception: # noqa: BLE001 - return False - - @pytest.mark.asyncio +@pytest.mark.usefixtures("db") async def test_persist_rejections_roundtrip() -> None: """One decision in → one row in rejected_updates with correct columns.""" - if not await _db_reachable(): - pytest.skip(f"dev DB unreachable at {get_settings().database_url}") ensure_migrations() factory = get_sessionmaker() @@ -343,12 +319,9 @@ async def test_persist_rejections_roundtrip() -> None: # Fixture: building + property + event b = ( await session.execute( - text( - "INSERT INTO buildings (address) VALUES " - "('Test Validator Bldg') RETURNING id" - ) + text("INSERT INTO buildings (address) VALUES ('Test Validator Bldg') RETURNING id") ) - ).first() + ).one() p = ( await session.execute( text( @@ -360,7 +333,7 @@ async def test_persist_rejections_roundtrip() -> None: ), {"bid": b.id}, ) - ).first() + ).one() ref = f"test-validator-{uuid4().hex[:8]}" e = ( await session.execute( @@ -373,7 +346,7 @@ async def test_persist_rejections_roundtrip() -> None: ), {"ref": ref, "pid": p.id}, ) - ).first() + ).one() await session.commit() # Use the validate() output shape directly. @@ -415,7 +388,7 @@ async def test_persist_rejections_roundtrip() -> None: ), {"eid": e.id}, ) - ).first() + ).one() assert row is not None assert row.proposed_section == "financials" assert row.proposed_field == "rent_amount" @@ -428,13 +401,7 @@ async def test_persist_rejections_roundtrip() -> None: text("DELETE FROM rejected_updates WHERE event_id = :eid"), {"eid": e.id}, ) - await session.execute( - text("DELETE FROM events WHERE id = :eid"), {"eid": e.id} - ) - await session.execute( - text("DELETE FROM properties WHERE id = :pid"), {"pid": p.id} - ) - await session.execute( - text("DELETE FROM buildings WHERE id = :bid"), {"bid": b.id} - ) + await session.execute(text("DELETE FROM events WHERE id = :eid"), {"eid": e.id}) + await session.execute(text("DELETE FROM properties WHERE id = :pid"), {"pid": p.id}) + await session.execute(text("DELETE FROM buildings WHERE id = :bid"), {"bid": b.id}) await session.commit() diff --git a/backend/tests/test_worker_steps.py b/backend/tests/test_worker_steps.py new file mode 100644 index 0000000..ab453e5 --- /dev/null +++ b/backend/tests/test_worker_steps.py @@ -0,0 +1,60 @@ +"""Pure parts of the worker's pipeline steps.""" + +from __future__ import annotations + +from backend.pipeline.differ import DiffPlan, FactDecision +from backend.pipeline.validator import Rejection +from backend.pipeline.worker import _drop_hard_contradictions + + +def _decision(section: str, field: str) -> FactDecision: + return FactDecision( + section=section, field=field, value="v", confidence=0.9, supersedes_id=None, reason="new" + ) + + +def _contradiction(section: str, field: str, *, hard: bool) -> Rejection: + return Rejection( + section=section, + field=field, + proposed_value="v", + proposed_confidence=0.0, + constraint_name="semantic_consistency", + reason="contradicts the file", + required_source_type=None, + needs_review=not hard, + ) + + +def test_hard_contradictions_remove_their_decision_and_soft_ones_keep_it() -> None: + plan = DiffPlan( + decisions=[ + _decision("overview", "floor_count"), + _decision("tenants", "current_tenant_name"), + _decision("maintenance", "open_water_damage"), + ], + skipped=[("lease.end_date", "unchanged")], + ) + + result = _drop_hard_contradictions( + plan, + [ + _contradiction("overview", "floor_count", hard=True), + _contradiction("tenants", "current_tenant_name", hard=False), + ], + ) + + assert [(d.section, d.field) for d in result.decisions] == [ + ("tenants", "current_tenant_name"), + ("maintenance", "open_water_damage"), + ] + assert result.skipped == plan.skipped + + +def test_plan_is_unchanged_without_hard_contradictions() -> None: + plan = DiffPlan(decisions=[_decision("overview", "floor_count")], skipped=[]) + + assert ( + _drop_hard_contradictions(plan, [_contradiction("overview", "floor_count", hard=False)]) + is plan + ) diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..a148843 --- /dev/null +++ b/conftest.py @@ -0,0 +1,145 @@ +"""Shared pytest fixtures for the backend, connectors and eval suites. + +Database tests run against the Postgres at ``DATABASE_URL`` / +``DATABASE_URL_SYNC`` (``docker compose up -d postgres`` provides one). Three +fixtures make that safe to do repeatedly against a developer's database: + +``_fresh_engine`` (autouse) + The application caches one async engine per process. Its asyncpg pool is + bound to the event loop that created it, while pytest-asyncio gives every + test a new loop, so a cached engine from an earlier test fails with + "attached to a different loop". Each test gets a fresh engine and the old + one is disposed afterwards. + +``db`` + Requested by tests that need Postgres. Checks connectivity once per + session and applies the schema and migrations. An unreachable database is + a test *failure* with instructions, never a silent skip: a skipped + integration test looks exactly like a passing one in a summary line. + +``_no_llm_keys`` (autouse) + Blanks the LLM API keys for every test. Environment variables take + precedence over ``.env``, so a developer's real keys never turn a test run + into paid, nondeterministic API calls. Tests that need a "configured" + provider set a fake key themselves. + +``_no_leaked_rows`` (autouse, session) + Counts rows in the core tables before and after the run and errors if any + count changed. Tests must clean up what they create; this keeps the suite + from polluting the database it runs against. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Iterator + +import psycopg2 +import pytest + +from backend.config import get_settings +from backend.db import session as db_session + +_GUARDED_TABLES = ( + "liegenschaften", + "buildings", + "properties", + "tenants", + "events", + "facts", + "signals", + "approval_log", + "outbox", + "uncertainty_events", + "rejected_updates", + "failed_events", + "replay_runs", + "cost_ledger", + "property_files", + "building_files", + "liegenschaft_files", +) + + +def _connect() -> psycopg2.extensions.connection: + return psycopg2.connect(get_settings().database_url_sync, connect_timeout=3) + + +def _row_counts() -> dict[str, int]: + """Row count per guarded table; tables that do not exist yet count as 0.""" + counts: dict[str, int] = {} + with _connect() as conn, conn.cursor() as cur: + for table in _GUARDED_TABLES: + cur.execute("SELECT to_regclass(%s) IS NOT NULL", (f"public.{table}",)) + row = cur.fetchone() + if row and row[0]: + cur.execute(f"SELECT count(*) FROM {table}") # noqa: S608 - fixed allow-list + counts[table] = int(cur.fetchone()[0]) + else: + counts[table] = 0 + conn.close() + return counts + + +@pytest.fixture(scope="session") +def _db_error() -> str | None: + """``None`` when Postgres accepts connections, otherwise the error text.""" + try: + _connect().close() + except psycopg2.OperationalError as exc: + return str(exc).strip() + return None + + +@pytest.fixture(scope="session") +def db(_db_error: str | None) -> None: + """Require a reachable Postgres with the current schema applied.""" + if _db_error is not None: + pytest.fail( + f"Postgres is not reachable at {get_settings().database_url_sync}: {_db_error}\n" + "Start it with `docker compose up -d postgres` (or point DATABASE_URL and " + "DATABASE_URL_SYNC at another instance).", + pytrace=False, + ) + from connectors.migrations import apply_all # noqa: PLC0415 + from seed.seed import _apply_schema, _schema_applied # noqa: PLC0415 + + with _connect() as conn, conn.cursor() as cur: + if not _schema_applied(cur): + _apply_schema(cur) + conn.close() + apply_all() + + +@pytest.fixture(autouse=True) +def _no_llm_keys(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + monkeypatch.setenv("LLM_PROVIDER", "gemini") + monkeypatch.setenv("GEMINI_API_KEY", "") + monkeypatch.setenv("PIONEER_API_KEY", "") + get_settings.cache_clear() + yield + get_settings.cache_clear() + + +@pytest.fixture(autouse=True) +async def _fresh_engine() -> AsyncIterator[None]: + db_session.get_engine.cache_clear() + db_session.get_sessionmaker.cache_clear() + yield + if db_session.get_engine.cache_info().currsize: + await db_session.get_engine().dispose() + db_session.get_engine.cache_clear() + db_session.get_sessionmaker.cache_clear() + + +@pytest.fixture(scope="session", autouse=True) +def _no_leaked_rows(_db_error: str | None) -> Iterator[None]: + if _db_error is not None: + yield + return + before = _row_counts() + yield + after = _row_counts() + leaked = {t: (before[t], after[t]) for t in _GUARDED_TABLES if before[t] != after[t]} + if leaked: + detail = ", ".join(f"{t}: {b} -> {a}" for t, (b, a) in leaked.items()) + pytest.fail(f"test suite left rows behind: {detail}", pytrace=False) diff --git a/connectors/__init__.py b/connectors/__init__.py index 9758bb7..fb01dd1 100644 --- a/connectors/__init__.py +++ b/connectors/__init__.py @@ -1,7 +1,7 @@ """Customer-agnostic data connectors. -A *connector* is anything that turns a customer's raw data — folder of -EMLs, bank CSV, master-data spreadsheet, archive of PDFs — into the +A *connector* is anything that turns a customer's raw data (a folder of +EMLs, a bank CSV, a master-data spreadsheet, an archive of PDFs) into the event/fact stream Keystone's pipeline already consumes. Reuses (does not replace): @@ -14,8 +14,8 @@ - ``seed.seed._upsert_*`` helpers for master-data upserts. The first composer (``connectors.buena_archive``) targets the Buena -hackathon dataset. The next customer gets a sibling composer; the -shape-handling primitives below are shared. +sample dataset's directory layout. Another customer gets a sibling +composer; the shape-handling primitives below are shared. """ from __future__ import annotations diff --git a/connectors/base.py b/connectors/base.py index 26cde3b..39b6539 100644 --- a/connectors/base.py +++ b/connectors/base.py @@ -1,12 +1,12 @@ -"""Connector Protocol — common shape every customer integration honors. +"""Connector Protocol: the common shape every customer integration honors. A connector exposes two iterators: -- :meth:`Connector.pull` — full backfill. Yields events from oldest to +- :meth:`Connector.pull`: full backfill. Yields events from oldest to newest. Idempotent: re-running on the same input produces the same ``(source, source_ref)`` tuples and is absorbed by the events ``UNIQUE (source, source_ref)`` constraint. -- :meth:`Connector.stream` — incremental updates only. Used by the +- :meth:`Connector.stream`: incremental updates only. Used by the scheduler / admin-driven "advance one day" path. Both iterators yield :class:`ConnectorEvent` dataclasses whose fields @@ -30,7 +30,7 @@ from collections.abc import AsyncIterator, Iterator from dataclasses import dataclass, field -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import Any, Protocol, runtime_checkable from uuid import UUID @@ -50,7 +50,7 @@ class ConnectorEvent: metadata: Structured context (parsed headers, currency amounts, classifier outputs, …). PII redacted. property_id: Optional pre-routed property UUID. ``None`` means - "let the router decide" — the worker / structured extractor + "let the router decide"; the worker / structured extractor will route on ingest. received_at: When the event happened from the customer's perspective. Defaults to ingestion time but should be the @@ -58,7 +58,9 @@ class ConnectorEvent: bank Valuta, invoice Datum, …). document_type: For PDF-derived events, the classified type (lease, invoice, mahnung, …). ``None`` for non-PDF sources. - Phase 9 constraints read this field. + Source-type constraints (e.g. owner changes require a + ``kaufvertrag``, floor-count changes a ``structural_permit``) + read this field to decide whether a PDF is authoritative. """ source: str @@ -66,7 +68,7 @@ class ConnectorEvent: raw_content: str metadata: dict[str, Any] = field(default_factory=dict) property_id: UUID | None = None - received_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + received_at: datetime = field(default_factory=lambda: datetime.now(UTC)) document_type: str | None = None @@ -109,5 +111,5 @@ class ConnectorError(RuntimeError): """Recoverable connector error. Message is safe to surface to the user.""" -class DataMissing(ConnectorError): +class DataMissingError(ConnectorError): """The customer dataset is not present at the configured path.""" diff --git a/connectors/buena_archive.py b/connectors/buena_archive.py index c921596..d3ae670 100644 --- a/connectors/buena_archive.py +++ b/connectors/buena_archive.py @@ -1,4 +1,4 @@ -"""Buena composite — the only place that knows Buena's directory shape. +"""Buena composite: the only place that knows Buena's directory shape. Wires :mod:`csv_stammdaten`, :mod:`eml_archive`, :mod:`camt_bank`, :mod:`pdf_invoice_archive`, and :mod:`pdf_letter_archive` against the @@ -11,9 +11,9 @@ Extracted/ ├── stammdaten/ │ ├── eigentuemer.csv (35 rows) - │ ├── einheiten.csv (52 rows — units inside buildings) - │ ├── mieter.csv (26 rows — active + closed leases) - │ ├── dienstleister.csv (16 rows — contractors) + │ ├── einheiten.csv (52 rows: units inside buildings) + │ ├── mieter.csv (26 rows: active + closed leases) + │ ├── dienstleister.csv (16 rows: contractors) │ └── stammdaten.json (canonical: liegenschaft + gebaeude │ + einheiten + eigentuemer + mieter │ + dienstleister) @@ -49,8 +49,8 @@ import structlog from connectors import camt_bank, eml_archive, pdf_invoice_archive, pdf_letter_archive, redact -from connectors.base import ConnectorEvent, DataMissing -from connectors.csv_stammdaten import ColumnMap, EntityType, parse_iso_date +from connectors.base import ConnectorEvent, DataMissingError +from connectors.csv_stammdaten import ColumnMap, parse_iso_date log = structlog.get_logger(__name__) @@ -71,15 +71,14 @@ def require_root(env_value: str | None = None) -> Path: """Like :func:`get_extracted_root` but raises if the folder is missing.""" root = get_extracted_root(env_value) if not root.is_dir(): - raise DataMissing( - f"Buena dataset not found at {root!s}; set EXTRACTED_ROOT or " - "place the folder there." + raise DataMissingError( + f"Buena dataset not found at {root!s}; set EXTRACTED_ROOT or place the folder there." ) return root # ----------------------------------------------------------------------------- -# Stammdaten — adapt Buena rows onto Phase 0's seed dataclasses +# Stammdaten: adapt Buena rows onto the seed dataclasses # ----------------------------------------------------------------------------- @@ -88,7 +87,7 @@ class BuenaStammdaten: """Concrete Stammdaten payload after redaction + adaptation. ``liegenschaften`` is the WEG tier (`Wohnungseigentümergemeinschaft`, - owners' association) — one Liegenschaft owns N Häuser; per-WEG + owners' association): one Liegenschaft owns N Häuser; per-WEG events (Hausgeld, Verwaltergebühr, shared contractor fees) attach here, not to a single Haus. """ @@ -113,33 +112,63 @@ class BuenaStammdaten: "bic": "bic", }, metadata_columns=( - "strasse", "plz", "ort", "land", "ust_id", "steuernummer", - "stil", "sprache", "vertrag_monatlich", "stundensatz", + "strasse", + "plz", + "ort", + "land", + "ust_id", + "steuernummer", + "stil", + "sprache", + "vertrag_monatlich", + "stundensatz", ), pii_columns=("email", "telefon", "iban"), ) OWNER_COLUMN_MAP = ColumnMap( required={ - "id": "id", "anrede": "anrede", "vorname": "vorname", - "nachname": "nachname", "firma": "firma", - "email": "email", "telefon": "telefon", "iban": "iban", "bic": "bic", + "id": "id", + "anrede": "anrede", + "vorname": "vorname", + "nachname": "nachname", + "firma": "firma", + "email": "email", + "telefon": "telefon", + "iban": "iban", + "bic": "bic", }, metadata_columns=( - "strasse", "plz", "ort", "land", "einheit_ids", - "selbstnutzer", "sev_mandat", "beirat", "sprache", + "strasse", + "plz", + "ort", + "land", + "einheit_ids", + "selbstnutzer", + "sev_mandat", + "beirat", + "sprache", ), pii_columns=("email", "telefon", "iban"), ) TENANT_COLUMN_MAP = ColumnMap( required={ - "id": "id", "anrede": "anrede", "vorname": "vorname", - "nachname": "nachname", "email": "email", "telefon": "telefon", - "einheit_id": "einheit_id", "eigentuemer_id": "eigentuemer_id", - "mietbeginn": "mietbeginn", "mietende": "mietende", - "kaltmiete": "kaltmiete", "nk_vorauszahlung": "nk_vorauszahlung", - "kaution": "kaution", "iban": "iban", "bic": "bic", + "id": "id", + "anrede": "anrede", + "vorname": "vorname", + "nachname": "nachname", + "email": "email", + "telefon": "telefon", + "einheit_id": "einheit_id", + "eigentuemer_id": "eigentuemer_id", + "mietbeginn": "mietbeginn", + "mietende": "mietende", + "kaltmiete": "kaltmiete", + "nk_vorauszahlung": "nk_vorauszahlung", + "kaution": "kaution", + "iban": "iban", + "bic": "bic", }, metadata_columns=("sprache",), pii_columns=("email", "telefon", "iban"), @@ -147,7 +176,7 @@ class BuenaStammdaten: def _short_address(strasse: str, hausnr: str) -> str: - """e.g. ``"Immanuelkirchstr. 26 · WE 01"``-style — passes through unchanged.""" + """e.g. ``"Musterstr. 26 · WE 01"``-style; passes through unchanged.""" if not strasse: return hausnr if hausnr and hausnr not in strasse: @@ -160,7 +189,7 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: stammdaten_dir = root / "stammdaten" json_path = stammdaten_dir / "stammdaten.json" if not json_path.is_file(): - raise DataMissing(f"missing stammdaten.json under {stammdaten_dir!s}") + raise DataMissingError(f"missing stammdaten.json under {stammdaten_dir!s}") payload: dict[str, Any] = json.loads(json_path.read_text(encoding="utf-8")) @@ -174,8 +203,7 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: { "buena_liegenschaft_id": lie_id, "name": str( - liegenschaft.get("name") - or f"WEG {liegenschaft.get('strasse', '')}".strip() + liegenschaft.get("name") or f"WEG {liegenschaft.get('strasse', '')}".strip() ), "metadata": { "buena_liegenschaft_id": lie_id, @@ -201,9 +229,13 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: haus_id = str(g.get("id", "")) hausnr = str(g.get("hausnr", "") or "") building_address = ( - f"{liegenschaft.get('strasse', '')} {hausnr}, " - f"{liegenschaft.get('plz', '')} {liegenschaft.get('ort', '')}" - ).strip(", ").strip() + ( + f"{liegenschaft.get('strasse', '')} {hausnr}, " + f"{liegenschaft.get('plz', '')} {liegenschaft.get('ort', '')}" + ) + .strip(", ") + .strip() + ) buildings.append( { "buena_haus_id": haus_id, @@ -266,10 +298,12 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: lage = str(u.get("lage") or "") addr_short = _short_address( str(liegenschaft.get("strasse", "")), - str(next( - (g["hausnr"] for g in gebaeude_list if str(g.get("id")) == haus_id), - "", - )), + str( + next( + (g["hausnr"] for g in gebaeude_list if str(g.get("id")) == haus_id), + "", + ) + ), ) prop_name = ( f"{liegenschaft.get('strasse', '').strip()} {einheit_nr}".strip() @@ -295,7 +329,9 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: "address": ( f"{liegenschaft.get('strasse', '')} {einheit_nr}, " f"{liegenschaft.get('plz', '')} {liegenschaft.get('ort', '')}" - ).strip(", ").strip(), + ) + .strip(", ") + .strip(), "aliases": aliases, "metadata": { "buena_eh_id": eh_id, @@ -313,9 +349,10 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: # ---- Tenants (PII redacted; only active or recently active) ---- tenants: list[dict[str, Any]] = [] for m in mieter_list: - full_name = " ".join( - part for part in (m.get("vorname"), m.get("nachname")) if part - ).strip() or "Mieter" + full_name = ( + " ".join(part for part in (m.get("vorname"), m.get("nachname")) if part).strip() + or "Mieter" + ) eh_id = str(m.get("einheit_id", "")) mietbeginn: date | None = parse_iso_date(m.get("mietbeginn")) mietende: date | None = parse_iso_date(m.get("mietende")) @@ -330,12 +367,8 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: "metadata": { "buena_mie_id": m.get("id"), "buena_eh_id": eh_id, - "mietbeginn": ( - mietbeginn.isoformat() if mietbeginn else None - ), - "mietende": ( - mietende.isoformat() if mietende else None - ), + "mietbeginn": (mietbeginn.isoformat() if mietbeginn else None), + "mietende": (mietende.isoformat() if mietende else None), "kaltmiete": m.get("kaltmiete"), "nk_vorauszahlung": m.get("nk_vorauszahlung"), "kaution": m.get("kaution"), @@ -391,7 +424,7 @@ def load_stammdaten(root: Path) -> BuenaStammdaten: # ----------------------------------------------------------------------------- -# Event composers — these are what the CLI actually calls +# Event composers: these are what the CLI actually calls # ----------------------------------------------------------------------------- diff --git a/connectors/buena_email_loader.py b/connectors/buena_email_loader.py index bbd4c45..916e650 100644 --- a/connectors/buena_email_loader.py +++ b/connectors/buena_email_loader.py @@ -1,21 +1,21 @@ """Stream Buena ``.eml`` archive into events + facts. -Step 6 mirrors the structured backfill loop (see +The email backfill mirrors the structured backfill loop (see :mod:`connectors.buena_event_loader`) but with two free-text-only concerns: -- **Routing escalates** — :func:`backend.pipeline.router.route_text_event` +- **Routing escalates**: :func:`backend.pipeline.router.route_text_event` applies the WEG keyword precedence so e.g. a Brandschutznachweis email lands at the Liegenschaft instead of being greedily claimed by a property's address token-overlap. -- **Extraction is cost-bounded** — every Gemini call charges the +- **Extraction is cost-bounded**: every Gemini call charges the durable :mod:`connectors.cost_ledger`. When cumulative spend hits the cap the loop aborts cleanly and the next invocation refuses to start until the operator runs ``--reset-cost-ledger``. Resumability is free: ``events.UNIQUE (source, source_ref)`` absorbs re-runs. Persistent failure (3 attempts that raise) is captured in the -``failed_events`` table for human triage in Step 9. +``failed_events`` table for human triage. """ from __future__ import annotations @@ -23,8 +23,9 @@ import asyncio import re from collections.abc import Iterable -from dataclasses import dataclass, field as dc_field -from datetime import datetime, timezone +from dataclasses import dataclass +from dataclasses import field as dc_field +from datetime import UTC, datetime from decimal import Decimal from pathlib import Path from typing import Any @@ -45,17 +46,17 @@ StructuredRoute, route_text_event, ) -from backend.services.gemini import ExtractionResult +from backend.services.llm import ExtractionResult from connectors import buena_archive, cost_ledger, eml_archive from connectors.base import ConnectorEvent -from connectors.cost_ledger import CostCapExceeded +from connectors.cost_ledger import CostCapExceededError from connectors.migrations import apply_all as ensure_migrations log = structlog.get_logger(__name__) -# Cost ledger label dedicated to Step 6 email backfill. Kept separate -# from ``step5_eval`` so the operator can read the email-only spend +# Cost ledger label dedicated to the email backfill. Kept separate +# from the eval runner's label so the operator can read the email-only spend # without subtracting other run costs. LEDGER_LABEL = "step6_email_backfill" @@ -68,15 +69,16 @@ # After successful extraction, events whose ``received_at`` is older # than ``today − HISTORICAL_THRESHOLD_DAYS`` get stamped -# ``processed_at = received_at`` so Phase 9's validator/uncertainty -# layers don't silently re-process pre-validator extractions. New +# ``processed_at = received_at`` so the validator/uncertainty layers +# treat them as settled history and don't silently re-process +# extractions that were made before validation existed. New # events stamp ``processed_at = now()`` as usual. HISTORICAL_THRESHOLD_DAYS = 30 # --- Granular unrouted-reason classifiers ---------------------------------- -# Step 6 broke the single "no match" miss reason into auditable buckets. -# Each regex is named after the bucket it produces. +# A single "no match" miss reason says nothing about what to fix, so +# misses are split into auditable buckets. Each regex is named after the bucket it produces. # Buena unit conventions + generic apartment markers + HAUS-NN. _PROPERTY_TOKEN_RE = re.compile( @@ -85,7 +87,7 @@ re.IGNORECASE, ) -# Word-boundary, case-insensitive WEG keyword regex — same vocabulary the +# Word-boundary, case-insensitive WEG keyword regex: same vocabulary the # router uses for liegenschaft escalation. _WEG_KEYWORD_RE = re.compile( r"\b(?:" + "|".join(re.escape(k) for k in WEG_KEYWORDS) + r")\b", @@ -142,9 +144,10 @@ def _classify_unrouted_reason( ) -> str: """Bucket a route_text_event miss into an actionable category. - Hierarchy is intentional — first match wins, ordered from "structural + Hierarchy is intentional: first match wins, ordered from "structural skip-no-extraction-needed" to "real signal but no alias matched". - Each bucket maps to a Step 9 / Step 8 follow-up. + Each bucket maps to a distinct operator follow-up (ignore, translate, + seed missing units, learn new senders). Buckets: body_too_short @@ -153,20 +156,21 @@ def _classify_unrouted_reason( auto_reply "Out of office" / "Abwesenheit" markers in subject or body. non_de_en_language_ - langdetect returns something other than de/en/nl/af. Step 9 - decides whether to translate or drop. + langdetect returns something other than de/en/nl/af. These + need a decision on whether to translate or drop them. weg_keyword_no_liegenschaft Body has a WEG keyword (Hausgeld, Mahnung, …) but no - liegenschaft was resolved — interesting only when the + liegenschaft was resolved. Interesting only when the customer has multiple WEGs (Buena: single WEG, so this is effectively "no liegenschaft loaded yet" if it ever fires). property_tokens_no_alias_match Body has property-shaped tokens (EH-NNN / Wohnung 4B / …) - that didn't match any seeded alias — a Step 9 onboarding - signal: customer has units we haven't seeded. + that didn't match any seeded alias. An onboarding signal: + the customer has units we haven't seeded. unknown_sender_domain Sender domain has no prior routed event in the system. - Feeds Step 9's sender_routing_history bootstrap. + Useful input for learning which senders map to which + properties. no_signal_known_sender Sender is known but the body is too thin to route. no_signal @@ -264,13 +268,13 @@ def _is_historical(received_at: datetime | None, *, threshold_days: int) -> bool """``True`` if ``received_at`` is older than ``threshold_days`` ago. Matches the live worker's stamping policy so backfilled events - don't re-run through Phase 9's validator/uncertainty layers. + don't re-run through the validator/uncertainty layers. """ if received_at is None: return False if received_at.tzinfo is None: - received_at = received_at.replace(tzinfo=timezone.utc) - age_days = (datetime.now(tz=timezone.utc) - received_at).days + received_at = received_at.replace(tzinfo=UTC) + age_days = (datetime.now(tz=UTC) - received_at).days return age_days > threshold_days @@ -376,7 +380,7 @@ async def _record_failure( """Increment the failed_events row for ``event_id``. Returns ``True`` when ``retry_count`` has hit (or exceeded) the - configured ``dead_letter_after`` ceiling — at that point the row + configured ``dead_letter_after`` ceiling; at that point the row is the operator's signal that the event is permanently failed. """ truncated = (error or "")[:1000] @@ -466,12 +470,12 @@ async def _process_event( ) -> bool: """Full single-event pipeline. Returns ``True`` to keep iterating. - Returns ``False`` when the cost cap has been hit — the caller stops + Returns ``False`` when the cost cap has been hit; the caller stops the outer loop. Persistent extraction failures don't stop the loop; they land in ``failed_events``. The mutation surface (``summary``, ``known_sender_domains``) is - safe under the asyncio-single-threaded model — increments don't + safe under the asyncio-single-threaded model: increments don't race because there's no real parallelism, only cooperative multitasking. The ``ledger_lock`` is what we need: it serializes the read-modify-write inside :func:`cost_ledger.charge` so two @@ -513,9 +517,9 @@ async def _process_event( ) if route.property_id is not None: summary.routed_property += 1 - # Track this sender's domain as "seen" — feeds Step 9's - # sender_routing_history bootstrap and lets the unrouted - # classifier distinguish unknown vs no-signal senders. + # Track this sender's domain as "seen". This lets the + # unrouted classifier distinguish unknown vs no-signal + # senders. sender = str(ev.metadata.get("from", "") or "") domain_match = _DOMAIN_RE.search(sender) if domain_match: @@ -531,13 +535,9 @@ async def _process_event( metadata=ev.metadata, known_sender_domains=known_sender_domains, ) - summary.miss_reasons[bucket] = ( - summary.miss_reasons.get(bucket, 0) + 1 - ) + summary.miss_reasons[bucket] = summary.miss_reasons.get(bucket, 0) + 1 - historical = _is_historical( - ev.received_at, threshold_days=HISTORICAL_THRESHOLD_DAYS - ) + historical = _is_historical(ev.received_at, threshold_days=HISTORICAL_THRESHOLD_DAYS) # --- 3. Extract facts (only when the event landed at a property) ------- error_text: str | None = None @@ -582,7 +582,7 @@ async def _process_event( try: async with ledger_lock: cost_ledger.charge(label, cost) - except CostCapExceeded as exc: + except CostCapExceededError as exc: log.warning( "buena_email.cost_cap_post_charge", cumulative=str(exc.cumulative), @@ -598,21 +598,17 @@ async def _process_event( event_id=event_id, route=route, received_at=ev.received_at, - historical=( - historical and not reprocess_historical - ), + historical=(historical and not reprocess_historical), error=None, ) await session.commit() return False - except Exception as exc: # noqa: BLE001 — keep loop alive + except Exception as exc: # noqa: BLE001 (keep loop alive) summary.extractor_errors += 1 error_text = f"{type(exc).__name__}: {exc}"[:500] if len(summary.error_samples) < 5: summary.error_samples.append(error_text) - log.exception( - "buena_email.extractor_error", source_ref=ev.source_ref - ) + log.exception("buena_email.extractor_error", source_ref=ev.source_ref) async with factory() as session: hit_dead_letter = await _record_failure( session, @@ -642,9 +638,7 @@ async def _process_event( return True -async def _populate_top_properties( - factory: Any, summary: EmailBackfillSummary -) -> None: +async def _populate_top_properties(factory: Any, summary: EmailBackfillSummary) -> None: """Top 10 properties by inserted email-event count (sanity check).""" async with factory() as session: result = await session.execute( @@ -670,9 +664,9 @@ async def _load_known_sender_domains(factory: Any) -> set[str]: Reading existing email events whose property_id is set lets the "unknown_sender_domain" bucket distinguish first-time senders from senders we've successfully routed before. Empty on a fresh DB; that's - fine — every classification will fall through to the - unknown-sender-domain bucket on the first run, which is itself the - signal Step 9 wants. + fine: every classification will fall through to the + unknown-sender-domain bucket on the first run, which correctly + reports that no sender has been seen yet. """ domains: set[str] = set() async with factory() as session: @@ -709,16 +703,17 @@ async def backfill_emails( Args: root: Override ``EXTRACTED_ROOT``; defaults to the Buena archive. - cap_usd: Hard ceiling on the durable cost ledger for label - ``step6_email_backfill``. - dead_letter_after: Persistent-failure ceiling — once an event's + cap_usd: Hard ceiling on the durable cost ledger for + :data:`LEDGER_LABEL`. + dead_letter_after: Persistent-failure ceiling: once an event's ``failed_events.retry_count`` reaches this number, the row stays as the operator's dead-letter signal. reprocess_historical: When ``False`` (default), events older than 30 days are stamped ``processed_at = received_at`` after - successful extraction so Phase 9's validator/uncertainty - layers don't re-process pre-validator extractions. Phase 9 - migrations flip this to ``True`` once those layers ship. + successful extraction so the validator/uncertainty layers + don't re-process extractions made before validation existed. + Pass ``True`` to stamp ``processed_at = now()`` instead when + the archive should be treated as freshly processed. limit: Stop after ``limit`` ``.eml`` files. ``None`` means full archive. concurrency: Number of parallel extraction workers. Default 1 @@ -727,7 +722,7 @@ async def backfill_emails( read-modify-write can't double-spend; the worst-case overshoot is bounded by ``N × max_call_cost`` because that many calls can be in-flight when the cap is breached. See - DECISIONS.md for the auditable bound. + docs/DECISIONS.md for the auditable bound. """ extracted_root = root if root is not None else buena_archive.require_root() emails_dir = extracted_root / "emails" @@ -758,7 +753,7 @@ async def backfill_emails( iterator: Iterable[ConnectorEvent] = eml_archive.walk_directory(emails_dir) if concurrency <= 1: - # Sequential path — preserves the dry-run / test path behaviour. + # Sequential path: preserves the dry-run / test path behaviour. seen = 0 for ev in iterator: if limit is not None and seen >= limit: @@ -778,13 +773,11 @@ async def backfill_emails( if not proceed: break else: - # Concurrent path — producer feeds a bounded queue, ``concurrency`` + # Concurrent path: producer feeds a bounded queue, ``concurrency`` # consumers process events. ``abort_event`` short-circuits both # sides on cost-cap breach; in-flight tasks finish (≤ N × call cost # overshoot) but no new work starts. - queue: asyncio.Queue[ConnectorEvent | None] = asyncio.Queue( - maxsize=concurrency * 4 - ) + queue: asyncio.Queue[ConnectorEvent | None] = asyncio.Queue(maxsize=concurrency * 4) abort_event = asyncio.Event() async def _producer() -> None: @@ -820,7 +813,7 @@ async def _consumer(_worker_id: int) -> None: ledger_lock=ledger_lock, known_sender_domains=known_sender_domains, ) - except Exception: # noqa: BLE001 — keep workers alive + except Exception: # noqa: BLE001 (keep workers alive) log.exception( "buena_email.consumer_error", worker=_worker_id, @@ -831,9 +824,7 @@ async def _consumer(_worker_id: int) -> None: abort_event.set() producer_task = asyncio.create_task(_producer()) - consumer_tasks = [ - asyncio.create_task(_consumer(i)) for i in range(concurrency) - ] + consumer_tasks = [asyncio.create_task(_consumer(i)) for i in range(concurrency)] await asyncio.gather(producer_task, *consumer_tasks) state_after = cost_ledger.get_state(LEDGER_LABEL) diff --git a/connectors/buena_event_loader.py b/connectors/buena_event_loader.py index 5ea60b8..d14b822 100644 --- a/connectors/buena_event_loader.py +++ b/connectors/buena_event_loader.py @@ -1,12 +1,14 @@ """Stream Buena structured events into the events + facts tables. -Phase 8 Step 3 backfills the deterministic data sources (bank -transactions, invoice PDFs) directly: each event lands in ``events`` +This module backfills the deterministic data sources (bank +transactions, invoice PDFs) directly, without the LLM worker: each event lands in ``events`` via :func:`backend.pipeline.events.insert_event`, the structured router in :mod:`backend.pipeline.router` resolves a property when possible, and :mod:`backend.pipeline.structured_extractors` writes facts synchronously. Stamping ``processed_at = received_at`` keeps the live -worker hands-off (KEYSTONE Part X "historical events stamped" rule). +worker hands-off: the worker only claims events whose ``processed_at`` +is NULL, so historical events that already have their facts written +are never re-extracted. Idempotency: @@ -22,7 +24,7 @@ import asyncio from collections.abc import Callable, Iterable from dataclasses import dataclass -from datetime import datetime +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -37,7 +39,7 @@ stamp_processed, ) from connectors import buena_archive -from connectors.base import ConnectorEvent, DataMissing +from connectors.base import ConnectorEvent, DataMissingError from connectors.migrations import apply_all as ensure_migrations log = structlog.get_logger(__name__) @@ -49,8 +51,8 @@ class BackfillSummary: The four-tier counts (``routed_property / routed_building / routed_liegenschaft / unrouted``) sum to ``inserted_now`` and let the - operator read the per-tier miss rates that Phase 8.1 verification - requires. + operator read the per-tier miss rates, which is how routing quality + is checked after a backfill. """ label: str @@ -66,11 +68,7 @@ class BackfillSummary: @property def routed(self) -> int: """Total events that resolved to *some* scope (any tier).""" - return ( - self.routed_property - + self.routed_building - + self.routed_liegenschaft - ) + return self.routed_property + self.routed_building + self.routed_liegenschaft def as_json(self) -> dict[str, Any]: """Serializable view for the CLI's ``--json`` mode.""" @@ -127,9 +125,7 @@ async def _ingest_one( summary.unrouted += 1 if summary.miss_reasons is None: summary.miss_reasons = {} - summary.miss_reasons[route.reason] = ( - summary.miss_reasons.get(route.reason, 0) + 1 - ) + summary.miss_reasons[route.reason] = summary.miss_reasons.get(route.reason, 0) + 1 # Write facts (no-op when no scope is resolved). written = await fact_writer( @@ -159,9 +155,7 @@ def _normalise_ts(received: datetime | None) -> datetime | None: if received is None: return None if received.tzinfo is None: - from datetime import timezone # noqa: PLC0415 - - return received.replace(tzinfo=timezone.utc) + return received.replace(tzinfo=UTC) return received @@ -178,10 +172,8 @@ async def _drive( for ev in iterator: summary.total_seen += 1 try: - await _ingest_one( - factory, ev, fact_writer=fact_writer, summary=summary - ) - except Exception: # noqa: BLE001 — keep the backfill moving + await _ingest_one(factory, ev, fact_writer=fact_writer, summary=summary) + except Exception: # noqa: BLE001 (keep the backfill moving) log.exception( "backfill.error", label=label, @@ -209,7 +201,7 @@ async def backfill_bank(*, root: Path | None = None) -> BackfillSummary: async def backfill_invoices(*, root: Path | None = None) -> BackfillSummary: """Backfill every PDF under ``Extracted/rechnungen/`` (filename only). - PDF text is *not* extracted by default — Step 3 only needs the + PDF text is *not* extracted by default: the backfill only needs the filename for ID + document_type, which the connector populates from heuristics. ``extract_invoice_facts`` records the latest invoice + serviced_by edge when the property resolves. @@ -223,7 +215,7 @@ async def backfill_invoices(*, root: Path | None = None) -> BackfillSummary: # ----------------------------------------------------------------------------- -# Sync wrappers — the CLI is sync; running coroutines via asyncio.run keeps the +# Sync wrappers: the CLI is sync; running coroutines via asyncio.run keeps the # entry points small. # ----------------------------------------------------------------------------- @@ -281,12 +273,10 @@ async def _reroute_one( summary: RerouteSummary, ) -> None: """Re-evaluate routing for one already-ingested event.""" - from sqlalchemy import text # noqa: PLC0415 — local import keeps imports tidy + from sqlalchemy import text # noqa: PLC0415 (local import keeps imports tidy) async with factory() as session: - route: StructuredRoute = await route_structured( - session, metadata, event_source=source - ) + route: StructuredRoute = await route_structured(session, metadata, event_source=source) if route.property_id is not None: summary.moved_to_property += 1 elif route.building_id is not None: @@ -297,9 +287,7 @@ async def _reroute_one( summary.still_unrouted += 1 if summary.miss_reasons is None: summary.miss_reasons = {} - summary.miss_reasons[route.reason] = ( - summary.miss_reasons.get(route.reason, 0) + 1 - ) + summary.miss_reasons[route.reason] = summary.miss_reasons.get(route.reason, 0) + 1 await session.commit() return @@ -323,7 +311,7 @@ async def _reroute_one( ) # Write any facts that follow from the new scope. Same writer - # logic as the backfill — identical writes short-circuit. + # logic as the backfill; identical writes short-circuit. writer = ( extract_bank_facts if source == "bank" @@ -352,10 +340,11 @@ async def re_route_unrouted( ) -> RerouteSummary: """Walk every event with no scope set and re-evaluate routing. - One-time migration step after Phase 8.1 schema/router changes — - surfaces in ``DECISIONS.md`` as a documented re-attribution pass, - not as ongoing pipeline behavior. Idempotent: re-running on already- - re-routed events finds nothing new to scan. + One-time migration step for events ingested before the router + learned the building and Liegenschaft tiers; it is recorded in + ``docs/DECISIONS.md`` as a documented re-attribution pass, not as + ongoing pipeline behavior. Idempotent: re-running on already-re-routed + events finds nothing new to scan. """ from sqlalchemy import text # noqa: PLC0415 @@ -418,5 +407,5 @@ def run_re_route(sources: list[str] | None = None) -> RerouteSummary: "run_backfill_bank", "run_backfill_invoices", "run_re_route", - "DataMissing", + "DataMissingError", ] diff --git a/connectors/buena_loader.py b/connectors/buena_loader.py index 63c3531..8f0ed15 100644 --- a/connectors/buena_loader.py +++ b/connectors/buena_loader.py @@ -1,9 +1,9 @@ -"""Adapt Buena Stammdaten dicts onto Phase 0's seed dataclasses + upserts. +"""Adapt Buena Stammdaten dicts onto the seed dataclasses + upserts. This module is the bridge between :mod:`connectors.buena_archive` (which produces redacted dicts) and :mod:`seed.seed` (which owns the canonical ``_upsert_*`` helpers). Reusing the existing helpers keeps a single -ingestion path for **all** customer master data — Berliner 4B and the +ingestion path for **all** customer master data: Berliner 4B and the Buena dataset travel through the same SQL. Public entry point: :func:`load_stammdaten` runs the full upsert @@ -202,14 +202,14 @@ def load_stammdaten( with psycopg2.connect(url) as conn: conn.autocommit = False with conn.cursor() as cur: - # Phase 0 schema is the contract; the seed module already knows + # The base schema is the contract; the seed module already knows # how to apply it idempotently. Re-using that here ensures the # canonical tables exist on a fresh DB before our additive # migrations + Buena rows land. if not _schema_applied(cur): _apply_schema(cur) - # ---- Liegenschaften (WEG) — must come before buildings so we + # ---- Liegenschaften (WEG): must come before buildings so we # can stamp building.liegenschaft_id during the building upsert. for raw in payload.liegenschaften: lie_key = str(raw.get("buena_liegenschaft_id") or "") @@ -230,32 +230,32 @@ def load_stammdaten( # ---- Owners ---- for raw in payload.owners: - seed = _owner_seed(raw) - before = _count(cur, "owners", "email", seed.email) - uid = _upsert_owner(cur, seed) + owner_seed = _owner_seed(raw) + before = _count(cur, "owners", "email", owner_seed.email) + uid = _upsert_owner(cur, owner_seed) if before == 0: summary.owners_inserted_now += 1 - owner_uuid_by_key[seed.key] = uid + owner_uuid_by_key[owner_seed.key] = uid # ---- Buildings + Haus → WEG link ---- for raw in payload.buildings: - seed = _building_seed(raw) - before = _count(cur, "buildings", "address", seed.address) - uid = _upsert_building(cur, seed) + building_seed = _building_seed(raw) + before = _count(cur, "buildings", "address", building_seed.address) + uid = _upsert_building(cur, building_seed) if before == 0: summary.buildings_inserted_now += 1 - building_uuid_by_key[seed.key] = uid + building_uuid_by_key[building_seed.key] = uid lie_key = str(raw.get("buena_liegenschaft_id") or "") - lie_uuid = liegenschaft_uuid_by_key.get(lie_key) - if lie_uuid is not None: - _set_building_liegenschaft(cur, uid, lie_uuid) + weg_uuid = liegenschaft_uuid_by_key.get(lie_key) + if weg_uuid is not None: + _set_building_liegenschaft(cur, uid, weg_uuid) # ---- Contractors ---- for raw in payload.contractors: - seed = _contractor_seed(raw) - before = _count(cur, "contractors", "name", seed.name) - _upsert_contractor(cur, seed) + contractor_seed = _contractor_seed(raw) + before = _count(cur, "contractors", "name", contractor_seed.name) + _upsert_contractor(cur, contractor_seed) if before == 0: summary.contractors_inserted_now += 1 @@ -274,24 +274,30 @@ def load_stammdaten( building_key=building_key, ) continue - seed = _property_seed(raw, owner_key, building_key) - before = _count(cur, "properties", "name", seed.name) - uid = _upsert_property(cur, seed, owner_uuid, building_uuid) + prop_seed = _property_seed(raw, owner_key, building_key) + before = _count(cur, "properties", "name", prop_seed.name) + uid = _upsert_property(cur, prop_seed, owner_uuid, building_uuid) if before == 0: summary.properties_inserted_now += 1 - property_uuid_by_eh[seed.key] = uid + property_uuid_by_eh[prop_seed.key] = uid # Edges that are always true once the property exists. _add_edge( - cur, summary, - from_type="property", from_id=uid, - to_type="owner", to_id=owner_uuid, + cur, + summary, + from_type="property", + from_id=uid, + to_type="owner", + to_id=owner_uuid, rel="owned_by", ) _add_edge( - cur, summary, - from_type="property", from_id=uid, - to_type="building", to_id=building_uuid, + cur, + summary, + from_type="property", + from_id=uid, + to_type="building", + to_id=building_uuid, rel="in_building", ) @@ -308,20 +314,23 @@ def load_stammdaten( if metadata.get("active") is False: summary.tenants_skipped_inactive += 1 continue - seed = _tenant_seed(raw) - if not seed.email: + tenant_seed = _tenant_seed(raw) + if not tenant_seed.email: # _upsert_tenant uses email as natural key; skip rows # without one rather than collapse them all together. summary.tenants_skipped_inactive += 1 continue - before = _count_tenant(cur, property_uuid, seed.email) - uid = _upsert_tenant(cur, property_uuid, seed) + before = _count_tenant(cur, property_uuid, tenant_seed.email) + uid = _upsert_tenant(cur, property_uuid, tenant_seed) if before == 0: summary.tenants_inserted_now += 1 _add_edge( - cur, summary, - from_type="property", from_id=property_uuid, - to_type="tenant", to_id=uid, + cur, + summary, + from_type="property", + from_id=property_uuid, + to_type="tenant", + to_id=uid, rel="occupied_by", ) @@ -337,7 +346,8 @@ def _count(cur: psycopg2.extensions.cursor, table: str, column: str, value: Any) f"SELECT COUNT(*) FROM {table} WHERE {column} = %s", (value,), ) - return int(cur.fetchone()[0] or 0) + row = cur.fetchone() + return int(row[0] or 0) if row else 0 def _count_tenant(cur: psycopg2.extensions.cursor, property_id: str, email: str) -> int: @@ -346,7 +356,8 @@ def _count_tenant(cur: psycopg2.extensions.cursor, property_id: str, email: str) "SELECT COUNT(*) FROM tenants WHERE property_id = %s AND email = %s", (property_id, email), ) - return int(cur.fetchone()[0] or 0) + row = cur.fetchone() + return int(row[0] or 0) if row else 0 def _add_edge( @@ -376,7 +387,7 @@ def load_from_disk( extracted_root: str | None = None, connection_url: str | None = None, ) -> LoadSummary: - """Convenience wrapper — read from disk + load. Used by the CLI.""" + """Convenience wrapper: read from disk + load. Used by the CLI.""" root = buena_archive.require_root(extracted_root) payload = buena_archive.load_stammdaten(root) return load_stammdaten(payload, connection_url=connection_url) diff --git a/connectors/camt_bank.py b/connectors/camt_bank.py index 9420d09..dc8408d 100644 --- a/connectors/camt_bank.py +++ b/connectors/camt_bank.py @@ -9,8 +9,8 @@ referenz_id, error_types`` This connector emits :class:`ConnectorEvent` rows the structured -extractor (Phase 8 Step 3) can convert directly into financial facts — -no Gemini needed. +extractor (:mod:`backend.pipeline.structured_extractors`) can convert +directly into financial facts, so no LLM call is needed. """ from __future__ import annotations @@ -18,7 +18,7 @@ import csv import hashlib from collections.abc import Iterator -from datetime import datetime, timezone +from datetime import UTC, datetime from decimal import Decimal, InvalidOperation from pathlib import Path from typing import Any @@ -43,7 +43,7 @@ def _stable_source_ref(row: dict[str, str]) -> str: f"{row.get('betrag', '')}|" f"{row.get('verwendungszweck', '')}|" f"{row.get('id', '')}" - ).encode("utf-8") + ).encode() return hashlib.sha256(canonical).hexdigest()[:12] @@ -62,7 +62,7 @@ def _parse_date(raw: str | None) -> datetime | None: if not raw or not raw.strip(): return None try: - return datetime.strptime(raw.strip(), "%Y-%m-%d").replace(tzinfo=timezone.utc) + return datetime.strptime(raw.strip(), "%Y-%m-%d").replace(tzinfo=UTC) except ValueError: return None @@ -83,7 +83,7 @@ def parse_row(row: dict[str, str]) -> ConnectorEvent: signed_amount = -amount if typ == "DEBIT" else amount received_at = _parse_date(row.get("datum")) - received_at = received_at or datetime.now(timezone.utc) + received_at = received_at or datetime.now(UTC) metadata: dict[str, Any] = { "valuta": row.get("datum"), diff --git a/connectors/cli.py b/connectors/cli.py index e55a47d..3c62a1c 100644 --- a/connectors/cli.py +++ b/connectors/cli.py @@ -1,4 +1,4 @@ -"""Connector CLI — single entry point for every customer ingest path. +"""Connector CLI: the single entry point for every customer ingest path. Usage:: @@ -20,10 +20,13 @@ import structlog from backend.logging import configure_logging -from connectors.base import DataMissing +from backend.pipeline.materializer import run_materialize_all from connectors import cost_ledger as cost_ledger_module +from connectors.base import DataMissingError from connectors.buena_email_loader import ( LEDGER_LABEL as EMAIL_LEDGER_LABEL, +) +from connectors.buena_email_loader import ( EmailBackfillSummary, run_backfill_emails, ) @@ -35,7 +38,7 @@ run_re_route, ) from connectors.buena_loader import load_from_disk -from backend.pipeline.materializer import run_materialize_all +from connectors.sample_events import run_load_sample_events log = structlog.get_logger("connectors.cli") @@ -66,15 +69,14 @@ def _cmd_load_stammdaten(args: argparse.Namespace) -> int: """Handle the ``load-stammdaten`` subcommand.""" if args.source not in SUPPORTED_SOURCES: print( - f"unknown --source: {args.source!r}; " - f"supported: {', '.join(SUPPORTED_SOURCES)}", + f"unknown --source: {args.source!r}; supported: {', '.join(SUPPORTED_SOURCES)}", file=sys.stderr, ) return 2 try: summary = load_from_disk(extracted_root=args.extracted_root) - except DataMissing as exc: + except DataMissingError as exc: print(f"buena dataset missing: {exc}", file=sys.stderr) return 3 @@ -128,14 +130,13 @@ def _cmd_backfill_bank(args: argparse.Namespace) -> int: """Handle the ``backfill-bank`` subcommand.""" if args.source not in SUPPORTED_SOURCES: print( - f"unknown --source: {args.source!r}; " - f"supported: {', '.join(SUPPORTED_SOURCES)}", + f"unknown --source: {args.source!r}; supported: {', '.join(SUPPORTED_SOURCES)}", file=sys.stderr, ) return 2 try: summary = run_backfill_bank(extracted_root=args.extracted_root) - except DataMissing as exc: + except DataMissingError as exc: print(f"buena dataset missing: {exc}", file=sys.stderr) return 3 if args.json: @@ -149,14 +150,13 @@ def _cmd_backfill_invoices(args: argparse.Namespace) -> int: """Handle the ``backfill-invoices`` subcommand.""" if args.source not in SUPPORTED_SOURCES: print( - f"unknown --source: {args.source!r}; " - f"supported: {', '.join(SUPPORTED_SOURCES)}", + f"unknown --source: {args.source!r}; supported: {', '.join(SUPPORTED_SOURCES)}", file=sys.stderr, ) return 2 try: summary = run_backfill_invoices(extracted_root=args.extracted_root) - except DataMissing as exc: + except DataMissingError as exc: print(f"buena dataset missing: {exc}", file=sys.stderr) return 3 if args.json: @@ -171,7 +171,10 @@ def _format_email_backfill(summary: EmailBackfillSummary) -> str: inserted = summary.inserted_now or 1 pct_routed = ( (summary.routed_property + summary.routed_building + summary.routed_liegenschaft) - / inserted * 100 if summary.inserted_now else 0.0 + / inserted + * 100 + if summary.inserted_now + else 0.0 ) pct_unrouted = (summary.unrouted / inserted * 100) if summary.inserted_now else 0.0 miss_lines = ( @@ -183,9 +186,7 @@ def _format_email_backfill(summary: EmailBackfillSummary) -> str: ) or " (none)" ) - err_lines = ( - "\n".join(f" {s}" for s in summary.error_samples) or " (none)" - ) + err_lines = "\n".join(f" {s}" for s in summary.error_samples) or " (none)" top_props = ( "\n".join( f" {n:>4} {name}" @@ -224,18 +225,16 @@ def _cmd_backfill_emails(args: argparse.Namespace) -> int: """Handle the ``backfill-emails`` subcommand.""" if args.source not in SUPPORTED_SOURCES: print( - f"unknown --source: {args.source!r}; " - f"supported: {', '.join(SUPPORTED_SOURCES)}", + f"unknown --source: {args.source!r}; supported: {', '.join(SUPPORTED_SOURCES)}", file=sys.stderr, ) return 2 if args.reset_cost_ledger: - # Friction gate — ledger reset is intentional. The y/N prompt + # Friction gate: ledger reset is intentional. The y/N prompt # makes it impossible to wipe spend by reflex. prompt = ( - f"Reset cost ledger row '{EMAIL_LEDGER_LABEL}' " - "(deletes durable spend record)? [y/N] " + f"Reset cost ledger row '{EMAIL_LEDGER_LABEL}' (deletes durable spend record)? [y/N] " ) try: answer = input(prompt).strip().lower() @@ -244,10 +243,10 @@ def _cmd_backfill_emails(args: argparse.Namespace) -> int: if answer != "y": print("aborted: cost ledger NOT reset", file=sys.stderr) return 4 - cost_ledger_module.reset_label(EMAIL_LEDGER_LABEL) + cost_ledger_module.reset_label(EMAIL_LEDGER_LABEL, allow_production=True) print(f"cost ledger row '{EMAIL_LEDGER_LABEL}' reset") - from decimal import Decimal as _Decimal # noqa: PLC0415 — local import + from decimal import Decimal as _Decimal # noqa: PLC0415 (local import) try: summary = run_backfill_emails( @@ -258,7 +257,7 @@ def _cmd_backfill_emails(args: argparse.Namespace) -> int: limit=args.limit, concurrency=args.concurrency, ) - except DataMissing as exc: + except DataMissingError as exc: print(f"buena dataset missing: {exc}", file=sys.stderr) return 3 @@ -277,9 +276,10 @@ def _cmd_materialize_all(args: argparse.Namespace) -> int: Calls the renderer for every property/building/liegenschaft and upserts the rendered markdown into the matching ``*_files`` table. - Idempotent — re-running just refreshes ``last_rendered_at`` and the - ``content_md`` snapshot. Used as the Phase 12 bootstrap path so the - cache exists before the applier hook starts propagating updates. + Idempotent: re-running just refreshes ``last_rendered_at`` and the + ``content_md`` snapshot. Run it once to bootstrap the cache on an + existing database, so every file exists before the applier hook starts + propagating incremental updates into it. """ counts = run_materialize_all() if args.json: @@ -293,6 +293,19 @@ def _cmd_materialize_all(args: argparse.Namespace) -> int: return 0 +def _cmd_load_sample_events(args: argparse.Namespace) -> int: + """Handle the ``load-sample-events`` subcommand.""" + summary = run_load_sample_events() + if args.json: + print(json.dumps(summary.__dict__, indent=2)) + else: + print( + f"sample events: {summary.inserted} inserted, " + f"{summary.already_present} already present, {summary.processed} processed." + ) + return 0 + + def _cmd_re_route(args: argparse.Namespace) -> int: """Handle the one-time ``re-route`` subcommand. @@ -314,7 +327,7 @@ def build_parser() -> argparse.ArgumentParser: """Construct the argparse parser. Exposed for tests.""" parser = argparse.ArgumentParser( prog="connectors.cli", - description="Customer data ingestion — Buena is the first composer.", + description="Customer data ingestion: Buena is the first composer.", ) sub = parser.add_subparsers(dest="command", required=True) @@ -372,8 +385,7 @@ def build_parser() -> argparse.ArgumentParser: "--max-total-cost-usd", type=float, default=20.00, - help="Hard ceiling on the cost ledger for label " - f"'{EMAIL_LEDGER_LABEL}'. Default: 20.00.", + help=f"Hard ceiling on the cost ledger for label '{EMAIL_LEDGER_LABEL}'. Default: 20.00.", ) emails.add_argument( "--dead-letter-after", @@ -387,15 +399,14 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="When set, events older than 30 days are stamped " "processed_at=now() rather than processed_at=received_at. " - "Phase 9 migration flips this on once the validator/uncertainty " - "layers ship; default keeps backfill quiet for the live worker.", + "By default historical events keep processed_at=received_at so " + "the live worker does not re-process them.", ) emails.add_argument( "--limit", type=int, default=None, - help="Stop after N .eml files. Use for dry-runs without burning " - "the full cost cap.", + help="Stop after N .eml files. Use for dry-runs without burning the full cost cap.", ) emails.add_argument( "--concurrency", @@ -405,7 +416,7 @@ def build_parser() -> argparse.ArgumentParser: "(sequential). At N>1 the cost ledger charge() call is " "serialized via asyncio.Lock; worst-case overshoot if the " "cap is breached mid-flight is bounded by N * max_call_cost. " - "See DECISIONS.md for the auditable bound.", + "See docs/DECISIONS.md for the auditable bound.", ) emails.add_argument( "--reset-cost-ledger", @@ -420,15 +431,14 @@ def build_parser() -> argparse.ArgumentParser: "re-route", help=( "ONE-TIME migration: re-evaluate routing on every event that " - "has no scope set. Idempotent — safe to re-run." + "has no scope set. Idempotent: safe to re-run." ), ) reroute.add_argument( "--sources", nargs="*", default=None, - help="Optional list of event sources to limit the rescan to " - "(default: all sources).", + help="Optional list of event sources to limit the rescan to (default: all sources).", ) reroute.add_argument("--json", action="store_true") reroute.set_defaults(func=_cmd_re_route) @@ -436,14 +446,24 @@ def build_parser() -> argparse.ArgumentParser: materialize = sub.add_parser( "materialize-all", help=( - "Phase 12 bootstrap: render every property / building / " - "liegenschaft and store the markdown in the matching " - "*_files cache table. Idempotent." + "Render every property / building / liegenschaft and store " + "the markdown in the matching *_files cache table. Run once " + "after a bulk load that bypassed the applier. Idempotent." ), ) materialize.add_argument("--json", action="store_true") materialize.set_defaults(func=_cmd_materialize_all) + sample = sub.add_parser( + "load-sample-events", + help=( + "Insert the synthetic emails in Extracted_demo/sample_events/ and " + "process them, so the featured property has a history. Idempotent." + ), + ) + sample.add_argument("--json", action="store_true") + sample.set_defaults(func=_cmd_load_sample_events) + return parser diff --git a/connectors/cost_ledger.py b/connectors/cost_ledger.py index a596f86..f5e1e11 100644 --- a/connectors/cost_ledger.py +++ b/connectors/cost_ledger.py @@ -6,7 +6,7 @@ ``hit_at`` and aborts the process cleanly; subsequent invocations read the same row and abort *immediately* before issuing any LLM calls. -Reset is intentional and friction-gated — see +Reset is intentional and friction-gated; see :func:`reset_label` and the ``--reset-cost-ledger`` CLI flag, which prompts for ``y/N``. @@ -18,7 +18,7 @@ against the cap and short-circuits when exceeded. - For best-fit accounting, the caller can call :func:`record_actual` after the response lands to reconcile against measured token usage. - Phase 8 keeps this simple: estimated cost == actual cost. + Currently the two are the same: estimated cost == actual cost. """ from __future__ import annotations @@ -45,13 +45,12 @@ class LedgerState: exhausted: bool -class CostCapExceeded(RuntimeError): +class CostCapExceededError(RuntimeError): """Raised when a charge would push spend beyond ``cap_usd``.""" def __init__(self, label: str, cumulative: Decimal, cap: Decimal) -> None: super().__init__( - f"cost cap reached for label={label!r}: " - f"cumulative=${cumulative:.4f} cap=${cap:.4f}" + f"cost cap reached for label={label!r}: cumulative=${cumulative:.4f} cap=${cap:.4f}" ) self.label = label self.cumulative = cumulative @@ -85,7 +84,9 @@ def get_state(label: str, *, url: str | None = None) -> LedgerState | None: ) -def ensure_label(label: str, cap_usd: Decimal | float | str, *, url: str | None = None) -> LedgerState: +def ensure_label( + label: str, cap_usd: Decimal | float | str, *, url: str | None = None +) -> LedgerState: """Create the ledger row if missing; return current state.""" cap = Decimal(str(cap_usd)) ensure_migrations(url) @@ -103,6 +104,8 @@ def ensure_label(label: str, cap_usd: Decimal | float | str, *, url: str | None ) row = cur.fetchone() conn.commit() + if row is None: # unreachable: INSERT ... ON CONFLICT ... RETURNING always yields a row + raise RuntimeError(f"cost_ledger upsert returned no row for label={label}") return LedgerState( source_label=row[0], cumulative_usd=Decimal(row[1]), @@ -120,7 +123,7 @@ def charge( """Add ``amount_usd`` to ``label`` and return the post-charge state. Raises: - CostCapExceeded: if the post-charge cumulative would exceed the + CostCapExceededError: if the post-charge cumulative would exceed the stored ``cap_usd``. The row's ``hit_at`` is set on first breach so future calls also short-circuit. """ @@ -161,7 +164,7 @@ def charge( cumulative=str(cumulative), cap=str(cap), ) - raise CostCapExceeded(label, cumulative, cap) + raise CostCapExceededError(label, cumulative, cap) cur.execute( """ @@ -187,11 +190,28 @@ def charge( ) -def reset_label(label: str, *, url: str | None = None) -> None: +# Labels with this prefix belong to tests and may be reset freely. +TEST_LABEL_PREFIX = "test_" + + +def reset_label(label: str, *, url: str | None = None, allow_production: bool = False) -> None: """Delete the ledger row for ``label``. Used by ``--reset-cost-ledger``. - The CLI prompts ``y/N`` before calling this. + Only labels starting with :data:`TEST_LABEL_PREFIX` can be reset by + default. Any other label is a real spend record, and deleting it while + a backfill is charging it crashes that backfill; resetting one needs + ``allow_production=True``, which the CLI passes only after its ``y/N`` + prompt. + + Raises: + ValueError: ``label`` is not a test label and ``allow_production`` + is false. Nothing is deleted. """ + if not label.startswith(TEST_LABEL_PREFIX) and not allow_production: + raise ValueError( + f"refusing to reset cost ledger label {label!r}: only labels starting with " + f"{TEST_LABEL_PREFIX!r} can be reset without allow_production=True" + ) with _connect(url) as conn, conn.cursor() as cur: cur.execute("DELETE FROM cost_ledger WHERE source_label = %s", (label,)) conn.commit() diff --git a/connectors/csv_stammdaten.py b/connectors/csv_stammdaten.py index 4f15268..7c2a279 100644 --- a/connectors/csv_stammdaten.py +++ b/connectors/csv_stammdaten.py @@ -2,13 +2,13 @@ Parameterised by entity type (``owner | building | property | tenant | contractor``) and a column mapping. The loader reads the CSV, applies -PII redaction, and adapts each row into one of Phase 0's seed -dataclasses (``OwnerSeed``, ``BuildingSeed``, …) so we can reuse the +PII redaction, and adapts each row into one of the seed +dataclasses from :mod:`seed.realistic_data` (``OwnerSeed``, ``BuildingSeed``, …) so we can reuse the existing ``seed.seed._upsert_*`` helpers. The Buena composer (:mod:`connectors.buena_archive`) wires four CSV -readers — `eigentuemer`, `gebaeude/liegenschaft`, `mieter`, -`dienstleister` — plus the unit/property hybrid that comes from +readers (`eigentuemer`, `gebaeude/liegenschaft`, `mieter`, +`dienstleister`) plus the unit/property hybrid that comes from `einheiten.csv` joined with `liegenschaft` rows in `stammdaten.json`. """ @@ -19,7 +19,7 @@ from dataclasses import dataclass, field from datetime import date, datetime from pathlib import Path -from typing import Any, Literal, cast +from typing import Any, Literal import structlog @@ -37,7 +37,7 @@ class ColumnMap: The keys are Keystone field names; the values are the customer's column header in the source CSV. ``metadata_columns`` is the - pass-through bucket — every header listed here ends up under + pass-through bucket: every header listed here ends up under ``metadata`` after PII redaction. """ @@ -81,7 +81,7 @@ def _redact_value(column: str, value: str, pii_columns: Iterable[str]) -> Any: if "email" in lower or "mail" in lower: return redact.email_redact(value) if "bic" in lower: - # BIC is bank identifier — not strictly PII but Buena treats it as + # BIC is a bank identifier: not strictly PII, but Buena treats it as # bank-internal. Keep as-is; downstream can scrub if needed. return value return redact.scrub_text(value) @@ -111,9 +111,7 @@ def read_rows( if value is None: redacted[column] = None continue - redacted[column] = _redact_value( - column, value.strip(), column_map.pii_columns - ) + redacted[column] = _redact_value(column, value.strip(), column_map.pii_columns) mapped: dict[str, Any] = {} for canonical, source_col in column_map.required.items(): @@ -124,15 +122,14 @@ def read_rows( if col in redacted: metadata[col] = redacted[col] - natural_key = str(mapped.get("id") or mapped.get("email") or - mapped.get("name") or "") + natural_key = str(mapped.get("id") or mapped.get("email") or mapped.get("name") or "") log.debug( "stammdaten.row", entity_type=entity_type, natural_key=natural_key, ) yield StammdatenRow( - entity_type=cast(EntityType, entity_type), + entity_type=entity_type, natural_key=natural_key, fields=mapped, metadata=metadata, @@ -140,7 +137,7 @@ def read_rows( def parse_iso_date(value: Any) -> date | None: - """Public helper — exposed so composers can keep date logic consistent.""" + """Public helper, exposed so composers can keep date logic consistent.""" if value in (None, "", b""): return None if isinstance(value, date): diff --git a/connectors/document_type.py b/connectors/document_type.py index 9dec980..aaf6488 100644 --- a/connectors/document_type.py +++ b/connectors/document_type.py @@ -3,11 +3,12 @@ Pure function over ``(filename, head_text)``. Filename heuristics run first (cheap, deterministic). When heuristics return ``None`` the classifier falls back to Gemini Flash on the first 800 chars of -extracted text — and only when the Phase 8 cost ledger has remaining -budget under the ``pdf_doctype`` sub-label (default sub-cap ``$2``). +extracted text, and only when the cost ledger +(:mod:`connectors.cost_ledger`) has remaining budget under the +``pdf_doctype`` sub-label (default sub-cap ``$2``). -Phase 9 :mod:`backend.pipeline.validator` reads the resulting label -out of ``event.metadata.document_type`` to enforce constraints like +:mod:`backend.pipeline.validator` reads the resulting label out of +``event.metadata.document_type`` to enforce constraints like *"rent changes require a lease_addendum"*. """ @@ -21,7 +22,7 @@ import structlog from connectors import cost_ledger -from connectors.cost_ledger import CostCapExceeded +from connectors.cost_ledger import CostCapExceededError log = structlog.get_logger(__name__) @@ -37,7 +38,7 @@ "other", ] -#: All valid labels at runtime — used by the Gemini fallback to validate +#: All valid labels at runtime, used by the Gemini fallback to validate #: the model output. ``get_args`` gives us the literal members. DOCUMENT_TYPES: Final[tuple[str, ...]] = get_args(DocumentType) @@ -78,47 +79,46 @@ def _filename_heuristic(filename: str) -> DocumentType | None: {head_text} --- -Choose ONE label from this exact list — answer with JSON only: +Choose ONE label from this exact list and answer with JSON only: {labels_json} Output schema: {{"document_type": "