# STANDARD AgileHub: multitenant-architecture v1.0

> **Codename progetto**: NAVIGAI (Navigare nell'AI)
> **Status**: `proposed`
> **Applies to**: `*` (tutta la suite — 11 prodotti)
> **Owner**: REGENT (coordinamento) + TITAN (backend) + VIGILE (audit) + Agile AI (KB master) + PRISMA (UI master/tenant)
> **Date**: 2026-05-17
> **Public facing**: AgileHub (NAVIGAI è il codename interno, invisibile al cliente)

---

## 1. Scopo

Definire l'architettura multitenant esplicita di AgileHub con un livello master condiviso, tenant client isolati, catalogo cross-tenant condivisibile, billing per-tenant e governance centralizzata.

## 2. Tassonomia tenant

| Tipo | Esempio | id | is_master | tier | parent_tenant_id |
|---|---|---|---|---|---|
| **Master** | AgileHub | 1 | TRUE | `master` | NULL |
| Client enterprise | Work Group s.r.l. | N | FALSE | `enterprise` | 1 |
| Client professional | Studio Tremolada | N | FALSE | `professional` | 1 |
| Client trial | sandbox | N | FALSE | `trial` | 1 |
| Sandbox interno | Agile Technology test | N | FALSE | `trial` | 1 |

## 3. Visibility ENUM cross-tabella

Ogni record sensibile (KB articles, personas, workflow templates, routing rules, RAG repositories) ha colonna `visibility ENUM('global','shared','tenant','team','private')`.

| Valore | Significato | Lettura da |
|---|---|---|
| `global` | Master AgileHub catalog, riusabile read-only da tutti i tenant | tutti |
| `shared` | Visibile a tenant + i suoi sotto-tenant | tenant + figli |
| `tenant` | Solo tenant proprietario | tenant |
| `team` | Team specifico dentro un tenant | team members |
| `private` | Singolo utente | owner_user_id |

## 4. Opt-out granulare

Tabella `nexus_tenant_db.tenant_global_exclusions(tenant_id, resource_type, resource_id, exclusion_reason)` permette al client di dichiarare "non voglio usare quell'articolo KB master/quella persona master/quella regola routing master".

## 5. JWT additivi (no breaking)

Claims aggiunti (additive, retro-compat):
- `tenant_id BIGINT`
- `tenant_slug VARCHAR(64)`
- `is_master TINYINT(1)`
- `permitted_tenant_ids INT[]` (per is_master users che possono switchare contesto)

Vecchi JWT senza nuovi claim restano validi → tenant_id desunto via fallback `tenants.email → user → tenant_membership`.

## 6. Shared library

Pacchetto npm interno `@agile/tenant-auth` (Node) + `agile_tenant_auth` (Python) fornisce:
- `extractTenantContext(req)` → `{ tenant_id, tenant_slug, is_master, user_id }`
- `requireSameTenant(req, resourceTenantId)` → throws 403 se mismatch
- `requireMaster(req)` → throws 403 se !is_master
- `withTenantFilter(query)` → injects `WHERE (tenant_id = X OR visibility = 'global')`

## 7. Vault namespace tenant-aware

Pattern: `tier1__<ms>__<tenant_slug>__<feature>`

Esempi:
- `tier1__nexus-marketing-ms__work_group_001__mailgun_api_key`
- `tier1__nexus-presenter-ms__agilehub_master__tavus_api_key`

Compatibility: namespace senza `<tenant_slug>` restano validi per master.

## 8. Audit log HMAC chain

JSONL append-only in `docs/multitenant-audit/YYYY-MM-WNN.jsonl` con catena HMAC-SHA256 (ogni entry contiene SHA del precedente). Genesis entry firmata da TITAN al kickoff SG-0.

## 9. Distributed tracing

Header `X-Trace-Id` propagato cross-MS in tutti i call HTTP/Redis Streams. Generato in API gateway Apache se assente. Pino structured log + Loki backend.

## 10. Status page tenant-aware

`/status` Next.js mostra SLA + uptime + latency p99 **per-tenant** (con auth). SLA differenziato per tier:
- master: 99.99%
- enterprise: 99.95%
- professional: 99.9%
- trial: 99%

## 11. Canary deploy

Apache `mod_proxy_balancer` rolling 5% → 50% → 100% con auto-rollback se error rate > 2% per 5 min.

## 12. Billing per-tenant

Tabella `nexus_hub.hub_cost_events(tenant_id, ms, event_type, cost_eur_micros, ts)` con 8 hook nei MS:
- nexus-ai-ms (tokens LLM Anthropic + Voyage embedding)
- nexus-marketing-ms (email sends via Mailgun)
- nexus-call-ms (Twilio minutes)
- nexus-presenter-ms (Tavus session-minutes + LiveKit)
- nexus-voice-ms (Deepgram STT + ElevenLabs TTS)
- nexus-rag-ms (Voyage embed/rerank + storage GB)
- nexus-hub-ms (server time)
- agilehub-workflow-engine (Haiku suggester tokens)

Export mensile CSV/PDF (showback) per cliente.

## 13. Compliance

- **GDPR Art.32**: encryption at rest+transit, access controls, audit trail, business continuity, periodic testing — tutti documentati in `docs/COMPLIANCE_GDPR_ART32.md`
- **ISO A.18.1.5** readiness: gap analysis NON certificazione formale
- **Retention fiscale IT**: 10 anni per `hub_cost_events` (NON 7)
- **GDPR Art.17 erasure**: cascade già implementato in nexus-rag-ms (estendere ai 13 MS)

## 14. Pen test esterno

STRIDE 13×6 matrix (13 MS × 6 categorie) eseguita da vendor EU certificato durante SG-5. Budget €15K una tantum. Vendor RFP da VIGILE.

## 15. Roadmap distribution

| Wave | Prodotti | Trigger |
|---|---|---|
| **Reference** | AGILEHUB | SG-0 in progress |
| **Wave 1 (P1)** | TRPG, SUSTAINAI, NIS2, DFM | SG-4 GREEN |
| **Wave 2 (P2)** | TAXAI, LG231, MKTG, ALLRISK, WMS, MADEBYCLOUD, CERTISOURCE | post smoke Wave 1 |

Distribution via INSTALLATORE pattern: docs_file scp + claude_md append + claude memory write nei 11 container DevEnv prodotto + `hub_standards_adoption` row per ogni prodotto (status `pending → acknowledged → implemented`).

## 16. NESSUN out-of-scope (v1.0)

Documentato esplicitamente FUORI da v1.0:
- Multi-region failover (Hetzner Helsinki + EU secondary)
- Self-service tenant signup pubblico con CC payment
- Multi-currency (solo EUR)
- SAML/OIDC federation
- Tenant white-label dominio custom (solo subdomain `{slug}.agilehub.it`)
- Audit log immutabile blockchain
- ISO 27001 / SOC 2 certification formale

---

## Adoption tracker (status iniziale)

| Prodotto | docs_file | claude_md | claude_memory | adoption_status |
|---|---|---|---|---|
| AGILEHUB | ✓ pending SG-0 | pending | pending | `proposed` |
| TRPG | pending | pending | pending | `pending` |
| SUSTAINAI | pending | pending | pending | `pending` |
| NIS2 | pending | pending | pending | `pending` |
| TAXAI | pending | pending | pending | `pending` |
| LG231 | pending | pending | pending | `pending` |
| DFM | pending | pending | pending | `pending` |
| MKTG | pending | pending | pending | `pending` |
| ALLRISK | pending | pending | pending | `pending` |
| WMS | pending | pending | pending | `pending` |
| MADEBYCLOUD | pending | pending | pending | `pending` |
| CERTISOURCE | pending | pending | pending | `pending` |

## Riferimenti

- [NAVIGAI_EXECUTIVE_BRIEF.md](NAVIGAI_EXECUTIVE_BRIEF.md)
- [NAVIGAI_ARCHITETTURA_TECNICA.md](NAVIGAI_ARCHITETTURA_TECNICA.md)
- [NAVIGAI_ROADMAP_OPERATIVA.md](NAVIGAI_ROADMAP_OPERATIVA.md)
- [PLAN_MULTITENANT_MASTER_REFACTOR_V11.md](PLAN_MULTITENANT_MASTER_REFACTOR_V11.md) (920 righe production-ready)
