Compare commits
184
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a05bd34af3 | ||
|
|
ea0aa18b8d | ||
|
|
87ecee5301 | ||
|
|
17add13d9d | ||
|
|
88a03a65f2 | ||
|
|
cb165cd821 | ||
|
|
15f87eada2 | ||
|
|
b80f52cb50 | ||
|
|
3a0ef3a734 | ||
|
|
192a65a798 | ||
|
|
19e962d8ec | ||
|
|
b7d88ce24a | ||
|
|
0baa5952bc | ||
|
|
903304adf1 | ||
|
|
be0090d513 | ||
|
|
69c516dba4 | ||
|
|
252b3f05f2 | ||
|
|
89ae15ca4c | ||
|
|
84d912b8ba | ||
|
|
02b6469c2d | ||
|
|
43d33d0edb | ||
|
|
b6434bcc50 | ||
|
|
390161e224 | ||
|
|
a5154cbd3b | ||
|
|
b747200f3a | ||
|
|
1bbc5dbfce | ||
|
|
20636f88d2 | ||
|
|
c5e2c69b1e | ||
|
|
ef5ee0d19b | ||
|
|
a13913f1a0 | ||
|
|
a3b14d9c00 | ||
|
|
f33135b87f | ||
|
|
dc6f25b673 | ||
|
|
f7d65dde01 | ||
|
|
1c10e5b798 | ||
|
|
97fab2c76d | ||
|
|
11b7128204 | ||
|
|
fe1edb84f8 | ||
|
|
606dd960b8 | ||
|
|
0443b734c1 | ||
|
|
75a6a63665 | ||
|
|
753f178b0c | ||
|
|
005b371ac0 | ||
|
|
4fbb3b3469 | ||
|
|
d3bf3c36e0 | ||
|
|
ac475ab92c | ||
|
|
c79bfa844f | ||
|
|
44fda7beb9 | ||
|
|
38fed379ae | ||
|
|
11e36e674e | ||
|
|
1b55d8558c | ||
|
|
90934453e6 | ||
|
|
4ad908bfbf | ||
|
|
ad6740ffa8 | ||
|
|
ee1e1c0671 | ||
|
|
04d1dbf1f9 | ||
|
|
e65838118c | ||
|
|
e221b5b09f | ||
|
|
c19b6296ed | ||
|
|
00567bb097 | ||
|
|
f6aba94864 | ||
|
|
09826d146e | ||
|
|
82a5b9adec | ||
|
|
0b57e2ec75 | ||
|
|
2b0d5dd3d9 | ||
|
|
a097a82e17 | ||
|
|
b8945556ad | ||
|
|
d1bc725ab5 | ||
|
|
5dc372c043 | ||
|
|
2359cc8b59 | ||
|
|
284b9d50fe | ||
|
|
b9bfa9e5bd | ||
|
|
8546c7021b | ||
|
|
1166a0c7f1 | ||
|
|
a1b353fcee | ||
|
|
a26b534c34 | ||
|
|
b85a6ec0c7 | ||
|
|
a19c6abd26 | ||
|
|
d7aefed0de | ||
|
|
364ad44759 | ||
|
|
0c2ca4a69d | ||
|
|
2843d8775a | ||
|
|
064779e187 | ||
|
|
1fa61b2dac | ||
|
|
4f8725e234 | ||
|
|
bd64340ca1 | ||
|
|
dbe6f4f684 | ||
|
|
43d30944aa | ||
|
|
075cff00a2 | ||
|
|
7cd8f4b90e | ||
|
|
7f03504c2d | ||
|
|
83fdb9a2a2 | ||
|
|
b1686f3a98 | ||
|
|
bcf6f83813 | ||
|
|
5e2ae9de31 | ||
|
|
b0594df5f2 | ||
|
|
efb45a3ee6 | ||
|
|
95b743d6fd | ||
|
|
3bd983297b | ||
|
|
21d948634e | ||
|
|
3e96b9c1e9 | ||
|
|
ba28a86fe5 | ||
|
|
a6fc86025c | ||
|
|
408050bcb8 | ||
|
|
495993cad6 | ||
|
|
4f2f801889 | ||
|
|
a99d4a8974 | ||
|
|
e50c04c96f | ||
|
|
bbadf22d39 | ||
|
|
aa7e1626ea | ||
|
|
afb07f70b9 | ||
|
|
09feddae4a | ||
|
|
d00ae070ec | ||
|
|
2734215833 | ||
|
|
e42edd86fa | ||
|
|
33831a8c2c | ||
|
|
94e815e88a | ||
|
|
bff1248e32 | ||
|
|
7e4936a2e4 | ||
|
|
4ca0a2c460 | ||
|
|
6eeddfdc76 | ||
|
|
2e7651812a | ||
|
|
9bf6ccee36 | ||
|
|
e70e3196ec | ||
|
|
4d1c33bf18 | ||
|
|
0addcfb382 | ||
|
|
fdda8a9fae | ||
|
|
09433b5d28 | ||
|
|
a5d9eeb338 | ||
|
|
687aad6cbd | ||
|
|
2796965aed | ||
|
|
8c31802662 | ||
|
|
a520d54bcf | ||
|
|
fc956d4ceb | ||
|
|
95feba6204 | ||
|
|
451d62ed46 | ||
|
|
6ea663b4c4 | ||
|
|
1b19deb728 | ||
|
|
e25ff86420 | ||
|
|
a025542545 | ||
|
|
c9101db1e1 | ||
|
|
fe3bc4f057 | ||
|
|
6dd9dd4f62 | ||
|
|
c4a66e9773 | ||
|
|
01b3c594a1 | ||
|
|
cc3129116a | ||
|
|
a01457debb | ||
|
|
02b3b17269 | ||
|
|
db06af0489 | ||
|
|
36487d2869 | ||
|
|
842c39081b | ||
|
|
26cd9feeb2 | ||
|
|
48a599e76c | ||
|
|
0e7184a59e | ||
|
|
802c9259dc | ||
|
|
a34a61458e | ||
|
|
afa68150c0 | ||
|
|
53047b6c16 | ||
|
|
f8af47d1d5 | ||
|
|
39e8084b1a | ||
|
|
4069cb0e01 | ||
|
|
eaa0e25524 | ||
|
|
910b1d7e07 | ||
|
|
f9c207c4f6 | ||
|
|
f8b3ae3011 | ||
|
|
88792eeb47 | ||
|
|
598677d343 | ||
|
|
7a6eb3abe8 | ||
|
|
2f631f419a | ||
|
|
101376540a | ||
|
|
45a108b4a0 | ||
|
|
25d3976226 | ||
|
|
564008be13 | ||
|
|
b5efdbbc2e | ||
|
|
1d8e22be82 | ||
|
|
1765daed2d | ||
|
|
a979d0e5f9 | ||
|
|
2b96518a52 | ||
|
|
5cc9282b31 | ||
|
|
486268efd9 | ||
|
|
b1e00bb347 | ||
|
|
0e5bf72dee | ||
|
|
1ce20d8bdb | ||
|
|
0e2b938fbd |
No files matched your search
@@ -0,0 +1,58 @@
|
|||||||
|
---
|
||||||
|
description: Kairo Architektur-Leitplanken und Dokumentenpriorität
|
||||||
|
globs: backend/**,frontend/**,docs/**,.gitea/**
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Kairo Architecture Rules
|
||||||
|
|
||||||
|
Du arbeitest an **Jinkendo Kairo**. Kairo ist mandantenfähig und Actor-first.
|
||||||
|
|
||||||
|
## Führende Product-Dokumente (ab 2026-07-05)
|
||||||
|
|
||||||
|
1. `docs/product/Kairo_Vision_and_Product_Direction_v0.2.md`
|
||||||
|
2. `docs/product/Kairo_Canonical_Operating_Model_v0.2.md`
|
||||||
|
3. `docs/product/Kairo_Implementation_Truth_Table_v0.1.md`
|
||||||
|
|
||||||
|
## Product Vision
|
||||||
|
|
||||||
|
Kairo ist Program Director — nicht To-do-Tool, nicht CRUD-Omnibus.
|
||||||
|
|
||||||
|
- **Plan:** Roadmap / RoadmapItem (Gates, Meilensteine, Reifegrade)
|
||||||
|
- **Ist:** committete Actions (Arbeitspakete), später Tasks
|
||||||
|
- **IA:** Workspace (Ausführung), Initiative-Unterseiten (Steuerung, Ausführung, Plan, Eingang, Journey)
|
||||||
|
- **Bearbeitung:** Modal oder Objekt-Detail — nicht Inline-CRUD auf Übersichtsseiten
|
||||||
|
|
||||||
|
Do not reduce Kairo to Initiative → Action.
|
||||||
|
Do not expand InitiativeDetail as all-in-one CRUD wall.
|
||||||
|
Do not continue prompt/AI/workflow/MCP before Plan/Ist and Gates are modeled.
|
||||||
|
|
||||||
|
## Dokumentenpriorität bei Konflikten
|
||||||
|
|
||||||
|
1. Vision & Product Direction v0.2
|
||||||
|
2. Canonical Operating Model v0.2
|
||||||
|
3. Implementation Truth Table
|
||||||
|
4. System Target State, ADPs (Scope Lock)
|
||||||
|
5. Tenant Invariants, Principle Gate
|
||||||
|
6. Product Spec v0.2 (Referenz)
|
||||||
|
7. Sprint History (Completion Reports — nicht als Zielbild)
|
||||||
|
|
||||||
|
## Reference design principles
|
||||||
|
|
||||||
|
Referenzmaterial unter `docs/reference/design-principles/`. Nicht automatisch Scope.
|
||||||
|
|
||||||
|
## Harte Guardrails
|
||||||
|
|
||||||
|
- Kein Single-User ohne Tenant
|
||||||
|
- User ≠ Actor; Agenten sind Actors
|
||||||
|
- Auth, Capability, Feature, Governance trennen
|
||||||
|
- Keine hardcodierten Rechte, Prompts oder Fachkonfiguration
|
||||||
|
- Nummerierte SQL-Migrationen; kein ad-hoc DDL in Routern
|
||||||
|
- Keine Mitai-/Shinkan-Domänenlogik kopieren
|
||||||
|
- Keine parallele Steuerungslogik außerhalb `backend/steering/`
|
||||||
|
- Keine neuen OM-Tabellen ohne ADP (Scope Lock bis RoadmapItem-ADP)
|
||||||
|
- **Archetyp-/Methoden-Plugin (AP2.3/AP2.4):** siehe `.cursor/rules/kairo-plugin-architecture.mdc` — keine Archetyp-Ifs in Pages, keine neuen Features in `methodUiDefaults.js`
|
||||||
|
|
||||||
|
## Abweichungen
|
||||||
|
|
||||||
|
Architecture Decision Proposal nach `docs/architecture/ARCHITECTURE_DECISION_PROPOSAL_TEMPLATE.md`.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
description: Deployment und Tests — kein lokaler Lauf; Verifikation über develop auf Raspberry
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Kairo — Deployment & Tests
|
||||||
|
|
||||||
|
## Kein lokaler Test-/DB-Lauf
|
||||||
|
|
||||||
|
Backend-Tests (pytest), Migrationen und Integrationstests **können auf der Entwicklungsmaschine in der Regel nicht ausgeführt werden** — PostgreSQL/Docker ist lokal oft nicht verfügbar.
|
||||||
|
|
||||||
|
Versuche nicht wiederholt, lokale pytest-/Migration-Läufe als Abnahme zu erzwingen, wenn die DB nicht erreichbar ist.
|
||||||
|
|
||||||
|
## Verifikation über Remote-Deploy
|
||||||
|
|
||||||
|
Praktische Verifikation erfolgt durch **Deployment auf ein entferntes System (Raspberry Pi)**:
|
||||||
|
|
||||||
|
1. Änderungen **committen** und auf Branch **`develop`** pushen
|
||||||
|
2. Deployment wird dadurch ausgelöst (CI/Deploy-Pipeline auf dem Raspberry)
|
||||||
|
3. Dort laufen Migrationen, Backend-Tests und Smoke-Checks gegen echte Infrastruktur
|
||||||
|
|
||||||
|
**Dev-Instanz (kein localhost):** [https://dev.kairo.jinkendo.de](https://dev.kairo.jinkendo.de)
|
||||||
|
Schnellcheck: `GET https://dev.kairo.jinkendo.de/api/health` (Version + DB).
|
||||||
|
|
||||||
|
**Gitea Actions** (Test-Suite läuft nach Deploy automatisch):
|
||||||
|
|
||||||
|
- Übersicht: `http://192.168.2.144:3000/Lars/Kairo-Jinkendo/actions`
|
||||||
|
- Workflows: `deploy-dev.yml` (Deploy), `test.yml` (pytest, lint, k6, Playwright)
|
||||||
|
- Filter z. B. `?workflow=test.yml` oder `?workflow=deploy-dev.yml`
|
||||||
|
- Run-Detail: `/Lars/Kairo-Jinkendo/actions/runs/{id}`
|
||||||
|
|
||||||
|
Nach Push auf `develop`: Deploy-Run grün → Health auf Dev → Test-Suite in Gitea Actions prüfen.
|
||||||
|
|
||||||
|
## Konsequenz für Agenten
|
||||||
|
|
||||||
|
- Code und Tests **schreiben** und dokumentieren — aber fehlende lokale DB nicht als Implementierungsblocker behandeln
|
||||||
|
- Frontend: `npm test` / `vite build` lokal weiterhin sinnvoll, wenn Node verfügbar
|
||||||
|
- Backend: Abnahme über Gitea Actions (`test.yml`) + Dev-Health — nicht lokales pytest erzwingen
|
||||||
|
- Funktionale Checks gegen **https://dev.kairo.jinkendo.de**, nicht localhost
|
||||||
|
- **Nicht** proaktiv committen/pushen, es sei denn, der Nutzer bittet explizit darum
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
---
|
||||||
|
description: Archetyp-/Methoden-Plugin-Architektur (AP2.3/AP2.4) — verbindlich für neue Implementierungen
|
||||||
|
globs: backend/steering/**,backend/entity_archetypes/**,backend/services/operating_context.py,frontend/src/registry/**,frontend/src/pages/**,frontend/src/context/InitiativeOperationsContext.jsx
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Kairo Plugin-Architektur (AP2.3 / AP2.4)
|
||||||
|
|
||||||
|
Verbindliche ADPs: `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `docs/architecture/ADP_Steering_Kernel_Spine_v0.1.md`, **`docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`**, **`.cursor/rules/kairo-steering-kernel.mdc`**
|
||||||
|
|
||||||
|
## Vier Schichten — Auflösung zur Laufzeit
|
||||||
|
|
||||||
|
| Schicht | Registry | Liefert |
|
||||||
|
|---------|----------|---------|
|
||||||
|
| **Archetyp** | `entity_archetypes` + `ui_profile_json` | Nav, Routen, Plan-Outline, `om_capabilities` |
|
||||||
|
| **Methode** | `steering/methods/registrations/` | `data_slices`, `steering_elements`, `ui_features`, `graph_profile`, Strategie |
|
||||||
|
| **Element** | `steering/elements/registry.py` + FE `steeringElementRegistry.js` | Control-/Work-Bausteine |
|
||||||
|
| **Runtime** | `GET /api/initiatives/:id/operating-context` + **`steering/kernel/evaluate_steering()`** | Plugin-Auflösung + **Herzmaschine** |
|
||||||
|
|
||||||
|
```text
|
||||||
|
data_slices = archetype.om_capabilities ∩ method.data_slices
|
||||||
|
steering_elements = method.steering_elements (nur Methode)
|
||||||
|
ui_features = method.ui_features (nur Methode)
|
||||||
|
nav / routes = archetype.ui_profile (nur Archetyp)
|
||||||
|
```
|
||||||
|
|
||||||
|
Archetyp-Default-Methode ist **Empfehlung**, nicht Lock — kompatible Methoden über `compatible_archetype_keys` + `om_capabilities`.
|
||||||
|
|
||||||
|
## Erweitern (Open/Closed)
|
||||||
|
|
||||||
|
**Neue Methode:** neues Modul unter `steering/methods/registrations/` → `MethodDefinition` vollständig → Import in `steering/__init__.py` → pytest. **Kein** Core-Edit.
|
||||||
|
|
||||||
|
**Neuer Archetyp:** Seed in `entity_archetypes/registry.py` + `ui_profiles.py` + optional EFS — **kein** React-If in Pages.
|
||||||
|
|
||||||
|
**Neues Steuerungselement:** Eintrag in `steering/elements/registry.py` + FE `steeringElementRegistry.js`; Methoden referenzieren nur registrierte Keys.
|
||||||
|
|
||||||
|
## Frontend — verbindlich
|
||||||
|
|
||||||
|
- UI aus `operating-context` via `resolveOperatingProfile.js`
|
||||||
|
- Control/Work: `hasSteeringElement(steeringElements, '…')` — **keine** `archetype_key === 'initiative.…'`-Ifs
|
||||||
|
- Daten: `loadOperatingSlices` / `refreshOm([…])` — **kein** Full-Reload nach Mutationen
|
||||||
|
- Route Gating: `OperatingRouteGate` + `MODE_ROUTE_GROUPS`
|
||||||
|
- Provider: `ScopedOperationsBridge` (ein Provider pro Vorhaben)
|
||||||
|
|
||||||
|
## Verboten
|
||||||
|
|
||||||
|
- `uiFeatures` am Archetyp-Profil (deprecated — nur Methode)
|
||||||
|
- Hardcodierte Methoden-UI in `methodUiDefaults.js` für **neue** Archetypen
|
||||||
|
- Parallele Steuerungslogik außerhalb `backend/steering/`
|
||||||
|
- Methoden-Dropdown ohne Archetyp-Filter (`GET /steering/methods?archetype_key=…`)
|
||||||
|
- **Initiative-Steuerung** (Next, Attention) außerhalb `steering/kernel/evaluate_steering()` — siehe `ADP_Steering_Kernel_Spine_v0.1.md`
|
||||||
|
|
||||||
|
## Fallback (legacy)
|
||||||
|
|
||||||
|
`methodUiDefaults.js` nur wenn Operating Context fehlt — nicht für neue Features erweitern.
|
||||||
|
|
||||||
|
## Abnahme neuer Archetyp-/Methoden-Slices
|
||||||
|
|
||||||
|
- Operating Context liefert `steering_elements` + `ui_features`
|
||||||
|
- pytest für Methoden-Vertrag (`test_ap24_*`) grün
|
||||||
|
- Spec unter `docs/product/archetypes/` referenziert Elemente und kompatible Methoden
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
---
|
||||||
|
description: Steering Kernel v0.4 — verbindliche Regeln für Read Models, Proposals, Attention, Agent-Slots, Ranker (alle Coding-Agenten)
|
||||||
|
globs: backend/steering/**,backend/data_layer/initiative_snapshot.py,frontend/src/components/SteeringProposalsPanel.jsx,frontend/src/components/AgentSlotsPanel.jsx,frontend/src/utils/steeringProposals.js,frontend/src/utils/agentSlots.js,frontend/src/utils/sprintCommitProposal.js,frontend/src/pages/initiative/InitiativeInboxPage.jsx,frontend/src/pages/initiative/InitiativePlanPage.jsx,frontend/src/pages/initiative/InitiativeOverviewPage.jsx,frontend/src/pages/modes/PlanSprintPage.jsx
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Kairo Steering Kernel — Coding Rules (verbindlich)
|
||||||
|
|
||||||
|
**Primärdokument:** `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`
|
||||||
|
**Architektur:** `docs/architecture/ADP_Steering_Kernel_Extension_Model_v0.1.md`
|
||||||
|
|
||||||
|
## Herzmaschine
|
||||||
|
|
||||||
|
- Initiative-Steuerung **nur** via `evaluate_steering()` in `backend/steering/kernel/evaluate.py`
|
||||||
|
- Snapshot spiegelt `evaluation.read_models` + `evaluation.proposals` + `evaluation.agent_slots` — **kein** Duplikat-Rechnen
|
||||||
|
|
||||||
|
## Neue Fähigkeit = Provider registrieren
|
||||||
|
|
||||||
|
| Was | Wo |
|
||||||
|
|-----|-----|
|
||||||
|
| Read Model | `steering/read_models/registry.py` |
|
||||||
|
| Proposal | `steering/proposals/registry.py` |
|
||||||
|
| Attention | `steering/attention/contributors/*.py` + Registry |
|
||||||
|
| Agent-Slot | `steering/agent_slots/registry.py` |
|
||||||
|
| Sprint-Ranker | `register_sprint_commit_ranker()` — weitere Ranker analog |
|
||||||
|
|
||||||
|
Aktivierung über `steering_elements` / `data_slices` im Methoden-Vertrag — **nicht** über Page-Ifs oder `method_key`-Branches im Kernel.
|
||||||
|
|
||||||
|
## Proposals
|
||||||
|
|
||||||
|
- **Kein Auto-Commit** — Accept in UI/API
|
||||||
|
- **Keine feste Bug/Story-Policy** — `ranker_key` + `factors[]`; Heuristik = Fallback (`heuristic_v0`)
|
||||||
|
- Abhängigkeiten: `dependency_refs`, `dependency_blocked`
|
||||||
|
- KI: `agent_v1` Ranker + Actor-Slot — **keine** hardcodierten Prompts (Principle Gate)
|
||||||
|
|
||||||
|
## Agent-Slots
|
||||||
|
|
||||||
|
- Deklarative Fenster für Actors — **kein** Prompt, **keine** Auto-Ausführung
|
||||||
|
- Config: `operatingContext.agent_slot_config` (`enabled_slots`, `guardrail_pack`, `stale_debt_days`)
|
||||||
|
- UI: `AgentSlotsPanel` + Snapshot `steering_kernel.agent_slots`
|
||||||
|
|
||||||
|
## Portfolio (K-Ext-5)
|
||||||
|
|
||||||
|
- Aggregiert Kernel-Output über Initiativen: `GET /api/workspace/steering`
|
||||||
|
- Modul: `steering/portfolio/aggregate.py` — **kein** Duplikat-Rechnen außerhalb Kernel
|
||||||
|
- Legacy `/api/workspace/attention` bleibt (SQL-Regeln) bis vollständige Migration
|
||||||
|
|
||||||
|
## Frontend
|
||||||
|
|
||||||
|
- `SteeringProposalsPanel` + `PROPOSAL_UI_CONFIG` in `utils/steeringProposals.js`
|
||||||
|
- Daten aus `steeringSnapshot.steering_kernel.proposals`
|
||||||
|
- Keine neue Proposal-Page pro Methode
|
||||||
|
|
||||||
|
## Methoden-Parität (Ist)
|
||||||
|
|
||||||
|
| Provider | Element-Gate |
|
||||||
|
|----------|--------------|
|
||||||
|
| `sprint_commit` | `work_cycle_scope` |
|
||||||
|
| `gate_next_actions` | `gate_fulfillment` |
|
||||||
|
| `intake_triage` | `backlog` slice, **excludes** `work_cycle_scope` |
|
||||||
|
| `epic_rollup` | `backlog_epic_hierarchy` |
|
||||||
|
| `planning_debt` / `execution_graph` | `gate_fulfillment` / `critical_path` |
|
||||||
|
| `tech_debt_summary` | `backlog` + `actions` slices |
|
||||||
|
| `review.due` / `recurring.due` / `review.guardrail` | Agent-Slots (data_slices + elements) |
|
||||||
|
|
||||||
|
## Verboten
|
||||||
|
|
||||||
|
- Steuerungslogik außerhalb `backend/steering/`
|
||||||
|
- Archetyp-Ifs für Steuerungs-UI
|
||||||
|
- `evaluate_next_work` für Commit-Vorschläge (Plan ≠ Ist)
|
||||||
|
- OM-Tabellen für Vorschläge
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- Unit-Test pro Provider/Ranker
|
||||||
|
- Snapshot-Integration wenn DB-Test verfügbar
|
||||||
|
- Truth Table aktualisieren
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
---
|
||||||
|
description: Vibe-Coder Agent — Kairo Operational API mit Actor Service Token
|
||||||
|
alwaysApply: false
|
||||||
|
globs:
|
||||||
|
- "**/*"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Kairo — Vibe-Coder API (AP1.7)
|
||||||
|
|
||||||
|
Du arbeitest als **Agent-Actor** an Kairo. Nutze die **Operational API** — nicht die volle UI-REST-API.
|
||||||
|
|
||||||
|
## Einmal-Setup (Nutzer, einmalig)
|
||||||
|
|
||||||
|
1. In Kairo als Tenant-Admin einloggen (Browser).
|
||||||
|
2. Actor `Cursor Agent` anlegen (Typ `agent`) — oder vorhandenen aus Actor-Verzeichnis nutzen.
|
||||||
|
3. Service Token erstellen:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/actors/{actor_id}/service-tokens
|
||||||
|
X-Auth-Token: {session}
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{"label": "Cursor Agent", "capabilities": []}
|
||||||
|
```
|
||||||
|
|
||||||
|
Antwort enthält **`token`** (nur einmal sichtbar) — Format: `kairo_at_{prefix}_{secret}`.
|
||||||
|
|
||||||
|
4. In Cursor **Environment Variables** (oder `.env` lokal, nicht committen):
|
||||||
|
|
||||||
|
```text
|
||||||
|
KAIRO_API_BASE=http://192.168.2.144:3097
|
||||||
|
KAIRO_ACTOR_TOKEN=kairo_at_...
|
||||||
|
```
|
||||||
|
|
||||||
|
Optional für Dogfooding:
|
||||||
|
|
||||||
|
```text
|
||||||
|
KAIRO_INITIATIVE_ID={uuid von „Jinkendo Kairo“}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Authentifizierung
|
||||||
|
|
||||||
|
Jeder Operational-Request:
|
||||||
|
|
||||||
|
```http
|
||||||
|
X-Actor-Token: {KAIRO_ACTOR_TOKEN}
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternativ: `Authorization: Bearer {KAIRO_ACTOR_TOKEN}`
|
||||||
|
|
||||||
|
**Nicht** Session-Token in Agent-Skripten hardcoden — Service Token ist tenant-scoped, capability-gebunden, widerrufbar.
|
||||||
|
|
||||||
|
## Typischer Agent-Loop
|
||||||
|
|
||||||
|
```text
|
||||||
|
GET /api/operational/me
|
||||||
|
GET /api/operational/initiatives/{id}/context → enthält active_work_cycle
|
||||||
|
GET /api/initiatives/{id}/work-cycles/active → aktive Sprint-Zeitbox
|
||||||
|
POST /api/initiatives/{id}/work-cycles → {"title","status":"active"}
|
||||||
|
GET /api/operational/next-action?initiative_id={id}&limit=5
|
||||||
|
… Arbeit …
|
||||||
|
PATCH /api/operational/actions/{id}/status {"status":"in_progress"}
|
||||||
|
PATCH /api/operational/actions/{id}/status {"status":"done","note":"Commit …"}
|
||||||
|
POST /api/operational/evidence {"initiative_id","action_id","title","body":"Commit-Link"}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- Kein Gate `reached`, kein Lifecycle-Wechsel, kein Portfolio-Reorder über Operational API.
|
||||||
|
- Mutierende Calls werden auditiert (`actor_id` aus Token).
|
||||||
|
- Token-Leak → Token widerrufen: `DELETE /api/actors/service-tokens/{token_id}` (Session-Auth).
|
||||||
|
|
||||||
|
## Referenz
|
||||||
|
|
||||||
|
- `docs/architecture/ADP_Operational_Actor_Interface_Vibe_Coder_v0.1.md`
|
||||||
|
- OpenAPI: `{KAIRO_API_BASE}/api/docs` (Nicht-Prod)
|
||||||
+9
-56
@@ -1,70 +1,23 @@
|
|||||||
# === .env neben der jeweiligen docker-compose.*.yml kopieren ====================
|
# === .env neben docker-compose.*.yml ==========================================
|
||||||
# Docker Compose ersetzt ${VARIABLE} beim Start.
|
# Pro Umgebung eigene Datei (~/docker/kairo/.env Prod, ~/docker/kairo-dev/.env Dev)
|
||||||
#
|
|
||||||
# Pro Umgebung eigene Datei (z. B. ~/docker/kairo/.env für Prod,
|
|
||||||
# ~/docker/kairo-dev/.env für Dev) — dieselben SCHLÜSSEL, unterschiedliche Werte.
|
|
||||||
# Kein separates DEV_APP_URL vs APP_URL: immer APP_URL, ALLOWED_ORIGINS, DB_*, …
|
|
||||||
|
|
||||||
# ─── Typische Werte PROD (docker-compose.yml) ─────────────────────────────────
|
# ─── DEV (docker-compose.dev-env.yml) ────────────────────────────────────────
|
||||||
# DB_NAME=kairo
|
|
||||||
# DB_USER=kairo_user
|
|
||||||
# DB_PASSWORD=…
|
|
||||||
# APP_URL=https://kairo.jinkendo.de
|
|
||||||
# ALLOWED_ORIGINS=https://kairo.jinkendo.de
|
|
||||||
# ENVIRONMENT=production
|
|
||||||
# KAIRO_MEDIA_HOST=/kairo-media
|
|
||||||
# MEDIA_ROOT=/app/media
|
|
||||||
|
|
||||||
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
|
|
||||||
# DB_NAME=kairo_dev
|
# DB_NAME=kairo_dev
|
||||||
# DB_USER=kairo_dev
|
# DB_USER=kairo_dev
|
||||||
# DB_PASSWORD=dev_password
|
# DB_PASSWORD=dev_password
|
||||||
# APP_URL=https://dev.kairo.jinkendo.de
|
# APP_URL=https://dev.kairo.jinkendo.de
|
||||||
# ALLOWED_ORIGINS=https://dev.kairo.jinkendo.de,http://192.168.2.49:3097
|
# ALLOWED_ORIGINS=https://dev.kairo.jinkendo.de,http://192.168.2.49:3097
|
||||||
# ENVIRONMENT=development
|
# ENVIRONMENT=development
|
||||||
# KAIRO_MEDIA_HOST=/kairo-media/dev
|
# SESSION_DAYS=30
|
||||||
# MEDIA_ROOT=/app/media
|
# KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||||
|
# KAIRO_BOOTSTRAP_ADMIN_PASSWORD=change-me-in-dev-env
|
||||||
|
# KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||||
|
# KAIRO_BOOTSTRAP_TENANT_NAME=Default Tenant
|
||||||
|
|
||||||
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
|
# ─── PROD (docker-compose.yml) ───────────────────────────────────────────────
|
||||||
DB_HOST=postgres
|
|
||||||
DB_PORT=5432
|
|
||||||
DB_NAME=kairo
|
DB_NAME=kairo
|
||||||
DB_USER=kairo_user
|
DB_USER=kairo_user
|
||||||
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
||||||
|
|
||||||
OPENROUTER_API_KEY=your_api_key_here
|
|
||||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
|
||||||
|
|
||||||
# Vereins-Kontingente hart blockieren (KI-Kosten!). Nur 1, true oder yes aktivieren.
|
|
||||||
CLUB_FEATURE_ENFORCE=1
|
|
||||||
|
|
||||||
# KI-Debug (Docker): KAIRO_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs.
|
|
||||||
# KAIRO_AI_DEBUG=1
|
|
||||||
|
|
||||||
SMTP_HOST=smtp.example.com
|
|
||||||
SMTP_PORT=587
|
|
||||||
SMTP_USER=noreply@jinkendo.de
|
|
||||||
SMTP_PASS=your_smtp_password
|
|
||||||
SMTP_FROM=noreply@jinkendo.de
|
|
||||||
SMTP_SSL=
|
|
||||||
SMTP_STARTTLS=
|
|
||||||
|
|
||||||
AUTO_ADMIN_FIRST_USER=true
|
|
||||||
ADMIN_BOOTSTRAP_EMAILS=
|
|
||||||
|
|
||||||
APP_URL=https://kairo.jinkendo.de
|
APP_URL=https://kairo.jinkendo.de
|
||||||
ALLOWED_ORIGINS=https://kairo.jinkendo.de
|
ALLOWED_ORIGINS=https://kairo.jinkendo.de
|
||||||
ENVIRONMENT=production
|
ENVIRONMENT=production
|
||||||
|
|
||||||
# Medien (Docker Compose): KAIRO_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
|
|
||||||
# MEDIA_ROOT = gleicher Pfad im Container (muss mit dem Mount-Ziel übereinstimmen).
|
|
||||||
KAIRO_MEDIA_HOST=/kairo-media
|
|
||||||
MEDIA_ROOT=/app/media
|
|
||||||
|
|
||||||
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
|
|
||||||
MEDIAWIKI_USER=Jinkendo
|
|
||||||
MEDIAWIKI_PASSWORD=CHANGE_ME
|
|
||||||
MEDIAWIKI_CATEGORY_EXERCISES=Übungen
|
|
||||||
MEDIAWIKI_CATEGORY_SKILLS=Fähigkeitsbeschreibung
|
|
||||||
MEDIAWIKI_CATEGORY_METHODS=Methodenbeschreibung
|
|
||||||
MEDIAWIKI_CATEGORY_MODELS=Reifegradmodelle
|
|
||||||
@@ -12,17 +12,30 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
echo "=== Deploying Kairo to DEVELOPMENT ==="
|
echo "=== Deploying Kairo to DEVELOPMENT ==="
|
||||||
cd /home/lars/docker/kairo-dev
|
REPO="http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git"
|
||||||
git fetch origin develop || git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git .
|
TARGET="/home/lars/docker/kairo-dev"
|
||||||
|
mkdir -p "$TARGET"
|
||||||
|
cd "$TARGET"
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
git clone -b develop "$REPO" .
|
||||||
|
else
|
||||||
|
git fetch origin develop
|
||||||
|
git checkout develop
|
||||||
git reset --hard origin/develop
|
git reset --hard origin/develop
|
||||||
docker compose -f docker-compose.dev-env.yml build --no-cache
|
fi
|
||||||
docker compose -f docker-compose.dev-env.yml up -d
|
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
||||||
sleep 5
|
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||||
if ! curl -sf http://localhost:8097/api/version; then
|
if ! docker compose -f docker-compose.dev-env.yml up -d --wait; then
|
||||||
echo "✗ DEV API nicht erreichbar — Backend-Logs (Migration/Startup):"
|
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 120 || true
|
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||||
|
docker compose -f docker-compose.dev-env.yml ps || true
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "✓ DEV API healthy"
|
if ! curl -sf http://localhost:8097/api/health; then
|
||||||
curl -sf http://localhost:3097/api/version && echo "✓ DEV über Frontend-Nginx (wie Browser) healthy"
|
echo "✗ DEV API nicht erreichbar — Backend-Logs:"
|
||||||
|
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ DEV API /api/health OK"
|
||||||
|
curl -sf http://localhost:3097/api/health && echo "✓ DEV Frontend-Proxy /api/health OK"
|
||||||
echo "=== Kairo DEV Deploy complete ==="
|
echo "=== Kairo DEV Deploy complete ==="
|
||||||
@@ -12,12 +12,30 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
echo "=== Deploying Kairo to PRODUCTION ==="
|
echo "=== Deploying Kairo to PRODUCTION ==="
|
||||||
cd /home/lars/docker/kairo
|
REPO="http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git"
|
||||||
git fetch origin main || git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git .
|
TARGET="/home/lars/docker/kairo"
|
||||||
|
mkdir -p "$TARGET"
|
||||||
|
cd "$TARGET"
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
git clone -b main "$REPO" .
|
||||||
|
else
|
||||||
|
git fetch origin main
|
||||||
|
git checkout main
|
||||||
git reset --hard origin/main
|
git reset --hard origin/main
|
||||||
docker compose build --no-cache
|
fi
|
||||||
docker compose up -d
|
docker compose build --no-cache backend frontend
|
||||||
sleep 5
|
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||||
curl -sf http://localhost:8004/api/version && echo "✓ PROD API (direkt) healthy"
|
if ! docker compose up -d --wait; then
|
||||||
curl -sf http://localhost:3004/api/version && echo "✓ PROD API über Frontend-Nginx (wie Browser) healthy"
|
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||||
|
docker compose logs backend --tail 150 || true
|
||||||
|
docker compose ps || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! curl -sf http://localhost:8004/api/health; then
|
||||||
|
echo "✗ PROD API nicht erreichbar — Backend-Logs:"
|
||||||
|
docker compose logs backend --tail 150 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ PROD API /api/health OK"
|
||||||
|
curl -sf http://localhost:3004/api/health && echo "✓ PROD Frontend-Proxy /api/health OK"
|
||||||
echo "=== Kairo PROD Deploy complete ==="
|
echo "=== Kairo PROD Deploy complete ==="
|
||||||
+97
-178
@@ -1,11 +1,13 @@
|
|||||||
name: Test Suite
|
name: Test Suite
|
||||||
|
|
||||||
# develop: push/PR → Tests gegen Dev (parallel oder vor Deploy Development).
|
# develop: push/PR → Tests gegen deployte Dev-Instanz (wartet auf Container).
|
||||||
# main: kein push/PR-Trigger — vermeidet doppelten Dev-Lauf beim Merge develop→main;
|
# main: push → Prod-Tests gegen kairo (8004/3004), parallel zu deploy-prod.yml.
|
||||||
# Prod-Tests nur via workflow_run nach erfolgreichem Deploy Production.
|
# workflow_run: optional (Gitea/act feuert oft nicht — push-Trigger ist maßgeblich).
|
||||||
|
# Frontend-Build: deploy-dev/prod (docker compose build backend frontend), nicht hier.
|
||||||
|
# compose-smoke (PR): eigener Stack auf CI-Ports 18197/13197 (kein Konflikt mit kairo-dev).
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [develop]
|
branches: [develop, main]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [develop]
|
branches: [develop]
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@@ -32,11 +34,16 @@ jobs:
|
|||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
APP_DIR="/home/lars/docker/kairo-dev"
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
fi
|
fi
|
||||||
|
elif [ "$REF_NAME" = "main" ]; then
|
||||||
|
APP_DIR="/home/lars/docker/kairo"
|
||||||
|
COMPOSE_FILE="docker-compose.yml"
|
||||||
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
APP_DIR="/home/lars/docker/kairo-dev"
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
echo "pytest gegen ${APP_DIR} (${COMPOSE_FILE})"
|
||||||
|
|
||||||
cd "$APP_DIR"
|
cd "$APP_DIR"
|
||||||
echo "Warte auf stabilen backend-Container …"
|
echo "Warte auf stabilen backend-Container …"
|
||||||
for i in $(seq 1 60); do
|
for i in $(seq 1 60); do
|
||||||
@@ -54,115 +61,99 @@ jobs:
|
|||||||
done
|
done
|
||||||
|
|
||||||
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
||||||
pip install -r /app/requirements-dev.txt &&
|
pip install -q -r requirements-dev.txt &&
|
||||||
cd /app &&
|
python -m pytest tests -ra -vv --tb=short &&
|
||||||
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
|
python run_seeds.py --only seed_001_cleanup_pytest_artifacts --force
|
||||||
python scripts/security_release_checks.py &&
|
|
||||||
ACCESS_LAYER_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
|
||||||
"
|
"
|
||||||
|
echo "✓ pytest OK"
|
||||||
|
|
||||||
lint-backend:
|
lint-backend:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Check backend syntax
|
- name: Checkout repository
|
||||||
run: |
|
if: github.event_name != 'workflow_run'
|
||||||
EVENT_NAME="${{ github.event_name }}"
|
uses: actions/checkout@v4
|
||||||
REF_NAME="${{ github.ref_name }}"
|
|
||||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
|
||||||
APP_DIR="/home/lars/docker/kairo"
|
|
||||||
|
|
||||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
- name: Check backend syntax (Checkout)
|
||||||
|
if: github.event_name != 'workflow_run'
|
||||||
|
run: |
|
||||||
|
python3 -m py_compile backend/main.py backend/run_migrations.py backend/db.py
|
||||||
|
echo "✓ Backend syntax OK"
|
||||||
|
|
||||||
|
- name: Check backend syntax (Deploy-Pfad)
|
||||||
|
if: github.event_name == 'workflow_run'
|
||||||
|
run: |
|
||||||
|
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
APP_DIR="/home/lars/docker/kairo-dev"
|
||||||
|
else
|
||||||
|
APP_DIR="/home/lars/docker/kairo"
|
||||||
fi
|
fi
|
||||||
elif [ "$REF_NAME" = "develop" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
|
||||||
fi
|
|
||||||
|
|
||||||
python3 -m py_compile "$APP_DIR/backend/main.py"
|
python3 -m py_compile "$APP_DIR/backend/main.py"
|
||||||
echo "✓ Backend syntax OK"
|
echo "✓ Backend syntax OK"
|
||||||
|
|
||||||
build-frontend:
|
compose-smoke:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: github.event_name == 'pull_request'
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Build frontend
|
|
||||||
run: |
|
|
||||||
EVENT_NAME="${{ github.event_name }}"
|
|
||||||
REF_NAME="${{ github.ref_name }}"
|
|
||||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
|
||||||
APP_DIR="/home/lars/docker/kairo"
|
|
||||||
|
|
||||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
|
||||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
|
||||||
fi
|
|
||||||
elif [ "$REF_NAME" = "develop" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
|
||||||
fi
|
|
||||||
|
|
||||||
cd "$APP_DIR/frontend"
|
|
||||||
npm install
|
|
||||||
npm run build
|
|
||||||
echo "✓ Frontend build OK"
|
|
||||||
|
|
||||||
k6-health-baseline:
|
|
||||||
name: k6 /health Baseline
|
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
env:
|
||||||
E2E_TARGET_URL: https://dev.kairo.jinkendo.de
|
COMPOSE_PROJECT_NAME: kairo-ci-smoke
|
||||||
|
DB_PASSWORD: ci_smoke_password
|
||||||
|
KAIRO_BACKEND_PORT: 18197
|
||||||
|
KAIRO_FRONTEND_PORT: 13197
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
- name: Isolierter Stack (CI-Ports, kein Konflikt mit kairo-dev)
|
||||||
id: e2e
|
run: |
|
||||||
|
set -e
|
||||||
|
COMPOSE="docker-compose.dev-env.yml"
|
||||||
|
API_PORT="${KAIRO_BACKEND_PORT}"
|
||||||
|
UI_PORT="${KAIRO_FRONTEND_PORT}"
|
||||||
|
echo "compose-smoke auf localhost:${API_PORT} / ${UI_PORT}"
|
||||||
|
docker compose -f "$COMPOSE" up -d --build --wait
|
||||||
|
curl -sf "http://localhost:${API_PORT}/api/health"
|
||||||
|
curl -sf "http://localhost:${UI_PORT}/api/health"
|
||||||
|
docker compose -f "$COMPOSE" exec -T backend pip install -q -r requirements-dev.txt
|
||||||
|
docker compose -f "$COMPOSE" exec -T backend python -m pytest tests -ra -vv --tb=short
|
||||||
|
docker compose -f "$COMPOSE" down -v
|
||||||
|
echo "✓ compose-smoke OK"
|
||||||
|
|
||||||
|
k6-health-baseline:
|
||||||
|
name: k6 /api/health Baseline
|
||||||
|
needs: [pytest-backend]
|
||||||
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: k6-Ziel wählen
|
||||||
|
id: k6
|
||||||
run: |
|
run: |
|
||||||
EVENT="${{ github.event_name }}"
|
EVENT="${{ github.event_name }}"
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
REF="${{ github.ref_name }}"
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||||
echo "base_url=https://kairo.jinkendo.de" >> $GITHUB_OUTPUT
|
elif [ "$REF" = "main" ]; then
|
||||||
echo "→ k6 gegen Prod-Basis."
|
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||||
else
|
else
|
||||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:8097" >> $GITHUB_OUTPUT
|
||||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ k6 gegen Dev (${DEV_BASE})."
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Dev /health abwarten
|
- name: /api/health abwarten
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
run: |
|
run: |
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
BASE="${{ steps.k6.outputs.base_url }}"
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 90); do
|
for i in $(seq 1 90); do
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
if curl -sf "$BASE/api/health" >/dev/null 2>&1; then
|
||||||
echo "Health OK (Versuch $i)"
|
echo "Health OK (Versuch $i)"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
sleep 2
|
sleep 2
|
||||||
done
|
done
|
||||||
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
curl -v "$BASE/api/health" || true
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Prod /health abwarten
|
|
||||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
|
||||||
run: |
|
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 60); do
|
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
|
||||||
echo "Health OK (Versuch $i)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
echo "Timeout: Prod /health nicht erreichbar"
|
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Install k6
|
- name: Install k6
|
||||||
@@ -175,26 +166,26 @@ jobs:
|
|||||||
aarch64|arm64) K6_ARCH=arm64 ;;
|
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||||
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
|
|
||||||
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||||
tar -xzf /tmp/k6.tgz -C /tmp
|
tar -xzf /tmp/k6.tgz -C /tmp
|
||||||
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||||
k6 version
|
|
||||||
|
|
||||||
- name: k6 Health-Baseline (parallele /health)
|
- name: k6 Health-Baseline
|
||||||
env:
|
|
||||||
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
BASE_URL="${{ steps.k6.outputs.base_url }}"
|
||||||
k6 run scripts/load/k6-health-baseline.js
|
if [ -z "$BASE_URL" ]; then
|
||||||
echo "✓ k6 Health-Baseline passed"
|
echo "BASE_URL leer — steps.k6.outputs.base_url prüfen"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "k6 gegen BASE_URL=$BASE_URL (K6_CI=1, quiet)"
|
||||||
|
BASE_URL="$BASE_URL" K6_CI=1 k6 run --quiet scripts/load/k6-health-baseline.js
|
||||||
|
echo "✓ k6 Health-Baseline OK"
|
||||||
|
|
||||||
playwright-tests:
|
playwright-smoke:
|
||||||
|
needs: [pytest-backend]
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
|
||||||
E2E_TARGET_URL: https://dev.kairo.jinkendo.de
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -202,111 +193,39 @@ jobs:
|
|||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
node-version: "20"
|
||||||
|
|
||||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
- name: Playwright-Ziel wählen
|
||||||
id: e2e
|
id: pw
|
||||||
run: |
|
run: |
|
||||||
EVENT="${{ github.event_name }}"
|
EVENT="${{ github.event_name }}"
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
REF="${{ github.ref_name }}"
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||||
echo "base_url=https://kairo.jinkendo.de" >> $GITHUB_OUTPUT
|
elif [ "$REF" = "main" ]; then
|
||||||
echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
|
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||||
else
|
else
|
||||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:3097" >> $GITHUB_OUTPUT
|
||||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Dev /health abwarten
|
- name: /api/health abwarten
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
run: |
|
run: |
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
BASE="${{ steps.pw.outputs.base_url }}"
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 90); do
|
for i in $(seq 1 90); do
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
if curl -sf "$BASE/api/health" >/dev/null 2>&1; then
|
||||||
echo "Health OK (Versuch $i)"
|
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
sleep 2
|
sleep 2
|
||||||
done
|
done
|
||||||
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Prod /health abwarten
|
|
||||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
|
||||||
run: |
|
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 60); do
|
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
|
||||||
echo "Health OK (Versuch $i)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
echo "Timeout: Prod /health nicht erreichbar"
|
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Testnutzer registrieren (Dev, nur wenn möglich)
|
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
env:
|
|
||||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
|
||||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
|
||||||
run: |
|
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
|
|
||||||
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
curl -sf -X POST "$BASE/api/auth/register" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d "{\"email\":\"${E2E_DEV_TEST_EMAIL}\",\"password\":\"${E2E_DEV_TEST_PASSWORD}\",\"name\":\"Playwright CI\"}" \
|
|
||||||
|| echo "(Register evtl. schon erfolgt oder Limits — Login-Test gilt trotzdem.)"
|
|
||||||
|
|
||||||
- name: Install Playwright
|
- name: Install Playwright
|
||||||
run: |
|
run: |
|
||||||
npm ci || npm install
|
npm install
|
||||||
npx playwright install --with-deps chromium
|
npx playwright install --with-deps chromium
|
||||||
|
|
||||||
- name: Run Playwright tests
|
- name: Run Playwright smoke
|
||||||
env:
|
env:
|
||||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
PLAYWRIGHT_BASE_URL: ${{ steps.pw.outputs.base_url }}
|
||||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
run: npx playwright test tests/smoke-health.spec.js
|
||||||
run: |
|
|
||||||
set -e
|
|
||||||
MODE="${{ steps.e2e.outputs.mode }}"
|
|
||||||
BASE_URL="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
export PLAYWRIGHT_BASE_URL="$BASE_URL"
|
|
||||||
|
|
||||||
if [ "$MODE" = "prod" ]; then
|
|
||||||
export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
|
|
||||||
export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
|
|
||||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
|
||||||
echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
|
|
||||||
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
|
|
||||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
|
||||||
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir -p screenshots
|
|
||||||
npx playwright test
|
|
||||||
echo "✓ Playwright tests passed"
|
|
||||||
|
|
||||||
- name: Upload test screenshots
|
|
||||||
if: failure()
|
|
||||||
uses: actions/upload-artifact@v3
|
|
||||||
with:
|
|
||||||
name: playwright-screenshots
|
|
||||||
path: screenshots/
|
|
||||||
retention-days: 7
|
|
||||||
@@ -59,6 +59,7 @@ coverage/
|
|||||||
# Temp
|
# Temp
|
||||||
tmp/
|
tmp/
|
||||||
*.tmp
|
*.tmp
|
||||||
|
*_alt.md
|
||||||
|
|
||||||
# Claude: nur ausgewählte Bereiche versionieren
|
# Claude: nur ausgewählte Bereiche versionieren
|
||||||
.claude/**
|
.claude/**
|
||||||
|
|||||||
@@ -1,59 +1,188 @@
|
|||||||
# Kairo Jinkendo – Entwickler-Kontext
|
# CLAUDE.md – Jinkendo Kairo
|
||||||
|
|
||||||
## Projekt-Übersicht
|
Du arbeitest im Projekt **Jinkendo Kairo**.
|
||||||
|
|
||||||
**Kairo Jinkendo** (回廊 Jinkendo) — Schwesterprodukt in der **Jinkendo**-App-Familie (人拳道).
|
Kairo ist der operative Program Director der Jinkendo-Produktfamilie.
|
||||||
Domains: kairo.jinkendo.de · dev.kairo.jinkendo.de
|
|
||||||
|
|
||||||
**Status:** Infrastruktur (Docker, Gitea Actions, Deployment-Doku) ist eingerichtet. Anwendungscode folgt.
|
## Leitfrage
|
||||||
|
|
||||||
## Tech-Stack (geplant)
|
Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||||
|
|
||||||
| Komponente | Technologie |
|
---
|
||||||
|-----------|-------------|
|
|
||||||
| Frontend | React 18 + Vite + PWA (Node 20) |
|
|
||||||
| Backend | FastAPI Python 3.12 |
|
|
||||||
| Datenbank | PostgreSQL 16 Alpine |
|
|
||||||
| Container | Docker + Docker Compose |
|
|
||||||
| Auth | Token-basiert + bcrypt (Familien-Standard) |
|
|
||||||
|
|
||||||
**Ports:** Prod 3004/8004 · Dev 3097/8097 — nicht ändern ohne explizite Freigabe (Reverse Proxy/Fritz!Box).
|
## 1. Aktueller Entwicklungsstand
|
||||||
|
|
||||||
## Deployment
|
Foundation AP0.1–AP0.7 abgeschlossen. Operating Model AP0.8–AP0.10, Steering AP1.0–AP1.1b technisch geliefert.
|
||||||
|
|
||||||
```
|
**Technisch vorhanden:**
|
||||||
Internet → Fritz!Box (privat.stommer.com) → Synology NAS → Raspberry Pi 5 (192.168.2.49)
|
|
||||||
|
|
||||||
Git Workflow:
|
- Tenant, User, Actor, TenantContext, Auth, Capabilities
|
||||||
develop → Auto-Deploy → dev.kairo.jinkendo.de (kairo-dev/, Port 3097/8097)
|
- OM-Entitäten (Backlog, Blocker, Milestone-Brücke, Evidence, Decision, Review, Recurring)
|
||||||
main → Auto-Deploy → kairo.jinkendo.de (kairo/, Port 3004/8004)
|
- `backend/steering/` (Lifecycle, Snapshot, Method Registry, **Plugin-Architektur AP2.3/AP2.4**)
|
||||||
|
- **Operating Context API** + slice-bewusstes Frontend-Laden (AP2.3)
|
||||||
|
- **Steuerungselement-Registry** + Methoden-Vertrag (AP2.4)
|
||||||
|
- Workspace-GUI, Data Layer, Actor Directory
|
||||||
|
|
||||||
Gitea: http://192.168.2.144:3000/Lars/Kairo-Jinkendo
|
**Produktlich fehlt (Vision):**
|
||||||
Runner: Raspberry Pi (/home/lars/gitea-runner/) — gemeinsam mit Shinkan/Mitai
|
|
||||||
|
|
||||||
Manuell:
|
- Getrennte IA (Ausführung / Plan / Eingang / Journey) — nicht Omnibus-InitiativeDetail
|
||||||
cd /home/lars/docker/kairo[-dev]
|
- RoadmapItem / Quality Gates — Milestone heute nur CRUD
|
||||||
docker compose -f docker-compose[.dev-env].yml build --no-cache && up -d
|
- Plan vs. Ist, Abhängigkeiten, Task-Hierarchie
|
||||||
|
- Modal/Detail-Bearbeitung statt Inline-CRUD
|
||||||
|
|
||||||
|
**Ist-Stand:** `docs/product/Kairo_Implementation_Truth_Table_v0.1.md`
|
||||||
|
|
||||||
|
Nächster Fokus: **Specs Welle 1 finalisieren**, dann **Stufe-A End-to-End** (AP2.2b/c/e, AP1.9d) und **AP2.1 Validation** — auf Plugin-Architektur AP2.3/4 aufsetzen, kein Layout-Patching auf InitiativeDetail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Verbindliche Primärdokumente
|
||||||
|
|
||||||
|
Lies bei Projektstart in dieser Reihenfolge:
|
||||||
|
|
||||||
|
1. `docs/product/Kairo_Vision_and_Product_Direction_v0.2.md`
|
||||||
|
2. `docs/product/Kairo_Canonical_Operating_Model_v0.2.md`
|
||||||
|
3. `docs/product/Kairo_Implementation_Truth_Table_v0.1.md`
|
||||||
|
4. `docs/product/DOCUMENTATION_REVISION_PROGRAM_v0.2.md`
|
||||||
|
5. `docs/product/Kairo_Corrected_MVP_Roadmap_v0.2.md`
|
||||||
|
6. `docs/architecture/Kairo_System_Target_State_v0.1.md`
|
||||||
|
7. `docs/architecture/ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`
|
||||||
|
8. `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||||
|
9. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||||
|
10. `.cursor/rules/kairo-architecture.mdc`
|
||||||
|
11. **`.cursor/rules/kairo-steering-kernel.mdc`** + `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md` (Steering Kernel v0.3 — Read Models, Proposals, Ranker)
|
||||||
|
11. `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md` (AP2.3 — **geliefert**)
|
||||||
|
12. `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md` (AP2.4 — **geliefert**)
|
||||||
|
13. `.cursor/rules/kairo-plugin-architecture.mdc`
|
||||||
|
|
||||||
|
Historisch / Referenz (nicht führend bei Konflikt):
|
||||||
|
|
||||||
|
- `docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md` → superseded by Vision v0.2
|
||||||
|
- `docs/product/Kairo_Canonical_Operating_Model_v0.1.md` → superseded by v0.2
|
||||||
|
- `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md` — Referenz
|
||||||
|
- Sprint Completion Reports — historisch
|
||||||
|
|
||||||
|
Bei Konflikten gilt folgende Auslegungsreihenfolge:
|
||||||
|
|
||||||
|
1. Vision & Product Direction v0.2
|
||||||
|
2. Canonical Operating Model v0.2
|
||||||
|
3. Implementation Truth Table
|
||||||
|
4. System Target State / ADPs
|
||||||
|
5. Tenant Invariants, Principle Gate
|
||||||
|
6. Product Spec v0.2 (Referenz)
|
||||||
|
7. Sprint History
|
||||||
|
8. Mitai/Shinkan Designprinzipien (Referenz, kein Scope)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Aktuelle Produktleitlinie
|
||||||
|
|
||||||
|
Kairo darf nicht auf `Initiative → Action` reduziert werden.
|
||||||
|
|
||||||
|
Der aktuelle Vorhaben-/Maßnahmen-Slice ist nur ein technischer Startpunkt.
|
||||||
|
|
||||||
|
Kairo ist ein operativer Program Director.
|
||||||
|
|
||||||
|
Das kanonische Operating Model umfasst (Zielbild):
|
||||||
|
|
||||||
|
- Initiative / Programm, Project optional
|
||||||
|
- **Roadmap / RoadmapItem** (Gates, Meilensteine, Reifegrade) — Plan-Struktur
|
||||||
|
- BacklogItem (Eingang) → Action (Arbeitspaket) → Task (später) — Ist-Struktur
|
||||||
|
- Assignment, Blocker, Evidence, Decision, Review, RecurringElement
|
||||||
|
- AttentionItem, NextActionCandidate (Read Models via `backend/steering/`)
|
||||||
|
|
||||||
|
**UI-Regel:** Workspace = Portfolio aller Initiativen. Initiative-Übersicht = operative Steuerung (Alltag). Pflege/Anlage auf Unterseiten. Vibe-Coder über Operational Actor Interface (API).
|
||||||
|
|
||||||
|
Prompt-/KI-/Workflow-/MCP-Themen bleiben eingefroren, bis der MVP-Fachkern entlang des Operating Models trägt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Designprinzipien als Referenz
|
||||||
|
|
||||||
|
Die Designprinzipien aus Mitai und Shinkan liegen unter:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/reference/design-principles/
|
||||||
|
mitai/
|
||||||
|
shinkan/
|
||||||
|
alignment/
|
||||||
```
|
```
|
||||||
|
|
||||||
## Verzeichnisstruktur (Zielbild)
|
Diese Dokumente sind **Referenzmaterial**, nicht direkter Arbeitsauftrag.
|
||||||
|
|
||||||
```
|
Sie dienen dazu, Entscheidungen zu begründen und bekannte Anti-Patterns zu vermeiden.
|
||||||
backend/ # FastAPI — noch anzulegen
|
|
||||||
frontend/ # React + Vite — noch anzulegen
|
|
||||||
.gitea/workflows/ # CI/CD (deploy + test)
|
|
||||||
docs/ # Deployment-Doku
|
|
||||||
scripts/load/ # k6 Health-Baseline
|
|
||||||
```
|
|
||||||
|
|
||||||
## Referenz
|
Sie dürfen nicht dazu verwendet werden, Kairo mit Mitai- oder Shinkan-Domänenlogik zu überladen.
|
||||||
|
|
||||||
Deployment-Muster und Familien-Standards: Schwesterprojekt **shinkan-jinkendo** (`c:\Dev\shinkan-jinkendo`).
|
---
|
||||||
|
|
||||||
## Jinkendo-Familie
|
## 4. Auslegungsreihenfolge bei Konflikten
|
||||||
|
|
||||||
```
|
Siehe **Abschnitt 2** — die Product-Reset-Reihenfolge ist verbindlich.
|
||||||
mitai.jinkendo.de → Körper-Tracker (身体)
|
|
||||||
shinkan.jinkendo.de → Trainingsplanung (真観)
|
Bei technischen Foundation-Konflikten zusätzlich:
|
||||||
kairo.jinkendo.de → (回廊 — Produktdefinition folgt)
|
|
||||||
```
|
- `Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||||
|
- `Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||||
|
|
||||||
|
Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Verbindliche Regeln
|
||||||
|
|
||||||
|
1. Kairo ist mandantenfähig.
|
||||||
|
2. Alle operativen Zuweisungen laufen über Actors.
|
||||||
|
3. User und Actor sind nicht dasselbe.
|
||||||
|
4. Agenten sind Actors, keine Sonderlogik.
|
||||||
|
5. Jeder geschützte Request soll über TenantContext aufgelöst werden.
|
||||||
|
6. Auth, Capability, Feature und Governance sind getrennte Konzepte.
|
||||||
|
7. Rechte und Capabilities werden nicht verstreut hardcodiert.
|
||||||
|
8. Prompts werden nicht hardcodiert.
|
||||||
|
9. Platzhalter werden validiert.
|
||||||
|
10. Fachliche Konfiguration wird nicht hardcodiert.
|
||||||
|
11. Admin- und Agentenaktionen werden auditiert.
|
||||||
|
12. Migrationen sind nummeriert und reproduzierbar.
|
||||||
|
|
||||||
|
### Plugin-Architektur (AP2.3 / AP2.4 — verbindlich)
|
||||||
|
|
||||||
|
13. **Archetyp ≠ Methode:** Archetyp = IA-Hülle + `om_capabilities`; Methode = Steuerungsmotor (`steering_elements`, `ui_features`, Strategie).
|
||||||
|
14. Runtime-Auflösung über `GET …/operating-context` — kein hardcodiertes Methoden-/Archetyp-UI in React-Pages.
|
||||||
|
15. Neue Archetypen/Methoden nur über **Registrierungsmodule** (`entity_archetypes/`, `steering/methods/registrations/`) — Open/Closed.
|
||||||
|
16. Control-/Work-UI aus `steering_elements` + `steeringElementRegistry.js`, nicht aus Archetyp-Ifs.
|
||||||
|
17. Siehe `.cursor/rules/kairo-plugin-architecture.mdc` und ADP AP2.3 / AP2.4.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Nicht tun
|
||||||
|
|
||||||
|
- Kairo auf `Initiative → Action` reduzieren oder als To-do-Tool behandeln
|
||||||
|
- InitiativeDetail weiter als Omnibus-CRUD-Seite ausbauen (Layout-Patches)
|
||||||
|
- Inline-Listenformulare als Haupt-Bearbeitungs-Pattern einführen
|
||||||
|
- Meilensteine als Status-Dropdown ohne Gate-Verifikation behandeln
|
||||||
|
- Prompt-/KI-/Workflow-/MCP-Arbeit vor Operating-Model-MVP
|
||||||
|
- keine Mitai-Domänenlogik kopieren
|
||||||
|
- keine Shinkan-Domänenlogik kopieren
|
||||||
|
- keine Trainingsplanung bauen
|
||||||
|
- keine Gesundheitslogik bauen
|
||||||
|
- keine Lebensmanager-/Seichō-Logik in Kairo einbauen
|
||||||
|
- kein Billing oder SSO bauen
|
||||||
|
- keine strategischen Produktentscheidungen eigenmächtig ändern
|
||||||
|
- keine Designprinzipien aus `docs/reference/` ohne Principle-Gate oder Architecture Decision in Scope ziehen
|
||||||
|
- **keine Archetyp-Ifs** in Pages für Steuerungs-UI (`initiative.product === …`) — AP2.4 `steering_elements`
|
||||||
|
- **`methodUiDefaults.js` nicht für neue Archetypen erweitern** — Operating Context + Resolver
|
||||||
|
- **kein Full-`load()`** nach OM-Mutationen — `refreshOm([sliceKeys])`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Abweichungen
|
||||||
|
|
||||||
|
Bei notwendiger Abweichung erstelle ein Architecture Decision Proposal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Nächste Entwicklungsschritte
|
||||||
|
|
||||||
|
Siehe `docs/product/Kairo_Corrected_MVP_Roadmap_v0.2.md` und `Sprint1_AP1_2c_IA_Skeleton_Assignment_v0.1.md`.
|
||||||
|
|
||||||
|
Foundation AP0.1–AP2.4 Plugin-Architektur geliefert. **Produkt:** Specs Welle 1 → AP2.2b/c/e + AP1.9d → AP2.1 Validation. Scope Lock: `ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`; Plugin: ADP AP2.3/AP2.4.
|
||||||
@@ -1,63 +1,424 @@
|
|||||||
# Kairo Jinkendo (回廊)
|
# Jinkendo Kairo
|
||||||
|
|
||||||
**Programmmanager für alles im Leben** — Produktfamilie Jinkendo (人拳道), Schwesterprodukt zu Shinkan und Mitai.
|
Operativer Program Director der Jinkendo-Produktfamilie.
|
||||||
|
|
||||||
> Infrastruktur-Setup: Deployment, Docker und Gitea Actions sind vorbereitet.
|
Kairo steuert Vorhaben, Programme, Projekte, Meilensteine, Maßnahmen, Backlogs, Reviews, Nachweise und die Zusammenarbeit von Menschen, Arbeitsgruppen und KI-Agenten.
|
||||||
> Anwendungscode (Backend/Frontend) folgt in einem separaten Schritt.
|
|
||||||
|
|
||||||
## Deployment-Übersicht
|
## Leitfrage
|
||||||
|
|
||||||
| Umgebung | Branch | Server-Pfad | Host-Ports (UI/API) | Domain |
|
> Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||||
|----------|--------|-------------|---------------------|--------|
|
|
||||||
| **Development** | `develop` | `/home/lars/docker/kairo-dev` | 3097 / 8097 | https://dev.kairo.jinkendo.de |
|
|
||||||
| **Production** | `main` | `/home/lars/docker/kairo` | 3004 / 8004 | https://kairo.jinkendo.de |
|
|
||||||
|
|
||||||
Auto-Deploy via Gitea Actions auf dem Raspberry Pi (gleicher Runner wie Shinkan/Mitai).
|
## Product Direction Reset
|
||||||
|
|
||||||
**Gitea:** http://192.168.2.144:3000/Lars/Kairo-Jinkendo
|
Kairo wurde nach AP0.7 produktstrategisch neu ausgerichtet.
|
||||||
|
|
||||||
## Tech-Stack (geplant)
|
Die führenden Dokumente sind:
|
||||||
|
|
||||||
- **Frontend:** React 18 + Vite + PWA
|
- `docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md`
|
||||||
- **Backend:** FastAPI (Python 3.12)
|
- `docs/product/Kairo_Canonical_Operating_Model_v0.1.md`
|
||||||
- **Datenbank:** PostgreSQL 16
|
- `docs/product/Kairo_Corrected_MVP_Roadmap_v0.1.md`
|
||||||
- **Container:** Docker + Docker Compose
|
|
||||||
|
|
||||||
## Lokales Setup (wenn App-Code vorhanden)
|
Kairo ist nicht als einfache Aufgabenliste zu verstehen, sondern als operativer Program Director.
|
||||||
|
|
||||||
|
Der aktuelle technische Slice `Initiative → Action` bleibt gültig, ist aber nicht das Zielmodell.
|
||||||
|
|
||||||
|
Siehe auch `CLAUDE.md` für die verbindliche Dokumentenreihenfolge.
|
||||||
|
|
||||||
|
Abschlussbericht: `docs/sprints/Sprint0_AP0_R1_Completion_Report_v0.1.md`
|
||||||
|
|
||||||
|
**Nächster geplanter Auftrag (Entwurf):** `docs/sprints/Sprint0_AP0_8_Assignment_v0.1.md`
|
||||||
|
|
||||||
|
## Startzustand
|
||||||
|
|
||||||
|
Dieses Repository startet mit einem reinen Spezifikations- und Sprint-0-Handover-Paket.
|
||||||
|
|
||||||
|
Noch nicht enthalten:
|
||||||
|
|
||||||
|
- produktiver Anwendungscode
|
||||||
|
- endgültiger Technologie-Stack
|
||||||
|
- vollständige Jinkendo-Foundation
|
||||||
|
- Mitai- oder Shinkan-Code
|
||||||
|
- Billing / SSO / zentrale Produktfamilien-Konvergenz
|
||||||
|
|
||||||
|
## Verbindliche Dokumente für Sprint 0
|
||||||
|
|
||||||
|
**Product Reset (führend ab AP0.R1):**
|
||||||
|
|
||||||
|
1. `docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md`
|
||||||
|
2. `docs/product/Kairo_Canonical_Operating_Model_v0.1.md`
|
||||||
|
3. `docs/product/Kairo_Corrected_MVP_Roadmap_v0.1.md`
|
||||||
|
|
||||||
|
**Foundation & Steuerung:**
|
||||||
|
|
||||||
|
4. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||||
|
5. `docs/architecture/Kairo_Current_State_Gap_Analysis_AP0.1_AP0.6b_v0.1.md`
|
||||||
|
6. `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||||
|
7. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||||
|
8. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||||
|
9. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||||
|
10. `CLAUDE.md`
|
||||||
|
11. `.cursor/rules/kairo-architecture.mdc`
|
||||||
|
|
||||||
|
## Arbeitsmodus
|
||||||
|
|
||||||
|
Kairo wird iterativ entwickelt.
|
||||||
|
|
||||||
|
Sprint 0 baut nur das Fundament:
|
||||||
|
|
||||||
|
- Tenant
|
||||||
|
- User
|
||||||
|
- Actor
|
||||||
|
- TenantContext
|
||||||
|
- Auth-Gates
|
||||||
|
- Capability/Rights Registry
|
||||||
|
- minimale Feature Registry
|
||||||
|
- minimale Prompt Registry
|
||||||
|
- Platzhaltermodell
|
||||||
|
- Audit
|
||||||
|
- Migration/Deploy-Grundlage
|
||||||
|
|
||||||
|
Vorhaben, Projekte, Meilensteine und Maßnahmen kommen erst nach Sprint 0.
|
||||||
|
|
||||||
|
|
||||||
|
## Designprinzipien-Referenzen
|
||||||
|
|
||||||
|
Die extrahierten Designprinzipien aus Mitai und Shinkan liegen im Repository unter:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/reference/design-principles/
|
||||||
|
```
|
||||||
|
|
||||||
|
Diese Dokumente sind Referenzen, kein direkter Sprint-Scope.
|
||||||
|
|
||||||
|
Verbindlich ist nur, was über das Kairo Sprint-0 Principle Gate oder eine Architecture Decision übernommen wurde.
|
||||||
|
|
||||||
|
## Deployment & CI
|
||||||
|
|
||||||
|
Zwei getrennte Gitea-Workflows (wie Shinkan):
|
||||||
|
|
||||||
|
| Workflow | Branch |
|
||||||
|
|----------|--------|
|
||||||
|
| **Deploy Development** | `develop` |
|
||||||
|
| **Deploy Production** | `main` |
|
||||||
|
| **Test Suite** | nach Deploy + bei Push/PR `develop` |
|
||||||
|
|
||||||
|
Details: [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
|
Voraussetzungen: Docker + Docker Compose.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git
|
git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git
|
||||||
cd Kairo-Jinkendo
|
cd Kairo-Jinkendo
|
||||||
cp .env.example .env
|
git checkout develop
|
||||||
# .env anpassen
|
|
||||||
|
|
||||||
# Development
|
# Dev-Stack (PostgreSQL + Backend + Frontend)
|
||||||
docker compose -f docker-compose.dev-env.yml up --build
|
docker compose -f docker-compose.dev-env.yml up --build
|
||||||
|
|
||||||
# Production (lokal)
|
# Health prüfen
|
||||||
docker compose up --build
|
curl http://localhost:8097/api/health
|
||||||
|
curl http://localhost:3097/api/health
|
||||||
|
|
||||||
|
# Tests im Backend-Container
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend pip install -r requirements-dev.txt
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
```
|
```
|
||||||
|
|
||||||
Frontend (Dev): http://localhost:3097
|
UI: http://localhost:3097 · API: http://localhost:8097
|
||||||
Backend (Dev): http://localhost:8097
|
|
||||||
|
|
||||||
## Server-Einrichtung
|
Interaktive API-Doku (Dev): http://localhost:8097/api/docs
|
||||||
|
|
||||||
Siehe [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) für Verzeichnisse, `.env`-Dateien und Reverse-Proxy-Hinweise auf dem Pi.
|
### Auth (AP0.2)
|
||||||
|
|
||||||
## Git-Workflow
|
**Ersteinrichtung Dev** (automatisch per Seed nach jedem Backend-Start):
|
||||||
|
|
||||||
```
|
| Feld | Wert |
|
||||||
develop → Auto-Deploy → kairo-dev (Dev)
|
|------|------|
|
||||||
main → Auto-Deploy → kairo (Prod)
|
| E-Mail | `lars@stommer.com` |
|
||||||
|
| Passwort | `12345678` |
|
||||||
|
|
||||||
|
Alternativ: UI-Registrierung (nur wenn DB leer und Dev-Seed deaktiviert) oder Bootstrap per `.env`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_PASSWORD=…
|
||||||
|
KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dokumentation
|
Migrationen & idempotente Data-Seeds: [docs/MIGRATIONS.md](docs/MIGRATIONS.md)
|
||||||
|
|
||||||
- **Deployment:** [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)
|
| Endpoint | Methode | Auth | Beschreibung |
|
||||||
- **Entwickler-Kontext:** [CLAUDE.md](CLAUDE.md)
|
|----------|---------|------|--------------|
|
||||||
- **Schwesterprojekt (Referenz):** [shinkan-jinkendo](http://192.168.2.144:3000/Lars/shinkan-jinkendo)
|
| `/api/auth/setup-status` | GET | — | Ob Erstregistrierung offen ist |
|
||||||
|
| `/api/auth/register` | POST | — | Erster User → Portal-Admin + Tenant (nur wenn noch kein User) |
|
||||||
|
| `/api/auth/login` | POST | — | E-Mail + Passwort → Session-Token |
|
||||||
|
| `/api/auth/logout` | POST | `X-Auth-Token` | Session löschen |
|
||||||
|
| `/api/me` | GET | `X-Auth-Token` | Aktueller User + Tenant-Liste |
|
||||||
|
| `/api/me/context` | GET | `X-Auth-Token` | TenantContext (Tenant + Human Actor + Capabilities) |
|
||||||
|
| `/api/me/entitlements` | GET | `X-Auth-Token` | Entitlements-Snapshot (Rollen, Capabilities, Features-Platzhalter) |
|
||||||
|
| `/api/me/admin/demo` | GET | `X-Auth-Token` + `kairo.admin.access` | Beispiel-Endpoint mit `require_capability` |
|
||||||
|
| `/api/me/tenant` | POST | `X-Auth-Token` | Aktiven Tenant wechseln (nur Memberships) |
|
||||||
|
|
||||||
## Lizenz
|
Vorhaben und Maßnahmen (AP0.5 minimaler Slice):
|
||||||
|
|
||||||
Proprietary – Lars Stommer
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/initiatives` | GET | `kairo.initiative.read` | Vorhaben im aktiven Tenant |
|
||||||
|
| `/api/initiatives` | POST | `kairo.initiative.manage` | Vorhaben anlegen |
|
||||||
|
| `/api/initiatives/{id}` | GET | `kairo.initiative.read` | Einzelnes Vorhaben |
|
||||||
|
| `/api/initiatives/{id}` | PATCH | `kairo.initiative.manage` | Vorhaben bearbeiten |
|
||||||
|
| `/api/initiatives/{id}` | DELETE | `kairo.initiative.manage` | Vorhaben löschen |
|
||||||
|
| `/api/initiatives/{id}/actions` | GET | `kairo.action.read` | Maßnahmen eines Vorhabens |
|
||||||
|
| `/api/initiatives/{id}/actions` | POST | `kairo.action.manage` | Maßnahme anlegen |
|
||||||
|
| `/api/actions/{id}` | GET | `kairo.action.read` | Einzelne Maßnahme |
|
||||||
|
| `/api/actions/{id}` | PATCH | `kairo.action.manage` | Maßnahme bearbeiten / Status |
|
||||||
|
| `/api/actions/{id}/assignments` | PUT | `kairo.action.manage` | Actors zuweisen (ersetzt Liste) |
|
||||||
|
| `/api/actions/{id}` | DELETE | `kairo.action.manage` | Maßnahme löschen |
|
||||||
|
| `/api/actions/me/open` | GET | `kairo.action.read` | Offene Maßnahmen des aktuellen Actors (via Data Layer) |
|
||||||
|
|
||||||
|
Actor Directory und Workspace Data Layer (AP0.7):
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/actors` | GET | `kairo.actor.read` | Actors des aktiven Tenants (Filter: `actor_type`, `q`, `include_inactive`) |
|
||||||
|
| `/api/actors/{id}` | GET | `kairo.actor.read` | Einzelner Actor (404 cross-tenant) |
|
||||||
|
| `/api/workspace/summary` | GET | `kairo.workspace.read` | Workspace-Kennzahlen |
|
||||||
|
| `/api/workspace/actions/open` | GET | `kairo.workspace.read` | Meine offenen Maßnahmen (open/in_progress) |
|
||||||
|
| `/api/workspace/actions/blocked` | GET | `kairo.workspace.read` | Meine blockierten Maßnahmen |
|
||||||
|
| `/api/workspace/initiatives/active` | GET | `kairo.workspace.read` | Aktive/pausierte Vorhaben (`?limit=`) |
|
||||||
|
| `/api/workspace/actors/workload` | GET | `kairo.workspace.read` | Actor-Workload (Basic) |
|
||||||
|
|
||||||
|
Operating Model Extension I (AP0.8, Schema `007`):
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/workspace/attention` | GET | `kairo.attention.read` | Regelbasierte Attention-Items |
|
||||||
|
| `/api/workspace/next-actions` | GET | `kairo.attention.read` | NextActionCandidates (`?limit=`) |
|
||||||
|
| `/api/initiatives/{id}/blockers` | GET/POST | `kairo.blocker.read/manage` | Blocker eines Vorhabens |
|
||||||
|
| `/api/blockers/{id}` | GET/PATCH/DELETE | `kairo.blocker.read/manage` | Einzelner Blocker |
|
||||||
|
| `/api/initiatives/{id}/backlog` | GET/POST | `kairo.backlog.read/manage` | Backlog-Items |
|
||||||
|
| `/api/backlog/{id}` | GET/PATCH/DELETE | `kairo.backlog.read/manage` | Einzelnes Backlog-Item |
|
||||||
|
| `/api/backlog/{id}/convert-to-action` | POST | `kairo.backlog.manage` | Backlog → Maßnahme |
|
||||||
|
| `/api/initiatives/{id}/milestones` | GET/POST | `kairo.milestone.read/manage` | Meilensteine |
|
||||||
|
| `/api/milestones/{id}` | GET/PATCH/DELETE | `kairo.milestone.read/manage` | Einzelner Meilenstein |
|
||||||
|
|
||||||
|
**Status Blocker:** `open`, `in_progress`, `resolved`, `accepted_risk`, `dismissed`
|
||||||
|
|
||||||
|
**Status Backlog:** `new`, `triaged`, `accepted`, `rejected`, `converted`
|
||||||
|
|
||||||
|
**Status Meilenstein:** `planned`, `active`, `at_risk`, `reached`, `moved`, `discarded`
|
||||||
|
|
||||||
|
Capabilities gesamt nach AP0.8: **25** (inkl. `kairo.attention.read` und Blocker/Backlog/Milestone read/manage).
|
||||||
|
|
||||||
|
Operating Model Extension II (AP0.9, Schema `008`):
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/initiatives/{id}/evidence` | GET/POST | `kairo.evidence.read/manage` | Evidence eines Vorhabens |
|
||||||
|
| `/api/evidence/{id}` | GET/PATCH/DELETE | `kairo.evidence.read/manage` | Einzelnes Evidence |
|
||||||
|
| `/api/initiatives/{id}/decisions` | GET/POST | `kairo.decision.read/manage` | Entscheidungen |
|
||||||
|
| `/api/decisions/{id}` | GET/PATCH/DELETE | `kairo.decision.read/manage` | Einzelne Entscheidung |
|
||||||
|
| `/api/initiatives/{id}/reviews` | GET/POST | `kairo.review.read/manage` | Reviews |
|
||||||
|
| `/api/reviews/{id}` | GET/PATCH/DELETE | `kairo.review.read/manage` | Einzelnes Review |
|
||||||
|
| `/api/initiatives/{id}/recurring` | GET/POST | `kairo.recurring.read/manage` | Recurring-Elemente |
|
||||||
|
| `/api/recurring/{id}` | GET/PATCH/DELETE | `kairo.recurring.read/manage` | Einzelnes Recurring-Element |
|
||||||
|
|
||||||
|
**Action-Status (erweitert):** `open`, `ready`, `in_progress`, `blocked`, `review_required`, `done`, `discarded` — optional `due_at`
|
||||||
|
|
||||||
|
**Attention-Regeln 7–9:** `overdue_action`, `review_due`, `recurring_due`
|
||||||
|
|
||||||
|
Capabilities gesamt nach AP0.9: **33**.
|
||||||
|
|
||||||
|
Operating Model Integration (AP0.10, Schema weiter `008`):
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/initiatives/{id}/steering-snapshot` | GET | `kairo.initiative.read` | Verknüpfter Graph + Lifecycle + Operating Phase (deprecated) |
|
||||||
|
| `/api/initiatives/{id}/steering-context` | GET | `kairo.initiative.read` | SteeringContext (Lifecycle, Methode) |
|
||||||
|
|
||||||
|
**Steering Core (AP1.0, Schema `009`):** `backend/steering/` — Standard Lifecycle, Hook/Method Registry, Signal Engine. Scope Lock: siehe `docs/architecture/ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`.
|
||||||
|
|
||||||
|
Version nach AP1.0: **`0.11.0-ap1.0`**
|
||||||
|
|
||||||
|
**AP1.1 — Method Registry:**
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/steering/methods` | GET | `kairo.initiative.read` | Built-in Steuerungsmethoden |
|
||||||
|
| `/api/steering/initiatives/{id}/context` | PATCH | `kairo.initiative.manage` | Methode pro Vorhaben setzen |
|
||||||
|
|
||||||
|
Version nach AP1.1: **`0.11.1-ap1.1`**
|
||||||
|
|
||||||
|
**Operating-Transitions:** Blocker gelöst → Maßnahme entblocken; Review abgeschlossen → Maßnahme `review_required` → `done`
|
||||||
|
|
||||||
|
**Attention Regel 10:** `action_review_required` — Maßnahme ohne geplantes Review
|
||||||
|
|
||||||
|
Version nach AP0.10: **`0.10.0-ap0.10`**. Brücke zum Steering Core: `docs/architecture/Kairo_Operating_Model_Steering_Bridge_v0.1.md`
|
||||||
|
|
||||||
|
Operating Model Integration UI (AP0.10b, Schema weiter `008`):
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/workspace/actions/today` | GET | `kairo.workspace.read` | Meine Maßnahmen heute (überfällig zuerst) |
|
||||||
|
|
||||||
|
**Workspace-Widgets:** Nächste sinnvolle Schritte, Heute, Aufmerksamkeit (erweitert)
|
||||||
|
|
||||||
|
**Steuerungszustand v2:** Meilenstein-Horizont, Next Actions pro Vorhaben, Phase-Klartext
|
||||||
|
|
||||||
|
Version nach AP0.10b: **`0.10.1-ap0.10b`**
|
||||||
|
|
||||||
|
Operating Model Integration UI (AP0.10b, Schema weiter `008`):
|
||||||
|
|
||||||
|
Tenant-Invarianten: `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||||
|
`docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||||
|
|
||||||
|
**Status Vorhaben:** `active`, `paused`, `completed`, `archived`
|
||||||
|
|
||||||
|
**Status Maßnahme:** `open`, `in_progress`, `blocked`, `done`, `discarded`
|
||||||
|
|
||||||
|
**Priorität:** `low`, `normal`, `high`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Vorhaben anlegen
|
||||||
|
curl -s -X POST http://localhost:8097/api/initiatives \
|
||||||
|
-H "X-Auth-Token: TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d '{"title":"Erstes Vorhaben","goal":"MVP validieren","priority":"high"}'
|
||||||
|
|
||||||
|
# Maßnahme mit Zuweisung
|
||||||
|
curl -s -X POST http://localhost:8097/api/initiatives/INITIATIVE_ID/actions \
|
||||||
|
-H "X-Auth-Token: TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d '{"title":"API testen","assigned_actor_ids":["ACTOR_ID"]}'
|
||||||
|
|
||||||
|
# Meine offenen Maßnahmen
|
||||||
|
curl -s http://localhost:8097/api/actions/me/open -H "X-Auth-Token: TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Workspace UI (AP0.6 / AP0.6b)
|
||||||
|
|
||||||
|
Nach Login leitet Kairo auf den **Workspace** weiter.
|
||||||
|
|
||||||
|
| Route | Beschreibung |
|
||||||
|
|-------|--------------|
|
||||||
|
| `/workspace` | Karten: Kontext, Überblick, **Aufmerksamkeit**, offene/blockierte Maßnahmen, aktive Vorhaben |
|
||||||
|
| `/initiatives` | Vorhabenliste mit offenen Maßnahmen-Zähler |
|
||||||
|
| `/initiatives/:id` | Vorhaben-Detail: Maßnahmen, **Meilensteine**, **Backlog**, **Blocker** |
|
||||||
|
| `/my-actions` | Alle offenen Maßnahmen des aktuellen Actors |
|
||||||
|
|
||||||
|
**App Shell (AP0.6b):** Desktop-Sidebar (≥1024px), Mobile-Header + Bottom-Navigation (<1024px), Tenant-/Actor-Kontext, Jinkendo-Family-Design-Tokens (`--jk-*`).
|
||||||
|
|
||||||
|
**Frontend-Struktur:** `frontend/src/api/`, `registry/`, `widgets/`, `pages/`, `components/`, `styles/`, `config/appNav.js`
|
||||||
|
|
||||||
|
**Widget Registry (frontend-only):** Widgets in `registry/widgetRegistry.js` — Capability-Filter, keine Backend-Persistenz.
|
||||||
|
|
||||||
|
**PWA:** `frontend/public/manifest.webmanifest`, Icon unter `public/icons/`. Kein Service Worker (bewusst — Installierbarkeit über Manifest; kein Offline-Caching in Sprint 0).
|
||||||
|
|
||||||
|
**Tests (Frontend):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm install && npm run test && npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
**Manueller Smoke-Test (Desktop + Mobile):**
|
||||||
|
|
||||||
|
1. Login → Workspace lädt mit Karten
|
||||||
|
2. Navigation: Workspace / Vorhaben / Meine Maßnahmen
|
||||||
|
3. Vorhaben anlegen → Detail → Maßnahme anlegen → Status *Erledigt*
|
||||||
|
4. Prüfen: Maßnahme verschwindet aus „Meine offenen Maßnahmen“
|
||||||
|
5. Responsive: DevTools Viewports **1440px**, **1024px**, **390px** — keine horizontale Scrollbar, Bottom-Nav sichtbar unter 1024px
|
||||||
|
6. PWA: Manifest unter `/manifest.webmanifest` erreichbar; „App installieren“ im Browser prüfbar
|
||||||
|
7. AP0.7: ActorSelect lädt `/api/actors`; Maßnahme einem Agent zuweisen; Workspace-Überblick sichtbar
|
||||||
|
8. AP0.8: Attention-Widget auf Workspace; Vorhaben-Detail mit Blocker/Backlog/Meilenstein; Backlog → Maßnahme konvertieren
|
||||||
|
|
||||||
|
Abschlussberichte: `docs/sprints/Sprint0_AP0_6_Completion_Report_v0.1.md`, `docs/sprints/Sprint0_AP0_6b_Completion_Report_v0.2.md`, `docs/sprints/Sprint0_AP0_7_Completion_Report_v0.2.md`, `docs/sprints/Sprint0_AP0_8_Completion_Report_v0.1.md`
|
||||||
|
|
||||||
|
### Registries (AP0.4)
|
||||||
|
|
||||||
|
Feature-, Prompt-, Placeholder- und Config-Registry analog zur Rights Registry: Code-Registrierung → Startup-Sync → DB.
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/features` | GET | `kairo.feature.registry.read` | Feature-Katalog |
|
||||||
|
| `/api/prompts` | GET | `kairo.prompt.registry.read` | Prompt-Definitionen |
|
||||||
|
| `/api/prompts/{key}` | GET | `kairo.prompt.registry.read` | Definition + aktive Version |
|
||||||
|
| `/api/prompts/{key}/render` | POST | `kairo.prompt.render` | Single-Mode Rendering (ohne LLM) |
|
||||||
|
| `/api/config` | GET | `kairo.config.registry.read` | Konfiguration (global/tenant) |
|
||||||
|
| `/api/config` | POST | `kairo.config.registry.manage` | Konfiguration setzen |
|
||||||
|
|
||||||
|
Startup: `sync_prompt_feature_config.py` nach Rights-Sync (`SKIP_REGISTRY_SYNC=1` zum Überspringen).
|
||||||
|
|
||||||
|
Abschlussbericht: `docs/sprints/Sprint0_AP0_4_Completion_Report_v0.2.md`
|
||||||
|
|
||||||
|
**Prompt-Modell:** `PromptDefinition` → `PromptVersion` → optional `PromptStep` (workflow-/pipeline-fähig; AP0.4 führt nur `execution_mode=single` aus).
|
||||||
|
|
||||||
|
**Beispiel-Prompts:** `kairo.system.health_summary`, `kairo.context.debug_summary`
|
||||||
|
|
||||||
|
**Features im Entitlements-Snapshot:** `kairo.prompt.registry`, `kairo.config.registry`, `kairo.feature.registry`
|
||||||
|
|
||||||
|
| Capability | Modul | Kurzbeschreibung |
|
||||||
|
|------------|-------|------------------|
|
||||||
|
| `kairo.feature.registry.read` | feature | Feature-Katalog lesen |
|
||||||
|
| `kairo.feature.registry.manage` | feature | Feature-Metadaten verwalten |
|
||||||
|
| `kairo.prompt.registry.read` | prompt | Prompt Registry lesen |
|
||||||
|
| `kairo.prompt.registry.manage` | prompt | Prompt Registry verwalten |
|
||||||
|
| `kairo.config.registry.read` | config | Config lesen |
|
||||||
|
| `kairo.config.registry.manage` | config | Config schreiben |
|
||||||
|
| `kairo.prompt.render` | prompt | Prompt rendern (Test/Preview) |
|
||||||
|
|
||||||
|
Zusätzlich AP0.3-Capabilities (siehe oben).
|
||||||
|
|
||||||
|
Enforcement: `CAPABILITY_ENFORCE=probe` (Default) oder `enforce`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||||
|
curl -s -X POST http://localhost:8097/api/prompts/kairo.system.health_summary/render \
|
||||||
|
-H "X-Auth-Token: TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d '{"values":{"debug_message":"OK","debug_level":"info"},"use_context":false}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Capabilities (AP0.3)
|
||||||
|
|
||||||
|
Registry-first: Capabilities werden in `backend/rights_registrations/` registriert und beim Start via `sync_rights_registry.py` in die DB synchronisiert.
|
||||||
|
|
||||||
|
| Capability | Modul | Kurzbeschreibung |
|
||||||
|
|------------|-------|------------------|
|
||||||
|
| `kairo.admin.access` | platform | Portal-Administration |
|
||||||
|
| `kairo.tenant.manage` | tenant | Tenant-Verwaltung |
|
||||||
|
| `kairo.actor.read` | tenant | Actors im Tenant lesen (Directory) |
|
||||||
|
| `kairo.actor.manage` | tenant | Actors verwalten |
|
||||||
|
| `kairo.workspace.read` | workspace | Workspace Read-Models / Data Layer |
|
||||||
|
| `kairo.initiative.read` | initiative | Vorhaben lesen |
|
||||||
|
| `kairo.initiative.manage` | initiative | Vorhaben verwalten |
|
||||||
|
| `kairo.action.read` | action | Maßnahmen lesen |
|
||||||
|
| `kairo.action.manage` | action | Maßnahmen verwalten / zuweisen |
|
||||||
|
| `kairo.context.read` | platform | TenantContext lesen |
|
||||||
|
| `kairo.entitlements.read` | platform | Entitlements lesen |
|
||||||
|
|
||||||
|
Enforcement: `CAPABILITY_ENFORCE=probe` (Default, loggt Verweigerungen) oder `enforce` (HTTP 403).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Login
|
||||||
|
curl -s -X POST http://localhost:8097/api/auth/login \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"email":"admin@kairo.local","password":"…"}'
|
||||||
|
|
||||||
|
# Geschützter Endpoint
|
||||||
|
curl -s http://localhost:8097/api/me -H "X-Auth-Token: TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
Regeln: `user_id` kommt aus der Session, nicht aus Client-Headern. Portalrolle (`portal_role`) und Tenantrolle (`tenant_role`) sind getrennt.
|
||||||
|
|
||||||
|
## AP0.1 – Stand Projektgrundlage
|
||||||
|
|
||||||
|
| Bereich | Status |
|
||||||
|
|---------|--------|
|
||||||
|
| Git + Gitea (`develop` / `main`) | erledigt |
|
||||||
|
| Docker Compose (Prod + Dev) | erledigt |
|
||||||
|
| Backend (FastAPI, Migrationen, `/api/health`) | erledigt |
|
||||||
|
| Frontend minimal (React + nginx Proxy) | erledigt |
|
||||||
|
| pytest (Health + Migrationen + Auth/Tenant/Actor) | erledigt (AP0.2) |
|
||||||
|
| Gitea Actions (Deploy + Test) | erledigt |
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y postgresql-client \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
ENV PIP_DEFAULT_TIMEOUT=120
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN chmod +x /app/entrypoint.sh
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||||
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
# Backend
|
|
||||||
|
|
||||||
FastAPI-Anwendung — noch anzulegen.
|
|
||||||
|
|
||||||
Erwartete Struktur (analog shinkan-jinkendo):
|
|
||||||
|
|
||||||
```
|
|
||||||
backend/
|
|
||||||
├── Dockerfile
|
|
||||||
├── main.py
|
|
||||||
├── requirements.txt
|
|
||||||
├── migrations/
|
|
||||||
└── routers/
|
|
||||||
```
|
|
||||||
+243
@@ -0,0 +1,243 @@
|
|||||||
|
"""Authentication: bcrypt passwords, server-side sessions, FastAPI dependencies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import bcrypt
|
||||||
|
from fastapi import Depends, Header, HTTPException
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
AUTH_HEADER = "X-Auth-Token"
|
||||||
|
SESSION_DAYS = int(os.getenv("SESSION_DAYS", "30"))
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, stored_hash: str) -> bool:
|
||||||
|
if not stored_hash:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def make_token() -> str:
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
|
||||||
|
def _session_expiry() -> datetime:
|
||||||
|
return datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_by_email(email: str) -> Optional[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, email, password_hash, display_name, portal_role, is_active
|
||||||
|
FROM users
|
||||||
|
WHERE LOWER(email) = LOWER(%s)
|
||||||
|
""",
|
||||||
|
(email.strip(),),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_by_id(user_id: str) -> Optional[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, email, display_name, portal_role, is_active, created_at
|
||||||
|
FROM users
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_session(token: str) -> Optional[dict[str, Any]]:
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
s.id AS session_id,
|
||||||
|
s.token,
|
||||||
|
s.user_id,
|
||||||
|
s.active_tenant_id,
|
||||||
|
s.expires_at,
|
||||||
|
u.email,
|
||||||
|
u.display_name,
|
||||||
|
u.portal_role,
|
||||||
|
u.is_active AS user_is_active
|
||||||
|
FROM sessions s
|
||||||
|
JOIN users u ON u.id = s.user_id
|
||||||
|
WHERE s.token = %s AND s.expires_at > NOW()
|
||||||
|
""",
|
||||||
|
(token,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
session = dict(row)
|
||||||
|
if not session.get("user_is_active"):
|
||||||
|
return None
|
||||||
|
return session
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _default_active_tenant(user_id: str) -> Optional[str]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT tm.tenant_id
|
||||||
|
FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = %s
|
||||||
|
AND tm.is_active = TRUE
|
||||||
|
AND t.is_active = TRUE
|
||||||
|
ORDER BY tm.created_at ASC
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return str(row[0]) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(user_id: str, active_tenant_id: Optional[str] = None) -> dict[str, Any]:
|
||||||
|
token = make_token()
|
||||||
|
tenant_id = active_tenant_id or _default_active_tenant(user_id)
|
||||||
|
expires_at = _session_expiry()
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (token, user_id, active_tenant_id, expires_at)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING token, expires_at, active_tenant_id
|
||||||
|
""",
|
||||||
|
(token, user_id, tenant_id, expires_at),
|
||||||
|
)
|
||||||
|
row = dict(cur.fetchone())
|
||||||
|
conn.commit()
|
||||||
|
row["user_id"] = user_id
|
||||||
|
return row
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_session(token: str) -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def set_session_active_tenant(token: str, tenant_id: str) -> bool:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE sessions s
|
||||||
|
SET active_tenant_id = %s
|
||||||
|
FROM users u
|
||||||
|
WHERE s.token = %s
|
||||||
|
AND s.user_id = u.id
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = s.user_id
|
||||||
|
AND tm.tenant_id = %s
|
||||||
|
AND tm.is_active = TRUE
|
||||||
|
AND t.is_active = TRUE
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(tenant_id, token, tenant_id),
|
||||||
|
)
|
||||||
|
updated = cur.rowcount > 0
|
||||||
|
conn.commit()
|
||||||
|
return updated
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def login(email: str, password: str) -> dict[str, Any]:
|
||||||
|
user = get_user_by_email(email)
|
||||||
|
if not user or not user.get("is_active"):
|
||||||
|
log_audit("auth.login_failed", details={"email": email.strip().lower()})
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||||
|
|
||||||
|
if not verify_password(password, user["password_hash"]):
|
||||||
|
log_audit("auth.login_failed", user_id=str(user["id"]), details={"email": user["email"]})
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||||
|
|
||||||
|
session = create_session(str(user["id"]))
|
||||||
|
log_audit("auth.login", user_id=str(user["id"]), details={"email": user["email"]})
|
||||||
|
return {
|
||||||
|
"token": session["token"],
|
||||||
|
"expires_at": session["expires_at"].isoformat(),
|
||||||
|
"user": {
|
||||||
|
"id": str(user["id"]),
|
||||||
|
"email": user["email"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"portal_role": user["portal_role"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def logout(token: str) -> None:
|
||||||
|
session = get_session(token)
|
||||||
|
if session:
|
||||||
|
log_audit(
|
||||||
|
"auth.logout",
|
||||||
|
user_id=str(session["user_id"]),
|
||||||
|
tenant_id=str(session["active_tenant_id"]) if session.get("active_tenant_id") else None,
|
||||||
|
)
|
||||||
|
delete_session(token)
|
||||||
|
|
||||||
|
|
||||||
|
def require_auth(x_auth_token: Optional[str] = Header(default=None, alias=AUTH_HEADER)) -> dict[str, Any]:
|
||||||
|
session = get_session(x_auth_token or "")
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(status_code=401, detail="Nicht eingeloggt")
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def require_portal_admin(session: dict[str, Any] = Depends(require_auth)) -> dict[str, Any]:
|
||||||
|
if session.get("portal_role") != "admin":
|
||||||
|
raise HTTPException(status_code=403, detail="Nur für Portal-Admins")
|
||||||
|
return session
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Bootstrap first admin user from environment (optional alternative to UI registration)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from services.registration import provision_system_admin, user_count
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str) -> str:
|
||||||
|
return os.getenv(name, "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_admin_if_needed() -> None:
|
||||||
|
if _env("SKIP_BOOTSTRAP").lower() in ("1", "true", "yes"):
|
||||||
|
return
|
||||||
|
|
||||||
|
email = _env("KAIRO_BOOTSTRAP_ADMIN_EMAIL")
|
||||||
|
password = _env("KAIRO_BOOTSTRAP_ADMIN_PASSWORD")
|
||||||
|
if not email or not password:
|
||||||
|
return
|
||||||
|
|
||||||
|
if user_count() > 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
tenant_slug = _env("KAIRO_BOOTSTRAP_TENANT_SLUG") or "default"
|
||||||
|
tenant_name = _env("KAIRO_BOOTSTRAP_TENANT_NAME") or "Default Tenant"
|
||||||
|
display_name = _env("KAIRO_BOOTSTRAP_ADMIN_NAME") or "Kairo Admin"
|
||||||
|
|
||||||
|
provision_system_admin(
|
||||||
|
email=email,
|
||||||
|
password=password,
|
||||||
|
display_name=display_name,
|
||||||
|
tenant_slug=tenant_slug,
|
||||||
|
tenant_name=tenant_name,
|
||||||
|
source="env_bootstrap",
|
||||||
|
)
|
||||||
|
print(f"[bootstrap] Systemadmin und Tenant '{tenant_slug}' angelegt")
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Central capability resolution and FastAPI enforcement dependencies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException
|
||||||
|
|
||||||
|
from rights_registry import load_grants_for_roles
|
||||||
|
from services.audit import log_audit
|
||||||
|
from tenant_context import TenantContext, get_tenant_context, require_tenant_context
|
||||||
|
|
||||||
|
CAPABILITY_ENFORCE_ENV = "CAPABILITY_ENFORCE"
|
||||||
|
|
||||||
|
|
||||||
|
def capability_enforcement_mode() -> str:
|
||||||
|
raw = os.getenv(CAPABILITY_ENFORCE_ENV, "probe").strip().lower()
|
||||||
|
return "enforce" if raw in ("1", "true", "enforce", "yes") else "probe"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_capabilities(*, portal_role: str, tenant_role: str | None) -> frozenset[str]:
|
||||||
|
return frozenset(load_grants_for_roles(portal_role=portal_role, tenant_role=tenant_role))
|
||||||
|
|
||||||
|
|
||||||
|
def has_capability(ctx: TenantContext, capability_key: str) -> bool:
|
||||||
|
return capability_key in ctx.capabilities
|
||||||
|
|
||||||
|
|
||||||
|
def check_capability(ctx: TenantContext, capability_key: str) -> dict[str, Any]:
|
||||||
|
allowed = has_capability(ctx, capability_key)
|
||||||
|
return {
|
||||||
|
"capability_key": capability_key,
|
||||||
|
"allowed": allowed,
|
||||||
|
"reason": None if allowed else "missing_grant",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def require_capability(capability_key: str) -> Callable[..., TenantContext]:
|
||||||
|
"""FastAPI dependency — blocks in enforce mode, probes in probe mode."""
|
||||||
|
|
||||||
|
def _dependency(ctx: TenantContext = Depends(require_tenant_context)) -> TenantContext:
|
||||||
|
return _enforce_capability(ctx, capability_key)
|
||||||
|
|
||||||
|
return _dependency
|
||||||
|
|
||||||
|
|
||||||
|
def require_capability_ctx(capability_key: str) -> Callable[..., TenantContext]:
|
||||||
|
"""Like require_capability but allows portal context without active tenant."""
|
||||||
|
|
||||||
|
def _dependency(ctx: TenantContext = Depends(get_tenant_context)) -> TenantContext:
|
||||||
|
return _enforce_capability(ctx, capability_key)
|
||||||
|
|
||||||
|
return _dependency
|
||||||
|
|
||||||
|
|
||||||
|
def _enforce_capability(ctx: TenantContext, capability_key: str) -> TenantContext:
|
||||||
|
result = check_capability(ctx, capability_key)
|
||||||
|
if result["allowed"]:
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
"capability.denied",
|
||||||
|
user_id=ctx.user_id,
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
details={
|
||||||
|
"capability_key": capability_key,
|
||||||
|
"mode": capability_enforcement_mode(),
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"tenant_role": ctx.tenant_role,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if capability_enforcement_mode() == "enforce":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=f"Capability fehlt: {capability_key}",
|
||||||
|
)
|
||||||
|
return ctx
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
"""Central configuration service — no plaintext secrets."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
SECRET_VALUE_FORBIDDEN = (
|
||||||
|
"Configuration entries with is_secret=true must not store plaintext values; "
|
||||||
|
"use environment or secret management."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_secret_entry(*, is_secret: bool, value: Any) -> None:
|
||||||
|
if not is_secret:
|
||||||
|
return
|
||||||
|
if value not in (None, {}, "", {"ref": "env"}):
|
||||||
|
raise ValueError(SECRET_VALUE_FORBIDDEN)
|
||||||
|
|
||||||
|
|
||||||
|
def get_config(
|
||||||
|
config_key: str,
|
||||||
|
*,
|
||||||
|
scope: str = "global",
|
||||||
|
tenant_id: str | None = None,
|
||||||
|
) -> dict | None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE config_key = %s AND scope = %s
|
||||||
|
AND (
|
||||||
|
(scope = 'global' AND tenant_id IS NULL)
|
||||||
|
OR (scope = 'tenant' AND tenant_id = %s::uuid)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(config_key, scope, tenant_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"config_key": row[0],
|
||||||
|
"scope": row[1],
|
||||||
|
"tenant_id": str(row[2]) if row[2] else None,
|
||||||
|
"value": row[3],
|
||||||
|
"value_type": row[4],
|
||||||
|
"description": row[5],
|
||||||
|
"is_secret": row[6],
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_configs(*, scope: str | None = None, tenant_id: str | None = None) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
if scope == "global":
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE scope = 'global' AND tenant_id IS NULL
|
||||||
|
ORDER BY config_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
elif scope == "tenant" and tenant_id:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE scope = 'tenant' AND tenant_id = %s::uuid
|
||||||
|
ORDER BY config_key
|
||||||
|
""",
|
||||||
|
(tenant_id,),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
ORDER BY scope, config_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
rows = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
item = {
|
||||||
|
"config_key": row[0],
|
||||||
|
"scope": row[1],
|
||||||
|
"tenant_id": str(row[2]) if row[2] else None,
|
||||||
|
"value_type": row[4],
|
||||||
|
"description": row[5],
|
||||||
|
"is_secret": row[6],
|
||||||
|
}
|
||||||
|
if row[6]:
|
||||||
|
item["value"] = {"ref": "env"}
|
||||||
|
else:
|
||||||
|
item["value"] = row[3]
|
||||||
|
rows.append(item)
|
||||||
|
return rows
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_config(
|
||||||
|
*,
|
||||||
|
config_key: str,
|
||||||
|
scope: str,
|
||||||
|
value: Any,
|
||||||
|
value_type: str = "string",
|
||||||
|
description: str = "",
|
||||||
|
is_secret: bool = False,
|
||||||
|
tenant_id: str | None = None,
|
||||||
|
user_id: str | None = None,
|
||||||
|
) -> dict:
|
||||||
|
_validate_secret_entry(is_secret=is_secret, value=value)
|
||||||
|
if scope == "tenant" and not tenant_id:
|
||||||
|
raise ValueError("tenant_id required for tenant-scoped config")
|
||||||
|
if scope == "global":
|
||||||
|
tenant_id = None
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
if scope == "global":
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO configuration_entries (
|
||||||
|
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
)
|
||||||
|
VALUES (%s, 'global', NULL, %s::jsonb, %s, %s, %s)
|
||||||
|
ON CONFLICT (config_key) WHERE scope = 'global' DO UPDATE SET
|
||||||
|
value = EXCLUDED.value,
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_secret = EXCLUDED.is_secret,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
config_key,
|
||||||
|
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||||
|
value_type,
|
||||||
|
description,
|
||||||
|
is_secret,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO configuration_entries (
|
||||||
|
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
)
|
||||||
|
VALUES (%s, 'tenant', %s::uuid, %s::jsonb, %s, %s, %s)
|
||||||
|
ON CONFLICT (config_key, tenant_id) WHERE scope = 'tenant' DO UPDATE SET
|
||||||
|
value = EXCLUDED.value,
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_secret = EXCLUDED.is_secret,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
config_key,
|
||||||
|
tenant_id,
|
||||||
|
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||||
|
value_type,
|
||||||
|
description,
|
||||||
|
is_secret,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
"config.entry.changed",
|
||||||
|
user_id=user_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
details={"config_key": config_key, "scope": scope, "is_secret": is_secret},
|
||||||
|
)
|
||||||
|
result = get_config(config_key, scope=scope, tenant_id=tenant_id)
|
||||||
|
assert result is not None
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def sync_default_configs(defaults: list[dict]) -> int:
|
||||||
|
if not defaults:
|
||||||
|
return 0
|
||||||
|
for item in defaults:
|
||||||
|
existing = get_config(item["config_key"], scope=item.get("scope", "global"))
|
||||||
|
if existing:
|
||||||
|
continue
|
||||||
|
upsert_config(
|
||||||
|
config_key=item["config_key"],
|
||||||
|
scope=item.get("scope", "global"),
|
||||||
|
value=item["value"],
|
||||||
|
value_type=item.get("value_type", "string"),
|
||||||
|
description=item.get("description", ""),
|
||||||
|
is_secret=item.get("is_secret", False),
|
||||||
|
)
|
||||||
|
print(f"[config_service] Default configs ensured — {len(defaults)} item(s)")
|
||||||
|
return 0
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Kairo Data Layer — read-oriented aggregation for workspace and dashboards."""
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""Action read-models for workspace — tenant-scoped, actor-assignment based."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.actions import OPEN_ACTION_STATUSES, _attach_assignments, _serialize_row
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def _require_actor(ctx: TenantContext) -> str:
|
||||||
|
if not ctx.actor_id:
|
||||||
|
raise ValueError("Kein Actor im TenantContext")
|
||||||
|
return ctx.actor_id
|
||||||
|
|
||||||
|
|
||||||
|
def _list_assigned_actions(
|
||||||
|
*,
|
||||||
|
tenant_id: str,
|
||||||
|
actor_id: str,
|
||||||
|
statuses: list[str],
|
||||||
|
order_today: bool = False,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
order_clause = """
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN a.due_at IS NOT NULL AND a.due_at < NOW() THEN 0 ELSE 1 END,
|
||||||
|
CASE a.status WHEN 'blocked' THEN 0 WHEN 'review_required' THEN 1 ELSE 2 END,
|
||||||
|
CASE a.priority
|
||||||
|
WHEN 'high' THEN 0
|
||||||
|
WHEN 'normal' THEN 1
|
||||||
|
WHEN 'low' THEN 2
|
||||||
|
END,
|
||||||
|
a.due_at ASC NULLS LAST,
|
||||||
|
a.updated_at DESC
|
||||||
|
""" if order_today else """
|
||||||
|
ORDER BY
|
||||||
|
CASE a.priority
|
||||||
|
WHEN 'high' THEN 0
|
||||||
|
WHEN 'normal' THEN 1
|
||||||
|
WHEN 'low' THEN 2
|
||||||
|
END,
|
||||||
|
a.updated_at DESC
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT a.id, a.tenant_id, a.initiative_id, a.title, a.description,
|
||||||
|
a.status, a.priority, a.due_at, a.created_at, a.updated_at,
|
||||||
|
i.title AS initiative_title,
|
||||||
|
(a.due_at IS NOT NULL AND a.due_at < NOW()) AS is_overdue
|
||||||
|
FROM actions a
|
||||||
|
JOIN action_assignments aa
|
||||||
|
ON aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||||
|
JOIN initiatives i
|
||||||
|
ON i.id = a.initiative_id AND i.tenant_id = a.tenant_id
|
||||||
|
WHERE a.tenant_id = %s
|
||||||
|
AND aa.actor_id = %s
|
||||||
|
AND a.status = ANY(%s)
|
||||||
|
{order_clause}
|
||||||
|
""",
|
||||||
|
(tenant_id, actor_id, statuses),
|
||||||
|
)
|
||||||
|
actions = [_serialize_row(dict(row)) for row in cur.fetchall()]
|
||||||
|
for action in actions:
|
||||||
|
action["is_overdue"] = bool(action.pop("is_overdue", False))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return _attach_assignments(actions, tenant_id=tenant_id)
|
||||||
|
|
||||||
|
|
||||||
|
def get_my_open_actions(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||||
|
"""Open + in_progress actions assigned to current actor (excludes blocked)."""
|
||||||
|
actor_id = _require_actor(ctx)
|
||||||
|
return _list_assigned_actions(
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
actor_id=actor_id,
|
||||||
|
statuses=["open", "in_progress"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_my_blocked_actions(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||||
|
"""Blocked actions assigned to current actor."""
|
||||||
|
actor_id = _require_actor(ctx)
|
||||||
|
return _list_assigned_actions(
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
actor_id=actor_id,
|
||||||
|
statuses=["blocked"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_my_open_actions(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||||
|
"""All non-terminal open actions (open, in_progress, blocked) — legacy compat."""
|
||||||
|
actor_id = _require_actor(ctx)
|
||||||
|
return _list_assigned_actions(
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
actor_id=actor_id,
|
||||||
|
statuses=list(OPEN_ACTION_STATUSES),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_my_today_actions(ctx: TenantContext, *, limit: int = 15) -> list[dict[str, Any]]:
|
||||||
|
"""Maßnahmen für heute — überfällig zuerst, dann blockiert/review, dann Priorität."""
|
||||||
|
if limit < 1:
|
||||||
|
limit = 1
|
||||||
|
if limit > 50:
|
||||||
|
limit = 50
|
||||||
|
actor_id = _require_actor(ctx)
|
||||||
|
actions = _list_assigned_actions(
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
actor_id=actor_id,
|
||||||
|
statuses=["open", "ready", "in_progress", "blocked", "review_required"],
|
||||||
|
order_today=True,
|
||||||
|
)
|
||||||
|
return actions[:limit]
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""Actor workload read-models — tenant-scoped aggregation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def get_actor_workload(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||||
|
"""Open/blocked/in_progress action counts per active actor in tenant."""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
a.id AS actor_id,
|
||||||
|
a.name AS display_name,
|
||||||
|
a.actor_type,
|
||||||
|
COUNT(*) FILTER (WHERE act.status = 'open') AS open_actions,
|
||||||
|
COUNT(*) FILTER (WHERE act.status = 'blocked') AS blocked_actions,
|
||||||
|
COUNT(*) FILTER (WHERE act.status = 'in_progress') AS in_progress_actions
|
||||||
|
FROM actors a
|
||||||
|
LEFT JOIN action_assignments aa
|
||||||
|
ON aa.actor_id = a.id AND aa.tenant_id = a.tenant_id
|
||||||
|
LEFT JOIN actions act
|
||||||
|
ON act.id = aa.action_id
|
||||||
|
AND act.tenant_id = aa.tenant_id
|
||||||
|
AND act.status IN ('open', 'in_progress', 'blocked')
|
||||||
|
WHERE a.tenant_id = %s AND a.is_active = TRUE
|
||||||
|
GROUP BY a.id, a.name, a.actor_type
|
||||||
|
ORDER BY
|
||||||
|
CASE a.actor_type
|
||||||
|
WHEN 'human' THEN 0
|
||||||
|
WHEN 'working_group' THEN 1
|
||||||
|
WHEN 'agent' THEN 2
|
||||||
|
ELSE 3
|
||||||
|
END,
|
||||||
|
a.name
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id,),
|
||||||
|
)
|
||||||
|
result = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
result.append(
|
||||||
|
{
|
||||||
|
"actor_id": str(row["actor_id"]),
|
||||||
|
"display_name": row["display_name"],
|
||||||
|
"actor_type": row["actor_type"],
|
||||||
|
"open_actions": int(row["open_actions"] or 0),
|
||||||
|
"blocked_actions": int(row["blocked_actions"] or 0),
|
||||||
|
"in_progress_actions": int(row["in_progress_actions"] or 0),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Attention and NextAction — thin Data Layer wrapper (AP1.0)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from steering.signals.engine import evaluate
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def get_attention_items(ctx: TenantContext):
|
||||||
|
return evaluate(ctx, kind="attention")
|
||||||
|
|
||||||
|
|
||||||
|
def get_next_action_candidates(ctx: TenantContext, *, limit: int = 10):
|
||||||
|
return evaluate(ctx, kind="next_action", limit=limit)
|
||||||
|
|
||||||
|
|
||||||
|
def get_next_action_candidates_for_initiative(
|
||||||
|
ctx: TenantContext, *, initiative_id: str, limit: int = 5
|
||||||
|
):
|
||||||
|
return evaluate(
|
||||||
|
ctx,
|
||||||
|
kind="next_action",
|
||||||
|
limit=limit,
|
||||||
|
initiative_id=initiative_id,
|
||||||
|
)
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
"""Initiative steering snapshot — verknüpftes Read-Model (AP0.10a).
|
||||||
|
|
||||||
|
Baut aus flachen OM-Tabellen einen erklärbaren Graph für UI und spätere Steering Core.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from entity_archetypes.registry import archetype_label
|
||||||
|
from method_profiles.registry import get_method_profile
|
||||||
|
from steering.context import get_steering_context_dto
|
||||||
|
from steering.kernel import evaluate_steering
|
||||||
|
from steering.signals.snapshot_signals import derive_initiative_signals
|
||||||
|
from services.initiatives import get_initiative
|
||||||
|
from services.progression_graph import compute_progression_state
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
OPEN_BLOCKER = ("open", "in_progress")
|
||||||
|
OPEN_ACTION = ("open", "ready", "in_progress", "blocked", "review_required")
|
||||||
|
ACTIVE_INITIATIVE = ("active", "paused")
|
||||||
|
|
||||||
|
_REASON_LABELS = {
|
||||||
|
"open_action_priority": "Offenes Arbeitspaket",
|
||||||
|
"milestone_at_risk_or_active": "Plan-Element aktiv oder gefährdet",
|
||||||
|
"blocked_action": "Blockiertes Arbeitspaket",
|
||||||
|
"backlog_triage": "Eingang triagieren",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _steering_guidance(
|
||||||
|
*,
|
||||||
|
next_actions: list[dict[str, Any]],
|
||||||
|
signals: list[str],
|
||||||
|
method_key: str,
|
||||||
|
) -> str:
|
||||||
|
if next_actions:
|
||||||
|
item = next_actions[0]
|
||||||
|
title = item.get("title") or "Nächster Schritt"
|
||||||
|
hint = (
|
||||||
|
item.get("recommended_action")
|
||||||
|
or item.get("summary")
|
||||||
|
or _REASON_LABELS.get(item.get("reason_code", ""), "")
|
||||||
|
)
|
||||||
|
if hint:
|
||||||
|
return f"Als Nächstes: {title} — {hint}"
|
||||||
|
return f"Als Nächstes: {title}"
|
||||||
|
if signals:
|
||||||
|
return "Attention: Struktur oder Ist-Arbeit ergänzen, um Next Actions zu erzeugen."
|
||||||
|
return (
|
||||||
|
f"Methode {method_key}: Plan oder Eingang befüllen, dann committete Arbeit starten."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _attention_items(signals: list[str]) -> list[dict[str, str]]:
|
||||||
|
return [{"code": code, "label": code.replace("_", " ")} for code in signals]
|
||||||
|
|
||||||
|
|
||||||
|
def _sid(value: Any) -> Optional[str]:
|
||||||
|
return str(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(value: Any) -> Optional[str]:
|
||||||
|
return value.isoformat() if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def get_initiative_steering_snapshot(
|
||||||
|
ctx: TenantContext, *, initiative_id: str
|
||||||
|
) -> Optional[dict[str, Any]]:
|
||||||
|
"""Tenant-scoped Graph-Snapshot eines Vorhabens."""
|
||||||
|
initiative = get_initiative(tenant_id=ctx.tenant_id, initiative_id=initiative_id)
|
||||||
|
if not initiative:
|
||||||
|
return None
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, title, description, status, priority, due_at,
|
||||||
|
created_at, updated_at
|
||||||
|
FROM actions
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
actions_raw = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, action_id, title, status, created_at, updated_at
|
||||||
|
FROM blockers
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
blockers = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, action_id, milestone_id, title, status, created_at, updated_at
|
||||||
|
FROM evidence
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
evidence = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, action_id, milestone_id, title, status, due_at,
|
||||||
|
created_at, updated_at
|
||||||
|
FROM reviews
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
reviews = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, title, status, priority, converted_action_id, item_kind,
|
||||||
|
parent_backlog_id, created_at, updated_at
|
||||||
|
FROM backlog_items
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
backlog = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT ri.id, ri.title, ri.status, ri.target_date, ri.item_type,
|
||||||
|
ri.sequencing_mode, ri.sort_order, ri.created_at, ri.updated_at
|
||||||
|
FROM roadmap_items ri
|
||||||
|
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
|
||||||
|
WHERE ri.tenant_id = %s AND r.initiative_id = %s
|
||||||
|
ORDER BY ri.sort_order ASC, ri.updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
roadmap_items_raw = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, title, status, outcome, created_at, updated_at
|
||||||
|
FROM decisions
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
decisions = [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, title, status, next_due_at, created_at, updated_at
|
||||||
|
FROM recurring_elements
|
||||||
|
WHERE tenant_id = %s AND initiative_id = %s
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
recurring = [dict(r) for r in cur.fetchall()]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
blockers_by_action: dict[str, list[dict]] = {}
|
||||||
|
unlinked_blockers: list[dict] = []
|
||||||
|
for b in blockers:
|
||||||
|
item = {
|
||||||
|
"id": _sid(b["id"]),
|
||||||
|
"title": b["title"],
|
||||||
|
"status": b["status"],
|
||||||
|
"action_id": _sid(b.get("action_id")),
|
||||||
|
}
|
||||||
|
aid = item["action_id"]
|
||||||
|
if aid:
|
||||||
|
blockers_by_action.setdefault(aid, []).append(item)
|
||||||
|
else:
|
||||||
|
unlinked_blockers.append(item)
|
||||||
|
|
||||||
|
evidence_by_action: dict[str, list[dict]] = {}
|
||||||
|
unlinked_evidence: list[dict] = []
|
||||||
|
for e in evidence:
|
||||||
|
item = {
|
||||||
|
"id": _sid(e["id"]),
|
||||||
|
"title": e["title"],
|
||||||
|
"status": e["status"],
|
||||||
|
"action_id": _sid(e.get("action_id")),
|
||||||
|
"milestone_id": _sid(e.get("milestone_id")),
|
||||||
|
}
|
||||||
|
aid = item["action_id"]
|
||||||
|
if aid:
|
||||||
|
evidence_by_action.setdefault(aid, []).append(item)
|
||||||
|
else:
|
||||||
|
unlinked_evidence.append(item)
|
||||||
|
|
||||||
|
reviews_by_action: dict[str, list[dict]] = {}
|
||||||
|
reviews_by_milestone: dict[str, list[dict]] = {}
|
||||||
|
unlinked_reviews: list[dict] = []
|
||||||
|
planned_reviews_due = 0
|
||||||
|
for r in reviews:
|
||||||
|
item = {
|
||||||
|
"id": _sid(r["id"]),
|
||||||
|
"title": r["title"],
|
||||||
|
"status": r["status"],
|
||||||
|
"due_at": _iso(r.get("due_at")),
|
||||||
|
"action_id": _sid(r.get("action_id")),
|
||||||
|
"milestone_id": _sid(r.get("milestone_id")),
|
||||||
|
}
|
||||||
|
if r["status"] == "planned" and r.get("due_at"):
|
||||||
|
planned_reviews_due += 1
|
||||||
|
aid, mid = item["action_id"], item["milestone_id"]
|
||||||
|
if aid:
|
||||||
|
reviews_by_action.setdefault(aid, []).append(item)
|
||||||
|
elif mid:
|
||||||
|
reviews_by_milestone.setdefault(mid, []).append(item)
|
||||||
|
else:
|
||||||
|
unlinked_reviews.append(item)
|
||||||
|
|
||||||
|
actions: list[dict[str, Any]] = []
|
||||||
|
open_actions = blocked_actions = review_required_actions = 0
|
||||||
|
for a in actions_raw:
|
||||||
|
aid = _sid(a["id"])
|
||||||
|
status = a["status"]
|
||||||
|
if status in OPEN_ACTION:
|
||||||
|
open_actions += 1
|
||||||
|
if status == "blocked":
|
||||||
|
blocked_actions += 1
|
||||||
|
if status == "review_required":
|
||||||
|
review_required_actions += 1
|
||||||
|
action_blockers = blockers_by_action.get(aid, [])
|
||||||
|
open_blocker_count = sum(1 for b in action_blockers if b["status"] in OPEN_BLOCKER)
|
||||||
|
actions.append(
|
||||||
|
{
|
||||||
|
"id": aid,
|
||||||
|
"title": a["title"],
|
||||||
|
"status": status,
|
||||||
|
"priority": a["priority"],
|
||||||
|
"due_at": _iso(a.get("due_at")),
|
||||||
|
"blockers": action_blockers,
|
||||||
|
"evidence": evidence_by_action.get(aid, []),
|
||||||
|
"reviews": reviews_by_action.get(aid, []),
|
||||||
|
"open_blocker_count": open_blocker_count,
|
||||||
|
"has_open_blocker": open_blocker_count > 0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
roadmap_items: list[dict[str, Any]] = []
|
||||||
|
for m in roadmap_items_raw:
|
||||||
|
mid = _sid(m["id"])
|
||||||
|
roadmap_items.append(
|
||||||
|
{
|
||||||
|
"id": mid,
|
||||||
|
"title": m["title"],
|
||||||
|
"status": m["status"],
|
||||||
|
"item_type": m["item_type"],
|
||||||
|
"sequencing_mode": m["sequencing_mode"],
|
||||||
|
"sort_order": m.get("sort_order", 0),
|
||||||
|
"target_date": m["target_date"].isoformat() if m.get("target_date") else None,
|
||||||
|
"reviews": reviews_by_milestone.get(mid, []),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
open_blockers = sum(
|
||||||
|
1 for b in blockers if b["status"] in OPEN_BLOCKER
|
||||||
|
)
|
||||||
|
backlog_new = sum(1 for bi in backlog if bi["status"] in ("new", "triaged", "accepted"))
|
||||||
|
|
||||||
|
signals = derive_initiative_signals(
|
||||||
|
initiative_status=initiative["status"],
|
||||||
|
open_actions=open_actions,
|
||||||
|
blocked_actions=blocked_actions,
|
||||||
|
review_required_actions=review_required_actions,
|
||||||
|
open_blockers=open_blockers,
|
||||||
|
backlog_new=backlog_new,
|
||||||
|
planned_reviews_due=planned_reviews_due,
|
||||||
|
)
|
||||||
|
|
||||||
|
upcoming_milestones = sorted(
|
||||||
|
[
|
||||||
|
m
|
||||||
|
for m in roadmap_items
|
||||||
|
if m["status"] in ("planned", "active", "at_risk")
|
||||||
|
],
|
||||||
|
key=lambda m: (m["target_date"] is None, m["target_date"] or ""),
|
||||||
|
)[:5]
|
||||||
|
|
||||||
|
evaluation = evaluate_steering(ctx, initiative_id=initiative_id, next_work_limit=5)
|
||||||
|
next_actions = evaluation.next_work
|
||||||
|
kernel_attention = evaluation.attention
|
||||||
|
epic_rollup = evaluation.read_models.get("epic_rollup") or []
|
||||||
|
sprint_commit_proposals = evaluation.proposals.get("sprint_commit") or []
|
||||||
|
|
||||||
|
steering = get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||||
|
metadata = steering.get("lifecycle_metadata") or {}
|
||||||
|
if isinstance(metadata, str):
|
||||||
|
metadata = {}
|
||||||
|
method_profile_key = metadata.get("method_profile_key")
|
||||||
|
method_profile_label = None
|
||||||
|
if method_profile_key:
|
||||||
|
profile = get_method_profile(method_profile_key)
|
||||||
|
if profile:
|
||||||
|
method_profile_label = profile.get("label")
|
||||||
|
initiative_archetype = initiative.get("archetype_key") or "initiative.generic"
|
||||||
|
|
||||||
|
from services.work_cycle import get_active_work_cycle
|
||||||
|
|
||||||
|
active_work_cycle = get_active_work_cycle(
|
||||||
|
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"initiative_id": initiative_id,
|
||||||
|
"initiative_title": initiative["title"],
|
||||||
|
"initiative_status": initiative["status"],
|
||||||
|
"archetype_key": initiative_archetype,
|
||||||
|
"archetype_label": archetype_label(
|
||||||
|
entity_type="initiative", archetype_key=initiative_archetype
|
||||||
|
),
|
||||||
|
"method_profile_key": method_profile_key,
|
||||||
|
"method_profile_label": method_profile_label,
|
||||||
|
"lifecycle_state": steering["lifecycle_state"],
|
||||||
|
"lifecycle_label": steering["lifecycle_label"],
|
||||||
|
"method_key": steering["method_key"],
|
||||||
|
"method_label": steering.get("method_label"),
|
||||||
|
"method_version": steering["method_version"],
|
||||||
|
"steering_guidance": _steering_guidance(
|
||||||
|
next_actions=next_actions,
|
||||||
|
signals=signals,
|
||||||
|
method_key=steering["method_key"],
|
||||||
|
),
|
||||||
|
"attention_items": _attention_items(signals)
|
||||||
|
+ [
|
||||||
|
{
|
||||||
|
"code": item.get("reason_code") or item.get("kind", "attention"),
|
||||||
|
"label": item.get("summary") or item.get("title") or "Attention",
|
||||||
|
}
|
||||||
|
for item in kernel_attention[:5]
|
||||||
|
],
|
||||||
|
"signals": signals,
|
||||||
|
"steering_kernel": {
|
||||||
|
"horizon": evaluation.horizon.to_dict(),
|
||||||
|
"lifecycle": evaluation.lifecycle.to_dict(),
|
||||||
|
"primary_method_key": evaluation.binding.primary_method_key,
|
||||||
|
"composition_modifier": evaluation.binding.composition_modifier,
|
||||||
|
"data_source": evaluation.data_source,
|
||||||
|
"read_models": evaluation.read_models,
|
||||||
|
"proposals": evaluation.proposals,
|
||||||
|
"agent_slots": evaluation.agent_slots,
|
||||||
|
},
|
||||||
|
"upcoming_milestones": upcoming_milestones,
|
||||||
|
"upcoming_roadmap_items": upcoming_milestones,
|
||||||
|
"next_actions": next_actions,
|
||||||
|
"active_work_cycle": active_work_cycle,
|
||||||
|
"epic_rollup": epic_rollup,
|
||||||
|
"sprint_commit_proposals": sprint_commit_proposals,
|
||||||
|
"gate_next_actions_proposals": evaluation.proposals.get("gate_next_actions") or [],
|
||||||
|
"intake_triage_proposals": evaluation.proposals.get("intake_triage") or [],
|
||||||
|
"agent_slots": evaluation.agent_slots,
|
||||||
|
"tech_debt_summary": evaluation.read_models.get("tech_debt_summary") or {},
|
||||||
|
"counts": {
|
||||||
|
"actions_open": open_actions,
|
||||||
|
"actions_blocked": blocked_actions,
|
||||||
|
"actions_review_required": review_required_actions,
|
||||||
|
"blockers_open": open_blockers,
|
||||||
|
"backlog_open": backlog_new,
|
||||||
|
"decisions": len(decisions),
|
||||||
|
"reviews_planned_due": planned_reviews_due,
|
||||||
|
"recurring_active": sum(1 for r in recurring if r["status"] == "active"),
|
||||||
|
"unlinked_blockers": len(unlinked_blockers),
|
||||||
|
"unlinked_evidence": len(unlinked_evidence),
|
||||||
|
"unlinked_reviews": len(unlinked_reviews),
|
||||||
|
},
|
||||||
|
"actions": actions,
|
||||||
|
"roadmap_items": roadmap_items,
|
||||||
|
"milestones": roadmap_items,
|
||||||
|
"progression_state": compute_progression_state(
|
||||||
|
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||||
|
),
|
||||||
|
"initiative_level": {
|
||||||
|
"blockers": unlinked_blockers,
|
||||||
|
"evidence": unlinked_evidence,
|
||||||
|
"reviews": unlinked_reviews,
|
||||||
|
"decisions": [
|
||||||
|
{"id": _sid(d["id"]), "title": d["title"], "status": d["status"]}
|
||||||
|
for d in decisions
|
||||||
|
],
|
||||||
|
"backlog": [
|
||||||
|
{
|
||||||
|
"id": _sid(b["id"]),
|
||||||
|
"title": b["title"],
|
||||||
|
"status": b["status"],
|
||||||
|
"item_kind": b.get("item_kind"),
|
||||||
|
"parent_backlog_id": _sid(b.get("parent_backlog_id")),
|
||||||
|
"converted_action_id": _sid(b.get("converted_action_id")),
|
||||||
|
}
|
||||||
|
for b in backlog
|
||||||
|
],
|
||||||
|
"recurring": [
|
||||||
|
{
|
||||||
|
"id": _sid(r["id"]),
|
||||||
|
"title": r["title"],
|
||||||
|
"status": r["status"],
|
||||||
|
"next_due_at": _iso(r.get("next_due_at")),
|
||||||
|
}
|
||||||
|
for r in recurring
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"data_source": "initiative_steering_snapshot",
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Initiative read-models for workspace."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.initiatives import _serialize_row
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def get_active_initiatives(
|
||||||
|
ctx: TenantContext,
|
||||||
|
*,
|
||||||
|
limit: Optional[int] = None,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""Active and paused initiatives in the current tenant."""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
sql = """
|
||||||
|
SELECT id, tenant_id, title, goal, vision, target_state_summary, archetype_key,
|
||||||
|
status, priority, portfolio_rank, owner_actor_id, created_at, updated_at
|
||||||
|
FROM initiatives
|
||||||
|
WHERE tenant_id = %s AND status IN ('active', 'paused')
|
||||||
|
ORDER BY portfolio_rank ASC NULLS LAST, updated_at DESC, title
|
||||||
|
"""
|
||||||
|
params: list[Any] = [ctx.tenant_id]
|
||||||
|
if limit is not None:
|
||||||
|
sql += " LIMIT %s"
|
||||||
|
params.append(limit)
|
||||||
|
cur.execute(sql, params)
|
||||||
|
return [_serialize_row(dict(row)) for row in cur.fetchall()]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Portfolio steering read model — K-Ext-5."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from steering.portfolio.aggregate import aggregate_portfolio_steering
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def get_portfolio_steering(
|
||||||
|
ctx: TenantContext,
|
||||||
|
*,
|
||||||
|
max_initiatives: int = 50,
|
||||||
|
total_attention: int = 30,
|
||||||
|
total_next_work: int = 15,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return aggregate_portfolio_steering(
|
||||||
|
ctx,
|
||||||
|
max_initiatives=max_initiatives,
|
||||||
|
total_attention=total_attention,
|
||||||
|
total_next_work=total_next_work,
|
||||||
|
)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Workspace summary read-model — tenant-scoped KPIs for current actor."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def get_workspace_summary(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Summary for workspace dashboard.
|
||||||
|
|
||||||
|
Personal counts (current actor): open, blocked, recently done.
|
||||||
|
Tenant-wide: active initiatives count.
|
||||||
|
"""
|
||||||
|
if not ctx.actor_id:
|
||||||
|
return {
|
||||||
|
"open_actions_count": 0,
|
||||||
|
"blocked_actions_count": 0,
|
||||||
|
"active_initiatives_count": 0,
|
||||||
|
"done_actions_recent_count": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE a.status IN ('open', 'in_progress')
|
||||||
|
) AS open_actions_count,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE a.status = 'blocked'
|
||||||
|
) AS blocked_actions_count,
|
||||||
|
COUNT(*) FILTER (
|
||||||
|
WHERE a.status = 'done'
|
||||||
|
AND a.updated_at >= NOW() - INTERVAL '7 days'
|
||||||
|
) AS done_actions_recent_count
|
||||||
|
FROM actions a
|
||||||
|
JOIN action_assignments aa
|
||||||
|
ON aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||||
|
WHERE a.tenant_id = %s AND aa.actor_id = %s
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id, ctx.actor_id),
|
||||||
|
)
|
||||||
|
row = dict(cur.fetchone())
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS active_initiatives_count
|
||||||
|
FROM initiatives
|
||||||
|
WHERE tenant_id = %s AND status IN ('active', 'paused')
|
||||||
|
""",
|
||||||
|
(ctx.tenant_id,),
|
||||||
|
)
|
||||||
|
initiatives_row = dict(cur.fetchone())
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"open_actions_count": int(row["open_actions_count"] or 0),
|
||||||
|
"blocked_actions_count": int(row["blocked_actions_count"] or 0),
|
||||||
|
"active_initiatives_count": int(initiatives_row["active_initiatives_count"] or 0),
|
||||||
|
"done_actions_recent_count": int(row["done_actions_recent_count"] or 0),
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""PostgreSQL connection helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import psycopg2
|
||||||
|
from psycopg2.extensions import connection
|
||||||
|
|
||||||
|
|
||||||
|
def db_params() -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
"host": os.getenv("DB_HOST", "localhost"),
|
||||||
|
"port": os.getenv("DB_PORT", "5432"),
|
||||||
|
"dbname": os.getenv("DB_NAME", "kairo_dev"),
|
||||||
|
"user": os.getenv("DB_USER", "kairo_dev"),
|
||||||
|
"password": os.getenv("DB_PASSWORD", "dev_password"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_connection() -> connection:
|
||||||
|
p = db_params()
|
||||||
|
return psycopg2.connect(
|
||||||
|
host=p["host"],
|
||||||
|
port=p["port"],
|
||||||
|
database=p["dbname"],
|
||||||
|
user=p["user"],
|
||||||
|
password=p["password"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_retryable_db_error(exc: Exception) -> bool:
|
||||||
|
"""Nur temporäre Verbindungsprobleme erneut versuchen (nicht Auth/Config)."""
|
||||||
|
msg = str(exc).lower()
|
||||||
|
if "password authentication failed" in msg:
|
||||||
|
return False
|
||||||
|
if "does not exist" in msg and any(token in msg for token in ("role", "database")):
|
||||||
|
return False
|
||||||
|
if "no pg_hba.conf entry" in msg:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def connect_with_retry(max_retries: int = 30, sleep_seconds: float = 2.0) -> connection:
|
||||||
|
p = db_params()
|
||||||
|
last_exc: Exception | None = None
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
conn = get_connection()
|
||||||
|
conn.autocommit = False
|
||||||
|
print(f"[OK] Connected to database: {p['dbname']}")
|
||||||
|
return conn
|
||||||
|
except psycopg2.OperationalError as exc:
|
||||||
|
last_exc = exc
|
||||||
|
if not is_retryable_db_error(exc):
|
||||||
|
raise
|
||||||
|
if attempt >= max_retries - 1:
|
||||||
|
raise
|
||||||
|
print(f"Waiting for database... ({attempt + 1}/{max_retries})")
|
||||||
|
time.sleep(sleep_seconds)
|
||||||
|
if last_exc:
|
||||||
|
raise last_exc
|
||||||
|
raise RuntimeError("database connection failed")
|
||||||
|
|
||||||
|
|
||||||
|
def check_db() -> bool:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT 1")
|
||||||
|
cur.fetchone()
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Entitlements snapshot for GET /api/me/entitlements."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from capabilities import capability_enforcement_mode, check_capability
|
||||||
|
from feature_registry import load_active_features
|
||||||
|
from rights_registry import get_registered_capabilities
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def _capability_map(ctx: TenantContext) -> dict[str, dict[str, Any]]:
|
||||||
|
registered = {reg.key for reg in get_registered_capabilities()}
|
||||||
|
snapshot: dict[str, dict[str, Any]] = {}
|
||||||
|
for key in sorted(registered):
|
||||||
|
snapshot[key] = check_capability(ctx, key)
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
|
||||||
|
def _feature_snapshot() -> dict[str, dict[str, Any]]:
|
||||||
|
features = load_active_features()
|
||||||
|
return {
|
||||||
|
key: {
|
||||||
|
"enabled": meta["enabled"],
|
||||||
|
"module": meta["module"],
|
||||||
|
"name": meta["name"],
|
||||||
|
}
|
||||||
|
for key, meta in features.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_entitlements_snapshot(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
features = _feature_snapshot()
|
||||||
|
tenant_block = None
|
||||||
|
if ctx.tenant_id:
|
||||||
|
tenant_block = {
|
||||||
|
"tenant_id": ctx.tenant_id,
|
||||||
|
"slug": ctx.tenant_slug,
|
||||||
|
"name": ctx.tenant_name,
|
||||||
|
"role": ctx.tenant_role,
|
||||||
|
"capabilities": {
|
||||||
|
key: value
|
||||||
|
for key, value in _capability_map(ctx).items()
|
||||||
|
if key in ctx.capabilities
|
||||||
|
},
|
||||||
|
"features": features,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"account": {
|
||||||
|
"user_id": ctx.user_id,
|
||||||
|
"email": ctx.email,
|
||||||
|
"display_name": ctx.display_name,
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"capabilities": _capability_map(ctx),
|
||||||
|
"features": features,
|
||||||
|
},
|
||||||
|
"tenant": tenant_block,
|
||||||
|
"actor": (
|
||||||
|
{
|
||||||
|
"actor_id": ctx.actor_id,
|
||||||
|
"actor_type": ctx.actor_type,
|
||||||
|
}
|
||||||
|
if ctx.actor_id
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"roles": {
|
||||||
|
"portal": ctx.portal_role,
|
||||||
|
"tenant": ctx.tenant_role,
|
||||||
|
},
|
||||||
|
"capabilities": sorted(ctx.capabilities),
|
||||||
|
"features": features,
|
||||||
|
"enforcement": {
|
||||||
|
"capabilities": capability_enforcement_mode(),
|
||||||
|
"features": "probe",
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from entity_archetypes.registry import (
|
||||||
|
ENTITY_ARCHETYPES,
|
||||||
|
INITIATIVE_ARCHETYPES,
|
||||||
|
PROJECT_ARCHETYPES,
|
||||||
|
archetype_label,
|
||||||
|
list_archetypes,
|
||||||
|
mirror_project_archetype_key,
|
||||||
|
resolve_default_method_key,
|
||||||
|
validate_archetype_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ENTITY_ARCHETYPES",
|
||||||
|
"INITIATIVE_ARCHETYPES",
|
||||||
|
"PROJECT_ARCHETYPES",
|
||||||
|
"archetype_label",
|
||||||
|
"list_archetypes",
|
||||||
|
"mirror_project_archetype_key",
|
||||||
|
"resolve_default_method_key",
|
||||||
|
"validate_archetype_key",
|
||||||
|
]
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
"""System-Archetypen (AP1.10 + AP2.0) — Seeds, Bindings, Spiegel Project."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from entity_archetypes.ui_profiles import INITIATIVE_UI_PROFILES, resolve_ui_profile
|
||||||
|
|
||||||
|
# initiative suffix → default method (shared by initiative + project mirror)
|
||||||
|
_METHOD_BY_SUFFIX: dict[str, str] = {
|
||||||
|
"generic": "generic_operating",
|
||||||
|
"maturity_journey": "maturity_progression",
|
||||||
|
"linear_project": "sequential_dependency",
|
||||||
|
"recurring_program": "recurring_control",
|
||||||
|
"support_queue": "queue_pull",
|
||||||
|
"program": "program_delivery",
|
||||||
|
"product": "continuous_product",
|
||||||
|
"dispute_case": "dispute_procedure",
|
||||||
|
"content_project": "chapter_based_progression",
|
||||||
|
}
|
||||||
|
|
||||||
|
_INITIATIVE_SPEC_META: tuple[tuple[str, str, str], ...] = (
|
||||||
|
("generic", "Allgemeines Vorhaben", "Fallback ohne spezielle Steuerungsvorlage."),
|
||||||
|
(
|
||||||
|
"maturity_journey",
|
||||||
|
"Reifegrad-Entwicklung",
|
||||||
|
"Mehrstufige Entwicklung, Routinen, Graph-Voraussetzungen.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"linear_project",
|
||||||
|
"Lineares Vorhaben",
|
||||||
|
"Einmalprojekte mit Pfaden, Gates und Graph.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"recurring_program",
|
||||||
|
"Dauerprogramm / Rhythmus",
|
||||||
|
"Haushalt, Rhythmen, Abweichungs-Steuerung.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"support_queue",
|
||||||
|
"Inbox / Queue",
|
||||||
|
"Ad-hoc-Eingang, triage, thematische Zuordnung.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"program",
|
||||||
|
"Programm (begrenzt)",
|
||||||
|
"Phasen, Release-Programm mit Abschluss.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"product",
|
||||||
|
"Produkt (kontinuierlich)",
|
||||||
|
"Dauerbetrieb, Wartung, Issues, Weiterentwicklung.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"dispute_case",
|
||||||
|
"Verfahren / Konflikt",
|
||||||
|
"Reaktive Steuerung, Fristen, Entscheidungen.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"content_project",
|
||||||
|
"Inhalt / Kapitel",
|
||||||
|
"Bücher, Konzepte, Kapitelstruktur.",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_specs() -> tuple[dict[str, Any], ...]:
|
||||||
|
specs: list[dict[str, Any]] = []
|
||||||
|
for suffix, label, description in _INITIATIVE_SPEC_META:
|
||||||
|
method = _METHOD_BY_SUFFIX[suffix]
|
||||||
|
initiative_key = f"initiative.{suffix}"
|
||||||
|
ui_profile = INITIATIVE_UI_PROFILES.get(initiative_key, {})
|
||||||
|
specs.append(
|
||||||
|
{
|
||||||
|
"key": initiative_key,
|
||||||
|
"entity_type": "initiative",
|
||||||
|
"label": label,
|
||||||
|
"description": description,
|
||||||
|
"is_system": True,
|
||||||
|
"default_method_key": method,
|
||||||
|
"default_method_profile_key": None,
|
||||||
|
"ui_profile_json": ui_profile,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
specs.append(
|
||||||
|
{
|
||||||
|
"key": f"project.{suffix}",
|
||||||
|
"entity_type": "project",
|
||||||
|
"label": label,
|
||||||
|
"description": f"Project-Spiegel: {description}",
|
||||||
|
"is_system": True,
|
||||||
|
"default_method_key": method,
|
||||||
|
"default_method_profile_key": None,
|
||||||
|
"ui_profile_json": {},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return tuple(specs)
|
||||||
|
|
||||||
|
|
||||||
|
ENTITY_ARCHETYPES: tuple[dict[str, Any], ...] = _build_specs()
|
||||||
|
|
||||||
|
INITIATIVE_ARCHETYPES: tuple[dict[str, Any], ...] = tuple(
|
||||||
|
item for item in ENTITY_ARCHETYPES if item["entity_type"] == "initiative"
|
||||||
|
)
|
||||||
|
|
||||||
|
PROJECT_ARCHETYPES: tuple[dict[str, Any], ...] = tuple(
|
||||||
|
item for item in ENTITY_ARCHETYPES if item["entity_type"] == "project"
|
||||||
|
)
|
||||||
|
|
||||||
|
_ARCHETYPE_INDEX: dict[tuple[str, str], dict[str, Any]] = {
|
||||||
|
(item["entity_type"], item["key"]): item for item in ENTITY_ARCHETYPES
|
||||||
|
}
|
||||||
|
|
||||||
|
_KEY_INDEX: dict[str, dict[str, Any]] = {item["key"]: item for item in ENTITY_ARCHETYPES}
|
||||||
|
|
||||||
|
|
||||||
|
def _list_archetypes_from_memory(*, entity_type: Optional[str] = None) -> list[dict[str, Any]]:
|
||||||
|
items = ENTITY_ARCHETYPES
|
||||||
|
if entity_type is not None:
|
||||||
|
items = tuple(i for i in items if i["entity_type"] == entity_type)
|
||||||
|
return [_public_archetype(item) for item in items]
|
||||||
|
|
||||||
|
|
||||||
|
def _public_archetype(item: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"key": item["key"],
|
||||||
|
"entity_type": item["entity_type"],
|
||||||
|
"label": item["label"],
|
||||||
|
"description": item["description"],
|
||||||
|
"is_system": item["is_system"],
|
||||||
|
"default_method_key": item["default_method_key"],
|
||||||
|
"default_method_profile_key": item.get("default_method_profile_key"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _enrich_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
base = dict(row)
|
||||||
|
spec = _KEY_INDEX.get(base.get("key", ""))
|
||||||
|
if spec:
|
||||||
|
base.setdefault("default_method_key", spec["default_method_key"])
|
||||||
|
base.setdefault("default_method_profile_key", spec.get("default_method_profile_key"))
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def list_archetypes(*, entity_type: Optional[str] = None) -> list[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
if entity_type is None:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT archetype_key AS key, entity_type, label, description, is_system
|
||||||
|
FROM entity_archetypes
|
||||||
|
ORDER BY entity_type ASC, archetype_key ASC
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT archetype_key AS key, entity_type, label, description, is_system
|
||||||
|
FROM entity_archetypes
|
||||||
|
WHERE entity_type = %s
|
||||||
|
ORDER BY archetype_key ASC
|
||||||
|
""",
|
||||||
|
(entity_type,),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
if rows:
|
||||||
|
return [_enrich_row(dict(row)) for row in rows]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return _list_archetypes_from_memory(entity_type=entity_type)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_archetype_key(*, entity_type: str, archetype_key: str) -> None:
|
||||||
|
if (entity_type, archetype_key) not in _ARCHETYPE_INDEX:
|
||||||
|
raise ValueError(f"Unbekannter Archetyp: {archetype_key}")
|
||||||
|
|
||||||
|
|
||||||
|
def archetype_label(*, entity_type: str, archetype_key: str) -> Optional[str]:
|
||||||
|
item = _ARCHETYPE_INDEX.get((entity_type, archetype_key))
|
||||||
|
return item["label"] if item else None
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_default_method_key(archetype_key: str) -> str:
|
||||||
|
spec = _KEY_INDEX.get(archetype_key)
|
||||||
|
if not spec:
|
||||||
|
return "generic_operating"
|
||||||
|
return spec.get("default_method_key", "generic_operating")
|
||||||
|
|
||||||
|
|
||||||
|
def get_ui_profile_json(archetype_key: str) -> dict[str, Any]:
|
||||||
|
"""UI-Profil aus Registry-Seed (DB-Sync-Quelle)."""
|
||||||
|
spec = _KEY_INDEX.get(archetype_key)
|
||||||
|
if spec and spec.get("ui_profile_json"):
|
||||||
|
return dict(spec["ui_profile_json"])
|
||||||
|
return resolve_ui_profile(archetype_key)
|
||||||
|
|
||||||
|
|
||||||
|
def mirror_project_archetype_key(initiative_archetype_key: str) -> str:
|
||||||
|
if initiative_archetype_key.startswith("initiative."):
|
||||||
|
suffix = initiative_archetype_key[len("initiative.") :]
|
||||||
|
candidate = f"project.{suffix}"
|
||||||
|
if ( "project", candidate) in _ARCHETYPE_INDEX:
|
||||||
|
return candidate
|
||||||
|
return "project.generic"
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"""UI-Profile für Initiative-Archetypen — AP2.3a / AP2.3f."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
_PRODUCT_PROCESS = (
|
||||||
|
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
|
||||||
|
{"key": "sprint-plan", "to": "/plan/sprint", "label": "Sprint planen", "mode": "plan"},
|
||||||
|
{"key": "sprint-work", "to": "/work/sprint", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_LINEAR_PROCESS = (
|
||||||
|
{"key": "gates", "to": "/plan/gates", "label": "Zielzustände", "mode": "plan"},
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_MATURITY_PROCESS = (
|
||||||
|
{"key": "gates", "to": "/plan/gates", "label": "Stufen", "mode": "plan"},
|
||||||
|
{"key": "journey", "to": "/control/journey", "label": "Rhythmen", "mode": "control"},
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_PROGRAM_PROCESS = (
|
||||||
|
{"key": "gates", "to": "/plan/gates", "label": "Phasen", "mode": "plan"},
|
||||||
|
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_SUPPORT_QUEUE_PROCESS = (
|
||||||
|
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_CONTENT_PROCESS = (
|
||||||
|
{"key": "gates", "to": "/plan/gates", "label": "Kapitel", "mode": "plan"},
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_DISPUTE_PROCESS = (
|
||||||
|
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
|
||||||
|
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
|
||||||
|
)
|
||||||
|
|
||||||
|
_COMMON_OM_SLICES = (
|
||||||
|
"actions",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
)
|
||||||
|
|
||||||
|
GENERIC_UI_PROFILE: dict[str, Any] = {
|
||||||
|
"processSteps": [],
|
||||||
|
"planDefaultRoute": "/plan/profile",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": None,
|
||||||
|
"workNavKeys": None,
|
||||||
|
"dataSlices": [
|
||||||
|
"actions",
|
||||||
|
"backlog",
|
||||||
|
"roadmap",
|
||||||
|
"projects",
|
||||||
|
"blockers",
|
||||||
|
*_COMMON_OM_SLICES[1:],
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
}
|
||||||
|
|
||||||
|
INITIATIVE_UI_PROFILES: dict[str, dict[str, Any]] = {
|
||||||
|
"initiative.generic": dict(GENERIC_UI_PROFILE),
|
||||||
|
"initiative.product": {
|
||||||
|
"processSteps": list(_PRODUCT_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/inbox",
|
||||||
|
"workDefaultRoute": "/work/sprint",
|
||||||
|
"workDefaultRouteWithoutActiveWorkCycle": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "inbox", "work", "sprint", "gates"],
|
||||||
|
"workNavKeys": ["sprint", "today", "mine"],
|
||||||
|
"dataSlices": [
|
||||||
|
"backlog",
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"work_cycles",
|
||||||
|
"projects",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.linear_project": {
|
||||||
|
"processSteps": list(_LINEAR_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/gates",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "structure", "gates", "inbox", "work"],
|
||||||
|
"workNavKeys": ["today", "mine", "sprint"],
|
||||||
|
"dataSlices": [
|
||||||
|
"backlog",
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"projects",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.maturity_journey": {
|
||||||
|
"processSteps": list(_MATURITY_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/gates",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "gates", "work"],
|
||||||
|
"workNavKeys": ["today", "mine", "sprint"],
|
||||||
|
"dataSlices": [
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"recurring",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.program": {
|
||||||
|
"processSteps": list(_PROGRAM_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/gates",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "structure", "gates", "inbox", "sprint", "work"],
|
||||||
|
"workNavKeys": ["today", "mine", "sprint"],
|
||||||
|
"dataSlices": [
|
||||||
|
"backlog",
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"projects",
|
||||||
|
"work_cycles",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.support_queue": {
|
||||||
|
"processSteps": list(_SUPPORT_QUEUE_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/inbox",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "inbox", "work"],
|
||||||
|
"workNavKeys": ["today", "mine"],
|
||||||
|
"dataSlices": [
|
||||||
|
"backlog",
|
||||||
|
"actions",
|
||||||
|
"blockers",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.recurring_program": {
|
||||||
|
"processSteps": list(_MATURITY_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/gates",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
|
||||||
|
"workNavKeys": ["today", "mine"],
|
||||||
|
"dataSlices": [
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"recurring",
|
||||||
|
"blockers",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.content_project": {
|
||||||
|
"processSteps": list(_CONTENT_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/gates",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
|
||||||
|
"workNavKeys": ["today", "mine"],
|
||||||
|
"dataSlices": [
|
||||||
|
"actions",
|
||||||
|
"roadmap",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
"initiative.dispute_case": {
|
||||||
|
"processSteps": list(_DISPUTE_PROCESS),
|
||||||
|
"planDefaultRoute": "/plan/profile",
|
||||||
|
"workDefaultRoute": "/work/today",
|
||||||
|
"controlDefaultRoute": "/control/status",
|
||||||
|
"planOutlineKeys": ["profile", "work"],
|
||||||
|
"workNavKeys": ["today", "mine"],
|
||||||
|
"dataSlices": [
|
||||||
|
"actions",
|
||||||
|
"blockers",
|
||||||
|
"evidence",
|
||||||
|
"decisions",
|
||||||
|
"reviews",
|
||||||
|
"steering_methods",
|
||||||
|
],
|
||||||
|
"enabledModes": ["plan", "work", "control"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_ui_profile(archetype_key: str) -> dict[str, Any]:
|
||||||
|
"""UI-Profil aus Code-Seed; unbekannte Archetypen → Generic-Fallback."""
|
||||||
|
profile = INITIATIVE_UI_PROFILES.get(archetype_key)
|
||||||
|
resolved = dict(profile) if profile else dict(GENERIC_UI_PROFILE)
|
||||||
|
slices = resolved.get("dataSlices") or []
|
||||||
|
resolved["omCapabilities"] = list(resolved.get("omCapabilities") or slices)
|
||||||
|
resolved.pop("uiFeatures", None)
|
||||||
|
return resolved
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from entity_fields.definitions import FIELD_DEFINITIONS
|
||||||
|
from entity_fields.service import (
|
||||||
|
get_entity_field_values,
|
||||||
|
get_initiative_archetype_key,
|
||||||
|
list_field_definitions,
|
||||||
|
patch_entity_field_values,
|
||||||
|
)
|
||||||
|
from entity_fields.sync import sync_entity_field_registry_to_db
|
||||||
|
from entity_fields.validation import normalize_field_value, validate_required_fields
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"FIELD_DEFINITIONS",
|
||||||
|
"get_entity_field_values",
|
||||||
|
"get_initiative_archetype_key",
|
||||||
|
"list_field_definitions",
|
||||||
|
"normalize_field_value",
|
||||||
|
"patch_entity_field_values",
|
||||||
|
"sync_entity_field_registry_to_db",
|
||||||
|
"validate_required_fields",
|
||||||
|
]
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""System-Felddefinitionen (Seed) — AP1.10b / AP2.0b."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
FIELD_DEFINITIONS: tuple[dict[str, Any], ...] = (
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.program",
|
||||||
|
"field_key": "stakeholder_map",
|
||||||
|
"field_type": "longtext",
|
||||||
|
"label": "Stakeholder-Übersicht",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 10,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.program",
|
||||||
|
"field_key": "success_criteria",
|
||||||
|
"field_type": "longtext",
|
||||||
|
"label": "Erfolgskriterien",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 20,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.product",
|
||||||
|
"field_key": "release_theme",
|
||||||
|
"field_type": "text",
|
||||||
|
"label": "Release-Thema",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 10,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.product",
|
||||||
|
"field_key": "metrics",
|
||||||
|
"field_type": "longtext",
|
||||||
|
"label": "Metriken / KPIs",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 20,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.maturity_journey",
|
||||||
|
"field_key": "current_focus",
|
||||||
|
"field_type": "text",
|
||||||
|
"label": "Aktueller Fokus",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 10,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.maturity_journey",
|
||||||
|
"field_key": "training_frequency",
|
||||||
|
"field_type": "enum",
|
||||||
|
"label": "Trainingsfrequenz",
|
||||||
|
"required": False,
|
||||||
|
"searchable": False,
|
||||||
|
"sort_order": 20,
|
||||||
|
"validation_json": {"options": ["daily", "3x_week", "weekly", "flexible"]},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.content_project",
|
||||||
|
"field_key": "manuscript_status",
|
||||||
|
"field_type": "text",
|
||||||
|
"label": "Manuskript-Status",
|
||||||
|
"required": False,
|
||||||
|
"searchable": True,
|
||||||
|
"sort_order": 10,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"archetype_key": "initiative.content_project",
|
||||||
|
"field_key": "word_count_goal",
|
||||||
|
"field_type": "number",
|
||||||
|
"label": "Wortziel",
|
||||||
|
"required": False,
|
||||||
|
"searchable": False,
|
||||||
|
"sort_order": 20,
|
||||||
|
"validation_json": {},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
"""Entity Field System — Lesen/Schreiben dynamischer Feldwerte — AP1.10b/10c."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from psycopg2.extras import Json, RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from entity_fields.validation import normalize_field_value, validate_required_fields
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_definition(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
result = dict(row)
|
||||||
|
if result.get("id"):
|
||||||
|
result["id"] = str(result["id"])
|
||||||
|
validation = result.get("validation_json")
|
||||||
|
if validation is None:
|
||||||
|
result["validation_json"] = {}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _api_value_from_row(row: dict[str, Any], field_type: str) -> Any:
|
||||||
|
if field_type == "number":
|
||||||
|
if row.get("value_number") is not None:
|
||||||
|
return float(row["value_number"])
|
||||||
|
return None
|
||||||
|
if field_type == "boolean":
|
||||||
|
if row.get("value_boolean") is not None:
|
||||||
|
return bool(row["value_boolean"])
|
||||||
|
return False
|
||||||
|
if field_type == "date":
|
||||||
|
value_date = row.get("value_date")
|
||||||
|
if value_date is not None:
|
||||||
|
return value_date.isoformat()
|
||||||
|
return None
|
||||||
|
text = row.get("value_text") or ""
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def list_field_definitions(
|
||||||
|
*,
|
||||||
|
archetype_key: str,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, archetype_key, field_key, field_type, label,
|
||||||
|
required, searchable, sort_order, validation_json
|
||||||
|
FROM field_definitions
|
||||||
|
WHERE archetype_key = %s
|
||||||
|
ORDER BY sort_order ASC, field_key ASC
|
||||||
|
""",
|
||||||
|
(archetype_key,),
|
||||||
|
)
|
||||||
|
return [_serialize_definition(dict(row)) for row in cur.fetchall()]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_entity_field_values(
|
||||||
|
*,
|
||||||
|
tenant_id: str,
|
||||||
|
entity_type: str,
|
||||||
|
entity_id: str,
|
||||||
|
definitions: list[dict[str, Any]],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if not definitions:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
field_keys = [item["field_key"] for item in definitions]
|
||||||
|
type_by_key = {item["field_key"]: item["field_type"] for item in definitions}
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT field_key, value_text, value_number, value_boolean, value_date
|
||||||
|
FROM field_values
|
||||||
|
WHERE tenant_id = %s
|
||||||
|
AND entity_type = %s
|
||||||
|
AND entity_id = %s
|
||||||
|
AND field_key = ANY(%s)
|
||||||
|
""",
|
||||||
|
(tenant_id, entity_type, entity_id, field_keys),
|
||||||
|
)
|
||||||
|
rows = {row["field_key"]: dict(row) for row in cur.fetchall()}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
result: dict[str, Any] = {}
|
||||||
|
for field_key in field_keys:
|
||||||
|
row = rows.get(field_key)
|
||||||
|
if row is None:
|
||||||
|
field_type = type_by_key[field_key]
|
||||||
|
if field_type == "boolean":
|
||||||
|
result[field_key] = False
|
||||||
|
else:
|
||||||
|
result[field_key] = None if field_type in {"number", "date"} else ""
|
||||||
|
else:
|
||||||
|
result[field_key] = _api_value_from_row(row, type_by_key[field_key])
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def patch_entity_field_values(
|
||||||
|
*,
|
||||||
|
tenant_id: str,
|
||||||
|
entity_type: str,
|
||||||
|
entity_id: str,
|
||||||
|
definitions: list[dict[str, Any]],
|
||||||
|
values: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if not values:
|
||||||
|
return get_entity_field_values(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
definitions=definitions,
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed_keys = {item["field_key"] for item in definitions}
|
||||||
|
unknown = sorted(set(values.keys()) - allowed_keys)
|
||||||
|
if unknown:
|
||||||
|
raise ValueError(f"Unbekannte Felder: {', '.join(unknown)}")
|
||||||
|
|
||||||
|
definition_by_key = {item["field_key"]: item for item in definitions}
|
||||||
|
merged = get_entity_field_values(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
definitions=definitions,
|
||||||
|
)
|
||||||
|
merged.update(values)
|
||||||
|
validate_required_fields(definitions=definitions, values=merged)
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for field_key, raw_value in values.items():
|
||||||
|
definition = definition_by_key[field_key]
|
||||||
|
normalized = normalize_field_value(
|
||||||
|
field_type=definition["field_type"],
|
||||||
|
raw_value=raw_value,
|
||||||
|
validation_json=definition.get("validation_json"),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO field_values (
|
||||||
|
tenant_id, entity_type, entity_id, field_key,
|
||||||
|
value_json, value_text, value_number, value_boolean, value_date
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (tenant_id, entity_type, entity_id, field_key) DO UPDATE SET
|
||||||
|
value_json = EXCLUDED.value_json,
|
||||||
|
value_text = EXCLUDED.value_text,
|
||||||
|
value_number = EXCLUDED.value_number,
|
||||||
|
value_boolean = EXCLUDED.value_boolean,
|
||||||
|
value_date = EXCLUDED.value_date,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
tenant_id,
|
||||||
|
entity_type,
|
||||||
|
entity_id,
|
||||||
|
field_key,
|
||||||
|
Json(normalized["value_json"]) if normalized["value_json"] is not None else None,
|
||||||
|
normalized["value_text"],
|
||||||
|
normalized["value_number"],
|
||||||
|
normalized["value_boolean"],
|
||||||
|
normalized["value_date"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return get_entity_field_values(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
definitions=definitions,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_initiative_archetype_key(*, tenant_id: str, initiative_id: str) -> Optional[str]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT archetype_key
|
||||||
|
FROM initiatives
|
||||||
|
WHERE tenant_id = %s AND id = %s
|
||||||
|
""",
|
||||||
|
(tenant_id, initiative_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row[0] if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""Sync Entity-Archetypen und Felddefinitionen in PostgreSQL — AP1.10b / AP2.0b."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from entity_archetypes.registry import ENTITY_ARCHETYPES
|
||||||
|
from entity_fields.definitions import FIELD_DEFINITIONS
|
||||||
|
|
||||||
|
|
||||||
|
def sync_entity_field_registry_to_db() -> int:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for archetype in ENTITY_ARCHETYPES:
|
||||||
|
ui_profile = archetype.get("ui_profile_json") or {}
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO entity_archetypes (
|
||||||
|
archetype_key, entity_type, label, description, is_system,
|
||||||
|
ui_profile_json
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s::jsonb)
|
||||||
|
ON CONFLICT (archetype_key) DO UPDATE SET
|
||||||
|
entity_type = EXCLUDED.entity_type,
|
||||||
|
label = EXCLUDED.label,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_system = EXCLUDED.is_system,
|
||||||
|
ui_profile_json = EXCLUDED.ui_profile_json,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
archetype["key"],
|
||||||
|
archetype["entity_type"],
|
||||||
|
archetype["label"],
|
||||||
|
archetype["description"],
|
||||||
|
archetype["is_system"],
|
||||||
|
json.dumps(ui_profile),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
for field_def in FIELD_DEFINITIONS:
|
||||||
|
validation_json = field_def.get("validation_json") or {}
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO field_definitions (
|
||||||
|
archetype_key, field_key, field_type, label,
|
||||||
|
required, searchable, sort_order, validation_json
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb)
|
||||||
|
ON CONFLICT (archetype_key, field_key) DO UPDATE SET
|
||||||
|
field_type = EXCLUDED.field_type,
|
||||||
|
label = EXCLUDED.label,
|
||||||
|
required = EXCLUDED.required,
|
||||||
|
searchable = EXCLUDED.searchable,
|
||||||
|
sort_order = EXCLUDED.sort_order,
|
||||||
|
validation_json = EXCLUDED.validation_json,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
field_def["archetype_key"],
|
||||||
|
field_def["field_key"],
|
||||||
|
field_def["field_type"],
|
||||||
|
field_def["label"],
|
||||||
|
field_def["required"],
|
||||||
|
field_def["searchable"],
|
||||||
|
field_def["sort_order"],
|
||||||
|
json.dumps(validation_json),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(
|
||||||
|
"[entity_fields] Sync OK — "
|
||||||
|
f"{len(ENTITY_ARCHETYPES)} Archetyp(en), "
|
||||||
|
f"{len(FIELD_DEFINITIONS)} Felddefinition(en)"
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[entity_fields] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""Validierung dynamischer Feldwerte gegen Definitionen — AP1.10b/10c."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
VALID_FIELD_TYPES = frozenset(
|
||||||
|
{"text", "longtext", "number", "boolean", "date", "enum", "actor_ref", "url"}
|
||||||
|
)
|
||||||
|
|
||||||
|
_URL_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(value: str) -> date:
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(value)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(f"Ungültiges Datum: {value}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_url(value: str) -> None:
|
||||||
|
if not value.strip():
|
||||||
|
return
|
||||||
|
parsed = urlparse(value.strip())
|
||||||
|
if parsed.scheme and parsed.netloc:
|
||||||
|
return
|
||||||
|
if _URL_SCHEME_RE.match(value.strip()):
|
||||||
|
return
|
||||||
|
raise ValueError(f"Ungültige URL: {value}")
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_field_value(
|
||||||
|
*,
|
||||||
|
field_type: str,
|
||||||
|
raw_value: Any,
|
||||||
|
validation_json: Optional[dict[str, Any]] = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Wert normalisieren und in DB-Spalten aufteilen."""
|
||||||
|
validation_json = validation_json or {}
|
||||||
|
|
||||||
|
if field_type in {"text", "longtext", "url", "actor_ref", "enum"}:
|
||||||
|
if raw_value is None:
|
||||||
|
text = ""
|
||||||
|
elif not isinstance(raw_value, str):
|
||||||
|
raise ValueError(f"Feld erwartet Text, erhalten: {type(raw_value).__name__}")
|
||||||
|
else:
|
||||||
|
text = raw_value.strip()
|
||||||
|
if field_type == "url" and text:
|
||||||
|
_validate_url(text)
|
||||||
|
if field_type == "enum" and text:
|
||||||
|
options = validation_json.get("options") or []
|
||||||
|
if options and text not in options:
|
||||||
|
raise ValueError(f"Ungültiger Enum-Wert: {text}")
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": text,
|
||||||
|
"value_number": None,
|
||||||
|
"value_boolean": None,
|
||||||
|
"value_date": None,
|
||||||
|
"api_value": text,
|
||||||
|
}
|
||||||
|
|
||||||
|
if field_type == "number":
|
||||||
|
if raw_value is None or raw_value == "":
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": "",
|
||||||
|
"value_number": None,
|
||||||
|
"value_boolean": None,
|
||||||
|
"value_date": None,
|
||||||
|
"api_value": None,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
number = float(raw_value)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError(f"Ungültige Zahl: {raw_value}") from exc
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": str(number),
|
||||||
|
"value_number": number,
|
||||||
|
"value_boolean": None,
|
||||||
|
"value_date": None,
|
||||||
|
"api_value": number,
|
||||||
|
}
|
||||||
|
|
||||||
|
if field_type == "boolean":
|
||||||
|
if raw_value is None:
|
||||||
|
bool_val = False
|
||||||
|
elif isinstance(raw_value, bool):
|
||||||
|
bool_val = raw_value
|
||||||
|
elif isinstance(raw_value, str):
|
||||||
|
lowered = raw_value.strip().lower()
|
||||||
|
if lowered in {"true", "1", "yes", "on"}:
|
||||||
|
bool_val = True
|
||||||
|
elif lowered in {"false", "0", "no", "off", ""}:
|
||||||
|
bool_val = False
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Ungültiger Boolean-Wert: {raw_value}")
|
||||||
|
else:
|
||||||
|
bool_val = bool(raw_value)
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": "true" if bool_val else "false",
|
||||||
|
"value_number": None,
|
||||||
|
"value_boolean": bool_val,
|
||||||
|
"value_date": None,
|
||||||
|
"api_value": bool_val,
|
||||||
|
}
|
||||||
|
|
||||||
|
if field_type == "date":
|
||||||
|
if raw_value is None or raw_value == "":
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": "",
|
||||||
|
"value_number": None,
|
||||||
|
"value_boolean": None,
|
||||||
|
"value_date": None,
|
||||||
|
"api_value": None,
|
||||||
|
}
|
||||||
|
if isinstance(raw_value, date) and not isinstance(raw_value, datetime):
|
||||||
|
parsed = raw_value
|
||||||
|
elif isinstance(raw_value, str):
|
||||||
|
parsed = _parse_date(raw_value)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Ungültiges Datum: {raw_value}")
|
||||||
|
iso = parsed.isoformat()
|
||||||
|
return {
|
||||||
|
"value_json": None,
|
||||||
|
"value_text": iso,
|
||||||
|
"value_number": None,
|
||||||
|
"value_boolean": None,
|
||||||
|
"value_date": parsed,
|
||||||
|
"api_value": iso,
|
||||||
|
}
|
||||||
|
|
||||||
|
raise ValueError(f"Unbekannter Feldtyp: {field_type}")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_required_fields(
|
||||||
|
*,
|
||||||
|
definitions: list[dict[str, Any]],
|
||||||
|
values: dict[str, Any],
|
||||||
|
) -> None:
|
||||||
|
for definition in definitions:
|
||||||
|
if not definition.get("required"):
|
||||||
|
continue
|
||||||
|
key = definition["field_key"]
|
||||||
|
raw = values.get(key)
|
||||||
|
if raw is None or (isinstance(raw, str) and not raw.strip()):
|
||||||
|
raise ValueError(f"Pflichtfeld fehlt: {definition.get('label') or key}")
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "=== Kairo Backend Startup ==="
|
||||||
|
|
||||||
|
if [ "${SKIP_DB_MIGRATE}" != "1" ] && [ "${SKIP_DB_MIGRATE}" != "true" ] && [ "${SKIP_DB_MIGRATE}" != "yes" ]; then
|
||||||
|
python run_migrations.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_DB_MIGRATE] Migrationen übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_SEEDS}" != "1" ] && [ "${SKIP_SEEDS}" != "true" ] && [ "${SKIP_SEEDS}" != "yes" ]; then
|
||||||
|
python run_seeds.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_SEEDS] Data-Seeds übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_RIGHTS_SYNC}" != "1" ] && [ "${SKIP_RIGHTS_SYNC}" != "true" ] && [ "${SKIP_RIGHTS_SYNC}" != "yes" ]; then
|
||||||
|
python sync_rights_registry.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_RIGHTS_SYNC] Rights-Registry-Sync übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_REGISTRY_SYNC}" != "1" ] && [ "${SKIP_REGISTRY_SYNC}" != "true" ] && [ "${SKIP_REGISTRY_SYNC}" != "yes" ]; then
|
||||||
|
python sync_prompt_feature_config.py
|
||||||
|
python sync_entity_field_registry.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_REGISTRY_SYNC] Feature/Prompt/Config/EFS-Sync übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export KAIRO_DB_READY=1
|
||||||
|
echo "=== Starte Anwendung: $* ==="
|
||||||
|
exec "$@"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for feature registrations."""
|
||||||
|
|
||||||
|
from feature_registrations import platform, prompt_ops # noqa: F401
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Platform feature catalog entries."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from feature_registry import FeatureRegistration, register_feature
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.feature.registry",
|
||||||
|
module="platform",
|
||||||
|
name="Feature Registry",
|
||||||
|
description="Metadatenkatalog registrierter Kairo-Features",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.config.registry",
|
||||||
|
module="config",
|
||||||
|
name="Configuration Registry",
|
||||||
|
description="Zentrale fachliche Konfiguration (global/tenant)",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.prompt.registry",
|
||||||
|
module="prompt",
|
||||||
|
name="Prompt Registry",
|
||||||
|
description="Workflow-ready Prompt-Definitionen und Versionen",
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""Prompt-related feature metadata."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# Reserved for future prompt-domain features beyond registry catalog.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""In-memory feature registry with startup sync to PostgreSQL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
VALID_CONTEXT_KINDS = frozenset(
|
||||||
|
{
|
||||||
|
"kairo.tenant_context",
|
||||||
|
"kairo.actor_context",
|
||||||
|
"kairo.debug_context",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
VALID_EXECUTION_MODES = frozenset({"single", "pipeline", "workflow"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FeatureRegistration:
|
||||||
|
key: str
|
||||||
|
module: str
|
||||||
|
name: str
|
||||||
|
description: str
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, FeatureRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_feature(registration: FeatureRegistration) -> None:
|
||||||
|
if not registration.key or not registration.key.strip():
|
||||||
|
raise ValueError("Feature key is required")
|
||||||
|
if not registration.module or not registration.module.strip():
|
||||||
|
raise ValueError("Feature module is required")
|
||||||
|
if not registration.name or not registration.name.strip():
|
||||||
|
raise ValueError("Feature name is required")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Feature description is required")
|
||||||
|
if registration.key in _REGISTRY:
|
||||||
|
raise ValueError(f"Feature already registered: {registration.key}")
|
||||||
|
_REGISTRY[registration.key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_features() -> tuple[FeatureRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_feature_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_features_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[feature_registry] Keine Features registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO features (feature_key, module, name, description, is_active)
|
||||||
|
VALUES (%s, %s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (feature_key) DO UPDATE SET
|
||||||
|
module = EXCLUDED.module,
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(reg.key, reg.module, reg.name, reg.description),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[feature_registry] Sync OK — {len(_REGISTRY)} Feature(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[feature_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_active_features() -> dict[str, dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT feature_key, module, name, description
|
||||||
|
FROM features
|
||||||
|
WHERE is_active = TRUE
|
||||||
|
ORDER BY feature_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
row[0]: {
|
||||||
|
"enabled": True,
|
||||||
|
"module": row[1],
|
||||||
|
"name": row[2],
|
||||||
|
"description": row[3],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
"""Jinkendo Kairo — FastAPI application entry point."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from db import check_db
|
||||||
|
from version import APP_NAME, APP_VERSION, DB_SCHEMA_VERSION
|
||||||
|
|
||||||
|
import steering # noqa: F401 — bootstrap hooks & methods
|
||||||
|
|
||||||
|
if os.getenv("KAIRO_DB_READY") != "1":
|
||||||
|
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() not in ("1", "true", "yes"):
|
||||||
|
import run_migrations
|
||||||
|
|
||||||
|
exit_code = run_migrations.main()
|
||||||
|
if exit_code != 0:
|
||||||
|
print(f"[FAIL] Migrationen fehlgeschlagen (Exit {exit_code})")
|
||||||
|
sys.exit(exit_code)
|
||||||
|
else:
|
||||||
|
print("[SKIP_DB_MIGRATE] Migrationen übersprungen")
|
||||||
|
|
||||||
|
if os.getenv("SKIP_SEEDS", "").strip().lower() not in ("1", "true", "yes"):
|
||||||
|
import run_seeds
|
||||||
|
|
||||||
|
exit_code = run_seeds.main()
|
||||||
|
if exit_code != 0:
|
||||||
|
print(f"[FAIL] Seeds fehlgeschlagen (Exit {exit_code})")
|
||||||
|
sys.exit(exit_code)
|
||||||
|
else:
|
||||||
|
print("[SKIP_SEEDS] Data-Seeds übersprungen")
|
||||||
|
|
||||||
|
allowed_origins = [
|
||||||
|
origin.strip()
|
||||||
|
for origin in os.getenv("ALLOWED_ORIGINS", "http://localhost:3097").split(",")
|
||||||
|
if origin.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Jinkendo Kairo",
|
||||||
|
version=APP_VERSION,
|
||||||
|
docs_url="/api/docs" if os.getenv("ENVIRONMENT", "development") != "production" else None,
|
||||||
|
redoc_url=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=allowed_origins,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
from routers import ( # noqa: E402
|
||||||
|
actions,
|
||||||
|
actors,
|
||||||
|
auth,
|
||||||
|
backlog,
|
||||||
|
blockers,
|
||||||
|
config,
|
||||||
|
decisions,
|
||||||
|
entity_archetypes,
|
||||||
|
evidence,
|
||||||
|
execution_plan,
|
||||||
|
features,
|
||||||
|
initiatives,
|
||||||
|
journey,
|
||||||
|
me,
|
||||||
|
milestones,
|
||||||
|
projects,
|
||||||
|
roadmap,
|
||||||
|
prompts,
|
||||||
|
recurring,
|
||||||
|
reviews,
|
||||||
|
steering,
|
||||||
|
tasks,
|
||||||
|
workspace,
|
||||||
|
operational,
|
||||||
|
work_cycles,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(auth.router)
|
||||||
|
app.include_router(me.router)
|
||||||
|
app.include_router(features.router)
|
||||||
|
app.include_router(prompts.router)
|
||||||
|
app.include_router(config.router)
|
||||||
|
app.include_router(initiatives.router)
|
||||||
|
app.include_router(entity_archetypes.router)
|
||||||
|
app.include_router(journey.initiative_router)
|
||||||
|
app.include_router(journey.roadmap_router)
|
||||||
|
app.include_router(actions.router)
|
||||||
|
app.include_router(projects.initiative_router)
|
||||||
|
app.include_router(projects.items_router)
|
||||||
|
app.include_router(tasks.router)
|
||||||
|
app.include_router(blockers.router)
|
||||||
|
app.include_router(backlog.router)
|
||||||
|
app.include_router(milestones.router)
|
||||||
|
app.include_router(roadmap.initiative_router)
|
||||||
|
app.include_router(roadmap.items_router)
|
||||||
|
app.include_router(roadmap.deps_router)
|
||||||
|
app.include_router(roadmap.criteria_router)
|
||||||
|
app.include_router(execution_plan.initiative_router)
|
||||||
|
app.include_router(evidence.router)
|
||||||
|
app.include_router(decisions.router)
|
||||||
|
app.include_router(reviews.router)
|
||||||
|
app.include_router(recurring.router)
|
||||||
|
app.include_router(steering.router)
|
||||||
|
app.include_router(actors.router)
|
||||||
|
app.include_router(workspace.router)
|
||||||
|
app.include_router(operational.router)
|
||||||
|
app.include_router(work_cycles.initiative_router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/health")
|
||||||
|
def api_health():
|
||||||
|
db_status = "ok"
|
||||||
|
try:
|
||||||
|
if not check_db():
|
||||||
|
db_status = "error"
|
||||||
|
except Exception:
|
||||||
|
db_status = "error"
|
||||||
|
|
||||||
|
status = "ok" if db_status == "ok" else "degraded"
|
||||||
|
return {
|
||||||
|
"status": status,
|
||||||
|
"app": APP_NAME,
|
||||||
|
"db": db_status,
|
||||||
|
"version": APP_VERSION,
|
||||||
|
"schema": DB_SCHEMA_VERSION,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/version")
|
||||||
|
def api_version():
|
||||||
|
return {
|
||||||
|
"app": APP_NAME,
|
||||||
|
"version": APP_VERSION,
|
||||||
|
"schema": DB_SCHEMA_VERSION,
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Package marker for method profile seeds."""
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Referenz-Ausprägungen (Method Profiles) — Code-Seeds AP2.0b."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
METHOD_PROFILES: tuple[dict[str, Any], ...] = (
|
||||||
|
{
|
||||||
|
"key": "maturity.karate_kumite",
|
||||||
|
"label": "Karate Kumite",
|
||||||
|
"description": "Mehrere Fähigkeiten mit Stufen, Routinen und Voraussetzungs-Graph.",
|
||||||
|
"initiative_archetype_key": "initiative.maturity_journey",
|
||||||
|
"method_key": "maturity_progression",
|
||||||
|
"seed_hints": {
|
||||||
|
"skill_count": 8,
|
||||||
|
"stages_per_skill": "5-7",
|
||||||
|
"graph_prerequisites": True,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "content.book_writing",
|
||||||
|
"label": "Buch schreiben",
|
||||||
|
"description": "Kapitelstruktur, Schreib-APs, Review-Gates.",
|
||||||
|
"initiative_archetype_key": "initiative.content_project",
|
||||||
|
"method_key": "chapter_based_progression",
|
||||||
|
"seed_hints": {
|
||||||
|
"roadmap_item_type": "chapter",
|
||||||
|
"review_gates": True,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "product.kairo_dev",
|
||||||
|
"label": "Kairo Entwicklung",
|
||||||
|
"description": "Kontinuierliches Produkt mit Gate-Orientierung und optionaler Sprint-Zeitbox.",
|
||||||
|
"initiative_archetype_key": "initiative.product",
|
||||||
|
"method_key": "continuous_product",
|
||||||
|
"seed_hints": {
|
||||||
|
"agile_iteration_profile": True,
|
||||||
|
"default_actor_setup": "po_plus_vibe_coder",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "project.agile_iteration",
|
||||||
|
"label": "Projekt mit Sprint",
|
||||||
|
"description": "Lineares Projekt (A2) mit optionaler Agile-Iteration.",
|
||||||
|
"initiative_archetype_key": "initiative.linear_project",
|
||||||
|
"method_key": "sequential_dependency",
|
||||||
|
"seed_hints": {
|
||||||
|
"agile_iteration_profile": True,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
_PROFILE_INDEX = {item["key"]: item for item in METHOD_PROFILES}
|
||||||
|
|
||||||
|
|
||||||
|
def get_method_profile(key: str) -> Optional[dict[str, Any]]:
|
||||||
|
item = _PROFILE_INDEX.get(key)
|
||||||
|
return dict(item) if item else None
|
||||||
|
|
||||||
|
|
||||||
|
def list_method_profiles(*, initiative_archetype_key: Optional[str] = None) -> list[dict[str, Any]]:
|
||||||
|
items = METHOD_PROFILES
|
||||||
|
if initiative_archetype_key:
|
||||||
|
items = tuple(
|
||||||
|
i for i in items if i["initiative_archetype_key"] == initiative_archetype_key
|
||||||
|
)
|
||||||
|
return [dict(item) for item in items]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_method_for_profile(profile_key: str) -> Optional[str]:
|
||||||
|
profile = get_method_profile(profile_key)
|
||||||
|
return profile["method_key"] if profile else None
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- AP0.1: minimale Schema-Vorbereitung (keine Tenant/User/Actor-Fachlogik)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS kairo_app_meta (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
key VARCHAR(128) UNIQUE NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO kairo_app_meta (key, value)
|
||||||
|
VALUES ('schema_phase', 'ap0.1')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
-- AP0.2: Auth, Identity, Tenant & Actor Foundation
|
||||||
|
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
display_name VARCHAR(255) NOT NULL,
|
||||||
|
portal_role VARCHAR(32) NOT NULL DEFAULT 'user'
|
||||||
|
CHECK (portal_role IN ('user', 'admin')),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE tenant_memberships (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
tenant_role VARCHAR(32) NOT NULL DEFAULT 'member'
|
||||||
|
CHECK (tenant_role IN ('owner', 'admin', 'member')),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_tenant_memberships_user ON tenant_memberships(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE actors (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
actor_type VARCHAR(32) NOT NULL
|
||||||
|
CHECK (actor_type IN ('human', 'agent', 'working_group', 'external_system')),
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CHECK (
|
||||||
|
(actor_type = 'human' AND user_id IS NOT NULL)
|
||||||
|
OR (actor_type <> 'human' AND user_id IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX idx_actors_human_user_tenant
|
||||||
|
ON actors(tenant_id, user_id)
|
||||||
|
WHERE actor_type = 'human';
|
||||||
|
|
||||||
|
CREATE INDEX idx_actors_tenant ON actors(tenant_id);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
token VARCHAR(128) NOT NULL UNIQUE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
active_tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sessions_token ON sessions(token);
|
||||||
|
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE audit_log (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
action VARCHAR(64) NOT NULL,
|
||||||
|
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||||
|
details JSONB NOT NULL DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_audit_log_created ON audit_log(created_at DESC);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Tracking für idempotente Data-Seeds (Checksum-basiert, bei Änderung erneut ausführbar)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS data_seeds (
|
||||||
|
seed_name VARCHAR(255) PRIMARY KEY,
|
||||||
|
checksum VARCHAR(64) NOT NULL,
|
||||||
|
executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- AP0.3: Capability catalog and role → capability grants
|
||||||
|
|
||||||
|
CREATE TABLE capabilities (
|
||||||
|
capability_key VARCHAR(128) PRIMARY KEY,
|
||||||
|
module VARCHAR(64) NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE role_capability_grants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
role_scope VARCHAR(16) NOT NULL
|
||||||
|
CHECK (role_scope IN ('portal', 'tenant')),
|
||||||
|
role_code VARCHAR(32) NOT NULL,
|
||||||
|
capability_key VARCHAR(128) NOT NULL REFERENCES capabilities(capability_key) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (role_scope, role_code, capability_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_role_capability_grants_lookup
|
||||||
|
ON role_capability_grants(role_scope, role_code);
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
-- AP0.4: Feature, Prompt, Placeholder and Configuration registries
|
||||||
|
|
||||||
|
CREATE TABLE features (
|
||||||
|
feature_key VARCHAR(128) PRIMARY KEY,
|
||||||
|
module VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE prompt_definitions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_key VARCHAR(128) NOT NULL UNIQUE,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
purpose TEXT NOT NULL DEFAULT '',
|
||||||
|
context_kind VARCHAR(64) NOT NULL,
|
||||||
|
execution_mode VARCHAR(32) NOT NULL DEFAULT 'single'
|
||||||
|
CHECK (execution_mode IN ('single', 'pipeline', 'workflow')),
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||||
|
CHECK (status IN ('draft', 'active', 'archived')),
|
||||||
|
active_version_id UUID,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE prompt_versions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_definition_id UUID NOT NULL REFERENCES prompt_definitions(id) ON DELETE CASCADE,
|
||||||
|
version VARCHAR(64) NOT NULL,
|
||||||
|
body TEXT NOT NULL DEFAULT '',
|
||||||
|
input_schema JSONB,
|
||||||
|
output_schema JSONB,
|
||||||
|
model_policy_key VARCHAR(128),
|
||||||
|
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
changelog TEXT NOT NULL DEFAULT '',
|
||||||
|
UNIQUE (prompt_definition_id, version)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE prompt_definitions
|
||||||
|
ADD CONSTRAINT fk_prompt_definitions_active_version
|
||||||
|
FOREIGN KEY (active_version_id) REFERENCES prompt_versions(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE TABLE prompt_steps (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_version_id UUID NOT NULL REFERENCES prompt_versions(id) ON DELETE CASCADE,
|
||||||
|
step_key VARCHAR(128) NOT NULL,
|
||||||
|
step_order INT NOT NULL DEFAULT 0,
|
||||||
|
step_type VARCHAR(32) NOT NULL DEFAULT 'template'
|
||||||
|
CHECK (step_type IN ('template', 'resolver', 'llm_call', 'postprocess', 'validation')),
|
||||||
|
template_body TEXT NOT NULL DEFAULT '',
|
||||||
|
input_mapping JSONB,
|
||||||
|
output_mapping JSONB,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (prompt_version_id, step_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_prompt_steps_version_order
|
||||||
|
ON prompt_steps(prompt_version_id, step_order);
|
||||||
|
|
||||||
|
CREATE TABLE placeholder_definitions (
|
||||||
|
placeholder_key VARCHAR(128) NOT NULL,
|
||||||
|
context_kind VARCHAR(64) NOT NULL,
|
||||||
|
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||||
|
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
source VARCHAR(64) NOT NULL DEFAULT 'input',
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (placeholder_key, context_kind)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE configuration_entries (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
config_key VARCHAR(128) NOT NULL,
|
||||||
|
scope VARCHAR(32) NOT NULL DEFAULT 'global'
|
||||||
|
CHECK (scope IN ('global', 'tenant')),
|
||||||
|
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
value JSONB NOT NULL DEFAULT '{}',
|
||||||
|
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||||
|
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
is_secret BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CHECK (
|
||||||
|
(scope = 'global' AND tenant_id IS NULL)
|
||||||
|
OR (scope = 'tenant' AND tenant_id IS NOT NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_configuration_entries_global
|
||||||
|
ON configuration_entries (config_key)
|
||||||
|
WHERE scope = 'global';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_configuration_entries_tenant
|
||||||
|
ON configuration_entries (config_key, tenant_id)
|
||||||
|
WHERE scope = 'tenant';
|
||||||
|
|
||||||
|
CREATE TABLE prompt_execution_logs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_definition_id UUID REFERENCES prompt_definitions(id) ON DELETE SET NULL,
|
||||||
|
prompt_version_id UUID REFERENCES prompt_versions(id) ON DELETE SET NULL,
|
||||||
|
execution_mode VARCHAR(32) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL
|
||||||
|
CHECK (status IN ('success', 'error', 'skipped')),
|
||||||
|
rendered_preview TEXT,
|
||||||
|
input_summary JSONB,
|
||||||
|
error_message TEXT,
|
||||||
|
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_prompt_execution_logs_created
|
||||||
|
ON prompt_execution_logs(created_at DESC);
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
-- AP0.5: Minimal initiatives (Vorhaben), actions (Maßnahmen), action_assignments
|
||||||
|
|
||||||
|
CREATE TABLE initiatives (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
goal TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||||
|
CHECK (status IN ('active', 'paused', 'completed', 'archived')),
|
||||||
|
priority VARCHAR(16) NOT NULL DEFAULT 'normal'
|
||||||
|
CHECK (priority IN ('low', 'normal', 'high')),
|
||||||
|
owner_actor_id UUID NOT NULL REFERENCES actors(id) ON DELETE RESTRICT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_initiatives_tenant ON initiatives(tenant_id);
|
||||||
|
CREATE INDEX idx_initiatives_owner ON initiatives(owner_actor_id);
|
||||||
|
|
||||||
|
CREATE TABLE actions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'in_progress', 'blocked', 'done', 'discarded')),
|
||||||
|
priority VARCHAR(16) NOT NULL DEFAULT 'normal'
|
||||||
|
CHECK (priority IN ('low', 'normal', 'high')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_actions_tenant ON actions(tenant_id);
|
||||||
|
CREATE INDEX idx_actions_initiative ON actions(initiative_id);
|
||||||
|
CREATE INDEX idx_actions_status ON actions(tenant_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE action_assignments (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||||
|
actor_id UUID NOT NULL REFERENCES actors(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (action_id, actor_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_action_assignments_tenant ON action_assignments(tenant_id);
|
||||||
|
CREATE INDEX idx_action_assignments_actor ON action_assignments(actor_id);
|
||||||
|
CREATE INDEX idx_action_assignments_action ON action_assignments(action_id);
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
-- AP0.8: Operating Model Extension I — blockers, backlog_items, milestones
|
||||||
|
|
||||||
|
CREATE TABLE blockers (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'in_progress', 'resolved', 'accepted_risk', 'dismissed')),
|
||||||
|
reported_by_actor_id UUID NULL REFERENCES actors(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_blockers_tenant_initiative ON blockers(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_blockers_tenant_status ON blockers(tenant_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE backlog_items (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'new'
|
||||||
|
CHECK (status IN ('new', 'triaged', 'accepted', 'rejected', 'converted')),
|
||||||
|
priority VARCHAR(16) NOT NULL DEFAULT 'normal'
|
||||||
|
CHECK (priority IN ('low', 'normal', 'high')),
|
||||||
|
converted_action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_backlog_items_tenant_initiative ON backlog_items(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_backlog_items_tenant_status ON backlog_items(tenant_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE milestones (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
goal_description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'planned'
|
||||||
|
CHECK (status IN ('planned', 'active', 'at_risk', 'reached', 'moved', 'discarded')),
|
||||||
|
target_date DATE NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_milestones_tenant_initiative ON milestones(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_milestones_tenant_status ON milestones(tenant_id, status);
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
-- AP0.9: Operating Model Extension II — evidence, decisions, reviews, recurring_elements, action due_at
|
||||||
|
|
||||||
|
ALTER TABLE actions ADD COLUMN due_at TIMESTAMPTZ NULL;
|
||||||
|
|
||||||
|
ALTER TABLE actions DROP CONSTRAINT actions_status_check;
|
||||||
|
|
||||||
|
ALTER TABLE actions ADD CONSTRAINT actions_status_check
|
||||||
|
CHECK (status IN (
|
||||||
|
'open', 'ready', 'in_progress', 'blocked', 'review_required', 'done', 'discarded'
|
||||||
|
));
|
||||||
|
|
||||||
|
CREATE INDEX idx_actions_due_at ON actions(tenant_id, due_at) WHERE due_at IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE TABLE evidence (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||||
|
milestone_id UUID NULL REFERENCES milestones(id) ON DELETE SET NULL,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'submitted'
|
||||||
|
CHECK (status IN ('submitted', 'accepted', 'rejected')),
|
||||||
|
submitted_by_actor_id UUID NULL REFERENCES actors(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_evidence_tenant_initiative ON evidence(tenant_id, initiative_id);
|
||||||
|
|
||||||
|
CREATE TABLE decisions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'proposed'
|
||||||
|
CHECK (status IN ('proposed', 'decided', 'superseded')),
|
||||||
|
outcome TEXT NOT NULL DEFAULT '',
|
||||||
|
decided_by_actor_id UUID NULL REFERENCES actors(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_decisions_tenant_initiative ON decisions(tenant_id, initiative_id);
|
||||||
|
|
||||||
|
CREATE TABLE reviews (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||||
|
milestone_id UUID NULL REFERENCES milestones(id) ON DELETE SET NULL,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
summary TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'planned'
|
||||||
|
CHECK (status IN ('planned', 'completed', 'skipped')),
|
||||||
|
due_at TIMESTAMPTZ NULL,
|
||||||
|
reviewed_by_actor_id UUID NULL REFERENCES actors(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_reviews_tenant_initiative ON reviews(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_reviews_due_at ON reviews(tenant_id, due_at) WHERE due_at IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE TABLE recurring_elements (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||||
|
CHECK (status IN ('active', 'paused', 'ended')),
|
||||||
|
interval_days INT NULL CHECK (interval_days IS NULL OR interval_days > 0),
|
||||||
|
next_due_at TIMESTAMPTZ NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_recurring_elements_tenant_initiative ON recurring_elements(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_recurring_elements_next_due ON recurring_elements(tenant_id, next_due_at)
|
||||||
|
WHERE next_due_at IS NOT NULL;
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
-- AP1.0: Steering Foundation — steering_contexts
|
||||||
|
|
||||||
|
CREATE TABLE steering_contexts (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
method_key VARCHAR(64) NOT NULL DEFAULT 'generic_operating',
|
||||||
|
method_version VARCHAR(32) NOT NULL DEFAULT '0.1.0',
|
||||||
|
lifecycle_state VARCHAR(64) NOT NULL DEFAULT 'intake',
|
||||||
|
lifecycle_metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, initiative_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_steering_contexts_tenant ON steering_contexts(tenant_id);
|
||||||
|
CREATE INDEX idx_steering_contexts_initiative ON steering_contexts(tenant_id, initiative_id);
|
||||||
|
|
||||||
|
INSERT INTO steering_contexts (tenant_id, initiative_id, lifecycle_state)
|
||||||
|
SELECT
|
||||||
|
i.tenant_id,
|
||||||
|
i.id,
|
||||||
|
CASE
|
||||||
|
WHEN i.status IN ('completed', 'archived') THEN 'closure'
|
||||||
|
WHEN EXISTS (
|
||||||
|
SELECT 1 FROM actions a
|
||||||
|
WHERE a.initiative_id = i.id
|
||||||
|
AND a.tenant_id = i.tenant_id
|
||||||
|
AND a.status IN (
|
||||||
|
'open', 'ready', 'in_progress', 'blocked', 'review_required'
|
||||||
|
)
|
||||||
|
) THEN 'action_selection'
|
||||||
|
WHEN EXISTS (
|
||||||
|
SELECT 1 FROM backlog_items bi
|
||||||
|
WHERE bi.initiative_id = i.id
|
||||||
|
AND bi.tenant_id = i.tenant_id
|
||||||
|
AND bi.status IN ('new', 'triaged', 'accepted')
|
||||||
|
) THEN 'structure_setup'
|
||||||
|
ELSE 'planning'
|
||||||
|
END
|
||||||
|
FROM initiatives i;
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
-- AP1.4: Roadmap + RoadmapItem + Dependencies (methodenneutral)
|
||||||
|
|
||||||
|
CREATE TABLE roadmaps (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL DEFAULT 'Plan',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, initiative_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmaps_tenant_initiative ON roadmaps(tenant_id, initiative_id);
|
||||||
|
|
||||||
|
CREATE TABLE roadmap_items (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
roadmap_id UUID NOT NULL REFERENCES roadmaps(id) ON DELETE CASCADE,
|
||||||
|
item_type VARCHAR(32) NOT NULL DEFAULT 'milestone'
|
||||||
|
CHECK (item_type IN ('milestone', 'review_gate', 'maturity_stage')),
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
goal_description TEXT NOT NULL DEFAULT '',
|
||||||
|
definition_of_done JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'planned'
|
||||||
|
CHECK (status IN ('planned', 'active', 'at_risk', 'reached', 'moved', 'discarded')),
|
||||||
|
sequencing_mode VARCHAR(32) NOT NULL DEFAULT 'sequential'
|
||||||
|
CHECK (sequencing_mode IN ('sequential', 'parallel', 'optional')),
|
||||||
|
target_date DATE NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmap_items_tenant_roadmap ON roadmap_items(tenant_id, roadmap_id);
|
||||||
|
CREATE INDEX idx_roadmap_items_tenant_status ON roadmap_items(tenant_id, status);
|
||||||
|
CREATE INDEX idx_roadmap_items_tenant_type ON roadmap_items(tenant_id, item_type);
|
||||||
|
|
||||||
|
CREATE TABLE roadmap_item_dependencies (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
from_item_id UUID NOT NULL REFERENCES roadmap_items(id) ON DELETE CASCADE,
|
||||||
|
to_item_id UUID NOT NULL REFERENCES roadmap_items(id) ON DELETE CASCADE,
|
||||||
|
dependency_type VARCHAR(32) NOT NULL DEFAULT 'requires'
|
||||||
|
CHECK (dependency_type IN ('requires', 'blocks', 'related')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, from_item_id, to_item_id, dependency_type)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmap_deps_from ON roadmap_item_dependencies(tenant_id, from_item_id);
|
||||||
|
CREATE INDEX idx_roadmap_deps_to ON roadmap_item_dependencies(tenant_id, to_item_id);
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD COLUMN roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_backlog_roadmap_item ON backlog_items(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
|
CREATE INDEX idx_actions_roadmap_item ON actions(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- Ein Plan pro Initiative
|
||||||
|
INSERT INTO roadmaps (tenant_id, initiative_id, title)
|
||||||
|
SELECT tenant_id, id, 'Plan' FROM initiatives;
|
||||||
|
|
||||||
|
-- Bestehende Meilensteine → RoadmapItems (IDs beibehalten für Evidence/Review-FKs)
|
||||||
|
INSERT INTO roadmap_items (
|
||||||
|
id, tenant_id, roadmap_id, item_type, title, goal_description, status,
|
||||||
|
sequencing_mode, target_date, sort_order, created_at, updated_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
m.id,
|
||||||
|
m.tenant_id,
|
||||||
|
r.id,
|
||||||
|
'milestone',
|
||||||
|
m.title,
|
||||||
|
m.goal_description,
|
||||||
|
m.status,
|
||||||
|
'sequential',
|
||||||
|
m.target_date,
|
||||||
|
0,
|
||||||
|
m.created_at,
|
||||||
|
m.updated_at
|
||||||
|
FROM milestones m
|
||||||
|
JOIN roadmaps r ON r.initiative_id = m.initiative_id AND r.tenant_id = m.tenant_id;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
-- AP1.4b: Plan-Ist-Verknüpfung für Evidence und Reviews
|
||||||
|
|
||||||
|
ALTER TABLE evidence
|
||||||
|
ADD COLUMN roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
ALTER TABLE reviews
|
||||||
|
ADD COLUMN roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_evidence_roadmap_item ON evidence(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
|
CREATE INDEX idx_reviews_roadmap_item ON reviews(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- Bestehende milestone_id-Verknüpfungen spiegeln (RoadmapItem behält oft dieselbe UUID)
|
||||||
|
UPDATE evidence e
|
||||||
|
SET roadmap_item_id = e.milestone_id
|
||||||
|
WHERE e.milestone_id IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM roadmap_items ri
|
||||||
|
WHERE ri.id = e.milestone_id AND ri.tenant_id = e.tenant_id
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE reviews r
|
||||||
|
SET roadmap_item_id = r.milestone_id
|
||||||
|
WHERE r.milestone_id IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM roadmap_items ri
|
||||||
|
WHERE ri.id = r.milestone_id AND ri.tenant_id = r.tenant_id
|
||||||
|
);
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
-- AP1.4b: Gate-Checkliste (Prüfplan pro RoadmapItem)
|
||||||
|
|
||||||
|
CREATE TABLE roadmap_item_criteria (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
roadmap_item_id UUID NOT NULL REFERENCES roadmap_items(id) ON DELETE CASCADE,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
criterion_kind VARCHAR(32) NOT NULL DEFAULT 'evidence_required'
|
||||||
|
CHECK (criterion_kind IN ('manual', 'evidence_required', 'review_required', 'metric')),
|
||||||
|
verification_hint TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'satisfied', 'waived', 'deferred', 'failed')),
|
||||||
|
waived_or_deferred_decision_id UUID NULL REFERENCES decisions(id) ON DELETE SET NULL,
|
||||||
|
satisfied_by_evidence_id UUID NULL REFERENCES evidence(id) ON DELETE SET NULL,
|
||||||
|
satisfied_at TIMESTAMPTZ NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmap_criteria_item ON roadmap_item_criteria(tenant_id, roadmap_item_id);
|
||||||
|
CREATE INDEX idx_roadmap_criteria_status ON roadmap_item_criteria(tenant_id, status);
|
||||||
|
|
||||||
|
-- Compat: Default-Kriterium pro bestehendem Plan-Element
|
||||||
|
INSERT INTO roadmap_item_criteria (
|
||||||
|
tenant_id, roadmap_item_id, sort_order, title, description, criterion_kind, status
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
ri.tenant_id,
|
||||||
|
ri.id,
|
||||||
|
0,
|
||||||
|
'Gate allgemein',
|
||||||
|
COALESCE(NULLIF(ri.goal_description, ''), 'Akzeptierter Nachweis oder abgeschlossenes Review am Plan-Element.'),
|
||||||
|
'evidence_required',
|
||||||
|
'open'
|
||||||
|
FROM roadmap_items ri;
|
||||||
|
|
||||||
|
-- Bereits vorhandene accepted Evidence → Default-Kriterium satisfied
|
||||||
|
UPDATE roadmap_item_criteria ric
|
||||||
|
SET
|
||||||
|
status = 'satisfied',
|
||||||
|
satisfied_at = NOW(),
|
||||||
|
satisfied_by_evidence_id = sub.evidence_id
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT ON (ric2.id)
|
||||||
|
ric2.id AS criterion_id,
|
||||||
|
e.id AS evidence_id
|
||||||
|
FROM roadmap_item_criteria ric2
|
||||||
|
JOIN evidence e
|
||||||
|
ON e.tenant_id = ric2.tenant_id
|
||||||
|
AND e.roadmap_item_id = ric2.roadmap_item_id
|
||||||
|
AND e.status = 'accepted'
|
||||||
|
WHERE ric2.title = 'Gate allgemein'
|
||||||
|
ORDER BY ric2.id, e.updated_at DESC
|
||||||
|
) sub
|
||||||
|
WHERE ric.id = sub.criterion_id;
|
||||||
|
|
||||||
|
-- Bereits reached Gates ohne Evidence: Review completed
|
||||||
|
UPDATE roadmap_item_criteria ric
|
||||||
|
SET status = 'satisfied', satisfied_at = NOW()
|
||||||
|
FROM roadmap_items ri
|
||||||
|
WHERE ric.roadmap_item_id = ri.id
|
||||||
|
AND ric.tenant_id = ri.tenant_id
|
||||||
|
AND ric.title = 'Gate allgemein'
|
||||||
|
AND ric.status = 'open'
|
||||||
|
AND ri.status = 'reached'
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM reviews rev
|
||||||
|
WHERE rev.tenant_id = ri.tenant_id
|
||||||
|
AND rev.initiative_id IN (
|
||||||
|
SELECT r.initiative_id FROM roadmaps r WHERE r.id = ri.roadmap_id
|
||||||
|
)
|
||||||
|
AND rev.status = 'completed'
|
||||||
|
AND (rev.roadmap_item_id = ri.id OR rev.milestone_id = ri.id)
|
||||||
|
);
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- AP1.5: Project, Task, Action.project_id — operative Ist-Hierarchie
|
||||||
|
|
||||||
|
CREATE TABLE projects (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||||
|
CHECK (status IN ('active', 'paused', 'completed', 'archived')),
|
||||||
|
roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
target_date DATE NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_projects_tenant_initiative ON projects(tenant_id, initiative_id);
|
||||||
|
CREATE INDEX idx_projects_tenant_status ON projects(tenant_id, status);
|
||||||
|
CREATE INDEX idx_projects_roadmap_item ON projects(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN project_id UUID NULL REFERENCES projects(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_actions_project ON actions(tenant_id, project_id)
|
||||||
|
WHERE project_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE TABLE tasks (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'in_progress', 'done', 'discarded')),
|
||||||
|
roadmap_item_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
due_at TIMESTAMPTZ NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_tasks_tenant_action ON tasks(tenant_id, action_id);
|
||||||
|
CREATE INDEX idx_tasks_tenant_status ON tasks(tenant_id, status);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- AP1.5c: Rekursive Projects (parent_project_id, container_kind)
|
||||||
|
|
||||||
|
ALTER TABLE projects
|
||||||
|
ADD COLUMN parent_project_id UUID NULL REFERENCES projects(id) ON DELETE SET NULL,
|
||||||
|
ADD COLUMN container_kind VARCHAR(32) NULL
|
||||||
|
CHECK (
|
||||||
|
container_kind IS NULL
|
||||||
|
OR container_kind IN ('project', 'stream', 'phase', 'release')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_projects_parent ON projects(tenant_id, parent_project_id)
|
||||||
|
WHERE parent_project_id IS NOT NULL;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- AP1.12c: Backlog sort_order für Reorder im Plan-Modus
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
(ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY tenant_id, initiative_id
|
||||||
|
ORDER BY created_at ASC, id ASC
|
||||||
|
) - 1) * 10 AS next_order
|
||||||
|
FROM backlog_items
|
||||||
|
)
|
||||||
|
UPDATE backlog_items bi
|
||||||
|
SET sort_order = ranked.next_order
|
||||||
|
FROM ranked
|
||||||
|
WHERE bi.id = ranked.id;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_backlog_items_sort
|
||||||
|
ON backlog_items (tenant_id, initiative_id, sort_order);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- AP1.10a: Initiative Standardfelder + Archetyp-Schlüssel
|
||||||
|
|
||||||
|
ALTER TABLE initiatives
|
||||||
|
ADD COLUMN IF NOT EXISTS vision TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
ALTER TABLE initiatives
|
||||||
|
ADD COLUMN IF NOT EXISTS target_state_summary TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
ALTER TABLE initiatives
|
||||||
|
ADD COLUMN IF NOT EXISTS archetype_key VARCHAR(64) NOT NULL DEFAULT 'initiative.generic';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_initiatives_archetype
|
||||||
|
ON initiatives (tenant_id, archetype_key);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_initiatives_status_tenant
|
||||||
|
ON initiatives (tenant_id, status);
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
-- AP1.10b: Entity Field System (EFS) — Archetypen, Felddefinitionen, Werte
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS entity_archetypes (
|
||||||
|
archetype_key VARCHAR(64) PRIMARY KEY,
|
||||||
|
entity_type VARCHAR(64) NOT NULL,
|
||||||
|
label VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
is_system BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entity_archetypes_entity_type
|
||||||
|
ON entity_archetypes (entity_type);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS field_definitions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
archetype_key VARCHAR(64) NOT NULL
|
||||||
|
REFERENCES entity_archetypes (archetype_key) ON DELETE CASCADE,
|
||||||
|
field_key VARCHAR(64) NOT NULL,
|
||||||
|
field_type VARCHAR(32) NOT NULL
|
||||||
|
CHECK (field_type IN (
|
||||||
|
'text', 'longtext', 'number', 'boolean', 'date', 'enum', 'actor_ref', 'url'
|
||||||
|
)),
|
||||||
|
label VARCHAR(255) NOT NULL,
|
||||||
|
required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
searchable BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
validation_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (archetype_key, field_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_field_definitions_archetype
|
||||||
|
ON field_definitions (archetype_key, sort_order);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS field_values (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants (id) ON DELETE CASCADE,
|
||||||
|
entity_type VARCHAR(64) NOT NULL,
|
||||||
|
entity_id UUID NOT NULL,
|
||||||
|
field_key VARCHAR(64) NOT NULL,
|
||||||
|
value_json JSONB,
|
||||||
|
value_text TEXT NOT NULL DEFAULT '',
|
||||||
|
value_number NUMERIC,
|
||||||
|
value_boolean BOOLEAN,
|
||||||
|
value_date DATE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, entity_type, entity_id, field_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_field_values_entity
|
||||||
|
ON field_values (tenant_id, entity_type, entity_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_field_values_search
|
||||||
|
ON field_values (tenant_id, entity_type, field_key)
|
||||||
|
WHERE value_text <> '';
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- AP1.5d: Rekursive Tasks unter Action
|
||||||
|
|
||||||
|
ALTER TABLE tasks
|
||||||
|
ADD COLUMN IF NOT EXISTS parent_task_id UUID NULL
|
||||||
|
REFERENCES tasks (id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_tasks_parent
|
||||||
|
ON tasks (tenant_id, parent_task_id)
|
||||||
|
WHERE parent_task_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_tasks_action_parent
|
||||||
|
ON tasks (tenant_id, action_id, parent_task_id);
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
-- AP2.0b: Project archetype_key (Spiegel der Initiative)
|
||||||
|
|
||||||
|
ALTER TABLE projects
|
||||||
|
ADD COLUMN IF NOT EXISTS archetype_key VARCHAR(64) NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_projects_archetype
|
||||||
|
ON projects (tenant_id, archetype_key)
|
||||||
|
WHERE archetype_key IS NOT NULL;
|
||||||
|
|
||||||
|
-- Bestehende Projects: Mirror aus Initiative (einmalig)
|
||||||
|
UPDATE projects p
|
||||||
|
SET archetype_key = CASE i.archetype_key
|
||||||
|
WHEN 'initiative.generic' THEN 'project.generic'
|
||||||
|
WHEN 'initiative.maturity_journey' THEN 'project.maturity_journey'
|
||||||
|
WHEN 'initiative.linear_project' THEN 'project.linear_project'
|
||||||
|
WHEN 'initiative.recurring_program' THEN 'project.recurring_program'
|
||||||
|
WHEN 'initiative.support_queue' THEN 'project.support_queue'
|
||||||
|
WHEN 'initiative.program' THEN 'project.program'
|
||||||
|
WHEN 'initiative.product' THEN 'project.product'
|
||||||
|
WHEN 'initiative.dispute_case' THEN 'project.dispute_case'
|
||||||
|
WHEN 'initiative.content_project' THEN 'project.content_project'
|
||||||
|
ELSE 'project.generic'
|
||||||
|
END
|
||||||
|
FROM initiatives i
|
||||||
|
WHERE p.initiative_id = i.id
|
||||||
|
AND p.tenant_id = i.tenant_id
|
||||||
|
AND p.archetype_key IS NULL;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- AP1.4d: Graph Engine — erweiterte Kantenarten + Parallelgruppe
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_item_dependencies
|
||||||
|
DROP CONSTRAINT IF EXISTS roadmap_item_dependencies_dependency_type_check;
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_item_dependencies
|
||||||
|
ADD CONSTRAINT roadmap_item_dependencies_dependency_type_check
|
||||||
|
CHECK (dependency_type IN (
|
||||||
|
'requires', 'blocks', 'related', 'parallel_group', 'optional_branch'
|
||||||
|
));
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_item_dependencies
|
||||||
|
ADD COLUMN IF NOT EXISTS group_key VARCHAR(128) NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmap_deps_group_key
|
||||||
|
ON roadmap_item_dependencies(tenant_id, group_key)
|
||||||
|
WHERE group_key IS NOT NULL;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- AP1.14: Plan-Snapshots (Plan-Revision) — Soll-Zustand getrennt von Ist
|
||||||
|
|
||||||
|
CREATE TABLE roadmap_plan_snapshots (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
roadmap_id UUID NOT NULL REFERENCES roadmaps(id) ON DELETE CASCADE,
|
||||||
|
revision_number INT NOT NULL,
|
||||||
|
reason TEXT NOT NULL DEFAULT '',
|
||||||
|
plan_payload JSONB NOT NULL,
|
||||||
|
created_by_user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, initiative_id, revision_number)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_roadmap_plan_snapshots_initiative
|
||||||
|
ON roadmap_plan_snapshots(tenant_id, initiative_id, created_at DESC);
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
-- AP1.8a: Portfolio-Priorität (relatives Ranking im Tenant)
|
||||||
|
|
||||||
|
ALTER TABLE initiatives
|
||||||
|
ADD COLUMN IF NOT EXISTS portfolio_rank INT;
|
||||||
|
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY tenant_id
|
||||||
|
ORDER BY updated_at DESC, title
|
||||||
|
) - 1 AS rn
|
||||||
|
FROM initiatives
|
||||||
|
)
|
||||||
|
UPDATE initiatives AS i
|
||||||
|
SET portfolio_rank = ranked.rn
|
||||||
|
FROM ranked
|
||||||
|
WHERE i.id = ranked.id AND i.portfolio_rank IS NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_initiatives_tenant_portfolio_rank
|
||||||
|
ON initiatives (tenant_id, portfolio_rank);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN initiatives.portfolio_rank IS
|
||||||
|
'Relatives Portfolio-Ranking (0 = höchste Aufmerksamkeit). AP1.8a';
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- AP1.16a: Durchführungsplan — Action-Reihenfolge, kind, Abhängigkeiten
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN IF NOT EXISTS action_kind VARCHAR(32) NOT NULL DEFAULT 'delivery'
|
||||||
|
CHECK (action_kind IN ('delivery', 'planning', 'review'));
|
||||||
|
|
||||||
|
CREATE INDEX idx_actions_initiative_sort
|
||||||
|
ON actions(tenant_id, initiative_id, sort_order);
|
||||||
|
|
||||||
|
CREATE TABLE action_dependencies (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||||
|
predecessor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||||
|
successor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||||
|
dependency_kind VARCHAR(32) NOT NULL DEFAULT 'requires'
|
||||||
|
CHECK (dependency_kind IN ('requires', 'blocks', 'relates')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, predecessor_action_id, successor_action_id, dependency_kind)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_action_deps_predecessor
|
||||||
|
ON action_dependencies(tenant_id, predecessor_action_id);
|
||||||
|
|
||||||
|
CREATE INDEX idx_action_deps_successor
|
||||||
|
ON action_dependencies(tenant_id, successor_action_id);
|
||||||
|
|
||||||
|
CREATE INDEX idx_action_deps_initiative
|
||||||
|
ON action_dependencies(tenant_id, initiative_id);
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- AP1.7c — Actor Service Tokens für Operational API (Vibe-Coder / Agenten)
|
||||||
|
|
||||||
|
CREATE TABLE actor_service_tokens (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
actor_id UUID NOT NULL REFERENCES actors(id) ON DELETE CASCADE,
|
||||||
|
label VARCHAR(255) NOT NULL,
|
||||||
|
token_prefix VARCHAR(16) NOT NULL,
|
||||||
|
token_hash VARCHAR(64) NOT NULL,
|
||||||
|
capabilities JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
expires_at TIMESTAMPTZ NULL,
|
||||||
|
last_used_at TIMESTAMPTZ NULL,
|
||||||
|
created_by_user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
revoked_at TIMESTAMPTZ NULL,
|
||||||
|
UNIQUE (token_prefix)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_actor_service_tokens_tenant ON actor_service_tokens(tenant_id);
|
||||||
|
CREATE INDEX idx_actor_service_tokens_actor ON actor_service_tokens(actor_id);
|
||||||
|
CREATE INDEX idx_actor_service_tokens_hash ON actor_service_tokens(token_hash);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- AP2.0f — work_cycle (Zeitbox/Sprint) + actions.work_cycle_id
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_items DROP CONSTRAINT IF EXISTS roadmap_items_item_type_check;
|
||||||
|
ALTER TABLE roadmap_items ADD CONSTRAINT roadmap_items_item_type_check
|
||||||
|
CHECK (item_type IN ('milestone', 'review_gate', 'maturity_stage', 'work_cycle'));
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN work_cycle_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_actions_work_cycle ON actions(tenant_id, work_cycle_id)
|
||||||
|
WHERE work_cycle_id IS NOT NULL;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- AP2.2e: Sprint-Planung — Item-Arten, Feature-Referenz, Unplan-Support
|
||||||
|
|
||||||
|
ALTER TABLE actions DROP CONSTRAINT IF EXISTS actions_action_kind_check;
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD CONSTRAINT actions_action_kind_check
|
||||||
|
CHECK (action_kind IN ('delivery', 'planning', 'review', 'bug', 'issue'));
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN IF NOT EXISTS parent_action_id UUID NULL
|
||||||
|
REFERENCES actions (id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_actions_parent
|
||||||
|
ON actions (tenant_id, initiative_id, parent_action_id)
|
||||||
|
WHERE parent_action_id IS NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD COLUMN IF NOT EXISTS item_kind VARCHAR(32) NOT NULL DEFAULT 'story'
|
||||||
|
CHECK (item_kind IN ('story', 'bug', 'issue'));
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD COLUMN IF NOT EXISTS parent_action_id UUID NULL
|
||||||
|
REFERENCES actions (id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_backlog_parent_action
|
||||||
|
ON backlog_items (tenant_id, initiative_id, parent_action_id)
|
||||||
|
WHERE parent_action_id IS NOT NULL;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- AP2.3a: UI-Profil pro Archetyp (Registry-Sync → Frontend Operating Context)
|
||||||
|
|
||||||
|
ALTER TABLE entity_archetypes
|
||||||
|
ADD COLUMN IF NOT EXISTS ui_profile_json JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- AP2.2f / ADP Backlog Epic-Hierarchie — parent_backlog_id + item_kind epic
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD COLUMN IF NOT EXISTS parent_backlog_id UUID NULL
|
||||||
|
REFERENCES backlog_items (id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_backlog_parent_backlog
|
||||||
|
ON backlog_items (tenant_id, initiative_id, parent_backlog_id)
|
||||||
|
WHERE parent_backlog_id IS NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD CONSTRAINT backlog_items_item_kind_check
|
||||||
|
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic'));
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- P7: Technische Schuld — item_kind / action_kind tech_debt
|
||||||
|
|
||||||
|
ALTER TABLE actions DROP CONSTRAINT IF EXISTS actions_action_kind_check;
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD CONSTRAINT actions_action_kind_check
|
||||||
|
CHECK (action_kind IN ('delivery', 'planning', 'review', 'bug', 'issue', 'tech_debt'));
|
||||||
|
|
||||||
|
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
|
||||||
|
ALTER TABLE backlog_items
|
||||||
|
ADD CONSTRAINT backlog_items_item_kind_check
|
||||||
|
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic', 'tech_debt'));
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- AP A1.1 — CadenceInstance (minimal): eine offene Instanz pro Recurring, Tages-Tracking
|
||||||
|
|
||||||
|
CREATE TABLE cadence_instances (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
recurring_element_id UUID NOT NULL REFERENCES recurring_elements(id) ON DELETE CASCADE,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'completed')),
|
||||||
|
due_at TIMESTAMPTZ NOT NULL,
|
||||||
|
completed_at TIMESTAMPTZ NULL,
|
||||||
|
measurement_note TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_cadence_instances_tenant_recurring
|
||||||
|
ON cadence_instances(tenant_id, recurring_element_id);
|
||||||
|
|
||||||
|
CREATE INDEX idx_cadence_instances_open_due
|
||||||
|
ON cadence_instances(tenant_id, due_at)
|
||||||
|
WHERE status = 'open';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX idx_cadence_instances_one_open_per_recurring
|
||||||
|
ON cadence_instances(recurring_element_id)
|
||||||
|
WHERE status = 'open';
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- AP A1.2 — RecurringElement an Reifegrad-Stufe binden (Activity Set)
|
||||||
|
|
||||||
|
ALTER TABLE recurring_elements
|
||||||
|
ADD COLUMN roadmap_item_id UUID NULL
|
||||||
|
REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_recurring_elements_stage
|
||||||
|
ON recurring_elements(tenant_id, roadmap_item_id)
|
||||||
|
WHERE roadmap_item_id IS NOT NULL;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- AP-A1-PM-2: Progression graph — join_gate, strand binding, recurring strand
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_items
|
||||||
|
DROP CONSTRAINT IF EXISTS roadmap_items_item_type_check;
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_items
|
||||||
|
ADD CONSTRAINT roadmap_items_item_type_check
|
||||||
|
CHECK (item_type IN (
|
||||||
|
'milestone', 'review_gate', 'maturity_stage', 'work_cycle', 'join_gate'
|
||||||
|
));
|
||||||
|
|
||||||
|
ALTER TABLE roadmap_items
|
||||||
|
ADD COLUMN IF NOT EXISTS strand_project_id UUID NULL
|
||||||
|
REFERENCES projects(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_roadmap_items_strand
|
||||||
|
ON roadmap_items(tenant_id, strand_project_id)
|
||||||
|
WHERE strand_project_id IS NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE recurring_elements
|
||||||
|
ADD COLUMN IF NOT EXISTS project_id UUID NULL
|
||||||
|
REFERENCES projects(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_recurring_elements_project
|
||||||
|
ON recurring_elements(tenant_id, project_id)
|
||||||
|
WHERE project_id IS NOT NULL;
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
-- Unified Schedule & Cadence Layer (ADP v0.1)
|
||||||
|
|
||||||
|
CREATE TABLE schedules (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
schedule_kind VARCHAR(16) NOT NULL DEFAULT 'interval'
|
||||||
|
CHECK (schedule_kind IN ('interval', 'weekdays')),
|
||||||
|
interval_days INT NULL CHECK (interval_days IS NULL OR interval_days > 0),
|
||||||
|
weekday_mask INT NOT NULL DEFAULT 0,
|
||||||
|
pause_until DATE NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_schedules_tenant ON schedules(tenant_id);
|
||||||
|
|
||||||
|
ALTER TABLE recurring_elements
|
||||||
|
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
|
||||||
|
REFERENCES schedules(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
ALTER TABLE recurring_elements
|
||||||
|
ADD COLUMN IF NOT EXISTS action_id UUID NULL
|
||||||
|
REFERENCES actions(id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX idx_recurring_elements_action
|
||||||
|
ON recurring_elements(action_id)
|
||||||
|
WHERE action_id IS NOT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE actions
|
||||||
|
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
|
||||||
|
REFERENCES schedules(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
-- Backfill: one schedule per recurring without schedule_id
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
r RECORD;
|
||||||
|
sid UUID;
|
||||||
|
idays INT;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN
|
||||||
|
SELECT id, tenant_id, interval_days
|
||||||
|
FROM recurring_elements
|
||||||
|
WHERE schedule_id IS NULL
|
||||||
|
LOOP
|
||||||
|
idays := GREATEST(COALESCE(r.interval_days, 1), 1);
|
||||||
|
INSERT INTO schedules (tenant_id, schedule_kind, interval_days, weekday_mask)
|
||||||
|
VALUES (r.tenant_id, 'interval', idays, 0)
|
||||||
|
RETURNING id INTO sid;
|
||||||
|
UPDATE recurring_elements SET schedule_id = sid WHERE id = r.id;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Operational API auth — Session or Actor Service Token (AP1.7c)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, Header, HTTPException
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER, get_session
|
||||||
|
from capabilities import _enforce_capability
|
||||||
|
from services.actor_service_tokens import validate_service_token
|
||||||
|
from tenant_context import TenantContext, resolve_tenant_context
|
||||||
|
|
||||||
|
ACTOR_TOKEN_HEADER = "X-Actor-Token"
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_actor_token(
|
||||||
|
x_actor_token: Optional[str],
|
||||||
|
authorization: Optional[str],
|
||||||
|
) -> Optional[str]:
|
||||||
|
if x_actor_token and x_actor_token.strip():
|
||||||
|
return x_actor_token.strip()
|
||||||
|
if authorization:
|
||||||
|
scheme, _, value = authorization.partition(" ")
|
||||||
|
if scheme.lower() == "bearer" and value.strip():
|
||||||
|
return value.strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_service_token_context(raw_token: str) -> TenantContext:
|
||||||
|
resolved = validate_service_token(raw_token)
|
||||||
|
if not resolved:
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültiger oder abgelaufener Actor-Token")
|
||||||
|
|
||||||
|
return TenantContext(
|
||||||
|
user_id="",
|
||||||
|
email="",
|
||||||
|
display_name=resolved["actor_name"],
|
||||||
|
portal_role="",
|
||||||
|
tenant_id=resolved["tenant_id"],
|
||||||
|
tenant_slug=resolved["tenant_slug"],
|
||||||
|
tenant_name=resolved["tenant_name"],
|
||||||
|
tenant_role=None,
|
||||||
|
actor_id=resolved["actor_id"],
|
||||||
|
actor_type=resolved["actor_type"],
|
||||||
|
session_token="",
|
||||||
|
capabilities=resolved["capabilities"],
|
||||||
|
auth_source="service_token",
|
||||||
|
service_token_id=resolved["token_id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_operational_context(
|
||||||
|
x_actor_token: Optional[str] = Header(default=None, alias=ACTOR_TOKEN_HEADER),
|
||||||
|
authorization: Optional[str] = Header(default=None),
|
||||||
|
x_auth_token: Optional[str] = Header(default=None, alias=AUTH_HEADER),
|
||||||
|
) -> TenantContext:
|
||||||
|
actor_token = _extract_actor_token(x_actor_token, authorization)
|
||||||
|
if actor_token:
|
||||||
|
return resolve_service_token_context(actor_token)
|
||||||
|
|
||||||
|
session_token = (x_auth_token or "").strip()
|
||||||
|
if not session_token:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Authentifizierung erforderlich (X-Actor-Token oder X-Auth-Token)",
|
||||||
|
)
|
||||||
|
session = get_session(session_token)
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültige Session")
|
||||||
|
ctx = resolve_tenant_context(session)
|
||||||
|
if not ctx.tenant_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein aktiver Tenant — Tenant wählen")
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def require_operational_capability(capability_key: str) -> Callable[..., TenantContext]:
|
||||||
|
"""Service tokens: always enforce. Sessions: probe/enforce per CAPABILITY_ENFORCE."""
|
||||||
|
|
||||||
|
def _dependency(
|
||||||
|
ctx: TenantContext = Depends(get_operational_context),
|
||||||
|
) -> TenantContext:
|
||||||
|
if ctx.auth_source == "service_token":
|
||||||
|
if capability_key not in ctx.capabilities:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=f"Capability fehlt auf Service Token: {capability_key}",
|
||||||
|
)
|
||||||
|
return ctx
|
||||||
|
return _enforce_capability(ctx, capability_key)
|
||||||
|
|
||||||
|
return _dependency
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for placeholder registrations."""
|
||||||
|
|
||||||
|
from placeholder_registrations import actor_context, debug, tenant_context # noqa: F401
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Actor context placeholders."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.actor_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Actors", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des Tenants", required=True)
|
||||||
|
)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""Debug context placeholders."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.debug_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("debug_message", _CTX, "string", "Freier Debug-Text", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("debug_level", _CTX, "string", "Log-Level oder Kategorie", required=False)
|
||||||
|
)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""TenantContext placeholders for prompt rendering."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.tenant_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_name", _CTX, "string", "Name des aktiven Tenants", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des aktiven Tenants", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_name", _CTX, "string", "Anzeigename des Human Actors", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Human Actors", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ (z. B. human)", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("portal_role", _CTX, "string", "Portal-Rolle des Users", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_role", _CTX, "string", "Tenant-Rolle in der Membership", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration(
|
||||||
|
"capabilities",
|
||||||
|
_CTX,
|
||||||
|
"json",
|
||||||
|
"Aufgelöste Capability-Keys als JSON-Array",
|
||||||
|
required=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""Placeholder definitions registry with DB sync."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from feature_registry import VALID_CONTEXT_KINDS
|
||||||
|
|
||||||
|
VALID_VALUE_TYPES = frozenset({"string", "number", "boolean", "object", "array", "json"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PlaceholderRegistration:
|
||||||
|
placeholder_key: str
|
||||||
|
context_kind: str
|
||||||
|
value_type: str
|
||||||
|
description: str
|
||||||
|
required: bool = False
|
||||||
|
source: str = "input"
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: list[PlaceholderRegistration] = []
|
||||||
|
|
||||||
|
|
||||||
|
def register_placeholder(registration: PlaceholderRegistration) -> None:
|
||||||
|
if not registration.placeholder_key or not registration.placeholder_key.strip():
|
||||||
|
raise ValueError("Placeholder key is required")
|
||||||
|
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||||
|
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||||
|
if registration.value_type not in VALID_VALUE_TYPES:
|
||||||
|
raise ValueError(f"Unknown value_type: {registration.value_type}")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Placeholder description is required")
|
||||||
|
key = (registration.placeholder_key, registration.context_kind)
|
||||||
|
if any((r.placeholder_key, r.context_kind) == key for r in _REGISTRY):
|
||||||
|
raise ValueError(f"Placeholder already registered: {key}")
|
||||||
|
_REGISTRY.append(registration)
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_placeholders() -> tuple[PlaceholderRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_placeholder_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_placeholders_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[placeholder_registry] Keine Placeholder registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO placeholder_definitions (
|
||||||
|
placeholder_key, context_kind, value_type, description,
|
||||||
|
required, source, is_active
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (placeholder_key, context_kind) DO UPDATE SET
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
required = EXCLUDED.required,
|
||||||
|
source = EXCLUDED.source,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
reg.placeholder_key,
|
||||||
|
reg.context_kind,
|
||||||
|
reg.value_type,
|
||||||
|
reg.description,
|
||||||
|
reg.required,
|
||||||
|
reg.source,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[placeholder_registry] Sync OK — {len(_REGISTRY)} Placeholder(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[placeholder_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_placeholders_for_context(context_kind: str) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT placeholder_key, value_type, description, required, source
|
||||||
|
FROM placeholder_definitions
|
||||||
|
WHERE context_kind = %s AND is_active = TRUE
|
||||||
|
ORDER BY placeholder_key
|
||||||
|
""",
|
||||||
|
(context_kind,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"placeholder_key": row[0],
|
||||||
|
"value_type": row[1],
|
||||||
|
"description": row[2],
|
||||||
|
"required": row[3],
|
||||||
|
"source": row[4],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Build placeholder value maps from TenantContext."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def build_tenant_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"tenant_name": ctx.tenant_name or "",
|
||||||
|
"tenant_id": ctx.tenant_id or "",
|
||||||
|
"actor_name": ctx.display_name,
|
||||||
|
"actor_id": ctx.actor_id or "",
|
||||||
|
"actor_type": ctx.actor_type or "",
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"tenant_role": ctx.tenant_role or "",
|
||||||
|
"capabilities": sorted(ctx.capabilities),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_actor_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"actor_id": ctx.actor_id or "",
|
||||||
|
"actor_type": ctx.actor_type or "",
|
||||||
|
"tenant_id": ctx.tenant_id or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def merge_context_values(ctx: TenantContext, context_kind: str, extra: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
base: dict[str, Any] = {}
|
||||||
|
if context_kind == "kairo.tenant_context":
|
||||||
|
base = build_tenant_context_values(ctx)
|
||||||
|
elif context_kind == "kairo.actor_context":
|
||||||
|
base = build_actor_context_values(ctx)
|
||||||
|
merged = {**base, **extra}
|
||||||
|
for key, value in merged.items():
|
||||||
|
if key == "capabilities" and isinstance(value, list):
|
||||||
|
merged[key] = value
|
||||||
|
elif isinstance(value, (dict, list)) and key != "capabilities":
|
||||||
|
continue
|
||||||
|
return merged
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for prompt registrations."""
|
||||||
|
|
||||||
|
from prompt_registrations import debug, platform # noqa: F401
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Debug prompts for actor context kind."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from prompt_registry import PromptRegistration, PromptVersionRegistration, register_prompt
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.actor.debug_summary",
|
||||||
|
name="Actor Context Debug",
|
||||||
|
purpose="Minimaler Prompt für kairo.actor_context",
|
||||||
|
context_kind="kairo.actor_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body="Actor {{actor_id}} ({{actor_type}}) in tenant {{tenant_id}}.",
|
||||||
|
changelog="Actor context smoke",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Technical smoke-test prompts — no product logic."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from prompt_registry import (
|
||||||
|
PromptRegistration,
|
||||||
|
PromptStepRegistration,
|
||||||
|
PromptVersionRegistration,
|
||||||
|
register_prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.system.health_summary",
|
||||||
|
name="System Health Summary",
|
||||||
|
purpose="Smoke-Test für Registry, Versionierung und Rendering",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body="",
|
||||||
|
changelog="Initial smoke prompt",
|
||||||
|
steps=(
|
||||||
|
PromptStepRegistration(
|
||||||
|
step_key="summary",
|
||||||
|
step_order=0,
|
||||||
|
step_type="template",
|
||||||
|
template_body=(
|
||||||
|
"Kairo Systemstatus: {{debug_message}} "
|
||||||
|
"(Level: {{debug_level}})"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.context.debug_summary",
|
||||||
|
name="Tenant Context Debug Summary",
|
||||||
|
purpose="Smoke-Test für TenantContext-Placeholder",
|
||||||
|
context_kind="kairo.tenant_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body=(
|
||||||
|
"Tenant {{tenant_name}} ({{tenant_id}}): "
|
||||||
|
"Portal={{portal_role}}, Tenant-Rolle={{tenant_role}}, "
|
||||||
|
"Actor={{actor_id}} ({{actor_type}})."
|
||||||
|
),
|
||||||
|
changelog="Initial tenant context prompt",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Pipeline/workflow structural sample — not executed in AP0.4
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.pipeline.placeholder",
|
||||||
|
name="Pipeline Placeholder",
|
||||||
|
purpose="Strukturelle Vorbereitung für pipeline execution_mode",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
execution_mode="pipeline",
|
||||||
|
active_version="0.1.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="0.1.0",
|
||||||
|
body="Pipeline placeholder: {{debug_message}}",
|
||||||
|
changelog="Not executed in AP0.4",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
"""Prompt definition registry with versioning and optional steps."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from feature_registry import VALID_CONTEXT_KINDS, VALID_EXECUTION_MODES
|
||||||
|
|
||||||
|
VALID_STEP_TYPES = frozenset(
|
||||||
|
{"template", "resolver", "llm_call", "postprocess", "validation"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptStepRegistration:
|
||||||
|
step_key: str
|
||||||
|
step_order: int
|
||||||
|
step_type: str
|
||||||
|
template_body: str
|
||||||
|
input_mapping: dict | None = None
|
||||||
|
output_mapping: dict | None = None
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptVersionRegistration:
|
||||||
|
version: str
|
||||||
|
body: str
|
||||||
|
input_schema: dict | None = None
|
||||||
|
output_schema: dict | None = None
|
||||||
|
model_policy_key: str | None = None
|
||||||
|
changelog: str = ""
|
||||||
|
steps: tuple[PromptStepRegistration, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptRegistration:
|
||||||
|
prompt_key: str
|
||||||
|
name: str
|
||||||
|
purpose: str
|
||||||
|
context_kind: str
|
||||||
|
execution_mode: str
|
||||||
|
active_version: str
|
||||||
|
versions: tuple[PromptVersionRegistration, ...]
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, PromptRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_prompt(registration: PromptRegistration) -> None:
|
||||||
|
if not registration.prompt_key or not registration.prompt_key.strip():
|
||||||
|
raise ValueError("Prompt key is required")
|
||||||
|
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||||
|
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||||
|
if registration.execution_mode not in VALID_EXECUTION_MODES:
|
||||||
|
raise ValueError(f"Unknown execution_mode: {registration.execution_mode}")
|
||||||
|
if not registration.versions:
|
||||||
|
raise ValueError("At least one prompt version is required")
|
||||||
|
version_ids = {v.version for v in registration.versions}
|
||||||
|
if registration.active_version not in version_ids:
|
||||||
|
raise ValueError(f"active_version not found in versions: {registration.active_version}")
|
||||||
|
for step in _iter_steps(registration):
|
||||||
|
if step.step_type not in VALID_STEP_TYPES:
|
||||||
|
raise ValueError(f"Unknown step_type: {step.step_type}")
|
||||||
|
if registration.prompt_key in _REGISTRY:
|
||||||
|
raise ValueError(f"Prompt already registered: {registration.prompt_key}")
|
||||||
|
_REGISTRY[registration.prompt_key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_steps(registration: PromptRegistration):
|
||||||
|
for version in registration.versions:
|
||||||
|
yield from version.steps
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_prompts() -> tuple[PromptRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_prompt_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_prompts_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[prompt_registry] Keine Prompts registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_definitions (
|
||||||
|
prompt_key, name, purpose, context_kind, execution_mode, status
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, 'active')
|
||||||
|
ON CONFLICT (prompt_key) DO UPDATE SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
purpose = EXCLUDED.purpose,
|
||||||
|
context_kind = EXCLUDED.context_kind,
|
||||||
|
execution_mode = EXCLUDED.execution_mode,
|
||||||
|
status = 'active',
|
||||||
|
updated_at = NOW()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
reg.prompt_key,
|
||||||
|
reg.name,
|
||||||
|
reg.purpose,
|
||||||
|
reg.context_kind,
|
||||||
|
reg.execution_mode,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
definition_id = cur.fetchone()[0]
|
||||||
|
|
||||||
|
active_version_id = None
|
||||||
|
for version in reg.versions:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_versions (
|
||||||
|
prompt_definition_id, version, body,
|
||||||
|
input_schema, output_schema, model_policy_key, changelog
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s::jsonb, %s::jsonb, %s, %s)
|
||||||
|
ON CONFLICT (prompt_definition_id, version) DO UPDATE SET
|
||||||
|
body = EXCLUDED.body,
|
||||||
|
input_schema = EXCLUDED.input_schema,
|
||||||
|
output_schema = EXCLUDED.output_schema,
|
||||||
|
model_policy_key = EXCLUDED.model_policy_key,
|
||||||
|
changelog = EXCLUDED.changelog
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
definition_id,
|
||||||
|
version.version,
|
||||||
|
version.body,
|
||||||
|
json.dumps(version.input_schema) if version.input_schema else None,
|
||||||
|
json.dumps(version.output_schema) if version.output_schema else None,
|
||||||
|
version.model_policy_key,
|
||||||
|
version.changelog,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
version_id = cur.fetchone()[0]
|
||||||
|
if version.version == reg.active_version:
|
||||||
|
active_version_id = version_id
|
||||||
|
|
||||||
|
for step in version.steps:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_steps (
|
||||||
|
prompt_version_id, step_key, step_order, step_type,
|
||||||
|
template_body, input_mapping, output_mapping, enabled
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s::jsonb, %s)
|
||||||
|
ON CONFLICT (prompt_version_id, step_key) DO UPDATE SET
|
||||||
|
step_order = EXCLUDED.step_order,
|
||||||
|
step_type = EXCLUDED.step_type,
|
||||||
|
template_body = EXCLUDED.template_body,
|
||||||
|
input_mapping = EXCLUDED.input_mapping,
|
||||||
|
output_mapping = EXCLUDED.output_mapping,
|
||||||
|
enabled = EXCLUDED.enabled,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
version_id,
|
||||||
|
step.step_key,
|
||||||
|
step.step_order,
|
||||||
|
step.step_type,
|
||||||
|
step.template_body,
|
||||||
|
json.dumps(step.input_mapping) if step.input_mapping else None,
|
||||||
|
json.dumps(step.output_mapping) if step.output_mapping else None,
|
||||||
|
step.enabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if active_version_id:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE prompt_definitions
|
||||||
|
SET active_version_id = %s, updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(active_version_id, definition_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
print(f"[prompt_registry] Sync OK — {len(_REGISTRY)} Prompt(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[prompt_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_prompt_definition(prompt_key: str) -> dict | None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, prompt_key, name, purpose, context_kind, execution_mode,
|
||||||
|
status, active_version_id
|
||||||
|
FROM prompt_definitions
|
||||||
|
WHERE prompt_key = %s
|
||||||
|
""",
|
||||||
|
(prompt_key,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": str(row[0]),
|
||||||
|
"prompt_key": row[1],
|
||||||
|
"name": row[2],
|
||||||
|
"purpose": row[3],
|
||||||
|
"context_kind": row[4],
|
||||||
|
"execution_mode": row[5],
|
||||||
|
"status": row[6],
|
||||||
|
"active_version_id": str(row[7]) if row[7] else None,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_active_prompt_version(definition: dict) -> dict | None:
|
||||||
|
version_id = definition.get("active_version_id")
|
||||||
|
if not version_id:
|
||||||
|
return None
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, version, body, input_schema, output_schema, model_policy_key
|
||||||
|
FROM prompt_versions
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(version_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": str(row[0]),
|
||||||
|
"version": row[1],
|
||||||
|
"body": row[2],
|
||||||
|
"input_schema": row[3],
|
||||||
|
"output_schema": row[4],
|
||||||
|
"model_policy_key": row[5],
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_template_steps(version_id: str) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT step_key, step_order, step_type, template_body, enabled
|
||||||
|
FROM prompt_steps
|
||||||
|
WHERE prompt_version_id = %s AND enabled = TRUE
|
||||||
|
ORDER BY step_order, step_key
|
||||||
|
""",
|
||||||
|
(version_id,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"step_key": row[0],
|
||||||
|
"step_order": row[1],
|
||||||
|
"step_type": row[2],
|
||||||
|
"template_body": row[3],
|
||||||
|
"enabled": row[4],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_prompt_definitions() -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT prompt_key, name, purpose, context_kind, execution_mode, status
|
||||||
|
FROM prompt_definitions
|
||||||
|
ORDER BY prompt_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"prompt_key": row[0],
|
||||||
|
"name": row[1],
|
||||||
|
"purpose": row[2],
|
||||||
|
"context_kind": row[3],
|
||||||
|
"execution_mode": row[4],
|
||||||
|
"status": row[5],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""Single-mode prompt rendering without LLM execution."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from prompt_registry import load_active_prompt_version, load_prompt_definition, load_template_steps
|
||||||
|
from prompt_validation import PLACEHOLDER_PATTERN, PlaceholderValidationError, validate_placeholder_input
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
PLACEHOLDER_SUB = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||||
|
|
||||||
|
|
||||||
|
class PromptRenderError(Exception):
|
||||||
|
def __init__(self, message: str, *, code: str = "render_error"):
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
def _render_template(template: str, values: dict[str, Any]) -> str:
|
||||||
|
def replacer(match: re.Match[str]) -> str:
|
||||||
|
key = match.group(1)
|
||||||
|
if key not in values:
|
||||||
|
return match.group(0)
|
||||||
|
value = values[key]
|
||||||
|
if isinstance(value, (dict, list)):
|
||||||
|
return json.dumps(value, ensure_ascii=False)
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
return PLACEHOLDER_SUB.sub(replacer, template)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_template_body(version: dict) -> tuple[str, str]:
|
||||||
|
"""Return (template_body, source) where source is 'body' or 'step'."""
|
||||||
|
steps = load_template_steps(version["id"])
|
||||||
|
template_steps = [s for s in steps if s["step_type"] == "template" and s["template_body"]]
|
||||||
|
if template_steps:
|
||||||
|
step = template_steps[0]
|
||||||
|
return step["template_body"], f"step:{step['step_key']}"
|
||||||
|
if version.get("body"):
|
||||||
|
return version["body"], "body"
|
||||||
|
raise PromptRenderError("No template body or template step found", code="no_template")
|
||||||
|
|
||||||
|
|
||||||
|
def _write_execution_log(
|
||||||
|
*,
|
||||||
|
definition: dict,
|
||||||
|
version: dict,
|
||||||
|
status: str,
|
||||||
|
rendered_preview: str | None,
|
||||||
|
input_summary: dict | None,
|
||||||
|
error_message: str | None,
|
||||||
|
user_id: str | None,
|
||||||
|
) -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_execution_logs (
|
||||||
|
prompt_definition_id, prompt_version_id, execution_mode,
|
||||||
|
status, rendered_preview, input_summary, error_message, created_by
|
||||||
|
)
|
||||||
|
VALUES (%s::uuid, %s::uuid, %s, %s, %s, %s::jsonb, %s, %s::uuid)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
definition["id"],
|
||||||
|
version["id"],
|
||||||
|
definition["execution_mode"],
|
||||||
|
status,
|
||||||
|
rendered_preview,
|
||||||
|
json.dumps(input_summary) if input_summary else None,
|
||||||
|
error_message,
|
||||||
|
user_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def render_prompt_single(
|
||||||
|
prompt_key: str,
|
||||||
|
*,
|
||||||
|
values: dict[str, Any],
|
||||||
|
user_id: str | None = None,
|
||||||
|
log_execution: bool = True,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
definition = load_prompt_definition(prompt_key)
|
||||||
|
if not definition:
|
||||||
|
raise PromptRenderError(f"Unknown prompt: {prompt_key}", code="not_found")
|
||||||
|
if definition["status"] != "active":
|
||||||
|
raise PromptRenderError(f"Prompt not active: {prompt_key}", code="inactive")
|
||||||
|
|
||||||
|
execution_mode = definition["execution_mode"]
|
||||||
|
if execution_mode in ("pipeline", "workflow"):
|
||||||
|
raise PromptRenderError(
|
||||||
|
f"execution_mode '{execution_mode}' is not implemented in AP0.4",
|
||||||
|
code="mode_not_implemented",
|
||||||
|
)
|
||||||
|
|
||||||
|
version = load_active_prompt_version(definition)
|
||||||
|
if not version:
|
||||||
|
raise PromptRenderError("No active prompt version", code="no_version")
|
||||||
|
|
||||||
|
template_body, template_source = _resolve_template_body(version)
|
||||||
|
|
||||||
|
try:
|
||||||
|
validation = validate_placeholder_input(
|
||||||
|
template=template_body,
|
||||||
|
context_kind=definition["context_kind"],
|
||||||
|
values=values,
|
||||||
|
)
|
||||||
|
rendered = _render_template(template_body, values)
|
||||||
|
result = {
|
||||||
|
"prompt_key": prompt_key,
|
||||||
|
"version": version["version"],
|
||||||
|
"execution_mode": execution_mode,
|
||||||
|
"template_source": template_source,
|
||||||
|
"rendered_text": rendered,
|
||||||
|
"validation": validation,
|
||||||
|
}
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="success",
|
||||||
|
rendered_preview=rendered[:2000],
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=None,
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
except PlaceholderValidationError as exc:
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="error",
|
||||||
|
rendered_preview=None,
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=str(exc),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
log_audit(
|
||||||
|
"prompt.render.failed",
|
||||||
|
user_id=user_id,
|
||||||
|
details={
|
||||||
|
"prompt_key": prompt_key,
|
||||||
|
"missing": exc.missing,
|
||||||
|
"type_errors": exc.type_errors,
|
||||||
|
"unknown": exc.unknown,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
raise PromptRenderError(str(exc), code="validation_failed") from exc
|
||||||
|
except PromptRenderError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="error",
|
||||||
|
rendered_preview=None,
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=str(exc),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
raise PromptRenderError(str(exc), code="render_error") from exc
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""Placeholder extraction and validation for prompt templates."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from placeholder_registry import load_placeholders_for_context
|
||||||
|
|
||||||
|
PLACEHOLDER_PATTERN = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||||
|
|
||||||
|
|
||||||
|
class PlaceholderValidationError(Exception):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str,
|
||||||
|
*,
|
||||||
|
missing: list[str] | None = None,
|
||||||
|
type_errors: list[str] | None = None,
|
||||||
|
unknown: list[str] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.missing = missing or []
|
||||||
|
self.type_errors = type_errors or []
|
||||||
|
self.unknown = unknown or []
|
||||||
|
|
||||||
|
|
||||||
|
def extract_placeholders(template: str) -> set[str]:
|
||||||
|
return set(PLACEHOLDER_PATTERN.findall(template))
|
||||||
|
|
||||||
|
|
||||||
|
def _check_value_type(value: Any, value_type: str) -> bool:
|
||||||
|
if value_type == "string":
|
||||||
|
return isinstance(value, str)
|
||||||
|
if value_type == "number":
|
||||||
|
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||||
|
if value_type == "boolean":
|
||||||
|
return isinstance(value, bool)
|
||||||
|
if value_type == "object":
|
||||||
|
return isinstance(value, dict)
|
||||||
|
if value_type == "array":
|
||||||
|
return isinstance(value, list)
|
||||||
|
if value_type == "json":
|
||||||
|
return True
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def validate_placeholder_input(
|
||||||
|
*,
|
||||||
|
template: str,
|
||||||
|
context_kind: str,
|
||||||
|
values: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Validate input values against registry; return metadata including unknown placeholders."""
|
||||||
|
registry = {p["placeholder_key"]: p for p in load_placeholders_for_context(context_kind)}
|
||||||
|
used = extract_placeholders(template)
|
||||||
|
missing: list[str] = []
|
||||||
|
type_errors: list[str] = []
|
||||||
|
unknown = sorted(key for key in used if key not in registry)
|
||||||
|
|
||||||
|
for key, meta in registry.items():
|
||||||
|
if meta["required"] and key not in values:
|
||||||
|
missing.append(key)
|
||||||
|
if key in values and not _check_value_type(values[key], meta["value_type"]):
|
||||||
|
type_errors.append(f"{key}: expected {meta['value_type']}")
|
||||||
|
|
||||||
|
if missing or type_errors:
|
||||||
|
raise PlaceholderValidationError(
|
||||||
|
"Placeholder validation failed",
|
||||||
|
missing=missing,
|
||||||
|
type_errors=type_errors,
|
||||||
|
unknown=unknown,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"used_placeholders": sorted(used),
|
||||||
|
"unknown_placeholders": unknown,
|
||||||
|
"optional_missing": sorted(
|
||||||
|
key for key in registry if not registry[key]["required"] and key not in values
|
||||||
|
),
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest==8.3.4
|
||||||
|
httpx==0.27.2
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
fastapi==0.111.0
|
||||||
|
uvicorn[standard]==0.29.0
|
||||||
|
psycopg2-binary==2.9.9
|
||||||
|
sqlparse>=0.5.0
|
||||||
|
pydantic==2.7.1
|
||||||
|
email-validator>=2.1.0
|
||||||
|
bcrypt>=4.1.0
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""Import all module registrations — side effect registers capabilities."""
|
||||||
|
|
||||||
|
from . import ( # noqa: F401
|
||||||
|
initiative_ops,
|
||||||
|
operating_model_ops,
|
||||||
|
platform,
|
||||||
|
registry_ops,
|
||||||
|
tenant_ops,
|
||||||
|
workspace_ops,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"initiative_ops",
|
||||||
|
"operating_model_ops",
|
||||||
|
"platform",
|
||||||
|
"registry_ops",
|
||||||
|
"tenant_ops",
|
||||||
|
"workspace_ops",
|
||||||
|
]
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Initiative and action capabilities (AP0.5)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.initiative.read",
|
||||||
|
module="initiative",
|
||||||
|
description="Vorhaben im aktiven Tenant lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.initiative.manage",
|
||||||
|
module="initiative",
|
||||||
|
description="Vorhaben im aktiven Tenant anlegen und bearbeiten",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.action.read",
|
||||||
|
module="action",
|
||||||
|
description="Maßnahmen im aktiven Tenant lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.action.manage",
|
||||||
|
module="action",
|
||||||
|
description="Maßnahmen anlegen, bearbeiten, zuweisen und Status ändern",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
"""Operating model capabilities (AP0.8)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
_MEMBER_READ = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_MEMBER_MANAGE = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.attention.read",
|
||||||
|
module="attention",
|
||||||
|
description="Attention- und NextAction-Sichten lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.blocker.read",
|
||||||
|
module="blocker",
|
||||||
|
description="Blocker im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.blocker.manage",
|
||||||
|
module="blocker",
|
||||||
|
description="Blocker anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.backlog.read",
|
||||||
|
module="backlog",
|
||||||
|
description="Backlog-Items im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.backlog.manage",
|
||||||
|
module="backlog",
|
||||||
|
description="Backlog-Items anlegen, bearbeiten und konvertieren",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.milestone.read",
|
||||||
|
module="milestone",
|
||||||
|
description="Meilensteine im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.milestone.manage",
|
||||||
|
module="milestone",
|
||||||
|
description="Meilensteine anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.evidence.read",
|
||||||
|
module="evidence",
|
||||||
|
description="Evidence im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.evidence.manage",
|
||||||
|
module="evidence",
|
||||||
|
description="Evidence anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.decision.read",
|
||||||
|
module="decision",
|
||||||
|
description="Entscheidungen im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.decision.manage",
|
||||||
|
module="decision",
|
||||||
|
description="Entscheidungen anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.review.read",
|
||||||
|
module="review",
|
||||||
|
description="Reviews im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.review.manage",
|
||||||
|
module="review",
|
||||||
|
description="Reviews anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.recurring.read",
|
||||||
|
module="recurring",
|
||||||
|
description="Recurring-Elemente im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.recurring.manage",
|
||||||
|
module="recurring",
|
||||||
|
description="Recurring-Elemente anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.roadmap.reopen",
|
||||||
|
module="roadmap",
|
||||||
|
description="Erreichte Plan-Elemente wieder öffnen (Reopen)",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.roadmap.reopen.emergency",
|
||||||
|
module="roadmap",
|
||||||
|
description="Plan-Reopen als Portal-Admin (Notfall)",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.project.read",
|
||||||
|
module="project",
|
||||||
|
description="Projekte im aktiven Tenant lesen",
|
||||||
|
default_grants=_MEMBER_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.project.manage",
|
||||||
|
module="project",
|
||||||
|
description="Projekte anlegen und bearbeiten",
|
||||||
|
default_grants=_MEMBER_MANAGE,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Platform-level Kairo capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.admin.access",
|
||||||
|
module="platform",
|
||||||
|
description="Zugriff auf Portal-Administration und Admin-Endpunkte",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.context.read",
|
||||||
|
module="platform",
|
||||||
|
description="TenantContext und Session-Kontext lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.entitlements.read",
|
||||||
|
module="platform",
|
||||||
|
description="Entitlements-Snapshot lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""AP0.4 registry and prompt capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
_TENANT_READ = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_TENANT_ADMIN = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.feature.registry.read",
|
||||||
|
module="feature",
|
||||||
|
description="Feature Registry lesen",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.feature.registry.manage",
|
||||||
|
module="feature",
|
||||||
|
description="Feature Registry verwalten (Sync/Metadaten)",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.registry.read",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompt Registry lesen",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.registry.manage",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompt Registry verwalten",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.config.registry.read",
|
||||||
|
module="config",
|
||||||
|
description="Configuration Registry lesen",
|
||||||
|
default_grants=_TENANT_ADMIN,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.config.registry.manage",
|
||||||
|
module="config",
|
||||||
|
description="Configuration Registry schreiben",
|
||||||
|
default_grants=_TENANT_ADMIN,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.render",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompts rendern (ohne LLM)",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Tenant and actor management capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.tenant.manage",
|
||||||
|
module="tenant",
|
||||||
|
description="Tenant-Einstellungen und Mandantenverwaltung",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.actor.manage",
|
||||||
|
module="tenant",
|
||||||
|
description="Actors im aktiven Tenant verwalten",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Workspace read capabilities (AP0.7)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.actor.read",
|
||||||
|
module="tenant",
|
||||||
|
description="Actors im aktiven Tenant lesen (Directory)",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.workspace.read",
|
||||||
|
module="workspace",
|
||||||
|
description="Workspace-Übersichten und aggregierte Read-Models lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""In-memory capability registry with startup sync to PostgreSQL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
RoleGrant = tuple[str, str] # (role_scope, role_code)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CapabilityRegistration:
|
||||||
|
key: str
|
||||||
|
module: str
|
||||||
|
description: str
|
||||||
|
default_grants: tuple[RoleGrant, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, CapabilityRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_capability(registration: CapabilityRegistration) -> None:
|
||||||
|
if not registration.key or not registration.key.strip():
|
||||||
|
raise ValueError("Capability key is required")
|
||||||
|
if not registration.module or not registration.module.strip():
|
||||||
|
raise ValueError("Capability module is required")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Capability description is required")
|
||||||
|
if registration.key in _REGISTRY:
|
||||||
|
raise ValueError(f"Capability already registered: {registration.key}")
|
||||||
|
_REGISTRY[registration.key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_capabilities() -> tuple[CapabilityRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_registry_for_tests() -> None:
|
||||||
|
"""Test helper — reset in-memory registry."""
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_rights_registry_to_db() -> int:
|
||||||
|
"""Upsert capabilities and ensure default grants from registry."""
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[rights_registry] Keine Capabilities registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO capabilities (capability_key, module, description, is_active)
|
||||||
|
VALUES (%s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (capability_key) DO UPDATE SET
|
||||||
|
module = EXCLUDED.module,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(reg.key, reg.module, reg.description),
|
||||||
|
)
|
||||||
|
for role_scope, role_code in reg.default_grants:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO role_capability_grants (role_scope, role_code, capability_key)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (role_scope, role_code, capability_key) DO NOTHING
|
||||||
|
""",
|
||||||
|
(role_scope, role_code, reg.key),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[rights_registry] Sync OK — {len(_REGISTRY)} Capability(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[rights_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_grants_for_roles(
|
||||||
|
*,
|
||||||
|
portal_role: str,
|
||||||
|
tenant_role: str | None,
|
||||||
|
) -> set[str]:
|
||||||
|
"""Resolve capability keys granted by portal and optional tenant role."""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
keys: set[str] = set()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.capability_key
|
||||||
|
FROM role_capability_grants g
|
||||||
|
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||||
|
WHERE g.role_scope = 'portal'
|
||||||
|
AND g.role_code = %s
|
||||||
|
AND c.is_active = TRUE
|
||||||
|
""",
|
||||||
|
(portal_role,),
|
||||||
|
)
|
||||||
|
keys.update(row[0] for row in cur.fetchall())
|
||||||
|
|
||||||
|
if tenant_role:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.capability_key
|
||||||
|
FROM role_capability_grants g
|
||||||
|
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||||
|
WHERE g.role_scope = 'tenant'
|
||||||
|
AND g.role_code = %s
|
||||||
|
AND c.is_active = TRUE
|
||||||
|
""",
|
||||||
|
(tenant_role,),
|
||||||
|
)
|
||||||
|
keys.update(row[0] for row in cur.fetchall())
|
||||||
|
return keys
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
Loaded 100 of 766 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user