diff --git a/CHANGELOG.md b/CHANGELOG.md index aa6af5e..66e0dbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,18 +6,25 @@ Generated section is appended on release tag via `git-cliff` (see `.gitea/workfl ## [Unreleased] ### Added -- +- docs: 2026-09-11 revision — single platform cluster (`breakpilot-platform`) with staging and production on separate Hetzner VMs; core cluster (`breakpilot`) reduced to company infrastructure +- docs: always-on customer ⇄ CRM ⇄ ERP link (outbox, HMAC webhooks, 15-min reconcile, continuous usage records); ERPNext mock for staging +- docs: CLI licence model (registry-issued Ed25519 licence tokens, offline verify, phone-home, 4-state ladder) for Werkpilot and Firmwerk +- docs: `PRODUCT_INTEGRATION_SPEC.md` contract 2.0 — frontend types `standalone | headless | cli`, registry-backed entitlement check, usage event push +- docs: M-MIG-0 … M-MIG-9 migration milestones replace the M0–M19 greenfield plan ### Changed +- docs: hosts fixed to `app-stage.breakpilot.com` / `app.breakpilot.com`; tenants addressed by path; one branded host per web product per environment +- docs: first-line products are Prüfwerk (+ Werkbank add-on), Werkpilot, Firmwerk; breakpilot-compliance (dsms) migrates last; CERTifAI parked +- docs: Keycloak stays on core with realms `breakpilot-stage` / `breakpilot-prod`; token claims reduced to `tenant_id, tenant_slug, org_roles, tenant_status` +- docs: tenant status ladder unified with ERP/02 (`active | warning | restricted | halted`) +- docs: `COST_PLAN.md` rewritten for Hetzner (no commitments) - chore(domain): yourplatform.com → breakpilot.com -- + +### Removed +- docs: SysEleven topology, three-cluster split, PowerDNS + DNS-01 wildcard TLS, Stalwart mail, Orca-Proxy container, web-component/widget frontend contract, `cdn.breakpilot.com` bundles, custom domains (M18.1), Stripe and Polar.sh billing rails ### Fixed - ci: rework workflow for Gitea Actions (bash commitlint, inline gitleaks binary, per-stack jobs gated on real code) -- - -### Removed -- ### Security - diff --git a/COST_PLAN.md b/COST_PLAN.md index cf38c60..808f9ab 100644 --- a/COST_PLAN.md +++ b/COST_PLAN.md @@ -1,258 +1,84 @@ -# Cost Plan — SysEleven Infrastructure +# Cost Plan — Hetzner Infrastructure -Companion to `INFRASTRUCTURE.md` and `IMPLEMENTATION_PLAN.md`. Pricing source: `SysEleven-Cloud-Services-Preisinformationen_01_26_v2.pdf` (effective 2026-01-20). All prices net EUR, exclusive of 19% VAT. Region: DUS2 + HAM1. +Companion to `INFRASTRUCTURE.md` and `IMPLEMENTATION_PLAN.md`. **Revised 2026-09-11:** replaces the SysEleven plan (DUS2, 4 VMs / 3 clusters). The company runs on Hetzner Cloud already; the platform adds one Hetzner VM now (staging) and one later (production). All prices net EUR, exclusive of 19% VAT. **Hetzner list prices change; every figure marked "≈" must be re-checked in the Hetzner console at booking time.** --- ## 1. TL;DR -**Locked topology (2026-05-18):** 4 billable VMs — 1 stage + 3 prod — totalling **48 GiB-RAM**. See `INFRASTRUCTURE.md §1`. +| Item | Now (staging only) | After prod go-live | +|---|---|---| +| Core cluster (2 existing VMs, already paid) | unchanged | unchanged | +| `bp-platform-stage` — CX43/CPX41 class, 8 vCPU / 16 GB, 1 IPv4 | ≈ €25–30 | ≈ €25–30 | +| `bp-platform-prod` — ≥ 16 GB, dedicated cores (CCX23/CCX33 class), 1 IPv4 | — | ≈ €40–65 | +| Hetzner Volume for prod data (100 GB, €0.05/GB) | — | ≈ €5 | +| Object Storage (backups + seed + exports, ~300 GB) | ≈ €3–6 | ≈ €6–12 | +| Snapshots (2 VMs × ~40 GB, €0.012/GB) | ≈ €1 | ≈ €2 | +| Strato domain + mail (existing) | unchanged | unchanged | +| **Platform delta, net / month** | **≈ €30–40** | **≈ €80–125** | -All four pricing modes, side by side, at the locked sizing: - -| Mode | Compute €/mo | Storage €/mo | Network €/mo | **Total net €/mo** | + 19% VAT | **Annual gross €** | -|---|---:|---:|---:|---:|---:|---:| -| **On-Demand** | 434.50 | 112 | 2.92 | **549.42** | 653.81 | **7,846** | -| **12-month commit** | 295.20 | 112 | 2.92 | **410.12** | 488.04 | **5,856** | -| **36-month no upfront** | 216.00 | 112 | 2.92 | **330.92** | 393.79 | **4,725** | -| **36-month upfront** | 192.00 | 112 | 2.92 | **306.92** | 365.23 | **4,383** | - -**36M upfront one-time payment**: €6,912 net at signing (compute only; storage + network still billed monthly). - -**Recommended cash plan for Year 1:** -1. Months 1–3: burn On-Demand (~€549/mo) while flavors get proven against real workload -2. Month 4 onward: sign 36M-upfront commit at proven size (~€307/mo) -3. Year-1 total infra: **€4,410 net / €5,248 gross** + one-time €6,912 upfront in Month 4 - -Growth tiers extend that same baseline (next 4 sections drill in). +No commitments, no upfront payments: Hetzner bills hourly, monthly capped. Compare: the SysEleven plan was €307–549/mo plus €6,912 upfront. --- ## 2. What to use / what to skip -### Use from day one -| Service | Why | Cost | +| Service | Use? | Why | |---|---|---| -| **OpenStack IaaS (m2 GP)** | Bread and butter. General-purpose 1:4 vCPU:RAM fits everything. | per VM, see §3 | -| **Block Storage (Ceph)** | 3x replicated, persistent. €0.10/GiB/mo. | per GiB | -| **Object Storage (S3)** | Backups, audit logs, demo seed bundles, export ZIPs. €0.02/GiB/mo. | per GiB | -| **Floating IP** | Public IPs for vm-edge (1) and stage (1). | €2.92/IP/mo | -| **VPN as a Service** | Inclusive. Use for ops access from our laptops. | €0 | -| **Self-Service Support** | Free. Adequate while we're shaking out the platform. | €0 | - -### Defer until clearly needed -| Service | When to add | Cost | -|---|---|---| -| **DNS Zones (DNSaaS)** | Never — we self-host PowerDNS on vm-edge per [[self-hosted-oss-first]] | €10/zone — skipped | -| **Load Balancer (Octavia)** | When we add a second vm-edge for HA (Tier D). Until then orca-proxy + Floating IP is enough. | €14.60–57.67/mo | -| **Business Support** | When MRR > €5k. Below that, Self-Service docs cover us. | €185/mo | -| **Priority Support** | Only if we sign an Enterprise contract that requires <1h response. | €545/mo | -| **DDoS Guard PLUS** | After first attack OR before launching anything customer-promoted. | €875/mo | -| **DBaaS PostgreSQL Cluster** | When tenant_registry Postgres becomes the bottleneck (200+ customers, see RISK-1 in INFRASTRUCTURE.md). | €213–426/mo per cluster (m2.small–medium, 36M upfront) | -| **MetaKube Core (managed K8s)** | We use Orca (the user's own product). MetaKube would compete with Orca, not complement it. Skip unless Orca is replaced. | €0 by design | -| **Managed VM (Business/Priority)** | Defeats Orca. We are the ones who manage VMs. | skipped — saves €1k+/mo | -| **Operational Support Platform** | €759–€1,479/mo. Massive overkill until late stage. | skipped | - -### GPU instances (separate concern) -LiteLLM today is a passthrough. If we ever self-host an inference model: -- **L40S (24 GB GPU RAM)**: €1,309/mo On-Demand, €1,086 (12M), €877 (24M) -- **H100 NVL (94 GB)**: €5,755/mo On-Demand, €4,637 (12M), €3,743 (24M) - -For now: route LLM calls through LiteLLM → external provider. Add GPU only if a customer pays for dedicated inference. +| Cloud Servers (CX/CPX shared, CCX dedicated) | **Yes** | Shared vCPU is fine for staging; dedicated cores for prod (scan workloads, Chrome, Mongo). | +| Primary IPv4 per VM | **Yes** | Per-node ingress needs one public IPv4 per node (≈ €0.50–1/mo each). | +| Private Network | **Yes (free)** | Master ↔ agent Orca traffic; never expose 6880/6881 publicly. | +| Cloud Firewall | **Yes (free)** | Per-VM rules in §3 of INFRASTRUCTURE.md. | +| Snapshots | **Yes** | Weekly snapshot of each platform VM before prod; nightly for prod. | +| Volumes | Later | Attach when local NVMe > 60 %; dsms data on prod. | +| Object Storage (nbg1) | **Yes** | Already in use for core (`bp-*` buckets); one more bucket per cluster. | +| Load Balancer | Later (Tier D) | Only when a second prod app node exists. | +| Hetzner DNS | No | Zone stays at Strato (mail, existing records). Revisit only if Strato record limits bite. | +| Managed Kubernetes / any managed service | No | Orca orchestrates. | +| GPU servers | No | LiteLLM routes to external providers; add only for a paying dedicated-inference customer. | --- -## 3. Per-VM sizing — Locked topology (Tier A, 5 customers) +## 3. Sizing -Flavor mapping from `INFRASTRUCTURE.md §1` to SysEleven `m2` General Purpose (1 vCPU : 4 GiB RAM, 50 GiB ephemeral root included). +### Staging — `bp-platform-stage` (booked in M-MIG-3) -### Compute — all four pricing modes side by side +Committed memory of the full first-line stack ≈ 13 GB (INFRASTRUCTURE.md §2): portal, tenant-registry + Postgres, ERPNext mock, Prüfwerk (agent, dashboard, MCP, docs, Mongo, browserless/Chrome, soft-PLC, PLC-sim), Werkbank runner, Firmwerk cloud + Mongo, OTel agent, plus the Orca master itself. **16 GB is the floor**; 8 GB would force dropping browserless and the PLC targets from staging. 8 vCPU keeps Rust builds of demo targets and Chrome-based scans from starving the portal. -| VM | Env | Flavor | vCPU | RAM | On-Demand | 12M | 36M no-upfront | 36M upfront | -|---|---|---|---:|---:|---:|---:|---:|---:| -| stage | stage | m2.small | 2 | 8 GB | 72.42 | 49.20 | 36.00 | 32.00 | -| vm-edge | prod | m2.small | 2 | 8 GB | 72.42 | 49.20 | 36.00 | 32.00 | -| vm-control | prod | m2.medium | 4 | 16 GB | 144.83 | 98.40 | 72.00 | 64.00 | -| vm-data | prod | m2.medium | 4 | 16 GB | 144.83 | 98.40 | 72.00 | 64.00 | -| **TOTAL** | | | **12** | **48 GB** | **434.50** | **295.20** | **216.00** | **192.00** | +### Production — `bp-platform-prod` (sized in the production plan) -**36M upfront one-time cost:** 192 × 36 = **€6,912 net** at signing (compute only; everything else billed monthly). +Same stack minus the mock, plus headroom for real scans and, after M-MIG-9, the dsms project (Postgres 17, IPFS, Qdrant, Ollama embed ≈ +6 GB). Start at 16 GB dedicated (CCX23 class) if dsms stays on the stage node for a while; otherwise 32 GB (CCX33 class). Decide at prod planning with 4 weeks of staging metrics from SigNoz. -**Reference per-GiB-RAM rates** (the linear model behind all numbers above): -| Mode | €/GiB-RAM/mo | -|---|---:| -| On-Demand | 9.05 | -| 12M commit | 6.15 | -| 36M no-upfront | 4.50 | -| 36M upfront | 4.00 | +### Storage -Any future sizing change can be sanity-checked as `RAM × rate`. - -### Storage — Tier A steady state - -| Item | GiB | €/GiB/mo | €/mo | -|---|---:|---:|---:| -| stage block (ephemeral PG + Mongo + Qdrant in-VM) | +50 | 0.10 | 5.00 | -| vm-edge block (pg-keycloak + pg-infisical + Gitea repos) | +50 | 0.10 | 5.00 | -| vm-control block (MariaDB + Stalwart spool) | +250 | 0.10 | 25.00 | -| vm-data block (MongoDB + pg-app + Qdrant + MinIO) | +500 | 0.10 | 50.00 | -| Object storage — geo-redundant backups (DUS2↔HAM1) | ~500 | 0.0496 | 25.00 *(€12.50 first 6mo via launch discount)* | -| Object storage — seed bundles + exports + audit archive | ~100 | 0.02 | 2.00 | -| **Storage subtotal (steady state)** | | | **112.00** | -| **Storage subtotal (first 6 months)** | | | **99.50** | - -### Network - -| Item | €/mo | -|---|---:| -| 1 Floating IP (vm-edge — only public host in prod) | 2.92 | -| 1 Floating IP (stage — public for tester access) | 2.92 | -| PowerDNS (self-hosted on vm-edge) | 0 | -| Octavia Load Balancer (deferred to Tier D HA phase) | 0 | -| **Network subtotal** | **5.84** | - -> Storage table above uses 1 Floating IP. Adjust to **€5.84** if running stage with its own public IP (recommended). One-line delta of €2.92/mo. - -### Combined Tier A — four-mode summary - -| Mode | Compute | Storage | Network | **Total net €/mo** | + 19% VAT | **Annual gross €** | -|---|---:|---:|---:|---:|---:|---:| -| On-Demand | 434.50 | 112 | 5.84 | **552.34** | 657.28 | **7,887** | -| 12M commit | 295.20 | 112 | 5.84 | **413.04** | 491.52 | **5,898** | -| 36M no-upfront | 216.00 | 112 | 5.84 | **333.84** | 397.27 | **4,767** | -| 36M upfront | 192.00 | 112 | 5.84 | **309.84** | 368.71 | **4,425** | - -### Recommended cash plan — Year 1 (use this line in the pitch) - -| Months | Mode | €/mo (net) | Subtotal € | -|---|---|---:|---:| -| 1–3 (rightsizing window) | On-Demand | 552.34 | 1,657 | -| 4–12 (proven baseline) | 36M upfront | 309.84 | 2,789 | -| **Year-1 infra net** | | | **4,446** | -| + 19% VAT | | | **5,291** | -| + one-time 36M upfront in Month 4 | (compute)| | **6,912** | -| **Year-1 cash out (gross)** | | | **12,203** | - -### 3-year cumulative (full 36M commitment term) - -| Item | € | -|---|---:| -| Months 1–3 On-Demand (compute+storage+net) | 1,657 | -| Compute 36M upfront (paid Month 4) | 6,912 | -| Storage + network, 36 months × ~118 €/mo | 4,248 | -| **3-year infra net** | **12,817** | -| + 19% VAT | **15,252** | +Local NVMe of the flavors (80–160 GB) covers launch. Object storage grows with backups (30-day retention of nightly dumps ≈ 30 × dump size) and exports. --- -## 4. Growth tiers — what scales when +## 4. Growth tiers -### Tier A — Pilot (5 customers, first 6 months) -- **Locked topology**: 4 VMs (stage + vm-edge + vm-control + vm-data). See INFRASTRUCTURE.md §1. -- **Year 1 cash plan**: 3 months On-Demand → 36M upfront. ~€310/mo committed compute+storage+net + one-time €6,912. -- **Add**: Self-Service support (free). Skip LB, DNSaaS, DDoS, DBaaS, MetaKube, Managed Services. - -### Tier B — Early growth (50–200 customers, Year 1) -- **Vertical scale only.** Bump vm-data m2.medium → m2.large (+€64/mo for 36M upfront). -- **Add cold-standby vm-edge-spare** (€0 idle, only billed during a swap event). -- **Add Business Support** (€185/mo) once MRR > €5k. -- **Add LB Single Instance** (€14.60/mo) when we want zero-downtime portal deploys. -- **Add DDoS Guard PLUS** (€875/mo) before any marketing push. -- Estimated total: **~€1,100–1,400/mo + VAT**. - -### Tier C — Scale (500–1000 customers, Year 1–2) -- **Split vm-data** into vm-data + vm-data-db (move pg-app to its own VM; resolves RISK-1). - - Alternative: move pg-registry to DBaaS m2.small cluster (3 inst, 36M upfront): **€213/mo** -- **Split vm-control** into vm-control + vm-ops (ERPNext + MariaDB + Stalwart go to vm-ops): **+€64/mo** -- **HA edge**: second vm-edge, switch Floating IP → Load Balancer Double Instance (**€58/mo**). -- **Object storage growth:** audit logs, exports, demo backups → estimated 2 TB = **€40/mo**. -- Estimated total: **~€2,000–2,500/mo + VAT**. - -### Tier D — Full scale (2000 customers, Year 2–3) -- **3-node clusters** on hot paths: vm-control × 2, vm-data × 2. -- **Split vm-edge** into vm-edge + vm-identity + vm-secrets (back toward original 7-VM design). -- **DBaaS m2.medium cluster** (4V/16GB, 36M upfront): **€426/mo** for tenant_registry. -- **Keycloak HA cluster**: 2 vm-identity (m2.medium) + Postgres replica. -- **Priority Support** (€545/mo) becomes worth it. -- **Object storage:** ~5 TB = **€100/mo**. -- **DDoS Guard PREMIUM** (€2,200/mo) if traffic warrants — likely stays on PLUS. -- Estimated total: **€4,500–6,000/mo + VAT**. - -### Compute scaling cheat sheet (vs locked topology) - -| Tier | Customers | Topology delta from Tier A | Compute €/mo (36M upfront) | +| Tier | Customers | Topology delta | Platform compute ≈ €/mo | |---|---:|---|---:| -| **A** | 5 | locked baseline: stage + 3 prod VMs (48 GiB) | **192** | -| **B** | 200 | + vm-data bumped m2.med → m2.large (+16 GiB) | **256** | -| **C** | 1000 | + split vm-data (+16 GiB), split vm-control (+16 GiB) | **384** | -| **D** | 2000 | + split vm-edge (3 → 3 VMs), HA clusters (~+90 GiB) | **~640** | - -The **€4/GiB-RAM/mo rate** (GP, 36M upfront) is the linear model — everything else (storage, network, support, DBaaS, DDoS) scales sub-linearly with customer count. Compute is never the bottleneck on the bill. +| **A** | ≤ 50 | stage CX43 + prod CCX23/33 | 65–95 | +| **B** | 50–200 | prod flavor bump; small control VM (CX23 class) as Orca master; prod Volume | 110–160 | +| **C** | 200–500 | split prod into app node + db node; Keycloak to its own core node | 200–300 | +| **D** | 500+ | second prod app node + Load Balancer; second S3 provider | 350–500 | --- ## 5. Cost per customer -| Tier | Customers | Monthly infra net (€) | Per customer/month (€) | -|---|---:|---:|---:| -| A | 5 | 310 | **62.00** | -| B | 200 | 1,200 | **6.00** | -| C | 1000 | 2,300 | **2.30** | -| D | 2000 | 5,000 | **2.50** | - -At Tier A the per-customer cost is irrelevant — fixed costs dominate. From Tier B onward our gross margin on a Professional plan (assume €99/customer/month) is **~94%** infrastructure-only. Add LLM passthrough (LiteLLM) + Polar.sh fees (~5%) + on-call time, and we are still well above the 80% gross margin floor SaaS investors look for. - -**Break-even: ~4 paying customers at €99/mo covers Tier A infra (€310/mo net).** +At Tier A the platform delta is ≈ €80–125/mo; **one `PLT-CORE-CLD-STD` tenant (€290/mo) covers it**. From Tier B onward infrastructure is < 3 % of revenue at the SKU-sheet prices; LLM passthrough (LiteLLM) and on-call time dominate the cost of goods, not compute. --- -## 6. SysEleven services we explicitly skip and why +## 6. Things to validate at booking -| Service | Why skip | -|---|---| -| DNSaaS (€10/zone) | We self-host PowerDNS on vm-gateway. €0 marginal cost since vm-gateway exists anyway. | -| MetaKube Core | Orca already orchestrates our containers. MetaKube would mean abandoning Orca, which the user owns. | -| MetaKube Accelerator | Same — competes with Orca. | -| MetaKube Operator add-ons (ExternalDNS, Cert-Manager, Tideways, Velero etc. at €78–171/mo each) | We pick and roll our own per [[self-hosted-oss-first]]. | -| Managed VM (Business €128–142/mo per VM, Priority €164–182) | Defeats Orca. We are the operators. Saves €1k+/mo at 7 VMs. | -| Operational Support Platform (€759–1,479/mo) | Massively over-specified for our scale. Buy individual Engineering Support days (€1,264/day) on demand if a real incident requires it. | -| DDoS Guard PREMIUM (€2,200) / ENTERPRISE (€4,800) | PLUS at €875/mo is enough for ≤500-customer scale. Upgrade if we see actual 1+ Tbps attacks. | -| Block Storage for Databases (€0.09 vs €0.10) | The €0.01/GiB difference saves ~€5/mo at our scale. Use it only on DBaaS cluster volumes (where SysEleven enforces it anyway). | +- Exact flavor names and prices in the console (CX43 / CPX41 / CCX23 naming changes between generations). +- Location: `fsn1` or `nbg1` — keep the platform in the same location as the core master for latency to Keycloak; Object Storage is `nbg1` regardless. +- IPv4 availability and price per primary IP. +- Whether the company Hetzner project (the one holding the core servers and the `bp-*` buckets, migrated 2026-09-10) is used — it must be, for one invoice and one firewall set. --- -## 7. Negotiation levers - -SysEleven publishes list prices but is open to commercial negotiation, especially as a German Mittelstand provider courting startups. Things worth asking for: - -1. **Startup credits.** Hetzner, OVH, and most EU clouds run startup-credit programs. Ask SysEleven for the equivalent before signing the 36M commit. Even €5–10k of credits = 6–12 months of Tier A infra free. -2. **EXIST / HTGF discount.** If we close the €1.5M raise (`project_breakpilot_fundraising`), SysEleven sometimes offers "Gründerförderung" pricing for HTGF-backed companies. -3. **Single-region discount.** We don't need DUS2 + HAM1 geo-redundancy at Tier A. Ask if single-region (DUS2 only) is cheaper. -4. **Object storage commitment.** 6-month 50%-off on geo-redundant storage applies anyway, but bulk commitments on regular S3 may unlock further pricing. -5. **Bundled support.** If we commit to 36M IaaS + Business Support, ask for support fee waiver in year 1. -6. **Move-in incentive.** Negotiate a setup/migration credit covering first 3 months of On-Demand burn. - ---- - -## 8. Open questions / things to validate - -- **Port 25 outbound from vm-ops.** Confirmed with SysEleven that outbound SMTP is allowed by default; if not, fall-back is to relay through Postal/Postmark for transactional only. -- **Region choice.** DUS2 vs HAM1 — DUS2 is the only region for L40S GPUs, HAM1 has A30. If we never self-host inference, region is purely a latency choice (DUS2 closer to most EU customers). -- **Geo-redundant Ceph backups.** Currently planning local block + S3 backup. Could also use SysEleven's geo-redundant S3 (DUS2 ↔ HAM1) for true DR. Cost: €0.05/GiB/mo vs €0.02 single-region. At 500GB backup that's €15/mo extra — buy it. -- **Egress traffic.** Fair Use policy — they reserve the right to bill if we exceed normal patterns. CERTifAI LLM passthrough could be heavy. Ask for clarification on what triggers metered billing. -- **VPN-as-a-Service inclusive.** Confirmed in the pricing doc. Use it for ops access — replaces our need to build IP-allowlists into Orca-Proxy for `erp.` and `git.`. - ---- - -## 9. Recommendation summary - -1. **Sign On-Demand for first 90 days.** Burn ~€1,365/mo while you find the right flavor for each VM. -2. **At Day 90, commit 36M upfront on proven baselines.** Cuts monthly to ~€700. -3. **Keep all 7 VMs separate.** The €100/mo difference vs. consolidation is not worth losing failure isolation. -4. **Skip every Managed Service.** We have Orca. -5. **Add Business Support at €5k MRR, DDoS PLUS before any public marketing push.** -6. **Negotiate startup credits before signing.** Could be worth months of free infra. - ---- - -*End of document. Pricing snapshot 2026-01-20; re-check before signing commitments.* +*End of document. Revised 2026-09-11; re-check prices before each booking.* diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index b3a339f..37172e8 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,748 +1,207 @@ # Implementation Plan — Breakpilot Platform -Companion to `PLATFORM_ARCHITECTURE.md`, `INFRASTRUCTURE.md`, and `PRODUCT_INTEGRATION_SPEC.md`. +Companion to `PLATFORM_ARCHITECTURE.md`, `INFRASTRUCTURE.md`, `PRODUCT_INTEGRATION_SPEC.md` and `ERP/03 Implementation Plan`. -This is the build plan for an AI coding agent (Claude Code, executing PRs against the listed repos). Each milestone is sized to fit in 1–3 PRs, ships independently, and leaves the system in a working state. +**Revised 2026-09-11.** The greenfield plan (M0–M19, SysEleven, three clusters) is replaced by a **migration plan**: the platform is reorganised in place and brought live on **staging** first. Milestones are named `M-MIG-{n}` and keep the old format (Goal, Depends on, Repos, Deliverables, Acceptance, Tests, Gate, Effort). Production is a separate plan written after the staging gate (M-MIG-8) passes. --- ## 0. How to read this document -- Milestones are named `M{phase}.{n}` and grouped by phase. -- Each milestone has: **Goal**, **Depends on**, **Repos/files**, **Deliverables**, **Acceptance**, **Tests**, **Gate**, **Effort** (S = ≤1 day, M = 2–4 days, L = ≥1 week). -- "Gate" is who/what approves the PR for merge. Standard is 1 human reviewer + green CI; some milestones add a manual sign-off. -- Phases are ordered; milestones within a phase can be parallelised where dependencies allow. -- The dependency graph at §11 is the source of truth — when in doubt, read it. +- Each milestone ships independently and leaves the system in a working state; **no milestone starts before the previous one's Acceptance is verified.** +- "Gate": standard = 1 human reviewer + green CI; some milestones add a manual sign-off (anything that touches live systems, DNS, or is irreversible). +- Effort: S ≤ 1 day, M = 2–4 days, L ≥ 1 week. +- §1 conventions apply to every PR in every repo. --- -## 1. Cross-cutting conventions (apply to every PR in every repo) +## 1. Cross-cutting conventions ### 1.1 Repo strategy -Polyrepo under the Gitea org `gitea.meghsakha.com/platform/`. One repo per deployable unit. Existing product repos stay where they are. -**Infrastructure repos.** The IaC is split by Orca cluster — one cluster per plane, one repo per cluster — per the 2026-06-30 cluster-split decision (see [Plane model memory](../../../../home/sharang/.claude/projects/-home-sharang-workspace/memory/project_breakpilot_plane_model.md) and `INFRASTRUCTURE.md §6`). Until the legal entity is established and SysEleven / Hetzner business contracts can be signed, the cluster manifests live as design-only staging directories under `platform/orca-platform/clusters/`. At migration time each `clusters//` subdir becomes its own repo: +Polyrepo under the Gitea org `git.breakpilot.com/platform/`. One repo per deployable unit. -| Repo | Purpose | Created in | +| Repo | Purpose | Status | |---|---|---| -| `platform/orca-platform` | IaC staging — cluster.toml templates, per-cluster service manifests under `clusters/breakpilot-{edge,control,app}/`, overlays, DNS zones, dev-compose | M1.1 | -| `platform/breakpilot-edge` | Identity + Infra cluster (vm-edge): Keycloak, Gitea, Infisical, PowerDNS, Orca-Proxy | M1.2 (split from `orca-platform/clusters/breakpilot-edge/`) | -| `platform/breakpilot-control` | Control cluster (vm-control): portal, tenant-registry, ERPNext, MariaDB, Stalwart, Frappe HD | M1.2 (split from `orca-platform/clusters/breakpilot-control/`) | -| `platform/breakpilot-app` | App cluster (vm-app-prod + vm-app-stage): CERTifAI, compliance-*, Mongo, MinIO, Qdrant, LiteLLM, pg-app | M1.2 (split from `orca-platform/clusters/breakpilot-app/`) | +| `platform/orca-platform` | IaC for the **platform cluster**: `cluster.toml`, `services//service.toml`, `keycloak/` realm exports, `tests/stage/`, `scripts/validate.sh`, `dev/` compose | exists; restructured in M-MIG-3 | +| `sharang/orca-infra` | IaC for the **core cluster** (unchanged owner; company infra) | exists | +| `platform/tenant-registry` | Go: tenants, catalog, entitlements, usage, licences, ERP link, audit, `cmd/erpmock` | exists; extended M-MIG-5/7 | +| `platform/portal` | Next.js 16 customer area + backstage | exists; path tenancy M-MIG-5 | +| `platform/pruefwerk` | Prüfwerk (moved from `sharang/compliance-scanner-agent`) | M-MIG-4 | +| `platform/werkbank` | Werkbank runner (moved from `sharang/werkbank`) | M-MIG-4 | +| `platform/werkpilot` | Werkpilot CLI (moved from `sharang/werkpilot`) | M-MIG-4 | +| `platform/firmwerk` | Firmwerk CLI + cloud-server (moved from `sharang/firmwerk`) | M-MIG-4 | +| `platform/docs` | Mirror of the Collectives specs (Collectives is canonical) | exists | +| `platform/seed-data` | Demo tenant fixtures per product | exists (scaffold) | +| `platform/design-tokens` | CSS variables / fonts, optional for product UIs | exists; no longer required by the contract | -**Product / business repos:** +Stays put: `sharang/certifai` (parked), `sharang/breakpilot-site`, `sharang/breakpilot-notetaker`, `Benjamin_Boenisch/breakpilot-compliance` (dsms; migrates as a deployment in M-MIG-9, repo unchanged). -| Repo | Purpose | Created in | -|---|---|---| -| `platform/tenant-registry` | Go service: tenant glue, audit, API keys | M4.1 | -| `platform/portal` | Next.js 15: customer area + backstage | M5.1 | -| `platform/docs` | Architecture, integration spec, this plan, runbooks | M0.1 | -| `platform/seed-data` | Demo tenant fixtures per product | M13.1 | -| `platform/design-tokens` | CSS variables / fonts (consumed by product web comps) | M5.1 | +### 1.2 Per-repo scaffolding, 1.3 branch + commit conventions, 1.4 PR template, 1.5 CI checks, 1.6 approval gates — unchanged from the 2026-05 plan (trunk-based, Conventional Commits, squash-merge, commitlint + gitleaks + trivy, CODEOWNERS). -**Existing repos that get changes (no new repos):** -- `benjamin_boenisch/certifai` — M6.1 / M6.2 / M6.3 -- `benjamin_boenisch/breakpilot-compliance` — M7.1 / M7.2 +### 1.7 Versioning + release strategy (Orca reality) -### 1.2 Per-repo scaffolding (must exist before any feature work) -Every new repo lands in M0.1 with: - -``` -/README.md what this repo is, how to run, links to architecture -/CONTRIBUTING.md branch model, commit format, how to open a PR -/CODEOWNERS at least one mandatory reviewer (us) -/.gitea/ - /pull_request_template.md - /issue_template/ - bug.md - feature.md -/.gitea/workflows/ - ci.yaml fmt → lint → test → build (per-language details in M0.2) - release.yaml on tag: build image, push to registry -/CHANGELOG.md generated from conventional commits -/LICENSE MIT for portal/docs; Apache-2.0 for libraries -``` - -### 1.3 Branch + commit conventions -- **Trunk-based.** `main` is always deployable. Feature branches: `feat/`, `fix/`, `chore/`. Max lifetime 5 days. -- **Conventional Commits** (`feat:`, `fix:`, `chore:`, `docs:`, `refactor:`, `test:`, `breaking!:`). Enforced by `commitlint` in CI. -- **Squash-merge** to main. PR title becomes the commit message. -- **Direct push to main is blocked** by Gitea branch protection. - -### 1.4 PR template (in every repo) -```markdown -## What -<1-3 bullets> - -## Why - - -## How - - -## Test plan -- [ ] unit -- [ ] integration (if API surface changed) -- [ ] e2e (if user-facing flow changed) -- [ ] manual smoke on stage - -## Risk - - -## Linked milestone -M{phase}.{n} -``` - -### 1.5 CI checks (required before merge, configured in M0.2) -Per language defaults: - -| Stack | Required checks | -|---|---| -| Go | `go fmt -l (no diff)`, `go vet`, `golangci-lint`, `go test ./...`, `go build` | -| Rust | `cargo fmt --check`, `cargo clippy -- -D warnings`, `cargo test -j8` | -| TypeScript | `pnpm lint`, `pnpm typecheck`, `pnpm test`, `pnpm build` | -| Python | `ruff check`, `ruff format --check`, `mypy`, `pytest` | -| All | `commitlint`, image build, container scan (`trivy`), SBOM upload | - -### 1.6 Approval gates -- **Standard gate** (most milestones): 1 human reviewer approves + all CI checks green. Enforced by Gitea branch protection on `main`. -- **CODEOWNERS** auto-requests the right reviewer based on path. -- **Production-promotion gate** (release tags only): manual sign-off by `@sharang` on the release issue + stage soak ≥ 24h. -- **Security gate** (M2.x, M4.x, M14.x): security checklist in PR body completed. - -### 1.7 Versioning + release strategy -- **Semver** per repo. Container images carry **three tags**: `:sha-`, `:v1.4.2`, `:env-stage` / `:env-prod`. -- **Stage** auto-deploys on every merge to `main` (Gitea Actions → Orca apply against `stage` cluster). -- **Production** deploys only when a release tag `vX.Y.Z` is created. Tag creation requires the production-promotion gate. -- **Rollback**: `orca rollout undo ` flips back to previous image tag. RTO target ≤ 5 min for any single service. -- **Database migrations** are forward-only and run as an init container before the service starts. Migrations that delete columns require two releases (1: stop writing, 2: drop). +- Semver per repo. Images: `:sha-` and `:latest` on every `main` build (Harbor `repo.breakpilot.com//`), cosign-signed. +- **Stage** auto-deploys on merge to `main`: CI POSTs a signed webhook to the platform master, Orca re-pulls and restarts `-stage`. +- **Production** (later): tag `vX.Y.Z` → CI retags `:sha-…` as `:prod-` and pushes to a `prod` branch that triggers the `-prod` webhook. Manual sign-off before the tag. +- **Rollback:** `orca rollback -` on the master (previous image). RTO ≤ 5 min. +- **Config changes** (service files): PR → merge → `git pull && orca deploy` on the master (documented in `orca-platform/README.md`). +- Database migrations forward-only, run by an init container / `migrate` binary before the service starts. ### 1.8 Environments -Three Orca clusters, **one per plane** (not one per env). Stage and prod live in the same `breakpilot-app` cluster on different VMs: -| Cluster | VMs | Plane | Envs hosted | -|---|---|---|---| -| `breakpilot-edge` | `vm-edge` (1) | Identity + Infra | shared by stage + prod (single Keycloak realm, `tenant.kind` differentiates) | -| `breakpilot-control` | `vm-control` (1) | Control | shared by stage + prod (single tenant-registry, `tenant.kind` differentiates) | -| `breakpilot-app` | `vm-app-prod`, `vm-app-stage` (2) | App | prod on `vm-app-prod`, stage on `vm-app-stage` | +| Env | Where | Keycloak realm | tenant-registry | ERPNext | Data | Deploy | +|---|---|---|---|---|---|---| +| dev | laptop, `orca-platform/dev/` compose | `breakpilot-dev` (local KC) | local | mock | fixtures | n/a | +| stage | `bp-platform-stage` (cluster master) | `breakpilot-stage` on core KC | `tenant-registry-stage` + `pg-stage` | `erpnext-mock-stage` | synthetic + demo | auto on merge | +| prod | `bp-platform-prod` (agent) | `breakpilot-prod` on core KC | `tenant-registry-prod` + `pg-prod` | live `erp.breakpilot.com` | real | tag + sign-off | -| Env | Where it runs | Data | Auto-deploy? | -|---|---|---|---| -| dev | Developer machine, docker-compose (`platform/orca-platform/dev/`) | fixtures | n/a | -| stage | `vm-app-stage` in `breakpilot-app`; calls prod KC + prod tenant-registry under `tenant.kind = "stage"` | seeded demo + synthetic customers | yes (on merge to main) | -| prod | `vm-app-prod` in `breakpilot-app` + `vm-control` + `vm-edge` | real | tag + gate | +Hosts: `app-stage.breakpilot.com` / `app.breakpilot.com` (portal, tenants by path), `registry-stage` / `registry` (+ `licence`), `pruefwerk-stage` / `pruefwerk`, `firmwerk-stage` / `firmwerk`. Dev: `localhost` ports. -Identity and Control are NOT duplicated for stage. Stage workloads authenticate against the prod Keycloak realm with `tenant.kind = "stage"` and read tenant config from the prod `tenant-registry` (read-only for stage tenants) per `INFRASTRUCTURE.md §5`. - -Domain pattern: -- dev: `*.localhost` (mkcert) -- stage: `*.stage.breakpilot.com` -- prod: `*.breakpilot.com` - -### 1.9 Observability + audit -- **SigNoz** (already running at `signoz.meghsakha.com`) for traces, logs, metrics. Every service ships OTel SDK from day one. -- **Audit events** in the Retraced-shape schema (PRODUCT_INTEGRATION_SPEC.md §8.4) emitted to Tenant Registry `/audit` from every service. Required for every state-changing endpoint. -- **Structured logs** (JSON) only. No `fmt.Println` / `console.log` in committed code; CI rejects. - -### 1.10 Secrets -- Infisical machine identity per service, path `/{env}/{service}/`. -- The only secret allowed in an Orca env file is the Keycloak DB URI (bootstrap exception — see INFRASTRUCTURE.md). -- CI scans for committed secrets via `gitleaks`. Failures block merge. - -### 1.11 Testing policy (mandatory; see also `feedback_testing_everything`) -- **Unit**: every non-trivial function. -- **Integration**: every API endpoint, against real Postgres/MongoDB via `testcontainers`. No mock databases. -- **E2E**: every user-facing flow has at least one Playwright spec running against stage post-deploy. -- **Regression**: when a bug is fixed, a failing test is added FIRST, then the fix. -- **No PR ships without tests.** "Manual tested" is not acceptable except for IaC. - -### 1.12 A/B testing (designed for, adopted later) -Every place where a future flag would gate behaviour MUST flow through a single `featureFlags.evaluate(tenantId, flagKey)` function. Initial implementation returns hard-coded values from `manifest.yaml`. Swap to Unleash/OpenFeature in M19.1 with zero call-site changes. +### 1.9 Observability + audit, 1.10 secrets, 1.11 testing policy, 1.12 feature flags — unchanged, except: secrets are Orca project-scoped (`orca secrets set --project`), Infisical only for the licence signing key and CI credentials. --- -## 2. Phase 0 — Foundations (M0.x – M3.x) +## 2. What already exists (2026-09-11 baseline) -**Goal:** Repos exist, CI works, infra is provisioned and observable, identity + secrets are usable. No customer-visible features yet. +- Core cluster `breakpilot` (orca-infra) with Keycloak (realms `master`, `breakpilot`, `breakpilot-dev`, `certifai`), Gitea 1.27 + Actions, Harbor, LiteLLM, Infisical, SigNoz, ERPNext v15 + CRM + Helpdesk, Nextcloud, chat, status page, landing + `kontakt-relay` (website form → CRM Lead). +- On that cluster, to be moved: portal (`portal-dev` + 4 per-tenant containers), tenant-registry (`tenant-registry-dev`), the Prüfwerk stack (project `certifai`), and the dsms stack (project `breakpilot-dsms`, 12 services on `*.breakpilot.ai`). +- `platform/tenant-registry`: schema (tenants, tenant_projects, tenant_products, tenant_idp_config, api_keys, audit_log), tenant lifecycle + catalog (hard-coded) + API keys + audit + memberships endpoints, Keycloak org provisioning, product provisioning callback. No usage / plans / subscriptions / ERP / licence code. +- `platform/portal`: signup, tenant shell, catalog + trial, products, api-keys, audit (registry-backed); billing/users/settings are fixtures; host-based tenancy. +- Prüfwerk: multi-tenant (Mongo per tenant), Keycloak auth, MCP, docs; JWT validation without iss/aud; no registry integration beyond claims. +- Werkbank: runner, no packaging. Werkpilot: release pipeline, no licensing. Firmwerk: own licensing. +- ERP: nothing implemented (`ERP/03` Phase 0 blocked on Steuerberater; Phase 1 SKUs can start). -### M0.1 — Bootstrap repos and docs -- **Depends on:** nothing -- **Repos:** `platform/docs`, `platform/orca-platform`, `platform/portal`, `platform/tenant-registry`, `platform/design-tokens`, `platform/seed-data` -- **Deliverables:** create the Gitea `platform` org; for each repo add the §1.2 scaffolding; `platform/docs` ingests the existing `PLATFORM_ARCHITECTURE.md`, `INFRASTRUCTURE.md`, `PRODUCT_INTEGRATION_SPEC.md`, this plan. -- **Acceptance:** every repo has a working `README.md`, `CONTRIBUTING.md`, `CODEOWNERS`, PR template. -- **Tests:** n/a -- **Gate:** standard -- **Effort:** S -- **Note:** the three cluster repos (`platform/breakpilot-edge`, `platform/breakpilot-control`, `platform/breakpilot-app`) are NOT created at M0.1 — their service manifests live as design-only directories under `platform/orca-platform/clusters/` until M1.2 splits them. +--- -### M0.2 — CI templates + branch protection -- **Depends on:** M0.1 -- **Repos:** all of the above -- **Deliverables:** `.gitea/workflows/ci.yaml` per repo (matching §1.5 by stack), Gitea branch protection on `main` (require PR, 1 review, status checks green, no direct push), `commitlint`, `gitleaks`, `trivy` configured. -- **Acceptance:** a deliberately-broken PR is rejected by every check; a clean PR is mergeable. -- **Tests:** smoke PR per repo demonstrating green CI. -- **Gate:** standard -- **Effort:** S +## 3. Migration milestones -### M0.3 — Self-hosted DNS + wildcard TLS -- **Depends on:** M1.2 (vm-edge must exist before PowerDNS lands) -- **Repos:** `platform/breakpilot-edge` +### M-MIG-0 — Preparation (no service changes) +- **Goal:** clean repos, recorded live state, cold archives, credentials ready. +- **Depends on:** plan approval. +- **Repos:** `sharang/orca-infra`, `platform/orca-platform`, Gitea admin, Harbor. +- **Deliverables:** commit the master's uncommitted `cluster.toml` on orca-infra and pull everywhere; discard the stale local edits in orca-platform and pull `origin/main`; record `orca status`, `orca webhooks list`, `docker ps` (both nodes), realm export of `breakpilot-dev`, Gitea runner host + labels; archives to `s3://bp-orca-backups/archive-2026-09-platform-stop/` (registry `pg_dumpall`, `certifai-mongo` mongodump, tar of every portal/registry/certifai volume) with one test restore; lower Strato TTLs on the hosts that move; Gitea org secrets in `platform` (`REGISTRY_USER/PASS`, `COSIGN_KEY/PASSWORD`, `ORCA_WEBHOOK_SECRET_STAGE`, `BP_S3_*`) and a bot user `platform-ci` with read access to `platform/*`; Harbor projects `pruefwerk`, `firmwerk`, `platform`. +- **Acceptance:** both IaC repos clean on `origin/main`; archive listed in S3 and the registry dump restores into a scratch Postgres; runner known; org secrets present. +- **Gate:** standard + manual (touches the core master). **Effort:** S–M. + +### M-MIG-1 — Spec revision (this revision) +- **Goal:** Collectives specs describe the target; `platform/docs` mirrors them. +- **Deliverables:** `PLATFORM_ARCHITECTURE.md`, `INFRASTRUCTURE.md`, `IMPLEMENTATION_PLAN.md`, `PRODUCT_INTEGRATION_SPEC.md` (2.0), `COST_PLAN.md`, `CHANGELOG.md`, `Readme.md` template, `ERP/02`, `ERP/03` revised; `BreakPilot Infra` docs updated after M-MIG-2; one mirror commit in `platform/docs`. +- **Acceptance:** grep of the Collectives tree for `*.stage.breakpilot.com`, `web component`, `widget`, `custom domain`, `SysEleven`, `PowerDNS`, `Stalwart`, `Stripe`, `Polar` hits only changelog/history lines; `platform/docs` diff equals Collectives. +- **Gate:** owner review. **Effort:** M. **Status:** in progress 2026-09-11. + +### M-MIG-2 — Stop and archive on the core cluster +- **Goal:** the core cluster runs company infrastructure plus (temporarily) dsms and its two dependencies. +- **Depends on:** M-MIG-0. +- **Repos:** `sharang/orca-infra`. +- **Deliverables:** `orca stop` in order: `breakpilot-portal-{acme,hello,globex,sandbox}`, `breakpilot-portal`, `compliance-dashboard`, `compliance-docs`, `compliance-agent`, `browserless`, `soft-plc`, `plc-sim`, `mailserver`. **Keep** `breakpilot-tenant-registry(+db)`, `compliance-mcp`, `certifai-mongo` (dsms depends on them) → moved into `services/dsms-deps/service.toml`. Remove the stopped blocks, `git pull && orca deploy` on the master, verify prune or `docker rm -f` on both nodes. Clean-up: Gatus portal checks (`services/core/status/config.yaml`), Keycloak admin password rotation (the agent held it), scanner mailserver certbot + ports 25/587/993, orca webhook registrations for portal/registry/scanner. Volumes kept until M-MIG-6 verification. Update `BreakPilot Infra` Readme + Service Catalog. +- **Acceptance:** `orca status` = core + dsms + dsms-deps; `docker ps` on both nodes matches; Gatus green; `https://api-dev.breakpilot.ai/health` and a membership-checked dsms call succeed; next nightly backup succeeds. +- **Gate:** standard + manual sign-off. **Effort:** S–M. + +### M-MIG-3 — Staging VM and the platform cluster +- **Goal:** `breakpilot-platform` cluster exists with one node serving `https://app-stage.breakpilot.com`. +- **Depends on:** M-MIG-0. +- **Repos:** `platform/orca-platform`. +- **Deliverables:** Hetzner VM `bp-platform-stage` (CX43/CPX41 class, Ubuntu 24.04, company project, private network `breakpilot-platform`, Cloud Firewall per `INFRASTRUCTURE.md §3`); docker + `docker login repo.breakpilot.com`; Orca at the core master's version or newer (both ≥ 0.2.13 with ACME fast-retry), installed as master with `orca install-service`; repo restructure: `cluster.toml` (name `breakpilot-platform`, ACME email, S3 backup `bp-platform-backups`, LiteLLM, admin + deployer tokens), `services//service.toml` layout (`platform-stage`, `pruefwerk-stage`, `firmwerk-stage`), every service pinned + memory-limited, `[security_headers] frame_options="DENY"`; delete `clusters/`, `overlays/`, `dns/`, `manifests/`, `scripts/{apply,plan}.sh`, `release.yaml`, the restore-drill stub; adapt `validate.sh` (pins ∈ {`bp-platform-stage`,`bp-platform-prod`}, memory required, secret refs project-scoped); README + `WEBHOOKS.md` describe the deploy flow; Strato A records `app-stage`, `registry-stage`, `pruefwerk-stage`, `firmwerk-stage`; a hello service on `app-stage`. +- **Acceptance:** `orca status` healthy; `curl -I https://app-stage.breakpilot.com` = valid Let's Encrypt cert; backup lands in S3; a signed test webhook redeploys the hello service. +- **Gate:** standard + manual (spend + DNS). **Effort:** M. + +### M-MIG-4 — Move and rename the product repos +- **Goal:** the four product repos live under `platform/` with their final names and build green. +- **Depends on:** M-MIG-0 (bot user, org secrets, Harbor projects). +- **Order (git dependencies):** firmwerk → pruefwerk → werkbank → werkpilot; then registry/portal link fixes. - **Deliverables:** - - **PowerDNS Authoritative** on `vm-edge` (Orca-managed). PostgreSQL backend on same VM (small; ~100 records). - - At the registrar (Benjamin's account): set `ns1.breakpilot.com` and `ns2.breakpilot.com` glue records pointing at vm-edge public IP; delegate the domain to those NS. - - Zone file committed in `orca-platform/dns/breakpilot.com.zone`; Orca syncs into PowerDNS on apply. - - Records: apex `breakpilot.com`, wildcards `*.breakpilot.com` + `*.stage.breakpilot.com`, plus `auth.`, `erp.`, `mcp.`, `cdn.`, `mail.`, `ns1.`, `ns2.`, SPF/DKIM/DMARC TXT records (for M3.2). - - Wildcard TLS via Let's Encrypt **DNS-01 against PowerDNS** (Lego's `--dns=pdns` provider); ACME credentials in Infisical at `/prod/orca-proxy/PDNS_API_KEY`. - - Orca-Proxy reloads the cert via watch on the secret file; renewal cron runs at 02:00 daily. -- **Acceptance:** `dig @1.1.1.1 anything.breakpilot.com` returns an answer; `curl https://anything.breakpilot.com` returns 404 from Orca-Proxy (no TLS error). -- **Tests:** ACME renewal dry-run; PowerDNS zone-diff check in CI; reach via stage and prod subdomains; cert expiry page wired to SigNoz alert. -- **Gate:** standard + manual DNS-delegation check by both founders (irreversible from registrar side without 24–48h propagation) -- **Effort:** M (was S — registrar delegation + PowerDNS adds setup time vs. Cloudflare) + 1. `sharang/firmwerk` → `platform/firmwerk`: `README.md` package path; workflows `.github/` → `.gitea/` (`runs-on: docker`); tag `v0.4.3`. + 2. `sharang/compliance-scanner-agent` → `platform/pruefwerk` (transfer + rename): firmwerk git deps → `platform/firmwerk` tag `v0.4.3`, imports `tramiton_*` → `firmwerk_*`, `cargo update`; CI + 3 Dockerfiles → `platform-ci` token, `full_name: platform/pruefwerk`, images → `repo.breakpilot.com/pruefwerk/*`; fix `fixtures/demo-targets/targets.json`, vitepress config, demo-targets docs, `.cargo/audit.toml`, `.env.example` + `config.rs` openplc default, `dedup.rs`, `agent_client.rs`; delete the mailserver compose; delete stale branches; remove the retired repo webhook. + 3. `sharang/werkbank` → `platform/werkbank`: Cargo deps → `platform/pruefwerk` at a **tag**; `DESIGN.md`; add `Dockerfile` + `.gitea/workflows/ci.yml` → `repo.breakpilot.com/pruefwerk/werkbank`. + 4. `sharang/werkpilot` → `platform/werkpilot`: `release.yml` fallback; `custom_providers/litellm.json` → `llm.breakpilot.com`. + 5. `platform/tenant-registry` `go.mod` module → `git.breakpilot.com/platform/tenant-registry` (+ imports); README/CONTRIBUTING links in registry, portal, seed-data, docs. + 6. `sharang/certifai`: delete its two retired webhooks only. +- **Acceptance:** CI green on `main` in all four repos after the move; `cargo build` of werkbank and pruefwerk against the new git deps; `grep -r "sharang/\|meghsakha"` in the four repos returns only LICENSE/history; images visible under Harbor `pruefwerk/`. +- **Gate:** standard. **Effort:** M. -### M1.1 — `orca-platform` repo (IaC staging) -- **Depends on:** M0.1, M0.2 -- **Repos:** `platform/orca-platform` -- **Deliverables:** per-cluster manifest layout under `clusters/breakpilot-{edge,control,app}/services/`; per-env overlays (`overlays/dev`, `overlays/stage`, `overlays/prod`); `cluster.toml.tmpl` template parameterized by cluster; a `Makefile` with `make plan` / `make apply` per env; `scripts/validate.sh` enforces a per-cluster `placement.node` whitelist (`breakpilot-edge → vm-edge`, `breakpilot-control → vm-control`, `breakpilot-app → {vm-app-prod, vm-app-stage}`). -- **Acceptance:** `make plan ENV=stage` and `make plan ENV=prod` both resolve cleanly; `make validate` passes the per-cluster node check on all manifests. -- **Tests:** `make validate` runs in CI; PRs that break a manifest or cross-place a service into the wrong cluster's node fail. -- **Gate:** standard -- **Effort:** M -- **Status (2026-06-30):** layout landed; cluster split refactor merged via PR #6 (`6be727d4`). Manifests under `clusters/breakpilot-*/services/` are stubs awaiting per-milestone fill-in. `make apply` is a no-op until M1.2. +### M-MIG-5 — Platform services on staging +- **Goal:** signup → tenant → login → catalog works at `app-stage.breakpilot.com`. +- **Depends on:** M-MIG-3, M-MIG-4 (registry module path). +- **Repos:** `platform/orca-platform`, `platform/tenant-registry`, `platform/portal`, Keycloak (core). +- **Deliverables:** realm `breakpilot-stage` from an adapted `dev/keycloak/realm-export.json` (orgs on; clients per `PLATFORM_ARCHITECTURE.md §4`; scope `tenant-context` = `tenant_id, tenant_slug, org_roles, tenant_status`; device flow; roles; theme) exported to `orca-platform/keycloak/breakpilot-stage.json`. Registry: migration `0002` (`products` table replacing `catalog.go`, seeded `pruefwerk` (+addon `werkbank`), `werkpilot`, `firmwerk`; `certifai` and `compliance` keys removed/disabled), `GET /v1/tenants`, `POST /v1/internal/entitlements/check`, per-client authorization map, invite `client_id`/`redirect_uri` from env, provisioning fan-out with outbox retry, `SyncClaims(tenant_status)`. Portal: path tenancy in `middleware.ts`/`host.ts` (`PORTAL_APEX_HOSTS`), fixtures only under `BP_DEV_FIXTURE`, product tiles use catalog `launch_url`, `AUTH_URL`. Deploy project `platform-stage` (`pg-stage`, `tenant-registry-stage`, `portal-stage`) with CI webhooks. +- **Acceptance:** `/start` creates a tenant → KC org + invite mail (to a `@breakpilot.com` address); login at `app-stage.breakpilot.com//dashboard`; catalog shows three products; API key create/verify; audit entries; portal Playwright suite passes against staging. +- **Gate:** standard + security checklist. **Effort:** L. -### M1.2 — Provision VMs + split cluster repos (locked topology) -- **Depends on:** M1.1 (manifest layout exists); **legal entity established** (gating SysEleven / Hetzner business contracts; no commercial activity before this). -- **Repos:** `platform/orca-platform` (source of split), `platform/breakpilot-edge`, `platform/breakpilot-control`, `platform/breakpilot-app` (created in this milestone). -- **Deliverables:** **4 VMs across 3 clusters**, one cluster per plane (per the 2026-06-30 cluster-split decision): +### M-MIG-6 — Products on staging +- **Goal:** Prüfwerk (+Werkbank), Firmwerk cloud and the two CLIs run against staging with multi-tenancy. +- **Depends on:** M-MIG-5. +- **Repos:** `platform/pruefwerk`, `platform/werkbank`, `platform/firmwerk`, `platform/werkpilot`, `platform/orca-platform`. +- **Deliverables:** Prüfwerk: iss+aud validation, CORS allowlist, scheduler via `GET /v1/tenants`, entitlement check on tenant-context build, §4.1 endpoints, usage events; services `pruefwerk-{mongo,agent,dashboard,mcp,docs}-stage`, `browserless-stage`, `soft-plc-stage`, `plc-sim-stage` on `pruefwerk-stage.breakpilot.com` (+ `/mcp`, `/docs`); no mailserver on stage. Werkbank: `werkbank-runner-stage` with a registry API key (`werkbank:runner`). Firmwerk: `firmwerk-cloud-stage` + `firmwerk-mongo-stage` on `firmwerk-stage.breakpilot.com`; CLI `v0.4.3` under `platform` packages. Werkpilot: release under `platform/werkpilot`. +- **Acceptance:** tenants `acme` and `globex` via portal; Prüfwerk login per tenant; scan of `cra-vuln-demo`; tenant B cannot read A's scan (404/403); MCP token bound to tenant; runner completes a `dast` job; `firmwerk` device login against `firmwerk-stage`; Gatus checks for the stage hosts; old volumes on core deleted afterwards. +- **Gate:** standard + security checklist. **Effort:** L. - | Cluster | VM | Flavor | Plane | Services | - |---|---|---|---|---| - | `breakpilot-edge` | `vm-edge` | m2.small, public IP | Identity + Infra | orca-proxy, PowerDNS, Keycloak (repurposed from CERTifAI), pg-keycloak, Infisical, pg-infisical, redis-infisical, Gitea | - | `breakpilot-control` | `vm-control` | m2.medium | Control | portal, tenant-registry, ERPNext, Frappe HD, MariaDB, redis-erpnext, Stalwart | - | `breakpilot-app` | `vm-app-prod` | m2.medium | App (prod) | CERTifAI, compliance ×3, MongoDB, LiteLLM, pg-app, Qdrant, MinIO | - | `breakpilot-app` | `vm-app-stage` | m2.small, public IP | App (stage) | slim parallel set for staging; calls prod KC + prod tenant-registry under `tenant.kind = "stage"` | +### M-MIG-7 — Entitlements, licences and the ERP link +- **Goal:** the always-on ERP link and CLI licensing work end-to-end against the ERPNext mock. +- **Depends on:** M-MIG-6. (= `ERP/03` Phase 5.) +- **Repos:** `platform/tenant-registry`, `platform/portal`, `platform/pruefwerk`, `platform/firmwerk`, `platform/werkpilot`, `platform/orca-platform`. +- **Deliverables:** `cmd/erpmock` (Frappe REST surface for Customer / Subscription / Usage Record / CRM Lead / Sales Invoice, seeded SKU items, request log, `/_mock/fire/*` webhook triggers) deployed as `erpnext-mock-stage`. Registry migration `0003`: `plans`, `subscriptions`, `usage_events`, `erp_outbox`, `licences`; ladder statuses `warning|restricted|halted` on `tenants.status`; ERPNext client + outbox worker; HMAC webhook receiver (idempotent) + 15-min reconcile; licence endpoints (Ed25519 key in Infisical `platform/stage/licence-signing`, `/.well-known/licence-keys.json`, heartbeat, revoke); `SyncClaims` on every ladder change. Products: Prüfwerk usage events; Firmwerk cloud-server replaces its own model with registry licence verification + `entitlements/check`; `firmwerk login` / `werkpilot login` device flow → licence, offline verify, heartbeat, ladder; Werkpilot LiteLLM virtual key at licence issue. Portal: billing page from registry (subscriptions, invoices via ERP), ladder banner, catalog request → CRM Lead through the outbox. +- **Acceptance:** see M-MIG-8. +- **Gate:** standard + security checklist. **Effort:** L (2–3 weeks). - - **Split the cluster repos:** for each cluster, lift `platform/orca-platform/clusters/breakpilot-/` into its own Gitea repo `platform/breakpilot-` with the §1.2 scaffolding + its own `cluster.toml` + its own `services/` tree. Empty out (or stub) the original `clusters/breakpilot-/` in `orca-platform` and leave a pointer README. - - **Repurpose the existing Keycloak.** The CERTifAI Keycloak realm export + user database moves to `vm-edge` rather than standing up a fresh instance — a hostname swap and realm export/import, not a re-bootstrap. - - **Private network** 10.0.0.0/16 between all four VMs. - - **Public ingress** per Orca's per-node-ingress model: every VM binds 80/443 and runs its own Let's Encrypt ACME; A records for a service point at the agent IP that runs the container, not at a master. - - **SSH disabled**; only `orca exec` for shell access. -- **Acceptance:** - - Every VM is reachable from its cluster's Orca master; private-network connectivity verified. - - Resource limits per service set in manifest per `INFRASTRUCTURE.md §6` co-tenant notes. - - `make validate` (in `orca-platform`) and the new per-cluster repo CIs all pass. - - Cold-start sequence from `INFRASTRUCTURE.md §10 Scenario F` runs successfully on `vm-app-stage`. -- **Tests:** cold-start drill on `vm-app-stage`; cross-cluster reachability matrix; KC realm-import smoke (stage tenant logs in). -- **Gate:** standard + manual sign-off (touches infra spend and 36M commitment decision) + legal-entity confirmation before any contract signing. -- **Effort:** L (was M — adds the 3-repo split + KC realm migration on top of provisioning). -- **Cost impact:** see COST_PLAN.md §3. Initial run: ~€552/mo On-Demand, dropping to ~€310/mo after 36M-upfront commit in Month 4. `vm-app-stage` is the cheapest VM in the topology so adding it doesn't materially shift the bill. +### M-MIG-8 — End-to-end tests on staging (gate for the production plan) +- **Depends on:** M-MIG-7. +- **Deliverables:** Playwright (portal) + `hurl`/`curl` scripts in `orca-platform/tests/stage/` covering: + 1. signup → trial → KC org → mock Customer with `tenant_id` → `erp_customer_id` set; + 2. `fire/sales-order-submit` (`PLT-CORE-CLD-STD` + `CRA-CSA-CLD-STD`) → active → Prüfwerk allowed; a tenant without entitlement → 403; + 3. scan → usage event → outbox → usage record in the mock ≤ 60 s; kill the worker, scan, restart → exactly one record; + 4. `fire/invoice-overdue` → warning banner; past grace → restricted → Prüfwerk writes 402, reads OK; `fire/payment-entry` → active; + 5. Firmwerk licence: login → offline verify with network off → revoke → degrade → hard-stop (clock-skewed); + 6. Werkpilot login, licence check, seat event; + 7. isolation: cross-tenant API key / MCP token → 403; separate Mongo databases; + 8. ops: restore drill of `pg-stage`; redeploy via CI webhook; Gatus green 24 h. +- **Acceptance:** all eight pass on two consecutive days. +- **Gate:** owner sign-off → production plan starts. **Effort:** M. -**Pre-M1.2 reality (today, single-VM era):** until this milestone lands, everything runs on the existing single VM (`46.225.100.82`) via `~/workspace/orca-infra`. M7.x work (tenant-registry-aware compliance-agent, per-tenant MCP) and other product work is meaningful on the single-VM setup and ports cleanly into `breakpilot-app/services/prod/` at migration time. - -### M1.3 — Backups, monitoring, on-call -- **Depends on:** M1.2 -- **Repos:** `platform/breakpilot-edge`, `platform/breakpilot-control`, `platform/breakpilot-app` (each cluster owns its own `[backup]` block + restore script per `INFRASTRUCTURE.md §6`) -- **Deliverables:** backup cron per VM per `INFRASTRUCTURE.md §3` (Postgres pg_dump on `pg-keycloak` / `pg-app` / `mariadb`, MinIO bucket replication); SigNoz OTel collector running on every VM; alert routing to `oncall@breakpilot.com`; restore runbook in `platform/docs/runbooks/restore.md`. Each cluster repo has its own S3 bucket per `INFRASTRUCTURE.md §6` so a runaway backup on `breakpilot-app` cannot fill the bucket `breakpilot-edge` writes to. -- **Acceptance:** restore drill on `vm-app-stage` succeeds (script in `breakpilot-app/scripts/restore-drill.sh`); SigNoz shows traces from a synthetic request through `vm-app-stage` → `vm-control` → `vm-edge`. -- **Tests:** disaster-recovery exercise per failure scenario in `INFRASTRUCTURE.md §10` — at least Scenarios A, B, F validated on stage. -- **Gate:** standard + manual sign-off -- **Effort:** L - -### M2.1 — Keycloak deployment (repurpose from CERTifAI) -- **Depends on:** M1.2, M1.3 -- **Repos:** `platform/breakpilot-edge` -- **Deliverables:** Keycloak 26 on **`vm-edge`** (co-tenant with the rest of infra; JVM heap pinned `-Xmx1500m` so it cannot starve PowerDNS / Infisical, per `INFRASTRUCTURE.md §6`). Postgres backing store (`pg-keycloak`) also on `vm-edge`. Exposed at `auth.breakpilot.com`; stage tenants authenticate against the same instance under `tenant.kind = "stage"` (no separate stage realm). **The CERTifAI Keycloak instance is repurposed here** — its realm export + user database moves to `vm-edge` rather than standing up a fresh instance. Realm import file in `breakpilot-edge/services/keycloak/realm-export.json` (committed, source-of-truth). -- **Acceptance:** master admin login works; realm `breakpilot-prod` exists; the realm carries the migrated CERTifAI users; a stage tenant test login succeeds with `tenant.kind = "stage"` in the JWT. -- **Tests:** automated realm-state diff in CI (`kcadm` against checked-in export); side-by-side comparison of pre-migration and post-migration realm exports flags any silent drift. -- **Gate:** standard + security checklist + manual sign-off on the realm-import diff (irreversible without restoring from KC backup). -- **Effort:** M -- **Note:** the escape hatch — if the JVM/PowerDNS fight shows up in alerts after launch — is to flip Keycloak's `placement.node` to a new `vm-edge-identity` VM inside the same `breakpilot-edge` cluster. No schema migration, just a container move. - -### M2.2 — Realm configuration: roles + protocol mappers + Organizations -- **Depends on:** M2.1 -- **Repos:** `platform/breakpilot-edge` (realm config) -- **Deliverables:** Organizations feature enabled; realm roles `BREAKPILOT_ADMIN`, `SUPPORT_ENGINEER`, `SALES_REP`; org roles `IT_ADMIN`, `CXO`, `FINANCE`, `LEGAL`, `USER`; protocol mapper that calls Tenant Registry at token issuance for `products`, `plan`, `tenant_status`, `tenant_kind` claims; SALES_REP guardrail policy (token only issuable with `org_id = demo`). -- **Acceptance:** a test user gets the expected JWT claims; a SALES_REP user cannot get a JWT for a non-demo org (verified by integration test). -- **Tests:** Keycloak integration suite in `platform/tenant-registry/test/keycloak_test.go`. -- **Gate:** standard + security checklist -- **Effort:** M - -### M3.1 — Infisical -- **Depends on:** M1.2 -- **Repos:** `platform/breakpilot-edge` -- **Deliverables:** Infisical on **`vm-edge`** (co-tenant with Keycloak, PowerDNS, Gitea), machine identity per service, secret paths laid out per `PRODUCT_INTEGRATION_SPEC.md §9.4`. -- **Acceptance:** a stub service can read its secrets at startup; rotating a secret in Infisical UI is picked up on next pod start. -- **Tests:** smoke test container reads secrets. -- **Gate:** standard + security checklist -- **Effort:** S -- **Bootstrap exception (per `INFRASTRUCTURE.md §8 rule 3`):** Keycloak's `KC_DB_URL` lives in Orca env (not Infisical) because both run on `vm-edge` and we'd otherwise have a circular bootstrap dependency. - -### M3.2 — Stalwart transactional email -- **Depends on:** M0.3 (needs DNS records under our control), M3.1 -- **Repos:** `platform/breakpilot-control` -- **Deliverables:** - - **Stalwart** on `vm-control` (Orca-managed); reachable at `mail.breakpilot.com`. - - DNS records added to the zone in M0.3: `mail` A record, MX → mail, SPF (`v=spf1 mx -all`), DKIM (Stalwart-generated public key), DMARC (`p=quarantine; rua=mailto:dmarc@breakpilot.com`), reverse DNS (PTR) configured at the cloud provider for the vm-control public IP — coordinate with vm-edge since outbound mail must egress from a host with a clean PTR. - - SMTP submission service account per platform sender: `noreply@`, `oncall@`, `support@`, `billing@`, `dmarc@`. - - Outbound queue and bounce handler; failed deliveries surface as audit events. - - Webhook receiver at `/inbound/postmaster` for bounce/complaint feedback loops (Gmail FBL, MS SNDS). - - **IP warming plan**: write a `platform/docs/runbooks/email-warming.md` documenting the 4–8 week ramp from low daily volumes; first 2 weeks of trial nudges (M12.2) explicitly throttled. -- **Acceptance:** test email from `noreply@breakpilot.com` to `parnerkarsharang@gmail.com` lands in inbox (not spam) on day 1; SPF/DKIM/DMARC all "pass" in Gmail's "show original" view; mail-tester.com score ≥ 9/10. -- **Tests:** automated daily mail-tester check (failure pages on-call); bounce-handling integration test. -- **Gate:** standard + security checklist + manual deliverability sign-off (DKIM keys are load-bearing) -- **Effort:** L (deliverability tuning is the long tail) - -**Phase 0 exit criteria:** -- `vm-app-stage` boots cold from cron-driven nightly stop/start using only `INFRASTRUCTURE.md §5` ordering; `breakpilot-edge` and `breakpilot-control` clusters remain warm throughout (no nightly cycling for identity / control). -- A synthetic HTTPS request to `https://hello.stage.breakpilot.com` reaches a stub container on `vm-app-stage`. -- Restore drill on `vm-app-prod` Postgres (`pg-app`) and `vm-control` Postgres (`pg-keycloak`, `pg-mariadb`) both succeed end-to-end. -- All three cluster repos (`platform/breakpilot-edge`, `platform/breakpilot-control`, `platform/breakpilot-app`) have green CI on main and a successful `make validate`. +### M-MIG-9 — breakpilot-dsms migration (last) +- **Depends on:** M-MIG-8; decision on pitch-deck's home (shares `breakpilot-db`). +- **Deliverables:** pin dsms images to digests; `pg_dump` `compliance_db` + `breakpilot_db`; tar `/data/ipfs`, Qdrant, dataroom, Ollama volumes; copy to the platform node; project `dsms` (12 services, pinned, no public Postgres port, Qdrant on the project network) with `AUTH_TENANT_REGISTRY_URL` → `tenant-registry-stage`, `SCANNER_MCP_URL` → `pruefwerk-stage…/mcp`, realm `breakpilot-stage` clients `compliance-client`/`compliance-svc`, `BP_S3_*`; Strato repoint of `admin-dev/developers-dev/api-dev/sdk-dev/qdrant-dev.breakpilot.ai` and `pitch.breakpilot.com`; then stop + remove `breakpilot-dsms` and `dsms-deps` on core, close port 54321, prune `breakpilot-dev` clients, drop `auth-dev.meghsakha.com`, retire `mail.scanner.meghsakha.com`, delete Harbor `certifai/*`; update `BreakPilot Infra` docs. +- **Acceptance:** dsms health on the new IPs; a known CID resolves; Prüfwerk control mapping works against the new `BREAKPILOT_BASE_URL`; core `orca status` = core only. +- **Gate:** standard + manual (data move, DNS). **Effort:** M–L. --- -## 3. Phase 1 — Control plane core (M4.x – M5.x) +## 4. Production (separate plan, after M-MIG-8) -**Goal:** Tenant Registry stores tenants; the portal authenticates a user and resolves their tenant. No products surfaced yet. - -### M4.1 — Tenant Registry: schema + migrations -- **Depends on:** M1.2, M2.2 -- **Repos:** `platform/tenant-registry` -- **Deliverables:** Go service scaffold; `golang-migrate` migrations for `tenants`, `tenant_projects`, `tenant_products`, `tenant_idp_config`, `api_keys`, `audit_log` per `PLATFORM_ARCHITECTURE.md §5c`; the `tenant.status` enum + `tenant.kind` column from the lifecycle spec. -- **Acceptance:** `make migrate-up` on a fresh Postgres produces the documented schema. -- **Tests:** migration up/down round-trip via `testcontainers-go`. -- **Gate:** standard -- **Effort:** M - -### M4.2 — Tenant Registry: REST API -- **Depends on:** M4.1 -- **Repos:** `platform/tenant-registry` -- **Deliverables:** OpenAPI 3.1 spec at `/openapi.yaml`; endpoints `POST /tenants`, `GET /tenants/:id`, `POST /tenants/:id/activate`, `POST /tenants/:id/cancel`, `GET /catalog`, `POST /catalog/request`, `POST /catalog/trial-request`, `POST /api-keys`, `POST /internal/api-keys/verify`, `POST /audit`, `GET /audit`. -- **Acceptance:** every endpoint passes the OpenAPI contract test; returns documented errors for invalid input. -- **Tests:** integration tests against real Postgres for every endpoint. -- **Gate:** standard -- **Effort:** L - -### M4.3 — Tenant Registry: Keycloak adapter -- **Depends on:** M4.2, M2.2 -- **Repos:** `platform/tenant-registry` -- **Deliverables:** package `internal/keycloak` that creates orgs, invites IT_ADMIN users, sets realm roles, and serves the protocol-mapper claims endpoint (the URL Keycloak hits during token issuance from M2.2). -- **Acceptance:** creating a tenant via `POST /tenants` provisions a Keycloak org and one IT_ADMIN user; user receives invite email. -- **Tests:** integration test against the stage Keycloak. -- **Gate:** standard -- **Effort:** M - -### M5.1 — Portal scaffold: subdomain routing + OIDC login -- **Depends on:** M2.2, M4.3, M0.3 -- **Repos:** `platform/portal`, `platform/design-tokens` -- **Deliverables:** Next.js 15 app on `vm-control`; middleware reads `Host` → extracts slug → calls Tenant Registry `GET /tenants?slug=` → injects tenant context; Keycloak OIDC login; logout; `design-tokens` package consumed by portal. -- **Acceptance:** visiting `https://acme.stage.breakpilot.com` redirects to Keycloak; after login, user lands on `/acme/dashboard` (empty page) with valid session. -- **Tests:** Playwright e2e: login + logout for an existing test tenant. -- **Gate:** standard -- **Effort:** M - -### M5.2 — Portal: dashboard + backstage shells -- **Depends on:** M5.1 -- **Repos:** `platform/portal` -- **Deliverables:** customer dashboard route `/[slug]/dashboard` (renders product tiles from JWT `products` claim — empty initially), backstage routes per `PLATFORM_ARCHITECTURE.md §5a` skeleton, RBAC enforcement (§5a "Operating principles" — hide what user can't access), session refresh. -- **Acceptance:** user with `org_roles=[USER]` cannot see settings or billing links; backstage routes return 403 for non-`BREAKPILOT_ADMIN` users. -- **Tests:** Playwright spec per role × route matrix. -- **Gate:** standard -- **Effort:** M - -### M5.3 — Playwright e2e harness -- **Depends on:** M5.2 -- **Repos:** `platform/portal` -- **Deliverables:** Playwright config that runs against `stage.breakpilot.com` post-deploy; CI job `e2e-stage` triggered after stage deploy; failure pages on-call. -- **Acceptance:** breaking change to login is caught in CI within 10 min of merge. -- **Tests:** the suite itself. -- **Gate:** standard -- **Effort:** S - -**Phase 1 exit criteria:** -- A tenant created via `POST /tenants` results in a working login flow at `.stage.breakpilot.com`. -- All Phase 1 routes have a passing Playwright spec running on every stage deploy. +Book `bp-platform-prod`, join as agent over the private network, realm `breakpilot-prod`, projects `*-prod`, A records `app`, `registry`, `licence`, `pruefwerk`, `firmwerk`; wire the live ERPNext (`tenant_id` custom field, API user `platform-registry`, Frappe Webhooks with HMAC — `ERP/03` Phase 5 *live* steps); `prod` branch webhooks; deployer-token handling per RISK-2; demo tenant on prod; go-live checklist from `PRODUCT_INTEGRATION_SPEC.md §13` per product. --- -## 4. Phase 2 — Existing product uplift (M6.x – M7.x, parallel) +## 5. Cross-cutting work (ongoing) -**Goal:** CERTifAI and breakpilot-compliance both honour the JWT contract and surface a real product tile in the portal. - -### M6.1 — CERTifAI: org_id scoping at DB layer -- **Depends on:** M2.2 -- **Repos:** `benjamin_boenisch/certifai` -- **Deliverables:** MongoDB middleware that requires `org_id` on every query; backfill script for existing collections; per-tenant collection-level role checks (`IT_ADMIN` → Admin, etc.). -- **Acceptance:** integration test attempting a cross-tenant read returns `403`; existing single-tenant flows still work for tenant `default`. -- **Tests:** unit + integration; regression tests for every existing controller. -- **Gate:** standard + security checklist -- **Effort:** L (4–6 weeks per prior gap analysis) - -### M6.2 — CERTifAI: JWT validation + role mapping -- **Depends on:** M6.1 -- **Repos:** `benjamin_boenisch/certifai` -- **Deliverables:** Keycloak JWKS validation middleware; role mapping per `PLATFORM_ARCHITECTURE.md §6`; tenant_status middleware (returns 402 on writes when `frozen`, 410 when `archived`, allows demo with no metering). -- **Acceptance:** all four `tenant.status` states behave per spec; tested against a stage Keycloak. -- **Tests:** integration tests per status value. -- **Gate:** standard + security checklist -- **Effort:** M - -### M6.3 — CERTifAI: manifest + integration assets -- **Depends on:** M6.2 -- **Repos:** `benjamin_boenisch/certifai` -- **Deliverables:** `product.manifest.yaml` per `PRODUCT_INTEGRATION_SPEC.md §10` published to `cdn.breakpilot.com`; OpenAPI 3.1 spec; `/v1/health`, `/v1/usage`, `/v1/tenants/:id/export`, `DELETE /v1/tenants/:id/data`, `POST /v1/tenants/demo/reset`; web component `certifai-dashboard` per §5.A. -- **Acceptance:** CERTifAI appears in the portal catalog; subscribed tenants can open it from the dashboard. -- **Tests:** contract test that manifest validates against schema; web component renders inside portal shadow-DOM host. -- **Gate:** standard -- **Effort:** L - -### M7.1 — Compliance: JWT validation upgrade -- **Depends on:** M2.2 -- **Repos:** `benjamin_boenisch/breakpilot-compliance` -- **Deliverables:** Next.js proxy validates JWT against Keycloak JWKS (replacing today's `X-Tenant-ID` trust); tenant_status middleware as in M6.2. -- **Acceptance:** spoofing `X-Tenant-ID` without a JWT returns 401; valid JWT for tenant A cannot read tenant B data. -- **Tests:** integration tests for both auth and status states. -- **Gate:** standard + security checklist -- **Effort:** M (3–5 weeks per prior gap analysis) - -### M7.2 — Compliance: manifest + integration assets -- **Depends on:** M7.1 -- **Repos:** `benjamin_boenisch/breakpilot-compliance` -- **Deliverables:** same endpoint set as M6.3; web component (existing React → `@r2wc/react-to-web-component` per §5.A); manifest with `supports_projects: true` (already implemented). -- **Acceptance:** compliance appears in portal catalog; opens from dashboard; project switching works inside the product. -- **Tests:** as M6.3. -- **Gate:** standard -- **Effort:** M - -**Phase 2 exit criteria:** -- A real tenant on stage can subscribe to both products and use them through the portal. -- Cross-product audit at `/[slug]/audit` shows events from both products in the Retraced schema. +Regression tests first; security review per milestone (`cargo audit`, `npm audit`, `semgrep`); DR drill at M-MIG-8; doc currency (PR template tick); OSS swap-in readiness per `PRODUCT_INTEGRATION_SPEC.md §15`. --- -## 5. Phase 3 — Business operations (M8.x – M9.x) - -**Goal:** ERPNext and Frappe HD run, Sales Order → tenant activate works, tickets escalate to Gitea. - -### M8.1 — ERPNext deployment -- **Depends on:** M1.2, M2.1 -- **Repos:** `platform/breakpilot-control` -- **Deliverables:** Frappe + ERPNext on `vm-control` (separate Postgres database from tenant_registry — see `INFRASTRUCTURE.md` RISK-1); reached at `erp.breakpilot.com`; Keycloak OIDC; IP-restricted at Orca-Proxy. -- **Acceptance:** us login works; a Customer record can be created manually. -- **Tests:** smoke test for OIDC; backup of Frappe filestore validated. -- **Gate:** standard + manual sign-off (touches `vm-control` resources) -- **Effort:** M - -### M8.2 — ERPNext customization -- **Depends on:** M8.1 -- **Repos:** `platform/breakpilot-control` (`erpnext-app/` subdir under the cluster repo) -- **Deliverables:** custom Frappe app with: `tenant_id` field on `Customer`; `sales_owner` field on `Lead`; server scripts for the Sales Order → Tenant Registry webhook; `Cancel` workflow that calls Tenant Registry `/cancel`. -- **Acceptance:** submitting a Sales Order in ERPNext triggers a tenant activation in stage Tenant Registry. -- **Tests:** server-script unit tests (Frappe test harness); integration test exercises the full webhook. -- **Gate:** standard -- **Effort:** M - -### M8.3 — Self-serve billing (Polar.sh) -- **Depends on:** M8.1, M5.2 -- **Repos:** `platform/portal`, `platform/tenant-registry` -- **Deliverables:** - - Polar.sh organization + products configured for Starter / Professional / per-seat tiers. - - Polar Checkout embedded in portal `/[slug]/billing/upgrade`. - - Webhook listener at `tenant-registry /polar/webhook` (HMAC-verified) handles `subscription.created`, `subscription.updated`, `subscription.canceled`, `order.paid` → flips `tenant.status`, mirrors the customer + invoice into ERPNext via REST. - - Polar acts as Merchant of Record — they handle EU VAT MOSS, no per-country tax registration needed for our side. - - Portal billing page reads invoices from ERPNext (single source of truth for accounting) but links out to Polar's customer portal for payment-method management. -- **Acceptance:** signing up self-serve creates a tenant, a Polar subscription, an ERPNext Customer + Invoice, and a usable login; VAT line item appears correctly on the EU customer's invoice. -- **Tests:** integration test against Polar sandbox; webhook replay test; tax calculation correct for at least DE, FR, NL, US. -- **Gate:** standard + security checklist -- **Effort:** L - -> **Why Polar.sh over Stripe / Lemon Squeezy:** OSS-aligned, Merchant of Record (handles EU VAT MOSS automatically), developer-first, 4% + Stripe fees vs. Lemon's 5%. Stripe direct would require us to register for VAT in 27 countries — not viable for a 2-person team. See [[self-hosted-oss-first]]. - -### M9.1 — Frappe Helpdesk -- **Depends on:** M8.1 -- **Repos:** `platform/breakpilot-control` -- **Deliverables:** Frappe HD on the same Frappe bench; customer portal embedded at `/[slug]/support/`. -- **Acceptance:** a customer user can submit a ticket; we receive it. -- **Tests:** Playwright spec for ticket submission. -- **Gate:** standard -- **Effort:** S - -### M9.2 — HD → Gitea escalation -- **Depends on:** M9.1 -- **Repos:** `platform/breakpilot-control` (`erpnext-app/` subdir) -- **Deliverables:** server script that on a `Ticket: Escalate to Engineering` action creates a Gitea issue in the matching repo via Gitea REST API; reverse webhook from Gitea on issue close marks ticket resolved. -- **Acceptance:** the round-trip works for a test ticket on stage. -- **Tests:** integration test against stage Gitea. -- **Gate:** standard -- **Effort:** S - -**Phase 3 exit criteria:** -- ERPNext is the source of truth for billing/CRM/HR. -- The full Lead → Quote → Sales Order → Tenant chain works on stage. - ---- - -## 6. Phase 4 — Customer UX & lifecycle (M10.x – M14.x) - -**Goal:** Every customer-facing flow from `PLATFORM_ARCHITECTURE.md` works end-to-end on stage. - -### M10.1 — Customer area: full surfaces -- **Depends on:** M5.2, M6.3, M7.2 -- **Repos:** `platform/portal` -- **Deliverables:** real implementations of `/[slug]/dashboard`, `/[slug]/products/*`, `/[slug]/projects`, `/[slug]/settings/{identity,users,api-keys,integrations}`, `/[slug]/billing`, `/[slug]/audit`, `/[slug]/support`. -- **Acceptance:** every route is implemented, RBAC-gated, with empty/loading/error states. -- **Tests:** one Playwright spec per route × primary role. -- **Gate:** standard -- **Effort:** L - -### M10.2 — Cross-product audit view -- **Depends on:** M10.1, M4.2 -- **Repos:** `platform/portal` -- **Deliverables:** audit page filters by product/actor/action/time; CSV + PDF export; events rendered from the Retraced-shape schema. -- **Acceptance:** a DPO-style query ("show me everything user X did across all products last month") returns in <2s for a tenant with 100k events. -- **Tests:** load test with synthetic events. -- **Gate:** standard + security checklist -- **Effort:** M - -### M11.1 — Catalog flow (P13) -- **Depends on:** M4.2, M10.1 -- **Repos:** `platform/portal`, `platform/tenant-registry` -- **Deliverables:** `/[slug]/catalog` UI per `PLATFORM_ARCHITECTURE.md` P13; "Request" button creates ERPNext CRM Lead. -- **Acceptance:** customer requests a non-subscribed product; sales sees a Lead in ERPNext with the right `sales_owner`. -- **Tests:** Playwright e2e covering the full P13 sequence. -- **Gate:** standard -- **Effort:** M - -### M12.1 — Self-serve trial (P15) -- **Depends on:** M8.3, M11.1 -- **Repos:** `platform/portal`, `platform/tenant-registry` -- **Deliverables:** public `/start` form; trial tenant provisioning (status=trial, trial_ends_at); banner; trial_quota enforcement (read by products from JWT). -- **Acceptance:** prospect signs up; trial tenant with 14-day timer exists; quota enforced. -- **Tests:** Playwright e2e signs up → uses → hits quota. -- **Gate:** standard -- **Effort:** M - -### M12.2 — Trial lifecycle cron + emails -- **Depends on:** M12.1, M3.2 (Stalwart must be deliverability-clean) -- **Repos:** `platform/tenant-registry` -- **Deliverables:** scheduler in tenant-registry that runs day-7/12/14 emails; status transitions trial → active (on payment) or trial → frozen → archived; SMTP via Stalwart at `mail.breakpilot.com:587`; sender `noreply@breakpilot.com`; HTML + plaintext templates committed under `tenant-registry/templates/email/`; List-Unsubscribe headers per RFC 8058. -- **Acceptance:** in a time-warped stage test (script that advances `trial_ends_at`), all transitions fire in order and all three emails land in Gmail inbox. -- **Tests:** integration test with time injection; deliverability spot-check at each release. -- **Gate:** standard -- **Effort:** M - -### M13.1 — Demo tenant seeding -- **Depends on:** M6.3, M7.2 -- **Repos:** `platform/seed-data` -- **Deliverables:** per-product fixture archives (`certifai/seed-v1.tar.gz`, `compliance/seed-v1.tar.gz`); publishing pipeline to `cdn.breakpilot.com`; `catalog.demo.seed_data_url` populated in product manifests. -- **Acceptance:** calling `POST /v1/tenants/demo/reset` on either product restores fixtures. -- **Tests:** integration test asserts fixture state after reset. -- **Gate:** standard -- **Effort:** M - -### M13.2 — Sales demo flow (P14) -- **Depends on:** M2.2, M13.1 -- **Repos:** `platform/portal`, `platform/tenant-registry` -- **Deliverables:** demo tenant created in stage and prod with `kind=demo, status=demo`; SALES_REP role usable; backstage routes restricted to `/backstage/leads` and `/backstage/demo`; demo tenant audit events tagged `{"demo": true}` and hidden from real-tenant audit views. -- **Acceptance:** sales rep logs in at `demo.breakpilot.com`, walks both products live, [Request Trial] modal creates a CRM Lead with `sales_owner = the rep`. -- **Tests:** Playwright e2e for the sales walk-through. -- **Gate:** standard + security checklist (SALES_REP guardrail enforcement is the load-bearing piece) -- **Effort:** M - -### M13.3 — Nightly demo reset -- **Depends on:** M13.2 -- **Repos:** `platform/tenant-registry` -- **Deliverables:** cron at 03:00 Europe/Berlin calls each product's reset endpoint; failures page on-call. -- **Acceptance:** after a deliberately-corrupted demo state, the next 03:00 reset restores fixtures. -- **Tests:** test runs the reset manually + verifies fixture state. -- **Gate:** standard -- **Effort:** S - -### M14.1 — Cancel + frozen state (P16 part 1) -- **Depends on:** M10.1, M6.2, M7.1 -- **Repos:** `platform/portal`, `platform/tenant-registry` -- **Deliverables:** cancel modal with reason + typed-confirm; status active → frozen transition; Stripe `cancel_at_period_end`; ERPNext Opportunity → Lost; reactivation path within 30 days. -- **Acceptance:** test customer cancels; portal switches to read-only; reactivate restores `active` status without data loss. -- **Tests:** Playwright e2e covering cancel + reactivate. -- **Gate:** standard + security checklist -- **Effort:** M - -### M14.2 — Offboarding cron + final export (P16 part 2) -- **Depends on:** M14.1, M6.3, M7.2 -- **Repos:** `platform/tenant-registry` -- **Deliverables:** day-30 cron builds final export ZIP per product, emails signed URL (7-day TTL), calls `DELETE /v1/tenants/:id/data` on every subscribed product, archives Keycloak org, marks `tenant.status = archived`. -- **Acceptance:** time-warped test runs the full P16 sequence end-to-end on stage; export ZIP contains data from both products; second post-archive request to either product returns 410. -- **Tests:** integration test with time injection; GDPR-compliance regression suite added. -- **Gate:** standard + security checklist + manual sign-off (irreversible operation) -- **Effort:** L - -**Phase 4 exit criteria:** -- Every flow P1–P16 from `PLATFORM_ARCHITECTURE.md` has a passing Playwright spec. -- Stage runs a full lifecycle: sign-up trial → convert → use → cancel → offboard, in an automated nightly job. -- We can hand a prospect a real demo using `demo.breakpilot.com`. - ---- - -## 7. Phase 5 — Headless products (M15.x – M17.x) - -**Goal:** Make the platform host products with no UI of their own. - -### M15.1 — API key infrastructure -- **Depends on:** M4.2, M10.1 -- **Repos:** `platform/tenant-registry`, `platform/portal` -- **Deliverables:** API key CRUD per `PRODUCT_INTEGRATION_SPEC.md §6.2`; portal UI at `/[slug]/settings/api-keys`; `POST /internal/api-keys/verify` for products. -- **Acceptance:** create key in portal; product call with key succeeds; revoke kills access within 60s. -- **Tests:** integration tests for verify endpoint; Playwright for portal UI. -- **Gate:** standard + security checklist (rotation + scope enforcement) -- **Effort:** M - -### M15.2 — Webhook delivery -- **Depends on:** M15.1 -- **Repos:** `platform/tenant-registry`, `platform/portal` -- **Deliverables:** webhook config + delivery service per `PLATFORM_ARCHITECTURE.md` H4; portal page `/[slug]/integrations`; signed payloads; 3-attempt retry with backoff; dead-letter visible at `/webhooks/deliveries`. -- **Acceptance:** test webhook to https://requestbin.com works; failed deliveries appear in dead letter. -- **Tests:** integration tests with a local sink. -- **Gate:** standard -- **Effort:** M - -### M16.1 — First headless product reference implementation -- **Depends on:** M15.2 -- **Repos:** TBD (proof-of-concept can live in `platform/docs/examples/headless-template/`) -- **Deliverables:** a minimal headless product (e.g., echo-bot) that implements the full §5.C contract: manifest, API, audit emit, usage emit, demo reset, GDPR endpoints. -- **Acceptance:** echo-bot is bookable from catalog, works end-to-end, passes the same lifecycle test as Phase 4. -- **Tests:** the lifecycle e2e from M14.2 extended to include echo-bot. -- **Gate:** standard -- **Effort:** M - -### M17.1 — MCP servers (Enterprise) -- **Depends on:** M6.3, M7.2 -- **Repos:** `benjamin_boenisch/certifai`, `benjamin_boenisch/breakpilot-compliance` -- **Deliverables:** MCP endpoints per `PRODUCT_INTEGRATION_SPEC.md §10` `mcp:` block; gated on `plan == enterprise`; routed via `mcp.breakpilot.com`. -- **Acceptance:** Claude Code can connect to `mcp.breakpilot.com/certifai` with a service token and call `list_ai_agents`. -- **Tests:** MCP contract test using `mcp-cli`. -- **Gate:** standard + security checklist -- **Effort:** L - -**Phase 5 exit criteria:** -- A third-party (or us) can add a new headless product by following `PRODUCT_INTEGRATION_SPEC.md` and a referenced template, with no portal code changes required. - ---- - -## 8. Phase 6 — Enterprise + scale (M18.x – M19.x) - -These ship only when a paying customer requires them. - -### M18.1 — Custom domains -- **Depends on:** M0.3, M10.1 -- **Repos:** `platform/breakpilot-edge` (Orca-Proxy ACME), `platform/portal` (UI) -- **Deliverables:** ACME on-demand TLS in Orca-Proxy; portal UI for customer to add domain; CNAME verification. -- **Acceptance:** `compliance.acme.com` resolves and renders the Acme portal. -- **Tests:** integration test with a synthetic domain. -- **Gate:** standard -- **Effort:** M - -### M18.2 — Physical data isolation -- **Depends on:** M4.1, M6.1, M7.1 -- **Repos:** all app-plane products + `platform/tenant-registry` -- **Deliverables:** option per tenant for a dedicated Postgres / Mongo schema or database; provisioning automation; migration path from logical → physical. -- **Acceptance:** an enterprise tenant runs on a dedicated schema; cross-tenant queries are physically impossible. -- **Tests:** isolation enforcement test. -- **Gate:** standard + security review + manual sign-off -- **Effort:** L - -### M19.1 — A/B testing infra -- **Depends on:** anywhere `featureFlags.evaluate()` is called -- **Repos:** new `platform/feature-flags` (Unleash on `vm-control` or hosted) + portal SDK shim -- **Deliverables:** swap the hard-coded `evaluate()` from §1.12 to call Unleash; eval results land in audit events for reproducibility. -- **Acceptance:** flipping a flag in Unleash changes behaviour for the targeted tenant set within 30s; no behavior change for other tenants. -- **Tests:** integration test asserts flag-driven branches. -- **Gate:** standard -- **Effort:** M - ---- - -## 9. Cross-cutting work (every phase, ongoing) - -These are not milestones — they are commitments enforced by CI and process. - -- **Regression suite expansion.** Every bug fix lands with a regression test FIRST. Tracked by `tests-added` label on PRs; fix-without-test PRs are rejected by reviewer. -- **Security review per phase.** End of each phase: dependency audit (`cargo audit`, `npm audit`, `pip-audit`), SAST scan (`semgrep`), threat model update in `platform/docs/security/`. -- **Disaster-recovery drills.** Once per phase on stage: pick one scenario from `INFRASTRUCTURE.md §10`, run it, document time-to-recover in the runbook. -- **Doc currency.** PR template requires the author to tick "docs updated" or "n/a" — CI fails on a missing tick. -- **OSS swap-in readiness.** When adding metering / audit / SCIM / flag eval code, use the schema/interface noted in `PRODUCT_INTEGRATION_SPEC.md §15` so swap-in stays cheap. - ---- - -## 10. First-PR checklist for Claude Code - -When starting work, the first sequence of PRs should be: - -1. **PR-1** (M0.1): Create `platform/docs` with copied architecture docs + this plan. Land in 1 day. -2. **PR-2 to PR-7** (M0.1 continued): Bootstrap each of the other five repos with §1.2 scaffolding. Land in parallel. -3. **PR-8** (M0.2): CI templates + branch protection per repo. -4. **PR-9** (M1.1): `orca-platform` directory layout + first stub manifest. -5. **PR-10** (M1.2): VM provisioning + cluster-repo split. Per the 2026-06-30 decision: 4 VMs across 3 clusters (`vm-edge` in `breakpilot-edge`, `vm-control` in `breakpilot-control`, `vm-app-prod` + `vm-app-stage` in `breakpilot-app`). Spin up `vm-edge` first since DNS, Keycloak, and Infisical all live there. **Gated on legal entity** (cannot sign SysEleven / Hetzner business contracts before). -6. **PR-11** (M0.3): PowerDNS on vm-edge + zone file + registrar NS delegation + wildcard TLS via Let's Encrypt DNS-01. - -After PR-11, the dependency graph fans out and parallel work begins. - -For each PR, Claude Code MUST: -- Open the PR with the §1.4 template filled in. -- Link the milestone ID in PR body (`Linked milestone: M0.1`). -- Wait for human approval (no self-merge — branch protection enforces). -- After merge: verify the stage deploy succeeds before starting the next dependent PR. - ---- - -## 11. Dependency graph +## 6. Dependency graph ``` - ┌── M6.1 ── M6.2 ── M6.3 ──┐ - │ │ - ┌── M2.1 ── M2.2 ────────┤ ├── M10.1 ── M10.2 - │ │ │ │ -M0.1 ── M0.2 ── M1.1 ──┼── M1.2 ── M0.3 ── M1.3 │ │ ├── M11.1 ── M12.1 ── M12.2 - │ │ │ │ │ │ - │ └── M3.1 ── M3.2 │ ├── M13.2 ── M13.3 │ - │ │ │ │ │ - └─────────────────────── M4.1 ── M4.2 ── M4.3 ── M5.1 ── M5.2 ── M5.3 M13.1 │ - │ - M8.1 ── M8.2 ── M8.3 ── M9.1 ── M9.2 ──────────────────────┤ - │ - M15.1 ── M15.2 ── M16.1 ── M17.1 │ - │ - M14.1 ── M14.2 - -Phase-6 (M18, M19) depends on Phase-4 completion + a paying customer. -M12.2 depends on M3.2 (Stalwart deliverability must be clean before trial emails go out). +M-MIG-0 ──┬── M-MIG-1 (specs, parallel) + ├── M-MIG-2 (stop on core) ─────────────────────────────────────────┐ + ├── M-MIG-3 (stage VM + cluster) ──┐ │ + └── M-MIG-4 (repo moves) ──────────┴── M-MIG-5 ── M-MIG-6 ── M-MIG-7 ── M-MIG-8 ── M-MIG-9 + │ + production plan ``` -**Critical path** (longest chain to first paying customer): -`M0.1 → M0.2 → M1.1 → M1.2 → M0.3 → M1.3 → M2.1 → M2.2 → M4.1 → M4.2 → M4.3 → M5.1 → M5.2 → M6.2 → M6.3 → M10.1 → M11.1 → M12.1` - -That's 18 milestones. With one full-time agent and standard human review pacing, plan for **9–13 weeks** to first paying customer flow on stage (added 1 week for the PowerDNS / DNS-delegation cycle vs. the prior Cloudflare path); **+2–4 weeks** for prod hardening and the Phase-4 lifecycle completion. - -> **Note on M3.2 critical path:** Stalwart IP warming (4–8 weeks) runs in *background parallel* — start it immediately after M3.1 so warming finishes before M12.2 needs it. It is NOT on the critical path for first paying customer (that customer can be onboarded by hand), but it IS on the critical path for self-serve trial volume. - -**Parallelism opportunities:** -- M6.x and M7.x can run fully in parallel (different repos, different stacks). -- M8.x is independent of all app-plane work once M2.2 is done. -- M15.x can begin as soon as M10.1 lands. +**Critical path:** M-MIG-0 → M-MIG-3 → M-MIG-5 → M-MIG-6 → M-MIG-7 → M-MIG-8. With one agent and standard review pacing: **6–9 weeks** to a passing staging gate. M-MIG-1, M-MIG-2 and M-MIG-4 run in parallel with M-MIG-3. --- -## 12. Open questions to resolve before starting +## 7. Open questions -**Resolved:** -- ~~Email provider~~ → **Stalwart**, self-hosted on vm-control. Plan in M3.2; 4–8 week IP warming acknowledged. -- ~~Stripe vs Lemon Squeezy~~ → **Polar.sh**. Plan in M8.3. -- ~~Cloudflare account ownership~~ → not used; DNS is self-hosted via PowerDNS on vm-edge (M0.3). Registrar account (Benjamin's) still needs documented 2FA recovery — see new DR item below. - -**Still open:** -- **CDN host** for `cdn.breakpilot.com`: self-hosted MinIO + Caddy on vm-edge is the OSS-aligned default; alternative is BunnyCDN (cheap, EU). Decide before M6.3 (manifest bundles + hero images). -- **Cloud provider for port 25 outbound.** Stalwart needs unblocked port 25 to send mail. Hetzner blocks by default and requires a request to unblock with proof of intent + abuse contact; OVH and Scaleway unblock on request faster. Confirm with Benjamin which provider vm-control runs on. Block on M3.2 if port 25 is unblockable — fallback is sending via a different provider's IP with reverse DNS. -- **Test data privacy.** The demo tenant must contain ONLY synthetic data — confirm seed pipeline strips real PII even if our test orgs accidentally seed from prod. -- **Registrar + DNS bus-factor.** Document who owns the registrar account, who has 2FA recovery codes, and the procedure to update NS records without that person available. Goes in `platform/docs/runbooks/dr.md` before M0.3 ships. -- **Internal CA.** `step-ca` listed in INFRASTRUCTURE.md vm-edge as "optional" — decide whether inter-service mTLS is in scope for Phase 0 or deferred until Phase 4 (Enterprise tier). +- **Pitch-deck's home** (shares the dsms Postgres): move with dsms or split the database first? Decide before M-MIG-9. +- **Gitea Actions runner location** (not an Orca service; verify in M-MIG-0) and whether a second runner should live on the platform master for isolation. +- **Second backup provider** for the platform bucket (3-2-1) before production. +- **Prüfwerk crate/binary renames** (`compliance-*` → `pruefwerk-*`) and the Mongo prefix: cosmetic, deferred; the Mongo prefix rename is a data migration. +- **`DR-WS-08 §6B` role mapping** remains open; staging uses the V1 `org_roles` model. +- **ERP Phase 0/1** (Steuerberater, SKU import) proceed independently on the live ERPNext; the platform only needs the SKU codes, which are already fixed in the SKU sheet. --- -*End of document. Open items in §12 should be triaged before M0.1 starts; the bus-factor and port-25 items are the only hard blockers.* +*End of document. Revised 2026-09-11.* diff --git a/INFRASTRUCTURE.md b/INFRASTRUCTURE.md index 10d9693..7883072 100644 --- a/INFRASTRUCTURE.md +++ b/INFRASTRUCTURE.md @@ -1,344 +1,261 @@ # Infrastructure Specification -**Status:** Locked Topology +**Status:** Revised topology (2026-09-11) **Authors:** Sharang, Benjamin -**Date:** 2026-05-11 (topology lock: 2026-05-18; cluster split: 2026-06-30) -**Companion docs:** PLATFORM_ARCHITECTURE.md, IMPLEMENTATION_PLAN.md, COST_PLAN.md -**Cloud provider:** SysEleven Cloud Services (DUS2, OpenStack) — multi-VM rollout gated on legal entity +**Date:** 2026-05-11 (topology lock: 2026-05-18; cluster split: 2026-06-30; **revised 2026-09-11**) +**Companion docs:** PLATFORM_ARCHITECTURE.md, IMPLEMENTATION_PLAN.md, COST_PLAN.md, `BreakPilot Infra/Infrastructure Architecture` (as-built core cluster) +**Cloud provider:** Hetzner Cloud (fsn1 / nbg1, EU) + Hetzner Object Storage (nbg1). DNS at Strato. --- -> **2026-06-30 cluster-split decision.** The 4 VMs from the May 18 lock are unchanged in count and flavor. What changes is how they're organized: **one Orca cluster per plane**, three cluster repos (`platform/breakpilot-edge`, `platform/breakpilot-control`, `platform/breakpilot-app`). Identity and Infra are co-tenant on `vm-edge` inside `breakpilot-edge` (single-VM core; KC JVM heap pinned so it cannot starve PowerDNS / Infisical). The "Data plane" is renamed to **App plane** to reflect that it carries product workloads, not just data stores. `vm-data` is renamed `vm-app-prod`, and the standalone `stage` VM is renamed `vm-app-stage` — both live in the same `breakpilot-app` cluster. Multi-VM rollout is gated on the legal entity being established so we can sign SysEleven business contracts; until then, single-VM ops continues via `~/workspace/orca-infra`. See `IMPLEMENTATION_PLAN.md §1.1 / M1.2` and `platform/orca-platform/clusters/README.md` for the migration mechanics. **The SLA targets in §6 / §7 below are unaffected** — they apply at the plane level regardless of which cluster a plane lives in. +> **2026-09-11 revision.** Replaces the SysEleven 4-VM / 3-cluster design. The company already runs a single Hetzner Orca cluster (`breakpilot`, see `BreakPilot Infra`). That cluster becomes **core-only**. A second Orca cluster, `breakpilot-platform`, hosts the customer-facing platform with **staging and production on separate VMs**. PowerDNS, Stalwart, Orca-Proxy-as-a-container, wildcard TLS and SysEleven pricing are gone. The legal entity (BreakPilot GmbH, HRB 736403) exists, so the "gated on legal entity" clauses are discharged. -## 1. VM Inventory - -**Four billable VMs across three Orca clusters.** Dev runs entirely on developer laptops via docker-compose. +## 1. Cluster and VM Inventory ``` -┌──────────────────┬────────────────────┬──────────┬────────────────────────┬───────────┬─────────────────┐ -│ Name │ Cluster │ Env │ SysEleven flavor │ Public IP │ Planes owned │ -├──────────────────┼────────────────────┼──────────┼────────────────────────┼───────────┼─────────────────┤ -│ vm-edge │ breakpilot-edge │ prod │ m2.small (2v / 8 GB) │ YES (1) │ Identity + Infra│ -│ vm-control │ breakpilot-control │ prod │ m2.medium (4v / 16 GB) │ No │ Control │ -│ vm-app-prod │ breakpilot-app │ prod │ m2.medium (4v / 16 GB) │ No │ App (prod) │ -│ vm-app-stage │ breakpilot-app │ stage │ m2.small (2v / 8 GB) │ YES (1) │ App (stage) │ -│ (dev) │ — │ dev │ local docker-compose │ n/a │ all (in-memory) │ -└──────────────────┴────────────────────┴──────────┴────────────────────────┴───────────┴─────────────────┘ +┌──────────────────────┬────────────────────┬───────┬────────────────────────────┬───────────┬──────────────────────────┐ +│ Node │ Cluster │ Env │ Flavor (Hetzner) │ Public IP │ Role / planes │ +├──────────────────────┼────────────────────┼───────┼────────────────────────────┼───────────┼──────────────────────────┤ +│ breakpilot-infra-vm1 │ breakpilot (core) │ core │ existing, 46.225.100.82 │ YES │ master · Identity+Infra │ +│ ubuntu-16gb-fsn1-1 │ breakpilot (core) │ core │ existing 16 GB, 178.105.159.224 │ YES │ agent · ERP, Nextcloud… │ +│ bp-platform-stage │ breakpilot-platform│ stage │ CX43/CPX41 class 8v/16 GB │ YES │ MASTER · Control+App (stage) │ +│ bp-platform-prod │ breakpilot-platform│ prod │ sized at prod planning (≥16 GB, dedicated cores preferred) │ YES │ agent · Control+App (prod) │ +│ (dev) │ — │ dev │ laptop docker-compose │ n/a │ all (in-memory) │ +└──────────────────────┴────────────────────┴───────┴────────────────────────────┴───────────┴──────────────────────────┘ ``` -**Total compute:** 48 GiB-RAM, 12 vCPU. **Monthly compute net: €192 (36M upfront) / €295 (12M) / €435 (On-Demand).** See COST_PLAN.md for the full three-mode table. The cluster split does not change the per-VM bill (same flavors); the additional cost is operational (3 cluster repos to keep CI green in) and is offset by the independent failure-domain wins. +**Why this topology** -### Why this topology and not the previous 7-VM layout - -The earlier draft proposed one VM per service group (vm-gateway, vm-identity, vm-secrets, vm-ops, vm-control, vm-certifai, vm-compliance). That gave maximum failure isolation but cost 132 GiB-RAM stage+prod. At 5 customers the isolation is unused — every VM ran at <10% utilisation. The locked topology buys back failure isolation incrementally as load grows (see §13 Growth Trajectory). - -Critical isolations preserved even at 4 VMs: -- **vm-edge isolates identity from app workloads.** Keycloak JVM has its own page cache + heap pin (`-Xmx1500m`) so ERPNext or product background jobs on a different VM cannot starve token issuance — and PowerDNS / Infisical on the same VM cannot be starved by KC either. -- **vm-app-prod isolates product databases from stateless services.** All app-plane DBs share one host, but they're walled off from the portal + ERPNext + Stalwart competing on vm-control. -- **vm-app-stage runs the app plane only.** It calls prod Keycloak (`breakpilot-edge`) + prod Tenant Registry (`breakpilot-control`) under `tenant.kind = stage` rather than mirroring those services. Stage and prod live in the **same** `breakpilot-app` Orca cluster on **different** VMs — same config, different physical workloads. +- **Core stays where it is.** Keycloak, Gitea, Harbor, ERPNext, LiteLLM, Infisical, SigNoz, Nextcloud, chat and the landing page are company infrastructure and keep running on the cluster they run on today. Nothing customer-facing shares a node with them after M-MIG-2. +- **One platform cluster, one node per environment.** Orca can pin services to a node (`placement.node`) but has no environments, namespaces or label scheduling. Separate VMs give staging and production physical isolation; separate Orca projects, service names, realms, databases and secret scopes give them logical isolation. +- **The staging VM is the cluster master.** It exists first; production joins later as an agent over the Hetzner private network. Unpinned services land on the master, so `validate.sh` rejects any unpinned service. +- **Per-node ingress.** Every node binds 80/443 and issues its own certificates (HTTP-01). A hostname's A record points at the node running the service. No wildcard, no DNS-01, no shared proxy. --- -## 2. Service-to-VM Mapping +## 2. Service-to-Node Mapping -Each VM is owned by one Orca cluster (see §1). Service manifests live in that cluster's repo at `platform/breakpilot-/services/...`. +### Core cluster (`sharang/orca-infra`) — after M-MIG-2 ``` -vm-edge (cluster: breakpilot-edge, prod, m2.small 8 GB, public IP) - ├── orca-proxy (Orca-managed; wildcard TLS terminator) - ├── powerdns-auth (Orca-managed; authoritative DNS for breakpilot.com) - ├── keycloak-26 (Orca-managed; JVM, ~1.5 GB heap; repurposed from CERTifAI KC at M2.1) - ├── postgres-keycloak (Orca-managed; dedicated PG instance for Keycloak only) - ├── infisical (Orca-managed) - ├── postgres-infisical (Orca-managed; dedicated PG instance for Infisical only) - ├── redis-infisical (Orca-managed; ephemeral) - └── gitea (Orca-managed; SQLite backend to avoid a third PG) +breakpilot-infra-vm1 (master, 46.225.100.82) + keycloak + db auth.breakpilot.com realms: master, breakpilot, breakpilot-stage, breakpilot-prod + gitea + db git.breakpilot.com (+ SSH :22222) + harbor (9 svcs) repo.breakpilot.com projects: breakpilot, pruefwerk, firmwerk, platform, observability + litellm + db/redis llm.breakpilot.com + infisical + db/redis secrets.breakpilot.com + gatus status.breakpilot.com + matrix/synapse/proxy chat.breakpilot.com + landing + kontakt-relay breakpilot.com, www. + coturn + otel-agent-master + [until M-MIG-9] breakpilot-dsms (12 svcs) · tenant-registry-dev · compliance-mcp · certifai-mongo -vm-control (cluster: breakpilot-control, prod, m2.medium 16 GB) - ├── customer-portal (Orca-managed; Next.js) - ├── tenant-registry (Orca-managed; Go) - ├── orca-controller (Orca core process; NOT a managed container) - ├── erpnext (Orca-managed; Frappe bench) - ├── frappe-hd (same bench as ERPNext) - ├── mariadb (Orca-managed; for ERPNext) - ├── redis-erpnext (Orca-managed) - └── stalwart-mail (Orca-managed; SMTP/IMAP/JMAP on mail.breakpilot.com) +ubuntu-16gb-fsn1-1 (agent, 178.105.159.224) + erpnext stack (9 svcs) erp.breakpilot.com + Frappe CRM + Helpdesk + nextcloud + collabora cloud.breakpilot.com, collabora. + signoz + clickhouse signoz.breakpilot.com, otel.breakpilot.com + element, jitsi element.breakpilot.com, meet.breakpilot.com + kellnr crates.breakpilot.com + penpot design.breakpilot.com + otel-agent-workhorse +``` -vm-app-prod (cluster: breakpilot-app, prod, m2.medium 16 GB) - ├── certifai-dashboard (Orca-managed) - ├── mongodb (Orca-managed) - ├── litellm (Orca-managed) - ├── backend-compliance (Orca-managed) - ├── ai-compliance-sdk (Orca-managed) - ├── admin-compliance (Orca-managed) - ├── postgres-app (Orca-managed; schemas: tenant_registry, compliance) - ├── qdrant (Orca-managed) - └── minio (Orca-managed) +Stopped and archived at M-MIG-2: `breakpilot-portal` + 4 per-tenant portals, `compliance-agent`, `compliance-dashboard`, `compliance-docs`, `browserless`, `soft-plc`, `plc-sim`, `mailserver`. -vm-app-stage (cluster: breakpilot-app — SAME cluster as vm-app-prod, stage, m2.small 8 GB, public IP) - ├── orca-proxy (light; only routes to stage app) - ├── customer-portal (NEW VERSION under test) - ├── tenant-registry (placeholder; stage actually calls PROD tenant-registry — manifest exists for parity, see §5 isolation rules) - ├── certifai-dashboard (NEW VERSION under test) - ├── backend-compliance (NEW VERSION under test) - ├── ai-compliance-sdk (NEW VERSION under test) - ├── admin-compliance (NEW VERSION under test) - ├── litellm (light; same image as prod) - ├── postgres-app-stage (ephemeral; lives entirely on vm-app-stage) - ├── mongodb-stage (ephemeral) - └── qdrant-stage (ephemeral, tiny corpus) +### Platform cluster (`platform/orca-platform`) — stage node - Calls OUT to prod: - → auth.breakpilot.com (PROD Keycloak in breakpilot-edge, under stage client_id, tenant.kind = "stage") - → registry.breakpilot.com (PROD tenant-registry in breakpilot-control, read-only for stage tenants) - → mail.breakpilot.com (PROD Stalwart in breakpilot-control, recipient filter forces +stage@ only) - → Polar SANDBOX webhook URL (NEVER prod Polar) - → no calls to prod Postgres-app, MariaDB, MongoDB +``` +bp-platform-stage (master, public IP, 8 vCPU / 16 GB) + project platform-stage + portal-stage app-stage.breakpilot.com 1 GB + tenant-registry-stage registry-stage.breakpilot.com 512 MB (migrate init) + pg-stage internal, volume 1.5 GB pre_hook pg_dumpall + erpnext-mock-stage internal 256 MB (stage only) + project pruefwerk-stage + pruefwerk-dashboard-stage pruefwerk-stage.breakpilot.com 1 GB + pruefwerk-agent-stage internal :3001 2 GB + pruefwerk-mcp-stage route pruefwerk-stage…/mcp/* 512 MB + pruefwerk-docs-stage route pruefwerk-stage…/docs/* 128 MB + pruefwerk-mongo-stage internal, volume 1.5 GB pre_hook mongodump + browserless-stage internal 1.5 GB + soft-plc-stage, plc-sim-stage internal (scan targets) 512 MB each + werkbank-runner-stage internal 1 GB + project firmwerk-stage + firmwerk-cloud-stage firmwerk-stage.breakpilot.com 512 MB + firmwerk-mongo-stage internal, volume 1 GB pre_hook mongodump + otel-agent (observability) internal 256 MB + ≈ 13 GB committed of 16 GB +``` + +### Platform cluster — prod node (later, same shape) + +`bp-platform-prod` (agent): projects `platform-prod`, `pruefwerk-prod`, `firmwerk-prod` with the same services minus `erpnext-mock`; talks to the live `erp.breakpilot.com`. After M-MIG-9 the `dsms` project (12 services) is added, initially on the stage node until the prod node exists. + +### Calls from the platform cluster into core (all HTTPS, all public hostnames) + +``` +→ auth.breakpilot.com OIDC, JWKS, admin API (tenant-registry-svc-{env}) +→ erp.breakpilot.com ERPNext REST + inbound webhooks (prod only; stage uses the mock) +→ repo.breakpilot.com image pulls (docker login per node) +→ llm.breakpilot.com LiteLLM (Prüfwerk triage, Werkpilot) +→ otel.breakpilot.com traces/logs/metrics +→ secrets.breakpilot.com licence signing key, CI credentials (bootstrap only) +→ git.breakpilot.com webhooks INTO the platform master come from Gitea Actions runners ``` ### Stage isolation rules (enforced at the platform, not in product code) | Risk | Enforcement mechanism | Owner | |---|---|---| -| Stage writes to prod database | Infisical scope: stage app only gets `/stage/*` secrets. Prod DB credentials never reach stage. | Infra plane | -| Stage emails real customers | Stalwart accept-rule: drop if recipient does not match `*+stage@*`. | Control plane (Stalwart config) | -| Stage triggers real Polar charges | Stage env points `POLAR_API_URL` to sandbox. Prod Polar webhook secret never on stage. | Control plane | -| Stage Keycloak JWT used in prod | `stage_client_id` issued only by Keycloak; prod services reject JWTs with this aud. | Identity plane | -| Stage load DOSes prod Keycloak | Keycloak rate-limit per client_id; stage limited to 60 req/s. | Identity plane | +| Stage writes to prod database | Separate VM, separate Orca projects, **project-scoped secrets** (`*-stage` never sees `*-prod` keys; prod values are never set globally). | Infra plane | +| Stage emails real customers | Realm `breakpilot-stage` SMTP = Strato `noreply+stage@`; tenant-registry-stage `EMAIL_ALLOWLIST_DOMAINS=breakpilot.com`; only `@breakpilot.com` test users exist in the realm. | Control plane | +| Stage creates real ERP records | Stage has no ERPNext credentials at all; `ERP_BASE_URL` points at `erpnext-mock-stage`. | Control plane | +| Stage JWT used in prod | Different realm → different issuer; every prod service pins `iss` and `aud`. | Identity plane | +| Stage load hurts prod | Different VM. Shared core services (Keycloak, LiteLLM) rate-limit per client. | Identity plane | +| Stage CI token deploys prod | Orca tokens are cluster-wide (no per-project RBAC) → prod deploys use a separate `prod` branch webhook + HMAC secret; the stage deployer token is never stored in a repo that can reach prod projects. **Residual risk, see RISK-2.** | Infra plane | --- ## 3. Network Topology ``` - INTERNET - │ - (breakpilot.com — authoritative on vm-edge PowerDNS; - stage.breakpilot.com — authoritative same zone) - │ - ┌─────────────┴─────────────┐ - │ │ - ┌───────▼────────┐ ┌────────▼─────────┐ - │ vm-edge │ │ stage │ - │ (public IP) │ │ (public IP) │ - │ │ │ │ - │ orca-proxy ────┤ │ orca-proxy │ - │ powerdns │ │ portal-new │ - │ keycloak │◄────────┤ tenant-registry-new - │ pg-keycloak │ stage │ certifai-new │ - │ infisical │ calls │ compliance-new │ - │ pg-infisical │ prod │ pg-stage │ - │ redis-infis │ KC + │ mongo-stage │ - │ gitea │ Stalwart│ qdrant-stage │ - └───────┬────────┘ └──────────────────┘ - │ PRIVATE NETWORK 10.0.0.0/16 - ┌────────┴─────────┐ - │ │ -┌──────▼───────┐ ┌───────▼──────┐ -│ vm-control │ │ vm-app-prod │ -│ │ │ │ -│ portal │ │ certifai │ -│ tenant-reg │ │ mongodb │ -│ orca-ctrl │ │ litellm │ -│ erpnext │ │ backend-comp │ -│ frappe-hd │ │ ai-sdk │ -│ mariadb │ │ admin-comp │ -│ redis-erp │ │ pg-app │ -│ stalwart │ │ qdrant │ -└──────────────┘ │ minio │ - └──────────────┘ + INTERNET + │ + (breakpilot.com zone at Strato — manual A records, no wildcard) + │ + ┌──────────────────────────────┼───────────────────────────────┐ + │ │ │ +┌────▼────────────────┐ ┌─────────▼───────────┐ ┌──────────────▼────────┐ +│ CORE master │ │ CORE workhorse │ │ bp-platform-stage │ +│ 46.225.100.82 │ │ 178.105.159.224 │ │ │ +│ auth git repo llm │ │ erp cloud signoz │ │ app-stage registry- │ +│ secrets status chat │ │ meet design crates │ │ stage pruefwerk-stage │ +│ breakpilot.com │ │ │ │ firmwerk-stage │ +└─────────────────────┘ └──────────────────────┘ └──────────┬────────────┘ + │ Hetzner private + │ network 10.10.0.0/16 + ┌──────────▼────────────┐ + │ bp-platform-prod │ + │ (later) │ + │ app registry licence │ + │ pruefwerk firmwerk │ + └───────────────────────┘ -Orca-Proxy routing (vm-edge, by Host header): - auth.breakpilot.com → 127.0.0.1:8443 (Keycloak, local on vm-edge) - erp.breakpilot.com → vm-control:8000 (ERPNext) [allowlist: our IPs only] - git.breakpilot.com → vm-edge:3000 (Gitea, local) [allowlist: our IPs only] - mail.breakpilot.com → vm-control:587 (Stalwart submission) [allowlist: VM internal only] - ns1.breakpilot.com → 127.0.0.1:53 (PowerDNS, local) - *.breakpilot.com → vm-control:3000 (customer portal) +Firewall (Hetzner Cloud Firewall, per platform VM): + 22/tcp admin IPs only + 80,443/tcp any + 6880/tcp (orca API + agent websocket) private network only, plus the Gitea runner egress IP for webhooks + 6881/tcp (orca agent) private network only + everything else drop -Orca-Proxy routing (stage, by Host header): - *.stage.breakpilot.com → 127.0.0.1:3000 (stage portal — all subdomains route here) +Ingress (per node, Orca built-in proxy, HTTP-01 ACME): + bp-platform-stage + app-stage.breakpilot.com → portal-stage:3000 + registry-stage.breakpilot.com → tenant-registry-stage:8090 + pruefwerk-stage.breakpilot.com → pruefwerk-dashboard-stage:8080 + /mcp/* → pruefwerk-mcp-stage:8090 (strip_prefix) + /docs/* → pruefwerk-docs-stage:80 (VitePress base /docs/) + firmwerk-stage.breakpilot.com → firmwerk-cloud-stage:8080 + bp-platform-prod + app. registry. licence. pruefwerk. firmwerk.breakpilot.com (same targets, -prod) + +Cross-node traffic: Docker bridge networks are node-local. Anything that must cross VMs uses public HTTPS +(there is nothing stage↔prod by design). Master↔agent Orca traffic uses the private network. ``` +DNS records to add at Strato (stage): `app-stage`, `registry-stage`, `pruefwerk-stage`, `firmwerk-stage` → stage IP. Prod adds `app`, `registry`, `licence`, `pruefwerk`, `firmwerk` → prod IP. Lower TTLs before any cutover; a certificate is only issued after the A record points at the node. + --- -## 4. Storage and Volume Requirements - -Block volumes (Ceph 3x replicated, €0.10/GiB/mo) mounted to each VM. +## 4. Storage ``` -┌──────────────┬───────────────────────────────────────────┬─────────┬─────────────────────┐ -│ VM │ Data stores │ +Block │ Growth profile │ -├──────────────┼───────────────────────────────────────────┼─────────┼─────────────────────┤ -│ vm-edge │ pg-keycloak + pg-infisical + Gitea repos │ +50 GB │ Slow │ -│ vm-control │ MariaDB (ERPNext) + Stalwart mail spool │ +250 GB │ Medium │ -│ vm-app-prod │ MongoDB + pg-app + Qdrant + MinIO │ +500 GB │ Fast (scales w/ N) │ -│ stage │ pg-stage + mongo-stage + qdrant-stage │ +50 GB │ Resets per release │ -└──────────────┴───────────────────────────────────────────┴─────────┴─────────────────────┘ +┌────────────────────┬──────────────────────────────────────────────────┬─────────────────────────┐ +│ Node │ Data stores │ Disk │ +├────────────────────┼──────────────────────────────────────────────────┼─────────────────────────┤ +│ bp-platform-stage │ pg-stage, pruefwerk-mongo-stage, firmwerk-mongo- │ local NVMe (flavor); │ +│ │ stage, Docker volumes (orca-*) │ add a Hetzner Volume │ +│ │ │ (€0.05/GB) when > 60 % │ +│ bp-platform-prod │ pg-prod, mongo-prod ×2, later dsms (pg17, IPFS, │ local NVMe + Hetzner │ +│ │ qdrant, dataroom, ollama) │ Volume for dsms │ +└────────────────────┴──────────────────────────────────────────────────┴─────────────────────────┘ -Each VM's root disk: 50 GB ephemeral, included in flavor price. - -Object storage (S3, €0.02/GiB/mo single-region or €0.0496/GiB/mo geo-redundant): - ┌─────────────────────────────────┬─────────┬──────────────────────────┐ - │ Bucket │ Size │ Purpose │ - ├─────────────────────────────────┼─────────┼──────────────────────────┤ - │ s3://backups (geo-redundant) │ ~500 GB │ Database dumps │ - │ s3://seed-data │ ~30 GB │ Demo tenant fixtures │ - │ s3://exports │ ~50 GB │ GDPR/offboarding ZIPs │ - │ s3://audit-archive │ ~20 GB │ Old audit log overflow │ - └─────────────────────────────────┴─────────┴──────────────────────────┘ +Object storage (Hetzner Object Storage, nbg1, S3-compatible): + s3://bp-platform-backups Orca nightly backups of the platform cluster (separate from core's bp-orca-backups) + s3://bp-seed-data demo tenant fixtures (platform/seed-data) + s3://bp-exports GDPR / offboarding ZIPs (signed URLs, 7-day TTL) + s3://bp-rag existing dsms RAG bucket (moves with dsms) + s3://bp-sccache, bp-gitea-packages, bp-kellnr-* core (unchanged) ``` --- ## 5. Backup Requirements -All backups ship to **SysEleven Object Storage** (S3-compatible, geo-redundant DUS2 ↔ HAM1 for production-critical data). Backup jobs run as Orca one-shot containers on cron. Infisical holds the S3 credentials. +Orca-native backups per cluster (`[backup]` in each `cluster.toml`): nightly `0 0 3 * * *`, local copy + S3, per-datastore logical dumps via `pre_hook` (`pg_dumpall`, `mongodump`, `mariadb-dump`). Retention 14 days core (existing), 30 days platform. ``` -┌───────────────────────┬──────────────────┬────────────┬────────────┬──────────────────────┐ -│ Data store │ Method │ Frequency │ Retention │ Owner (who restores) │ -├───────────────────────┼──────────────────┼────────────┼────────────┼──────────────────────┤ -│ pg-keycloak (vm-edge) │ pg_dump → S3-geo │ Every 6h │ 14 days │ Infra Plane │ -│ pg-infisical (vm-edge)│ pg_dump → S3-geo │ Daily │ 30 days │ Infra Plane │ -│ Gitea (vm-edge) │ gitea dump → S3 │ Daily │ 30 days │ Infra Plane │ -│ Keycloak realm export │ KC export → S3 │ Daily │ 14 days │ Identity Plane (owns)│ -│ Infisical store │ encrypted → S3 │ Daily │ 30 days │ Infra Plane │ -│ MariaDB (vm-control) │ mysqldump → S3 │ Every 6h │ 30 days │ Control Plane │ -│ Stalwart queue/store │ tar → S3 │ Daily │ 7 days │ Control Plane │ -│ pg-app (vm-app-prod) │ pg_dump → S3-geo │ Every 6h │ 30 days │ App Plane (owns RPO) │ -│ MongoDB (vm-app-prod) │ mongodump → S3 │ Daily │ 30 days │ App Plane │ -│ MinIO (vm-app-prod) │ mc mirror → S3 │ Daily │ 90 days │ App Plane │ -│ Qdrant (vm-app-prod) │ API snap → S3 │ Daily │ 14 days │ App Plane (rebuild) │ -│ stage * │ no backup │ — │ — │ — (ephemeral) │ -│ Orca config (IaC) │ Gitea (VCS) │ On commit │ Forever │ Infra Plane │ -└───────────────────────┴──────────────────┴────────────┴────────────┴──────────────────────┘ +┌──────────────────────────────┬──────────────────────┬────────────┬───────────┬────────────────────┐ +│ Data store │ Method │ Frequency │ Retention │ Owner │ +├──────────────────────────────┼──────────────────────┼────────────┼───────────┼────────────────────┤ +│ keycloak-db (core) │ pg_dumpall pre_hook │ nightly │ 14 d │ Identity plane │ +│ keycloak realm export │ kc export → S3 │ on change │ 14 d │ Identity plane │ +│ gitea-db + repos (core) │ pre_hook + volume │ nightly │ 14 d │ Infra plane │ +│ harbor (core) │ db pre_hook; images │ nightly │ 14 d │ Infra plane │ +│ │ rebuildable from CI │ │ │ │ +│ erpnext mariadb (core) │ mariadb-dump pre_hook│ nightly │ 14 d │ Control plane │ +│ pg-prod (tenant-registry) │ pg_dumpall pre_hook │ nightly + │ 30 d │ Control plane │ +│ │ + 6-hourly cron dump │ 6 h │ │ (RPO ≤ 6 h) │ +│ pruefwerk-mongo-prod │ mongodump pre_hook │ nightly │ 30 d │ App plane │ +│ firmwerk-mongo-prod │ mongodump pre_hook │ nightly │ 30 d │ App plane │ +│ dsms (pg17, IPFS, qdrant…) │ pre_hooks + volumes │ nightly │ 30 d │ App plane │ +│ stage * │ nightly (convenience)│ nightly │ 7 d │ — (no SLA) │ +│ Orca config (IaC) │ Gitea │ on commit │ forever │ Infra plane │ +└──────────────────────────────┴──────────────────────┴────────────┴───────────┴────────────────────┘ ``` +**Known gaps (carried from the as-built runbook):** Orca backups are unencrypted (orca #117) and include `secrets.json`; restores are untested → a restore drill is part of M-MIG-8; both copies live at Hetzner (no 3-2-1) → add a second S3 provider before production. + ### RPO by data criticality ``` -CRITICAL (RPO ≤ 6h) - pg-keycloak — org memberships, IdP config - pg-app — tenant registry, compliance records - MariaDB/ERPNext — sales orders, invoices, contracts - -IMPORTANT (RPO ≤ 24h) - MongoDB — chat history, user preferences - MinIO — compliance evidence documents - pg-infisical — encrypted secrets - Stalwart store — inbound webhooks, bounce records - -RECOVERABLE (RPO ≤ 48h, rebuildable) - Qdrant — vector index (rebuildable from MinIO source documents) - Gitea — code (mirrored on dev machines) - Keycloak export — org structure (pg-keycloak is primary) - -NOT BACKED UP - stage (any data) — by design; restored from seed bundles on each deploy - redis-* — caches; restart cold +CRITICAL (RPO ≤ 6h) keycloak-db · pg-prod (tenants, subscriptions, licences, audit) · erpnext mariadb +IMPORTANT (RPO ≤ 24h) pruefwerk-mongo-prod · firmwerk-mongo-prod · dsms postgres + IPFS +RECOVERABLE harbor images (CI) · qdrant (rebuildable) · gitea (mirrored on laptops) +NOT BACKED UP stage data beyond 7 days · redis caches · browserless ``` --- ## 6. Constraint Framework -### Constraint types +Constraint types (AVAILABILITY, RTO, RPO, IaC, SECRET_HYGIENE, NETWORK, DATA_RESIDENCY, AUDIT_TRAIL, IMMUTABILITY, STAGE_ISOLATION) are unchanged. Planes remain the **SLA + ownership abstraction**; clusters and nodes are the **operational unit**. ``` -AVAILABILITY — required uptime percentage over rolling 30 days -RTO — Recovery Time Objective: max time to restore service after failure -RPO — Recovery Point Objective: max acceptable data loss window -IaC — service must be declared in Orca config, no manual container runs in prod -SECRET_HYGIENE — all secrets via Infisical machine identity; no env files, no hardcoded values -NETWORK — whether service is internet-exposed or internal-only -DATA_RESIDENCY — all data must remain in EU (SysEleven DUS2 + HAM1) -AUDIT_TRAIL — all mutating actions logged (who, what, when, from where) -IMMUTABILITY — config changes go through Gitea → Orca pipeline, not manual SSH -STAGE_ISOLATION— stage tenant cannot mutate any prod data; reads-only against prod KC + TR -``` - -### Plane ownership of constraints - -Planes are the **SLA + ownership abstraction**; clusters are the **operational unit**. The plane that owns a constraint owns it regardless of which cluster hosts the service. Identity and Infra are co-tenant in the `breakpilot-edge` cluster on `vm-edge`; they remain distinct planes for purposes of SLA + ownership accounting. - -``` -╔══════════════════════════════════════════════════════════════════════════════════════════╗ -║ IDENTITY PLANE (cluster: breakpilot-edge, on vm-edge) ║ -║ ║ -║ Owns / defines: ║ -║ AVAILABILITY — must be ≥ 99.5% (root dep for everything) ║ -║ RTO — ≤ 15 min ║ -║ AUDIT_TRAIL — realm-level audit (logins, token issuance, IdP events) ║ -║ DATA_RESIDENCY— Keycloak realm data must stay EU ║ -║ STAGE_ISOLATION— rate-limits stage_client_id; rejects stage JWTs in prod audiences ║ -║ ║ -║ Co-tenant note: shares vm-edge with Infra Plane services. JVM heap pinned to 1.5 GB ║ -║ in Orca manifest (-Xmx1500m) so it cannot starve PowerDNS / Infisical. Escape hatch ║ -║ if the heap fight shows up: flip placement.node to a new vm-edge-identity VM inside ║ -║ the SAME breakpilot-edge cluster — no schema migration, just a container move. ║ -║ ║ -║ KC instance is REPURPOSED from the existing CERTifAI Keycloak at M2.1 (realm export ║ -║ + user database move; hostname swap), not stood up fresh. ║ -╚══════════════════════════════════════════════════════════════════════════════════════════╝ - -╔══════════════════════════════════════════════════════════════════════════════════════════╗ -║ CONTROL PLANE (cluster: breakpilot-control, on vm-control) ║ -║ ║ -║ Owns / defines: ║ -║ RPO (tenant) — tenant registry & compliance schemas RPO ≤ 6h ║ -║ RPO (ERPNext) — sales orders, invoices RPO ≤ 6h ║ -║ AUDIT_TRAIL — all portal actions (invites, IdP changes, impersonations) ║ -║ AVAILABILITY — portal ≥ 99.5%; ERPNext ≥ 99% (internal) ║ -║ RTO (portal) — ≤ 10 min ║ -║ RTO (ERPNext) — ≤ 60 min ║ -║ ║ -║ Co-tenant note: ERPNext + Portal + Stalwart on one VM. Orca resource limits enforced: ║ -║ portal: 1 GB memory cap ║ -║ erpnext: 6 GB memory cap ║ -║ mariadb: 3 GB memory cap ║ -║ stalwart: 1 GB memory cap ║ -║ tenant-registry: 500 MB ║ -║ ║ -║ Stage callers: vm-app-stage in breakpilot-app calls THIS tenant-registry under ║ -║ tenant.kind = "stage" (read-only for stage tenants). No duplicated tenant-registry. ║ -╚══════════════════════════════════════════════════════════════════════════════════════════╝ - -╔══════════════════════════════════════════════════════════════════════════════════════════╗ -║ APP PLANE (was "Data Plane"; cluster: breakpilot-app, on vm-app-prod + vm-app-stage) ║ -║ ║ -║ Owns / defines: ║ -║ DATA_RESIDENCY — all customer data (MongoDB, pg-app, MinIO) must stay EU ║ -║ RPO (product) — compliance records ≤ 6h; chat history ≤ 24h ║ -║ DATA_ISOLATION — every query scoped by org_id/tenant_id ║ -║ AUDIT_TRAIL — product-level actions ║ -║ AVAILABILITY — CERTifAI ≥ 99.5%; compliance ≥ 99.5% ║ -║ ║ -║ Co-tenant note: vm-app-prod is the SCALE driver. When it hits 80% RAM, bump flavor ║ -║ (m2.medium → m2.large → m2.xlarge). See §13 Growth Trajectory. ║ -║ ║ -║ Stage VM (vm-app-stage) lives in the SAME cluster — same config, different physical ║ -║ workload. Stage authenticates against the prod Identity plane (breakpilot-edge KC) ║ -║ and reads tenant config from the prod Control plane (breakpilot-control ║ -║ tenant-registry) — never duplicates identity or control. ║ -╚══════════════════════════════════════════════════════════════════════════════════════════╝ - -╔══════════════════════════════════════════════════════════════════════════════════════════╗ -║ INFRA PLANE (cluster: breakpilot-edge, on vm-edge, alongside Identity) ║ -║ ║ -║ Owns / enforces ALL of: ║ -║ BACKUP — executes all backup jobs (pg_dump, mongodump, mc mirror) ║ -║ IaC — ALL services declared in Orca config; no manual prod changes ║ -║ IMMUTABILITY — config changes: Gitea commit → Gitea Actions → Orca API only ║ -║ SECRET_HYGIENE— Infisical (on vm-edge); provisions machine identities ║ -║ NETWORK — Orca-Proxy rules; VM firewall; no direct VM public exposure ║ -║ DATA_RESIDENCY— VM region = SysEleven DUS2; backups geo-redundant DUS2↔HAM1 ║ -║ AVAILABILITY — Orca restart policies, health checks ║ -║ COLD_START — enforces startup ordering (see §10 Scenario F) ║ -║ STAGE_ISOLATION— Infisical secret-path scoping for stage_app identity ║ -║ ║ -║ Per-cluster note: each of the three cluster repos has its own [backup] block + S3 ║ -║ bucket. A runaway backup on breakpilot-app cannot fill breakpilot-edge's bucket. ║ -╚══════════════════════════════════════════════════════════════════════════════════════════╝ +╔════════════════════════════════════════════════════════════════════════════════════════╗ +║ IDENTITY PLANE (core cluster, breakpilot-infra-vm1) ║ +║ AVAILABILITY ≥ 99.5% (root dependency of both environments) · RTO ≤ 15 min ║ +║ AUDIT_TRAIL realm events · DATA_RESIDENCY EU · STAGE_ISOLATION separate realms ║ +║ Note: one Keycloak instance serves company SSO + both platform realms (RISK-3). ║ +╠════════════════════════════════════════════════════════════════════════════════════════╣ +║ CONTROL PLANE (platform cluster, per env node) ║ +║ RPO (tenant registry) ≤ 6h · RPO (ERPNext, core) ≤ 24h · AUDIT_TRAIL portal actions ║ +║ AVAILABILITY portal ≥ 99.5%, registry ≥ 99.5%, ERPNext ≥ 99% (internal) ║ +║ RTO portal ≤ 10 min · registry ≤ 5 min · ERPNext ≤ 60 min ║ +║ ERP LINK: outbox depth < 100 and reconcile age < 30 min are SLOs (alerted) ║ +╠════════════════════════════════════════════════════════════════════════════════════════╣ +║ APP PLANE (platform cluster, per env node) ║ +║ DATA_RESIDENCY EU · DATA_ISOLATION per-tenant DB or tenant_id on every query ║ +║ AVAILABILITY Prüfwerk ≥ 99.5%, Firmwerk cloud ≥ 99.5%, licence endpoint ≥ 99.9% ║ +║ (CLIs tolerate 30 days of licence-endpoint outage by design) ║ +║ Co-tenant note: the prod node is the scale driver; bump flavor at 80% RAM. ║ +╠════════════════════════════════════════════════════════════════════════════════════════╣ +║ INFRA PLANE (both clusters) ║ +║ BACKUP per cluster bucket · IaC all services in Gitea · IMMUTABILITY git → orca deploy║ +║ SECRET_HYGIENE project-scoped Orca secrets, Infisical for signing keys ║ +║ NETWORK per-node ingress, Hetzner firewall, private network for master↔agent ║ +║ DATA_RESIDENCY Hetzner DE · COLD_START ordering (§10 F) · STAGE_ISOLATION (§2) ║ +╚════════════════════════════════════════════════════════════════════════════════════════╝ ``` --- @@ -346,357 +263,152 @@ Planes are the **SLA + ownership abstraction**; clusters are the **operational u ## 7. SLA Table ``` -┌───────────────────────┬──────────────┬─────────┬─────────┬────────────────────────────────┐ -│ Service │ Availability │ RTO │ RPO │ Host VM │ -├───────────────────────┼──────────────┼─────────┼─────────┼────────────────────────────────┤ -│ Orca-Proxy │ 99.9% │ 5 min │ N/A │ vm-edge │ -│ PowerDNS │ 99.9% │ 5 min │ N/A │ vm-edge │ -│ Keycloak │ 99.5% │ 15 min │ 6h │ vm-edge (root auth dep) │ -│ Infisical │ 99.5% │ 30 min │ 24h │ vm-edge (running svcs survive) │ -│ Gitea │ 99% │ 2h │ 24h │ vm-edge (dev machines mirror) │ -│ Customer Portal │ 99.5% │ 10 min │ N/A │ vm-control │ -│ Tenant Registry │ 99.5% │ 10 min │ 6h │ vm-control │ -│ ERPNext │ 99% │ 60 min │ 6h │ vm-control (internal only) │ -│ Frappe HD │ 99% │ 60 min │ 24h │ vm-control │ -│ MariaDB │ 99.5% │ 20 min │ 6h │ vm-control │ -│ Stalwart Mail │ 99% │ 60 min │ 24h │ vm-control │ -│ CERTifAI │ 99.5% │ 10 min │ 24h │ vm-app-prod │ -│ MongoDB │ 99.5% │ 20 min │ 24h │ vm-app-prod │ -│ LiteLLM │ 99% │ 5 min │ N/A │ vm-app-prod │ -│ backend-compliance │ 99.5% │ 10 min │ 6h │ vm-app-prod │ -│ ai-compliance-sdk │ 99.5% │ 10 min │ 6h │ vm-app-prod │ -│ pg-app │ 99.9% │ 20 min │ 6h │ vm-app-prod (SPOF — RISK-1) │ -│ MinIO │ 99.5% │ 30 min │ 24h │ vm-app-prod │ -│ Qdrant │ 99% │ 2h │ 24h │ vm-app-prod (rebuildable) │ -│ stage (any service) │ 95% │ best ef.│ N/A │ stage (ephemeral; no SLA) │ -└───────────────────────┴──────────────┴─────────┴─────────┴────────────────────────────────┘ +┌────────────────────────────┬──────────────┬─────────┬─────────┬──────────────────────────────┐ +│ Service │ Availability │ RTO │ RPO │ Node │ +├────────────────────────────┼──────────────┼─────────┼─────────┼──────────────────────────────┤ +│ Keycloak │ 99.5% │ 15 min │ 6h │ core master (root auth dep) │ +│ Harbor │ 99% │ 30 min │ 24h │ core master (deploys only) │ +│ Gitea │ 99% │ 2h │ 24h │ core master │ +│ LiteLLM │ 99% │ 5 min │ N/A │ core master (soft dep) │ +│ ERPNext + Helpdesk │ 99% │ 60 min │ 24h │ core workhorse (internal) │ +│ Customer Portal │ 99.5% │ 10 min │ N/A │ platform prod │ +│ Tenant Registry + licences │ 99.9% │ 5 min │ 6h │ platform prod │ +│ pg-prod │ 99.9% │ 20 min │ 6h │ platform prod (RISK-4) │ +│ Prüfwerk (dashboard/agent) │ 99.5% │ 10 min │ 24h │ platform prod │ +│ Prüfwerk MCP │ 99.5% │ 10 min │ N/A │ platform prod │ +│ Firmwerk cloud-server │ 99.5% │ 10 min │ 24h │ platform prod │ +│ Werkbank runner │ 99% │ 30 min │ N/A │ platform prod (stateless) │ +│ stage (any service) │ 95% │ best ef.│ 7d │ platform stage (no SLA) │ +└────────────────────────────┴──────────────┴─────────┴─────────┴──────────────────────────────┘ ``` +Measured via `status.breakpilot.com` (Gatus, 3-fail, 30-day rolling) per `Breakpilot SKU + SLA`. + --- ## 8. IaC Constraint (Orca) -Every production service declared in Orca config. No exceptions. - -### Rules +Every platform service is declared in `platform/orca-platform`, every core service in `sharang/orca-infra`. No exceptions. ``` -1. ALL containers run via Orca manifests committed to Gitea - → /orca/manifests/{vm-name}/{service-name}.toml - → Changes go through: Gitea PR → Gitea Actions lint → Orca API apply +1. ALL containers run via Orca service files committed to Gitea + → platform: services//service.toml (Orca-native TOML; one [[service]] per container) + → Changes go through: Gitea PR → CI (validate.sh, gitleaks, trivy) → merge → `git pull && orca deploy` on the master + → Image changes go through: product CI → Harbor → signed webhook → orca redeploy -2. NO manual docker run / docker-compose up on any production VM - → SSH to prod VMs allowed for debugging only; no state changes +2. EVERY platform service is pinned: [service.placement] node = "bp-platform-stage" | "bp-platform-prod" + → validate.sh fails the PR otherwise (unpinned = lands on the master) -3. Secrets are NEVER in Orca manifests - → Manifests reference Infisical paths, not values - → Bootstrap exception: Keycloak DB URI in Orca env (Keycloak runs ON vm-edge alongside - Infisical, so chicken-and-egg is solved by Orca env file, not Infisical lookup) +3. Service names are unique cluster-wide and suffixed by environment (-stage / -prod) + → stage and prod are separate projects with separate Docker networks -4. Restart policy: always (Orca restarts crashed containers with exponential backoff) - → Health check per service (HTTP /health or TCP probe) +4. Secrets are project-scoped: `orca secrets set --project

KEY value` + → production values are NEVER set globally (project secrets fall back to global) + → Orca env references `${secrets.KEY}` only; no values in service files -5. Resource limits MANDATORY in every manifest - → On a 3-VM prod, co-tenant noise is the single biggest risk; limits are non-negotiable - → See §6 Plane ownership "Co-tenant note" boxes for the per-service caps +5. Resource limits MANDATORY: resources.memory on every service (validate.sh) -6. Orca controller state itself is recoverable - → Manifest files in Gitea = desired state - → Loss of Orca controller = re-apply manifests from Gitea, services continue running +6. Restart policy: always; health check per service (HTTP or TCP) -7. Stage app gets its own Infisical scope - → /stage/* path; no prod-DB credentials reach this scope - → Enforced at Infisical machine-identity level, not in app code -``` +7. Images: product images are pushed with :sha- and :latest; `orca redeploy` re-pulls. + Pin by digest for cutovers. Prod promotion = retag :sha-… as :prod- (prod plan). -### Gitea Actions pipeline for infra changes +8. NO manual docker run / compose on any node. SSH for debugging only. Every node has + `docker login repo.breakpilot.com` done once at provisioning. -``` -infra change committed to Gitea - │ - ├── lint: validate Orca manifest schema - ├── diff: show what changes will be applied (orca plan) - ├── (manual approval gate for vm-edge changes — touches auth root) - └── apply: POST to Orca Controller API → rolling update +9. Orca control plane state is recoverable: service files in Gitea = desired state; + losing the master = re-install Orca on the same VM, restore ~/.orca from backup, `orca deploy`. ``` --- ## 9. Dependency Graph -Arrows = "requires to function." Dashed = soft (degrades, doesn't fail). -**Intra-VM dependencies elided** for clarity (e.g. Keycloak ↔ pg-keycloak are on the same host and start together). - ``` - EXTERNAL - AI APIs - (OpenAI / Anthropic) - │ - │ (soft) - ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ vm-edge (Identity + Infra) │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ pg-keycloak ──► keycloak │ │ -│ │ pg-infisical ─► infisical ◄── (all VMs pull on startup) │ │ -│ │ redis-infis ──► infisical │ │ -│ │ (sqlite) ─────► gitea │ │ -│ │ powerdns-auth (no deps) │ │ -│ │ orca-proxy (route table only; backends are remote) │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ Keycloak JWKS │ Infisical /secrets │ -│ │ │ │ -└────────────────────────────┼────────────────┼────────────────────┘ - ▼ ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ vm-control (Control) │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ mariadb + redis-erp ──► erpnext + frappe-hd │ │ -│ │ (intra) ─────────────► stalwart │ │ -│ │ ──────────────────────► customer-portal │ │ -│ │ ──────────────────────► tenant-registry ──► pg-app (vm-app-prod)│ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ tenant-registry API │ -└────────────────────────────┼─────────────────────────────────────┘ - ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ vm-app-prod (Data) │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ mongodb ───► certifai ◄── (vm-edge JWKS, vm-edge secrets) │ │ -│ │ litellm ───► certifai, ai-compliance-sdk │ │ -│ │ pg-app ────► tenant-registry-on-vm-control, backend-compl,│ │ -│ │ ai-compliance-sdk │ │ -│ │ qdrant ────► ai-compliance-sdk │ │ -│ │ minio ────► backend-compliance │ │ -│ │ backend-compliance ──► admin-compliance │ │ -│ └────────────────────────────────────────────────────────────┘ │ -└──────────────────────────────────────────────────────────────────┘ - -┌──────────────────────────────────────────────────────────────────┐ -│ stage (App plane only) │ -│ Calls vm-edge:8443 (KC) + vm-control:587 (Stalwart submission) │ -│ Calls Polar SANDBOX (never prod Polar webhook URL) │ -│ Its own ephemeral DBs; cannot read prod data │ -└──────────────────────────────────────────────────────────────────┘ + EXTERNAL AI APIs + │ (soft) + ▼ +┌───────────────────── CORE cluster ─────────────────────────────────────────┐ +│ keycloak-db ─► keycloak harbor litellm infisical erpnext │ +│ │ │ │ │ │ │ +└─────────────────────┼───────────┼────────────┼───────────┼───────────┼──────┘ + JWKS/OIDC ────┘ images ──┘ LLM ─────┘ signing ─┘ REST+webhooks (prod) + ▼ ▼ +┌───────────────────── PLATFORM cluster · one node per env ──────────────────┐ +│ pg-{env} ──► tenant-registry-{env} ◄──── erpnext-mock (stage) / erp (prod)│ +│ │ entitlements/check, api-keys/verify, usage, licences│ +│ ├──► portal-{env} │ +│ ├──► pruefwerk-agent ◄── pruefwerk-mongo, browserless, │ +│ │ │ soft-plc, plc-sim │ +│ │ ├──► pruefwerk-dashboard, pruefwerk-mcp, docs │ +│ │ └──► werkbank-runner (leases jobs) │ +│ └──► firmwerk-cloud ◄── firmwerk-mongo │ +│ CLIs (customer machines) ──► licence endpoint on tenant-registry │ +└────────────────────────────────────────────────────────────────────────────┘ ``` -### Simplified critical path (customer login → product use) +Critical path (customer login → product use): Strato DNS → node ingress → portal → Keycloak (core) → tenant-registry → product host → Keycloak (SSO) → product → tenant-registry (`entitlements/check`, cached). +--- + +## 10. Failure Scenarios + +### A — Core master (Keycloak, Harbor, Gitea, LiteLLM) fails — HIGHEST SEVERITY ``` - DNS (vm-edge PowerDNS) - │ - ▼ - orca-proxy (vm-edge) - │ - ├──► keycloak (vm-edge) ──► pg-keycloak (intra-VM) - │ - └──► customer-portal (vm-control) - ├──► tenant-registry (vm-control) ──► pg-app (vm-app-prod) - ├──► certifai (vm-app-prod) ──► mongodb (intra-VM) - └──► backend-compliance (vm-app-prod) ──► pg-app (intra-VM) - ──► ai-sdk ──► qdrant + minio - ──► litellm ──► [external AI APIs] +Impact: No new logins on either environment (JWTs expire within the access-token TTL); no deploys; + no LLM features. Running product sessions continue until token expiry. CLIs keep working + on their licence tokens (30-day ladder). ERPNext (workhorse) unaffected. +Recovery: Restore VM / Orca on the core master from Hetzner snapshot + nightly backup. RTO target 15 min. +Mitigation: Hetzner snapshot schedule for the core master; runbook; RISK-1. +``` +### B — bp-platform-stage (cluster master) fails +``` +Impact: Staging down. Production containers keep running but cannot be deployed/redeployed; + webhooks 503 until the master is back. No customer impact. +Recovery: Rebuild VM, reinstall Orca, restore ~/.orca, `orca deploy`; prod agent re-joins. RTO 30 min. +Mitigation: RISK-2; consider a small dedicated control VM at Tier B. +``` +### C — bp-platform-prod fails +``` +Impact: All products, portal, registry and licence endpoint down for production. + CLIs degrade along the ladder only after 7 days without heartbeat. +Recovery: Rebuild from snapshot + nightly backup; re-join; redeploy. RTO 30 min, RPO ≤ 6h for pg-prod. +Mitigation: Hetzner snapshots; tested restore drill (M-MIG-8); RISK-4. +``` +### D — LiteLLM fails: Prüfwerk LLM triage and Werkpilot degrade; scans and CRUD unaffected. Soft. +### E — Stage compromised or buggy: nothing reaches prod (separate VM, realm, secrets, mock ERP). Roll back image. RISK-5. +### F — Cold start (platform node): databases → tenant-registry (needs Keycloak up on core) → portal, products. Orca `depends_on` + health checks; 3–5 min. Core cold start unchanged from the as-built runbook. +### G — Tenant Registry fails +``` +Impact: Portal tenant lookup fails (cached 60 s); products' entitlement cache expires after 60 s + → they fail CLOSED (deny) per contract §9.1; licence heartbeats fail (ladder tolerates 7 days); + usage events buffered client-side and retried. +Recovery: Restart; pg-{env} must be healthy. RTO ≤ 5 min. +``` +### H — ERPNext down or unreachable from the platform +``` +Impact: NO customer impact. Outbox accumulates (customer upserts, leads, usage records); webhooks + are not received; the ladder does not change. Backstage /system/erp-link alerts at + outbox depth > 100 or reconcile age > 30 min. +Recovery: ERPNext restore per core runbook; outbox drains; reconcile repairs any missed webhook. ``` --- -## 10. Failure Scenarios and Deadlock Analysis - -### Scenario A — vm-edge fails (HIGHEST SEVERITY) +## 11. Cross-Dependency Summary ``` -Impact: TOTAL outage. Nothing reachable from internet. - No DNS. No TLS. No auth. No new logins. Running JWTs expire within 15 min, - then ALL services start returning 401. - Backstage and customer portal both fully blocked. - Stage also blocked (depends on prod Keycloak). -Cascade: T+0: DNS fails → orca-proxy unreachable - T+5m: existing JWTs still valid; portal cached → partial reads work - T+15m: JWTs expire → full outage -Deadlock: None — services downstream don't deadlock, they just fail closed -Recovery: 1. Spin up vm-edge-spare (cold standby, same Orca config) — ~3 min provision - 2. Restore pg-keycloak + pg-infisical from latest backup — ~5 min - 3. Swap registrar NS records to spare IP (TTL 60s) — ~2 min propagation - 4. Restart all services on vm-edge-spare via Orca apply — ~3 min - Total RTO target: 15 min -Mitigation: COLD STANDBY vm-edge-spare. Same Orca config committed in Gitea. - Provision cost when idle: €0 (only billed when running). - Test recovery quarterly. -Severity: CRITICAL — single host owns 3 root dependencies (DNS, auth, secrets) -Cost of fix at Tier C: split vm-edge into vm-edge + vm-identity + vm-secrets - (back toward original 7-VM design) — €100/mo extra -``` - -### Scenario B — vm-control fails (NEW — consequence of plane consolidation) - -``` -Impact: customer-portal: DOWN → /[slug]/* all return 503 - tenant-registry: DOWN → Keycloak protocol-mapper for products claim breaks - → users can log in but see "No active products" - ERPNext + Frappe HD: DOWN → we cannot create sales orders or read tickets - Stalwart: DOWN → no outbound emails (trial nudges, exports, ticket replies) - MariaDB: DOWN → ERPNext queries fail; backups paused - Products (CERTifAI, compliance): UNAFFECTED (on vm-app-prod, JWTs still validate) - Existing logged-in users: can use products directly via product subdomain - IF they bookmark it; portal home is 503. -Cascade: T+0: portal 503; new tenant onboarding blocked (registry down) - T+15m: existing JWTs missing refreshed products claim - T+1h: trial emails not sent → trial nudge cadence breaks -Deadlock: None -Recovery: Restart vm-control containers via Orca. If MariaDB corrupt: restore mysqldump. - RTO target: 10 min (portal) / 60 min (ERPNext) -Mitigation: Multiple services co-hosted = single failure hits many SLAs. - Resource limits in Orca prevent ERPNext OOM from killing portal. - Quarterly drill: deliberately stop portal, measure recovery. -Severity: HIGH — three services down at once, but products keep serving customers -Cost of fix at Tier B/C: split vm-control → vm-portal + vm-ops (ERPNext) - — €64/mo extra at m2.small -``` - -### Scenario C — vm-app-prod fails - -``` -Impact: tenant-registry queries: FAIL (pg-app down) → portal returns 503 for tenant lookup - customer-portal: DEGRADED (login works, dashboard fails) - CERTifAI: COMPLETELY DOWN - backend-compliance + ai-sdk + admin: COMPLETELY DOWN - ERPNext + Stalwart: UNAFFECTED -Cascade: T+0: products down; portal degraded - T+15m: support tickets pile up - Note: prod is partial — users see error pages but ERPNext + auth still work -Recovery: Restart vm-app-prod containers. If pg-app corrupt: restore from pg_dump (RPO 6h). - RTO target: 20 min -Mitigation: This is the SCALE-event VM. RISK-1 below makes this the worst SPOF: - one pg-app instance owns tenant_registry + compliance schemas. - HIGH PRIORITY fix: split pg-app into separate clusters at Tier B/C transition. -Severity: HIGH — products down, business operations (ERPNext) still work so we can - contact customers -``` - -### Scenario D — LiteLLM fails - -``` -Impact: CERTifAI: AI features fail (summarization, chat completion). - CERTifAI dashboard, sessions: UNAFFECTED. - compliance AI generation: FAILS (DSFA/TOM/VVT generation blocked). - Compliance CRUD: UNAFFECTED. -Cascade: Soft degradation only. Products show "AI features temporarily unavailable" banner. -Deadlock: None. -Recovery: Restart LiteLLM on vm-app-prod (stateless, ~30s). -Severity: MEDIUM — graceful degradation by design -``` - -### Scenario E — vm-app-stage compromised or buggy - -``` -Impact: On stage itself: stage portal serves bad data; stage testers see errors. - On prod: NONE if isolation rules in §2 are intact. - Worst case if isolation breaks: - - Stage code tries to call prod pg-app → fails (no creds in /stage/* Infisical) - - Stage emits real email → blocked by Stalwart recipient filter - - Stage triggers Polar charge → goes to sandbox, no real money -Cascade: None to prod by design. -Recovery: Roll back stage to previous image via Orca. RTO target: 5 min. -Mitigation: The 5 enforcement rules in §2 are the load-bearing controls. Verify quarterly - via deliberate red-team: try to write to prod pg-app from stage and confirm 401. -Severity: LOW (in prod) / HIGH (on stage, but stage SLA is 95%) -``` - -### Scenario F — Full Cold Start (Power Loss, All VMs Restart Simultaneously) - -``` -Three VMs boot at once. Services must start in dependency order or services -crash-loop until their deps are ready. - -DEADLOCK RISK: vm-control services (portal, tenant-registry) start before vm-app-prod - services (pg-app, certifai, compliance). They'll crash-loop ~2-5min - with backoff retries. - Same for ERPNext on vm-control trying to reach Keycloak on vm-edge. - -RESOLUTION: Orca enforces cross-VM startup ordering via health-check dependencies. - Bootstrap exception: Keycloak DB URI in Orca env on vm-edge (not from - Infisical — chicken-and-egg solved). - -Required cold start sequence: - - Phase 0 — Data roots on vm-app-prod (parallel): - pg-app, mongodb, qdrant, minio - Phase 0 — Data roots on vm-control (parallel): - mariadb, redis-erpnext - Phase 0 — Data roots on vm-edge (parallel): - pg-keycloak, pg-infisical, redis-infisical - - Phase 1 — Secrets + DNS on vm-edge: - infisical (needs: pg-infisical, redis-infisical) - powerdns-auth (no deps) - - Phase 2 — Identity on vm-edge: - keycloak (needs: pg-keycloak [Phase 0], infisical [Phase 1]) - gitea (needs: sqlite; ready from Phase 0) - - Phase 3 — Control on vm-control + Data services on vm-app-prod (parallel): - tenant-registry (needs: keycloak [Phase 2], pg-app [Phase 0, remote]) - erpnext + frappe-hd (needs: mariadb, redis-erpnext [Phase 0], keycloak [Phase 2]) - stalwart (needs: infisical [Phase 1]) - litellm (needs: infisical) - certifai (needs: keycloak, mongodb, litellm) - backend-compliance (needs: keycloak, pg-app) - ai-compliance-sdk (needs: pg-app, qdrant, litellm) - admin-compliance (needs: backend + sdk) - - Phase 4 — Customer-facing on vm-control: - customer-portal (needs: keycloak, tenant-registry) - - Phase 5 — Gateway on vm-edge (last): - orca-proxy (waits for all backends healthy before opening listener) - -Estimated cold-start time: 6-10 minutes (faster than 7-VM since less network roundtrip) -``` - -### Scenario G — Tenant Registry fails - -``` -Impact: Portal cannot resolve tenant from subdomain → /[slug]/* all 503 - Keycloak protocol mapper cannot get products claim → JWT missing field - → users can log in but see "No active products" - Products (CERTifAI, compliance) themselves: UNAFFECTED if already authenticated -Cascade: New logins degraded. - Existing sessions continue. -Deadlock: None. -Recovery: Restart tenant-registry on vm-control. pg-app on vm-app-prod must be healthy. - RTO target: ≤ 60s -Mitigation: Portal caches slug → tenant mapping with 60s TTL. - Short outage invisible to customers. -Severity: MEDIUM -``` - ---- - -## 11. Cross-Dependency Summary Table - -``` - Needs → │PG-KC│PG-Inf│PG-App│Mongo│Maria│Redis│Minio│Qdrant│ KC │Infis│Lit. │T.Reg│ -─────────────────────┼─────┼──────┼──────┼─────┼─────┼─────┼─────┼──────┼─────┼─────┼─────┼─────┤ -keycloak │ ● │ │ │ │ │ │ │ │ │ ◐* │ │ │ -infisical │ │ ● │ │ │ │ ● │ │ │ │ │ │ │ -gitea │ │ │ │ │ │ │ │ │ │ ● │ │ │ -tenant-registry │ │ │ ● │ │ │ │ │ │ ● │ ● │ │ │ -customer-portal │ │ │ │ │ │ │ │ │ ● │ ● │ │ ● │ -erpnext │ │ │ │ │ ● │ ● │ │ │ ● │ ● │ │ │ -frappe-hd │ │ │ │ │ ● │ ● │ │ │ │ ● │ │ │ -stalwart │ │ │ │ │ │ │ │ │ │ ● │ │ │ -certifai │ │ │ │ ● │ │ │ │ │ ● │ ● │ ◐ │ │ -litellm │ │ │ │ │ │ │ │ │ │ ● │ │ │ -backend-compl. │ │ │ ● │ │ │ │ │ │ ● │ ● │ │ │ -ai-compl-sdk │ │ │ ● │ │ │ │ │ ● │ │ ● │ ◐ │ │ -admin-compl. │ │ │ │ │ │ │ │ │ │ │ │ │ -orca-proxy │ │ │ │ │ │ │ │ │ │ │ │ │ -stage-app │ │ │ │ │ │ │ │ │ ● │ ◑ │ │ ◑ │ - -● = hard dependency (cannot start without) -◐ = soft dependency (starts, features degrade) -◑ = stage-only read-mostly dependency (writes blocked by Infisical scope) -◐*= bootstrap exception (Keycloak DB URI in Orca env on vm-edge, not Infisical) + Needs → │ KC │ pg-env │ mongo │ registry │ ERP │ LiteLLM │ Harbor │ Infisical │ +─────────────────────┼────┼────────┼───────┼──────────┼─────┼─────────┼────────┼───────────┤ +tenant-registry │ ● │ ● │ │ │ ◐ │ │ │ ◐ (licence key bootstrap) │ +portal │ ● │ │ │ ● │ │ │ │ │ +pruefwerk-agent │ ● │ │ ● │ ● │ │ ◐ │ │ │ +pruefwerk-dashboard │ ● │ │ │ │ │ │ │ │ +werkbank-runner │ │ │ │ ◐ │ │ │ │ │ +firmwerk-cloud │ ● │ │ ● │ ● │ │ │ │ │ +werkpilot (CLI) │ ◐ │ │ │ ◐ │ │ ● │ │ │ +all (deploy time) │ │ │ │ │ │ │ ● │ │ +● hard ◐ soft (degrades / cached / buffered) ``` --- @@ -704,92 +416,70 @@ stage-app │ │ │ │ │ │ │ ## 12. Open Infrastructure Risks (Priority Order) ``` -RISK-1 pg-app (vm-app-prod) is a single instance serving tenant_registry + compliance schemas. - One crash blocks portal AND compliance product simultaneously. - → Mitigation: split into pg-registry + pg-compliance at Tier B (200 customers). - Move pg-registry to its own DBaaS PostgreSQL cluster (€213/mo). - Priority: HIGH — fix before 100 customers; flagged also in COST_PLAN.md - -RISK-2 vm-edge is a single VM owning 3 root dependencies (DNS, auth, secrets). - Failure = total external outage. Highest blast radius in the system. - → Mitigation: - Phase A: cold-standby vm-edge-spare (idle cost €0; tested quarterly) - Phase B (Tier C, 500 cust): split vm-edge into vm-edge + vm-identity + vm-secrets +RISK-1 Core master is a single VM owning auth, git, image registry and LLM. + → Hetzner snapshot schedule + tested restore; long-term: move Keycloak to its own node. Priority: HIGH -RISK-3 vm-control hosts 5 service groups (portal, tenant-registry, ERPNext, Frappe HD, - Stalwart). Co-tenant noise risk; one OOM kills the others. - → Mitigation: - Phase A: hard Orca resource limits per service (see §6 co-tenant notes) - Phase B (Tier B): split vm-control → vm-portal + vm-ops at €64/mo extra +RISK-2 The staging VM is the platform cluster's only control plane and Orca tokens are cluster-wide + (a stage deployer token can deploy prod). + → Never store the deployer token where stage-only CI can read it; prod webhooks use their own + HMAC secret; revisit a dedicated control VM at Tier B. + Priority: HIGH (until prod exists: MEDIUM) + +RISK-3 One Keycloak instance serves company SSO and both platform realms. + → Realm-level rate limits per client; realm exports in git; RTO 15 min runbook. Priority: MEDIUM -RISK-4 Keycloak is a single instance with no clustering. - Any Keycloak outage = total auth failure within JWT TTL. - → Mitigation: short-term: tested runbook + 15min RTO target - long-term: Keycloak active-passive cluster (Phase 2, on split vm-identity) +RISK-4 pg-prod is a single instance for tenants, subscriptions, licences and audit. + → 6-hourly dumps in addition to nightly; split audit into its own DB when > 100 tenants. Priority: MEDIUM -RISK-5 Stage isolation depends on 5 enforcement controls (see §2 table). - If any one breaks, stage code can affect prod customers. - → Mitigation: quarterly red-team verification of each control. - Especially: Infisical secret-path scoping and Stalwart recipient filter. - Priority: MEDIUM — easy to forget once it's working +RISK-5 Stage isolation rests on the six controls in §2. + → Quarterly red-team: try to read a prod secret from a stage project; try a stage JWT on prod. + Priority: MEDIUM -RISK-6 Infisical downtime during multi-VM restart causes delayed cold start. - → Mitigation: Orca startup ordering + bootstrap secrets for Keycloak only - Priority: LOW — documented runbook; cold start is rare +RISK-6 ERPNext → registry webhooks have no guaranteed delivery (Frappe retries are best-effort). + → Outbox for the up direction, idempotent webhook receiver + 15-min reconcile for the down + direction, alerting on reconcile age. Tested in M-MIG-8 (kill worker, replay). + Priority: HIGH until the M-MIG-8 tests pass, then LOW -RISK-7 ERPNext → Tenant Registry webhook has no guaranteed delivery. - Failed activation = tenant not active after contract signed. - → Mitigation: Frappe retry + idempotent /activate endpoint + manual Backstage trigger +RISK-7 Orca project secrets fall back to global secrets; a missing stage key silently resolves to a + global value. + → No global secrets in the platform cluster at all; validate.sh greps service files for + `${secrets.` keys and checks they exist in the project scope (deploy-time check). + Priority: MEDIUM + +RISK-8 Backups unencrypted (orca #117) and single-provider. + → age-encrypt the S3 copy via `[secrets] age_recipients`; second provider before prod. + Priority: MEDIUM + +RISK-9 HTTP-01 cutovers leave a short TLS gap when a hostname moves between nodes. + → Lower TTLs 24h before; cut over in a night window; verify with `curl -I` immediately. Priority: LOW -RISK-8 LiteLLM calls external AI APIs (OpenAI / Anthropic). - → Mitigation: LiteLLM fallback routing; products degrade gracefully. - Priority: LOW — external dependency, by design +RISK-10 LiteLLM calls external AI APIs. → fallback routing; products degrade gracefully. LOW ``` --- -## 13. Growth Trajectory — when to add VMs - -The locked 4-VM topology is right for 5–~200 customers. Past that, expect to add VMs back in this order: +## 13. Growth Trajectory ``` -Tier A (5–200 cust): 4 VMs as locked €192/mo compute (36M upfront) - ↓ -Tier B (200–500): Bump vm-app-prod m2.med → m2.large +€64/mo - Add cold-standby vm-edge-spare +€0 (idle, paid only on swap) - ↓ -Tier C (500–1000): Split vm-app-prod: vm-app-prod + vm-app-prod-db +€64/mo - (postgres-app moves to its own VM, or DBaaS cluster +€213/mo) - Split vm-control: vm-control + vm-ops +€64/mo - (ERPNext + MariaDB + Stalwart move to vm-ops) - ↓ -Tier D (1000–2000): Split vm-edge: vm-edge + vm-identity + vm-secrets +€96/mo - HA Keycloak active-passive on 2× vm-identity +€32/mo - Octavia Load Balancer Double Instance +€58/mo - vm-app-prod m2.large → m2.xlarge or 2× +€128–256/mo - ↓ - Final topology ≈ 8 prod VMs + DBaaS +Tier A (launch, ≤ 50 cust): stage CX43 + prod ≥16 GB dedicated ≈ €60–90/mo platform compute +Tier B (50–200): bump prod flavor; small control VM as Orca master (RISK-2); + Hetzner Volume for prod data; second S3 provider for backups +Tier C (200–500): split prod: app node + db node (pg, mongo); Keycloak to its own core node +Tier D (500+): second prod app node (Orca pins per product), Hetzner LB in front ``` -Each step is justified by a measurable signal (>80% RAM, >70% CPU, sustained queue depth, or a specific outage scenario). Never split preemptively. +Each step is justified by a measurable signal (> 80% RAM, > 70% CPU, sustained queue depth, or a specific outage). Never split preemptively. --- -## 14. Cost summary (see COST_PLAN.md for full breakdown) +## 14. Cost summary -| Mode | Compute €/mo | Storage €/mo | Network €/mo | Total net | + 19% VAT | -|---|---:|---:|---:|---:|---:| -| On-Demand | 434.50 | 112 | 2.92 | 549.42 | 653.81 | -| 12-month commit | 295.20 | 112 | 2.92 | 410.12 | 488.04 | -| 36-month no upfront | 216.00 | 112 | 2.92 | 330.92 | 393.79 | -| 36-month upfront | 192.00 | 112 | 2.92 | 306.92 | 365.23 | - -Plus €6,912 net one-time payment if signing 36M-upfront for the compute portion. +See `COST_PLAN.md` (Hetzner). Platform stage ≈ €30/mo; prod sized at prod planning; core cluster unchanged. --- -*End of document. Review quarterly or after any significant infrastructure change. Topology last locked 2026-05-18.* +*End of document. Review after production go-live or any significant infrastructure change. Topology revised 2026-09-11.* diff --git a/PLATFORM_ARCHITECTURE.md b/PLATFORM_ARCHITECTURE.md index a2d384b..95fe7b3 100644 --- a/PLATFORM_ARCHITECTURE.md +++ b/PLATFORM_ARCHITECTURE.md @@ -1,91 +1,143 @@ # Platform Architecture — B2B Customer Portal -**Status:** Design Draft +**Status:** Revised design (2026-09 revision) **Authors:** Sharang, Benjamin -**Date:** 2026-05-11 (cluster split: 2026-06-30) +**Date:** 2026-05-11 · cluster split 2026-06-30 · **revised 2026-09-11** --- -> **2026-06-30 cluster-split decision.** The four-plane vocabulary in this document still applies as the **SLA + ownership abstraction**. What changed is the operational shape: planes are now hosted by **three Orca clusters** (one cluster per plane, with Identity and Infra co-tenant in the same cluster on a single VM). The "Data plane" is renamed **App plane** to reflect that it carries product workloads, not just data stores. Cluster repos: `platform/breakpilot-edge` (Identity + Infra), `platform/breakpilot-control` (Control), `platform/breakpilot-app` (App, with prod + stage VMs). Multi-VM rollout is gated on the legal entity being established. See `INFRASTRUCTURE.md §1`, `IMPLEMENTATION_PLAN.md §1.1 / M1.2`, and `platform/orca-platform/clusters/README.md` for the operational details. +> **2026-09-11 revision.** This supersedes the 2026-06-30 three-cluster design. What changed: +> +> - **Two Orca clusters, not three.** The existing `breakpilot` cluster (orca-infra) is **company core infrastructure only**. A new `breakpilot-platform` cluster hosts everything customer-facing. Staging and production live in that one cluster on **separate Hetzner VMs**. +> - **Hosts are fixed.** Portal at `app-stage.breakpilot.com` / `app.breakpilot.com`, tenants addressed by **path** (`/[slug]/…`), one branded host per web product per environment. No wildcard DNS, **no customer custom domains**. +> - **No web-component embedding.** Product UIs are standalone apps behind SSO (or headless, or CLI). The widget/custom-element contract is gone (`PRODUCT_INTEGRATION_SPEC.md` 2.0). +> - **Products:** Werkpilot, Werkbank, Prüfwerk, Firmwerk are the first line. CERTifAI is parked; breakpilot-compliance (the "dsms" stack) migrates last and is re-onboarded afterwards. +> - **ERPNext stays on core and is the commercial truth.** The customer ⇄ CRM ⇄ ERP link is **always on** (outbox + webhooks + reconcile), billing is ERPNext invoicing only (Stripe/Polar dropped), usage flows continuously as usage records. +> - **Keycloak stays on core**; the platform gets realms `breakpilot-stage` and `breakpilot-prod`. Token claims carry only coarse status; the tenant-registry is the entitlement authority (`ERP/02`). +> - **CLI products** are licensed by signed licence tokens issued by the tenant-registry. +> +> Migration mechanics: `IMPLEMENTATION_PLAN.md` (M-MIG milestones). Topology: `INFRASTRUCTURE.md`. ## 1. Vision -We sell CERTifAI and breakpilot-compliance as modular B2B building blocks. Customers buy one or both and operate them inside a unified customer portal — without needing to understand that they are separate products under the hood. +We sell **Werkpilot**, **Werkbank**, **Prüfwerk** and **Firmwerk** as modular B2B building blocks for machine and plant manufacturers and their software teams. Customers buy one or several and operate them under one platform tenant — a single login, a single bill, a single audit trail — without needing to understand that they are separate products under the hood. Each customer is a **tenant**: fully isolated data, their own user base, their own identity configuration. We manage all tenants from a single operator backstage. -ERPNext runs our company: CRM, sales orders, invoicing, HR. Frappe Helpdesk runs customer support. Gitea runs engineering. Everything else — Keycloak, all product services, all databases — runs on our own infrastructure managed by Orca. +ERPNext runs our company: CRM, sales orders, invoicing, HR. Frappe Helpdesk runs customer support. Gitea runs engineering. All of that is **core infrastructure** on the `breakpilot` cluster. The customer-facing platform — portal, tenant-registry, and the products — runs on the `breakpilot-platform` cluster and talks to core over HTTPS. --- ## 2. Products in Scope -| Product | What it is | -|---|---| -| **CERTifAI** | Self-hosted GDPR-compliant AI admin dashboard. Manages LLMs, AI agents, MCP servers, usage analytics. Built with Rust/Dioxus. | -| **breakpilot-compliance** | GDPR and AI-Act compliance automation. Covers DSFA, VVT, TOM, DSR, AI Act, risk, vendor, incidents. Built with Python/FastAPI + Go AI SDK + Next.js. | +| Product | Catalog key | Type | What it is | +|---|---|---|---| +| **Prüfwerk** | `pruefwerk` | Web + MCP | Compliance scanner for CRA/IEC 62443 style assessments: SBOM, DAST, LLM-assisted pentest orchestration, PLC provisioning tests, issue-tracker sync, CVE monitoring. Rust (agent API, Dioxus dashboard, MCP server, docs). Repo `platform/pruefwerk` (formerly `compliance-scanner-agent`, user-facing name until 2026-09-02: "Certifai"). | +| **Werkbank** | add-on of `pruefwerk` | Runner | Pull-based execution runner (`plc-provision`, `qemu-boot`, `dast`, `pentest` jobs) that leases work from Prüfwerk. Never sold standalone (`CRA-WBK-*` always attaches to a `CRA-CSA-*` subscription). Repo `platform/werkbank`. | +| **Werkpilot** | `werkpilot` | CLI | On-prem AI coding agent (goose fork) for machine and plant manufacturers: `werkpilot`, `werkpilotd`, `werkpilot-tui`. Talks to `llm.breakpilot.com`; no hosted UI. Repo `platform/werkpilot`. | +| **Firmwerk** | `firmwerk` | CLI + cloud-server | Reproducible firmware build, SBOM/VEX/attestation toolchain (`firmwerk` CLI) with a small cloud control plane for licences, SBOM upload, invites and OSV lookups (`firmwerk-cloud-server`). Formerly Tramiton. Repo `platform/firmwerk`. | +| **Platform tenant** | — | Portal | `PLT-CORE-CLD-*`: the tenant itself (users, SSO, API keys, audit, billing). Every cloud SKU needs one. | -Out of scope: breakpilot-dataroom, breakpilot-lehrer, breakpilot-pitch-deck. +**Later / parked:** + +| Product | Status | +|---|---| +| **breakpilot-compliance** (`compliance`; the "dsms" stack: backend-compliance, ai-compliance-sdk, admin-compliance, developer-portal, dsms-node/gateway, crawler, TTS) | Migrates to the platform cluster **last** (M-MIG-9). Re-onboarded to contract 2.0 afterwards. Until then it runs on the core cluster as today. | +| **CERTifAI** (GenAI admin dashboard) | Parked. Repo stays under `sharang`, nothing deployed, catalog key removed. | + +Out of scope: breakpilot-dataroom, breakpilot-lehrer, breakpilot-pitch-deck (the pitch deck moves together with dsms because it shares its database, but it is not a product). --- -## 3. The Four Planes - -Four logical planes — but only **three Orca clusters**. Identity and Infra are co-tenant in the `breakpilot-edge` cluster on `vm-edge` per the 2026-06-30 cluster-split decision. The plane abstraction owns SLA and audit responsibilities; the cluster abstraction owns operational concerns (failure domain, backup policy, CI scope, IaC repo). +## 3. Topology — Two Clusters, Two Environments ``` -╔══════════════════════════════════════════════════════════════════════════════╗ -║ PLANE 1 — IDENTITY cluster: breakpilot-edge VM: vm-edge ║ -║ (logical root, all auth flows through here) ║ -╚══════════════════════════════════════════════════════════════════════════════╝ - ↓ JWT -╔══════════════════════════════════════════════════════════════════════════════╗ -║ PLANE 2 — CONTROL cluster: breakpilot-control VM: vm-control ║ -║ (portal + ERPNext + tenant registry) ║ -╚══════════════════════════════════════════════════════════════════════════════╝ - ↓ tenant-scoped API calls -╔══════════════════════════════════════════════════════════════════════════════╗ -║ PLANE 3 — APP (was DATA) cluster: breakpilot-app VMs: vm-app-prod ║ -║ (CERTifAI + breakpilot-compliance + data stores) + vm-app-stage║ -╚══════════════════════════════════════════════════════════════════════════════╝ - ↓ everything runs on -╔══════════════════════════════════════════════════════════════════════════════╗ -║ PLANE 4 — INFRA cluster: breakpilot-edge VM: vm-edge (co-tenant) ║ -║ (Orca + Gitea + Infisical + PowerDNS + Orca-Proxy) ║ -╚══════════════════════════════════════════════════════════════════════════════╝ +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ CORE cluster `breakpilot` (orca-infra) — company infrastructure only ║ +║ master breakpilot-infra-vm1 (46.225.100.82) · workhorse ubuntu-16gb-fsn1-1 ║ +║ ║ +║ Keycloak (auth.) ERPNext + Helpdesk (erp.) Gitea (git.) Harbor (repo.) ║ +║ LiteLLM (llm.) Infisical (secrets.) SigNoz (signoz./otel.) Nextcloud ║ +║ Matrix/Element/Jitsi Penpot kellnr Gatus (status.) landing (breakpilot.com)║ +║ [until M-MIG-9: breakpilot-dsms + tenant-registry-dev + compliance-mcp] ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + ▲ HTTPS only: OIDC/JWKS, ERPNext REST + webhooks, image pulls, + │ LLM calls, OTel export, secret bootstrap +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ PLATFORM cluster `breakpilot-platform` (orca-platform) ║ +║ ║ +║ ┌─────────────────────────────────┐ ┌─────────────────────────────────┐ ║ +║ │ VM bp-platform-stage (MASTER) │ │ VM bp-platform-prod (agent) │ ║ +║ │ app-stage.breakpilot.com │ │ app.breakpilot.com │ ║ +║ │ portal-stage, tenant-registry- │ │ portal-prod, tenant-registry- │ ║ +║ │ stage + pg, erpnext-mock-stage │ │ prod + pg │ ║ +║ │ pruefwerk-*-stage, werkbank- │ │ pruefwerk-*-prod, werkbank- │ ║ +║ │ runner-stage, firmwerk-*-stage │ │ runner-prod, firmwerk-*-prod │ ║ +║ │ realm breakpilot-stage │ │ realm breakpilot-prod │ ║ +║ └─────────────────────────────────┘ └─────────────────────────────────┘ ║ +║ (prod VM joins later — same cluster, separate node, separate projects) ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ ``` -Stage and prod share the same App cluster on different VMs (`vm-app-stage` and `vm-app-prod`). Stage authenticates via the prod Identity plane (`auth.breakpilot.com`) and reads tenant config from the prod Control plane (`tenant-registry`) under `tenant.kind = "stage"` — Identity and Control are **not** duplicated for stage. +**Environments are separated by VM, realm, registry, database and secret scope.** Staging shares nothing stateful with production: + +| | stage | prod | +|---|---|---| +| VM / Orca node | `bp-platform-stage` (cluster master) | `bp-platform-prod` (agent) | +| Portal host | `app-stage.breakpilot.com` | `app.breakpilot.com` | +| Product hosts | `pruefwerk-stage.`, `firmwerk-stage.` | `pruefwerk.`, `firmwerk.` | +| Registry host | `registry-stage.breakpilot.com` | `registry.breakpilot.com` (+ alias `licence.breakpilot.com`) | +| Keycloak realm (on core) | `breakpilot-stage` | `breakpilot-prod` | +| tenant-registry + Postgres | own instance, own DB | own instance, own DB | +| ERPNext | **mock** (`erpnext-mock-stage`, in-cluster) | live `erp.breakpilot.com` | +| Orca projects / secrets | `*-stage` | `*-prod` | +| Data | synthetic + demo | real | + +The four **planes** (Identity, Control, App, Infra) survive as the SLA and ownership vocabulary (`INFRASTRUCTURE.md §6`). Identity and Infra are owned by the core cluster; Control and App by the platform cluster, per environment. --- ## 4. Plane 1 — Identity -**Technology:** Keycloak 26, single realm (`breakpilot-prod`) +**Technology:** Keycloak 26 on the core cluster (`auth.breakpilot.com`), one realm per platform environment: `breakpilot-stage`, `breakpilot-prod`. (`breakpilot` remains the company-staff SSO realm; `breakpilot-dev` is retired after the dsms migration.) -Keycloak is the only truth about who anyone is. Every other service validates JWTs issued here — nothing else handles auth logic. +Keycloak is the only truth about who anyone is. Every other service validates JWTs issued here — nothing else handles auth logic. **Keycloak carries only a coarse tenant status; it never carries entitlements** (`ERP/02`). ### Structure ``` -Realm: breakpilot-prod +Realm: breakpilot-prod (breakpilot-stage is identical) │ -├── Organizations (one per B2B customer) +├── Organizations (one per B2B customer; org attribute tenant_id = registry UUID) │ ├── Acme Corp → org_id: uuid-acme -│ ├── BayernAG → org_id: uuid-bayernag │ └── ... │ -├── Organization Roles (what a user can do within their company) +├── Organization Roles │ ├── IT_ADMIN — full portal access, user management, IdP config │ ├── CXO — dashboard, billing, audit (read) │ ├── FINANCE — billing, invoices │ ├── LEGAL — audit log, compliance read │ └── USER — product access only │ -├── Realm Roles (what we, the operators, can do) +├── Realm Roles (operators) │ ├── BREAKPILOT_ADMIN — full backstage, impersonation, demo tenant edit │ ├── SUPPORT_ENGINEER — read backstage, limited impersonation │ └── SALES_REP — demo tenant login, CRM read, NO real-tenant access │ +├── Clients +│ ├── portal-{env} confidential, auth code + PKCE +│ ├── portal-svc-{env} service account (registry calls) +│ ├── tenant-registry-svc-{env} service account (KC admin API: users + organizations) +│ ├── pruefwerk-dashboard-{env} public PKCE +│ ├── pruefwerk-svc-{env} service account +│ ├── firmwerk-svc-{env} service account +│ ├── werkpilot-cli / firmwerk-cli public, device-authorization grant (CLI login) +│ └── erp-svc-{env} service account (ERPNext → registry webhooks, prod only) +│ +├── Client scopes +│ ├── tenant-context tenant_id, tenant_slug, org_roles, tenant_status +│ ├── tenant-registry-audience aud: tenant-registry +│ └── pruefwerk-audience aud: pruefwerk +│ └── Identity Provider Brokering (per org, optional) ├── OIDC (Okta, Google Workspace, any OIDC provider) └── SAML (Azure AD, ADFS, any SAML 2.0 provider) @@ -93,1066 +145,417 @@ Realm: breakpilot-prod ### JWT Structure -Every service receives a JWT containing: - ``` -sub — user UUID -email — user email -org_id — customer tenant UUID (= Keycloak org ID) -org_name — human-readable company name -org_roles — [IT_ADMIN, USER, ...] roles within their org -realm_roles — [customer] | [BREAKPILOT_ADMIN] | [SUPPORT_ENGINEER] | [SALES_REP] -products — [certifai, compliance] entitlements (injected by protocol mapper) -plan — starter | professional | enterprise -iss — https://auth.breakpilot.com/realms/breakpilot-prod +sub — user UUID +email — user email +tenant_id — customer tenant UUID (= Keycloak org attribute; = registry tenants.id) +tenant_slug — acme +org_roles — [IT_ADMIN, USER, ...] +realm_roles — [] | [BREAKPILOT_ADMIN] | [SUPPORT_ENGINEER] | [SALES_REP] +tenant_status — demo | trial | active | warning | restricted | halted | archived +aud — per client scope (tenant-registry, pruefwerk, ...) +iss — https://auth.breakpilot.com/realms/breakpilot-{env} ``` -The `products` and `plan` claims are added by a Keycloak **protocol mapper** that reads live entitlements from the Tenant Registry at token issuance. Products do not need to call back to the registry on every request. +`tenant_status` is written by the tenant-registry (`SyncClaims`) whenever the ladder changes; token-TTL lag (≤ access-token lifetime) is accepted. **There is no `products` or `plan` claim.** Products ask the registry (§5c) for entitlements and cache the answer for ≤ 60 s. + +Multi-org users: the registry's `GET /v1/users/{id}/memberships` is the membership authority; per-user attributes in the token reflect the active org only. + +### CLI identity + +`werkpilot login` and `firmwerk login` use the OAuth **device-authorization grant** against the realm. The resulting user token is exchanged once at the registry for a **licence token** (§5c, `ERP/02`); day-to-day the CLIs run on the licence token, offline-verifiable, with an hourly phone-home. --- ## 5. Plane 2 — Control -Three distinct services. Clear separation of responsibility. - ### 5a. Customer Portal -**Technology:** Next.js 15 (new service) -**Deployed at:** `*.breakpilot.com` via Orca-Proxy wildcard routing +**Technology:** Next.js 16, Auth.js v5 (Keycloak provider) +**Deployed at:** `app-stage.breakpilot.com` (stage) / `app.breakpilot.com` (prod) — one fixed host per environment. The front door for all customers and for us. Owns no business logic — it is a routing, auth, and UI layer. -**Subdomain routing:** -- DNS wildcard `*.breakpilot.com` → Orca-Proxy -- Orca-Proxy reads `Host` header → routes all traffic to the portal container -- Portal reads `Host` → extracts tenant slug → looks up Tenant Registry +**Tenant routing (path-based):** +- The first path segment is the tenant slug: `https://app.breakpilot.com/acme/dashboard`. +- The portal resolves the slug via tenant-registry `GET /v1/tenants/by-slug/{slug}` (cached 60 s) and checks it against the session's `tenant_id`; mismatch → redirect to the user's own tenant. +- Reserved first segments: `start`, `backstage`, `api`, `auth`, `demo`. +- No `Host`-header tenancy, no wildcard certificates, no customer domains. **Customer area** (requires valid JWT for their org): ``` -/[slug]/dashboard product tiles, usage summary, activity +/[slug]/dashboard product tiles, usage summary, activity, billing-state banner /[slug]/catalog browse ALL products, subscribed and not (upgrade/upsell flow) /[slug]/products/ - /certifai CERTifAI product area (subscribed only) - /compliance breakpilot-compliance area (subscribed only) -/[slug]/projects optional sub-tenancy: dev/staging/prod separation [IT_ADMIN] + /pruefwerk launch → https://pruefwerk.breakpilot.com (SSO), runner status + /werkpilot downloads, licence status, seat usage + /firmwerk downloads, licence status, environments, cloud-server link +/[slug]/projects optional sub-tenancy [IT_ADMIN] (API deferred) /[slug]/settings/ /identity IdP configuration [IT_ADMIN] /users invite, roles, deactivate [IT_ADMIN] - /api-keys API keys for integrations [IT_ADMIN] + /api-keys API keys (products, MCP, runners) [IT_ADMIN] /integrations webhooks, process hooks -/[slug]/billing/ plan, usage, invoices [FINANCE, CXO, IT_ADMIN] +/[slug]/billing/ plan, subscriptions, usage, invoices (from ERPNext via registry) [FINANCE, CXO, IT_ADMIN] /[slug]/audit/ platform + product audit, filterable by product [LEGAL, IT_ADMIN] -/[slug]/support/ Frappe HD customer portal [all roles] +/[slug]/support/ link to Frappe HD customer portal [all roles] ``` -**Operating principles (borrowed from AWS/Azure/GCP consoles):** +Product tiles **launch** the product on its own host (SSO hand-off through Keycloak; no iframe, no custom element). Headless/CLI products render a portal-owned page (downloads, keys, licences, usage). -``` -1. Role-based UI hiding - The portal NEVER shows a button, link, or section the user cannot use. - Disabled-with-tooltip is also wrong — hide it. The customer's mental model - should be "the portal shows me what I can do," not "the portal teases me." +**Operating principles** (unchanged): role-based UI hiding; browse before buy; Tenant → Project → Resources hierarchy; cross-product activity log; cost and usage as first-class. -2. Browse before buy - /catalog shows every product available on the platform with description, - pricing tier, and a one-click "Request" CTA — even for products the - customer is not subscribed to. Drives organic upsell instead of - requiring sales touchpoints. - -3. Hierarchy: Tenant → Project (optional) → Resources - A tenant can have multiple projects (e.g., "Production", "Staging"). - Products that support project scoping isolate data per project. - Customers without sophistication operate as single-project (default). - Mirrors GCP Project / AWS Account / Azure Resource Group pattern. - -4. Cross-product activity log - /audit shows portal events AND every product's audit events filtered - by tenant. Filterable by product, actor, action, time range. One log - to satisfy DPO inquiries instead of hunting per-product. - -5. Cost and usage as first-class - Billing page is not just "your invoice." Shows live usage per product, - trend over time, and projected next invoice. Removes "bill shock." -``` - -**Backstage** (access by realm role): -- `BREAKPILOT_ADMIN` — everything below -- `SUPPORT_ENGINEER` — read all + impersonation, no create/delete -- `SALES_REP` — `/backstage/leads`, `/backstage/demo`, own CRM activity only; CANNOT load any other `/backstage/tenants/[id]` route +**Backstage** (`/backstage/…`, by realm role) — unchanged in scope: `BREAKPILOT_ADMIN` everything; `SUPPORT_ENGINEER` read + impersonation; `SALES_REP` only `/backstage/leads`, `/backstage/demo`. ``` /backstage/dashboard MRR, active tenants, system health /backstage/tenants/ /new create customer /[id]/overview health, logins, API volume - /[id]/products enable/configure products + /[id]/products enable/configure products, add-ons (werkbank runners) /[id]/users view members, impersonate - /[id]/billing Stripe + ERPNext view + /[id]/billing ERPNext view: subscriptions, invoices, dunning level, usage records + /[id]/licences issued CLI licences, revoke /[id]/support tickets for this customer /[id]/audit full audit trail /backstage/system/ /health all service health + /erp-link outbox depth, last reconcile, webhook failures /incidents incident log /releases deployment history ``` -### 5b. ERPNext +### 5b. ERPNext (core cluster) -**Technology:** Frappe + ERPNext (self-hosted via Orca) -**Access:** `erp.breakpilot.com` — us only (IP-restricted at Orca-Proxy) -**Auth:** Keycloak OIDC — we log in with our existing accounts, no separate password +**Technology:** Frappe + ERPNext v15 (+ Frappe CRM, Helpdesk) — `ghcr.io/mighty840/erpnext-stack:v15`, self-hosted via Orca on the **core** cluster +**Access:** `erp.breakpilot.com` — us only +**Auth:** Keycloak OIDC (realm `breakpilot`) -ERPNext is our **business operations backbone**. We do not build CRM, invoicing, or HR — we configure ERPNext for these. +ERPNext is our **business operations backbone** and the **commercial source of truth** for every tenant: customer, subscribed SKUs, term, payment status, dunning level. We do not build CRM, invoicing, or HR — we configure ERPNext for these. | ERPNext Module | Used for | |---|---| -| CRM | Leads, opportunities, deal pipeline | -| Sales | Quotations, Sales Orders (= contracts) | -| Accounts | Sales Invoices, payment tracking, DATEV export | +| CRM | Leads, opportunities, deal pipeline (website form via `kontakt-relay`, portal catalog requests, trial requests) | +| Sales | Quotations, Sales Orders (= contracts), Subscriptions (recurring SLA tiers), Pricing Rules | +| Accounts | Sales Invoices, Payment Entries, Dunning, DATEV export, Usage Records | | Buying | Our own SaaS costs, infrastructure invoices | -| HR | Sharang + Benjamin as employees, expense claims | +| HR | Founders as employees, expense claims | | Support (Frappe HD) | Customer tickets, SLA, escalation to Gitea | -**Integration with the platform:** -- ERPNext Customer record has a custom field `tenant_id` linking to the Tenant Registry -- When a Sales Order is submitted in ERPNext → webhook → Tenant Registry `/tenants/{id}/activate` -- Portal billing page reads invoices from ERPNext REST API server-side — customers never log into ERPNext directly -- We (founders) create quotations, orders, and invoices inside ERPNext +**Integration with the platform — always on, both directions** (`ERP/02`, P12, P17, P18): + +- ERPNext Customer carries the custom field `tenant_id` (= registry UUID). The registry creates/updates the Customer when a tenant is created (`erp_customer_id` written back). +- **Down (ERP → registry):** Frappe Webhooks (HMAC-signed) on `Sales Order` submit, `Subscription` status change, `Sales Invoice` overdue, `Payment Entry` submit, `Dunning` level change → `POST /v1/internal/erp/webhook`. Idempotent by ERP document name + modified timestamp. A **15-minute reconcile job** re-reads open Subscriptions per Customer and repairs any missed event. +- **Up (registry → ERP):** an **outbox** in the registry pushes Customer upserts, CRM Leads (catalog / trial requests), and **usage records** (`usage_events` → ERPNext usage lines on the Subscription) with retry/backoff. Target lag ≤ 60 s; the backstage `/system/erp-link` page shows outbox depth. +- Portal billing page reads Subscriptions and Sales Invoices from ERPNext **server-side via the registry** — customers never log into ERPNext directly. +- **Staging** talks to `erpnext-mock-stage`, an in-cluster mock of the same REST surface that can fire the same webhooks on demand. The live ERP configuration is applied only for production (`ERP/03 Phase 5`). ### 5c. Tenant Registry -**Technology:** Go service (new), PostgreSQL schema `tenant_registry` +**Technology:** Go service, PostgreSQL (one instance per environment) +**Hosts:** `registry-stage.breakpilot.com` / `registry.breakpilot.com` (alias `licence.breakpilot.com`) — needed publicly for ERPNext webhooks and CLI phone-home; everything else may use the in-node network. -The glue between Keycloak, ERPNext, and the products. The technical source of truth for "what is this tenant, what do they have access to, how are they configured." +The glue between Keycloak, ERPNext, and the products. **The entitlement authority**: it decides what each tenant may do now, derived from ERPNext's commercial state and expressed as one ladder. **Key data it holds:** ``` -tenants id, slug, name, erp_customer_id, stripe_cust_id, - status, plan, trial/contract dates, sales_owner, - kind (real | demo). - status ∈ {demo, trial, active, frozen, archived}. - demo — shared demo tenant; reset nightly; no billing - trial — real customer in their N-day evaluation window - active — paid, contract or self-serve plan - frozen — read-only after cancel / non-payment (30d grace) - archived — data export window closed; only audit log retained - -tenant_projects OPTIONAL sub-tenancy. id, tenant_id, name, slug, - status. Customers without need operate as a single - implicit "default" project. Products opt in via - manifest (supports_projects: true) and accept an - optional project_id parameter on tenant-scoped APIs. - Mirrors GCP Project / AWS Account pattern. - -tenant_products tenant ↔ product, enabled, config (litellm_url, - max_seats, modules_enabled), expires_at +tenants id (= Keycloak org attribute tenant_id), slug, name, + erp_customer_id, status, kind (customer | demo), plan (SKU tier), + trial_ends_at, contract_start/end, sales_owner. + status ∈ {demo, trial, active, warning, restricted, halted, archived} + demo shared demo tenant; reset nightly; no billing + trial real customer in their N-day evaluation window + active paid, current (Betriebsbereit) + warning overdue within grace; full access + banner (Warnung) + restricted grace exceeded; read-only + export only (Eingeschränkt) + halted long overdue / contract ended; export window only (Angehalten) + archived export window closed; data deleted; audit retained +products catalog (was hard-coded): key, name, type (standalone|headless|cli), + launch_url per env, skus[], addons[] (e.g. pruefwerk → werkbank), + manifest_url, enabled +plans SKU → tier, limits (seats, targets, scans/mo, environments, runners) +subscriptions tenant ↔ ERP Subscription / Sales Order: sku, tier, seats, period, + erp_status (mirrors ERPNext), synced_at +tenant_products tenant ↔ product entitlement: enabled, config (limits, addons, + litellm_url…), expires_at — derived from subscriptions +tenant_projects OPTIONAL sub-tenancy (schema exists; API deferred) tenant_idp_config type (oidc/saml), metadata, verified - -audit_log every portal AND product action: who, what, when, - from where, including impersonations. Indexed for - cross-product search (filter by tenant + product + - actor + action + time). Schema is Retraced-compatible - so we can swap implementation without changing - producers (see PRODUCT_INTEGRATION_SPEC.md §8.4). - -api_keys portal-owned. tenant_id, product, scopes, name, - hash, created_by, last_used_at, revoked_at. - Headless products call /internal/api-keys/verify - to validate inbound keys. Single source of truth - across all products. +api_keys portal-owned; tenant_id, product, scopes, name, hash (argon2id), + created_by, last_used_at, revoked_at. Products and runners verify + via /v1/internal/api-keys/verify. Single source of truth. +licences CLI licence tokens: id, tenant_id, product, sku, kid, issued_at, + expires_at, last_heartbeat_at, revoked_at, ladder_state +usage_events product, tenant_id, metric, quantity, occurred_at, idempotency_key, + erp_pushed_at +erp_outbox pending ERPNext writes (customer upsert, lead, usage record): + payload, attempts, next_attempt_at, last_error +audit_log every portal AND product action (Retraced-compatible; see + PRODUCT_INTEGRATION_SPEC.md §8.4) ``` **Links:** -- `tenant.id` = `Keycloak org_id` (one-to-one) -- `tenant.erp_customer_id` = `ERPNext Customer.name` (one-to-one) -- `tenant.stripe_cust_id` = Stripe Customer ID (self-serve billing only) +- `tenants.id` = Keycloak org attribute `tenant_id` (one-to-one; org alias = slug) +- `tenants.erp_customer_id` = ERPNext `Customer.name` (one-to-one; ERPNext `Customer.tenant_id` custom field is the reverse link) + +**API surface (groups):** + +``` +Tenant lifecycle POST /v1/tenants · GET /v1/tenants (service) · GET /v1/tenants/{id} + GET /v1/tenants/by-slug/{slug} · POST …/activate · POST …/cancel +Catalog GET /v1/catalog · POST /v1/catalog/request · POST /v1/catalog/trial-request +Entitlements GET /v1/entitlements?tenant_id= · + POST /v1/internal/entitlements/check {tenant_id, product, [addon]} + → {allowed, status, limits, reason} (products call this; cache ≤ 60 s) +Usage POST /v1/usage/events (batch, idempotent) · GET /v1/usage?tenant_id= +API keys GET/POST/DELETE /v1/api-keys · POST /v1/internal/api-keys/verify +Licences (CLI) POST /v1/licences (issue) · POST /v1/licences/heartbeat · + POST /v1/licences/{id}/revoke · GET /.well-known/licence-keys.json +Identity GET /v1/users/{id}/memberships · (SyncClaims → Keycloak tenant_status) +ERP link POST /v1/internal/erp/webhook (HMAC) · GET /v1/internal/erp/status +Audit POST /v1/audit · GET /v1/audit +Probes GET /healthz · GET /readyz +``` + +Authorization is **per client**: each Keycloak service client is mapped to the route groups it may call (portal-svc: tenants/catalog/api-keys/audit; pruefwerk-svc: entitlements/usage/audit/api-keys.verify; erp-svc: erp webhook only; …). ### 5d. Demo Tenant (Shared) -**Slug:** `demo` — reachable at `demo.breakpilot.com` +**Slug:** `demo` — reachable at `app.breakpilot.com/demo/…` **Status:** `demo` (never transitions; never billed) **Owner:** us (`BREAKPILOT_ADMIN` curates content; `SALES_REP` reads + logs in) -A single, shared tenant pre-seeded with realistic-but-fake data covering CERTifAI + breakpilot-compliance. Sales reps use it to walk prospects through the product live. Prospects do NOT log in directly — the sales rep drives the screen. +A single, shared tenant pre-seeded with realistic-but-fake data covering the first-line products. Sales reps use it to walk prospects through the product live. Prospects do NOT log in directly — the sales rep drives the screen. -**How it differs from a real tenant:** - -``` -DEMO TENANT REAL TENANT -───────────────────────────────────── ─────────────────────────────────── -status = demo status = trial | active -billing disabled billing active -audit emitted but not exported audit emitted and exportable -nightly reset job restores fixtures data is permanent -seed data loaded on reset: customer-owned data - product.manifest.seed_data_url -all real-tenant flows work otherwise same flows, same code paths -``` - -**Why shared and not per-prospect:** -- Cheap (one tenant, no Orca provisioning per prospect) -- Predictable (sales reps know exactly what's in there) -- The known-quantity model — works in practice, matches what we have experience with -- Tradeoff accepted: concurrent edits during the same day are visible across demo sessions; nightly reset hides this within 24h - -**Nightly reset:** -- Cron job (3:00 Europe/Berlin) calls each product's `/v1/tenants/demo/reset` endpoint -- Product fetches its fixtures from `catalog.seed_data_url` and restores -- Reset is itself an audit event; failures page the on-call +Differences from a real tenant and the nightly reset (03:00 Europe/Berlin, `POST /v1/tenants/demo/reset` on each product, fixtures from `platform/seed-data`) are unchanged from the 2026-05 design. ### 5e. Frappe Helpdesk + Gitea Issues -**Technology:** Frappe HD (installed on same Frappe bench as ERPNext), Gitea Issues - -**Support flow:** -- Customer submits ticket via `/[slug]/support/` (Frappe HD customer portal, embedded or linked) -- Agent (us) triages in Frappe HD agent UI at `erp.breakpilot.com` -- If technical: agent clicks "Escalate to Engineering" → Frappe server script creates a Gitea issue in the relevant repo via Gitea REST API → issue URL stored on ticket -- When Gitea issue is closed → Gitea webhook → Frappe HD → ticket marked "Resolved" +Unchanged: customer submits via `/[slug]/support/` (link to the Frappe HD customer portal on `erp.breakpilot.com`; no iframe), agent triages in Frappe HD, "Escalate to Engineering" creates a Gitea issue via REST, issue close → webhook → ticket resolved. --- -## 6. Plane 3 — App (was "Data") +## 6. Plane 3 — App (Products) -Renamed 2026-06-30. The plane carries product workloads end-to-end (dashboards, APIs, AI services) as well as the data stores those products own — "App" reflects the full surface, not just the storage tier. SLA targets are unchanged (CERTifAI ≥ 99.5%, compliance ≥ 99.5%, RPO ≤ 6h–24h per data class). Lives in the `breakpilot-app` cluster on `vm-app-prod` (prod) and `vm-app-stage` (stage). +All products run on the platform cluster, pinned to the environment's VM, and integrate through `PRODUCT_INTEGRATION_SPEC.md` 2.0. Each product owns its data store; nothing is shared across products. -### CERTifAI +### Prüfwerk (`pruefwerk`) -Self-hosted GDPR-compliant AI dashboard. After updates, it is fully tenant-aware. +**Surface:** standalone web app at `pruefwerk[-stage].breakpilot.com` (Dioxus dashboard), agent API, MCP server (`/mcp`), docs (`/docs`). +**Multi-tenancy:** one MongoDB database per tenant (`compliance_scanner_`), tenant-scoped webhooks, tenant-bound MCP tokens. +**Auth:** dashboard = Keycloak OIDC PKCE; agent validates user JWTs via JWKS with **issuer and audience** pinned; service token for registry; MCP = API keys / bound tokens. +**Entitlement:** on every tenant-context build the agent calls `entitlements/check` (cached ≤ 60 s): product `pruefwerk` enabled, limits (targets, scans/month), addons (`werkbank` runner count), ladder state. Scheduler enumerates tenants via `GET /v1/tenants` with a service token. +**Usage:** `scan.completed`, `target.added`, `seat.login` events → registry. +**Role mapping:** IT_ADMIN → Admin; CXO, USER → Member; FINANCE, LEGAL → Viewer. +**Werkbank** runners authenticate with a tenant-scoped API key (`product=pruefwerk`, scope `werkbank:runner`), verified by the agent through the registry; the runner count per tenant is an entitlement limit. -**Multi-tenancy:** All MongoDB queries scoped by `org_id` from JWT -**Auth:** Validates Keycloak JWT (JWKS endpoint), maps `org_roles` to product roles -**LiteLLM:** Shared managed instance (Starter/Professional, API key per tenant) or customer-hosted (Enterprise, URL stored in `tenant_products.config`) -**Role mapping:** +### Werkpilot (`werkpilot`) -| Portal role | CERTifAI role | -|---|---| -| IT_ADMIN | Admin | -| CXO, USER | Member | -| FINANCE, LEGAL | Viewer | +**Surface:** CLI only (`werkpilot`, `werkpilotd`, `werkpilot-tui`), released as signed tarballs through Gitea releases; no hosted service. +**Auth + entitlement:** `werkpilot login` (device flow) → licence token from the registry; offline verification; hourly heartbeat; local 4-state ladder. Seats = named users (`DEV-WP-CLD-*`), on-prem instances (`DEV-WP-OPR-*`) get yearly licences. +**Usage:** `seat.session_started` heartbeat events (daily aggregate) via the phone-home. +**LLM:** `llm.breakpilot.com` (core LiteLLM) with a per-tenant virtual key issued at licence time. -### breakpilot-compliance +### Firmwerk (`firmwerk`) -GDPR and AI-Act compliance automation platform. After updates, tenant identity comes from validated JWT — not raw client headers. +**Surface:** CLI (`firmwerk`) + `firmwerk-cloud-server` at `firmwerk[-stage].breakpilot.com` (licensing, SBOM upload receipts, invites, OSV lookups). +**Auth + entitlement:** `firmwerk login` (device flow) → licence token from the registry. The cloud-server **drops its own tenant/api-key/licence model**; it verifies registry licence tokens (public keys from `/.well-known/licence-keys.json`) and calls `entitlements/check` for limits (environments per user). Read-only usage is free forever; writes need an active subscription; 14-day trial on any tier. +**Usage:** `environment.created`, `sbom.uploaded`, `seat.active` events. -**Multi-tenancy:** All PostgreSQL queries scoped by `tenant_id` (= `org_id` from JWT) -**Auth:** Next.js proxy validates JWT → extracts `org_id` → sets `X-Tenant-ID` -**Role mapping:** `LEGAL` can approve DSFA; `IT_ADMIN` is compliance admin; `USER` contributes to DSR/VVT workflows +### breakpilot-compliance (`compliance`) — after M-MIG-9 + +Tenant identity from validated JWT; Postgres RLS by `tenant_id`; role mapping `LEGAL` approves DSFA, `IT_ADMIN` compliance admin, `USER` contributes. Re-onboarded to contract 2.0 once it runs on the platform cluster. --- ## 7. Plane 4 — Infra -Co-tenant with the **Identity plane** in the `breakpilot-edge` cluster on `vm-edge`. Single-VM core per the 2026-06-30 cluster-split decision. Keycloak JVM heap is pinned (`-Xmx1500m`) so it cannot starve PowerDNS / Infisical. Escape hatch if the heap fight shows up post-launch: peel Keycloak onto its own VM inside the same cluster — no schema migration, just a `placement.node` flip. - -**Orchestration:** Orca manages all containers on SysEleven VMs. Per-node ingress (every node binds 80/443 and runs its own ACME), one Orca cluster per plane (3 clusters total), one IaC repo per cluster (`platform/breakpilot-{edge,control,app}`). -**Secrets:** Infisical — every service has a machine identity, pulls its own secrets at startup -**CI/CD:** Gitea Actions → Docker build → push to private registry → Orca redeploy webhook (one CI/release cadence per cluster repo, plus per-product repos for the deployed services) -**Routing:** Orca-Proxy handles TLS termination and subdomain routing on each node (no central proxy SPOF) +**Orchestration:** Orca on Hetzner VMs. Per-node ingress: every node binds 80/443 and runs its own ACME (HTTP-01); a service's A record points at the VM that runs it. Two clusters, two IaC repos: `sharang/orca-infra` (core) and `platform/orca-platform` (platform). +**Placement:** every platform service carries `placement.node = "bp-platform-stage" | "bp-platform-prod"`; service names are unique cluster-wide (`-stage` / `-prod` suffix); `scripts/validate.sh` enforces both in CI. +**Secrets:** Orca project-scoped secrets (`orca secrets set --project

`), never global for production values. Infisical (core) holds the licence signing key and CI credentials. +**CI/CD:** Gitea Actions → image → Harbor `repo.breakpilot.com//` → signed webhook to the platform master (`main` → stage). Production deploys on tags via a `prod` branch webhook (prod plan). +**Routing (platform cluster, per node):** ``` -Orca-Proxy routing table: - auth.breakpilot.com → Keycloak - erp.breakpilot.com → ERPNext + Frappe HD (IP-restricted) - git.breakpilot.com → Gitea - secrets.breakpilot.com → Infisical (IP-restricted) - *.breakpilot.com → customer-portal (wildcard, Host → tenant) +bp-platform-stage bp-platform-prod (later) + app-stage.breakpilot.com → portal-stage app.breakpilot.com → portal-prod + registry-stage.… → tenant-registry-stage + registry.… / licence.… → tenant-registry-prod + pruefwerk-stage.… → pruefwerk-dashboard-stage + /mcp/* → pruefwerk-mcp-stage + /docs/* → pruefwerk-docs-stage + firmwerk-stage.… → firmwerk-cloud-stage + pruefwerk.… / firmwerk.… (same shape) + (erpnext-mock-stage, pg, mongo, browserless, soft-plc, plc-sim, werkbank-runner: internal) ``` -**Services managed by Orca:** +**Services managed by Orca (platform cluster, per environment):** ``` -Identity & Auth - └── Keycloak 26 - -Business Operations - ├── ERPNext (Frappe) - └── Frappe Helpdesk - -Developer Tooling - ├── Gitea - └── Gitea Runner - -Secrets - └── Infisical - -AI Inference - └── LiteLLM (shared, API key per tenant; or customer-hosted for Enterprise) - -Customer Portal - ├── customer-portal (new) - └── tenant-registry (new) - -Products - ├── certifai-dashboard - └── breakpilot-compliance stack - ├── backend-compliance (Python/FastAPI) - ├── ai-compliance-sdk (Go) - └── admin-compliance (Next.js) - -Data Stores - ├── PostgreSQL 17 [schemas: tenant_registry, compliance] - ├── MongoDB [CERTifAI] - ├── Qdrant [compliance RAG] - └── MinIO [compliance documents] +Control portal-{env}, tenant-registry-{env}, pg-{env}, erpnext-mock-stage (stage only) +Prüfwerk pruefwerk-agent, pruefwerk-dashboard, pruefwerk-mcp, pruefwerk-docs, + pruefwerk-mongo, browserless, soft-plc, plc-sim (scan targets), werkbank-runner +Firmwerk firmwerk-cloud, firmwerk-mongo +(dsms, after M-MIG-9) breakpilot-db, backend-compliance, ai-compliance-sdk, admin-compliance, + developer-portal, dsms-node, dsms-gateway, document-crawler, tts, qdrant, + ollama-embed, pitch-deck ``` -**Infisical secret namespacing:** +Core services consumed over HTTPS: Keycloak, ERPNext (prod), Gitea, Harbor, LiteLLM, Infisical, SigNoz/OTel, Gatus. -``` -/prod/ - /keycloak/ DB_PASS, ADMIN_PASS, REALM_KEYS - /erpnext/ DB_PASS, SMTP_PASS, OIDC_CLIENT_SECRET - /customer-portal/ KEYCLOAK_CLIENT_SECRET, ERP_API_KEY, REGISTRY_DB_URI - /tenant-registry/ POSTGRES_URI, KEYCLOAK_ADMIN_SECRET, ERP_API_KEY, STRIPE_SECRET - /certifai/ MONGODB_URI, KEYCLOAK_CLIENT_SECRET, LITELLM_MASTER_KEY - /compliance/ POSTGRES_URI, QDRANT_API_KEY, MINIO_KEYS, ANTHROPIC_API_KEY - /litellm/ OPENAI_API_KEY, ANTHROPIC_API_KEY, MASTER_KEY - /gitea-runner/ DOCKER_REGISTRY_PASS, ORCA_WEBHOOK_TOKEN -``` +**Security headers:** Orca `[security_headers] frame_options = "DENY"`, CSP set — product UIs are never embedded. --- ## 8. Process Sketches +Only the sketches that changed are drawn in full; the rest are listed with their delta. + ### P1 — New Customer Onboarding (Sales-Led) ``` - US (ERPNext) TENANT REGISTRY KEYCLOAK - │ │ │ - │ Lead → Opportunity │ │ - │ → Quotation (PDF sent) │ │ - │ → Sales Order submitted │ │ - │─────── webhook ─────────────►│ │ - │ │ create org ─────────►│ - │ │◄──── org_id ──────────│ - │ │ write tenant row │ - │ │ write tenant_products│ - │ │ send welcome email │ - │ │ │ │ - │ │ ▼ │ - │ IT ADMIN receives email │ - │ clicks setup link │ - │ │ ┌───────┤ - │ │ │set pw │ - │ │ │ 2FA │ - │ │ └───┬───┘ - │ │ │ - │ lands on /acme/dashboard │ - │ │ │ + US (ERPNext) TENANT REGISTRY KEYCLOAK IT ADMIN + │ Lead → Opportunity │ │ │ + │ → Quotation → Sales Order │ │ │ + │ submit ── webhook (HMAC) ──►│ │ │ + │ │ create/lookup tenant │ │ + │ │ create org ──────────►│ │ + │ │◄── org_id ────────────│ │ + │ │ subscriptions ← SO │ │ + │ │ tenant_products │ │ + │ │ status = active │ │ + │ │ SyncClaims ──────────►│ │ + │ │ outbox: Customer.tenant_id ──► ERPNext │ + │ │ invite IT_ADMIN ──────────────────────►│ + │ │ │ set pw + 2FA │ + │ │ lands on app.breakpilot.com/acme/dashboard ``` -### P2 — User Login (Customer's Own IdP) +### P2 / P3 — User Login -``` - USER ORCA-PROXY PORTAL KEYCLOAK CUSTOMER IdP - │ │ │ │ │ - │ acme.breakpilot.com │ │ │ │ - │───────────────────────►│ │ │ │ - │ │ Host=acme.* │ │ │ - │ │───────────────►│ │ │ - │ │ │ slug=acme │ │ - │ │ │ lookup tenant │ │ - │ │ │ → idp=acme-okta│ │ - │ │ │─── redirect ──►│ │ - │ │ │ kc_idp_hint │ │ - │ │ │ │─── redirect ──►│ - │ │ │ │ │ - │ │◄─────────────────────── auth ──┤ │ - │ │ │ │ issue JWT │ - │ │ │◄── JWT ────────│ │ - │◄── /acme/dashboard ────┤ │ │ │ -``` +As before, with `app.breakpilot.com/acme` instead of `acme.breakpilot.com`: portal resolves the slug from the path, looks up the tenant (IdP hint if configured), redirects to Keycloak, lands on `/acme/dashboard`. -### P3 — User Login (Our IdP — email + password) - -``` - USER PORTAL KEYCLOAK - │ │ │ - │ acme.breakpilot │ │ - │──────────────────►│ │ - │ │ redirect + PKCE │ - │ │─────────────────►│ - │◄── Keycloak login page ─────────────┤ - │ enter email + password (+ TOTP) │ - │─────────────────────────────────────►│ - │ │◄── JWT ──────────│ - │◄── /acme/dashboard┤ │ -``` - -### P4 — IT Admin Configures External IdP - -``` - IT ADMIN PORTAL TENANT REGISTRY KEYCLOAK - │ │ │ │ - │ /settings/ │ │ │ - │ identity │ │ │ - │───────────────►│ │ │ - │ fill OIDC/ │ │ │ - │ SAML details │ │ │ - │───────────────►│ │ │ - │ │── PATCH idp_config►│ │ - │ │ │── create IdP ────►│ - │ │ │ for org │ - │ │ │◄── ok ────────────│ - │ │ │ verified=true │ - │◄── "Test" btn ─┤ │ │ - │ auth popup ───────────────────────────────────────────►│ - │◄── success ────────────────────────────────────────────┤ - │◄── "IdP configured" ┤ │ │ -``` - -### P5 — IT Admin Invites a Team Member - -``` - IT ADMIN PORTAL KEYCLOAK NEW USER - │ │ │ │ - │ /settings/ │ │ │ - │ users → invite│ │ │ - │ email + role │ │ │ - │───────────────►│ │ │ - │ │ create user in org│ │ - │ │──────────────────►│ │ - │ │ │ send invite │ - │ │ │ email ────────►│ - │ │ │ │ click link - │ │ │◄── set pw ─────│ - │ │ │ (+ TOTP) │ - │ │ │ issue JWT │ - │ │◄─── JWT ──────────│ │ - │ │ │ ┌──────┘ - │ │ │ lands on│ - │ │ │ /acme/dashboard - │ │ │ (role-filtered view) -``` +### P4 — IdP configuration, P5 — Invite: unchanged. ### P6 — Customer Accesses a Product ``` - USER PORTAL KEYCLOAK PRODUCT (e.g. CERTifAI) - │ │ │ │ - │ /acme/products/ │ │ │ - │ certifai │ │ │ - │─────────────────►│ │ │ - │ │ check JWT: │ │ - │ │ products claim │ │ - │ │ includes │ │ - │ │ "certifai" ? │ │ - │ │ │ │ - │ [YES] ────────┤ │ │ - │ │ pass JWT ──────────────────────── │ - │ │ │ validate JWKS │ - │ │ │ extract org_id │ - │ │ │ scope all data │ - │◄── product UI ───┤ │ │ - │ │ │ │ - │ [NO] ─────────┤ │ │ - │◄── "Not in your plan" + upgrade CTA │ + USER PORTAL TENANT REGISTRY PRODUCT (pruefwerk.breakpilot.com) + │ /acme/products/ │ │ │ + │ pruefwerk │ │ │ + │─────────────────►│── check ─────────►│ │ + │ │◄ allowed/denied ──│ │ + │ [allowed] ◄─── "Open Prüfwerk" ─────┤ │ + │──────────── SSO redirect (Keycloak, same realm session) ───────►│ + │ │ │◄── entitlements/check ───│ (cached ≤60 s) + │ │ │── {allowed, limits} ────►│ + │◄─────────────────────────────────────────────── product UI ────│ + │ [denied] ◄── "Not in your plan" + request CTA (P13) │ ``` ### P7 — Finance User Views Billing ``` - FINANCE USER PORTAL ERPNEXT API STRIPE API - │ │ │ │ - │ /acme/billing│ │ │ - │──────────────►│ │ │ - │ │ role check: │ │ - │ │ FINANCE → ok │ │ - │ │ │ │ - │ │── fetch invoices►│ │ - │ │◄── invoice list ─│ │ - │ │ │ │ - │ │── fetch usage ────────────────────► │ - │ │◄── usage data ────────────────────── │ - │ │ │ │ - │◄── billing page renders │ │ - │ plan · usage · invoices │ │ - │ [Download PDF] ──────────────►│ │ - │◄── PDF streamed ─────────────────│ │ - │ │ │ - │ [Upgrade Plan] │ │ - │──────────────►│ │ │ - │ │ create CRM task in ERPNext │ - │ │─────────────────►│ │ - │ │ notify us (email/ERPNext task) │ - │◄── "We'll be in touch" ──┤ │ │ + FINANCE USER PORTAL TENANT REGISTRY ERPNEXT (core) + │ /acme/billing │ │ │ + │──────────────►│── subscriptions ─►│ (local mirror) │ + │ │── invoices ──────►│── REST (server) ────►│ + │ │◄──────────────────│◄─────────────────────│ + │◄── plan · usage (usage_events) · invoices · dunning state │ + │ [Download PDF] ─────────────────►│── print format ─────►│ + │ [Upgrade] → CRM Lead via outbox (P13) │ ``` -### P8 — Legal User Exports Audit Report +### P8 — Audit export, P9 — Support escalation, P10 — Backstage create, P11 — Impersonation: unchanged (URLs become `app.breakpilot.com/acme/...`). P10 additionally queues the ERPNext Customer upsert through the outbox. + +### P12 — ERPNext Event Drives the Ladder (always-on link) ``` - LEGAL USER PORTAL TENANT REGISTRY COMPLIANCE PRODUCT - │ │ │ │ - │ /acme/audit │ │ │ - │──────────────►│ │ │ - │ │ role check: │ │ - │ │ LEGAL → ok │ │ - │ │ │ │ - │ │── platform audit ──────────────────► - │ │ (who logged in, role changes, │ - │ │ IdP changes, impersonations) │ - │ │◄── audit_log rows ─────────────────┤ - │ │ │ │ - │ │── compliance audit ────────────────► - │ │ (DSFA approvals, DSR processing, │ - │ │ TOM completions) │ - │ │◄── compliance audit rows ──────────┤ - │ │ │ │ - │ [Export] │ │ │ - │──────────────►│ │ │ - │◄── ZIP: │ │ │ - │ platform-audit.csv │ │ - │ compliance-audit.pdf │ │ + ERPNEXT TENANT REGISTRY KEYCLOAK PRODUCTS + │ Sales Order submit / │ │ │ + │ Payment Entry / Invoice │ │ │ + │ overdue / Dunning / cancel │ │ │ + │── webhook (HMAC, doc name+ts)►│ idempotency check │ │ + │ │ recompute ladder: │ │ + │ │ paid → active │ │ + │ │ overdue ≤ grace → warning │ │ + │ │ grace exceeded → restricted │ │ + │ │ ended → halted → archived │ │ + │ │ update subscriptions/products │ │ + │ │── SyncClaims(tenant_status) ─►│ │ + │ │── suspend/reactivate ────────────────────► │ + │ │ audit event │ │ + │ every 15 min: reconcile ◄─────│ (re-read Subscriptions, repair drift) │ ``` -### P9 — Support Ticket Escalated to Engineering +### P13 — Catalog Request → CRM Lead (via outbox), P14 — Sales demo (`app.breakpilot.com/demo`), P15 — Self-serve trial (`/start`; conversion = Sales Order in ERPNext, no card PSP), P16 — Cancel and offboard (Subscription cancel in ERPNext → halted → export window → archived; `DELETE /v1/tenants/{id}/data` on every product): unchanged in substance. + +### P17 — Usage Event → ERPNext Usage Record ``` - CUSTOMER FRAPPE HD US (AGENT) GITEA - │ │ │ │ - │ submit ticket │ │ │ - │ via /support/ │ │ │ - │─────────────────►│ │ │ - │ │── notify agent ─►│ │ - │ │ │ triage ticket │ - │ │ │ → technical bug │ - │ │ │ │ - │ │ │ [Escalate] │ - │ │◄─────────────────│ │ - │ │ server script: │ │ - │ │ POST /issues ────────────────────► │ - │ │ │ {title, body, │ - │ │ │ labels:[bug]} │ - │ │◄──── issue URL ───────────────────┤ - │ │ store on ticket │ │ - │◄── "Escalated to engineering, we'll update you" ─────┤ - │ │ │ │ - │ │ │ dev fixes it │ - │ │ │ closes issue ─►│ - │ │◄──────── webhook ──────────────────│ - │ │ ticket → Resolved│ │ - │◄── notification ─│ │ │ + PRODUCT TENANT REGISTRY ERPNEXT + │ scan completed │ │ + │── POST /v1/usage/events│ (idempotency_key) │ + │ [{metric, qty, at}] ►│ store usage_events │ + │ │ enqueue erp_outbox │ + │◄── 202 ────────────────│ │ + │ │ worker: ── Usage Record on the │ + │ │ tenant's Subscription ►│ (≤ 60 s, retry/backoff) + │ │◄── ok / error (kept for retry) ──│ + │ │ portal usage chart reads usage_events; invoices stay fixed-tier ``` -### P10 — We Create a New Customer (Startup Flow) +### P18 — CLI Licence Lifecycle (Werkpilot, Firmwerk) ``` - US (BACKSTAGE) TENANT REGISTRY KEYCLOAK ERPNEXT IT ADMIN - │ │ │ │ │ - │ /backstage/ │ │ │ │ - │ tenants/new │ │ │ │ - │ fill: name, │ │ │ │ - │ contact, plan, │ │ │ │ - │ products │ │ │ │ - │──── [Create] ────►│ │ │ │ - │ │── create org ───►│ │ │ - │ │◄── org_id ───────│ │ │ - │ │── create Customer ──────────────►│ │ - │ │◄── erp_customer_id ──────────────│ │ - │ │ write tenant rows │ │ - │ │ send welcome email ─────────────────────────── │ - │◄── tenant created ┤ │ │ │ - │ "Awaiting setup"│ │ │ │ - │ │ │ │ click link│ - │ │ │◄── set pw ────────────────── │ - │ │ │ + 2FA │ │ - │ │ │ JWT issued │ │ - │ │◄─────────────────────────────────────── /acme/ ─┤ + CLI (customer machine) KEYCLOAK TENANT REGISTRY ERPNEXT + │ werkpilot login │ │ │ + │── device code ─────────────►│ user approves │ │ + │◄── user token ──────────────│ │ │ + │── POST /v1/licences (token, product, machine id) ►│ entitlements + ladder │ + │◄── licence JWT (Ed25519, valid-until, sku, tier, grace policy) ─┤ │ + │ verify offline against /.well-known/licence-keys.json │ │ + │ hourly: POST /licences/heartbeat ──────────────► │ refresh or refuse │ + │ │◄── ladder from ERP events ─│ + │ no renewal → local ladder: Healthy 0–7d → Warning 7–14d → Degraded 14–30d │ + │ (read-only) → Hard-stop > 30d │ │ ``` -### P11 — We Debug a Customer Issue (Impersonation) +### Headless Product Flows (H1–H6) -``` - US (BACKSTAGE) TENANT REGISTRY KEYCLOAK PORTAL (AS CUSTOMER) - │ │ │ │ - │ /backstage/ │ │ │ - │ tenants/acme/ │ │ │ - │ users → │ │ │ - │ Impersonate Alice│ │ │ - │──────────────────►│ │ │ - │ │ write audit_log │ │ - │ │ {action: │ │ - │ │ impersonate, │ │ - │ │ actor: sharang, │ │ - │ │ target: alice} │ │ - │ │── request token ►│ │ - │ │◄── imp. token ───│ │ - │◄── token ─────────┤ (30min, signed, │ │ - │ │ impersonated_by │ │ - │ │ claim) │ │ - │ │ │ - │ new tab: acme.breakpilot.com │ │ - │──────────────────────────────────────────────────────────►│ - │ │ [orange banner] │ - │ │ Impersonating │ - │ │ alice@acme.com │ - │ │ 29:47 remaining │ - │ reproduce issue, identify root cause │ │ - │──────────────────────────────────────────────────────────►│ - │ │ [Exit impersonation] -``` - -### P12 — ERPNext Sales Order Activates a Tenant - -``` - US (ERPNEXT) ERPNEXT TENANT REGISTRY KEYCLOAK IT ADMIN - │ │ │ │ │ - │ Sales Order │ │ │ │ - │ Submit ──── ►│ │ │ │ - │ │── webhook ───────►│ │ │ - │ │ {order_id, │ │ │ - │ │ tenant_id, │ │ │ - │ │ products, │ │ │ - │ │ plan, │ │ │ - │ │ contract_start │ │ │ - │ │ contract_end} │ │ │ - │ │ │ tenant.status │ │ - │ │ │ = active │ │ - │ │ │ tenant_products │ │ - │ │ │ enabled=true │ │ - │ │ │── update claims ─►│ │ - │ │ │ (protocol mapper│ │ - │ │ │ picks up new │ │ - │ │ │ entitlements) │ │ - │ │ │── send email ─────────────────►│ - │ │ │ "Subscription │ │ - │ │ │ now active" │ │ -``` - -### P13 — Customer Browses Catalog and Requests a New Product - -``` - USER (any role) PORTAL TENANT REGISTRY ERPNEXT (CRM) - │ │ │ │ - │ /acme/catalog │ │ │ - │──────────────►│ │ │ - │ │── GET /catalog ──────►│ │ - │ │◄── product manifests +│ │ - │ │ subscribed status │ │ - │◄── catalog page │ │ - │ • CERTifAI [✓ Subscribed] │ │ - │ • Compliance [✓ Subscribed] │ │ - │ • Notetaker [+ Request] │ │ - │ • Classifier [+ Request] │ │ - │ │ │ - │ click [Request] on Notetaker │ │ - │ Modal: "Why do you want this?" │ │ - │ + estimated seats / volume │ │ - │──────────────►│ │ │ - │ │── POST /catalog/ │ │ - │ │ request ─────────►│ │ - │ │ {tenant, product, │ │ - │ │ requested_by, note}│ │ - │ │ │── create CRM Lead ──►│ - │ │ │ linked to Customer │ - │ │ │◄── lead_id ──────────│ - │ │ │ notify sales_owner │ - │ │ │ (email + ERPNext │ - │ │ │ activity) │ - │◄── "We'll be in touch within 1 day" ──│ │ -``` - -### P14 — Sales Rep Demos to a Prospect (Shared Demo Tenant) - -``` - SALES REP KEYCLOAK PORTAL DEMO TENANT - │ │ │ │ - │ open Zoom with prospect, share screen │ - │ │ - │ demo.breakpilot.com │ - │────────────────────────────────►│ │ - │ │ │ Host: demo │ - │ │ │ → slug = demo │ - │ │ │ → tenant.kind=demo │ - │ │ │ tenant.status=demo │ - │ │ │ │ - │ │ OIDC redirect │ │ - │◄──────────────│─────────────────│ │ - │ login sales@breakpilot │ - │ realm_role=SALES_REP │ - │──────────────►│ │ │ - │ │ verify SALES_REP allowed on demo only │ - │ │ issue JWT: │ - │ │ org_id=demo, org_roles=[IT_ADMIN], │ - │ │ realm_roles=[SALES_REP], │ - │ │ products=[certifai, compliance] │ - │◄──────────────│ │ │ - │ │ │ - │ /demo/dashboard ───────────────►│ │ - │ /demo/products/certifai ─►│ load custom elt ►│ - │ /demo/products/compliance ─►│ load custom elt ►│ - │◄── show prospect every flow ────│ │ - │ │ │ - │ if prospect interested: │ - │ click [Request Trial] in /demo/catalog │ - │ modal: prospect email, company, est. seats │ - │ → POST /catalog/trial-request │ - │ creates CRM Lead in ERPNext, NOT a tenant │ - │ sales_owner = the logged-in SALES_REP │ - │ │ - │ 03:00 nightly: │ - │ cron → product /v1/tenants/demo/reset │ - │ fixtures from catalog.seed_data_url restored │ - │ demo is clean for next day │ -``` - -**Guardrails:** -- Keycloak policy: `SALES_REP` realm role MUST NOT be issued a token with `org_id ≠ demo` -- Backstage policy: `SALES_REP` CANNOT see real-tenant data, CAN see CRM (their leads) -- Real customer support is NEVER done from a SALES_REP login - -### P15 — Self-Serve Trial → Convert or Expire - -``` - PROSPECT PORTAL TENANT REGISTRY ERPNEXT KEYCLOAK - │ │ │ │ │ - │ breakpilot.com/start │ │ │ - │──────────────►│ │ │ │ - │ form: email, company, password │ │ │ - │──────────────►│ │ │ │ - │ │── POST /trials ──────►│ │ │ - │ │ {email, company, │ │ │ - │ │ requested_products} │ │ │ - │ │ │ │ │ - │ │ │ slugify(company) │ │ - │ │ │ create tenant │ │ - │ │ │ status=trial │ │ - │ │ │ trial_ends_at = │ │ - │ │ │ now + 14d │ │ - │ │ │ create Customer ►│ │ - │ │ │ tier=Trial │ │ - │ │ │ sales_owner= │ │ - │ │ │ unassigned │ │ - │ │ │── create org ───────────────►│ - │ │ │ + IT_ADMIN user │ - │ │ │ + verify email │ - │ │ │ │ │ - │◄── magic link │ │ │ │ - │ click link, set password │ │ │ - │ land on /acme-trial/dashboard │ │ │ - │ banner: "Trial: 14 days left — Add billing to keep your data" │ - │ │ │ │ - │ ── customer uses platform normally ── │ │ - │ │ │ │ - │ DAY 7 cron: trial_ends_at - 7d │ │ │ - │ → email IT_ADMIN + CXO │ │ │ - │ → CRM Activity: "Day-7 nudge" ►│ │ │ - │ │ │ │ - │ DAY 12: same, urgent tone │ │ │ - │ DAY 14: trial_ends_at reached │ │ │ - │ │ │ │ - │ IF customer added payment: │ │ │ - │ status: trial → active │ │ │ - │ Stripe subscription created │ │ │ - │ OR Sales Order in ERPNext signed │ │ │ - │ banner removed │ │ │ - │ │ - │ ELSE: │ - │ status: trial → frozen │ │ │ - │ 30-day grace: portal read-only, products return 402 │ │ - │ daily reminder email until day 44 │ │ - │ │ - │ DAY 44: frozen → archived │ │ │ - │ GDPR export ZIP emailed to IT_ADMIN │ │ │ - │ each product called: DELETE /v1/tenants/{id}/data │ │ - │ 30 days later: tenant row deleted (audit_log retained 7y) │ -``` - -**Trial scoping:** -- All paid products are available in trial mode by default unless `catalog.available_on_plans` excludes `trial` -- Usage-billed products (e.g., LiteLLM calls) get a hard cap during trial (manifest: `trial_quota`) -- Customer can upgrade plan mid-trial; trial timer just stops, no proration - -### P16 — Customer Cancels and Offboards - -``` - IT ADMIN PORTAL TENANT REGISTRY PRODUCTS ERPNEXT - │ │ │ │ │ - │ /acme/settings/billing │ │ │ - │──────────────►│ │ │ │ - │ [Cancel Subscription] │ │ │ - │ Modal: │ │ │ - │ • reason (dropdown) │ │ │ - │ • confirm typing "acme" │ │ │ - │ • shows: data retained 30d, then deleted │ │ - │──────────────►│ │ │ │ - │ │── POST /tenants/ │ │ │ - │ │ acme/cancel ─────►│ │ │ - │ │ │ status: active │ │ - │ │ │ → frozen │ │ - │ │ │ frozen_at = now │ │ - │ │ │ delete_at = │ │ - │ │ │ now + 30d │ │ - │ │ │── Stripe cancel │ │ - │ │ │ at_period_end │ │ - │ │ │── opportunity ──────────────────►│ - │ │ │ stage=Lost │ │ - │ │ │ reason=... │ │ - │ │ │── notify sales_owner │ - │ │ │ (could reach out for save) │ - │◄── confirmation page │ │ │ - │ "Frozen until . Download your data anytime." │ │ - │ │ │ │ - │ frozen state: │ │ │ - │ portal works READ-ONLY │ │ │ - │ /export available (all products) │ │ │ - │ product APIs return 402 on writes │ │ │ - │ │ │ │ - │ if customer changes mind within 30d: │ │ - │ [Reactivate] → status: frozen → active │ │ - │ no data loss │ │ - │ │ │ │ - │ DAY 30 cron: │ │ │ - │ tenant.delete_at reached │ │ │ - │ build final export ZIP per product ►│ /v1/tenants/{id}/export │ - │ email ZIP link to IT_ADMIN + CXO │ │ │ - │ (signed URL, 7-day TTL) │ │ │ - │ for each product: │ │ - │ DELETE /v1/tenants/{id}/data ────►│ │ │ - │ Keycloak: org archived, users disabled │ │ - │ ERPNext Customer: status=Inactive │ │ - │ tenant.status = archived │ │ - │ │ │ - │ audit_log retained 7y per GDPR / accounting │ │ -``` - -**Self-serve vs. enterprise:** -- Stripe-billed customers cancel in-portal; flow above -- ERPNext-billed (enterprise) customers send written notice; sales rep updates Sales Order; flow runs from `/backstage/tenants/[id]/lifecycle` with the same downstream effects - -### Headless Product Flows - -P1–P13 cover **interactive** products that ship a UI. Products declared as `frontend.type = headless` (see PRODUCT_INTEGRATION_SPEC.md §5) ship no frontend code — customers configure them through a portal-rendered UI and consume them via API/MCP from their own systems. Examples: a notetaker bot, a document classifier, a webhook router, a compliance reporter. - -The portal still hosts these products end-to-end: the customer area, billing, audit, and Backstage all work the same. Only the "use the product" surface changes from a UI to API keys + webhooks. - -### H1 — Customer Enables a Headless Product - -``` - IT ADMIN PORTAL TENANT REGISTRY HEADLESS PRODUCT - │ │ │ │ - │ /acme/products│ │ │ - │ /notetaker │ │ │ - │──────────────►│ │ │ - │ │ load manifest │ │ - │ │ frontend.type = │ │ - │ │ "headless" │ │ - │ │ │ │ - │ │ render portal-owned │ │ - │ │ config page from │ │ - │ │ manifest sections: │ │ - │ │ • API Keys │ │ - │ │ • Webhooks │ │ - │ │ • Usage chart │ │ - │ │ • Docs link │ │ - │ │ • Code samples │ │ - │◄── page ──────│ │ │ -``` - -### H2 — Generate API Key for a Headless Product - -``` - IT ADMIN PORTAL TENANT REGISTRY HEADLESS PRODUCT - │ │ │ │ - │ [Generate Key]│ │ │ - │ name: "prod" │ │ │ - │ scopes:[r,w] │ │ │ - │──────────────►│ │ │ - │ │── POST /api-keys ────►│ │ - │ │ {tenant, scopes, │ │ - │ │ product, name} │ │ - │ │ │ generate raw key │ - │ │ │ store HASH only │ - │ │ │ bind: tenant + │ - │ │ │ product + │ - │ │ │ scopes │ - │ │◄── raw key (once) ────│ │ - │◄── show once ─│ │ │ - │ "Copy now — │ │ │ - │ won't show │ │ │ - │ again" │ │ │ -``` - -### H3 — Customer's System Calls the Headless Product - -``` - CUSTOMER SYSTEM HEADLESS PRODUCT TENANT REGISTRY - │ │ │ - │ POST /v1/sessions │ │ - │ Auth: ApiKey k_xxx │ │ - │ X-Tenant: acme │ │ - │──────────────────────►│ │ - │ │ validate key ───────►│ - │ │ → tenant_id, │ - │ │ scopes │ - │ │◄─────────────────────│ - │ │ enforce scope │ - │ │ tenant_id in EVERY │ - │ │ DB query │ - │ │ process request │ - │ │ emit usage ─────────►│ - │ │ emit audit ─────────►│ - │◄── 200 response ──────│ │ -``` - -### H4 — Async Result Delivered via Webhook - -``` - HEADLESS PRODUCT CUSTOMER WEBHOOK URL PORTAL (delivery log) - │ │ │ - │ async job finishes │ │ - │ load webhook config │ │ - │ for this tenant + │ │ - │ this event type │ │ - │ │ │ - │ POST customer URL ─────►│ │ - │ Body: {event, result, │ │ - │ tenant, signature} │ │ - │◄── 200 ─────────────────│ │ - │ log delivery ────────────────────────────────────► - │ (success/fail, ts, │ │ - │ response code) │ │ - │ │ │ - │ if delivery fails: │ │ - │ retry with backoff │ │ - │ 3 attempts, then │ │ - │ dead-letter │ │ - │ visible in portal at │ │ - │ /webhooks/deliveries │ │ -``` - -### H5 — Headless Product Tile on Customer Dashboard - -``` - USER PORTAL TENANT REGISTRY HEADLESS PRODUCT - │ │ │ │ - │ /acme/dashboard │ │ │ - │─────────────────►│ │ │ - │ │ for each entitled │ │ - │ │ product in JWT: │ │ - │ │ │ │ - │ │ type=interactive → │ │ - │ │ render "Open" tile │ │ - │ │ │ │ - │ │ type=widget → │ │ - │ │ load widget bundle │ │ - │ │ render custom elt │ │ - │ │ │ │ - │ │ type=headless → │ │ - │ │ GET /v1/usage ─────────────────────────────►│ - │ │◄────────────────────── usage summary ────────│ - │ │ render stat tile: │ │ - │ │ "Notetaker │ │ - │ │ 142 sessions │ │ - │ │ last 30d" │ │ - │ │ click → goes to │ │ - │ │ /products/notetaker │ │ - │◄── dashboard ────│ │ │ -``` - -### H6 — Backstage Operates a Headless Product - -``` - US (BACKSTAGE) PORTAL TENANT REGISTRY HEADLESS PRODUCT - │ │ │ │ - │ /backstage/ │ │ │ - │ tenants/acme/ │ │ │ - │ products/ │ │ │ - │ notetaker │ │ │ - │──────────────►│ │ │ - │ │ NO "Impersonate" btn │ │ - │ │ (no UI to enter) │ │ - │ │ │ │ - │ │ shows: │ │ - │ │ • Health │ │ - │ │ • Usage 30/90d │ │ - │ │ • API call errors │ │ - │ │ • Webhook deliveries │ │ - │ │ • Failed deliveries │ │ - │ │ • Admin actions from │ │ - │ │ manifest: │ │ - │ │ [Flush queue] │ │ - │ │ [Rotate keys] │ │ - │ │ [Reset state] │ │ - │ [Flush queue] │ │ │ - │──────────────►│ │ │ - │ │── service token ─────►│ │ - │ │ POST /admin/flush ─────────────────────────► - │ │ │ audit event │ - │ │◄─────────────────────────────────── ok ───── │ - │◄── done ──────│ │ │ -``` +Unchanged for `frontend.type = headless` products (API keys, webhooks, portal-rendered config page, no impersonation). **H5 no longer has a widget branch**: dashboard tiles are either "Open" (standalone), a stat tile fed by `GET /v1/usage` (headless), or a licence/seat tile (cli). --- -## 9. Technology Decisions (Locked) +## 9. Technology Decisions (Locked — 2026-09-11) | Decision | Choice | Rationale | |---|---|---| -| Identity | Keycloak, single realm | Already in CERTifAI; Organizations + IdP brokering built-in | -| Tenant model | Keycloak Organization per customer | Native isolation, JWT claims, no custom multi-tenant auth code | -| Subdomain routing | Orca-Proxy, wildcard cert | Consistent with existing infra; tenant from `Host` header | -| Secret management | Infisical, machine identity per service | Uniform across all services; path-namespaced per service | -| Business operations | ERPNext (Frappe) | CRM + sales + invoicing + HR in one; avoids building our own | -| Customer support | Frappe Helpdesk | Same Frappe bench as ERPNext; native customer-ticket-account link | -| Engineering issues | Gitea Issues | Already running Gitea; Frappe HD → Gitea via REST API (server script) | -| Data isolation | Logical (tenant_id / org_id columns) | Sufficient for Starter/Professional; physical isolation offered for Enterprise | -| Billing — self-serve | Stripe (Starter, Professional) | Standard; portal billing page reads Stripe | -| Billing — enterprise | ERPNext Sales Invoices | Manual invoicing, DATEV export for accountant | -| Customer portal | New Next.js 15 app | Clean slate; existing admin apps have product-specific chrome | -| Tenant Registry | New Go service | Thin glue layer; owns entitlements, IdP config, audit log | -| Products scope | CERTifAI + breakpilot-compliance only | Dataroom and pitch-deck out of scope | +| Identity | Keycloak on core, one realm per platform env (`breakpilot-stage`, `breakpilot-prod`) | One instance to operate; hostname collision avoided; company SSO untouched | +| Tenant model | Keycloak Organization per customer, `tenant_id` org attribute = registry UUID | Native isolation, JWT claims, no custom multi-tenant auth code | +| Tenant routing | Fixed host per env, tenant slug in the path | Orca has no wildcard routing or DNS-01; no custom domains anyway | +| Product UIs | Standalone apps on branded hosts behind SSO; headless; CLI | No embedding contract to maintain; products keep their own stacks | +| Entitlements | tenant-registry is the authority; products call `entitlements/check`; Keycloak carries coarse `tenant_status` only | Finance never touches the IdP (`ERP/02`); no stale entitlement claims | +| Commercial truth | ERPNext (core), always-on link via outbox + webhooks + 15-min reconcile | One accounting system; no delivery-loss blind spot | +| Billing | ERPNext invoicing only (Quotation → SO → SI → Payment Entry, Subscriptions, Dunning); usage records continuous, invoices fixed-tier for launch | B2B DACH customers pay by invoice; no PSP integration before launch | +| CLI licensing | Registry-issued Ed25519 licence JWTs, offline verify, hourly phone-home, 4-state ladder | Works in customer CI and air-gapped setups; one licence system for both CLIs | +| Secret management | Orca project-scoped secrets; Infisical for signing keys + CI | Matches how Orca resolves `${secrets.*}`; prod never global | +| Business operations | ERPNext (Frappe) + Frappe CRM + Helpdesk | CRM + sales + invoicing + HR + support in one | +| Engineering issues | Gitea Issues | Already running; Frappe HD → Gitea via REST | +| Data isolation | Logical (tenant_id / per-tenant DB) | Sufficient for Starter/Professional; physical isolation for Enterprise later | +| Customer portal | Next.js 16 app (`platform/portal`) | Exists; path-based tenancy is a middleware change | +| Tenant Registry | Go service (`platform/tenant-registry`) | Exists; extended with products/plans/subscriptions/usage/licences/outbox | +| Products scope | Prüfwerk (+Werkbank), Werkpilot, Firmwerk | First line; compliance re-onboarded after migration; CERTifAI parked | +| Hosting | Hetzner Cloud, EU; one platform cluster, one VM per env | Legal entity exists; smallest topology that separates stage from prod | --- -## 10. Open Items / Phasing +## 10. Phasing -### Phase 0 — Foundation (pilot-ready, one real customer) -- Orca-Proxy: wildcard TLS, subdomain routing table -- Infisical: machine identities + secrets for all existing services -- Keycloak: Organizations enabled, realm roles (incl. `SALES_REP`), one test org -- Tenant Registry: core schema + API (`/tenants` CRUD + `/activate`), `status` enum -- Backstage minimal: create tenant form, tenant list, impersonation -- Portal login: subdomain detection → Keycloak OIDC → tenant context -- CERTifAI: MongoDB-backed sessions, `org_id` query scoping, role enforcement -- breakpilot-compliance: JWT → `X-Tenant-ID` validated at Next.js proxy -- **Demo tenant `demo` seeded**; sales rep can log in and walk a screen-shared prospect - -### Phase 1 — Customer-Facing Portal -- Full customer dashboard, product tiles, usage summary -- User management and invite flow -- IdP configuration wizard (OIDC + SAML) -- Billing page (ERPNext invoices + Stripe usage) -- Audit log page and CSV/PDF export -- Frappe HD embedded in `/[slug]/support/` - -### Phase 2 — Business Operations -- ERPNext configured: CRM, Sales Orders, Invoicing, HR -- ERPNext → Tenant Registry webhook (Sales Order submit → tenant activate) -- Frappe HD → Gitea escalation (server script) -- Backstage health dashboard (service health, incidents) -- Keycloak protocol mapper (products + plan injected into JWT) -- **Self-serve trial flow P15**: `/start` form, 14-day timer, day-7/12/14 emails, trial → frozen → archived state machine -- **Cancel + offboard flow P16**: cancel modal, 30-day frozen window, automated final-export ZIP, GDPR erasure call to every product -- **Demo nightly reset**: cron at 03:00 Europe/Berlin calls each product's `/v1/tenants/demo/reset` - -### Phase 3 — Product API Surface -- CERTifAI: OpenAPI spec, `/api/v1/health` + `/api/v1/usage` -- breakpilot-compliance: OpenAPI spec, `/api/v1/usage` -- Customer-facing API keys (IT Admin generates, scoped to their org) -- LiteLLM per-tenant API key metering → usage data in portal - -### Phase 4 — Enterprise Tier -- Physical data isolation option (dedicated PostgreSQL schema per tenant) -- Customer-hosted LiteLLM (URL stored in `tenant_products.config`) -- Custom domain support (`compliance.acme.com` → Orca-Proxy → portal) -- MCP servers per product (CERTifAI MCP, compliance MCP) -- SLA enforcement in Frappe HD per plan tier +See `IMPLEMENTATION_PLAN.md`: the migration milestones M-MIG-0 … M-MIG-9 (spec revision → stop on core → staging VM → repo moves → platform services → products → entitlements/licences/ERP link → E2E → dsms) replace the earlier M0–M19 plan. Production is planned separately after the staging gate passes. --- -*End of document. Updated after design review 2026-05-11.* +*End of document. Revised 2026-09-11 (staging rollout).* diff --git a/PRODUCT_INTEGRATION_SPEC.md b/PRODUCT_INTEGRATION_SPEC.md index c04b426..ec436e5 100644 --- a/PRODUCT_INTEGRATION_SPEC.md +++ b/PRODUCT_INTEGRATION_SPEC.md @@ -1,17 +1,19 @@ # Product Integration Specification -**Status:** Design Draft +**Status:** Revised design (2026-09 revision) **Authors:** Sharang, Benjamin -**Date:** 2026-05-11 -**Companion docs:** PLATFORM_ARCHITECTURE.md, INFRASTRUCTURE.md -**Contract version:** 1.0 +**Date:** 2026-05-11 · **revised 2026-09-11** +**Companion docs:** PLATFORM_ARCHITECTURE.md, INFRASTRUCTURE.md, ERP/02 Billing and Entitlements +**Contract version:** 2.0 --- +> **Contract 2.0 (2026-09-11) — breaking changes vs 1.0.** (1) The web-component / widget frontend contract is removed; frontend types are now `standalone | headless | cli`. (2) Entitlements are no longer read from a `products` JWT claim; products ask the tenant-registry (`entitlements/check`). (3) Usage is pushed by the product as events, continuously, instead of being polled daily. (4) The tenant status ladder is `demo | trial | active | warning | restricted | halted | archived`. (5) A licence contract for CLI products is added. No product shipped 1.0, so there is no N-1 support obligation for 1.0. + ## 1. Purpose This document defines the contract that **every product** must implement to be sold on the platform as a B2B building block. The contract is enforced by the Tenant Registry, Customer Portal, and Orca deployment pipeline. A product that does not implement the contract cannot be activated for a tenant. -The contract is designed to be **first-party today, third-party-ready tomorrow** — the technical surface is identical for our own products and any future external developers, with stricter verification gates for the latter. +The contract is **first-party today, third-party-ready tomorrow** — the technical surface is identical for our own products and any future external developers, with stricter verification gates for the latter. --- @@ -19,12 +21,12 @@ The contract is designed to be **first-party today, third-party-ready tomorrow** ``` 1. ONE TENANT, ONE TRUTH - Every request is scoped by org_id from the JWT. Cross-tenant data leakage is the - single largest commercial risk; the spec treats it as a contract violation. + Every request is scoped by tenant_id from the JWT, API key or licence token. Cross-tenant + data leakage is the single largest commercial risk; the spec treats it as a contract violation. -2. PLATFORM OWNS IDENTITY, BILLING, ROUTING - Products NEVER implement their own login, never store passwords, never invoice - customers directly. These are platform concerns. +2. PLATFORM OWNS IDENTITY, ENTITLEMENTS, BILLING, ROUTING + Products NEVER implement their own login, never store passwords, never decide entitlements + locally, never invoice customers. These are platform concerns. 3. PRODUCTS OWN THEIR DOMAIN AND DATA Products own their database, their data model, their backup, their RTO/RPO. @@ -34,7 +36,11 @@ The contract is designed to be **first-party today, third-party-ready tomorrow** Application containers are replaceable in seconds. State lives in databases that have explicit backup contracts. -5. CONTRACT EVOLVES, PRODUCTS DECLARE COMPATIBILITY +5. FAIL CLOSED + If the tenant-registry cannot be reached and the entitlement cache is stale, deny. + CLI products degrade along the licence ladder instead. + +6. CONTRACT EVOLVES, PRODUCTS DECLARE COMPATIBILITY Products declare which contract version they implement. The platform supports N and N-1; deprecation is announced before removal. ``` @@ -43,23 +49,23 @@ The contract is designed to be **first-party today, third-party-ready tomorrow** ## 3. Required Surfaces -A product is composed of five surfaces. Three are mandatory, one is tier-gated, one is mandatory documentation. - ``` -┌──────────────────────┬──────────────────────────────────────────┬───────────────┐ -│ Surface │ What │ Requirement │ -├──────────────────────┼──────────────────────────────────────────┼───────────────┤ -│ Backend API │ REST + OpenAPI 3.0 spec │ REQUIRED │ -│ Frontend │ Web component (custom element) │ REQUIRED │ -│ MCP Server │ MCP server exposing tenant-scoped tools │ REQUIRED for │ -│ │ │ Enterprise │ -│ │ │ tier; opt for │ -│ │ │ Starter/Pro │ -│ Documentation │ README, API docs, integration guide, │ REQUIRED │ -│ │ runbook, data model, GDPR retention │ │ -│ Observability │ /health, /metrics, structured logs, │ REQUIRED │ -│ │ audit event emission │ │ -└──────────────────────┴──────────────────────────────────────────┴───────────────┘ +┌──────────────────────┬──────────────────────────────────────────────┬───────────────────────┐ +│ Surface │ What │ Requirement │ +├──────────────────────┼──────────────────────────────────────────────┼───────────────────────┤ +│ Backend API │ REST + OpenAPI 3.0 spec (§4) │ REQUIRED (standalone, │ +│ │ │ headless); cli: the │ +│ │ │ licence client (§5.C) │ +│ Frontend │ one of: standalone app on its own host │ REQUIRED to declare │ +│ │ behind SSO · headless (portal-rendered) │ the type; no │ +│ │ · cli (downloads + licence page) │ embedding of any kind │ +│ MCP Server │ MCP server exposing tenant-scoped tools │ REQUIRED for │ +│ │ │ Enterprise tier │ +│ Documentation │ README, API docs, integration guide, │ REQUIRED │ +│ │ runbook, data model, GDPR retention │ │ +│ Observability │ /health, /metrics, structured logs, │ REQUIRED │ +│ │ audit + usage event emission │ │ +└──────────────────────┴──────────────────────────────────────────────┴───────────────────────┘ ``` --- @@ -68,490 +74,213 @@ A product is composed of five surfaces. Three are mandatory, one is tier-gated, ### 4.1 Mandatory Endpoints -Every product backend must implement these endpoints. The Tenant Registry health-checks them on deploy; any missing endpoint blocks the registration. - ``` GET /health - Returns 200 if healthy, 503 if unhealthy. - Body: {"status": "ok"|"degraded"|"down", "checks": {"db": "ok", "deps": "ok"}} + 200 {"status": "ok"|"degraded", "checks": {...}} · 503 {"status": "down"} Authentication: NONE (Orca probe) GET /version - Returns product version and contract version it implements. - Body: {"product": "certifai", "version": "1.4.2", "contract": "1.0", - "build": "", "deployed_at": "2026-05-10T..."} + {"product": "pruefwerk", "version": "1.4.2", "contract": "2.0", + "build": "", "deployed_at": "..."} Authentication: NONE GET /v1/usage - Query: ?tenant_id=&from=&to=&project_id= - Returns billing-relevant usage metrics for a tenant (and optional project). - Body: {"tenant_id": "...", "project_id": "...", "period": {...}, - "metrics": {"seats_active": 12, "api_calls": 14203, ...}} - Authentication: SERVICE TOKEN (called by billing job) - Note: products with high-cardinality usage (LLM tokens, etc.) SHOULD also - stream per-event metering to /internal/usage/events on Tenant Registry. - Event shape is Lago-compatible (transaction_id, code, external_subscription_id, - properties) so we can swap to a Lago instance later without changing producers. + ?tenant_id=&from=&to=[&project_id=] + Aggregated usage for dashboards (seats_active, scans, targets, environments, ...). + Authentication: SERVICE TOKEN (portal / registry) + NOTE: billing does NOT poll this. Billing-relevant usage is PUSHED (§9.2): + POST https://registry[-stage].breakpilot.com/v1/usage/events POST /v1/tenants/{id}/provision - Body: {"plan": "...", "config": {...}, "contract_version": "1.0"} - Initializes tenant-specific resources (schemas, default data, queues). - Must be idempotent: a second call with same params is a no-op. - Authentication: SERVICE TOKEN (called by Tenant Registry) + {"plan": "...", "limits": {...}, "addons": {...}, "contract_version": "2.0"} + Idempotent. Authentication: SERVICE TOKEN (tenant-registry) -POST /v1/tenants/{id}/suspend - Soft-suspend: data retained, all customer access blocked. +POST /v1/tenants/{id}/suspend ladder → restricted/halted (writes blocked) +POST /v1/tenants/{id}/reactivate ladder → active +POST /v1/tenants/{id}/terminate {"reason", "scheduled_erasure_at"} Authentication: SERVICE TOKEN -POST /v1/tenants/{id}/reactivate - Reverse of suspend. - Authentication: SERVICE TOKEN +POST /v1/tenants/{id}/export GDPR Art. 20 — signed URL to a ZIP + Authentication: USER JWT (IT_ADMIN or LEGAL) or SERVICE TOKEN (offboarding) -POST /v1/tenants/{id}/terminate - Hard terminate: schedules data for erasure per retention policy. - Body: {"reason": "...", "scheduled_erasure_at": "..."} - Authentication: SERVICE TOKEN +DELETE /v1/tenants/{id}/data GDPR Art. 17 — {"confirm": ""} + Authentication: SERVICE TOKEN + USER JWT (IT_ADMIN) -POST /v1/tenants/{id}/export - GDPR Article 20 (data portability) export for a tenant. - Returns: signed URL to a ZIP containing all tenant data in JSON + binary blobs. - Authentication: USER JWT (IT_ADMIN or LEGAL role) - -DELETE /v1/tenants/{id}/data - GDPR Article 17 (right to erasure) full deletion. - Body: {"confirm": ""} ← safety check - Authentication: SERVICE TOKEN + USER JWT (IT_ADMIN signing off) +POST /v1/tenants/demo/reset restores seed data; portal service token only ``` +`cli` products implement the tenant endpoints on their cloud component if they have one (Firmwerk cloud-server); pure CLIs (Werkpilot) have no backend and are exempt from §4.1 except `/version` inside the binary. + ### 4.2 Authentication Modes ``` -USER JWT Bearer token issued by Keycloak for a user session. - Contains: sub, org_id, org_roles, products, plan. - Validated via Keycloak JWKS endpoint. - Used for: all customer-facing endpoints. +USER JWT Bearer token issued by Keycloak (realm breakpilot-{env}). + Claims: sub, email, tenant_id, tenant_slug, org_roles, realm_roles, + tenant_status, aud, iss. ← NO products / plan claim. + Validate via JWKS (cache 5 min), pin iss AND aud. + Used for: all customer-facing endpoints. -SERVICE TOKEN Short-lived JWT issued by Keycloak via OAuth 2.0 - client_credentials flow. - Each service has a Keycloak client (id: certifai-svc, - compliance-svc, etc.) with declared scopes. - Used for: platform-to-product calls (provisioning), - product-to-product calls (inter-product API). - TTL: 15 minutes max. +SERVICE TOKEN Short-lived JWT via client_credentials (clients: portal-svc-{env}, + tenant-registry-svc-{env}, {product}-svc-{env}). TTL ≤ 15 min. + Used for: platform-to-product and product-to-product calls. -ORCA PROBE No authentication. Local network only. - Used for: /health, /version (Orca polls these). - Must not leak tenant data. +API KEY `Authorization: ApiKey k_...` issued by the portal, verified through + tenant-registry POST /v1/internal/api-keys/verify → {valid, tenant_id, + product, scopes}. Used for: headless products, MCP, Werkbank runners. + +LICENCE TOKEN Ed25519-signed JWT issued by tenant-registry (§5.C). Verified OFFLINE + against /.well-known/licence-keys.json. Used for: CLIs and their cloud + components. + +ORCA PROBE No authentication, local only: /health, /version. ``` ### 4.3 Tenant Scoping Rules ``` -1. EVERY non-probe endpoint extracts tenant context from JWT or path. - USER JWT → tenant = jwt.org_id - SERVICE TOKEN → tenant = path parameter, validated against service scopes - -2. EVERY query to the product database includes WHERE tenant_id = $1. - No exceptions. Code review enforces this; tests verify it. - -3. EVERY response includes only data for the requested tenant. - The product asserts this invariant in middleware (defense in depth). - -4. EVERY log line and audit event includes tenant_id as a structured field. +1. EVERY non-probe endpoint derives the tenant from the credential (JWT tenant_id, API key + binding, licence token tenant) — never from a client-supplied header. +2. EVERY query to the product database is tenant-scoped (per-tenant database, RLS, or + WHERE tenant_id = $1). No exceptions. Code review enforces this; tests verify it. +3. EVERY response includes only data for the requested tenant (asserted in middleware). +4. EVERY log line, audit event and usage event includes tenant_id. ``` -### 4.4 OpenAPI Spec - -Every product publishes `openapi.yaml` at `/openapi.yaml`. The Tenant Registry pulls this on product registration and validates that the mandatory endpoints from §4.1 are present with correct signatures. +### 4.4 Entitlement Check (replaces the `products` claim) ``` -Product OpenAPI must: - - Be valid OpenAPI 3.0 (3.1 not yet — tooling gap) - - Include all mandatory endpoints from §4.1 - - Document all custom endpoints with examples - - Declare authentication mode for each endpoint - - Declare scopes consumed (for SERVICE TOKEN endpoints) - - Include error response schemas (4xx, 5xx) +POST https://registry[-stage].breakpilot.com/v1/internal/entitlements/check +Authorization: Bearer +{"tenant_id": "...", "product": "pruefwerk", "addon": "werkbank" | null} +→ 200 {"allowed": true|false, "status": "active|warning|restricted|halted|trial|demo|archived", + "limits": {"targets": 25, "scans_per_month": 500, "runners": 2, ...}, + "expires_at": "...", "reason": "..."} + +Rules: + - Call on tenant-context creation (login, first request of a session, API-key verify) and + cache per tenant for ≤ 60 s. Re-check on every write if the cache is older than 60 s. + - allowed=false → 403 with {"error": "not_entitled", "product": "..."} and the portal's + catalog URL in the body so the UI can show "Not in your plan". + - registry unreachable + cache stale → deny (fail closed). Emit a `bp_entitlement_check_errors` + metric so it is visible. + - `status` drives the lifecycle behaviour in §9.3; limits are enforced by the product. ``` +### 4.5 OpenAPI Spec + +Every product with a backend publishes `openapi.yaml` at `/openapi.yaml` (OpenAPI 3.0), including all §4.1 endpoints, the authentication mode per endpoint, scopes consumed, and 4xx/5xx schemas. The registry validates it at registration. + --- ## 5. Frontend Contract -A product declares its frontend type in the manifest. The portal renders accordingly. Three types are supported: +A product declares its frontend type in the manifest. **No type embeds product UI in the portal**: no iframes, no custom elements, no remote bundles. The portal links; the product owns its UI. ``` -interactive Full UI shipped as a web component custom element. - Customer OPERATES the product through this UI. - Examples: CERTifAI, breakpilot-compliance, classic SaaS products. +standalone Full UI served by the product on its own host (pruefwerk[-stage].breakpilot.com), + behind the platform Keycloak realm (SSO). The portal shows a tile → "Open". + Examples: Prüfwerk dashboard, Firmwerk cloud-server pages. -widget Only a small dashboard tile component; no full product page. - Customer SEES product output in a tile; deeper management - happens on a portal-rendered config page. - Examples: monitoring, status reporting. +headless No frontend code. The portal renders a generic management UI (API keys, + webhooks, usage, docs, code samples) from a portal_config block in the manifest. + Customers consume the product via API / MCP from their own systems. -headless No frontend code at all. The portal renders a generic - management UI from a portal_config block in the manifest. - Customer CONFIGURES (API keys, webhooks) and their own - systems consume the product via API/MCP. - Examples: notetaker bot, document classifier, webhook router. +cli Product runs on the customer's machines. The portal renders downloads, licence + status, seats/environments and a "Sign in from the CLI" hint. A cloud component + (if any) is declared as a standalone or headless sub-surface. ``` -The portal branches its rendering on `manifest.frontend.type`. Backend, MCP, observability, and lifecycle contracts are identical across all three types — only the customer-facing surface changes. - -### 5.A Interactive (Web Component) - -The frontend is a **custom element** registered with a product-specific tag name. The Customer Portal loads the bundle and renders the element with attributes passed in by the portal. - -#### 5.A.1 Why web components - -Our products span Rust/Dioxus, Next.js, Go, Python. Web components are the only framework-agnostic surface that lets all of these ship a frontend without forcing a stack rewrite: - -- CERTifAI compiles Dioxus → WASM → wraps in a custom element -- breakpilot-compliance wraps React components via `@r2wc/react-to-web-component` -- Any future Vue/Svelte/Solid product also works - -#### 5.A.2 The Tag Contract - -Each product declares ONE primary tag in its manifest. The portal renders it like this: - -```html - -``` - -Attributes the portal passes (the product MUST handle these): +### 5.A Standalone ``` -tenant tenant slug (acme) -tenant-id tenant UUID (uuid-acme) -jwt short-lived JWT (≤ 5 min), product validates against Keycloak JWKS -locale en / de / fr / es / pt -theme light / dark -api-base backend URL the product should call -audit-callback-url URL to POST audit events to (portal-relative) +HOST one branded host per environment: {product}-stage.breakpilot.com / {product}.breakpilot.com + Sub-surfaces on the same host by path: /mcp/*, /docs/*, /api/*. +SSO OIDC PKCE against realm breakpilot-{env}; the product's Keycloak client is + {product}-dashboard-{env}. The portal hands off by plain link; Keycloak's realm + session makes the second login silent. +RETURN Product UIs show a "Back to portal" link to https://app[-stage].breakpilot.com/{slug}/dashboard + and read `tenant_slug` from the token for it. +THEME Consume @breakpilot/design-tokens CSS variables if you want; not required. + Respect prefers-color-scheme. +SECURITY Product responses set X-Frame-Options: DENY (or CSP frame-ancestors 'none'), + a strict CSP, and an explicit CORS allowlist limited to the portal host and + the product's own host. `CorsLayer::permissive()` and `webOrigins: ["+"]` + are contract violations. +TENANT UI must display the tenant name and the ladder banner (warning/restricted/ + halted) it gets from the entitlement check. ``` -#### 5.A.3 Events the Product Must Emit +### 5.B Headless -The component emits events upward via `CustomEvent`. The portal listens for these and integrates them: +Unchanged from 1.0: the portal renders API keys, webhooks, usage, docs and code samples from `portal_config`; keys are portal-owned and verified via `/v1/internal/api-keys/verify`; webhook configuration and delivery logging are portal-owned (`/internal/webhooks/dispatch`); no impersonation. + +### 5.C CLI (licence contract) ``` -breakpilot:navigate - Detail: {path: "/sub/route", title: "Page Title"} - Portal updates browser URL + breadcrumb without reloading. +LOGIN ` login` runs the OAuth device-authorization grant against + https://auth.breakpilot.com/realms/breakpilot-{env} (public client {product}-cli), + then POSTs the user token to registry /v1/licences {product, machine_id, hostname, + version} and stores the returned licence token under the CLI's config dir + (e.g. ~/.config/werkpilot/licence.jwt, ~/.config/firmwerk/licence.jwt). -breakpilot:error - Detail: {code: "...", message: "...", recoverable: true|false} - Portal shows toast / blocking error. +TOKEN JWT, alg EdDSA (Ed25519), kid → key in https://registry[-stage].breakpilot.com/ + .well-known/licence-keys.json (cache the key set for 30 days). + Claims: iss, sub (tenant_id), tenant_slug, product, sku, tier, seats|environments, + valid_until, grace {warn_days: 7, degrade_days: 14, stop_days: 30}, machine_id, + iat, exp (= valid_until + stop_days), jti (= licence id). -breakpilot:audit - Detail: {action: "...", target: "...", metadata: {...}} - Portal forwards to central audit log via audit-callback-url. +VERIFY OFFLINE on every start: signature, exp, product, machine_id (unless the SKU is + floating). Never phone home synchronously on the critical path. -breakpilot:loading - Detail: {state: "start"|"end", description: "Generating DSFA..."} - Portal shows progress indicator. +HEARTBEAT Hourly (jittered) POST /v1/licences/heartbeat {jti, version, usage: {...}}. + A 200 returns a refreshed token (new valid_until). 402/410 = revoked/halted: + keep the old token but start the ladder from `degraded`. Network errors: keep + counting from the last successful heartbeat. -breakpilot:request-upgrade - Detail: {feature: "...", required_plan: "enterprise"} - Portal opens upgrade-quote flow. +LADDER days since last successful heartbeat (or since valid_until if earlier): + 0–7 Healthy full function + 7–14 Warning full function + banner on every invocation + 14–30 Degraded read-only / analysis only (writes, builds, seals refused) + > 30 Hard-stop refuse to start except ` login` and ` licence status` + Firmwerk: read-only usage is free forever, so Degraded == free tier. + +USAGE Heartbeat carries daily usage counters (sessions, environments, builds) which the + registry turns into usage events (§9.2). No separate metering call. + +AIR-GAP Signed offline licence packages (same token, longer validity, monthly Enterprise / + quarterly Business rotation) issued from Backstage; no heartbeat expected. + +CLOUD PART A cloud component (firmwerk-cloud-server) verifies the same licence token as a + bearer credential and calls entitlements/check for limits. It MUST NOT keep its + own tenant/api-key/licence tables. ``` -#### 5.A.4 Design System Compatibility - -The platform publishes `@breakpilot/design-tokens` (CSS variables, fonts, spacing). Products are encouraged but not required to consume it. The portal injects design tokens into the shadow DOM root so consuming them is a single CSS line: - -```css -:host { color: var(--bp-text); background: var(--bp-surface); } -``` - -Products that ship custom styling must respect the `theme` attribute and the prefers-color-scheme media query. - -#### 5.A.5 Bundle Loading - -``` -Product publishes a bundle at: - https://cdn.breakpilot.com/products/{name}/{version}/element.js - -Portal loads it lazily via dynamic import when the user navigates to /[tenant]/products/{name}. -Portal caches the bundle URL per product version (declared in tenant_products.config). -Bundle size budget: ≤ 500KB gzipped for first load. -``` - -### 5.B Widget - -A widget product declares ONE custom element that renders only as a dashboard tile. It receives the same attributes as interactive products but emits no `breakpilot:navigate` events — clicking the tile takes the user to a portal-rendered config page (same surface as headless products in §5.C). - -```html - -``` - -Constraints: - -``` -Bundle size budget ≤ 50KB gzipped (widgets load eagerly on dashboard) -Dimensions declared in manifest (e.g., 200×120 or 400×240) -Refresh widget polls own API; portal does not push updates -Allowed events breakpilot:error, breakpilot:audit, breakpilot:request-upgrade - (NOT breakpilot:navigate — click-through is portal-controlled) -``` - -API keys, webhooks, and full management UI for widget products use the same portal-rendered config page as headless products (§5.C). - -### 5.C Headless - -The product ships NO frontend code. The portal renders a generic management UI from a `portal_config` block in the manifest. This page is served at `/[tenant]/products/{name}` and contains the same elements regardless of which product it is — populated entirely from manifest data. - -#### 5.C.1 What the Portal Renders - -``` -┌──────────────────────────────────────────────────────────┐ -│ Notetaker [Status: OK] │ -│ ────────────────────────────────────────────────────────│ -│ │ -│ USAGE (last 30 days) │ -│ ┌──────────────────────────────────────────────────┐ │ -│ │ 142 sessions processed ▁▃▆█▆▄▂▃▅▆▄▂▁▂▃▄▅▆▇█ │ │ -│ └──────────────────────────────────────────────────┘ │ -│ │ -│ API KEYS [+ Generate] │ -│ ──────────────────────────────────────────────────── │ -│ • prod-key k_xxx...4f12 scopes: r,w 2026-01-04│ -│ • staging-key k_xxx...9a83 scopes: r 2026-04-22│ -│ │ -│ WEBHOOKS [+ Add] │ -│ ──────────────────────────────────────────────────── │ -│ • https://acme.example.com/notetaker/cb │ -│ events: session.completed, session.failed │ -│ last 24h: 142 delivered, 0 failed [Test] │ -│ │ -│ CODE SAMPLES │ -│ ──────────────────────────────────────────────────── │ -│ [curl] [JS] [Python] │ -│ curl -X POST https://notetaker-api.breakpilot.com/v1 │ -│ -H "Authorization: ApiKey k_xxx" │ -│ -H "X-Tenant: acme" │ -│ -d '{...}' │ -│ │ -│ DOCS ► developers.breakpilot.com/products/notetaker │ -└──────────────────────────────────────────────────────────┘ -``` - -#### 5.C.2 Manifest Requirement - -A headless product must include a `portal_config` block declaring: - -- **sections**: which UI sections to render (subset of: `api_keys`, `webhooks`, `usage`, `docs`, `code_samples`, `custom_actions`) -- **webhook_events**: the catalog of events the product can emit -- **api_key_scopes**: the catalog of scopes that can be granted on a key -- **code_samples**: at least one language with a working request example -- **status_endpoint**: optional URL for the portal to poll for the status badge - -See §10.1 for the full schema. - -#### 5.C.3 API Keys - -API keys are a portal concern, not a product concern. Tenant Registry generates and stores key hashes; the product validates incoming keys against `POST /internal/api-keys/verify` on Tenant Registry. This means: - -- Key rotation is portal-controlled -- Scope enforcement is consistent across all headless products -- Revocation is instant (registry updates a single row) - -#### 5.C.4 Webhooks - -The portal owns webhook configuration UI and delivery logging. Products POST event payloads to a portal endpoint (`/internal/webhooks/dispatch`); the portal handles signing, delivery, retry, dead-letter, and the customer-visible delivery log. - -This keeps webhook UX consistent across all headless products and means a product cannot accidentally leak events from one tenant to another's webhook URL. - -#### 5.C.5 No Impersonation - -Backstage shows no "Impersonate" button for headless products — there is no UI to enter. Debugging is via API call logs, audit events, webhook delivery history, and admin actions declared in the manifest (e.g., "Flush Queue", "Rotate Keys", "Reset State"). - --- ## 6. MCP Server (Required for Enterprise) -### 6.1 What it is - -An MCP (Model Context Protocol) server exposes the product's capabilities as tools that customer-side AI agents can call. The customer's IT Admin configures the MCP endpoint in their AI agent platform (Claude Desktop, Cursor, internal agents, etc.). - -### 6.2 Required Behavior +Unchanged in substance. Endpoint per product on its own host: `https://pruefwerk[-stage].breakpilot.com/mcp`. Authentication via scoped API key or tenant-bound MCP token (verified through the registry), tools tenant-scoped by construction, catalog declared in the manifest, every tool call audited. ``` -1. ONE MCP server per product - Endpoint: https://mcp.{product}.breakpilot.com (or unified mcp.breakpilot.com/{product}) - -2. Authentication via SCOPED API KEY - Customer IT Admin generates API key in /[tenant]/settings/api-keys. - Key carries tenant_id binding and scopes (read/write per product domain). - No user JWT for MCP — agents authenticate as the org, not as a user. - -3. Tools are tenant-scoped - Every tool call uses the API key's tenant_id binding. - Cross-tenant calls are impossible by construction. - -4. Tool catalog declared in manifest - Each tool: name, description, parameters (JSONSchema), required_scopes. - -5. Audit every tool call - Emit breakpilot:audit-equivalent server-side: actor=api_key_id, - action=tool_name, metadata=parameters. +Prüfwerk MCP tools (existing): + list_targets · run_scan · get_scan_results · list_findings · get_sbom · list_cves · + create_pentest_run · get_control_mapping +Firmwerk cloud MCP (later): list_environments · get_sbom · list_vex ``` -### 6.3 Example Tool Catalogs - -``` -CERTifAI MCP tools: - list_ai_agents → returns agents configured for this tenant - get_llm_usage → returns LiteLLM usage for date range - run_news_search → SearXNG search - list_chat_sessions → user's chat history - -Compliance MCP tools: - create_dsfa → starts a DSFA workflow - check_tom_status → returns TOM compliance status - list_dsr_requests → returns open Data Subject Requests - approve_dsfa → marks DSFA as approved - list_ai_act_assessments → returns AI Act assessments -``` - -### 6.4 Activation - -Enterprise customers automatically get MCP enabled. Starter/Pro customers see "Available on Enterprise" in the API Keys page. Tenant Registry checks `tenant.plan` before issuing an MCP API key. +`tenant.plan` is no longer a token claim: the registry checks the tier when issuing an MCP key. --- ## 7. Documentation Contract -A product ships five required documents. They are published at `developers.breakpilot.com/products/{name}/`. - -``` -1. README What does it do? Value prop in 200 words. - Who is the typical user? What are the workflows? - -2. API Reference Auto-generated from openapi.yaml. - Hosted via Redoc or Stoplight Elements. - -3. Integration Guide For customer IT teams. How to: - - Enable the product on their tenant - - Configure SSO and roles - - Wire into their workflows - - Use the MCP server (if applicable) - - Generate and manage API keys - -4. Operational Runbook For us. How to: - - Deploy a new version - - Roll back - - Debug a stuck tenant - - Reset tenant state - - Investigate slow queries - -5. Data Model + GDPR What data is stored, in which table/collection, - personal data category (Art. 9 special category?), - retention period, GDPR lawful basis. - Used by customer DPOs for their own Verzeichnis. -``` +Unchanged: README, API reference (from openapi.yaml), integration guide, operational runbook, data model + GDPR table. Published at `{product}.breakpilot.com/docs/` (product-owned, e.g. VitePress with `base: '/docs/'`) and linked from the catalog manifest. --- ## 8. Observability Contract -### 8.1 Health Check - -``` -GET /health returns: - 200 {"status": "ok", "checks": {...}} — all good - 200 {"status": "degraded", "checks": {...}, "reason"} — degraded but serving - 503 {"status": "down", "checks": {...}, "reason"} — restart me -``` - -Orca polls every 30s. Three consecutive 503s triggers automatic restart. - -### 8.2 Metrics - -``` -GET /metrics returns Prometheus exposition format. - -Required metrics: - bp_http_requests_total{method, route, status, tenant_id} - bp_http_request_duration_seconds{method, route, tenant_id} - bp_active_tenants_gauge - bp_db_query_duration_seconds{operation} - bp_external_api_calls_total{provider, status} (LLM calls, etc.) -``` - -### 8.3 Structured Logging - -``` -All logs are JSON. All log lines include: - ts ISO-8601 timestamp - level debug|info|warn|error - service product name (certifai) - tenant_id tenant UUID (or "system" for non-tenant ops) - user_sub user UUID if applicable - request_id trace ID - msg human-readable message - ... additional structured fields - -No PII in logs (use the PII redaction middleware from breakpilot-core). -``` - -### 8.4 Audit Events - -Audit events go to the central audit log in Tenant Registry. Products emit them via POST to the audit-callback-url passed by the portal (frontend) or directly to Tenant Registry API (backend). - -``` -Event format (Retraced-shape — transformable 1:1 if we swap to BoxyHQ Retraced later): - { - "tenant_id": "uuid-acme", # → Retraced "group.id" - "project_id": "uuid-prod" | null, # optional sub-tenancy scope - "product": "certifai", # which product emitted - "actor": { - "id": "user-uuid" | "svc:certifai" | "api_key:keyid", - "type": "user" | "service" | "api_key", - "name": "alice@acme.com" - }, - "action": "dsfa.approve", # dotted: . - "crud": "u", # c|r|u|d - "target": { - "id": "", - "type": "dsfa" | "llm_config" | ..., - "name": "" - }, - "source_ip": "1.2.3.4", - "description": "Alice approved DSFA #42 for Customer Data Processing", - "fields": {...}, # additional structured metadata - "created_at": "2026-05-11T14:23:01Z" - } - -Mandatory event categories per product: - config changes everything in product settings - data exports anyone exporting tenant data - data deletions erasures and bulk deletes - permission changes role grants/revocations within product - approvals business-significant approvals (DSFA, etc.) - cross-product calls service-token calls into other products (auto-emitted - by both caller and callee, with on_behalf_of in fields) -``` - -The portal /audit page renders these events filtered by tenant + product + -actor + action + time range. The schema is intentionally Retraced-compatible -so the storage layer can be swapped without changing producers. +§8.1 health, §8.2 metrics (add `bp_entitlement_check_total{result}`, `bp_entitlement_check_errors_total`, `bp_usage_events_sent_total{metric}`, `bp_licence_heartbeats_total{result}` for CLI cloud parts), §8.3 JSON logs with `tenant_id`, §8.4 audit events (Retraced shape, `POST registry /v1/audit`) — unchanged from 1.0. OTel export goes to `otel.breakpilot.com` (core SigNoz), service name `{product}-{component}-{env}`. --- @@ -561,656 +290,356 @@ so the storage layer can be swapped without changing producers. ``` [REGISTRATION] - - Register an OIDC client in Keycloak (id: {product}-client) - Confidential, client_credentials grant for service tokens, - authorization_code grant if product has its own UI flows. - - Declare role mappings in product manifest: - role_mappings: - IT_ADMIN: Admin - LEGAL: Auditor - FINANCE: ReadOnly - USER: Member - - Declare an entitlement key (e.g. "certifai") that goes into JWT products claim. + - Keycloak clients in realm breakpilot-{env}: + {product}-dashboard-{env} public PKCE (standalone UI) + {product}-svc-{env} confidential, client_credentials (service token) + {product}-cli public, device-authorization grant (cli only) + - Client scope {product}-audience adds aud: {product} to user tokens. + - Declare role mappings in the manifest (IT_ADMIN → Admin, …). [RUNTIME] - - Validate JWT via Keycloak JWKS endpoint (cache JWKS for 5 min). - - Reject if products claim does not include this product's entitlement key. - - Reject if iss is not the platform Keycloak. - - Reject if exp expired or nbf future. + - Validate JWT via JWKS (cache 5 min). Reject if iss ≠ the realm's issuer, if aud does not + include {product}, if exp passed / nbf future, or if tenant_id is missing. + - Entitlement comes from the registry (§4.4), NEVER from the token. + - tenant_status in the token is a hint for banners; the registry answer is authoritative. [NEVER] - Never validate JWT against a static secret. JWKS only. - Never issue tokens. Never accept passwords. Never store credentials. + - Never skip audience/issuer validation ("validate_aud = false" is a contract violation). ``` ### 9.2 Control Plane ``` [REGISTRATION] - - On first deploy, product POSTs to Tenant Registry: - POST /catalog/products - body: manifest (see §10) - Tenant Registry verifies the manifest, pulls openapi.yaml, validates - mandatory endpoints, registers the product. - - - Product appears in Backstage product picker when creating sales orders. + - On first deploy, product POSTs its manifest to tenant-registry POST /v1/catalog/products + (service token). The registry validates it, pulls openapi.yaml, checks §4.1, registers the + product with its launch URLs per environment and its add-ons. [LIFECYCLE] - - On tenant.activate: Tenant Registry calls product /v1/tenants/{id}/provision - - On tenant.suspend: calls /suspend - - On tenant.churn: calls /terminate - - On contract.renew: no call (idempotent: just stays active) + - On tenant.activate: registry → /v1/tenants/{id}/provision (per entitled product, fan-out) + - ladder → restricted/halted: registry → /suspend ; ladder → active: /reactivate + - On offboarding: registry → /export then DELETE /v1/tenants/{id}/data + - Provisioning calls are retried from the registry outbox; products must be idempotent. -[USAGE METERING] - - Tenant Registry runs a daily job hitting product /v1/usage for billing. - - Product is responsible for accurate metering and idempotent reporting. +[USAGE — PUSH, CONTINUOUS] + - Product POSTs usage events as they happen (batch every ≤ 60 s): + POST /v1/usage/events + [{"idempotency_key": "::", "tenant_id": "...", + "product": "pruefwerk", "metric": "scan.completed", "quantity": 1, + "occurred_at": "...", "properties": {"target_id": "..."}}] + → 202. Retry on 5xx with the same idempotency_key; the registry dedups. + - Metrics per product are declared in the manifest (`usage.metrics`) and map to the SKU + sheet's quota dimensions (targets, scans/month, seats, environments, tokens). + - The registry forwards usage to ERPNext (usage records on the tenant's Subscription). + Invoices are fixed-tier at launch; metered SKUs switch on later without product changes. + - GET /v1/usage (§4.1) remains for dashboards only. -[BACKSTAGE ACTIONS] - - Product declares custom admin actions in manifest: - admin_actions: - - name: "Rebuild RAG Index" - endpoint: POST /v1/tenants/{id}/admin/rebuild-rag - confirm: required - plane: data - - Backstage renders these as buttons on /backstage/tenants/{id}/products/{name} - - Calls are SERVICE TOKEN authenticated and audit-logged. +[BACKSTAGE ACTIONS] unchanged (admin_actions in manifest, service-token calls, audited). -[AUDIT EVENTS] - - Product POSTs all audit events to Tenant Registry /audit endpoint. - - Tenant Registry stores them in audit_log table for cross-product unified view. +[AUDIT EVENTS] unchanged (POST registry /v1/audit). ``` -### 9.3 Data Plane +### 9.3 App Plane (data + lifecycle) ``` -[DATA OWNERSHIP] - - Product owns its database. No other service queries it directly. - - Cross-product composition is via the inter-product service-token API (§11), - never via shared DB connections. +[DATA OWNERSHIP / ISOLATION / PROJECT SCOPING / BACKUP / GDPR / RESIDENCY] unchanged from 1.0. -[ISOLATION] - - Every table/collection has a tenant_id (or org_id) column. - - Every query filters by it. - - Database user permissions cannot bypass it. +[TENANT LIFECYCLE CONTRACT — ladder] + Products MUST honor the status returned by entitlements/check (tenant_status in the token + is a hint): -[PROJECT SCOPING — OPTIONAL] - - Products MAY support sub-tenancy via projects (mirrors GCP Project / - AWS Account pattern). Allows customers to separate dev / staging / prod - or per-team data within a single tenant. - - Declared in manifest: - data: - supports_projects: true - - Implementation: - - All tenant-scoped tables/collections add project_id column. - - Compound unique constraints become (tenant_id, project_id, key). - - All endpoints accept optional ?project_id=; absence means - the tenant's default implicit project. - - JWT may carry an active project_id claim; products SHOULD respect it - if present. - - Reference implementation: breakpilot-compliance already uses this pattern - (sdk_states UNIQUE on (tenant_id, project_id) since March 2026). - - Products that do NOT support projects must still gracefully ignore - project_id parameters (return tenant-wide data). + ┌────────────┬────────────────────────────────────────────────────────────────────────┐ + │ status │ Product behaviour │ + ├────────────┼────────────────────────────────────────────────────────────────────────┤ + │ demo │ Accept all calls, no usage events with billing effect, honour │ + │ │ /v1/tenants/demo/reset, audit tagged {"demo": true}. │ + │ trial │ Accept all calls up to manifest trial_quota; over quota → 429 + │ + │ │ X-Trial-Limit-Reset. Show "Trial" in the UI banner area. │ + │ active │ Normal operation. (Betriebsbereit)│ + │ warning │ Normal operation + persistent banner "payment overdue". (Warnung) │ + │ restricted │ Reads and /export allowed; writes / new runs / scans → 402; │ + │ │ background jobs paused; webhooks stop. (Eingeschränkt) │ + │ halted │ Only /export and read of existing exports; everything else → 402. │ + │ │ Data retained for the export window. (Angehalten) │ + │ archived │ All API calls return 410 Gone. Data already deleted. │ + └────────────┴────────────────────────────────────────────────────────────────────────┘ -[TENANT LIFECYCLE CONTRACT] - Products MUST honor the tenant.status passed in the JWT (`tenant_status` - custom claim) and behave per the table below. See PLATFORM_ARCHITECTURE.md - P15 + P16 for the full state machine. - - ┌──────────┬───────────────────────────────────────────────────────────┐ - │ status │ Product behavior │ - ├──────────┼───────────────────────────────────────────────────────────┤ - │ demo │ Accept all calls. Apply NO billing meter. Honor │ - │ │ /v1/tenants/demo/reset (idempotent). Seed from │ - │ │ catalog.demo.seed_data_url. Audit emitted but tagged │ - │ │ {"demo": true} so portal can hide from real audit. │ - ├──────────┼───────────────────────────────────────────────────────────┤ - │ trial │ Accept all calls up to catalog.trial_quota; over quota │ - │ │ return 429 with header X-Trial-Limit-Reset. Show "Trial" │ - │ │ context in any product UI banner area provided by host. │ - ├──────────┼───────────────────────────────────────────────────────────┤ - │ active │ Normal operation. │ - ├──────────┼───────────────────────────────────────────────────────────┤ - │ frozen │ Per data.frozen_behavior in manifest (typically reads │ - │ │ allowed, writes return 402, background jobs paused). │ - │ │ /export MUST work; webhook deliveries MUST stop. │ - ├──────────┼───────────────────────────────────────────────────────────┤ - │ archived │ All API calls return 410 Gone. Data already deleted by │ - │ │ the offboarding step; this state is for audit only. │ - └──────────┴───────────────────────────────────────────────────────────┘ - - Products MUST implement: - - GET /v1/tenants/{id}/export - Returns one ZIP per tenant containing every format declared in - data.offboarding_export_formats. Synchronous OK if <60s; async - with signed URL otherwise. - - DELETE /v1/tenants/{id}/data - Removes all tenant data within 30 days. Audit log retained - separately (see §8.4). Idempotent. - - POST /v1/tenants/demo/reset - Restores seed data. Only callable from the portal service token. - -[BACKUP CONTRACT] - - Product declares in manifest: - backup: - data_stores: [postgres, qdrant, minio] - rpo: 6h - rto: 30min - retention_days: 30 - - Infra Plane executes backups per declaration (pg_dump, etc.). - - Product publishes restore procedure in operational runbook. - -[GDPR ENDPOINTS] - - /v1/tenants/{id}/export returns ALL data for the tenant (JSON + blobs in ZIP). - - DELETE /v1/tenants/{id}/data deletes everything within 30 days of call. - - Both endpoints emit audit events. - -[DATA RESIDENCY] - - All data stays in EU (database, object storage, cache). - - Product declares any external data flows (e.g., LLM calls to OpenAI EU endpoint) - in the data model documentation. + CLI products apply the licence ladder in §5.C instead (Healthy/Warning/Degraded/Hard-stop). ``` ### 9.4 Infra Plane ``` -[IaC] - - Orca manifest at: /orca/manifests/{vm}/{product}.toml - - Manifest declares: image, resource limits, health check, secret refs, - network rules, replicas, restart policy. - - Changes go through Gitea PR → Gitea Actions → Orca apply. - -[SECRETS] - - All secrets via Infisical machine identity. - - Secret path namespacing: /prod/{product}/{KEY} - - Manifest references paths, never values: - secrets: - DB_URL: /prod/certifai/MONGODB_URI - LLM_KEY: /prod/certifai/LITELLM_MASTER_KEY - - Bootstrap secrets (DB URIs for Keycloak only) are the lone exception. - -[NETWORKING] - - Product services bind only to the private network. - - Public-facing routes pass through Orca-Proxy. - - Inter-product calls use internal DNS names (e.g., certifai.internal:8080). - -[BUILD + DEPLOY] - - Dockerfile in product repo root. - - Gitea Actions pipeline: - fmt → lint → test → build → push → orca apply → e2e - - Image tagged with git SHA + semver. - -[COLD START] - - Product declares startup dependencies in manifest: - depends_on: [keycloak, postgres-app, infisical] - - Orca enforces ordering on full restart (see INFRASTRUCTURE.md §10 Scenario F). +[IaC] Orca service file in platform/orca-platform: services/{product}-{env}/service.toml, + one [[service]] per container, placement.node = the env's VM, resources.memory, + health check, `${secrets.KEY}` references only. CI runs validate.sh. +[SECRETS] Orca project-scoped secrets (`orca secrets set --project {product}-{env}`). + Never global. Licence signing keys live in Infisical, read by the registry only. +[NETWORK] Products bind to the project network; public routes are declared with + `domain` / `routes` on the service; cross-node calls (none by design) use HTTPS. +[BUILD] Dockerfile in repo root (or Dockerfile.{component}); Gitea Actions: + fmt → lint → test → build → trivy → push repo.breakpilot.com/{product}/{image} + :sha- + :latest → cosign → signed webhook to the platform master. +[COLD START] `depends_on` in the service file; Orca orders startup. ``` --- ## 10. Product Manifest -The canonical declaration of a product, used by Tenant Registry, Orca, and Backstage. One file, committed to product repo, applied via deployment pipeline. - ```yaml # product.manifest.yaml -schema_version: "1.0" +schema_version: "2.0" product: - id: certifai - name: "CERTifAI" - description: "Self-hosted GDPR-compliant AI infrastructure dashboard" - vendor: breakpilot # we; future third-parties will use their slug - contract_version: "1.0" + id: pruefwerk + name: "Prüfwerk" + description: "Compliance scanner: SBOM, DAST, pentest orchestration, PLC provisioning tests" + vendor: breakpilot + contract_version: "2.0" product_version: "1.4.2" - repo: git.breakpilot.com/sharang/certifai + repo: git.breakpilot.com/platform/pruefwerk catalog: - # Renders in /[tenant]/catalog and /backstage/products - category: "AI Infrastructure" # AI Infrastructure | Compliance | Productivity | Security | Data - tagline: "GDPR-compliant LLMs without leaving the EU" - hero_image: https://cdn.breakpilot.com/products/certifai/hero.png - screenshots: - - https://cdn.breakpilot.com/products/certifai/dashboard.png - - https://cdn.breakpilot.com/products/certifai/agents.png - pricing_summary: "From €X/seat/month — included on Professional and Enterprise plans" - available_on_plans: [trial, professional, enterprise] # 'trial' opt-in for self-serve + category: "Security" # AI Infrastructure | Compliance | Productivity | Security | Data | Developer + tagline: "CRA readiness for machine software — scan, prove, fix" + hero_image: /docs/assets/hero.png # served by the product itself + pricing_summary: "From €1,490/tenant/month (CRA-CSA-CLD-STD)" + skus: [CRA-CSA-CLD-STD, CRA-CSA-CLD-BUS, CRA-CSA-CLD-ENT, CRA-CSA-CLD-SCAN] + addons: + - id: werkbank + name: "Werkbank runner" + skus: [CRA-WBK-CLD-STD, CRA-WBK-CLD-BUS, CRA-WBK-CLD-ENT] + limit_key: runners + available_on_plans: [trial, standard, business, enterprise] trial_days: 14 - trial_quota: # caps applied while tenant.status == trial - llm_tokens_per_day: 100_000 - api_calls_per_day: 10_000 - works_well_with: [compliance] # cross-product affinity; surfaced in catalog - depends_on_products: [] # hard dependencies (rare; for compositions) - + trial_quota: { targets: 2, scans_per_month: 10 } + works_well_with: [firmwerk, werkpilot] demo: - supported: true # MUST be true unless explicitly waived - seed_data_url: https://cdn.breakpilot.com/products/certifai/demo/seed-v3.tar.gz - reset_endpoint: /v1/tenants/demo/reset # called nightly by portal cron - persona_hints: # for sales rep talk track - - "GDPR officer at a 200-person SaaS" - - "CTO replacing OpenAI calls with EU-hosted LLMs" + supported: true + seed_data_ref: pruefwerk/seed-v1 # platform/seed-data + reset_endpoint: /v1/tenants/demo/reset identity: - oidc_client_id: certifai-client - entitlement_key: certifai - role_mappings: - IT_ADMIN: Admin - CXO: Member - FINANCE: Viewer - LEGAL: Viewer - USER: Member - required_scopes: - - read:agents - - write:agents - - read:usage + clients: + dashboard: pruefwerk-dashboard-{env} + service: pruefwerk-svc-{env} + audience: pruefwerk + role_mappings: { IT_ADMIN: Admin, CXO: Member, USER: Member, FINANCE: Viewer, LEGAL: Viewer } frontend: - type: interactive # interactive | widget | headless - tag: certifai-dashboard - bundle_url: https://cdn.breakpilot.com/products/certifai/{version}/element.js - bundle_size_kb: 380 - routes: - - path: / - label: "Dashboard" - - path: /agents - label: "AI Agents" - required_role: Member - - path: /providers - label: "Providers" - required_role: Admin + type: standalone # standalone | headless | cli + url: + stage: https://pruefwerk-stage.breakpilot.com + prod: https://pruefwerk.breakpilot.com + docs_path: /docs + back_to_portal: true backend: openapi_url: /openapi.yaml - base_url: https://certifai-api.internal/v1 + base_url: # internal, per env + stage: http://pruefwerk-agent-stage:3001 + prod: http://pruefwerk-agent-prod:3001 health_url: /health - service_token_audience: certifai-svc + service_token_audience: pruefwerk mcp: enabled: true required_plan: enterprise - endpoint: https://mcp.breakpilot.com/certifai + path: /mcp tools: - - name: list_ai_agents - description: "Returns AI agents configured for the tenant" - required_scope: read:agents - - name: get_llm_usage - description: "Returns LLM usage metrics" - required_scope: read:usage - # ... more tools + - { name: list_targets, description: "Targets configured for the tenant", required_scope: read:targets } + - { name: run_scan, description: "Start a scan", required_scope: write:scans } + # ... + +usage: + metrics: + - { key: scan.completed, unit: scan, quota: scans_per_month } + - { key: target.added, unit: target, quota: targets } + - { key: seat.login, unit: user, quota: users } + push_interval_s: 60 data: - data_stores: - - type: mongodb - vm: vm-certifai - - type: external_api - provider: litellm - pii_class: low - tenant_scoping: - field: org_id - enforcement: middleware - supports_projects: false # see §9.3 PROJECT SCOPING + data_stores: [{ type: mongodb, per_tenant_database: true }] + tenant_scoping: { field: tenant_id, enforcement: per-database } + supports_projects: false retention_default_days: 365 gdpr_export: /v1/tenants/{id}/export gdpr_erasure: /v1/tenants/{id}/data - offboarding_export_formats: [json, csv] # produced by P16 final-export step - frozen_behavior: - reads: allow # customer can still pull data / download exports - writes: deny_402 # POST/PUT/DELETE return 402 Payment Required - background_jobs: pause # scheduled work suspended, queue preserved + offboarding_export_formats: [json, cyclonedx, spdx] + frozen_behavior: { reads: allow, writes: deny_402, background_jobs: pause } -backup: - rpo: 24h - rto: 30min - retention_days: 30 +backup: { rpo: 24h, rto: 30min, retention_days: 30 } infra: - image: registry.breakpilot.com/certifai-dashboard - vm: vm-certifai - replicas: 1 - resource_limits: - cpu: "2000m" - memory: "4Gi" - health_check: - path: /health - interval: 30s - timeout: 5s - threshold: 3 - secrets: - - MONGODB_URI: /prod/certifai/MONGODB_URI - - KEYCLOAK_CLIENT_SECRET: /prod/certifai/KEYCLOAK_CLIENT_SECRET - - LITELLM_MASTER_KEY: /prod/certifai/LITELLM_MASTER_KEY - depends_on: - - keycloak - - mongodb - - infisical + images: + - repo.breakpilot.com/pruefwerk/compliance-agent + - repo.breakpilot.com/pruefwerk/compliance-dashboard + - repo.breakpilot.com/pruefwerk/compliance-mcp + - repo.breakpilot.com/pruefwerk/compliance-docs + orca_project: pruefwerk-{env} + depends_on: [pruefwerk-mongo, browserless] admin_actions: - - name: "Reset LiteLLM API Key" - description: "Rotates the per-tenant LiteLLM key" - endpoint: POST /v1/tenants/{id}/admin/rotate-litellm-key - confirm: required - audit_required: true + - { name: "Re-run CVE monitor", endpoint: "POST /v1/tenants/{id}/admin/cve-monitor", confirm: required, audit_required: true } observability: metrics: /metrics - logs: - format: json - pii_redaction: true - audit_endpoint: tenant-registry.internal/audit + logs: { format: json, pii_redaction: true } + audit_endpoint: registry /v1/audit ``` -### 10.1 Manifest Variants by Frontend Type - -The example above shows an `interactive` product. Headless and widget products differ only in the `frontend` block. - -#### Widget variant - -```yaml -frontend: - type: widget - tag: status-monitor-widget - bundle_url: https://cdn.breakpilot.com/products/status/{version}/widget.js - bundle_size_kb: 38 - dimensions: - width: 400 - height: 240 - poll_interval_s: 60 - portal_config: - # same shape as headless (§ below) — used for click-through management page - sections: [api_keys, webhooks, usage, docs] - api_key_scopes: [...] - webhook_events: [...] -``` - -#### Headless variant (no frontend bundle) +### 10.1 Manifest variants ```yaml +# headless — no frontend.url; portal renders everything frontend: type: headless - # NO tag, NO bundle_url — the portal renders 100% of the customer UI portal_config: - sections: - - api_keys - - webhooks - - usage - - code_samples - - docs - status_endpoint: /v1/status # optional; portal polls for status badge - api_key_scopes: - - id: read - description: "Read sessions and results" - - id: write - description: "Create new sessions" - - id: admin - description: "Manage settings (rare; consider before granting)" - webhook_events: - - name: session.completed - description: "Fires when a notetaker session is fully processed" - payload_schema_url: /schemas/session.completed.json - - name: session.failed - description: "Fires when a session cannot be processed" - payload_schema_url: /schemas/session.failed.json - code_samples: - - language: curl - title: "Create a session" - snippet: | - curl -X POST https://notetaker-api.breakpilot.com/v1/sessions \ - -H "Authorization: ApiKey k_xxx" \ - -H "X-Tenant: acme" \ - -d '{"audio_url": "...", "language": "en"}' - - language: python - title: "Create a session" - snippet: | - import requests - requests.post( - "https://notetaker-api.breakpilot.com/v1/sessions", - headers={"Authorization": "ApiKey k_xxx", "X-Tenant": "acme"}, - json={"audio_url": "...", "language": "en"}, - ) + sections: [api_keys, webhooks, usage, code_samples, docs] + api_key_scopes: [...] + webhook_events: [...] + code_samples: [...] + +# cli — Werkpilot +frontend: + type: cli + downloads: + releases_url: https://git.breakpilot.com/platform/werkpilot/releases + platforms: [linux-x86_64, linux-aarch64, macos-aarch64, windows-x86_64] + cloud: null # no hosted component +licence: + skus: [DEV-WP-CLD-STD, DEV-WP-CLD-BUS, DEV-WP-CLD-ENT, DEV-WP-OPR-STD, DEV-WP-OPR-BUS, DEV-WP-OPR-ENT] + seat_model: named_user # named_user | instance + grace: { warn_days: 7, degrade_days: 14, stop_days: 30 } + floating: false + offline_packages: true +usage: + metrics: + - { key: seat.session_started, unit: user, quota: users } + +# cli — Firmwerk (with cloud component) +frontend: + type: cli + downloads: + releases_url: https://git.breakpilot.com/api/packages/platform/generic/firmwerk + cloud: + type: standalone + url: { stage: https://firmwerk-stage.breakpilot.com, prod: https://firmwerk.breakpilot.com } +licence: + skus: [DEV-FWK-CLD-STD, DEV-FWK-CLD-BUS, DEV-FWK-CLD-ENT, DEV-FWK-OPR-STD, DEV-FWK-OPR-BUS, DEV-FWK-OPR-ENT] + seat_model: named_user + grace: { warn_days: 7, degrade_days: 14, stop_days: 30 } + free_read_only: true +usage: + metrics: + - { key: environment.created, unit: environment, quota: environments } + - { key: sbom.uploaded, unit: sbom } + - { key: seat.active, unit: user, quota: users } ``` -The Tenant Registry validates the `frontend` block against the type: -- `interactive` requires `tag` and `bundle_url`; `portal_config` is optional -- `widget` requires `tag`, `bundle_url`, `dimensions`, AND `portal_config` -- `headless` MUST NOT declare `tag` or `bundle_url`; `portal_config` is required +The registry validates: `standalone` requires `frontend.url` per env; `headless` requires `portal_config` and no `url`; `cli` requires `downloads` and a `licence` block; `addons[].limit_key` must exist in `usage.metrics[].quota` or `plans`. --- ## 11. Service Token Model (Inter-Product Communication) -Products can call each other directly. Auth is via short-lived service tokens issued by Keycloak's `client_credentials` flow. - -### 11.1 Flow +Unchanged mechanics (client_credentials, 15-min TTL, `X-On-Behalf-Of-User`, audit on both sides). Clients are named `{product}-svc-{env}`; the realm is `breakpilot-{env}`. ``` -1. Compliance product needs to list AI agents for an AI Act assessment. - -2. Compliance backend requests a service token: - POST https://auth.breakpilot.com/realms/breakpilot-prod/protocol/openid-connect/token - Body: grant_type=client_credentials - client_id=compliance-svc - client_secret= - scope=read:certifai-agents - Response: JWT (15 min TTL) - -3. Compliance calls CERTifAI: - GET https://certifai-api.internal/v1/tenants/{tenant_id}/agents - Authorization: Bearer - X-On-Behalf-Of-User: ← original user, for audit - X-Service-Reason: ai-act-assessment - -4. CERTifAI validates token: - - Issued by platform Keycloak: ok - - Audience includes "certifai-svc": ok - - Scopes include "read:certifai-agents": ok - - tenant_id in path matches caller's intent: ok (no cross-tenant) - -5. CERTifAI returns data. - -6. Both sides emit audit events: - {actor: "svc:compliance", action: "certifai.list_agents", - on_behalf_of: "user_sub", tenant_id: "...", reason: "ai-act-assessment"} +pruefwerk offers: read:pruefwerk-findings · read:pruefwerk-sbom · write:pruefwerk-scans +firmwerk offers: read:firmwerk-sbom · read:firmwerk-vex +compliance offers (after M-MIG-9): read:compliance-status · read:compliance-dsfa · read:control-catalog +pruefwerk consumes: read:control-catalog (OSCAL master controls from breakpilot-compliance; degrades + to unmapped findings when unavailable) ``` -### 11.2 Scope Catalog - -Each service declares scopes it offers (other services can request these) and scopes it consumes (it needs from other services). - -``` -certifai offers: - read:certifai-agents - read:certifai-usage - write:certifai-settings (rare; consider before granting) - -compliance offers: - read:compliance-status - read:compliance-dsfa - write:compliance-events (for cross-product event emission) - -billing-service consumes: - read:certifai-usage - read:compliance-status - -compliance consumes: - read:certifai-agents (for AI Act assessments) -``` - -Scopes are granted in Keycloak per service client. Grants are reviewed quarterly. - -### 11.3 Third-Party Readiness - -When we open the platform to third parties: - -``` -- Same OIDC client_credentials flow -- Manifests are SIGNED by third-party developer keys (signature verified by Tenant Registry) -- Third-party scopes are read-only by default; write scopes require manual approval -- Network isolation: third-party services run in a separate Orca subnet -- Resource limits enforced (CPU, memory, network egress) -- Per-tenant install requires explicit IT Admin consent (OAuth consent screen) -``` - -The contract surface today is the same — we just add verification gates. +Third-party readiness (§11.3 of 1.0) unchanged. --- ## 12. Versioning and Contract Evolution -### 12.1 Versions in play - -``` -contract_version This document. Updated when the platform changes what products - must implement. Currently 1.0. Bumped on breaking changes. - -product_version The product's own version (semver). Tracked by Tenant Registry. - Independent of contract version. - -api_version The version in URL paths (/v1/, /v2/). Within a contract version, - a product may have multiple API versions live. -``` - -### 12.2 Platform supports N and N-1 - -The platform always supports the current contract version and the previous one. Deprecation announced in this doc before any breaking change. - -### 12.3 Breaking Change Process - -``` -1. Announce in this doc (one section per breaking change with motivation). -2. Update contract_version, e.g. 1.0 → 2.0. -3. New products required to ship 2.0 from day one. -4. Existing products get 12 months to migrate. -5. After 12 months, 1.0 retired; tenants on 1.0 products are migrated or churned. -``` +`contract_version` 2.0 from 2026-09-11. No product reached 1.0 compliance, so 1.0 is retired immediately; the N/N-1 rule applies from 2.0 onward. Breaking-change process unchanged (announce here, bump, 12 months for existing products). --- ## 13. Onboarding Checklist for a New Product -A product is "ready to ship to a customer" when all boxes are ticked. - ``` ☐ Backend API ☐ openapi.yaml committed and validated ☐ Mandatory endpoints implemented (§4.1) - ☐ JWT validation via Keycloak JWKS + ☐ JWT validation via JWKS with iss AND aud pinned ☐ Service token validation - ☐ Tenant scoping enforced in middleware + tested - ☐ /v1/tenants/{id}/provision idempotency test passes - ☐ /v1/tenants/{id}/export produces valid GDPR-compliant ZIP - ☐ DELETE /v1/tenants/{id}/data is irreversible and audited + ☐ Entitlement check via registry, cached ≤ 60 s, fail-closed, tested (§4.4) + ☐ Tenant scoping enforced in middleware + negative test + ☐ /provision idempotency test · /export valid ZIP · DELETE …/data irreversible and audited -☐ Frontend (manifest declares one of: interactive | widget | headless) +☐ Frontend (manifest declares one of: standalone | headless | cli) + standalone: ☐ own host per env ☐ SSO via realm client ☐ back-to-portal link + ☐ X-Frame-Options DENY + CSP + CORS allowlist ☐ ladder banner + headless: ☐ portal_config complete ☐ api-keys/verify integration ☐ webhooks/dispatch integration + cli: ☐ `login` (device flow) ☐ offline licence verify ☐ heartbeat ☐ ladder behaviour + ☐ `licence status` command ☐ cloud part verifies licence tokens, keeps no own tenants - For frontend.type = interactive: - ☐ Custom element registered with declared tag - ☐ Bundle published to CDN (≤ 500KB gzipped) - ☐ Handles all required attributes (§5.A.2) - ☐ Emits all event types (§5.A.3) - ☐ Light + dark theme support (§5.A.4) - ☐ At least one locale beyond English - - For frontend.type = widget: - ☐ Widget custom element registered with declared tag - ☐ Bundle published to CDN (≤ 50KB gzipped) - ☐ Tile dimensions declared in manifest - ☐ Allowed events only (no breakpilot:navigate) - ☐ portal_config block complete (for click-through page) - - For frontend.type = headless: - ☐ NO tag and NO bundle_url declared - ☐ portal_config.sections declared - ☐ portal_config.api_key_scopes catalog complete - ☐ portal_config.webhook_events catalog with payload schemas - ☐ portal_config.code_samples in at least one language - ☐ Webhook payloads include HMAC signature for verification - ☐ Status endpoint returns valid format (if declared) - ☐ POST /internal/api-keys/verify integration tested with Tenant Registry - ☐ POST /internal/webhooks/dispatch integration tested with portal - -☐ MCP (if Enterprise plan or applicable) - ☐ MCP server deployed - ☐ Tool catalog declared in manifest - ☐ API key authentication implemented - ☐ All tools tenant-scoped and audited - -☐ Documentation - ☐ README published at developers.breakpilot.com/products/{name} - ☐ API reference auto-generated and live - ☐ Integration guide for customer IT - ☐ Operational runbook for us - ☐ Data model + GDPR retention table - -☐ Observability - ☐ /health implemented and returns valid format - ☐ /metrics in Prometheus format - ☐ JSON structured logging - ☐ Audit events emitted for all listed categories - ☐ No PII in logs (PII redaction tested) - -☐ Identity integration - ☐ Keycloak OIDC client registered - ☐ Role mappings declared and tested - ☐ Entitlement key included in tenant JWTs (verified end-to-end) - -☐ Control integration - ☐ product.manifest.yaml committed - ☐ Registered with Tenant Registry catalog - ☐ Lifecycle endpoints tested via Backstage "Create Test Tenant" - ☐ Usage endpoint returns valid format - ☐ Backstage admin actions render correctly - -☐ Data integration - ☐ All tables/collections have tenant_id - ☐ Cross-tenant query test (negative test) passes - ☐ Backup contract declared and Infra Plane is executing it - ☐ GDPR export tested with real data - ☐ Data residency confirmed (no exfiltration outside EU) - -☐ Infra integration - ☐ Orca manifest committed and applies cleanly - ☐ Dockerfile builds reproducibly - ☐ All secrets in Infisical (zero hardcoded) - ☐ Gitea Actions pipeline green - ☐ Resource limits set and tested under load - ☐ Cold start dependency order declared +☐ MCP (if Enterprise) — deployed at /mcp, catalog in manifest, key auth, tenant-scoped, audited +☐ Documentation — README, API ref, integration guide, runbook, data model + GDPR at {product}/docs +☐ Observability — /health, /metrics (incl. entitlement + usage counters), JSON logs, audit events, no PII +☐ Identity — realm clients registered, role mappings tested, aud claim present in tenant JWTs +☐ Control — manifest registered; lifecycle endpoints tested from Backstage; usage events arrive + in registry (and in ERPNext mock on stage); add-on limits enforced +☐ Data — tenant_id everywhere; cross-tenant negative test; backup declared and running; GDPR export tested +☐ Infra — service file pinned + memory set; validate.sh green; image signed; secrets project-scoped; + CI webhook redeploys stage ``` --- -## 14. Gap Analysis — Existing Products - -### CERTifAI vs. Contract 1.0 +## 14. Gap Analysis — First-Line Products vs Contract 2.0 (as of 2026-09-11) +### Prüfwerk (`platform/pruefwerk`) ``` -✓ OIDC via Keycloak — already implemented -✓ Role data model (Admin/Member/Viewer) — exists -✗ Mandatory endpoints — NONE of §4.1 implemented yet -✗ Frontend as web component — currently a full Dioxus fullstack app -✗ MCP server — not implemented -✗ Tenant scoping in queries — only chat is user-scoped, no org_id scoping -✗ Service token validation — not implemented -✗ GDPR export/erasure — not implemented -✗ /health, /metrics, structured audit emission — not implemented -✓ Orca + Infisical compatible — already deployed this way - -Effort estimate: 4-6 weeks of focused work +✓ Keycloak OIDC PKCE on the dashboard; JWT auth on the agent (JWKS) +✗ iss/aud not validated (validate_aud = false) — MUST fix +✗ CORS permissive — MUST fix (allowlist) +✓ Per-tenant MongoDB, tenant-scoped webhooks, tenant-bound MCP tokens, status gate (402/410) +✗ Entitlement check — reads claims only; `products` never enforced → switch to registry check +✗ Scheduler calls a non-existent GET /v1/tenants (falls back to tenant "dev") → use the new list endpoint +✗ /provision, /suspend, /reactivate, /terminate, /export, DELETE data, demo/reset — missing +✗ Usage events — none +✓ /health, OTel; ✗ /metrics contract counters; ✗ audit POST to registry +✗ Werkbank runner auth is a static token → registry API key with scope werkbank:runner +Effort: ~3 weeks (M-MIG-6 + M-MIG-7 items) ``` -### breakpilot-compliance vs. Contract 1.0 - +### Werkbank (`platform/werkbank`) +``` +✓ Leases jobs from Prüfwerk; tenant fixed per runner +✗ No Dockerfile / CI / service file +✗ Static runner token → registry API key +✗ Cargo git dependencies pinned to branch main on the old host → pin to a tag on platform/pruefwerk +Effort: ~3 days ``` -✓ Multi-tenant via X-Tenant-ID — exists (needs JWT validation upgrade) -✓ Modular Next.js frontend — close to web-component-wrappable -✗ Mandatory endpoints — partially implemented (usage endpoint missing) -✗ JWT validation at proxy — currently raw header trust -✗ Frontend as web component — needs wrapping with @r2wc/react-to-web-component -✗ MCP server — not implemented -✓ Backup contract — declared informally, needs to be in manifest -✗ GDPR export/erasure — partial (DSR module exists, doesn't cover whole tenant) -✓ Observability — partial (structured logs, no /metrics) -Effort estimate: 3-5 weeks of focused work +### Werkpilot (`platform/werkpilot`) +``` +✓ Release pipeline (tarball, SBOM, GPG), Kellnr mirror, no-egress guard, telemetry disabled +✗ No login / licence client / ladder / heartbeat (§5.C) — new +✗ Per-tenant LiteLLM virtual key issued with the licence — new +Effort: ~1.5 weeks +``` + +### Firmwerk (`platform/firmwerk`) +``` +✓ CLI + cloud-server exist; device login flow exists (own implementation) +✗ Own tenant / api_key / licence model in cloud-server → replace with registry licence verification +✗ Ed25519 licence issuance moves to the registry; CLI verifies registry tokens +✗ Workflows under .github with runs-on ubuntu-latest → .gitea, runs-on docker +✗ Entitlement check for environment limits; usage events +Effort: ~2 weeks ``` --- @@ -1218,28 +647,21 @@ Effort estimate: 3-5 weeks of focused work ## 15. Open Items ``` -- Design tokens package (@breakpilot/design-tokens) — needs to exist before web components ship -- CDN for product bundles — pick provider (Hetzner Object Storage + Cloudflare?) -- MCP gateway — single mcp.breakpilot.com vs. per-product subdomains -- Third-party manifest signing — defer until first real third-party conversation -- Inter-product event bus — explicitly deferred; service tokens cover the use cases for now -- Contract testing — automate manifest + openapi validation in Gitea Actions -- Customer-facing catalog UI — defined at /[tenant]/catalog (see PLATFORM_ARCHITECTURE.md - §5a operating principles); Backstage product picker reuses same catalog metadata. +- Contract testing — automate manifest + openapi validation in Gitea Actions (validate.sh for manifests). +- MCP on one host path (/mcp) is decided; a unified mcp.breakpilot.com gateway is deferred. +- Third-party manifest signing — defer until the first real third-party conversation. +- Inter-product event bus — deferred; service tokens cover current needs. +- Floating (concurrent) CLI seats — SKU sheet allows 2–2.5× named; implement after named seats work. +- Offline licence package tooling in Backstage — after the online path is proven on staging. OSS swap-in points (designed-for, not adopted yet): -- Audit log storage: BoxyHQ Retraced — our event schema is Retraced-shape (§8.4), - swap when audit query patterns outgrow PostgreSQL or when a customer asks for - exportable SOC2-grade audit retention. -- Usage metering: Lago — our /v1/usage endpoint plus optional per-event stream - (§4.1) is Lago-compatible. Swap when LiteLLM token billing requires real-time - metering or per-customer pricing tiers we cannot model in Stripe. -- Customer IdP federation (SCIM): BoxyHQ Jackson or Keycloak's SCIM module. - Adopt when first enterprise customer asks for automated user provisioning. -- Feature flags / per-tenant feature gating: OpenFeature (vendor-neutral). - Adopt when product features need finer-than-plan-tier gating per tenant. +- Audit log storage: Retraced-shape events (§8.4) → BoxyHQ Retraced when needed. +- Usage metering: usage_events are Lago-compatible (idempotency_key ≈ transaction_id, metric ≈ code) + should ERPNext usage records ever become the bottleneck. +- SCIM: BoxyHQ Jackson or Keycloak SCIM when the first enterprise customer asks. +- Feature flags: OpenFeature when finer-than-plan gating is needed. ``` --- -*End of document. Contract version 1.0. Next review: after first product (CERTifAI or compliance) achieves full compliance with §13 checklist.* +*End of document. Contract version 2.0 (2026-09-11). Next review: after Prüfwerk passes the §13 checklist on staging.* diff --git a/README.md b/README.md index 3fa13c7..efb82c4 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,20 @@ Platform-wide architecture, integration spec, runbooks. -> Part of the **Breakpilot Platform**. For the big picture see [`platform/docs`](https://gitea.meghsakha.com/platform/docs): -> [Architecture](https://gitea.meghsakha.com/platform/docs/src/branch/main/PLATFORM_ARCHITECTURE.md) · -> [Infrastructure](https://gitea.meghsakha.com/platform/docs/src/branch/main/INFRASTRUCTURE.md) · -> [Product Integration Spec](https://gitea.meghsakha.com/platform/docs/src/branch/main/PRODUCT_INTEGRATION_SPEC.md) · -> [Implementation Plan](https://gitea.meghsakha.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md) +> Part of the **Breakpilot Platform**. For the big picture see [`platform/docs`](https://git.breakpilot.com/platform/docs): +> [Architecture](https://git.breakpilot.com/platform/docs/src/branch/main/PLATFORM_ARCHITECTURE.md) · +> [Infrastructure](https://git.breakpilot.com/platform/docs/src/branch/main/INFRASTRUCTURE.md) · +> [Product Integration Spec](https://git.breakpilot.com/platform/docs/src/branch/main/PRODUCT_INTEGRATION_SPEC.md) · +> [Implementation Plan](https://git.breakpilot.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md) ## What this is -Platform-wide architecture, integration spec, runbooks. Scaffolded under milestone M0.1. See [`platform/docs`](https://gitea.meghsakha.com/platform/docs) for the full architecture context. +Platform-wide architecture, integration spec, runbooks. Scaffolded under milestone M0.1. See [`platform/docs`](https://git.breakpilot.com/platform/docs) for the full architecture context. **Plane:** Control **Owner:** @sharang **Status:** pre-alpha -**Linked milestone:** [M0.1](https://gitea.meghsakha.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md) +**Linked milestone:** [M0.1](https://git.breakpilot.com/platform/docs/src/branch/main/IMPLEMENTATION_PLAN.md) ## Run locally @@ -36,17 +36,17 @@ For IaC: list the make targets.}} ## Deployment -| Env | URL | How | +| Env | URL / host | How | |---|---|---| -| dev | `http://localhost:3000` | `make dev` | -| stage | `https://docs.stage.breakpilot.com` | auto on merge to `main` | -| prod | `https://docs.breakpilot.com` | manual: tag `vX.Y.Z` + sign-off | +| dev | `http://localhost:3000` | `make dev` | +| stage | `app-stage.breakpilot.com` (portal) · `-stage.breakpilot.com` (product UI) · internal for services without a UI | auto on merge to `main` (CI → Harbor → signed webhook → `orca redeploy -stage`) | +| prod | `app.breakpilot.com` · `.breakpilot.com` | tag `vX.Y.Z` + sign-off → `prod` branch webhook → `orca redeploy -prod` | -Rollback: `orca rollout undo docs --env={{env}}`. +Tenants are addressed by path (`/[slug]/…`), never by subdomain. Rollback: `orca rollback -{{env}}` (previous image) on the platform master. No `docs.breakpilot.com` — this repo is documentation only and is not deployed. ## Observability -- Traces, logs, metrics: [SigNoz](https://signoz.meghsakha.com) — service name `docs` +- Traces, logs, metrics: [SigNoz](https://signoz.breakpilot.com) — service name `docs` - Audit events: Tenant Registry `/audit` (Retraced-shape schema) - On-call: `oncall@breakpilot.com` · runbook at `platform/docs/runbooks/docs.md`