Compare commits
30
Commits
main
..
09433b5d28
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -1,30 +1,45 @@
|
||||
---
|
||||
description: Kairo Sprint-0 Architektur-Leitplanken und Dokumentenpriorität
|
||||
description: Kairo Architektur-Leitplanken und Dokumentenpriorität
|
||||
globs: backend/**,frontend/**,docs/**,.gitea/**
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Kairo Architecture Rules
|
||||
|
||||
Du arbeitest an **Jinkendo Kairo** (Sprint 0). Kairo ist mandantenfähig und Actor-first.
|
||||
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. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
2. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
3. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
4. `docs/reference/design-principles/alignment/*`
|
||||
5. Mitai/Shinkan-Einzelprinzipien (nur Begründung, kein Scope)
|
||||
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:
|
||||
|
||||
- `docs/reference/design-principles/mitai/`
|
||||
- `docs/reference/design-principles/shinkan/`
|
||||
- `docs/reference/design-principles/alignment/`
|
||||
|
||||
Nicht automatisch Implementierungs-Scope. Übernahme nur via Principle Gate oder Architecture Decision.
|
||||
Referenzmaterial unter `docs/reference/design-principles/`. Nicht automatisch Scope.
|
||||
|
||||
## Harte Guardrails
|
||||
|
||||
@@ -34,8 +49,9 @@ Nicht automatisch Implementierungs-Scope. Übernahme nur via Principle Gate oder
|
||||
- Keine hardcodierten Rechte, Prompts oder Fachkonfiguration
|
||||
- Nummerierte SQL-Migrationen; kein ad-hoc DDL in Routern
|
||||
- Keine Mitai-/Shinkan-Domänenlogik kopieren
|
||||
- Keine Vorhaben-/Projektlogik vor Sprint-0-Abschluss
|
||||
- Keine parallele Steuerungslogik außerhalb `backend/steering/`
|
||||
- Keine neuen OM-Tabellen ohne ADP (Scope Lock bis RoadmapItem-ADP)
|
||||
|
||||
## Abweichungen
|
||||
|
||||
Architecture Decision Proposal nach Vorlage in `docs/architecture/ARCHITECTURE_DECISION_PROPOSAL_TEMPLATE.md`.
|
||||
Architecture Decision Proposal nach `docs/architecture/ARCHITECTURE_DECISION_PROPOSAL_TEMPLATE.md`.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
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
|
||||
|
||||
## 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: nach AP-Umsetzung Abschlussbericht mit „Remote-Verifikation nach Push auf develop“ kennzeichnen
|
||||
- **Nicht** proaktiv committen/pushen, es sei denn, der Nutzer bittet explizit darum
|
||||
@@ -12,24 +12,25 @@ Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||
|
||||
## 1. Aktueller Entwicklungsstand
|
||||
|
||||
Sprint 0.
|
||||
Foundation AP0.1–AP0.7 abgeschlossen. Operating Model AP0.8–AP0.10, Steering AP1.0–AP1.1b technisch geliefert.
|
||||
|
||||
Es geht noch nicht um die vollständige Fachanwendung, sondern um das Fundament.
|
||||
**Technisch vorhanden:**
|
||||
|
||||
Sprint 0 baut:
|
||||
- Tenant, User, Actor, TenantContext, Auth, Capabilities
|
||||
- OM-Entitäten (Backlog, Blocker, Milestone-Brücke, Evidence, Decision, Review, Recurring)
|
||||
- `backend/steering/` (Lifecycle, Snapshot, Method Registry minimal)
|
||||
- Workspace-GUI, Data Layer, Actor Directory
|
||||
|
||||
- Tenant
|
||||
- User
|
||||
- Actor
|
||||
- TenantContext
|
||||
- Auth-Gates
|
||||
- Capability / Rights Registry
|
||||
- minimale Feature Registry
|
||||
- minimale Prompt Registry
|
||||
- Placeholder Validation
|
||||
- Configuration-Grundmodell
|
||||
- Audit
|
||||
- Migration/Deploy-Grundlage
|
||||
**Produktlich fehlt (Vision):**
|
||||
|
||||
- Getrennte IA (Ausführung / Plan / Eingang / Journey) — nicht Omnibus-InitiativeDetail
|
||||
- RoadmapItem / Quality Gates — Milestone heute nur CRUD
|
||||
- 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: **Dokumentations-Konsolidierung (Welle 2)**, dann **IA-Skeleton (AP1.2c)** und **RoadmapItem/Gates (AP1.4 + ADP)** — nicht weiteres Layout-Patching auf InitiativeDetail.
|
||||
|
||||
---
|
||||
|
||||
@@ -37,12 +38,56 @@ Sprint 0 baut:
|
||||
|
||||
Lies bei Projektstart in dieser Reihenfolge:
|
||||
|
||||
1. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
2. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
3. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
4. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||
5. `docs/architecture/Kairo_Architecture_References_v0.1.md`
|
||||
6. `.cursor/rules/kairo-architecture.mdc`
|
||||
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`
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -67,14 +112,12 @@ Sie dürfen nicht dazu verwendet werden, Kairo mit Mitai- oder Shinkan-Domänenl
|
||||
|
||||
## 4. Auslegungsreihenfolge bei Konflikten
|
||||
|
||||
Bei Konflikten gilt:
|
||||
Siehe **Abschnitt 2** — die Product-Reset-Reihenfolge ist verbindlich.
|
||||
|
||||
1. `Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
2. `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
3. `Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
4. `Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
5. `DESIGN_PRINCIPLES_ALIGNMENT.md`
|
||||
6. Mitai/Shinkan Einzelprinzipien
|
||||
Bei technischen Foundation-Konflikten zusätzlich:
|
||||
|
||||
- `Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
- `Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
|
||||
Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
|
||||
|
||||
@@ -99,12 +142,16 @@ Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
|
||||
|
||||
## 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
|
||||
- keine Vorhaben-/Projektlogik in AP0.1 vorziehen
|
||||
- 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
|
||||
@@ -115,6 +162,10 @@ Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
|
||||
|
||||
Bei notwendiger Abweichung erstelle ein Architecture Decision Proposal.
|
||||
|
||||
## 8. Aktueller erster Auftrag
|
||||
---
|
||||
|
||||
AP0.1 – Projektgrundlage (Backend, Frontend minimal, Tests, Deploy).
|
||||
## 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–AP1.1b technisch weit. **Produkt:** IA + RoadmapItem/Gates vor weiterem UI-Polish. Scope Lock: `ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`.
|
||||
@@ -8,6 +8,26 @@ Kairo steuert Vorhaben, Programme, Projekte, Meilensteine, Maßnahmen, Backlogs,
|
||||
|
||||
> Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||
|
||||
## Product Direction Reset
|
||||
|
||||
Kairo wurde nach AP0.7 produktstrategisch neu ausgerichtet.
|
||||
|
||||
Die führenden Dokumente sind:
|
||||
|
||||
- `docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md`
|
||||
- `docs/product/Kairo_Canonical_Operating_Model_v0.1.md`
|
||||
- `docs/product/Kairo_Corrected_MVP_Roadmap_v0.1.md`
|
||||
|
||||
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.
|
||||
@@ -22,14 +42,22 @@ Noch nicht enthalten:
|
||||
|
||||
## Verbindliche Dokumente für Sprint 0
|
||||
|
||||
1. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
2. `docs/architecture/Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
3. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
4. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
5. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||
6. `docs/sprints/Sprint0_AP0_1_Project_Setup_Assignment_v0.1.md`
|
||||
7. `CLAUDE.md`
|
||||
8. `.cursor/rules/kairo-architecture.mdc`
|
||||
**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
|
||||
|
||||
@@ -132,6 +160,178 @@ Migrationen & idempotente Data-Seeds: [docs/MIGRATIONS.md](docs/MIGRATIONS.md)
|
||||
| `/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) |
|
||||
|
||||
Vorhaben und Maßnahmen (AP0.5 minimaler Slice):
|
||||
|
||||
| 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.
|
||||
@@ -147,6 +347,8 @@ Feature-, Prompt-, Placeholder- und Config-Registry analog zur Rights Registry:
|
||||
|
||||
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`
|
||||
@@ -182,7 +384,13 @@ Registry-first: Capabilities werden in `backend/rights_registrations/` registrie
|
||||
|------------|-------|------------------|
|
||||
| `kairo.admin.access` | platform | Portal-Administration |
|
||||
| `kairo.tenant.manage` | tenant | Tenant-Verwaltung |
|
||||
| `kairo.actor.manage` | tenant | Actor-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 |
|
||||
|
||||
|
||||
@@ -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,322 @@
|
||||
"""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 data_layer.attention import get_next_action_candidates_for_initiative
|
||||
from steering.context import get_steering_context_dto
|
||||
from steering.signals.snapshot_signals import derive_initiative_signals
|
||||
from services.initiatives import get_initiative
|
||||
from tenant_context import TenantContext
|
||||
|
||||
OPEN_BLOCKER = ("open", "in_progress")
|
||||
OPEN_ACTION = ("open", "ready", "in_progress", "blocked", "review_required")
|
||||
ACTIVE_INITIATIVE = ("active", "paused")
|
||||
|
||||
|
||||
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, 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 id, title, status, target_date, item_type, sequencing_mode,
|
||||
sort_order, created_at, 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]
|
||||
|
||||
next_actions = get_next_action_candidates_for_initiative(
|
||||
ctx, initiative_id=initiative_id, limit=5
|
||||
)
|
||||
|
||||
steering = get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"initiative_title": initiative["title"],
|
||||
"initiative_status": initiative["status"],
|
||||
"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"],
|
||||
"signals": signals,
|
||||
"upcoming_milestones": upcoming_milestones,
|
||||
"upcoming_roadmap_items": upcoming_milestones,
|
||||
"next_actions": next_actions,
|
||||
"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,
|
||||
"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"],
|
||||
"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, status, priority,
|
||||
owner_actor_id, created_at, updated_at
|
||||
FROM initiatives
|
||||
WHERE tenant_id = %s AND status IN ('active', 'paused')
|
||||
ORDER BY 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,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),
|
||||
}
|
||||
+36
-1
@@ -11,6 +11,8 @@ 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
|
||||
@@ -53,13 +55,46 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
from routers import auth, config, features, me, prompts # noqa: E402
|
||||
from routers import ( # noqa: E402
|
||||
actions,
|
||||
actors,
|
||||
auth,
|
||||
backlog,
|
||||
blockers,
|
||||
config,
|
||||
decisions,
|
||||
evidence,
|
||||
features,
|
||||
initiatives,
|
||||
me,
|
||||
milestones,
|
||||
roadmap,
|
||||
prompts,
|
||||
recurring,
|
||||
reviews,
|
||||
steering,
|
||||
workspace,
|
||||
)
|
||||
|
||||
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(actions.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(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.get("/api/health")
|
||||
|
||||
@@ -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;
|
||||
@@ -1,5 +1,19 @@
|
||||
"""Import all module registrations — side effect registers capabilities."""
|
||||
|
||||
from . import platform, registry_ops, tenant_ops # noqa: F401
|
||||
from . import ( # noqa: F401
|
||||
initiative_ops,
|
||||
operating_model_ops,
|
||||
platform,
|
||||
registry_ops,
|
||||
tenant_ops,
|
||||
workspace_ops,
|
||||
)
|
||||
|
||||
__all__ = ["platform", "registry_ops", "tenant_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,155 @@
|
||||
"""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,
|
||||
)
|
||||
)
|
||||
@@ -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,115 @@
|
||||
"""Action (Maßnahme) API — AP0.5 / AP0.7."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from data_layer import actions as dl_actions
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import actions as action_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/actions", tags=["actions"])
|
||||
|
||||
|
||||
class ActionUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[
|
||||
Literal["open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"]
|
||||
] = None
|
||||
priority: Optional[Literal["low", "normal", "high"]] = None
|
||||
due_at: Optional[str] = None
|
||||
clear_due_at: bool = False
|
||||
|
||||
|
||||
class ActionAssignmentsRequest(BaseModel):
|
||||
actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/me/open")
|
||||
def list_my_open_actions(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
|
||||
):
|
||||
try:
|
||||
return dl_actions.get_all_my_open_actions(ctx)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/{action_id}")
|
||||
def get_action(
|
||||
action_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
|
||||
):
|
||||
item = action_service.get_action(tenant_id=ctx.tenant_id, action_id=action_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Maßnahme nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{action_id}")
|
||||
def update_action(
|
||||
action_id: str,
|
||||
body: ActionUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
due_at = None
|
||||
if body.due_at is not None:
|
||||
try:
|
||||
due_at = datetime.fromisoformat(body.due_at.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Ungültiges due_at") from exc
|
||||
try:
|
||||
item = action_service.update_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
due_at=due_at,
|
||||
clear_due_at=body.clear_due_at,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Maßnahme nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.put("/{action_id}/assignments")
|
||||
def set_action_assignments(
|
||||
action_id: str,
|
||||
body: ActionAssignmentsRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
item = action_service.set_action_assignments(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
actor_ids=body.actor_ids,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Maßnahme nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{action_id}", status_code=204)
|
||||
def delete_action(
|
||||
action_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
if not action_service.delete_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
user_id=ctx.user_id,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Maßnahme nicht gefunden")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Actor directory API — AP0.7."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from services import actors as actor_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/actors", tags=["actors"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_actors(
|
||||
actor_type: Optional[Literal["human", "agent", "working_group", "external_system"]] = None,
|
||||
include_inactive: bool = Query(default=False),
|
||||
q: Optional[str] = Query(default=None, max_length=100),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.actor.read")),
|
||||
):
|
||||
try:
|
||||
return actor_service.list_actors(
|
||||
tenant_id=ctx.tenant_id,
|
||||
actor_type=actor_type,
|
||||
include_inactive=include_inactive,
|
||||
q=q,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/{actor_id}")
|
||||
def get_actor(
|
||||
actor_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.actor.read")),
|
||||
):
|
||||
item = actor_service.get_actor(tenant_id=ctx.tenant_id, actor_id=actor_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Actor nicht gefunden")
|
||||
return item
|
||||
@@ -0,0 +1,103 @@
|
||||
"""BacklogItem API — AP0.8c."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import backlog as backlog_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/backlog", tags=["backlog"])
|
||||
|
||||
|
||||
class BacklogCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
|
||||
|
||||
class BacklogUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[Literal["new", "triaged", "accepted", "rejected"]] = None
|
||||
priority: Optional[Literal["low", "normal", "high"]] = None
|
||||
|
||||
|
||||
class BacklogConvertRequest(BaseModel):
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/{backlog_item_id}")
|
||||
def get_backlog_item(
|
||||
backlog_item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.read")),
|
||||
):
|
||||
item = backlog_service.get_backlog_item(
|
||||
tenant_id=ctx.tenant_id, backlog_item_id=backlog_item_id
|
||||
)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{backlog_item_id}")
|
||||
def update_backlog_item(
|
||||
backlog_item_id: str,
|
||||
body: BacklogUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
try:
|
||||
item = backlog_service.update_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{backlog_item_id}", status_code=204)
|
||||
def delete_backlog_item(
|
||||
backlog_item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
if not backlog_service.delete_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
|
||||
|
||||
@router.post("/{backlog_item_id}/convert-to-action", status_code=201)
|
||||
def convert_backlog_to_action(
|
||||
backlog_item_id: str,
|
||||
body: BacklogConvertRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
assigned = body.assigned_actor_ids
|
||||
if not assigned and ctx.actor_id:
|
||||
assigned = [ctx.actor_id]
|
||||
try:
|
||||
return backlog_service.convert_backlog_to_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
assigned_actor_ids=assigned,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Backlog-Item nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Blocker API — AP0.8b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import blockers as blocker_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/blockers", tags=["blockers"])
|
||||
|
||||
|
||||
class BlockerCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"] = "open"
|
||||
action_id: Optional[str] = None
|
||||
set_action_blocked: bool = False
|
||||
|
||||
|
||||
class BlockerUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[
|
||||
Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"]
|
||||
] = None
|
||||
action_id: Optional[str] = None
|
||||
clear_action_id: bool = False
|
||||
|
||||
|
||||
@router.get("/{blocker_id}")
|
||||
def get_blocker(
|
||||
blocker_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.read")),
|
||||
):
|
||||
item = blocker_service.get_blocker(tenant_id=ctx.tenant_id, blocker_id=blocker_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{blocker_id}")
|
||||
def update_blocker(
|
||||
blocker_id: str,
|
||||
body: BlockerUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
try:
|
||||
item = blocker_service.update_blocker(
|
||||
tenant_id=ctx.tenant_id,
|
||||
blocker_id=blocker_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
clear_action_id=body.clear_action_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{blocker_id}", status_code=204)
|
||||
def delete_blocker(
|
||||
blocker_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
if not blocker_service.delete_blocker(
|
||||
tenant_id=ctx.tenant_id, blocker_id=blocker_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Decision API — AP0.9c."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import decisions as decision_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/decisions", tags=["decisions"])
|
||||
|
||||
|
||||
class DecisionUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[Literal["proposed", "decided", "superseded"]] = None
|
||||
outcome: Optional[str] = None
|
||||
decided_by_actor_id: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/{decision_id}")
|
||||
def get_decision(
|
||||
decision_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.decision.read")),
|
||||
):
|
||||
item = decision_service.get_decision(tenant_id=ctx.tenant_id, decision_id=decision_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Entscheidung nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{decision_id}")
|
||||
def update_decision(
|
||||
decision_id: str,
|
||||
body: DecisionUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.decision.manage")),
|
||||
):
|
||||
try:
|
||||
item = decision_service.update_decision(
|
||||
tenant_id=ctx.tenant_id,
|
||||
decision_id=decision_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
outcome=body.outcome,
|
||||
decided_by_actor_id=body.decided_by_actor_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Entscheidung nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{decision_id}", status_code=204)
|
||||
def delete_decision(
|
||||
decision_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.decision.manage")),
|
||||
):
|
||||
if not decision_service.delete_decision(
|
||||
tenant_id=ctx.tenant_id, decision_id=decision_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Entscheidung nicht gefunden")
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Evidence API — AP0.9b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import evidence as evidence_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/evidence", tags=["evidence"])
|
||||
|
||||
|
||||
class EvidenceUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[Literal["submitted", "accepted", "rejected"]] = None
|
||||
action_id: Optional[str] = None
|
||||
milestone_id: Optional[str] = None
|
||||
clear_action_id: bool = False
|
||||
clear_milestone_id: bool = False
|
||||
|
||||
|
||||
@router.get("/{evidence_id}")
|
||||
def get_evidence(
|
||||
evidence_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.evidence.read")),
|
||||
):
|
||||
item = evidence_service.get_evidence(tenant_id=ctx.tenant_id, evidence_id=evidence_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Evidence nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{evidence_id}")
|
||||
def update_evidence(
|
||||
evidence_id: str,
|
||||
body: EvidenceUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.evidence.manage")),
|
||||
):
|
||||
try:
|
||||
item = evidence_service.update_evidence(
|
||||
tenant_id=ctx.tenant_id,
|
||||
evidence_id=evidence_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
milestone_id=body.milestone_id,
|
||||
clear_action_id=body.clear_action_id,
|
||||
clear_milestone_id=body.clear_milestone_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Evidence nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{evidence_id}", status_code=204)
|
||||
def delete_evidence(
|
||||
evidence_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.evidence.manage")),
|
||||
):
|
||||
if not evidence_service.delete_evidence(
|
||||
tenant_id=ctx.tenant_id, evidence_id=evidence_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Evidence nicht gefunden")
|
||||
@@ -0,0 +1,543 @@
|
||||
"""Initiative (Vorhaben) API — AP0.5."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from data_layer import initiative_snapshot as dl_initiative_snapshot
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from steering.context import get_steering_context_dto
|
||||
from services import actions as action_service
|
||||
from services import backlog as backlog_service
|
||||
from services import blockers as blocker_service
|
||||
from services import decisions as decision_service
|
||||
from services import evidence as evidence_service
|
||||
from services import initiatives as initiative_service
|
||||
from services import milestones as milestone_service
|
||||
from services import recurring as recurring_service
|
||||
from services import reviews as review_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/initiatives", tags=["initiatives"])
|
||||
|
||||
|
||||
class InitiativeCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
goal: str = ""
|
||||
status: Literal["active", "paused", "completed", "archived"] = "active"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
owner_actor_id: Optional[str] = None
|
||||
|
||||
|
||||
class InitiativeUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
goal: Optional[str] = None
|
||||
status: Optional[Literal["active", "paused", "completed", "archived"]] = None
|
||||
priority: Optional[Literal["low", "normal", "high"]] = None
|
||||
owner_actor_id: Optional[str] = None
|
||||
|
||||
|
||||
class ActionCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal[
|
||||
"open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"
|
||||
] = "open"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
due_at: Optional[str] = None
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class BlockerCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"] = "open"
|
||||
action_id: Optional[str] = None
|
||||
set_action_blocked: bool = False
|
||||
|
||||
|
||||
class BacklogCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
|
||||
|
||||
class MilestoneCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
goal_description: str = ""
|
||||
status: Literal["planned", "active", "at_risk", "reached", "moved", "discarded"] = "planned"
|
||||
target_date: Optional[str] = None
|
||||
|
||||
|
||||
class EvidenceCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["submitted", "accepted", "rejected"] = "submitted"
|
||||
action_id: Optional[str] = None
|
||||
milestone_id: Optional[str] = None
|
||||
|
||||
|
||||
class DecisionCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["proposed", "decided", "superseded"] = "proposed"
|
||||
outcome: str = ""
|
||||
|
||||
|
||||
class ReviewCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
summary: str = ""
|
||||
status: Literal["planned", "completed", "skipped"] = "planned"
|
||||
due_at: Optional[str] = None
|
||||
action_id: Optional[str] = None
|
||||
milestone_id: Optional[str] = None
|
||||
|
||||
|
||||
class RecurringCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["active", "paused", "ended"] = "active"
|
||||
interval_days: Optional[int] = Field(default=None, gt=0)
|
||||
next_due_at: Optional[str] = None
|
||||
|
||||
|
||||
def _parse_optional_datetime(value: Optional[str], field_name: str) -> Optional[datetime]:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Ungültiges {field_name}") from exc
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_initiatives(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
):
|
||||
return initiative_service.list_initiatives(tenant_id=ctx.tenant_id)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_initiative(
|
||||
body: InitiativeCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
|
||||
):
|
||||
owner_actor_id = body.owner_actor_id or ctx.actor_id
|
||||
if not owner_actor_id:
|
||||
raise HTTPException(status_code=400, detail="Kein Actor im TenantContext")
|
||||
try:
|
||||
return initiative_service.create_initiative(
|
||||
tenant_id=ctx.tenant_id,
|
||||
title=body.title,
|
||||
goal=body.goal,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
owner_actor_id=owner_actor_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}")
|
||||
def get_initiative(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
):
|
||||
item = initiative_service.get_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/steering-snapshot")
|
||||
def get_initiative_steering_snapshot(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
):
|
||||
snapshot = dl_initiative_snapshot.get_initiative_steering_snapshot(
|
||||
ctx, initiative_id=initiative_id
|
||||
)
|
||||
if not snapshot:
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
return snapshot
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/steering-context")
|
||||
def get_initiative_steering_context(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
):
|
||||
if not initiative_service.get_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
return get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
|
||||
|
||||
@router.patch("/{initiative_id}")
|
||||
def update_initiative(
|
||||
initiative_id: str,
|
||||
body: InitiativeUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
|
||||
):
|
||||
try:
|
||||
item = initiative_service.update_initiative(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
goal=body.goal,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
owner_actor_id=body.owner_actor_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{initiative_id}", status_code=204)
|
||||
def delete_initiative(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
|
||||
):
|
||||
if not initiative_service.delete_initiative(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
user_id=ctx.user_id,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/actions")
|
||||
def list_initiative_actions(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
|
||||
):
|
||||
if not initiative_service.get_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
return action_service.list_actions_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/actions", status_code=201)
|
||||
def create_initiative_action(
|
||||
initiative_id: str,
|
||||
body: ActionCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
due_at = _parse_optional_datetime(body.due_at, "due_at")
|
||||
return action_service.create_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
due_at=due_at,
|
||||
assigned_actor_ids=body.assigned_actor_ids,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/blockers")
|
||||
def list_initiative_blockers(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.read")),
|
||||
):
|
||||
try:
|
||||
return blocker_service.list_blockers_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/blockers", status_code=201)
|
||||
def create_initiative_blocker(
|
||||
initiative_id: str,
|
||||
body: BlockerCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
try:
|
||||
return blocker_service.create_blocker(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
reported_by_actor_id=ctx.actor_id,
|
||||
user_id=ctx.user_id,
|
||||
set_action_blocked=body.set_action_blocked,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/backlog")
|
||||
def list_initiative_backlog(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.read")),
|
||||
):
|
||||
try:
|
||||
return backlog_service.list_backlog_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/backlog", status_code=201)
|
||||
def create_initiative_backlog_item(
|
||||
initiative_id: str,
|
||||
body: BacklogCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
try:
|
||||
return backlog_service.create_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/milestones")
|
||||
def list_initiative_milestones(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
return milestone_service.list_milestones_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/milestones", status_code=201)
|
||||
def create_initiative_milestone(
|
||||
initiative_id: str,
|
||||
body: MilestoneCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
from datetime import date as date_type
|
||||
|
||||
target_date = None
|
||||
if body.target_date:
|
||||
try:
|
||||
target_date = date_type.fromisoformat(body.target_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Ungültiges target_date") from exc
|
||||
try:
|
||||
return milestone_service.create_milestone(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
goal_description=body.goal_description,
|
||||
status=body.status,
|
||||
target_date=target_date,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/evidence")
|
||||
def list_initiative_evidence(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.evidence.read")),
|
||||
):
|
||||
try:
|
||||
return evidence_service.list_evidence_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/evidence", status_code=201)
|
||||
def create_initiative_evidence(
|
||||
initiative_id: str,
|
||||
body: EvidenceCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.evidence.manage")),
|
||||
):
|
||||
try:
|
||||
return evidence_service.create_evidence(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
milestone_id=body.milestone_id,
|
||||
submitted_by_actor_id=ctx.actor_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/decisions")
|
||||
def list_initiative_decisions(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.decision.read")),
|
||||
):
|
||||
try:
|
||||
return decision_service.list_decisions_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/decisions", status_code=201)
|
||||
def create_initiative_decision(
|
||||
initiative_id: str,
|
||||
body: DecisionCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.decision.manage")),
|
||||
):
|
||||
try:
|
||||
return decision_service.create_decision(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
outcome=body.outcome,
|
||||
decided_by_actor_id=ctx.actor_id if body.status == "decided" else None,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/reviews")
|
||||
def list_initiative_reviews(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.review.read")),
|
||||
):
|
||||
try:
|
||||
return review_service.list_reviews_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/reviews", status_code=201)
|
||||
def create_initiative_review(
|
||||
initiative_id: str,
|
||||
body: ReviewCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.review.manage")),
|
||||
):
|
||||
due_at = _parse_optional_datetime(body.due_at, "due_at")
|
||||
try:
|
||||
return review_service.create_review(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
summary=body.summary,
|
||||
status=body.status,
|
||||
due_at=due_at,
|
||||
action_id=body.action_id,
|
||||
milestone_id=body.milestone_id,
|
||||
reviewed_by_actor_id=ctx.actor_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/recurring")
|
||||
def list_initiative_recurring(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.read")),
|
||||
):
|
||||
try:
|
||||
return recurring_service.list_recurring_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/recurring", status_code=201)
|
||||
def create_initiative_recurring(
|
||||
initiative_id: str,
|
||||
body: RecurringCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
next_due_at = _parse_optional_datetime(body.next_due_at, "next_due_at")
|
||||
try:
|
||||
return recurring_service.create_recurring_element(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
interval_days=body.interval_days,
|
||||
next_due_at=next_due_at,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Milestone API — AP0.8d."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import milestones as milestone_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/milestones", tags=["milestones"])
|
||||
|
||||
|
||||
class MilestoneCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
goal_description: str = ""
|
||||
status: Literal["planned", "active", "at_risk", "reached", "moved", "discarded"] = "planned"
|
||||
target_date: Optional[date] = None
|
||||
|
||||
|
||||
class MilestoneUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
goal_description: Optional[str] = None
|
||||
status: Optional[
|
||||
Literal["planned", "active", "at_risk", "reached", "moved", "discarded"]
|
||||
] = None
|
||||
target_date: Optional[date] = None
|
||||
clear_target_date: bool = False
|
||||
|
||||
|
||||
@router.get("/{milestone_id}")
|
||||
def get_milestone(
|
||||
milestone_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
item = milestone_service.get_milestone(tenant_id=ctx.tenant_id, milestone_id=milestone_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{milestone_id}")
|
||||
def update_milestone(
|
||||
milestone_id: str,
|
||||
body: MilestoneUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
item = milestone_service.update_milestone(
|
||||
tenant_id=ctx.tenant_id,
|
||||
milestone_id=milestone_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
goal_description=body.goal_description,
|
||||
status=body.status,
|
||||
target_date=body.target_date,
|
||||
clear_target_date=body.clear_target_date,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{milestone_id}", status_code=204)
|
||||
def delete_milestone(
|
||||
milestone_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
if not milestone_service.delete_milestone(
|
||||
tenant_id=ctx.tenant_id, milestone_id=milestone_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
@@ -0,0 +1,84 @@
|
||||
"""RecurringElement API — AP0.9e."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import recurring as recurring_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/recurring", tags=["recurring"])
|
||||
|
||||
|
||||
class RecurringUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[Literal["active", "paused", "ended"]] = None
|
||||
interval_days: Optional[int] = Field(default=None, gt=0)
|
||||
clear_interval_days: bool = False
|
||||
next_due_at: Optional[str] = None
|
||||
clear_next_due_at: bool = False
|
||||
|
||||
|
||||
def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Ungültiges next_due_at") from exc
|
||||
|
||||
|
||||
@router.get("/{recurring_id}")
|
||||
def get_recurring_element(
|
||||
recurring_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.read")),
|
||||
):
|
||||
item = recurring_service.get_recurring_element(
|
||||
tenant_id=ctx.tenant_id, recurring_id=recurring_id
|
||||
)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Recurring-Element nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{recurring_id}")
|
||||
def update_recurring_element(
|
||||
recurring_id: str,
|
||||
body: RecurringUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
next_due_at = _parse_datetime(body.next_due_at) if body.next_due_at is not None else None
|
||||
try:
|
||||
item = recurring_service.update_recurring_element(
|
||||
tenant_id=ctx.tenant_id,
|
||||
recurring_id=recurring_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
interval_days=body.interval_days,
|
||||
clear_interval_days=body.clear_interval_days,
|
||||
next_due_at=next_due_at,
|
||||
clear_next_due_at=body.clear_next_due_at,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Recurring-Element nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{recurring_id}", status_code=204)
|
||||
def delete_recurring_element(
|
||||
recurring_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
if not recurring_service.delete_recurring_element(
|
||||
tenant_id=ctx.tenant_id, recurring_id=recurring_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Recurring-Element nicht gefunden")
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Review API — AP0.9d."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import reviews as review_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/reviews", tags=["reviews"])
|
||||
|
||||
|
||||
class ReviewUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
summary: Optional[str] = None
|
||||
status: Optional[Literal["planned", "completed", "skipped"]] = None
|
||||
due_at: Optional[str] = None
|
||||
clear_due_at: bool = False
|
||||
action_id: Optional[str] = None
|
||||
milestone_id: Optional[str] = None
|
||||
clear_action_id: bool = False
|
||||
clear_milestone_id: bool = False
|
||||
|
||||
|
||||
def _parse_due_at(value: Optional[str]) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Ungültiges due_at") from exc
|
||||
|
||||
|
||||
@router.get("/{review_id}")
|
||||
def get_review(
|
||||
review_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.review.read")),
|
||||
):
|
||||
item = review_service.get_review(tenant_id=ctx.tenant_id, review_id=review_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Review nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{review_id}")
|
||||
def update_review(
|
||||
review_id: str,
|
||||
body: ReviewUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.review.manage")),
|
||||
):
|
||||
due_at = _parse_due_at(body.due_at) if body.due_at is not None else None
|
||||
try:
|
||||
item = review_service.update_review(
|
||||
tenant_id=ctx.tenant_id,
|
||||
review_id=review_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
summary=body.summary,
|
||||
status=body.status,
|
||||
due_at=due_at,
|
||||
clear_due_at=body.clear_due_at,
|
||||
action_id=body.action_id,
|
||||
milestone_id=body.milestone_id,
|
||||
clear_action_id=body.clear_action_id,
|
||||
clear_milestone_id=body.clear_milestone_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Review nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{review_id}", status_code=204)
|
||||
def delete_review(
|
||||
review_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.review.manage")),
|
||||
):
|
||||
if not review_service.delete_review(
|
||||
tenant_id=ctx.tenant_id, review_id=review_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Review nicht gefunden")
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Roadmap API — AP1.4."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import roadmap as roadmap_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(tags=["roadmap"])
|
||||
|
||||
|
||||
class RoadmapItemCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
item_type: Literal["milestone", "review_gate", "maturity_stage"] = "milestone"
|
||||
goal_description: str = ""
|
||||
definition_of_done: list[Any] = Field(default_factory=list)
|
||||
status: Literal[
|
||||
"planned", "active", "at_risk", "reached", "moved", "discarded"
|
||||
] = "planned"
|
||||
sequencing_mode: Literal["sequential", "parallel", "optional"] = "sequential"
|
||||
target_date: Optional[date] = None
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class RoadmapItemUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
item_type: Optional[Literal["milestone", "review_gate", "maturity_stage"]] = None
|
||||
goal_description: Optional[str] = None
|
||||
definition_of_done: Optional[list[Any]] = None
|
||||
status: Optional[
|
||||
Literal["planned", "active", "at_risk", "reached", "moved", "discarded"]
|
||||
] = None
|
||||
sequencing_mode: Optional[Literal["sequential", "parallel", "optional"]] = None
|
||||
target_date: Optional[date] = None
|
||||
clear_target_date: bool = False
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class DependencyCreateRequest(BaseModel):
|
||||
to_item_id: str
|
||||
dependency_type: Literal["requires", "blocks", "related"] = "requires"
|
||||
|
||||
|
||||
initiative_router = APIRouter(prefix="/api/initiatives", tags=["roadmap"])
|
||||
items_router = APIRouter(prefix="/api/roadmap-items", tags=["roadmap"])
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/roadmap")
|
||||
def get_initiative_roadmap(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
roadmap = roadmap_service.get_roadmap_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not roadmap:
|
||||
return {"initiative_id": initiative_id, "items": []}
|
||||
items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
return {**roadmap, "items": items}
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/roadmap/items")
|
||||
def list_initiative_roadmap_items(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
return roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.post("/{initiative_id}/roadmap/items", status_code=201)
|
||||
def create_initiative_roadmap_item(
|
||||
initiative_id: str,
|
||||
body: RoadmapItemCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
return roadmap_service.create_roadmap_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
item_type=body.item_type,
|
||||
goal_description=body.goal_description,
|
||||
definition_of_done=body.definition_of_done,
|
||||
status=body.status,
|
||||
sequencing_mode=body.sequencing_mode,
|
||||
target_date=body.target_date,
|
||||
sort_order=body.sort_order,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@items_router.get("/{item_id}")
|
||||
def get_roadmap_item(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
item = roadmap_service.get_roadmap_item(tenant_id=ctx.tenant_id, item_id=item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@items_router.patch("/{item_id}")
|
||||
def update_roadmap_item(
|
||||
item_id: str,
|
||||
body: RoadmapItemUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
item = roadmap_service.update_roadmap_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
item_id=item_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
item_type=body.item_type,
|
||||
goal_description=body.goal_description,
|
||||
definition_of_done=body.definition_of_done,
|
||||
status=body.status,
|
||||
sequencing_mode=body.sequencing_mode,
|
||||
target_date=body.target_date,
|
||||
clear_target_date=body.clear_target_date,
|
||||
sort_order=body.sort_order,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@items_router.delete("/{item_id}", status_code=204)
|
||||
def delete_roadmap_item(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
if not roadmap_service.delete_roadmap_item(
|
||||
tenant_id=ctx.tenant_id, item_id=item_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
|
||||
|
||||
|
||||
@items_router.post("/{item_id}/verify-reached")
|
||||
def verify_roadmap_item_reached(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
return roadmap_service.verify_reached(
|
||||
tenant_id=ctx.tenant_id, item_id=item_id, user_id=ctx.user_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@items_router.get("/{item_id}/dependencies")
|
||||
def list_roadmap_item_dependencies(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
return roadmap_service.list_dependencies(tenant_id=ctx.tenant_id, item_id=item_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@items_router.post("/{item_id}/dependencies", status_code=201)
|
||||
def add_roadmap_item_dependency(
|
||||
item_id: str,
|
||||
body: DependencyCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
return roadmap_service.add_dependency(
|
||||
tenant_id=ctx.tenant_id,
|
||||
from_item_id=item_id,
|
||||
to_item_id=body.to_item_id,
|
||||
dependency_type=body.dependency_type,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Steering API — methods and context (AP1.1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import initiatives as initiative_service
|
||||
from services import steering_context as sc_service
|
||||
from steering.context import get_steering_context_dto
|
||||
from steering.methods.registry import list_methods
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/steering", tags=["steering"])
|
||||
|
||||
|
||||
class SteeringContextUpdateRequest(BaseModel):
|
||||
method_key: Optional[
|
||||
Literal["generic_operating", "product_milestone_driven"]
|
||||
] = None
|
||||
|
||||
|
||||
@router.get("/methods")
|
||||
def list_steering_methods(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
):
|
||||
return [
|
||||
{
|
||||
"key": m.key,
|
||||
"version": m.version,
|
||||
"label": m.label,
|
||||
"description": m.description,
|
||||
"next_action_strategy_key": m.next_action_strategy_key,
|
||||
}
|
||||
for m in list_methods()
|
||||
]
|
||||
|
||||
|
||||
@router.patch("/initiatives/{initiative_id}/context")
|
||||
def patch_initiative_steering_context(
|
||||
initiative_id: str,
|
||||
body: SteeringContextUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
|
||||
):
|
||||
if not initiative_service.get_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
|
||||
if not body.method_key:
|
||||
raise HTTPException(status_code=400, detail="method_key erforderlich")
|
||||
try:
|
||||
sc_service.update_method_key(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
method_key=body.method_key,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Workspace read API — delegates to Data Layer (AP0.7)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from data_layer import actions as dl_actions
|
||||
from data_layer import actors as dl_actors
|
||||
from data_layer import attention as dl_attention
|
||||
from data_layer import initiatives as dl_initiatives
|
||||
from data_layer import workspace as dl_workspace
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/workspace", tags=["workspace"])
|
||||
|
||||
|
||||
def _require_actor_ctx(ctx: TenantContext) -> TenantContext:
|
||||
if not ctx.actor_id:
|
||||
raise HTTPException(status_code=400, detail="Kein Actor im TenantContext")
|
||||
return ctx
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def workspace_summary(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
return dl_workspace.get_workspace_summary(ctx)
|
||||
|
||||
|
||||
@router.get("/actions/open")
|
||||
def workspace_open_actions(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
try:
|
||||
return dl_actions.get_my_open_actions(_require_actor_ctx(ctx))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/actions/blocked")
|
||||
def workspace_blocked_actions(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
try:
|
||||
return dl_actions.get_my_blocked_actions(_require_actor_ctx(ctx))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/actions/today")
|
||||
def workspace_today_actions(
|
||||
limit: Optional[int] = Query(default=15, ge=1, le=50),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
try:
|
||||
return dl_actions.get_my_today_actions(_require_actor_ctx(ctx), limit=limit or 15)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/initiatives/active")
|
||||
def workspace_active_initiatives(
|
||||
limit: Optional[int] = Query(default=None, ge=1, le=100),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
return dl_initiatives.get_active_initiatives(ctx, limit=limit)
|
||||
|
||||
|
||||
@router.get("/actors/workload")
|
||||
def workspace_actor_workload(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
return dl_actors.get_actor_workload(ctx)
|
||||
|
||||
|
||||
@router.get("/attention")
|
||||
def workspace_attention(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
|
||||
):
|
||||
return dl_attention.get_attention_items(ctx)
|
||||
|
||||
|
||||
@router.get("/next-actions")
|
||||
def workspace_next_actions(
|
||||
limit: Optional[int] = Query(default=10, ge=1, le=50),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
|
||||
):
|
||||
return dl_attention.get_next_action_candidates(ctx, limit=limit or 10)
|
||||
@@ -4,6 +4,21 @@
|
||||
-- Reparatur: ungültige Human-Actors (user_id NULL verletzt CHECK constraint)
|
||||
DELETE FROM actors WHERE actor_type = 'human' AND user_id IS NULL;
|
||||
|
||||
-- AP0.5: Vorhaben/Maßnahmen pytest-Artefakte vor Actor-Löschung entfernen
|
||||
-- (initiatives.owner_actor_id → actors ON DELETE RESTRICT)
|
||||
DELETE FROM initiatives
|
||||
WHERE owner_actor_id IN (
|
||||
SELECT id FROM actors WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$')
|
||||
);
|
||||
|
||||
DELETE FROM initiatives i
|
||||
USING tenants t
|
||||
WHERE i.tenant_id = t.id
|
||||
AND t.slug ~ '^t-[a-f0-9]{10}$'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tenant_memberships tm WHERE tm.tenant_id = t.id
|
||||
);
|
||||
|
||||
-- Abhängigkeiten vor User-Löschung (human actors: user_id NOT NULL constraint)
|
||||
DELETE FROM actors
|
||||
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
"""Action (Maßnahme) service — tenant-scoped CRUD, assignments, open actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import PRIORITIES, get_initiative
|
||||
|
||||
ActionStatus = Literal[
|
||||
"open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"
|
||||
]
|
||||
|
||||
ACTION_STATUSES = frozenset(
|
||||
{"open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"}
|
||||
)
|
||||
OPEN_ACTION_STATUSES = frozenset(
|
||||
{"open", "ready", "in_progress", "blocked", "review_required"}
|
||||
)
|
||||
|
||||
_ACTION_COLUMNS = """
|
||||
id, tenant_id, initiative_id, title, description,
|
||||
status, priority, due_at, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "owner_actor_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
if result.get("updated_at"):
|
||||
result["updated_at"] = result["updated_at"].isoformat()
|
||||
if result.get("due_at"):
|
||||
result["due_at"] = result["due_at"].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_action_status(status: str) -> None:
|
||||
if status not in ACTION_STATUSES:
|
||||
raise ValueError(f"Ungültiger Action-Status: {status}")
|
||||
|
||||
|
||||
def _validate_priority(priority: str) -> None:
|
||||
if priority not in PRIORITIES:
|
||||
raise ValueError(f"Ungültige Priorität: {priority}")
|
||||
|
||||
|
||||
def _load_assignments(*, tenant_id: str, action_ids: list[str]) -> dict[str, list[str]]:
|
||||
if not action_ids:
|
||||
return {}
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT action_id, actor_id
|
||||
FROM action_assignments
|
||||
WHERE tenant_id = %s AND action_id = ANY(%s::uuid[])
|
||||
ORDER BY created_at
|
||||
""",
|
||||
(tenant_id, action_ids),
|
||||
)
|
||||
result: dict[str, list[str]] = {aid: [] for aid in action_ids}
|
||||
for row in cur.fetchall():
|
||||
result[str(row["action_id"])].append(str(row["actor_id"]))
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _attach_assignments(
|
||||
actions: list[dict[str, Any]], *, tenant_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not actions:
|
||||
return actions
|
||||
action_ids = [a["id"] for a in actions]
|
||||
assignments = _load_assignments(tenant_id=tenant_id, action_ids=action_ids)
|
||||
for action in actions:
|
||||
action["assigned_actor_ids"] = assignments.get(action["id"], [])
|
||||
return actions
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_action(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: ActionStatus = "open",
|
||||
priority: str = "normal",
|
||||
due_at: Optional[Any] = None,
|
||||
assigned_actor_ids: Optional[list[str]] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_action_status(status)
|
||||
_validate_priority(priority)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
assigned_actor_ids = assigned_actor_ids or []
|
||||
for actor_id in assigned_actor_ids:
|
||||
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=actor_id):
|
||||
raise ValueError(f"Actor {actor_id} gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO actions (
|
||||
tenant_id, initiative_id, title, description, status, priority, due_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_ACTION_COLUMNS}
|
||||
""",
|
||||
(tenant_id, initiative_id, title, description, status, priority, due_at),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
for actor_id in assigned_actor_ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO action_assignments (tenant_id, action_id, actor_id)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(tenant_id, row["id"], actor_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
row["assigned_actor_ids"] = assigned_actor_ids
|
||||
log_audit(
|
||||
"action.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"action_id": row["id"],
|
||||
"initiative_id": initiative_id,
|
||||
"title": title,
|
||||
"status": status,
|
||||
"assigned_actor_ids": assigned_actor_ids,
|
||||
},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_actions_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
return []
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_ACTION_COLUMNS}
|
||||
FROM actions
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
actions = [_serialize_row(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return _attach_assignments(actions, tenant_id=tenant_id)
|
||||
|
||||
|
||||
def get_action(*, tenant_id: str, action_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_ACTION_COLUMNS}
|
||||
FROM actions
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
action = _serialize_row(dict(row))
|
||||
finally:
|
||||
conn.close()
|
||||
return _attach_assignments([action], tenant_id=tenant_id)[0]
|
||||
|
||||
|
||||
def update_action(
|
||||
*,
|
||||
tenant_id: str,
|
||||
action_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[ActionStatus] = None,
|
||||
priority: Optional[str] = None,
|
||||
due_at: Optional[Any] = None,
|
||||
clear_due_at: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_action(tenant_id=tenant_id, action_id=action_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
old_status = existing["status"]
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_action_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if priority is not None:
|
||||
_validate_priority(priority)
|
||||
updates.append("priority = %s")
|
||||
params.append(priority)
|
||||
if clear_due_at:
|
||||
updates.append("due_at = NULL")
|
||||
elif due_at is not None:
|
||||
updates.append("due_at = %s")
|
||||
params.append(due_at)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([action_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE actions
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING {_ACTION_COLUMNS}
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
result = get_action(tenant_id=tenant_id, action_id=action_id)
|
||||
assert result is not None
|
||||
|
||||
log_audit(
|
||||
"action.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"action_id": action_id, "fields": updates},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"action.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"action_id": action_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def set_action_assignments(
|
||||
*,
|
||||
tenant_id: str,
|
||||
action_id: str,
|
||||
actor_ids: list[str],
|
||||
user_id: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_action(tenant_id=tenant_id, action_id=action_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
unique_actor_ids = list(dict.fromkeys(actor_ids))
|
||||
for actor_id in unique_actor_ids:
|
||||
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=actor_id):
|
||||
raise ValueError(f"Actor {actor_id} gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM action_assignments WHERE action_id = %s AND tenant_id = %s",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
for actor_id in unique_actor_ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO action_assignments (tenant_id, action_id, actor_id)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(tenant_id, action_id, actor_id),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE actions SET updated_at = NOW() WHERE id = %s AND tenant_id = %s",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"action.assigned",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"action_id": action_id,
|
||||
"actor_ids": unique_actor_ids,
|
||||
"previous_actor_ids": existing.get("assigned_actor_ids", []),
|
||||
},
|
||||
)
|
||||
return get_action(tenant_id=tenant_id, action_id=action_id)
|
||||
|
||||
|
||||
def delete_action(
|
||||
*,
|
||||
tenant_id: str,
|
||||
action_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM actions WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"action.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"action_id": action_id},
|
||||
)
|
||||
return deleted
|
||||
|
||||
|
||||
def list_open_actions_for_actor(
|
||||
*, tenant_id: str, actor_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
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
|
||||
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 BY
|
||||
CASE a.priority
|
||||
WHEN 'high' THEN 0
|
||||
WHEN 'normal' THEN 1
|
||||
WHEN 'low' THEN 2
|
||||
END,
|
||||
a.updated_at DESC
|
||||
""",
|
||||
(tenant_id, actor_id, list(OPEN_ACTION_STATUSES)),
|
||||
)
|
||||
actions = [_serialize_row(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return _attach_assignments(actions, tenant_id=tenant_id)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Actor creation helpers — User and Actor remain separate concepts."""
|
||||
"""Actor creation and directory helpers — User and Actor remain separate concepts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,6 +10,20 @@ from db import get_connection
|
||||
|
||||
ActorType = Literal["human", "agent", "working_group", "external_system"]
|
||||
|
||||
ACTOR_TYPES = frozenset({"human", "agent", "working_group", "external_system"})
|
||||
|
||||
|
||||
def _serialize_actor(row: dict[str, Any], *, include_user_id: bool = False) -> dict[str, Any]:
|
||||
result = {
|
||||
"id": str(row["id"]),
|
||||
"name": row["name"],
|
||||
"actor_type": row["actor_type"],
|
||||
"is_active": bool(row["is_active"]),
|
||||
}
|
||||
if include_user_id and row.get("user_id"):
|
||||
result["user_id"] = str(row["user_id"])
|
||||
return result
|
||||
|
||||
|
||||
def create_actor(
|
||||
*,
|
||||
@@ -66,3 +80,70 @@ def get_human_actor(tenant_id: str, user_id: str) -> Optional[dict[str, Any]]:
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_actors(
|
||||
*,
|
||||
tenant_id: str,
|
||||
actor_type: Optional[str] = None,
|
||||
include_inactive: bool = False,
|
||||
q: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if actor_type is not None and actor_type not in ACTOR_TYPES:
|
||||
raise ValueError(f"Ungültiger actor_type: {actor_type}")
|
||||
|
||||
conditions = ["tenant_id = %s"]
|
||||
params: list[Any] = [tenant_id]
|
||||
|
||||
if not include_inactive:
|
||||
conditions.append("is_active = TRUE")
|
||||
if actor_type:
|
||||
conditions.append("actor_type = %s")
|
||||
params.append(actor_type)
|
||||
if q:
|
||||
conditions.append("name ILIKE %s")
|
||||
params.append(f"%{q.strip()}%")
|
||||
|
||||
where = " AND ".join(conditions)
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, actor_type, name, user_id, is_active
|
||||
FROM actors
|
||||
WHERE {where}
|
||||
ORDER BY
|
||||
CASE actor_type
|
||||
WHEN 'human' THEN 0
|
||||
WHEN 'working_group' THEN 1
|
||||
WHEN 'agent' THEN 2
|
||||
ELSE 3
|
||||
END,
|
||||
name
|
||||
""",
|
||||
params,
|
||||
)
|
||||
return [_serialize_actor(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_actor(*, tenant_id: str, actor_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, actor_type, name, user_id, is_active
|
||||
FROM actors
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return _serialize_actor(dict(row))
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,296 @@
|
||||
"""BacklogItem service — tenant-scoped CRUD + convert (AP0.8c)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.actions import create_action
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import PRIORITIES, get_initiative
|
||||
|
||||
BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"]
|
||||
|
||||
BACKLOG_STATUSES = frozenset({"new", "triaged", "accepted", "rejected", "converted"})
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "converted_action_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
if result.get("updated_at"):
|
||||
result["updated_at"] = result["updated_at"].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in BACKLOG_STATUSES:
|
||||
raise ValueError(f"Ungültiger Backlog-Status: {status}")
|
||||
|
||||
|
||||
def _validate_priority(priority: str) -> None:
|
||||
if priority not in PRIORITIES:
|
||||
raise ValueError(f"Ungültige Priorität: {priority}")
|
||||
|
||||
|
||||
def create_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: BacklogStatus = "new",
|
||||
priority: str = "normal",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
_validate_priority(priority)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO backlog_items (
|
||||
tenant_id, initiative_id, title, description, status, priority
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
(tenant_id, initiative_id, title, description, status, priority),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": row["id"], "initiative_id": initiative_id, "title": title},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_backlog_for_initiative(*, tenant_id: str, initiative_id: str) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
FROM backlog_items
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_backlog_item(*, tenant_id: str, backlog_item_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
FROM backlog_items
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(backlog_item_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[BacklogStatus] = None,
|
||||
priority: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
|
||||
if not existing:
|
||||
return None
|
||||
if existing["status"] == "converted":
|
||||
raise ValueError("Konvertiertes Backlog-Item kann nicht bearbeitet werden")
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if priority is not None:
|
||||
_validate_priority(priority)
|
||||
updates.append("priority = %s")
|
||||
params.append(priority)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([backlog_item_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE backlog_items
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": backlog_item_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"backlog.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"backlog_item_id": backlog_item_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(backlog_item_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"backlog.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": backlog_item_id},
|
||||
)
|
||||
return deleted
|
||||
|
||||
|
||||
def convert_backlog_to_action(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
assigned_actor_ids: Optional[list[str]] = None,
|
||||
) -> dict[str, Any]:
|
||||
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
|
||||
if not existing:
|
||||
raise ValueError("Backlog-Item nicht gefunden")
|
||||
if existing["status"] == "converted":
|
||||
raise ValueError("Backlog-Item wurde bereits konvertiert")
|
||||
if existing["status"] not in ("accepted", "triaged", "new"):
|
||||
raise ValueError("Backlog-Item kann in diesem Status nicht konvertiert werden")
|
||||
|
||||
action = create_action(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
title=existing["title"],
|
||||
description=existing["description"] or "",
|
||||
priority=existing["priority"],
|
||||
assigned_actor_ids=assigned_actor_ids or [],
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE backlog_items
|
||||
SET status = 'converted',
|
||||
converted_action_id = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
(action["id"], backlog_item_id, tenant_id),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.converted_to_action",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"backlog_item_id": backlog_item_id,
|
||||
"action_id": action["id"],
|
||||
"initiative_id": existing["initiative_id"],
|
||||
},
|
||||
)
|
||||
return {"backlog_item": row, "action": action}
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Blocker service — tenant-scoped CRUD (AP0.8b)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
BlockerStatus = Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"]
|
||||
|
||||
BLOCKER_STATUSES = frozenset(
|
||||
{"open", "in_progress", "resolved", "accepted_risk", "dismissed"}
|
||||
)
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "action_id", "reported_by_actor_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
if result.get("updated_at"):
|
||||
result["updated_at"] = result["updated_at"].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in BLOCKER_STATUSES:
|
||||
raise ValueError(f"Ungültiger Blocker-Status: {status}")
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _action_in_initiative(*, tenant_id: str, initiative_id: str, action_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(action_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: BlockerStatus = "open",
|
||||
action_id: Optional[str] = None,
|
||||
reported_by_actor_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
set_action_blocked: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
if action_id and not _action_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, action_id=action_id
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
if reported_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=reported_by_actor_id
|
||||
):
|
||||
raise ValueError("Reporter-Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO blockers (
|
||||
tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
action_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
reported_by_actor_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
if set_action_blocked and action_id:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE actions SET status = 'blocked', updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"blocker.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": row["id"], "initiative_id": initiative_id, "title": title},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_blockers_for_initiative(*, tenant_id: str, initiative_id: str) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
FROM blockers
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_blocker(*, tenant_id: str, blocker_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
FROM blockers
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(blocker_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
blocker_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[BlockerStatus] = None,
|
||||
action_id: Optional[str] = None,
|
||||
clear_action_id: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_blocker(tenant_id=tenant_id, blocker_id=blocker_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if clear_action_id:
|
||||
updates.append("action_id = NULL")
|
||||
elif action_id is not None:
|
||||
if not _action_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
action_id=action_id,
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
updates.append("action_id = %s")
|
||||
params.append(action_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([blocker_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE blockers
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"blocker.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": blocker_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"blocker.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"blocker_id": blocker_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
from services.operating_transitions import after_blocker_status_change
|
||||
|
||||
after_blocker_status_change(
|
||||
tenant_id=tenant_id,
|
||||
blocker_id=blocker_id,
|
||||
action_id=result.get("action_id"),
|
||||
initiative_id=result.get("initiative_id"),
|
||||
old_status=old_status,
|
||||
new_status=status,
|
||||
user_id=user_id,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
blocker_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM blockers WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(blocker_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"blocker.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": blocker_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Decision service — tenant-scoped CRUD (AP0.9c)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
DecisionStatus = Literal["proposed", "decided", "superseded"]
|
||||
|
||||
DECISION_STATUSES = frozenset({"proposed", "decided", "superseded"})
|
||||
|
||||
_DECISION_COLUMNS = """
|
||||
id, tenant_id, initiative_id, title, description, status, outcome,
|
||||
decided_by_actor_id, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "decided_by_actor_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("created_at", "updated_at"):
|
||||
if result.get(ts_key):
|
||||
result[ts_key] = result[ts_key].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in DECISION_STATUSES:
|
||||
raise ValueError(f"Ungültiger Decision-Status: {status}")
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_decision(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: DecisionStatus = "proposed",
|
||||
outcome: str = "",
|
||||
decided_by_actor_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
if decided_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=decided_by_actor_id
|
||||
):
|
||||
raise ValueError("Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO decisions (
|
||||
tenant_id, initiative_id, title, description, status, outcome,
|
||||
decided_by_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_DECISION_COLUMNS}
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
outcome,
|
||||
decided_by_actor_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"decision.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"decision_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_decisions_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_DECISION_COLUMNS}
|
||||
FROM decisions
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_decision(*, tenant_id: str, decision_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_DECISION_COLUMNS}
|
||||
FROM decisions
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(decision_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_decision(
|
||||
*,
|
||||
tenant_id: str,
|
||||
decision_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[DecisionStatus] = None,
|
||||
outcome: Optional[str] = None,
|
||||
decided_by_actor_id: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_decision(tenant_id=tenant_id, decision_id=decision_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if outcome is not None:
|
||||
updates.append("outcome = %s")
|
||||
params.append(outcome)
|
||||
if decided_by_actor_id is not None:
|
||||
if decided_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=decided_by_actor_id
|
||||
):
|
||||
raise ValueError("Actor gehört nicht zum Tenant")
|
||||
updates.append("decided_by_actor_id = %s")
|
||||
params.append(decided_by_actor_id or None)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([decision_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE decisions
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING {_DECISION_COLUMNS}
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"decision.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"decision_id": decision_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"decision.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"decision_id": decision_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_decision(
|
||||
*,
|
||||
tenant_id: str,
|
||||
decision_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM decisions WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(decision_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"decision.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"decision_id": decision_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Evidence service — tenant-scoped CRUD (AP0.9b)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
EvidenceStatus = Literal["submitted", "accepted", "rejected"]
|
||||
|
||||
EVIDENCE_STATUSES = frozenset({"submitted", "accepted", "rejected"})
|
||||
|
||||
_EVIDENCE_COLUMNS = """
|
||||
id, tenant_id, initiative_id, action_id, milestone_id, title, description,
|
||||
status, submitted_by_actor_id, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in (
|
||||
"id",
|
||||
"tenant_id",
|
||||
"initiative_id",
|
||||
"action_id",
|
||||
"milestone_id",
|
||||
"submitted_by_actor_id",
|
||||
):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("created_at", "updated_at"):
|
||||
if result.get(ts_key):
|
||||
result[ts_key] = result[ts_key].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in EVIDENCE_STATUSES:
|
||||
raise ValueError(f"Ungültiger Evidence-Status: {status}")
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _action_in_initiative(*, tenant_id: str, initiative_id: str, action_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(action_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _milestone_in_initiative(
|
||||
*, tenant_id: str, initiative_id: str, milestone_id: str
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM milestones
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(milestone_id, tenant_id, initiative_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
return True
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM roadmap_items ri
|
||||
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
|
||||
WHERE ri.id = %s AND ri.tenant_id = %s AND r.initiative_id = %s
|
||||
AND ri.item_type = 'milestone'
|
||||
""",
|
||||
(milestone_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_evidence(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: EvidenceStatus = "submitted",
|
||||
action_id: Optional[str] = None,
|
||||
milestone_id: Optional[str] = None,
|
||||
submitted_by_actor_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
if action_id and not _action_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, action_id=action_id
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
if milestone_id and not _milestone_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, milestone_id=milestone_id
|
||||
):
|
||||
raise ValueError("Meilenstein gehört nicht zum Vorhaben")
|
||||
if submitted_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=submitted_by_actor_id
|
||||
):
|
||||
raise ValueError("Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO evidence (
|
||||
tenant_id, initiative_id, action_id, milestone_id,
|
||||
title, description, status, submitted_by_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_EVIDENCE_COLUMNS}
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
action_id,
|
||||
milestone_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
submitted_by_actor_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"evidence.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"evidence_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_evidence_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_EVIDENCE_COLUMNS}
|
||||
FROM evidence
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_evidence(*, tenant_id: str, evidence_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_EVIDENCE_COLUMNS}
|
||||
FROM evidence
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(evidence_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_evidence(
|
||||
*,
|
||||
tenant_id: str,
|
||||
evidence_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[EvidenceStatus] = None,
|
||||
action_id: Optional[str] = None,
|
||||
milestone_id: Optional[str] = None,
|
||||
clear_action_id: bool = False,
|
||||
clear_milestone_id: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_evidence(tenant_id=tenant_id, evidence_id=evidence_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if clear_action_id:
|
||||
updates.append("action_id = NULL")
|
||||
elif action_id is not None:
|
||||
if not _action_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
action_id=action_id,
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
updates.append("action_id = %s")
|
||||
params.append(action_id)
|
||||
if clear_milestone_id:
|
||||
updates.append("milestone_id = NULL")
|
||||
elif milestone_id is not None:
|
||||
if not _milestone_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
milestone_id=milestone_id,
|
||||
):
|
||||
raise ValueError("Meilenstein gehört nicht zum Vorhaben")
|
||||
updates.append("milestone_id = %s")
|
||||
params.append(milestone_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([evidence_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE evidence
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING {_EVIDENCE_COLUMNS}
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"evidence.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"evidence_id": evidence_id},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_evidence(
|
||||
*,
|
||||
tenant_id: str,
|
||||
evidence_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM evidence WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(evidence_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"evidence.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"evidence_id": evidence_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,259 @@
|
||||
"""Initiative (Vorhaben) service — tenant-scoped CRUD."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
|
||||
InitiativeStatus = Literal["active", "paused", "completed", "archived"]
|
||||
Priority = Literal["low", "normal", "high"]
|
||||
|
||||
INITIATIVE_STATUSES = frozenset({"active", "paused", "completed", "archived"})
|
||||
PRIORITIES = frozenset({"low", "normal", "high"})
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "owner_actor_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
if result.get("updated_at"):
|
||||
result["updated_at"] = result["updated_at"].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_initiative_status(status: str) -> None:
|
||||
if status not in INITIATIVE_STATUSES:
|
||||
raise ValueError(f"Ungültiger Initiative-Status: {status}")
|
||||
|
||||
|
||||
def _validate_priority(priority: str) -> None:
|
||||
if priority not in PRIORITIES:
|
||||
raise ValueError(f"Ungültige Priorität: {priority}")
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_initiative(
|
||||
*,
|
||||
tenant_id: str,
|
||||
title: str,
|
||||
owner_actor_id: str,
|
||||
goal: str = "",
|
||||
status: InitiativeStatus = "active",
|
||||
priority: Priority = "normal",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_initiative_status(status)
|
||||
_validate_priority(priority)
|
||||
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=owner_actor_id):
|
||||
raise ValueError("Owner-Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO initiatives (
|
||||
tenant_id, title, goal, status, priority, owner_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, title, goal, status, priority,
|
||||
owner_actor_id, created_at, updated_at
|
||||
""",
|
||||
(tenant_id, title, goal, status, priority, owner_actor_id),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"initiative.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"initiative_id": row["id"], "title": title, "status": status},
|
||||
)
|
||||
from services.steering_context import create_context_for_new_initiative
|
||||
|
||||
create_context_for_new_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=row["id"],
|
||||
user_id=user_id,
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_initiatives(*, tenant_id: str) -> list[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, title, goal, status, priority,
|
||||
owner_actor_id, created_at, updated_at
|
||||
FROM initiatives
|
||||
WHERE tenant_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id,),
|
||||
)
|
||||
return [_serialize_row(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_initiative(*, tenant_id: str, initiative_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, title, goal, status, priority,
|
||||
owner_actor_id, created_at, updated_at
|
||||
FROM initiatives
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(initiative_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_initiative(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
goal: Optional[str] = None,
|
||||
status: Optional[InitiativeStatus] = None,
|
||||
priority: Optional[Priority] = None,
|
||||
owner_actor_id: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
old_status = existing["status"]
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if goal is not None:
|
||||
updates.append("goal = %s")
|
||||
params.append(goal)
|
||||
if status is not None:
|
||||
_validate_initiative_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if priority is not None:
|
||||
_validate_priority(priority)
|
||||
updates.append("priority = %s")
|
||||
params.append(priority)
|
||||
if owner_actor_id is not None:
|
||||
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=owner_actor_id):
|
||||
raise ValueError("Owner-Actor gehört nicht zum Tenant")
|
||||
updates.append("owner_actor_id = %s")
|
||||
params.append(owner_actor_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([initiative_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE initiatives
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, title, goal, status, priority,
|
||||
owner_actor_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"initiative.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"initiative_id": initiative_id, "fields": updates},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"initiative.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"initiative_id": initiative_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_initiative(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM initiatives WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(initiative_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"initiative.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"initiative_id": initiative_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Milestone service — Kompatibilitäts-Wrapper auf RoadmapItems (AP0.8d → AP1.4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from services import roadmap as roadmap_service
|
||||
|
||||
MilestoneStatus = Literal[
|
||||
"planned", "active", "at_risk", "reached", "moved", "discarded"
|
||||
]
|
||||
|
||||
MILESTONE_STATUSES = roadmap_service.ROADMAP_ITEM_STATUSES
|
||||
|
||||
|
||||
def _as_milestone(item: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": item["id"],
|
||||
"tenant_id": item["tenant_id"],
|
||||
"initiative_id": item["initiative_id"],
|
||||
"title": item["title"],
|
||||
"goal_description": item.get("goal_description", ""),
|
||||
"status": item["status"],
|
||||
"target_date": item.get("target_date"),
|
||||
"created_at": item["created_at"],
|
||||
"updated_at": item["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def create_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
goal_description: str = "",
|
||||
status: MilestoneStatus = "planned",
|
||||
target_date: Optional[date] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
item = roadmap_service.create_roadmap_item(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=title,
|
||||
item_type="milestone",
|
||||
goal_description=goal_description,
|
||||
status=status,
|
||||
target_date=target_date,
|
||||
user_id=user_id,
|
||||
)
|
||||
return _as_milestone(item)
|
||||
|
||||
|
||||
def list_milestones_for_initiative(*, tenant_id: str, initiative_id: str) -> list[dict[str, Any]]:
|
||||
items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
return [_as_milestone(i) for i in items if i["item_type"] == "milestone"]
|
||||
|
||||
|
||||
def get_milestone(*, tenant_id: str, milestone_id: str) -> Optional[dict[str, Any]]:
|
||||
item = roadmap_service.get_roadmap_item(tenant_id=tenant_id, item_id=milestone_id)
|
||||
if not item or item["item_type"] != "milestone":
|
||||
return None
|
||||
return _as_milestone(item)
|
||||
|
||||
|
||||
def update_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
milestone_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
goal_description: Optional[str] = None,
|
||||
status: Optional[MilestoneStatus] = None,
|
||||
target_date: Optional[date] = None,
|
||||
clear_target_date: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
item = roadmap_service.update_roadmap_item(
|
||||
tenant_id=tenant_id,
|
||||
item_id=milestone_id,
|
||||
user_id=user_id,
|
||||
title=title,
|
||||
goal_description=goal_description,
|
||||
status=status,
|
||||
target_date=target_date,
|
||||
clear_target_date=clear_target_date,
|
||||
)
|
||||
return _as_milestone(item) if item else None
|
||||
|
||||
|
||||
def delete_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
milestone_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
item = roadmap_service.get_roadmap_item(tenant_id=tenant_id, item_id=milestone_id)
|
||||
if not item or item["item_type"] != "milestone":
|
||||
return False
|
||||
return roadmap_service.delete_roadmap_item(
|
||||
tenant_id=tenant_id, item_id=milestone_id, user_id=user_id
|
||||
)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Minimale Operating-Transitions — AP1.0 mit Hook Dispatch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from steering.hooks.dispatch import dispatch_hook
|
||||
|
||||
RESOLVED_BLOCKER_STATUSES = frozenset({"resolved", "accepted_risk", "dismissed"})
|
||||
|
||||
|
||||
def after_blocker_status_change(
|
||||
*,
|
||||
tenant_id: str,
|
||||
blocker_id: str,
|
||||
action_id: Optional[str],
|
||||
initiative_id: Optional[str] = None,
|
||||
old_status: str,
|
||||
new_status: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Blocker geschlossen → verknüpfte blockierte Maßnahme entblocken."""
|
||||
effects: list[dict[str, Any]] = []
|
||||
if new_status == old_status:
|
||||
return effects
|
||||
if new_status not in RESOLVED_BLOCKER_STATUSES or not action_id:
|
||||
return effects
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, status FROM actions
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
action = cur.fetchone()
|
||||
if not action or action["status"] != "blocked":
|
||||
return effects
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS remaining
|
||||
FROM blockers
|
||||
WHERE tenant_id = %s AND action_id = %s
|
||||
AND id != %s AND status IN ('open', 'in_progress')
|
||||
""",
|
||||
(tenant_id, action_id, blocker_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
remaining = int(row["remaining"]) if row else 0
|
||||
if remaining > 0:
|
||||
effects.append(
|
||||
{
|
||||
"kind": "action_still_blocked",
|
||||
"action_id": str(action_id),
|
||||
"reason": "other_open_blockers",
|
||||
}
|
||||
)
|
||||
return effects
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE actions SET status = 'open', updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s AND status = 'blocked'
|
||||
RETURNING id
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
effects.append(
|
||||
{
|
||||
"kind": "action_unblocked",
|
||||
"action_id": str(action_id),
|
||||
"trigger": "blocker_resolved",
|
||||
"blocker_id": blocker_id,
|
||||
}
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if effects:
|
||||
dispatch_hook(
|
||||
"on_blocker_resolved",
|
||||
None,
|
||||
{
|
||||
"blocker_id": blocker_id,
|
||||
"action_id": action_id,
|
||||
"initiative_id": initiative_id,
|
||||
"effects": effects,
|
||||
},
|
||||
tenant_id=tenant_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
if initiative_id and user_id:
|
||||
from steering.lifecycle.orchestrator import transition
|
||||
|
||||
transition(
|
||||
None,
|
||||
initiative_id,
|
||||
"action_selection",
|
||||
reason="blocker_resolved",
|
||||
tenant_id=tenant_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
if effects and user_id:
|
||||
from services.audit import log_audit
|
||||
|
||||
log_audit(
|
||||
"operating_transition.action_unblocked",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"effects": effects, "blocker_id": blocker_id},
|
||||
)
|
||||
return effects
|
||||
|
||||
|
||||
def after_review_status_change(
|
||||
*,
|
||||
tenant_id: str,
|
||||
review_id: str,
|
||||
action_id: Optional[str],
|
||||
initiative_id: Optional[str] = None,
|
||||
old_status: str,
|
||||
new_status: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Review abgeschlossen → Maßnahme aus review_required weiterführen."""
|
||||
effects: list[dict[str, Any]] = []
|
||||
if new_status == old_status or new_status != "completed" or not action_id:
|
||||
return effects
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE actions
|
||||
SET status = 'done', updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s AND status = 'review_required'
|
||||
RETURNING id
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
effects.append(
|
||||
{
|
||||
"kind": "action_completed_after_review",
|
||||
"action_id": str(action_id),
|
||||
"trigger": "review_completed",
|
||||
"review_id": review_id,
|
||||
}
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if effects:
|
||||
dispatch_hook(
|
||||
"on_review_completed",
|
||||
None,
|
||||
{
|
||||
"review_id": review_id,
|
||||
"action_id": action_id,
|
||||
"initiative_id": initiative_id,
|
||||
"effects": effects,
|
||||
},
|
||||
tenant_id=tenant_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
if effects and user_id:
|
||||
from services.audit import log_audit
|
||||
|
||||
log_audit(
|
||||
"operating_transition.action_completed_after_review",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"effects": effects, "review_id": review_id},
|
||||
)
|
||||
return effects
|
||||
@@ -0,0 +1,260 @@
|
||||
"""RecurringElement service — tenant-scoped CRUD (AP0.9e)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
RecurringStatus = Literal["active", "paused", "ended"]
|
||||
|
||||
RECURRING_STATUSES = frozenset({"active", "paused", "ended"})
|
||||
|
||||
_RECURRING_COLUMNS = """
|
||||
id, tenant_id, initiative_id, title, description, status,
|
||||
interval_days, next_due_at, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("created_at", "updated_at", "next_due_at"):
|
||||
if result.get(ts_key):
|
||||
result[ts_key] = result[ts_key].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in RECURRING_STATUSES:
|
||||
raise ValueError(f"Ungültiger Recurring-Status: {status}")
|
||||
|
||||
|
||||
def create_recurring_element(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: RecurringStatus = "active",
|
||||
interval_days: Optional[int] = None,
|
||||
next_due_at: Optional[datetime] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
if interval_days is not None and interval_days <= 0:
|
||||
raise ValueError("interval_days muss positiv sein")
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO recurring_elements (
|
||||
tenant_id, initiative_id, title, description, status,
|
||||
interval_days, next_due_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_RECURRING_COLUMNS}
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
interval_days,
|
||||
next_due_at,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"recurring.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"recurring_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_recurring_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_RECURRING_COLUMNS}
|
||||
FROM recurring_elements
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_recurring_element(
|
||||
*, tenant_id: str, recurring_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_RECURRING_COLUMNS}
|
||||
FROM recurring_elements
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(recurring_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_recurring_element(
|
||||
*,
|
||||
tenant_id: str,
|
||||
recurring_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[RecurringStatus] = None,
|
||||
interval_days: Optional[int] = None,
|
||||
clear_interval_days: bool = False,
|
||||
next_due_at: Optional[datetime] = None,
|
||||
clear_next_due_at: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if clear_interval_days:
|
||||
updates.append("interval_days = NULL")
|
||||
elif interval_days is not None:
|
||||
if interval_days <= 0:
|
||||
raise ValueError("interval_days muss positiv sein")
|
||||
updates.append("interval_days = %s")
|
||||
params.append(interval_days)
|
||||
if clear_next_due_at:
|
||||
updates.append("next_due_at = NULL")
|
||||
elif next_due_at is not None:
|
||||
updates.append("next_due_at = %s")
|
||||
params.append(next_due_at)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([recurring_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE recurring_elements
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING {_RECURRING_COLUMNS}
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"recurring.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"recurring_id": recurring_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"recurring.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"recurring_id": recurring_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_recurring_element(
|
||||
*,
|
||||
tenant_id: str,
|
||||
recurring_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM recurring_elements
|
||||
WHERE id = %s AND tenant_id = %s RETURNING id
|
||||
""",
|
||||
(recurring_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"recurring.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"recurring_id": recurring_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,351 @@
|
||||
"""Review service — tenant-scoped CRUD (AP0.9d)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
ReviewStatus = Literal["planned", "completed", "skipped"]
|
||||
|
||||
REVIEW_STATUSES = frozenset({"planned", "completed", "skipped"})
|
||||
|
||||
_REVIEW_COLUMNS = """
|
||||
id, tenant_id, initiative_id, action_id, milestone_id, title, summary,
|
||||
status, due_at, reviewed_by_actor_id, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in (
|
||||
"id",
|
||||
"tenant_id",
|
||||
"initiative_id",
|
||||
"action_id",
|
||||
"milestone_id",
|
||||
"reviewed_by_actor_id",
|
||||
):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("created_at", "updated_at", "due_at"):
|
||||
if result.get(ts_key):
|
||||
result[ts_key] = result[ts_key].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in REVIEW_STATUSES:
|
||||
raise ValueError(f"Ungültiger Review-Status: {status}")
|
||||
|
||||
|
||||
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
||||
(actor_id, tenant_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _action_in_initiative(*, tenant_id: str, initiative_id: str, action_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(action_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _milestone_in_initiative(
|
||||
*, tenant_id: str, initiative_id: str, milestone_id: str
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM milestones
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(milestone_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_review(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
summary: str = "",
|
||||
status: ReviewStatus = "planned",
|
||||
due_at: Optional[datetime] = None,
|
||||
action_id: Optional[str] = None,
|
||||
milestone_id: Optional[str] = None,
|
||||
reviewed_by_actor_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
if action_id and not _action_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, action_id=action_id
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
if milestone_id and not _milestone_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, milestone_id=milestone_id
|
||||
):
|
||||
raise ValueError("Meilenstein gehört nicht zum Vorhaben")
|
||||
if reviewed_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=reviewed_by_actor_id
|
||||
):
|
||||
raise ValueError("Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO reviews (
|
||||
tenant_id, initiative_id, action_id, milestone_id,
|
||||
title, summary, status, due_at, reviewed_by_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_REVIEW_COLUMNS}
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
action_id,
|
||||
milestone_id,
|
||||
title,
|
||||
summary,
|
||||
status,
|
||||
due_at,
|
||||
reviewed_by_actor_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"review.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"review_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_reviews_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_REVIEW_COLUMNS}
|
||||
FROM reviews
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_review(*, tenant_id: str, review_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_REVIEW_COLUMNS}
|
||||
FROM reviews
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(review_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_review(
|
||||
*,
|
||||
tenant_id: str,
|
||||
review_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
summary: Optional[str] = None,
|
||||
status: Optional[ReviewStatus] = None,
|
||||
due_at: Optional[datetime] = None,
|
||||
clear_due_at: bool = False,
|
||||
action_id: Optional[str] = None,
|
||||
milestone_id: Optional[str] = None,
|
||||
clear_action_id: bool = False,
|
||||
clear_milestone_id: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_review(tenant_id=tenant_id, review_id=review_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if summary is not None:
|
||||
updates.append("summary = %s")
|
||||
params.append(summary)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if clear_due_at:
|
||||
updates.append("due_at = NULL")
|
||||
elif due_at is not None:
|
||||
updates.append("due_at = %s")
|
||||
params.append(due_at)
|
||||
if clear_action_id:
|
||||
updates.append("action_id = NULL")
|
||||
elif action_id is not None:
|
||||
if not _action_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
action_id=action_id,
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
updates.append("action_id = %s")
|
||||
params.append(action_id)
|
||||
if clear_milestone_id:
|
||||
updates.append("milestone_id = NULL")
|
||||
elif milestone_id is not None:
|
||||
if not _milestone_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
milestone_id=milestone_id,
|
||||
):
|
||||
raise ValueError("Meilenstein gehört nicht zum Vorhaben")
|
||||
updates.append("milestone_id = %s")
|
||||
params.append(milestone_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([review_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE reviews
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING {_REVIEW_COLUMNS}
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"review.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"review_id": review_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"review.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"review_id": review_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
from services.operating_transitions import after_review_status_change
|
||||
|
||||
after_review_status_change(
|
||||
tenant_id=tenant_id,
|
||||
review_id=review_id,
|
||||
action_id=result.get("action_id"),
|
||||
initiative_id=result.get("initiative_id"),
|
||||
old_status=old_status,
|
||||
new_status=status,
|
||||
user_id=user_id,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_review(
|
||||
*,
|
||||
tenant_id: str,
|
||||
review_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM reviews WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(review_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"review.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"review_id": review_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,621 @@
|
||||
"""Roadmap service — tenant-scoped Plan/Gates (AP1.4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
|
||||
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage"]
|
||||
RoadmapItemStatus = Literal[
|
||||
"planned", "active", "at_risk", "reached", "moved", "discarded"
|
||||
]
|
||||
SequencingMode = Literal["sequential", "parallel", "optional"]
|
||||
DependencyType = Literal["requires", "blocks", "related"]
|
||||
|
||||
ROADMAP_ITEM_TYPES = frozenset({"milestone", "review_gate", "maturity_stage"})
|
||||
ROADMAP_ITEM_STATUSES = frozenset(
|
||||
{"planned", "active", "at_risk", "reached", "moved", "discarded"}
|
||||
)
|
||||
SEQUENCING_MODES = frozenset({"sequential", "parallel", "optional"})
|
||||
DEPENDENCY_TYPES = frozenset({"requires", "blocks", "related"})
|
||||
|
||||
TERMINAL_STATUSES = frozenset({"reached", "moved", "discarded"})
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "roadmap_id", "initiative_id", "from_item_id", "to_item_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("target_date"):
|
||||
result["target_date"] = (
|
||||
result["target_date"].isoformat()
|
||||
if hasattr(result["target_date"], "isoformat")
|
||||
else str(result["target_date"])
|
||||
)
|
||||
for ts in ("created_at", "updated_at"):
|
||||
if result.get(ts):
|
||||
result[ts] = result[ts].isoformat()
|
||||
dod = result.get("definition_of_done")
|
||||
if isinstance(dod, str):
|
||||
result["definition_of_done"] = json.loads(dod)
|
||||
return result
|
||||
|
||||
|
||||
def _validate_item_type(item_type: str) -> None:
|
||||
if item_type not in ROADMAP_ITEM_TYPES:
|
||||
raise ValueError(f"Ungültiger RoadmapItem-Typ: {item_type}")
|
||||
|
||||
|
||||
def _validate_status(status: str) -> None:
|
||||
if status not in ROADMAP_ITEM_STATUSES:
|
||||
raise ValueError(f"Ungültiger RoadmapItem-Status: {status}")
|
||||
|
||||
|
||||
def _validate_sequencing_mode(mode: str) -> None:
|
||||
if mode not in SEQUENCING_MODES:
|
||||
raise ValueError(f"Ungültiger sequencing_mode: {mode}")
|
||||
|
||||
|
||||
def _validate_dependency_type(dep_type: str) -> None:
|
||||
if dep_type not in DEPENDENCY_TYPES:
|
||||
raise ValueError(f"Ungültiger dependency_type: {dep_type}")
|
||||
|
||||
|
||||
def _sync_milestone_compat_row(
|
||||
cur,
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
item: dict[str, Any],
|
||||
) -> None:
|
||||
"""Hält milestones-Tabelle für Evidence/Review-FKs synchron (Compat bis Drop)."""
|
||||
if item["item_type"] != "milestone":
|
||||
cur.execute(
|
||||
"DELETE FROM milestones WHERE id = %s AND tenant_id = %s",
|
||||
(item["id"], tenant_id),
|
||||
)
|
||||
return
|
||||
|
||||
target_date = item.get("target_date")
|
||||
if target_date and isinstance(target_date, str):
|
||||
target_date = date.fromisoformat(target_date)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO milestones (
|
||||
id, tenant_id, initiative_id, title, goal_description, status, target_date
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
title = EXCLUDED.title,
|
||||
goal_description = EXCLUDED.goal_description,
|
||||
status = EXCLUDED.status,
|
||||
target_date = EXCLUDED.target_date,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
item["id"],
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
item["title"],
|
||||
item.get("goal_description", ""),
|
||||
item["status"],
|
||||
target_date,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def ensure_roadmap(*, tenant_id: str, initiative_id: str) -> dict[str, Any]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, created_at, updated_at
|
||||
FROM roadmaps
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return _serialize_row(dict(row))
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO roadmaps (tenant_id, initiative_id, title)
|
||||
VALUES (%s, %s, 'Plan')
|
||||
RETURNING id, tenant_id, initiative_id, title, created_at, updated_at
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
result = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_roadmap_for_initiative(*, tenant_id: str, initiative_id: str) -> Optional[dict[str, Any]]:
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, created_at, updated_at
|
||||
FROM roadmaps
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_roadmap_items_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
roadmap = get_roadmap_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not roadmap:
|
||||
return []
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
ri.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
|
||||
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
|
||||
ri.status, ri.sequencing_mode, ri.target_date, 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.target_date NULLS LAST, ri.title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_roadmap_item(*, tenant_id: str, item_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
ri.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
|
||||
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
|
||||
ri.status, ri.sequencing_mode, ri.target_date, 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.id = %s AND ri.tenant_id = %s
|
||||
""",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_roadmap_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
item_type: RoadmapItemType = "milestone",
|
||||
goal_description: str = "",
|
||||
definition_of_done: Optional[list[Any]] = None,
|
||||
status: RoadmapItemStatus = "planned",
|
||||
sequencing_mode: SequencingMode = "sequential",
|
||||
target_date: Optional[date] = None,
|
||||
sort_order: int = 0,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_item_type(item_type)
|
||||
_validate_status(status)
|
||||
if status == "reached":
|
||||
raise ValueError("Status 'reached' nur über verify-reached")
|
||||
_validate_sequencing_mode(sequencing_mode)
|
||||
|
||||
roadmap = ensure_roadmap(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
dod = definition_of_done if definition_of_done is not None else []
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO roadmap_items (
|
||||
tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date, sort_order
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
roadmap["id"],
|
||||
item_type,
|
||||
title,
|
||||
goal_description,
|
||||
json.dumps(dod),
|
||||
status,
|
||||
sequencing_mode,
|
||||
target_date,
|
||||
sort_order,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
row["initiative_id"] = initiative_id
|
||||
_sync_milestone_compat_row(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
item=row,
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"roadmap_item.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"roadmap_item_id": row["id"],
|
||||
"initiative_id": initiative_id,
|
||||
"item_type": item_type,
|
||||
"title": title,
|
||||
},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def update_roadmap_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
goal_description: Optional[str] = None,
|
||||
definition_of_done: Optional[list[Any]] = None,
|
||||
item_type: Optional[RoadmapItemType] = None,
|
||||
status: Optional[RoadmapItemStatus] = None,
|
||||
sequencing_mode: Optional[SequencingMode] = None,
|
||||
target_date: Optional[date] = None,
|
||||
clear_target_date: bool = False,
|
||||
sort_order: Optional[int] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
old_status = existing["status"]
|
||||
updates: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
updates.append("title = %s")
|
||||
params.append(title)
|
||||
if goal_description is not None:
|
||||
updates.append("goal_description = %s")
|
||||
params.append(goal_description)
|
||||
if definition_of_done is not None:
|
||||
updates.append("definition_of_done = %s::jsonb")
|
||||
params.append(json.dumps(definition_of_done))
|
||||
if item_type is not None:
|
||||
_validate_item_type(item_type)
|
||||
updates.append("item_type = %s")
|
||||
params.append(item_type)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
if status in TERMINAL_STATUSES and status == "reached":
|
||||
raise ValueError(
|
||||
"Status 'reached' nur über verify-reached — nicht direkt setzen"
|
||||
)
|
||||
if status in ("moved", "discarded"):
|
||||
raise ValueError(
|
||||
"Status moved/discarded erfordert Decision — noch nicht implementiert"
|
||||
)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if sequencing_mode is not None:
|
||||
_validate_sequencing_mode(sequencing_mode)
|
||||
updates.append("sequencing_mode = %s")
|
||||
params.append(sequencing_mode)
|
||||
if clear_target_date:
|
||||
updates.append("target_date = NULL")
|
||||
elif target_date is not None:
|
||||
updates.append("target_date = %s")
|
||||
params.append(target_date)
|
||||
if sort_order is not None:
|
||||
updates.append("sort_order = %s")
|
||||
params.append(sort_order)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([item_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE roadmap_items
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
result["initiative_id"] = existing["initiative_id"]
|
||||
_sync_milestone_compat_row(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
item=result,
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"roadmap_item.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"roadmap_item_id": item_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"roadmap_item.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"roadmap_item_id": item_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_roadmap_item(
|
||||
*, tenant_id: str, item_id: str, user_id: Optional[str] = None
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM milestones WHERE id = %s AND tenant_id = %s",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
cur.execute(
|
||||
"DELETE FROM roadmap_items WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"roadmap_item.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"roadmap_item_id": item_id},
|
||||
)
|
||||
return deleted
|
||||
|
||||
|
||||
def list_dependencies(*, tenant_id: str, item_id: str) -> list[dict[str, Any]]:
|
||||
item = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not item:
|
||||
raise ValueError("RoadmapItem nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, from_item_id, to_item_id, dependency_type, created_at
|
||||
FROM roadmap_item_dependencies
|
||||
WHERE tenant_id = %s AND (from_item_id = %s OR to_item_id = %s)
|
||||
ORDER BY created_at ASC
|
||||
""",
|
||||
(tenant_id, item_id, item_id),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
dep = dict(row)
|
||||
for key in ("id", "tenant_id", "from_item_id", "to_item_id"):
|
||||
dep[key] = str(dep[key])
|
||||
if dep.get("created_at"):
|
||||
dep["created_at"] = dep["created_at"].isoformat()
|
||||
items.append(dep)
|
||||
return items
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def add_dependency(
|
||||
*,
|
||||
tenant_id: str,
|
||||
from_item_id: str,
|
||||
to_item_id: str,
|
||||
dependency_type: DependencyType = "requires",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
_validate_dependency_type(dependency_type)
|
||||
if from_item_id == to_item_id:
|
||||
raise ValueError("Abhängigkeit auf sich selbst nicht erlaubt")
|
||||
|
||||
from_item = get_roadmap_item(tenant_id=tenant_id, item_id=from_item_id)
|
||||
to_item = get_roadmap_item(tenant_id=tenant_id, item_id=to_item_id)
|
||||
if not from_item or not to_item:
|
||||
raise ValueError("RoadmapItem nicht gefunden")
|
||||
if from_item["initiative_id"] != to_item["initiative_id"]:
|
||||
raise ValueError("Abhängigkeiten nur innerhalb eines Vorhabens")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO roadmap_item_dependencies (
|
||||
tenant_id, from_item_id, to_item_id, dependency_type
|
||||
)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, from_item_id, to_item_id, dependency_type, created_at
|
||||
""",
|
||||
(tenant_id, from_item_id, to_item_id, dependency_type),
|
||||
)
|
||||
row = dict(cur.fetchone())
|
||||
for key in ("id", "tenant_id", "from_item_id", "to_item_id"):
|
||||
row[key] = str(row[key])
|
||||
row["created_at"] = row["created_at"].isoformat()
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"roadmap_item.dependency_added",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"from_item_id": from_item_id,
|
||||
"to_item_id": to_item_id,
|
||||
"dependency_type": dependency_type,
|
||||
},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def verify_reached(
|
||||
*, tenant_id: str, item_id: str, user_id: Optional[str] = None
|
||||
) -> dict[str, Any]:
|
||||
"""Gate-Verify: reached nur mit accepted Evidence, completed Review oder gate_override Decision."""
|
||||
item = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not item:
|
||||
raise ValueError("RoadmapItem nicht gefunden")
|
||||
if item["status"] in TERMINAL_STATUSES:
|
||||
raise ValueError(f"RoadmapItem bereits terminal: {item['status']}")
|
||||
|
||||
initiative_id = item["initiative_id"]
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM evidence
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
AND status = 'accepted'
|
||||
AND milestone_id = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, initiative_id, item_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
verify_reason = "evidence_accepted"
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM reviews
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
AND status = 'completed'
|
||||
AND (milestone_id = %s)
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, initiative_id, item_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
verify_reason = "review_completed"
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM decisions
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
AND status = 'decided'
|
||||
AND title ILIKE %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, initiative_id, f"gate_override:{item_id}%"),
|
||||
)
|
||||
if cur.fetchone():
|
||||
verify_reason = "gate_override_decision"
|
||||
else:
|
||||
raise ValueError(
|
||||
"Verify fehlgeschlagen — accepted Evidence, completed Review "
|
||||
"oder gate_override Decision erforderlich"
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE roadmap_items
|
||||
SET status = 'reached', updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
""",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
row["initiative_id"] = initiative_id
|
||||
row["verify_reason"] = verify_reason
|
||||
_sync_milestone_compat_row(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
item=row,
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"roadmap_item.reached",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"roadmap_item_id": item_id, "verify_reason": verify_reason},
|
||||
)
|
||||
return row
|
||||
@@ -0,0 +1,259 @@
|
||||
"""SteeringContext write service — AP1.0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor, Json
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
from steering.lifecycle.states import validate_lifecycle_state
|
||||
|
||||
DEFAULT_METHOD_KEY = "generic_operating"
|
||||
DEFAULT_METHOD_VERSION = "0.1.0"
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
if result.get("updated_at"):
|
||||
result["updated_at"] = result["updated_at"].isoformat()
|
||||
if isinstance(result.get("lifecycle_metadata"), dict):
|
||||
pass
|
||||
elif result.get("lifecycle_metadata") is not None:
|
||||
result["lifecycle_metadata"] = dict(result["lifecycle_metadata"])
|
||||
return result
|
||||
|
||||
|
||||
def _infer_initial_lifecycle_state(*, tenant_id: str, initiative_id: str) -> str:
|
||||
initiative = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not initiative:
|
||||
return "intake"
|
||||
if initiative["status"] in ("completed", "archived"):
|
||||
return "closure"
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
AND status IN (
|
||||
'open', 'ready', 'in_progress', 'blocked', 'review_required'
|
||||
)
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
return "action_selection"
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM backlog_items
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
AND status IN ('new', 'triaged', 'accepted')
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
return "structure_setup"
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return "planning"
|
||||
|
||||
|
||||
def get_steering_context(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, method_key, method_version,
|
||||
lifecycle_state, lifecycle_metadata, created_at, updated_at
|
||||
FROM steering_contexts
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def ensure_steering_context(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
initial_state: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Vorhaben nicht gefunden")
|
||||
|
||||
state = initial_state or _infer_initial_lifecycle_state(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
validate_lifecycle_state(state)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO steering_contexts (
|
||||
tenant_id, initiative_id, method_key, method_version,
|
||||
lifecycle_state, lifecycle_metadata
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id, method_key, method_version,
|
||||
lifecycle_state, lifecycle_metadata, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
DEFAULT_METHOD_KEY,
|
||||
DEFAULT_METHOD_VERSION,
|
||||
state,
|
||||
Json({}),
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"steering_context.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"initiative_id": initiative_id, "lifecycle_state": state},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def update_lifecycle_state(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
lifecycle_state: str,
|
||||
user_id: Optional[str] = None,
|
||||
reason: str = "",
|
||||
from_state: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
validate_lifecycle_state(lifecycle_state)
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE steering_contexts
|
||||
SET lifecycle_state = %s, updated_at = NOW()
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, method_key, method_version,
|
||||
lifecycle_state, lifecycle_metadata, created_at, updated_at
|
||||
""",
|
||||
(lifecycle_state, tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError("SteeringContext nicht gefunden")
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"steering_context.lifecycle_transition",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": from_state,
|
||||
"to_state": lifecycle_state,
|
||||
"reason": reason,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def update_method_key(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
method_key: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
from steering.methods.registry import get_method
|
||||
|
||||
method = get_method(method_key)
|
||||
if not method:
|
||||
raise ValueError(f"Unbekannte Methode: {method_key}")
|
||||
|
||||
existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not existing:
|
||||
raise ValueError("SteeringContext nicht gefunden")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE steering_contexts
|
||||
SET method_key = %s, method_version = %s, updated_at = NOW()
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, method_key, method_version,
|
||||
lifecycle_state, lifecycle_metadata, created_at, updated_at
|
||||
""",
|
||||
(method.key, method.version, tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError("SteeringContext nicht gefunden")
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"steering_context.method_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"initiative_id": initiative_id,
|
||||
"from_method": existing["method_key"],
|
||||
"to_method": method_key,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def create_context_for_new_initiative(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
return ensure_steering_context(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
initial_state="intake",
|
||||
user_id=user_id,
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Adaptive Steering Core — AP1.0 Foundation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.hooks.registry import register_builtin_hooks
|
||||
from steering.methods.registrations import generic_operating, product_milestone_driven
|
||||
from steering.strategies.next_action import register_builtin_strategies
|
||||
|
||||
|
||||
def bootstrap_steering() -> None:
|
||||
"""Register built-in hooks, methods and strategies (idempotent)."""
|
||||
register_builtin_hooks()
|
||||
register_builtin_strategies()
|
||||
generic_operating.register()
|
||||
product_milestone_driven.register()
|
||||
|
||||
|
||||
bootstrap_steering()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""SteeringContext read helpers — AP1.0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from services import steering_context as sc_service
|
||||
from steering.lifecycle.states import lifecycle_label
|
||||
from steering.methods.registry import get_method
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def get_steering_context_dto(
|
||||
ctx: TenantContext, *, initiative_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
row = sc_service.get_steering_context(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if not row:
|
||||
row = sc_service.ensure_steering_context(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
)
|
||||
method = get_method(row["method_key"])
|
||||
return {
|
||||
**row,
|
||||
"lifecycle_label": lifecycle_label(row["lifecycle_state"]),
|
||||
"method_label": method.label if method else row["method_key"],
|
||||
}
|
||||
|
||||
|
||||
def get_or_create_for_initiative(
|
||||
ctx: TenantContext, *, initiative_id: str
|
||||
) -> dict[str, Any]:
|
||||
dto = get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
if not dto:
|
||||
raise ValueError("SteeringContext nicht verfügbar")
|
||||
return dto
|
||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
"""Hook dispatch — AP1.0 stub with audit trail."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from steering.hooks.registry import get_hook
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def dispatch_hook(
|
||||
slug: str,
|
||||
ctx: TenantContext | None,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
tenant_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Dispatch hook — AP1.0: audit only, no handlers yet."""
|
||||
hook = get_hook(slug)
|
||||
if not hook:
|
||||
return [{"kind": "hook_unknown", "slug": slug}]
|
||||
|
||||
tid = tenant_id or (ctx.tenant_id if ctx else None)
|
||||
if tid and user_id:
|
||||
from services.audit import log_audit
|
||||
|
||||
log_audit(
|
||||
f"steering.hook.{slug}",
|
||||
user_id=user_id,
|
||||
tenant_id=tid,
|
||||
details={"slug": slug, "payload": payload},
|
||||
)
|
||||
|
||||
return [{"kind": "hook_dispatched", "slug": slug, "lifecycle_step": hook.lifecycle_step}]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Hook Registry — stabile Einhängepunkte (AP1.0 definitions only)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
_HOOKS: dict[str, "HookDefinition"] = {}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HookDefinition:
|
||||
slug: str
|
||||
lifecycle_step: str
|
||||
description: str
|
||||
since_version: str = "0.11.0"
|
||||
|
||||
|
||||
def register_hook(defn: HookDefinition) -> None:
|
||||
if defn.slug in _HOOKS:
|
||||
raise ValueError(f"Hook already registered: {defn.slug}")
|
||||
_HOOKS[defn.slug] = defn
|
||||
|
||||
|
||||
def get_hook(slug: str) -> HookDefinition | None:
|
||||
return _HOOKS.get(slug)
|
||||
|
||||
|
||||
def list_hooks() -> tuple[HookDefinition, ...]:
|
||||
return tuple(_HOOKS.values())
|
||||
|
||||
|
||||
def clear_hooks_for_tests() -> None:
|
||||
_HOOKS.clear()
|
||||
|
||||
|
||||
def register_builtin_hooks() -> None:
|
||||
"""Slugs aus Target Architecture §7.3 — Handler folgen in AP1.3."""
|
||||
builtins = (
|
||||
("on_goal_captured", "intake", "Ziel erfasst"),
|
||||
("on_method_selected", "method_selection", "Methode gewählt"),
|
||||
("on_structure_required", "structure_setup", "Struktur erforderlich"),
|
||||
("on_backlog_required", "structure_setup", "Backlog erforderlich"),
|
||||
("on_next_action_requested", "action_selection", "Nächste Aktion angefragt"),
|
||||
("on_assignment_required", "assignment", "Zuweisung erforderlich"),
|
||||
("on_blocker_open", "waiting", "Blocker gemeldet"),
|
||||
("on_blocker_resolved", "action_selection", "Blocker geschlossen"),
|
||||
("on_wait_started", "waiting", "Warten begonnen"),
|
||||
("on_result_received", "result_intake", "Ergebnis eingegangen"),
|
||||
("on_evidence_required", "validation", "Nachweis erforderlich"),
|
||||
("on_review_due", "review", "Review fällig"),
|
||||
("on_review_completed", "review", "Review abgeschlossen"),
|
||||
("on_replan_required", "adaptation", "Anpassung nötig"),
|
||||
("on_closure_requested", "closure", "Abschluss angefragt"),
|
||||
)
|
||||
for slug, step, desc in builtins:
|
||||
if slug not in _HOOKS:
|
||||
register_hook(
|
||||
HookDefinition(
|
||||
slug=slug,
|
||||
lifecycle_step=step,
|
||||
description=desc,
|
||||
)
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,78 @@
|
||||
"""Lifecycle orchestrator — persistierter Standard Lifecycle (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from services import steering_context as sc_service
|
||||
from steering.lifecycle.states import validate_lifecycle_state
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def get_lifecycle_state(ctx: TenantContext, initiative_id: str) -> str:
|
||||
row = sc_service.get_steering_context(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if row:
|
||||
return row["lifecycle_state"]
|
||||
created = sc_service.ensure_steering_context(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
initial_state="intake",
|
||||
)
|
||||
return created["lifecycle_state"]
|
||||
|
||||
|
||||
def transition(
|
||||
ctx: TenantContext | None,
|
||||
initiative_id: str,
|
||||
to_state: str,
|
||||
*,
|
||||
reason: str = "",
|
||||
tenant_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Lifecycle-Transition — AP1.0: freier Übergang (Guards in AP1.1)."""
|
||||
validate_lifecycle_state(to_state)
|
||||
tid = tenant_id or (ctx.tenant_id if ctx else None)
|
||||
if not tid:
|
||||
raise ValueError("tenant_id erforderlich")
|
||||
|
||||
existing = sc_service.get_steering_context(tenant_id=tid, initiative_id=initiative_id)
|
||||
if not existing:
|
||||
existing = sc_service.ensure_steering_context(
|
||||
tenant_id=tid,
|
||||
initiative_id=initiative_id,
|
||||
initial_state=to_state,
|
||||
)
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": None,
|
||||
"to_state": to_state,
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
from_state = existing["lifecycle_state"]
|
||||
if from_state == to_state:
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": from_state,
|
||||
"to_state": to_state,
|
||||
"reason": reason,
|
||||
"unchanged": True,
|
||||
}
|
||||
|
||||
updated = sc_service.update_lifecycle_state(
|
||||
tenant_id=tid,
|
||||
initiative_id=initiative_id,
|
||||
lifecycle_state=to_state,
|
||||
user_id=user_id,
|
||||
reason=reason,
|
||||
from_state=from_state,
|
||||
)
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": from_state,
|
||||
"to_state": updated["lifecycle_state"],
|
||||
"reason": reason,
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Standard Lifecycle — gemeinsame Basis (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
STANDARD_LIFECYCLE_STEPS: tuple[str, ...] = (
|
||||
"intake",
|
||||
"method_selection",
|
||||
"structure_setup",
|
||||
"planning",
|
||||
"action_selection",
|
||||
"assignment",
|
||||
"waiting",
|
||||
"result_intake",
|
||||
"validation",
|
||||
"review",
|
||||
"adaptation",
|
||||
"closure",
|
||||
)
|
||||
|
||||
LIFECYCLE_LABELS: dict[str, str] = {
|
||||
"intake": "Aufnahme",
|
||||
"method_selection": "Methode wählen",
|
||||
"structure_setup": "Struktur aufbauen",
|
||||
"planning": "Planung",
|
||||
"action_selection": "Maßnahmen auswählen",
|
||||
"assignment": "Zuweisen",
|
||||
"waiting": "Warten",
|
||||
"result_intake": "Ergebnis aufnehmen",
|
||||
"validation": "Validierung",
|
||||
"review": "Review",
|
||||
"adaptation": "Anpassung",
|
||||
"closure": "Abschluss",
|
||||
}
|
||||
|
||||
|
||||
def lifecycle_label(state: str) -> str:
|
||||
return LIFECYCLE_LABELS.get(state, state)
|
||||
|
||||
|
||||
def validate_lifecycle_state(state: str) -> None:
|
||||
if state not in STANDARD_LIFECYCLE_STEPS:
|
||||
raise ValueError(f"Ungültiger Lifecycle-State: {state}")
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,21 @@
|
||||
"""Built-in method: generic_operating."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
|
||||
from steering.methods.registry import MethodDefinition, get_method, register_method
|
||||
|
||||
|
||||
def register() -> None:
|
||||
if get_method("generic_operating"):
|
||||
return
|
||||
register_method(
|
||||
MethodDefinition(
|
||||
key="generic_operating",
|
||||
version="0.1.0",
|
||||
label="Allgemeine Steuerung",
|
||||
description="Standard-Lifecycle ohne methodenspezifische Spezialisierung",
|
||||
default_lifecycle_steps=STANDARD_LIFECYCLE_STEPS,
|
||||
next_action_strategy_key="default",
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Built-in method: product_milestone_driven — AP1.1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
|
||||
from steering.methods.registry import MethodDefinition, get_method, register_method
|
||||
|
||||
_PRODUCT_STEPS = (
|
||||
"intake",
|
||||
"method_selection",
|
||||
"structure_setup",
|
||||
"planning",
|
||||
"action_selection",
|
||||
"assignment",
|
||||
"waiting",
|
||||
"result_intake",
|
||||
"validation",
|
||||
"review",
|
||||
"adaptation",
|
||||
"closure",
|
||||
)
|
||||
|
||||
|
||||
def register() -> None:
|
||||
if get_method("product_milestone_driven"):
|
||||
return
|
||||
register_method(
|
||||
MethodDefinition(
|
||||
key="product_milestone_driven",
|
||||
version="0.1.0",
|
||||
label="Produkt / Meilenstein",
|
||||
description="Meilenstein-orientierte Steuerung für Produkt- und Projektentwicklung",
|
||||
default_lifecycle_steps=_PRODUCT_STEPS,
|
||||
next_action_strategy_key="product_milestone_driven",
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Method Registry — built-in steering methods."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
_METHODS: dict[str, "MethodDefinition"] = {}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MethodDefinition:
|
||||
key: str
|
||||
version: str
|
||||
label: str
|
||||
description: str
|
||||
default_lifecycle_steps: tuple[str, ...]
|
||||
next_action_strategy_key: str = "default"
|
||||
|
||||
|
||||
def register_method(defn: MethodDefinition) -> None:
|
||||
if defn.key in _METHODS:
|
||||
raise ValueError(f"Method already registered: {defn.key}")
|
||||
_METHODS[defn.key] = defn
|
||||
|
||||
|
||||
def get_method(key: str) -> MethodDefinition | None:
|
||||
return _METHODS.get(key)
|
||||
|
||||
|
||||
def list_methods() -> tuple[MethodDefinition, ...]:
|
||||
return tuple(_METHODS.values())
|
||||
|
||||
|
||||
def clear_methods_for_tests() -> None:
|
||||
_METHODS.clear()
|
||||
Whitespace-only changes.
@@ -0,0 +1,707 @@
|
||||
"""Default Signal Rule Provider — regelbasiert, tenant-scoped (AP0.8a, AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from tenant_context import TenantContext
|
||||
|
||||
AttentionKind = Literal[
|
||||
"blocked_action",
|
||||
"open_blocker",
|
||||
"high_priority_action",
|
||||
"unassigned_action",
|
||||
"initiative_without_next_action",
|
||||
"stale_initiative",
|
||||
"milestone_at_risk",
|
||||
"overdue_action",
|
||||
"review_due",
|
||||
"recurring_due",
|
||||
"action_review_required",
|
||||
]
|
||||
|
||||
NextActionKind = Literal[
|
||||
"assign_action",
|
||||
"resolve_blocker",
|
||||
"create_action",
|
||||
"convert_backlog",
|
||||
"review_milestone",
|
||||
]
|
||||
|
||||
Severity = Literal["info", "warning", "critical"]
|
||||
|
||||
_SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
|
||||
|
||||
OPEN_BLOCKER_STATUSES = ("open", "in_progress")
|
||||
OPEN_ACTION_STATUSES = ("open", "ready", "in_progress", "blocked", "review_required")
|
||||
ACTIVE_INITIATIVE_STATUSES = ("active", "paused")
|
||||
|
||||
|
||||
def _serialize_attention(row: dict[str, Any]) -> dict[str, Any]:
|
||||
item = dict(row)
|
||||
for key in (
|
||||
"scope_id",
|
||||
"initiative_id",
|
||||
"action_id",
|
||||
"blocker_id",
|
||||
"milestone_id",
|
||||
"review_id",
|
||||
"recurring_element_id",
|
||||
):
|
||||
if item.get(key):
|
||||
item[key] = str(item[key])
|
||||
return item
|
||||
|
||||
|
||||
def _blocked_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'blocked_action' AS kind,
|
||||
'critical' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ist blockiert' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_blocked' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s AND a.status = 'blocked'
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _open_blockers(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'open_blocker' AS kind,
|
||||
'warning' AS severity,
|
||||
b.title AS title,
|
||||
'Offener Blocker im Vorhaben' AS summary,
|
||||
'blocker' AS scope_type,
|
||||
b.id AS scope_id,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
b.id AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'blockers' AS data_source
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
item = _serialize_attention(dict(row))
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def _high_priority_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
actor_filter = ""
|
||||
params: list[Any] = [ctx.tenant_id]
|
||||
if ctx.actor_id:
|
||||
actor_filter = """
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id
|
||||
AND aa.tenant_id = a.tenant_id
|
||||
AND aa.actor_id = %s
|
||||
)
|
||||
"""
|
||||
params.append(ctx.actor_id)
|
||||
else:
|
||||
return []
|
||||
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT
|
||||
'high_priority_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'High-Priority Maßnahme offen' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_high_priority_open' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.priority = 'high'
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
{actor_filter}
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
tuple(params),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _unassigned_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'unassigned_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ohne Zuweisung' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _initiatives_without_next_action(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'initiative_without_next_action' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Keine offene nächste Maßnahme' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT 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')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _stale_initiatives(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'stale_initiative' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Vorhaben seit über 14 Tagen unverändert' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_stale' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status = 'active'
|
||||
AND i.updated_at < NOW() - INTERVAL '14 days'
|
||||
ORDER BY i.updated_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _milestones_at_risk(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'milestone_at_risk' AS kind,
|
||||
'warning' AS severity,
|
||||
ri.title AS title,
|
||||
'Plan-Element als gefährdet markiert' AS summary,
|
||||
'milestone' AS scope_type,
|
||||
ri.id AS scope_id,
|
||||
r.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
ri.id AS milestone_id,
|
||||
'milestone_at_risk' AS reason_code,
|
||||
'roadmap_items' AS data_source
|
||||
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 ri.status = 'at_risk'
|
||||
ORDER BY ri.updated_at DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _actions_review_required(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'action_review_required' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Ma├ƒnahme wartet auf Review ÔÇö kein geplantes Review verkn├╝pft' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'action_review_required_no_review' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status = 'review_required'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM reviews r
|
||||
WHERE r.tenant_id = a.tenant_id
|
||||
AND r.action_id = a.id
|
||||
AND r.status = 'planned'
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _overdue_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'overdue_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme überfällig' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'action_overdue' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.due_at IS NOT NULL
|
||||
AND a.due_at < NOW()
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
ORDER BY a.due_at ASC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _reviews_due(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'review_due' AS kind,
|
||||
'warning' AS severity,
|
||||
r.title AS title,
|
||||
'Review fällig' AS summary,
|
||||
'review' AS scope_type,
|
||||
r.id AS scope_id,
|
||||
r.initiative_id,
|
||||
r.action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
r.milestone_id,
|
||||
r.id AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'review_due' AS reason_code,
|
||||
'reviews' AS data_source
|
||||
FROM reviews r
|
||||
WHERE r.tenant_id = %s
|
||||
AND r.status = 'planned'
|
||||
AND r.due_at IS NOT NULL
|
||||
AND r.due_at <= NOW()
|
||||
ORDER BY r.due_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
item = _serialize_attention(dict(row))
|
||||
for fk in ("action_id", "milestone_id"):
|
||||
if item.get(fk):
|
||||
item[fk] = str(item[fk])
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def _recurring_due(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'recurring_due' AS kind,
|
||||
'info' AS severity,
|
||||
re.title AS title,
|
||||
'Wiederkehrendes Element fällig' AS summary,
|
||||
'recurring_element' AS scope_type,
|
||||
re.id AS scope_id,
|
||||
re.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
re.id AS recurring_element_id,
|
||||
'recurring_due' AS reason_code,
|
||||
'recurring_elements' AS data_source
|
||||
FROM recurring_elements re
|
||||
WHERE re.tenant_id = %s
|
||||
AND re.status = 'active'
|
||||
AND re.next_due_at IS NOT NULL
|
||||
AND re.next_due_at <= NOW()
|
||||
ORDER BY re.next_due_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def get_attention_items(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte Attention Items ÔÇö tenant-scoped, erkl├ñrbar."""
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
items: list[dict[str, Any]] = []
|
||||
items.extend(_blocked_actions(cur, ctx))
|
||||
items.extend(_open_blockers(cur, ctx))
|
||||
items.extend(_high_priority_actions(cur, ctx))
|
||||
items.extend(_unassigned_actions(cur, ctx))
|
||||
items.extend(_initiatives_without_next_action(cur, ctx))
|
||||
items.extend(_stale_initiatives(cur, ctx))
|
||||
items.extend(_milestones_at_risk(cur, ctx))
|
||||
items.extend(_overdue_actions(cur, ctx))
|
||||
items.extend(_actions_review_required(cur, ctx))
|
||||
items.extend(_reviews_due(cur, ctx))
|
||||
items.extend(_recurring_due(cur, ctx))
|
||||
|
||||
items.sort(key=lambda x: _SEVERITY_ORDER.get(x["severity"], 99))
|
||||
return items
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_next_action_candidates(
|
||||
ctx: TenantContext, *, limit: int = 10
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte NextActionCandidates ÔÇö limitiert, tenant-scoped."""
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if limit > 50:
|
||||
limit = 50
|
||||
|
||||
conn = get_connection()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'resolve_blocker' AS kind,
|
||||
b.title AS title,
|
||||
'Blocker klären oder Status aktualisieren' AS summary,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'Blocker bearbeiten' AS recommended_action
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'assign_action' AS kind,
|
||||
a.title AS title,
|
||||
'Actor zuweisen' AS summary,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'Maßnahme zuweisen' AS recommended_action
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'convert_backlog' AS kind,
|
||||
bi.title AS title,
|
||||
'Freigegebenes Backlog-Item in Maßnahme umwandeln' AS summary,
|
||||
bi.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
bi.id AS backlog_item_id,
|
||||
'backlog_accepted_not_converted' AS reason_code,
|
||||
'In Maßnahme umwandeln' AS recommended_action
|
||||
FROM backlog_items bi
|
||||
WHERE bi.tenant_id = %s
|
||||
AND bi.status = 'accepted'
|
||||
AND bi.converted_action_id IS NULL
|
||||
ORDER BY bi.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["backlog_item_id"] = str(item["backlog_item_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'create_action' AS kind,
|
||||
i.title AS title,
|
||||
'Nächste Maßnahme für Vorhaben anlegen' AS summary,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'Maßnahme anlegen' AS recommended_action
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT 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')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
candidates.append(item)
|
||||
|
||||
return candidates[:limit]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_next_action_candidates_for_initiative(
|
||||
ctx: TenantContext, *, initiative_id: str, limit: int = 5
|
||||
) -> list[dict[str, Any]]:
|
||||
"""NextActionCandidates f├╝r ein Vorhaben ÔÇö tenant-scoped."""
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if limit > 20:
|
||||
limit = 20
|
||||
|
||||
conn = get_connection()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'resolve_blocker' AS kind,
|
||||
b.title AS title,
|
||||
'Blocker klären oder Status aktualisieren' AS summary,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'Blocker bearbeiten' AS recommended_action
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.initiative_id = %s
|
||||
AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'assign_action' AS kind,
|
||||
a.title AS title,
|
||||
'Actor zuweisen' AS summary,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'Maßnahme zuweisen' AS recommended_action
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s AND a.initiative_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'convert_backlog' AS kind,
|
||||
bi.title AS title,
|
||||
'Freigegebenes Backlog-Item in Maßnahme umwandeln' AS summary,
|
||||
bi.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
bi.id AS backlog_item_id,
|
||||
'backlog_accepted_not_converted' AS reason_code,
|
||||
'In Maßnahme umwandeln' AS recommended_action
|
||||
FROM backlog_items bi
|
||||
WHERE bi.tenant_id = %s AND bi.initiative_id = %s
|
||||
AND bi.status = 'accepted'
|
||||
AND bi.converted_action_id IS NULL
|
||||
ORDER BY bi.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["backlog_item_id"] = str(item["backlog_item_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = %s AND a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
LIMIT 1
|
||||
""",
|
||||
(initiative_id, ctx.tenant_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT title FROM initiatives
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(initiative_id, ctx.tenant_id),
|
||||
)
|
||||
init_row = cur.fetchone()
|
||||
if init_row:
|
||||
candidates.append(
|
||||
{
|
||||
"kind": "create_action",
|
||||
"title": init_row["title"],
|
||||
"summary": "Nächste Maßnahme für Vorhaben anlegen",
|
||||
"initiative_id": initiative_id,
|
||||
"action_id": None,
|
||||
"backlog_item_id": None,
|
||||
"reason_code": "initiative_no_open_action",
|
||||
"recommended_action": "Maßnahme anlegen",
|
||||
}
|
||||
)
|
||||
|
||||
return candidates[:limit]
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Signal Engine — method-aware NextAction (AP1.1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from services import steering_context as sc_service
|
||||
from steering.methods.registry import get_method
|
||||
from steering.signals import default_rules
|
||||
from steering.strategies.next_action.default_strategy import default_strategy
|
||||
from steering.strategies.next_action.registry import get_next_action_strategy
|
||||
from tenant_context import TenantContext
|
||||
|
||||
SignalKind = Literal["attention", "next_action"]
|
||||
|
||||
|
||||
def _resolve_method_key(ctx: TenantContext, initiative_id: str | None) -> str:
|
||||
if not initiative_id:
|
||||
return "generic_operating"
|
||||
row = sc_service.get_steering_context(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if row:
|
||||
return row["method_key"]
|
||||
return "generic_operating"
|
||||
|
||||
|
||||
def evaluate(
|
||||
ctx: TenantContext,
|
||||
kind: SignalKind = "attention",
|
||||
*,
|
||||
limit: int = 10,
|
||||
initiative_id: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if kind == "attention":
|
||||
return default_rules.get_attention_items(ctx)
|
||||
|
||||
method_key = _resolve_method_key(ctx, initiative_id)
|
||||
method = get_method(method_key)
|
||||
strategy_key = (
|
||||
method.next_action_strategy_key if method else default_strategy.key
|
||||
)
|
||||
strategy = get_next_action_strategy(strategy_key) or default_strategy
|
||||
return strategy.evaluate(ctx, initiative_id=initiative_id, limit=limit)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Initiative snapshot signals — erklärbare Heuristiken ohne operating_phase (AP1.2)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def derive_initiative_signals(
|
||||
*,
|
||||
initiative_status: str,
|
||||
open_actions: int,
|
||||
blocked_actions: int,
|
||||
review_required_actions: int,
|
||||
open_blockers: int,
|
||||
backlog_new: int,
|
||||
planned_reviews_due: int,
|
||||
) -> list[str]:
|
||||
"""Regelbasierte Signale für Steuerungs-Snapshot — kein Lifecycle-Ersatz."""
|
||||
if initiative_status in ("completed", "archived"):
|
||||
return ["initiative_terminal"]
|
||||
|
||||
signals: list[str] = []
|
||||
|
||||
if open_actions == 0 and backlog_new > 0:
|
||||
signals.append("backlog_awaiting_commit")
|
||||
return signals
|
||||
|
||||
if open_actions == 0 and backlog_new == 0:
|
||||
signals.append("no_open_work")
|
||||
return signals
|
||||
|
||||
if blocked_actions > 0:
|
||||
signals.append("actions_blocked")
|
||||
if open_blockers > 0:
|
||||
signals.append("open_blockers")
|
||||
if blocked_actions > 0 or open_blockers > 0:
|
||||
return signals
|
||||
|
||||
if review_required_actions > 0:
|
||||
signals.append("actions_need_review")
|
||||
if planned_reviews_due > 0:
|
||||
signals.append("reviews_due")
|
||||
if review_required_actions > 0 or planned_reviews_due > 0:
|
||||
return signals
|
||||
|
||||
if open_actions > 0:
|
||||
signals.append("work_in_progress")
|
||||
|
||||
return signals
|
||||
Whitespace-only changes.
@@ -0,0 +1,18 @@
|
||||
"""Bootstrap NextAction strategies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.strategies.next_action.default_strategy import default_strategy
|
||||
from steering.strategies.next_action.product_milestone_driven import (
|
||||
product_milestone_strategy,
|
||||
)
|
||||
from steering.strategies.next_action.registry import (
|
||||
get_next_action_strategy,
|
||||
register_next_action_strategy,
|
||||
)
|
||||
|
||||
|
||||
def register_builtin_strategies() -> None:
|
||||
for strategy in (default_strategy, product_milestone_strategy):
|
||||
if not get_next_action_strategy(strategy.key):
|
||||
register_next_action_strategy(strategy)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Default NextAction strategy — delegates to global rules (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.signals import default_rules
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
class DefaultNextActionStrategy:
|
||||
key = "default"
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
ctx: TenantContext,
|
||||
*,
|
||||
initiative_id: str | None = None,
|
||||
limit: int = 10,
|
||||
) -> list[dict[str, Any]]:
|
||||
if initiative_id:
|
||||
return default_rules.get_next_action_candidates_for_initiative(
|
||||
ctx, initiative_id=initiative_id, limit=limit
|
||||
)
|
||||
return default_rules.get_next_action_candidates(ctx, limit=limit)
|
||||
|
||||
|
||||
default_strategy = DefaultNextActionStrategy()
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Product/milestone-driven NextAction strategy — AP1.1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from db import get_connection
|
||||
from psycopg2.extras import RealDictCursor
|
||||
from steering.signals import default_rules
|
||||
from steering.strategies.next_action.default_strategy import DefaultNextActionStrategy
|
||||
from tenant_context import TenantContext
|
||||
|
||||
_default = DefaultNextActionStrategy()
|
||||
|
||||
|
||||
class ProductMilestoneDrivenStrategy:
|
||||
key = "product_milestone_driven"
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
ctx: TenantContext,
|
||||
*,
|
||||
initiative_id: str | None = None,
|
||||
limit: int = 10,
|
||||
) -> list[dict[str, Any]]:
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if not initiative_id:
|
||||
return _default.evaluate(ctx, limit=limit)
|
||||
|
||||
candidates: list[dict[str, Any]] = []
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'review_milestone' AS kind,
|
||||
ri.title AS title,
|
||||
'Plan-Element prüfen oder Status aktualisieren' AS summary,
|
||||
r.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'milestone_at_risk_or_active' AS reason_code,
|
||||
'Plan-Element prüfen' AS recommended_action
|
||||
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
|
||||
AND ri.item_type = 'milestone'
|
||||
AND ri.status IN ('at_risk', 'active')
|
||||
ORDER BY
|
||||
CASE ri.status WHEN 'at_risk' THEN 0 ELSE 1 END,
|
||||
ri.target_date ASC NULLS LAST,
|
||||
ri.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
candidates.append(item)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
rest = default_rules.get_next_action_candidates_for_initiative(
|
||||
ctx, initiative_id=initiative_id, limit=remaining
|
||||
)
|
||||
candidates.extend(rest)
|
||||
|
||||
return candidates[:limit]
|
||||
|
||||
|
||||
product_milestone_strategy = ProductMilestoneDrivenStrategy()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""NextAction strategy registry — AP1.1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Protocol
|
||||
|
||||
from tenant_context import TenantContext
|
||||
|
||||
_STRATEGIES: dict[str, "NextActionStrategy"] = {}
|
||||
|
||||
|
||||
class NextActionStrategy(Protocol):
|
||||
key: str
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
ctx: TenantContext,
|
||||
*,
|
||||
initiative_id: str | None = None,
|
||||
limit: int = 10,
|
||||
) -> list[dict[str, Any]]: ...
|
||||
|
||||
|
||||
def register_next_action_strategy(strategy: NextActionStrategy) -> None:
|
||||
if strategy.key in _STRATEGIES:
|
||||
raise ValueError(f"NextAction strategy already registered: {strategy.key}")
|
||||
_STRATEGIES[strategy.key] = strategy
|
||||
|
||||
|
||||
def get_next_action_strategy(key: str) -> NextActionStrategy | None:
|
||||
return _STRATEGIES.get(key)
|
||||
|
||||
|
||||
def clear_strategies_for_tests() -> None:
|
||||
_STRATEGIES.clear()
|
||||
@@ -1,4 +1,8 @@
|
||||
"""Shared pytest fixtures for AP0.2 auth tests."""
|
||||
"""Shared pytest fixtures — Integrationstests benötigen PostgreSQL.
|
||||
|
||||
Lokal typischerweise nicht verfügbar: Tests laufen nach Push auf develop/main
|
||||
im Backend-Container auf dem Pi (Gitea workflow test.yml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,6 +27,7 @@ def _db_available() -> bool:
|
||||
dbname=os.getenv("DB_NAME", "kairo_dev"),
|
||||
user=os.getenv("DB_USER", "kairo_dev"),
|
||||
password=os.getenv("DB_PASSWORD", "dev_password"),
|
||||
connect_timeout=3,
|
||||
)
|
||||
conn.close()
|
||||
return True
|
||||
@@ -30,7 +35,18 @@ def _db_available() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(not _db_available(), reason="PostgreSQL nicht erreichbar")
|
||||
_REMOTE_HINT = (
|
||||
"PostgreSQL lokal nicht erreichbar. "
|
||||
"Backend-Integrationstests laufen nach Push auf develop/main "
|
||||
"im deployten Backend-Container (Gitea: test.yml auf dem Pi)."
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _require_postgresql():
|
||||
"""Session-weiter Guard — verhindert Migrations-Setup ohne DB (keine ERROR-Spirale)."""
|
||||
if not _db_available():
|
||||
pytest.skip(_REMOTE_HINT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
@@ -53,6 +69,7 @@ def _seed_hygiene():
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _sync_rights_registry():
|
||||
import rights_registrations # noqa: F401
|
||||
import steering # noqa: F401 — bootstrap hooks & methods
|
||||
from rights_registry import sync_rights_registry_to_db
|
||||
|
||||
assert sync_rights_registry_to_db() == 0
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""AP0.7 — Actor directory, workspace data layer, tenant hardening tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import AUTH_HEADER
|
||||
from services.actors import create_actor
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def test_list_actors_tenant_scoped(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
agent = create_actor(tenant_id=user["tenant_id"], actor_type="agent", name="Bot Alpha")
|
||||
|
||||
res = client.get("/api/actors", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
ids = {a["id"] for a in body}
|
||||
assert user["actor_id"] in ids
|
||||
assert agent["id"] in ids
|
||||
types = {a["actor_type"] for a in body}
|
||||
assert "human" in types
|
||||
assert "agent" in types
|
||||
for actor in body:
|
||||
assert "user_id" not in actor
|
||||
|
||||
|
||||
def test_list_actors_filter_by_type(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
create_actor(tenant_id=user["tenant_id"], actor_type="agent", name="Filter Agent")
|
||||
|
||||
res = client.get("/api/actors?actor_type=agent", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert all(a["actor_type"] == "agent" for a in res.json())
|
||||
|
||||
|
||||
def test_list_actors_excludes_inactive_by_default(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
inactive = create_actor(
|
||||
tenant_id=user["tenant_id"], actor_type="external_system", name="Legacy"
|
||||
)
|
||||
conn = __import__("db").get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE actors SET is_active = FALSE WHERE id = %s", (inactive["id"],))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
res = client.get("/api/actors", headers=_auth(token))
|
||||
assert inactive["id"] not in {a["id"] for a in res.json()}
|
||||
|
||||
res_active = client.get("/api/actors?include_inactive=true", headers=_auth(token))
|
||||
assert inactive["id"] in {a["id"] for a in res_active.json()}
|
||||
|
||||
|
||||
def test_get_actor_detail(client):
|
||||
user = provision_user_in_tenant()
|
||||
token = _login(client, user)
|
||||
agent = create_actor(tenant_id=user["tenant_id"], actor_type="working_group", name="Team A")
|
||||
|
||||
res = client.get(f"/api/actors/{agent['id']}", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert res.json()["name"] == "Team A"
|
||||
assert res.json()["actor_type"] == "working_group"
|
||||
|
||||
|
||||
def test_cross_tenant_actor_directory_isolation(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
agent_a = create_actor(tenant_id=user_a["tenant_id"], actor_type="agent", name="Tenant A Agent")
|
||||
|
||||
list_b = client.get("/api/actors", headers=_auth(token_b)).json()
|
||||
assert agent_a["id"] not in {a["id"] for a in list_b}
|
||||
assert user_a["actor_id"] not in {a["id"] for a in list_b}
|
||||
|
||||
detail = client.get(f"/api/actors/{agent_a['id']}", headers=_auth(token_b))
|
||||
assert detail.status_code == 404
|
||||
|
||||
|
||||
def test_member_has_actor_and_workspace_capabilities(client):
|
||||
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||
token = _login(client, member)
|
||||
ctx = client.get("/api/me/context", headers=_auth(token)).json()
|
||||
assert "kairo.actor.read" in ctx["capabilities"]
|
||||
assert "kairo.workspace.read" in ctx["capabilities"]
|
||||
|
||||
|
||||
def test_workspace_summary(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
open_action = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
blocked = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Blocked",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{blocked['id']}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
done = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Done",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{done['id']}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/summary", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
summary = res.json()
|
||||
assert summary["open_actions_count"] >= 1
|
||||
assert summary["blocked_actions_count"] >= 1
|
||||
assert summary["active_initiatives_count"] >= 1
|
||||
assert summary["done_actions_recent_count"] >= 1
|
||||
assert open_action["id"] # used
|
||||
|
||||
|
||||
def test_workspace_open_and_blocked_actions(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
open_id = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Open",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()["id"]
|
||||
blocked_id = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Blocked",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()["id"]
|
||||
client.patch(
|
||||
f"/api/actions/{blocked_id}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
open_res = client.get("/api/workspace/actions/open", headers=_auth(token))
|
||||
blocked_res = client.get("/api/workspace/actions/blocked", headers=_auth(token))
|
||||
assert open_res.status_code == 200
|
||||
assert blocked_res.status_code == 200
|
||||
assert open_id in {a["id"] for a in open_res.json()}
|
||||
assert blocked_id in {a["id"] for a in blocked_res.json()}
|
||||
assert blocked_id not in {a["id"] for a in open_res.json()}
|
||||
|
||||
|
||||
def test_workspace_active_initiatives(client):
|
||||
user = provision_user_in_tenant()
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token, title="Active One").json()["id"]
|
||||
|
||||
res = client.get("/api/workspace/initiatives/active?limit=5", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
ids = {i["id"] for i in res.json()}
|
||||
assert initiative_id in ids
|
||||
|
||||
|
||||
def test_workspace_actor_workload(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
agent = create_actor(tenant_id=user["tenant_id"], actor_type="agent", name="Workload Bot")
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
assigned_actor_ids=[agent["id"]],
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/actors/workload", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
workload = {row["actor_id"]: row for row in res.json()}
|
||||
assert agent["id"] in workload
|
||||
assert workload[agent["id"]]["open_actions"] >= 1
|
||||
|
||||
|
||||
def test_cross_tenant_workspace_summary_isolation(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
_create_action(
|
||||
client,
|
||||
token_a,
|
||||
initiative_id,
|
||||
assigned_actor_ids=[user_a["actor_id"]],
|
||||
)
|
||||
|
||||
summary_b = client.get("/api/workspace/summary", headers=_auth(token_b)).json()
|
||||
assert summary_b["open_actions_count"] == 0
|
||||
|
||||
open_b = client.get("/api/workspace/actions/open", headers=_auth(token_b)).json()
|
||||
assert open_b == []
|
||||
|
||||
|
||||
def test_assign_action_to_tenant_actor(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
agent = create_actor(tenant_id=user["tenant_id"], actor_type="agent", name="Assignee")
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action_id = _create_action(client, token, initiative_id).json()["id"]
|
||||
|
||||
res = client.put(
|
||||
f"/api/actions/{action_id}/assignments",
|
||||
json={"actor_ids": [agent["id"]]},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["assigned_actor_ids"] == [agent["id"]]
|
||||
|
||||
|
||||
def test_unauthenticated_workspace_rejected(client):
|
||||
assert client.get("/api/workspace/summary").status_code == 401
|
||||
assert client.get("/api/actors").status_code == 401
|
||||
@@ -0,0 +1,279 @@
|
||||
"""AP0.8 — Operating Model Extension I tests.
|
||||
|
||||
Ausführung: im Backend-Container auf dem Pi nach Deploy (develop/main),
|
||||
siehe .gitea/workflows/test.yml und docs/DEPLOYMENT.md.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def _create_blocker(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Blocker Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_backlog(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Backlog Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_milestone(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Milestone Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/milestones",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def test_attention_blocked_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(
|
||||
client, token, initiative_id, assigned_actor_ids=[user["actor_id"]]
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
items = res.json()
|
||||
assert any(i["kind"] == "blocked_action" for i in items)
|
||||
blocked = next(i for i in items if i["kind"] == "blocked_action")
|
||||
assert blocked["reason_code"] == "action_blocked"
|
||||
assert blocked["data_source"] == "actions"
|
||||
assert blocked["scope_type"] == "action"
|
||||
|
||||
|
||||
def test_attention_unassigned_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_action(client, token, initiative_id, title="Unassigned")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "unassigned_action" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_initiative_without_next_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
_create_initiative(client, token, title="Empty Initiative")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "initiative_without_next_action" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_open_blocker(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_blocker(client, token, initiative_id, title="Dependency missing")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "open_blocker" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_milestone_at_risk(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
ms = _create_milestone(client, token, initiative_id).json()
|
||||
client.patch(
|
||||
f"/api/milestones/{ms['id']}",
|
||||
json={"status": "at_risk"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert any(i["kind"] == "milestone_at_risk" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_severity_sorting(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
_create_blocker(client, token, initiative_id)
|
||||
|
||||
items = client.get("/api/workspace/attention", headers=_auth(token)).json()
|
||||
severities = [i["severity"] for i in items]
|
||||
order = {"critical": 0, "warning": 1, "info": 2}
|
||||
assert severities == sorted(severities, key=lambda s: order.get(s, 99))
|
||||
|
||||
|
||||
def test_next_action_convert_backlog(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
item = _create_backlog(
|
||||
client, token, initiative_id, status="accepted", title="Convert me"
|
||||
).json()
|
||||
|
||||
res = client.get("/api/workspace/next-actions?limit=10", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(
|
||||
c["kind"] == "convert_backlog" and c["backlog_item_id"] == item["id"]
|
||||
for c in res.json()
|
||||
)
|
||||
|
||||
|
||||
def test_next_action_limit(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
for i in range(5):
|
||||
_create_backlog(
|
||||
client, token, initiative_id, status="accepted", title=f"Item {i}"
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/next-actions?limit=2", headers=_auth(token))
|
||||
assert len(res.json()) <= 2
|
||||
|
||||
|
||||
def test_blocker_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()
|
||||
|
||||
created = _create_blocker(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="API Block",
|
||||
action_id=action["id"],
|
||||
)
|
||||
assert created.status_code == 201
|
||||
blocker = created.json()
|
||||
assert blocker["initiative_id"] == initiative_id
|
||||
|
||||
listed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/blockers", headers=_auth(token)
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
assert any(b["id"] == blocker["id"] for b in listed.json())
|
||||
|
||||
updated = client.patch(
|
||||
f"/api/blockers/{blocker['id']}",
|
||||
json={"status": "resolved"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["status"] == "resolved"
|
||||
|
||||
deleted = client.delete(f"/api/blockers/{blocker['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_blocker_cross_tenant(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
blocker = _create_blocker(client, token_a, initiative_id).json()
|
||||
|
||||
assert (
|
||||
client.get(f"/api/blockers/{blocker['id']}", headers=_auth(token_b)).status_code
|
||||
== 404
|
||||
)
|
||||
|
||||
|
||||
def test_backlog_convert_to_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
item = _create_backlog(
|
||||
client, token, initiative_id, status="accepted", title="Feature X"
|
||||
).json()
|
||||
|
||||
converted = client.post(
|
||||
f"/api/backlog/{item['id']}/convert-to-action",
|
||||
json={},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert converted.status_code == 201
|
||||
body = converted.json()
|
||||
assert body["backlog_item"]["status"] == "converted"
|
||||
assert body["action"]["title"] == "Feature X"
|
||||
assert body["backlog_item"]["converted_action_id"] == body["action"]["id"]
|
||||
|
||||
|
||||
def test_backlog_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_backlog(client, token, initiative_id, status="triaged")
|
||||
assert created.status_code == 201
|
||||
item = created.json()
|
||||
|
||||
patched = client.patch(
|
||||
f"/api/backlog/{item['id']}",
|
||||
json={"status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
|
||||
deleted = client.delete(f"/api/backlog/{item['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_milestone_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_milestone(
|
||||
client, token, initiative_id, status="active", target_date="2026-12-31"
|
||||
)
|
||||
assert created.status_code == 201
|
||||
ms = created.json()
|
||||
assert ms["target_date"] == "2026-12-31"
|
||||
|
||||
deleted = client.delete(f"/api/milestones/{ms['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_member_has_ap08_capabilities(client):
|
||||
member = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, member)
|
||||
ctx = client.get("/api/me/context", headers=_auth(token)).json()
|
||||
caps = ctx["capabilities"]
|
||||
for key in (
|
||||
"kairo.attention.read",
|
||||
"kairo.blocker.read",
|
||||
"kairo.blocker.manage",
|
||||
"kairo.backlog.read",
|
||||
"kairo.backlog.manage",
|
||||
"kairo.milestone.read",
|
||||
"kairo.milestone.manage",
|
||||
):
|
||||
assert key in caps
|
||||
@@ -0,0 +1,165 @@
|
||||
"""AP0.9 — Operating Model Extension II tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def _create_evidence(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Evidence Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/evidence",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_decision(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Decision Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/decisions",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_review(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Review Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/reviews",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_recurring(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Recurring Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/recurring",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def test_action_ready_status_and_due_at(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
due = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||
created = client.post(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
json={"title": "Due Action", "status": "ready", "due_at": due},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
action = created.json()
|
||||
assert action["status"] == "ready"
|
||||
assert action["due_at"] is not None
|
||||
|
||||
|
||||
def test_attention_overdue_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id, title="Overdue").json()
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"due_at": past},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "overdue_action" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_review_due(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
created = _create_review(
|
||||
client, token, initiative_id, status="planned", due_at=past
|
||||
)
|
||||
assert created.status_code == 201
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "review_due" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_recurring_due(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
created = _create_recurring(
|
||||
client, token, initiative_id, status="active", next_due_at=past
|
||||
)
|
||||
assert created.status_code == 201
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "recurring_due" for i in res.json())
|
||||
|
||||
|
||||
def test_evidence_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_evidence(client, token, initiative_id)
|
||||
assert created.status_code == 201
|
||||
ev_id = created.json()["id"]
|
||||
|
||||
listed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/evidence", headers=_auth(token)
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
assert len(listed.json()) == 1
|
||||
|
||||
deleted = client.delete(f"/api/evidence/{ev_id}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_decision_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_decision(client, token, initiative_id, status="proposed")
|
||||
assert created.status_code == 201
|
||||
dec_id = created.json()["id"]
|
||||
|
||||
patched = client.patch(
|
||||
f"/api/decisions/{dec_id}",
|
||||
json={"status": "decided", "outcome": "Ja"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
assert patched.json()["status"] == "decided"
|
||||
|
||||
|
||||
def test_member_has_ap09_capabilities(client):
|
||||
member = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, member)
|
||||
ctx = client.get("/api/me/context", headers=_auth(token)).json()
|
||||
caps = ctx["capabilities"]
|
||||
for key in (
|
||||
"kairo.evidence.read",
|
||||
"kairo.evidence.manage",
|
||||
"kairo.decision.read",
|
||||
"kairo.decision.manage",
|
||||
"kairo.review.read",
|
||||
"kairo.review.manage",
|
||||
"kairo.recurring.read",
|
||||
"kairo.recurring.manage",
|
||||
):
|
||||
assert key in caps
|
||||
@@ -0,0 +1,81 @@
|
||||
"""AP0.10 — Integration: Snapshot, Transitions, Attention."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def test_steering_snapshot_graph(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id, title="Linked Action").json()
|
||||
|
||||
blocker = client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json={"title": "B", "action_id": action["id"]},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert blocker.status_code == 201
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
data = snap.json()
|
||||
assert isinstance(data.get("signals"), list)
|
||||
assert "operating_phase" not in data
|
||||
linked = next(a for a in data["actions"] if a["id"] == action["id"])
|
||||
assert len(linked["blockers"]) == 1
|
||||
assert linked["open_blocker_count"] == 1
|
||||
|
||||
|
||||
def test_blocker_resolve_unblocks_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()["id"]
|
||||
|
||||
created = client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json={
|
||||
"title": "Block",
|
||||
"action_id": action,
|
||||
"set_action_blocked": True,
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
blocker_id = created.json()["id"]
|
||||
blocked = client.get(f"/api/actions/{action}", headers=_auth(token)).json()
|
||||
assert blocked["status"] == "blocked"
|
||||
|
||||
client.patch(
|
||||
f"/api/blockers/{blocker_id}",
|
||||
json={"status": "resolved"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
unblocked = client.get(f"/api/actions/{action}", headers=_auth(token)).json()
|
||||
assert unblocked["status"] == "open"
|
||||
|
||||
|
||||
def test_attention_action_review_required_without_review(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "review_required"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "action_review_required" for i in res.json())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""AP0.10b — Steering UI Minimum tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def test_workspace_next_actions(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json={"title": "Blocker für NextAction"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/next-actions?limit=5", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
items = res.json()
|
||||
assert len(items) >= 1
|
||||
assert items[0]["recommended_action"]
|
||||
assert items[0]["initiative_id"]
|
||||
|
||||
|
||||
def test_workspace_today_actions(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(
|
||||
client, token, initiative_id, assigned_actor_ids=[user["actor_id"]]
|
||||
).json()
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"due_at": past},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/actions/today", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
items = res.json()
|
||||
assert len(items) >= 1
|
||||
assert items[0]["is_overdue"] is True
|
||||
|
||||
|
||||
def test_steering_snapshot_v2_fields(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/milestones",
|
||||
json={"title": "M1", "status": "planned", "target_date": "2026-12-31"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
data = snap.json()
|
||||
assert "upcoming_milestones" in data
|
||||
assert "next_actions" in data
|
||||
assert len(data["upcoming_milestones"]) >= 1
|
||||
@@ -0,0 +1,44 @@
|
||||
"""AP1.2 — Snapshot signals without operating_phase."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.signals.snapshot_signals import derive_initiative_signals
|
||||
|
||||
|
||||
def test_derive_signals_backlog_awaiting_commit():
|
||||
signals = derive_initiative_signals(
|
||||
initiative_status="active",
|
||||
open_actions=0,
|
||||
blocked_actions=0,
|
||||
review_required_actions=0,
|
||||
open_blockers=0,
|
||||
backlog_new=3,
|
||||
planned_reviews_due=0,
|
||||
)
|
||||
assert signals == ["backlog_awaiting_commit"]
|
||||
|
||||
|
||||
def test_derive_signals_work_in_progress():
|
||||
signals = derive_initiative_signals(
|
||||
initiative_status="active",
|
||||
open_actions=2,
|
||||
blocked_actions=0,
|
||||
review_required_actions=0,
|
||||
open_blockers=0,
|
||||
backlog_new=0,
|
||||
planned_reviews_due=0,
|
||||
)
|
||||
assert signals == ["work_in_progress"]
|
||||
|
||||
|
||||
def test_derive_signals_terminal():
|
||||
signals = derive_initiative_signals(
|
||||
initiative_status="completed",
|
||||
open_actions=0,
|
||||
blocked_actions=0,
|
||||
review_required_actions=0,
|
||||
open_blockers=0,
|
||||
backlog_new=0,
|
||||
planned_reviews_due=0,
|
||||
)
|
||||
assert signals == ["initiative_terminal"]
|
||||
@@ -0,0 +1,122 @@
|
||||
"""AP1.4 — RoadmapItem & Quality Gate tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def _create_roadmap_item(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Gate A", "item_type": "milestone", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/items",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def test_roadmap_item_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
created = _create_roadmap_item(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
sequencing_mode="parallel",
|
||||
item_type="maturity_stage",
|
||||
)
|
||||
assert created.status_code == 201
|
||||
item = created.json()
|
||||
assert item["item_type"] == "maturity_stage"
|
||||
assert item["sequencing_mode"] == "parallel"
|
||||
|
||||
listed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/items",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
assert len(listed.json()) >= 1
|
||||
|
||||
patched = client.patch(
|
||||
f"/api/roadmap-items/{item['id']}",
|
||||
json={"status": "at_risk"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
assert patched.json()["status"] == "at_risk"
|
||||
|
||||
deleted = client.delete(f"/api/roadmap-items/{item['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_verify_reached_requires_evidence(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
item = _create_roadmap_item(client, token, initiative_id, status="active").json()
|
||||
|
||||
fail = client.post(
|
||||
f"/api/roadmap-items/{item['id']}/verify-reached",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert fail.status_code == 400
|
||||
|
||||
evidence = client.post(
|
||||
f"/api/initiatives/{initiative_id}/evidence",
|
||||
json={
|
||||
"title": "Nachweis",
|
||||
"milestone_id": item["id"],
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert evidence.status_code == 201
|
||||
|
||||
ok = client.post(
|
||||
f"/api/roadmap-items/{item['id']}/verify-reached",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
assert ok.json()["status"] == "reached"
|
||||
assert ok.json()["verify_reason"] == "evidence_accepted"
|
||||
|
||||
|
||||
def test_milestone_compat_api_uses_roadmap(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
created = client.post(
|
||||
f"/api/initiatives/{initiative_id}/milestones",
|
||||
json={"title": "Legacy MS", "status": "planned"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
ms_id = created.json()["id"]
|
||||
|
||||
roadmap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/items",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
assert any(i["id"] == ms_id and i["item_type"] == "milestone" for i in roadmap)
|
||||
|
||||
|
||||
def test_steering_snapshot_reads_roadmap_items(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_roadmap_item(client, token, initiative_id, status="active", target_date="2026-12-31")
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
assert snap.get("roadmap_items")
|
||||
assert snap.get("upcoming_milestones")
|
||||
assert len(snap["upcoming_roadmap_items"]) >= 1
|
||||
@@ -0,0 +1,62 @@
|
||||
"""AP1.1 — Method Registry tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def test_list_steering_methods(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
|
||||
res = client.get("/api/steering/methods", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
methods = res.json()
|
||||
keys = {m["key"] for m in methods}
|
||||
assert "generic_operating" in keys
|
||||
assert "product_milestone_driven" in keys
|
||||
|
||||
|
||||
def test_change_initiative_method(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
res = client.patch(
|
||||
f"/api/steering/initiatives/{initiative_id}/context",
|
||||
json={"method_key": "product_milestone_driven"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["method_key"] == "product_milestone_driven"
|
||||
assert res.json()["method_label"] == "Produkt / Meilenstein"
|
||||
|
||||
|
||||
def test_product_milestone_next_action_prioritizes_milestone(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
client.patch(
|
||||
f"/api/steering/initiatives/{initiative_id}/context",
|
||||
json={"method_key": "product_milestone_driven"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/milestones",
|
||||
json={"title": "Release MVP", "status": "at_risk"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
next_actions = snap.json()["next_actions"]
|
||||
assert len(next_actions) >= 1
|
||||
assert next_actions[0]["kind"] == "review_milestone"
|
||||
@@ -0,0 +1,92 @@
|
||||
"""AP1.0 — Steering Foundation tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def test_steering_context_on_initiative_create(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
res = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-context",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["initiative_id"] == initiative_id
|
||||
assert data["lifecycle_state"] == "intake"
|
||||
assert data["method_key"] == "generic_operating"
|
||||
assert data["lifecycle_label"]
|
||||
|
||||
|
||||
def test_steering_snapshot_has_lifecycle(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_action(client, token, initiative_id)
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
data = snap.json()
|
||||
assert "lifecycle_state" in data
|
||||
assert "signals" in data
|
||||
assert "operating_phase" not in data
|
||||
assert data["lifecycle_state"] in (
|
||||
"intake",
|
||||
"planning",
|
||||
"action_selection",
|
||||
"structure_setup",
|
||||
)
|
||||
|
||||
|
||||
def test_steering_context_tenant_isolation(client):
|
||||
user_a = provision_user_in_tenant(tenant_role="member")
|
||||
token_a = _login(client, user_a)
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
|
||||
user_b = provision_user_in_tenant(tenant_role="member")
|
||||
token_b = _login(client, user_b)
|
||||
|
||||
res = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-context",
|
||||
headers=_auth(token_b),
|
||||
)
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
def test_lifecycle_transition_on_blocker_resolve(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(
|
||||
client, token, initiative_id, assigned_actor_ids=[user["actor_id"]]
|
||||
).json()
|
||||
blocker = client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json={"title": "B", "action_id": action["id"], "set_action_blocked": True},
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
|
||||
client.patch(
|
||||
f"/api/blockers/{blocker['id']}",
|
||||
json={"status": "resolved"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
ctx = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-context",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
assert ctx["lifecycle_state"] == "action_selection"
|
||||
@@ -0,0 +1,316 @@
|
||||
"""Initiatives and actions tests (AP0.5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from auth import AUTH_HEADER
|
||||
from db import get_connection
|
||||
from services.actors import create_actor
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def _login(client, user: dict) -> str:
|
||||
res = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
return res.json()["token"]
|
||||
|
||||
|
||||
def _auth(token: str) -> dict:
|
||||
return {AUTH_HEADER: token}
|
||||
|
||||
|
||||
def _create_initiative(client, token: str, *, title: str = "Test Vorhaben", **kwargs):
|
||||
body = {"title": title, **kwargs}
|
||||
return client.post("/api/initiatives", json=body, headers=_auth(token))
|
||||
|
||||
|
||||
def _create_action(client, token: str, initiative_id: str, *, title: str = "Test Maßnahme", **kwargs):
|
||||
body = {"title": title, **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def test_initiative_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Kairo MVP",
|
||||
goal="Erster Slice",
|
||||
priority="high",
|
||||
)
|
||||
assert created.status_code == 201
|
||||
initiative = created.json()
|
||||
assert initiative["title"] == "Kairo MVP"
|
||||
assert initiative["goal"] == "Erster Slice"
|
||||
assert initiative["status"] == "active"
|
||||
assert initiative["priority"] == "high"
|
||||
assert initiative["owner_actor_id"] == user["actor_id"]
|
||||
assert initiative["tenant_id"] == user["tenant_id"]
|
||||
|
||||
listed = client.get("/api/initiatives", headers=_auth(token))
|
||||
assert listed.status_code == 200
|
||||
assert any(i["id"] == initiative["id"] for i in listed.json())
|
||||
|
||||
fetched = client.get(f"/api/initiatives/{initiative['id']}", headers=_auth(token))
|
||||
assert fetched.status_code == 200
|
||||
|
||||
updated = client.patch(
|
||||
f"/api/initiatives/{initiative['id']}",
|
||||
json={"status": "paused", "goal": "Angepasst"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["status"] == "paused"
|
||||
assert updated.json()["goal"] == "Angepasst"
|
||||
|
||||
deleted = client.delete(f"/api/initiatives/{initiative['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
assert client.get(f"/api/initiatives/{initiative['id']}", headers=_auth(token)).status_code == 404
|
||||
|
||||
|
||||
def test_action_crud_and_status_change(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
created = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Status prüfen",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
)
|
||||
assert created.status_code == 201
|
||||
action = created.json()
|
||||
assert action["status"] == "open"
|
||||
assert action["assigned_actor_ids"] == [user["actor_id"]]
|
||||
|
||||
listed = client.get(f"/api/initiatives/{initiative_id}/actions", headers=_auth(token))
|
||||
assert listed.status_code == 200
|
||||
assert len(listed.json()) == 1
|
||||
|
||||
updated = client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "in_progress"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["status"] == "in_progress"
|
||||
|
||||
done = client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert done.status_code == 200
|
||||
assert done.json()["status"] == "done"
|
||||
|
||||
|
||||
def test_action_assignments(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
agent = create_actor(tenant_id=user["tenant_id"], actor_type="agent", name="Helper Agent")
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action_id = _create_action(client, token, initiative_id).json()["id"]
|
||||
|
||||
assigned = client.put(
|
||||
f"/api/actions/{action_id}/assignments",
|
||||
json={"actor_ids": [user["actor_id"], agent["id"]]},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert assigned.status_code == 200
|
||||
body = assigned.json()
|
||||
assert set(body["assigned_actor_ids"]) == {user["actor_id"], agent["id"]}
|
||||
|
||||
|
||||
def test_my_open_actions(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
|
||||
open_action = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Offen",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
in_progress = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="In Arbeit",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{in_progress['id']}",
|
||||
json={"status": "in_progress"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
done_action = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Erledigt",
|
||||
assigned_actor_ids=[user["actor_id"]],
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{done_action['id']}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
unassigned = _create_action(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="Nicht zugewiesen",
|
||||
).json()
|
||||
|
||||
open_res = client.get("/api/actions/me/open", headers=_auth(token))
|
||||
assert open_res.status_code == 200
|
||||
open_ids = {a["id"] for a in open_res.json()}
|
||||
assert open_action["id"] in open_ids
|
||||
assert in_progress["id"] in open_ids
|
||||
assert done_action["id"] not in open_ids
|
||||
assert unassigned["id"] not in open_ids
|
||||
for item in open_res.json():
|
||||
assert "initiative_title" in item
|
||||
|
||||
|
||||
def test_tenant_isolation_initiatives(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
|
||||
initiative_id = _create_initiative(client, token_a, title="Tenant A only").json()["id"]
|
||||
|
||||
assert client.get(f"/api/initiatives/{initiative_id}", headers=_auth(token_b)).status_code == 404
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/initiatives/{initiative_id}",
|
||||
json={"title": "Hack"},
|
||||
headers=_auth(token_b),
|
||||
).status_code
|
||||
== 404
|
||||
)
|
||||
assert client.get("/api/initiatives", headers=_auth(token_b)).json() == []
|
||||
|
||||
|
||||
def test_tenant_isolation_actions(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
action_id = _create_action(
|
||||
client,
|
||||
token_a,
|
||||
initiative_id,
|
||||
assigned_actor_ids=[user_a["actor_id"]],
|
||||
).json()["id"]
|
||||
|
||||
assert client.get(f"/api/actions/{action_id}", headers=_auth(token_b)).status_code == 404
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/actions/{action_id}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token_b),
|
||||
).status_code
|
||||
== 404
|
||||
)
|
||||
assert client.get("/api/actions/me/open", headers=_auth(token_b)).json() == []
|
||||
|
||||
|
||||
def test_cross_tenant_actor_assignment_rejected(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
action_id = _create_action(client, token_a, initiative_id).json()["id"]
|
||||
|
||||
res = client.put(
|
||||
f"/api/actions/{action_id}/assignments",
|
||||
json={"actor_ids": [user_b["actor_id"]]},
|
||||
headers=_auth(token_a),
|
||||
)
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
def test_audit_on_create_and_status_change(client):
|
||||
user = provision_user_in_tenant()
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token, title="Audit Test").json()["id"]
|
||||
action_id = _create_action(client, token, initiative_id).json()["id"]
|
||||
client.patch(
|
||||
f"/api/actions/{action_id}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT action FROM audit_log
|
||||
WHERE tenant_id = %s::uuid
|
||||
AND action IN (
|
||||
'initiative.created', 'action.created', 'action.status_changed'
|
||||
)
|
||||
ORDER BY created_at
|
||||
""",
|
||||
(user["tenant_id"],),
|
||||
)
|
||||
actions = {row[0] for row in cur.fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
assert "initiative.created" in actions
|
||||
assert "action.created" in actions
|
||||
assert "action.status_changed" in actions
|
||||
|
||||
|
||||
def test_unauthenticated_rejected(client):
|
||||
assert client.get("/api/initiatives").status_code == 401
|
||||
assert client.get("/api/actions/me/open").status_code == 401
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def enforce_capabilities(monkeypatch):
|
||||
monkeypatch.setenv("CAPABILITY_ENFORCE", "enforce")
|
||||
|
||||
|
||||
def test_member_has_initiative_capabilities(client):
|
||||
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||
token = _login(client, member)
|
||||
ctx = client.get("/api/me/context", headers=_auth(token)).json()
|
||||
assert "kairo.initiative.read" in ctx["capabilities"]
|
||||
assert "kairo.initiative.manage" in ctx["capabilities"]
|
||||
assert "kairo.action.read" in ctx["capabilities"]
|
||||
assert "kairo.action.manage" in ctx["capabilities"]
|
||||
|
||||
|
||||
def test_invalid_status_rejected(client):
|
||||
user = provision_user_in_tenant()
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action_id = _create_action(client, token, initiative_id).json()["id"]
|
||||
|
||||
res = client.patch(
|
||||
f"/api/actions/{action_id}",
|
||||
json={"status": "invalid_status"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 422
|
||||
@@ -36,6 +36,9 @@ def test_migration_runner_finds_migrations():
|
||||
assert "003_data_seeds_tracking" in names
|
||||
assert "004_capabilities_registry" in names
|
||||
assert "005_prompt_feature_config_registry" in names
|
||||
assert "006_initiatives_actions" in names
|
||||
assert "007_operating_model_extension_i" in names
|
||||
assert "008_operating_model_extension_ii" in names
|
||||
|
||||
|
||||
def test_migration_runner_is_idempotent():
|
||||
@@ -50,6 +53,9 @@ def test_migration_runner_is_idempotent():
|
||||
assert "003_data_seeds_tracking" in executed
|
||||
assert "004_capabilities_registry" in executed
|
||||
assert "005_prompt_feature_config_registry" in executed
|
||||
assert "006_initiatives_actions" in executed
|
||||
assert "007_operating_model_extension_i" in executed
|
||||
assert "008_operating_model_extension_ii" in executed
|
||||
|
||||
|
||||
def test_core_table_exists():
|
||||
|
||||
@@ -13,6 +13,7 @@ def test_registry_contains_initial_capabilities():
|
||||
"kairo.admin.access",
|
||||
"kairo.tenant.manage",
|
||||
"kairo.actor.manage",
|
||||
"kairo.actor.read",
|
||||
"kairo.context.read",
|
||||
"kairo.entitlements.read",
|
||||
"kairo.feature.registry.read",
|
||||
@@ -22,6 +23,26 @@ def test_registry_contains_initial_capabilities():
|
||||
"kairo.config.registry.read",
|
||||
"kairo.config.registry.manage",
|
||||
"kairo.prompt.render",
|
||||
"kairo.initiative.read",
|
||||
"kairo.initiative.manage",
|
||||
"kairo.action.read",
|
||||
"kairo.action.manage",
|
||||
"kairo.workspace.read",
|
||||
"kairo.attention.read",
|
||||
"kairo.blocker.read",
|
||||
"kairo.blocker.manage",
|
||||
"kairo.backlog.read",
|
||||
"kairo.backlog.manage",
|
||||
"kairo.milestone.read",
|
||||
"kairo.milestone.manage",
|
||||
"kairo.evidence.read",
|
||||
"kairo.evidence.manage",
|
||||
"kairo.decision.read",
|
||||
"kairo.decision.manage",
|
||||
"kairo.review.read",
|
||||
"kairo.review.manage",
|
||||
"kairo.recurring.read",
|
||||
"kairo.recurring.manage",
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +54,7 @@ def test_sync_is_idempotent():
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM capabilities")
|
||||
assert cur.fetchone()[0] == 12
|
||||
assert cur.fetchone()[0] == 33
|
||||
cur.execute("SELECT COUNT(*) FROM role_capability_grants")
|
||||
assert cur.fetchone()[0] >= 5
|
||||
finally:
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "0.4.0-ap0.4"
|
||||
DB_SCHEMA_VERSION = "005"
|
||||
APP_VERSION = "0.13.0-ap1.4"
|
||||
DB_SCHEMA_VERSION = "010"
|
||||
APP_NAME = "jinkendo-kairo"
|
||||
+14
-1
@@ -11,6 +11,19 @@ Kairo trennt **Schema-Migrationen** (einmalig) von **Data-Seeds** (idempotent, b
|
||||
| **Ausführung** | Beim Backend-Start (`run_migrations.py`), überspringbar via `SKIP_DB_MIGRATE=1` |
|
||||
| **Regel** | Jede Datei wird **genau einmal** angewendet. Änderungen → neue nummerierte Datei. |
|
||||
|
||||
### Aktuelle Schema-Migrationen
|
||||
|
||||
| Nr. | Datei | AP | Inhalt |
|
||||
|-----|-------|-----|--------|
|
||||
| 001 | `001_init_core.sql` | AP0.1 | `kairo_app_meta` |
|
||||
| 002 | `002_auth_identity_tenant_actor.sql` | AP0.2 | User, Tenant, Actor, Session, `audit_log` |
|
||||
| 003 | `003_data_seeds_tracking.sql` | AP0.2+ | `data_seeds` |
|
||||
| 004 | `004_capabilities_registry.sql` | AP0.3 | `capabilities`, `role_capability_grants` |
|
||||
| 005 | `005_prompt_feature_config_registry.sql` | AP0.4 | Feature/Prompt/Placeholder/Config |
|
||||
| 006 | `006_initiatives_actions.sql` | AP0.5 | `initiatives`, `actions`, `action_assignments` |
|
||||
|
||||
Aktuelle Schema-Version: **`006`** (`backend/version.py` → `DB_SCHEMA_VERSION`).
|
||||
|
||||
## Data-Seeds
|
||||
|
||||
| | |
|
||||
@@ -35,7 +48,7 @@ docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py --
|
||||
|
||||
| Seed | Typ | Zweck |
|
||||
|------|-----|--------|
|
||||
| `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`) und verwaiste Test-Tenants |
|
||||
| `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`), verwaiste Test-Tenants; löscht zuerst Initiatives (AP0.5 FK) |
|
||||
| `seed_002_bootstrap_admin` | Python | Legt Systemadmin aus `KAIRO_BOOTSTRAP_*` an, wenn noch kein User existiert |
|
||||
| `seed_003_ensure_dev_admin` | Python (dev) | Entfernt fremde Dev-User, stellt `lars@stommer.com` als Portal-Admin sicher (jeder Start) |
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Architecture Decision Proposal — AP0.5 Scope-Verschiebung Sprint 0
|
||||
|
||||
**Status:** angenommen (Umsetzung abgeschlossen)
|
||||
**Stand:** 2026-07-05
|
||||
**Autor:** Sprint-0-Umsetzung (Cursor/Claude)
|
||||
**Commits:** `afa6815`, `a34a614`
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
In `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` ist **AP0.5** als *Audit und minimale Admin-Prüfbarkeit* definiert. Gleichzeitig verbietet §13 *Vorhaben/Projektlogik in Sprint 0 vorziehen*; Sprint 1 sieht Vorhaben und Maßnahmen vor.
|
||||
|
||||
Für den ersten **fachlich nutzbaren Kairo-Slice** wurde AP0.5 bewusst neu beauftragt als *Minimaler Vorhaben- und Maßnahmen-Slice* (Migration 006, CRUD, Assignments, Capability-Gates, Tests).
|
||||
|
||||
Ohne dokumentierte Entscheidung entsteht ein **Nummerierungs- und Scope-Konflikt** zwischen Foundation-Dokument und Implementierung.
|
||||
|
||||
---
|
||||
|
||||
## Betroffene Regel
|
||||
|
||||
| Dokument | Regel |
|
||||
|----------|--------|
|
||||
| `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.5 | Audit + Admin-Prüfbarkeit |
|
||||
| `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` §13 | Keine Vorhaben/Projektlogik in Sprint 0 vorziehen |
|
||||
| `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` §14 | Vorhaben/Maßnahmen in Sprint 1 |
|
||||
| `Kairo_Sprint0_Principle_Gate_v0.1.md` G-01–G-12 | Architekturprinzipien (weiterhin verbindlich) |
|
||||
|
||||
---
|
||||
|
||||
## Optionen
|
||||
|
||||
| Option | Kurzbeschreibung | Pro | Contra |
|
||||
|--------|------------------|-----|--------|
|
||||
| A | Foundation-AP0.5 zuerst (Audit/Admin), Vorhaben in Sprint 1 | Entspricht Foundation 1:1 | Kein fachlicher End-to-End-Slice; Audit ohne Domäne schwer demonstrierbar |
|
||||
| B | **AP0.5 = Vorhaben/Maßnahmen-Slice; Foundation-AP0.5 → AP0.6 umbenennen** | Erster nutzbarer Slice; Principle Gate eingehalten (Tenant, Actor, Capability, Audit) | Scope-Verschiebung; Foundation-Dokument veraltet bis Update |
|
||||
| C | Vorhaben ohne AP-Nummer (Sprint-1-Vorgriff) | Schnell | Undokumentiert; verwirrt Sprint-Tracking |
|
||||
|
||||
---
|
||||
|
||||
## Empfehlung
|
||||
|
||||
**Option B** — angenommen und umgesetzt.
|
||||
|
||||
Begründung:
|
||||
|
||||
1. Der Slice ist **minimal** (keine Projects, Milestones, Programs, Reviews, KI).
|
||||
2. **Principle Gate** bleibt eingehalten: Tenant-first, Actor-first, TenantContext, Capability Registry, nummerierte Migration, Audit.
|
||||
3. Der ursprüngliche Foundation-AP0.5-Inhalt (granulares Audit, Admin-Routen) wird als **AP0.6** eingeplant — kein Verlust, nur Verschiebung.
|
||||
|
||||
---
|
||||
|
||||
## Risiko
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Foundation-Dokument und Code divergieren | Dieses ADP + Abschlussbericht AP0.5 v0.2; Foundation-Update in separatem Doc-Pass |
|
||||
| Sprint-1-Doppelarbeit | AP0.5 bewusst minimal; Meilensteine/Programme/Backlog bleiben Sprint 1 |
|
||||
| Audit-Schema ohne `actor_id` | Bekannte Lücke seit AP0.2; AP0.6 kann Schema erweitern |
|
||||
|
||||
---
|
||||
|
||||
## Rückbaubarkeit
|
||||
|
||||
- Tabellen `initiatives`, `actions`, `action_assignments` sind additiv (Migration 006).
|
||||
- Rückbau: neue Migration mit `DROP TABLE` — keine Änderung an AP0.1–0.4-Tabellen.
|
||||
- Capabilities in `initiative_ops.py` können deaktiviert werden, ohne andere Module zu brechen.
|
||||
|
||||
---
|
||||
|
||||
## Auswirkung auf Sprint 0
|
||||
|
||||
| Thema | Auswirkung |
|
||||
|-------|------------|
|
||||
| Sprint-0-Fundament (AP0.1–0.4) | unverändert |
|
||||
| AP0.5 (neu) | fachlicher Minimal-Slice Vorhaben/Maßnahmen |
|
||||
| Foundation-AP0.5 (Audit/Admin) | **→ AP0.6** (empfohlen) |
|
||||
| Sprint-0 DoD §12 | Vorhaben-Teil formal Sprint 1 — durch ADP begründete Ausnahme |
|
||||
| Prod/Dev | Schema `006`; pytest 55/55 grün nach Cleanup-Seed-Fix |
|
||||
|
||||
---
|
||||
|
||||
## Nächste Schritte (Dokumentation)
|
||||
|
||||
1. ~~ADP (dieses Dokument)~~
|
||||
2. ~~`docs/MIGRATIONS.md` um 006 ergänzen~~
|
||||
3. ~~`Sprint0_AP0_5_Completion_Report_v0.2.md`~~
|
||||
4. Foundation v0.4 (optional): AP-Nummern und §13/§14 angleichen
|
||||
@@ -0,0 +1,240 @@
|
||||
# Architecture Decision Proposal — AP1.0 Steering Foundation & Scope Lock
|
||||
|
||||
**Status:** angenommen (Umsetzung ausstehend)
|
||||
**Stand:** 2026-07-05
|
||||
**Autor:** Product/Architektur-Review (Cursor-Session)
|
||||
**Auslöser:** AP0.8–0.10b liefern OM-Inventar + provisorische Steuerungsfragmente ohne `backend/steering/` — Architektur-Kohärenz und MVP-Nachweis fehlen.
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Kairo hat drei parallele Steuerungsfragmente ohne gemeinsamen Kern:
|
||||
|
||||
| Fragment | Ort | Rolle |
|
||||
|----------|-----|--------|
|
||||
| Attention / NextAction | `data_layer/attention.py` | Regelbasierte Signale |
|
||||
| Transitions | `services/operating_transitions.py` | Blocker/Review Side Effects |
|
||||
| Operating Phase | `initiative_snapshot._derive_operating_phase` | UI-Heuristik (nicht persistiert) |
|
||||
|
||||
Das **Zielmodell** (Standard Lifecycle, Method Registry, Hook Registry, SteeringContext) ist in Target Architecture und Universal Steering Engine **entschieden**, aber **nicht implementiert** (`backend/steering/` = 0 Dateien).
|
||||
|
||||
Gleichzeitig wurde der dokumentierte Pfad „Inventar → Validation → Steering Core“ **gebrochen**:
|
||||
|
||||
- AP0.10a/b lieferten Integration/UI statt Validation
|
||||
- Offene Entscheidungen (Universal Steering §33: `steering_contexts`, `roadmap_item_id`) blieben ungeklärt
|
||||
- `milestones`-Tabelle als MVP-Brücke ohne Roadmap-Konsolidierungs-ADP
|
||||
|
||||
**Leitfrage:** Bauen wir weiter provisorische Enden, die später teuer refactored werden müssen — oder wechseln wir zu **Foundation-first** mit schmalem Steering-Skeleton?
|
||||
|
||||
---
|
||||
|
||||
## Betroffene Regel
|
||||
|
||||
| Dokument | Regel |
|
||||
|----------|--------|
|
||||
| `Kairo_Product_Definition_and_MVP_Reset_v0.1.md` §4 | Kairo ≠ `Initiative → Action` |
|
||||
| `Kairo_Canonical_Operating_Model_v0.1.md` §8 | Data Layer Read; Services Write |
|
||||
| `Kairo_Target_Architecture_…_v0.1.md` §7 | Standard Lifecycle als gemeinsame Basis |
|
||||
| `Kairo_Universal_Steering_Engine_Decision_v0.1.md` §32 | AP0.8 max. Ebene 1; spätere Fähigkeit nicht verbauen |
|
||||
| `Kairo_Operating_Model_Steering_Bridge_v0.1.md` §6 | Evolutionspfad AP1.0 → AP1.3 |
|
||||
| `Kairo_Sprint0_Principle_Gate_v0.1.md` G-01 | Verhindert teures Refactoring? |
|
||||
| `Kairo_MVP_Usability_Recovery_Plan_v0.1.md` §3 | Roadmap-Korrektur (wird durch dieses ADP ersetzt) |
|
||||
|
||||
---
|
||||
|
||||
## Optionen
|
||||
|
||||
| Option | Kurzbeschreibung | Pro | Contra |
|
||||
|--------|------------------|-----|--------|
|
||||
| A | **Weiter wie bisher** — AP0.10c UI, mehr Heuristiken, AP1.0 „irgendwann“ | Kurzfristig sichtbar | Mehr lose Enden; Doppel-Wahrheit Phase/Lifecycle; teurer Refactor |
|
||||
| B | **Strategiewechsel:** Scope Lock + AP1.0 Skeleton + Konsolidierung | Passt zu Zielarchitektur; eine Steuerungswahrheit | Kurz weniger neue UI-Features |
|
||||
| C | **Big Bang** — vollständiger Steering Core + Method Registry sofort | Architektonisch „fertig“ | Over-Engineering; ohne Validation falsche Methoden |
|
||||
|
||||
---
|
||||
|
||||
## Empfehlung
|
||||
|
||||
**Option B — angenommen.**
|
||||
|
||||
Begründung:
|
||||
|
||||
1. OM-Tabellen (AP0.8/0.9) sind **Andockdaten**, kein Wegwerf-Inventar.
|
||||
2. Was teuer wird, ist **verteilte Steuerungslogik** — nicht die Entitäten.
|
||||
3. Ein **schmaler AP1.0-Skeleton** (persistierter Lifecycle, Registry-Gerüst, Signal-Engine-Interface) ist die fehlende Foundation, auf die Methoden und Features einrasten.
|
||||
4. Validation (AP0.10d) **informiert** AP1.1 (erste Built-in-Methode), blockiert AP1.0 nicht.
|
||||
|
||||
---
|
||||
|
||||
## Scope Lock — ab sofort verbindlich
|
||||
|
||||
### Eingefroren (kein neues Code ohne ADP-Ausnahme)
|
||||
|
||||
| # | Verbot | Begründung |
|
||||
|---|--------|------------|
|
||||
| L1 | Neue Steuerungs-Heuristiken in `initiative_snapshot`, Routern, Frontend | Ersetzt durch `lifecycle_state` ab AP1.0 |
|
||||
| L2 | Duplizierte NextAction-/Attention-Regeln (neue SQL-Varianten) | Konsolidierung in `steering/signals/` |
|
||||
| L3 | **AP0.10c** Initiative Flow UI (Maßnahmen-Hub, Sektionen) | Erst nach AP1.0a — UI soll `lifecycle_state` lesen, nicht dritte Phase-Logik |
|
||||
| L4 | Neue OM-Tabellen | Regel aus Recovery Plan bleibt |
|
||||
| L5 | Workflow Runtime, Method Designer, KI/MCP | Product Direction |
|
||||
| L6 | `operating_phase` als zweite Wahrheit ausbauen | Nur Anzeige-Proxy bis AP1.2; dann aus `SteeringContext` |
|
||||
|
||||
### Erlaubt ohne ADP
|
||||
|
||||
| # | Erlaubt |
|
||||
|---|---------|
|
||||
| E1 | Bugfixes, Tenant-Invarianten, Tests |
|
||||
| E2 | AP0.10d Validation (Dokument + Checkliste, kein neues Steuerungs-SQL) |
|
||||
| E3 | AP1.0 Implementierung gemäß Assignment |
|
||||
| E4 | Refactor bestehender Regeln **in** `backend/steering/` (keine neuen Regeln) |
|
||||
| E5 | UI-Labels, die `lifecycle_state` / Hook-Signale **anzeigen** (nach AP1.0) |
|
||||
|
||||
---
|
||||
|
||||
## AP1.0 — Minimaler Steering-Skeleton (nächstes Code-Paket)
|
||||
|
||||
**Ziel:** Eine persistierte Steuerungswahrheit pro Initiative — Methoden können später einhängen.
|
||||
|
||||
**Nicht-Ziel:** Workflow Runtime, Agenten, Method Designer, Roadmap-Konsolidierung, volle Method Packages.
|
||||
|
||||
### A) Schema (Migration 009)
|
||||
|
||||
```text
|
||||
steering_contexts (
|
||||
id, tenant_id, initiative_id UNIQUE,
|
||||
method_key DEFAULT 'generic_operating',
|
||||
method_version DEFAULT '0.1.0',
|
||||
lifecycle_state NOT NULL, -- Standard Lifecycle Slug
|
||||
lifecycle_metadata JSONB DEFAULT '{}',
|
||||
created_at, updated_at
|
||||
)
|
||||
```
|
||||
|
||||
**Initial `lifecycle_state`:** bestehende Initiativen → `action_selection` wenn offene Actions, sonst `structure_setup` (Seed/Backfill-Logik im Assignment).
|
||||
|
||||
**Entscheidung Milestone-Brücke:** `milestones`-Tabelle **bleibt** bis AP1.2/ADP-TA-08 — keine Migration 009 zu `roadmap_items`.
|
||||
|
||||
### B) Backend-Modul `backend/steering/`
|
||||
|
||||
```text
|
||||
steering/
|
||||
__init__.py
|
||||
lifecycle/
|
||||
states.py # STANDARD_LIFECYCLE_STEPS (12 Slugs)
|
||||
orchestrator.py # get_state, transition (minimal, Guards stub)
|
||||
hooks/
|
||||
registry.py # HookDefinition + register_hook (Slugs aus Target Arch §7.3)
|
||||
dispatch.py # dispatch_hook(slug, ctx, payload) — no-op + audit stub
|
||||
methods/
|
||||
registry.py # MethodDefinition + register_method
|
||||
registrations/
|
||||
generic_operating.py # einzige Built-in-Methode AP1.0
|
||||
signals/
|
||||
engine.py # evaluate(ctx, scope) → ruft Provider auf
|
||||
default_rules.py # Move/wrap aus attention.py (keine neuen Regeln)
|
||||
context.py # get_or_create_steering_context, resolve_for_initiative
|
||||
```
|
||||
|
||||
### C) Services-Integration (minimal)
|
||||
|
||||
| Heute | AP1.0 |
|
||||
|-------|-------|
|
||||
| `operating_transitions.after_blocker_*` | ruft `dispatch_hook('on_blocker_resolved', …)` + Lifecycle-Transition wenn Guard passt |
|
||||
| `operating_transitions.after_review_*` | `on_review_completed` |
|
||||
| `initiative_snapshot.operating_phase` | **Deprecated-Feld**; parallel `lifecycle_state` + `lifecycle_label` aus Context |
|
||||
| `data_layer/attention.py` | Delegiert an `signals/engine.py` (Wrapper, Datei bleibt für API-Kompatibilität) |
|
||||
|
||||
### D) API (minimal)
|
||||
|
||||
| Endpoint | Beschreibung |
|
||||
|----------|--------------|
|
||||
| `GET /api/initiatives/{id}/steering-context` | Context + lifecycle_state + method_key |
|
||||
| Erweiterung `steering-snapshot` | Felder `lifecycle_state`, `lifecycle_label`; `operating_phase` als deprecated alias |
|
||||
|
||||
### E) Frontend (minimal)
|
||||
|
||||
- Steuerungszustand-Panel: **Lifecycle-Label** aus API (fachliches Label via `operating.js` Mapping auf Standard Lifecycle)
|
||||
- Kein AP0.10c Maßnahmen-Hub
|
||||
|
||||
### F) Tests
|
||||
|
||||
- SteeringContext tenant-scoped, Cross-Tenant 404
|
||||
- Lifecycle-Transition bei Blocker resolved (bestehendes Verhalten, neuer Pfad)
|
||||
- Signal Engine liefert gleiche Attention-Count wie vor Refactor (Regression)
|
||||
|
||||
### G) Version
|
||||
|
||||
- `0.11.0-ap1.0` · Schema `009`
|
||||
|
||||
---
|
||||
|
||||
## Konsolidierungs-Roadmap nach AP1.0
|
||||
|
||||
```text
|
||||
AP1.0 Steering Foundation (dieses ADP) ← JETZT
|
||||
AP0.10d MVP Validation (5 Vorhaben) ← parallel / unmittelbar danach
|
||||
AP1.1 Method Registry + 2. Built-in-Methode (product_milestone_driven)
|
||||
AP1.2 attention.py vollständig → signals/; operating_phase entfernen
|
||||
AP1.3 operating_transitions → Hook Orchestrator
|
||||
AP1.4 Milestone → RoadmapItem (ADP-TA-08) — nur mit separater ADP
|
||||
AP0.10c Initiative Flow UI ← nach AP1.2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Was bleibt / was wird refactored / was nicht weggeworfen
|
||||
|
||||
| Kategorie | Inhalt |
|
||||
|-----------|--------|
|
||||
| **Bleibt** | OM-Tabellen, Tenant/Actor/Capabilities, Data Layer Pattern, Backlog→Action, CRUD Services |
|
||||
| **Refactor** | `attention.py`, `operating_transitions.py`, Snapshot-Phase |
|
||||
| **Deprecated dann entfernen** | `operating_phase` Heuristik (AP1.2) |
|
||||
| **Spätere ADP** | `milestones` → `roadmap_items`, Project-Entität, generisches Assignment |
|
||||
|
||||
---
|
||||
|
||||
## Risiko
|
||||
|
||||
| Risiko | Schwere | Mitigation |
|
||||
|--------|---------|------------|
|
||||
| AP1.0 verzögert Nutzer-UI | mittel | AP0.10b bleibt; Validation dokumentiert Lücken |
|
||||
| Refactor bricht Attention-Tests | mittel | Regression-Suite vor Move |
|
||||
| Lifecycle zu abstrakt | mittel | Fachliche Labels in UI; `generic_operating` Method |
|
||||
| Doppelmodell Phase + Lifecycle kurz | niedrig | `operating_phase` deprecated; ADP L6 |
|
||||
| Over-Engineering AP1.0 | mittel | Assignment definiert harte Nicht-Ziele |
|
||||
|
||||
---
|
||||
|
||||
## Rückbaubarkeit
|
||||
|
||||
- Migration 009 additiv; `steering_contexts` droppbar ohne OM-Tabellen zu berühren
|
||||
- Wrapper in `attention.py` kann wieder direkt SQL ausführen
|
||||
- `operating_transitions` bleibt bis AP1.3 als Fallback aufrufbar
|
||||
- Method Registry mit einem Eintrag — Erweiterung ohne Schema-Change
|
||||
|
||||
---
|
||||
|
||||
## Auswirkung auf Sprint 0 / Sprint 1
|
||||
|
||||
| Thema | Auswirkung |
|
||||
|-------|------------|
|
||||
| AP0.8–0.9 | **Gültig** — System of Record |
|
||||
| AP0.10a/b | **Gültig** — Integration/UI; keine weiteren Ausbauten |
|
||||
| AP0.10c | **Eingefroren** bis AP1.2 |
|
||||
| AP0.10d | **Freigegeben** — Validation Report als Gate für AP1.1 |
|
||||
| Sprint 1 Start | AP1.0 = offizieller Sprint-1-Einstieg (Steering Foundation) |
|
||||
| Foundation AP0.1–0.7 | Unverändert gültig |
|
||||
|
||||
---
|
||||
|
||||
## Nächste Schritte
|
||||
|
||||
1. ~~ADP (dieses Dokument)~~ — angenommen
|
||||
2. `docs/sprints/Sprint1_AP1_0_Steering_Foundation_Assignment_v0.1.md` — Implementierungsauftrag
|
||||
3. `Kairo_MVP_Usability_Recovery_Plan_v0.1.md` §3 — Roadmap an ADP anbinden
|
||||
4. Umsetzung AP1.0 auf Branch `develop`
|
||||
5. AP0.10d Validation Report vor AP1.1
|
||||
|
||||
---
|
||||
|
||||
*Referenz: KAIRO-ARCH-01, Operating Model Steering Bridge, Universal Steering Engine Decision §31–32*
|
||||
@@ -0,0 +1,201 @@
|
||||
# ADP — Operational Actor Interface (Vibe-Coder) v0.1
|
||||
|
||||
**Status:** Entwurf zur Freigabe
|
||||
**Stand:** 2026-07-05
|
||||
**Autor:** Product/Architecture (DOC Welle 2)
|
||||
**Vision:** `Kairo_Vision_and_Product_Direction_v0.2.md` §7.5
|
||||
**Paket:** AP1.7
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Vibe-Coder und andere Agenten-Actors sollen Status melden, Next Action anfragen und Entscheidungsunterlagen ablegen — **ohne** UI und **ohne** Ad-hoc-Prompts.
|
||||
|
||||
Heute: Actors existieren (`actor_type=agent`), aber keine **definierte, auditierte API** für operative Arbeit. Gefahr: parallele Agent-Sonderlogik außerhalb `backend/steering/`.
|
||||
|
||||
---
|
||||
|
||||
## Betroffene Regel
|
||||
|
||||
- Canonical OM v0.2 §13 (Agenten-Regel)
|
||||
- Scope Lock AP1.0 — Agent-Runtime eingefroren; **API-Oberfläche** ist erlaubt nach IA
|
||||
- Tenant Invariants — Actor-first, Capability-gated
|
||||
|
||||
---
|
||||
|
||||
## Optionen
|
||||
|
||||
| Option | Kurzbeschreibung | Pro | Contra |
|
||||
|--------|------------------|-----|--------|
|
||||
| **A** | Bestehende REST-Endpoints + API-Keys pro Agent | Schnell | Uneinheitlich; fehlende Agent-Semantik |
|
||||
| **B** | **`/api/operational/`** Namespace — dünne Fassade über Services + Steering | Klar, dokumentiert, auditierbar | Neues Router-Paket |
|
||||
| **C** | MCP-only | Modern | Scope Lock; vorzeitig |
|
||||
|
||||
## Empfehlung
|
||||
|
||||
**Option B** — Operational API als **stabile Fassade** (AP1.7), intern ruft bestehende Services + `backend/steering/` auf.
|
||||
|
||||
Auth: Session oder **Actor Service Token** (Tenant-scoped, Capability-gebunden) — Detail in AP1.7 Implementierung.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints (v0.1 Spec)
|
||||
|
||||
Basis: `/api/operational` — alle Requests mit Actor-Identität (nicht User impersonation ohne Audit).
|
||||
|
||||
### Kontext
|
||||
|
||||
```http
|
||||
GET /api/operational/initiatives/{id}/context
|
||||
```
|
||||
|
||||
→ Steering Snapshot + Lifecycle + Method (subset für Agenten).
|
||||
|
||||
### Next Action
|
||||
|
||||
```http
|
||||
GET /api/operational/next-action?initiative_id=&limit=
|
||||
```
|
||||
|
||||
→ `NextActionCandidate[]` für **aufrufenden Actor** via `backend/steering/strategies/next_action/`.
|
||||
|
||||
### Arbeitspaket (Action)
|
||||
|
||||
```http
|
||||
GET /api/operational/actions/{id}
|
||||
PATCH /api/operational/actions/{id}/status
|
||||
{ "status": "in_progress", "note": "..." }
|
||||
POST /api/operational/actions/{id}/assignments
|
||||
{ "actor_ids": ["..."] }
|
||||
```
|
||||
|
||||
Capabilities: `kairo.action.read`, `kairo.action.manage`.
|
||||
|
||||
### Blocker
|
||||
|
||||
```http
|
||||
POST /api/operational/blockers
|
||||
{ "initiative_id", "action_id?", "title", "description?" }
|
||||
PATCH /api/operational/blockers/{id}
|
||||
{ "status": "resolved" }
|
||||
```
|
||||
|
||||
Capability: `kairo.blocker.manage`.
|
||||
|
||||
### Evidence
|
||||
|
||||
```http
|
||||
POST /api/operational/evidence
|
||||
{ "initiative_id", "action_id?", "roadmap_item_id?", "title", "body?" }
|
||||
```
|
||||
|
||||
Capability: `kairo.evidence.manage`.
|
||||
|
||||
### Decision-Unterlage
|
||||
|
||||
```http
|
||||
POST /api/operational/decisions/proposals
|
||||
{
|
||||
"initiative_id",
|
||||
"title",
|
||||
"rationale",
|
||||
"evidence_ids": [],
|
||||
"proposed_status": "proposed"
|
||||
}
|
||||
```
|
||||
|
||||
Erzeugt Decision `proposed` + verknüpfte Evidence — **kein** auto-`decided`.
|
||||
|
||||
Capability: `kairo.decision.manage`.
|
||||
|
||||
### Backlog-Vorschlag
|
||||
|
||||
```http
|
||||
POST /api/operational/backlog/proposals
|
||||
{ "initiative_id", "title", "description?", "roadmap_item_id?" }
|
||||
```
|
||||
|
||||
Status `new` — kein Auto-Convert zu Action.
|
||||
|
||||
Capability: `kairo.backlog.manage`.
|
||||
|
||||
### Explizit nicht in v0.1
|
||||
|
||||
- Gate `reached` setzen
|
||||
- Initiative Lifecycle ändern
|
||||
- Method wechseln
|
||||
- Portfolio-Priorität
|
||||
|
||||
---
|
||||
|
||||
## Response-Konvention
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": { },
|
||||
"actor_id": "uuid",
|
||||
"audit_ref": "uuid optional"
|
||||
}
|
||||
```
|
||||
|
||||
Fehler: HTTP 403 Capability, 404 Tenant-Isolation, 422 Validation.
|
||||
|
||||
---
|
||||
|
||||
## Audit
|
||||
|
||||
Jeder mutierende Call:
|
||||
|
||||
- `audit_log`: actor_id, action, resource_type, resource_id, payload_hash
|
||||
- Agent-Runs später korrelierbar (`agent_run_id` optional header)
|
||||
|
||||
---
|
||||
|
||||
## UI-Äquivalenz
|
||||
|
||||
| API | UI-Ort |
|
||||
|-----|--------|
|
||||
| context | Initiative-Übersicht |
|
||||
| next-action | Next-Action-Widget |
|
||||
| action status | Ausführung / Action-Detail |
|
||||
| blockers/evidence | Action-Detail / Unterseiten |
|
||||
| decision proposals | Entscheidungen-Unterseite |
|
||||
|
||||
---
|
||||
|
||||
## Implementierungsreihenfolge
|
||||
|
||||
1. AP1.2c — IA steht
|
||||
2. AP1.7a — Read-only: context, next-action, get action
|
||||
3. AP1.7b — Mutations: status, blockers, evidence, proposals
|
||||
4. AP1.7c — Actor Service Token Auth (wenn Session nicht reicht)
|
||||
|
||||
---
|
||||
|
||||
## Risiko
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Agent umgeht Gate-Verify | Endpoint-Whitelist; kein gate reached |
|
||||
| Token-Leak | Tenant-scoped, rotierbar, minimal capabilities |
|
||||
| Duplikat-Logik | Fassade nur — Services/steering unverändert |
|
||||
|
||||
---
|
||||
|
||||
## Rückbaubarkeit
|
||||
|
||||
Router `/api/operational` entfernbar ohne Domänenänderung.
|
||||
|
||||
---
|
||||
|
||||
## Freigabe-Checkliste PO
|
||||
|
||||
- [ ] Endpoint-Liste ausreichend für Vibe-Coder-Handover
|
||||
- [ ] Proposals statt Auto-Commit akzeptiert
|
||||
- [ ] AP1.7 nach AP1.2c
|
||||
|
||||
---
|
||||
|
||||
*Handover: `Sprint0_Vibe_Coder_Handover_v0.2.md`*
|
||||
@@ -0,0 +1,178 @@
|
||||
# ADP — RoadmapItem & Quality Gate Model v0.1
|
||||
|
||||
**Status:** Entwurf zur Freigabe
|
||||
**Stand:** 2026-07-05
|
||||
**Autor:** Product/Architecture (DOC Welle 2)
|
||||
**Vision:** `Kairo_Vision_and_Product_Direction_v0.2.md` §6
|
||||
**Paket:** AP1.4
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Die Tabelle `milestones` ist eine **MVP-Brücke** mit Titel, optionalem Text, Status-Dropdown — **kein Quality Gate**:
|
||||
|
||||
- kein prüfbares DoD-Modell
|
||||
- keine Abhängigkeiten (sequenziell / parallel)
|
||||
- kein Verify vor `reached`
|
||||
- keine Plan-Ist-Verknüpfung zu Actions/Backlog
|
||||
- irreführend in UI und Docs als „Meilenstein fertig“
|
||||
|
||||
Gleichzeitig verbietet Scope Lock (ADP AP1.0) neue OM-Tabellen **bis ADP** — dieses ADP ist die Freigabe für AP1.4.
|
||||
|
||||
---
|
||||
|
||||
## Betroffene Regel
|
||||
|
||||
- `Kairo_Canonical_Operating_Model_v0.2.md` §6–7
|
||||
- `Kairo_System_Target_State_v0.1.md` §12–13
|
||||
- `ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md` — Ausnahme AP1.4
|
||||
- AD-TA-08 (Milestone-Brücke → RoadmapItem Konsolidierung)
|
||||
|
||||
---
|
||||
|
||||
## Optionen
|
||||
|
||||
| Option | Kurzbeschreibung | Pro | Contra |
|
||||
|--------|------------------|-----|--------|
|
||||
| **A** | `milestones` erweitern (DoD JSON, deps) | Weniger Migration | Doppelmodell bleibt; widerspricht Target State |
|
||||
| **B** | **Roadmap + RoadmapItem** neu; `milestones` migrieren | Kanonisches Modell; Gates; Dependencies | Migration; größerer Scope |
|
||||
| **C** | Nur UI/DoD auf `milestones` | Schnell | Kein Roadmap; Plan/Ist unmöglich |
|
||||
|
||||
## Empfehlung
|
||||
|
||||
**Option B** — schmale erste Migration:
|
||||
|
||||
```text
|
||||
roadmaps (1 pro Initiative initial)
|
||||
roadmap_items
|
||||
roadmap_item_dependencies
|
||||
roadmap_item_criteria (DoD-Zeilen, optional Phase 1 nur JSONB)
|
||||
```
|
||||
|
||||
`item_type` initial: `milestone`, `review_gate`, `maturity_stage`.
|
||||
|
||||
Bestehende `milestones` → `roadmap_items` mit `legacy_milestone_id` oder One-shot-Migration.
|
||||
|
||||
---
|
||||
|
||||
## Fachmodell (Minimal AP1.4)
|
||||
|
||||
### RoadmapItem
|
||||
|
||||
| Feld | Typ | Pflicht |
|
||||
|------|-----|---------|
|
||||
| id | uuid | ✓ |
|
||||
| tenant_id, initiative_id, roadmap_id | uuid | ✓ |
|
||||
| item_type | enum | ✓ |
|
||||
| title | text | ✓ |
|
||||
| goal_description | text | |
|
||||
| definition_of_done | jsonb / criteria table | ◐ Phase 1: jsonb Liste |
|
||||
| target_date | date | |
|
||||
| status | planned/active/at_risk/reached/moved/discarded | ✓ |
|
||||
| sequencing_mode | sequential / parallel / optional | ✓ default sequential |
|
||||
| sort_order | int | |
|
||||
|
||||
### Dependencies
|
||||
|
||||
| Feld | Typ |
|
||||
|------|-----|
|
||||
| from_item_id | uuid |
|
||||
| to_item_id | uuid |
|
||||
| dependency_type | requires / blocks / related |
|
||||
|
||||
### Verknüpfung Ist → Plan
|
||||
|
||||
| Relation | Beschreibung |
|
||||
|----------|--------------|
|
||||
| `backlog_items.roadmap_item_id` | optional FK |
|
||||
| `actions.roadmap_item_id` | optional FK |
|
||||
|
||||
### Gate-Verify
|
||||
|
||||
- Übergang `→ reached`: mindestens eine **Evidence** `accepted` ODER **Review** `completed` ODER explizite **Decision** `decided` mit Typ `gate_override`
|
||||
- Übergang `→ moved/discarded`: **Decision** Pflicht
|
||||
|
||||
---
|
||||
|
||||
## API (Minimal)
|
||||
|
||||
```text
|
||||
GET /api/initiatives/:id/roadmap
|
||||
GET /api/initiatives/:id/roadmap/items
|
||||
POST /api/initiatives/:id/roadmap/items
|
||||
PATCH /api/roadmap-items/:id
|
||||
POST /api/roadmap-items/:id/verify-reached
|
||||
GET /api/roadmap-items/:id/dependencies
|
||||
POST /api/roadmap-items/:id/dependencies
|
||||
```
|
||||
|
||||
Steering Snapshot: `upcoming_milestones` liest aus `roadmap_items` statt `milestones`.
|
||||
|
||||
---
|
||||
|
||||
## UI (Minimal)
|
||||
|
||||
- Unterseite **Plan** (`/initiatives/:id/plan`) — Liste + Gate-Detail-Route
|
||||
- Initiative-**Übersicht**: Horizont aus RoadmapItems (read)
|
||||
- Gate-Detail: DoD, Dependencies, Verify-Aktionen
|
||||
|
||||
**Nicht AP1.4:** Gantt, Drag-Drop-Graph (Tabelle reicht).
|
||||
|
||||
---
|
||||
|
||||
## Migration
|
||||
|
||||
1. Migration `010_roadmap_items.sql`
|
||||
2. Datenmigration `milestones` → `roadmap_items` (type=milestone)
|
||||
3. Deprecate `milestones` Router (410 + Link) oder View-Compat one release
|
||||
4. Drop `milestones` in `011` nach Compat-Periode
|
||||
|
||||
---
|
||||
|
||||
## Risiko
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Scope Creep | AP1.4 nur Minimal; kein Structure Builder |
|
||||
| Breaking API | Compat-Layer one release |
|
||||
| UI vor Schema | AP1.2c Plan-Shell vor AP1.4 Daten |
|
||||
|
||||
---
|
||||
|
||||
## Rückbaubarkeit
|
||||
|
||||
- `roadmap_items` isoliert; Rollback Migration 010
|
||||
- Milestone-Compat-View aus roadmap_items möglich
|
||||
|
||||
---
|
||||
|
||||
## Auswirkung auf Sprint 0 / Scope Lock
|
||||
|
||||
**Erweitert Scope Lock** explizit für AP1.4. Keine anderen Tabellen ohne neues ADP.
|
||||
|
||||
---
|
||||
|
||||
## Freigabe-Checkliste PO
|
||||
|
||||
- [ ] Gate-Verify-Regel akzeptiert
|
||||
- [ ] item_type initial: milestone, review_gate, maturity_stage
|
||||
- [ ] milestones-Tabelle darf deprecated werden
|
||||
- [ ] AP1.4 nach AP1.2c
|
||||
- [ ] **Methodenneutralität:** Schema/UI nicht nur für sequenzielle Software-Gates
|
||||
|
||||
---
|
||||
|
||||
## Methodische Neutralität (AP1.4)
|
||||
|
||||
AP1.4 liefert das **generische Plan-Gerüst**. Konkrete Methoden (z. B. `product_milestone_driven`, Reifegrad-Parallelpfade, Content-Kapitel) **registrieren sich** über:
|
||||
|
||||
- `item_type` + `sequencing_mode` auf RoadmapItem
|
||||
- `method_key` auf `steering_context` (bereits vorhanden)
|
||||
- später: Method-spezifische Verify-Policies, Structure Builder, Next-Action-Strategien
|
||||
|
||||
**Nicht:** fest codierte „Meilenstein = lineare Software-Roadmap“-UI oder Dependency-Modell nur für WBS.
|
||||
|
||||
---
|
||||
|
||||
*Implementierung: `Kairo_Corrected_MVP_Roadmap_v0.2.md` AP1.4*
|
||||
@@ -0,0 +1,94 @@
|
||||
# CLAUDE.md Addendum
|
||||
## Kairo Product Direction Reset v0.1
|
||||
|
||||
Dieses Addendum ist in `CLAUDE.md` aufzunehmen oder dort zu referenzieren.
|
||||
|
||||
---
|
||||
|
||||
## Current Product Direction
|
||||
|
||||
Kairo is not a task list.
|
||||
|
||||
Kairo is the operational Program Director of the Jinkendo product family.
|
||||
|
||||
The central question is:
|
||||
|
||||
> Which next step moves an initiative forward most effectively now?
|
||||
|
||||
---
|
||||
|
||||
## Do not reduce Kairo to
|
||||
|
||||
```text
|
||||
Initiative
|
||||
→ Action
|
||||
```
|
||||
|
||||
This is only the first technical slice.
|
||||
|
||||
The canonical operating model includes:
|
||||
|
||||
- Initiative
|
||||
- Project optional
|
||||
- Milestone
|
||||
- BacklogItem
|
||||
- Action
|
||||
- Assignment to Actor
|
||||
- Blocker
|
||||
- Decision
|
||||
- Evidence
|
||||
- Review
|
||||
- RecurringElement
|
||||
- AttentionItem
|
||||
- NextActionCandidate
|
||||
|
||||
---
|
||||
|
||||
## Current implementation state
|
||||
|
||||
Valid but incomplete:
|
||||
|
||||
- Tenant
|
||||
- Actor
|
||||
- TenantContext
|
||||
- Capabilities
|
||||
- Entitlements
|
||||
- Initiative
|
||||
- Action
|
||||
- Assignment
|
||||
- Workspace UX
|
||||
|
||||
Missing MVP-critical concepts:
|
||||
|
||||
- Data Layer
|
||||
- Actor Directory
|
||||
- Tenant Invariants
|
||||
- Backlog
|
||||
- Blocker
|
||||
- Milestone
|
||||
- Evidence
|
||||
- Review
|
||||
- Recurrence
|
||||
- Attention / Next Action
|
||||
|
||||
---
|
||||
|
||||
## Implementation rule
|
||||
|
||||
Do not continue foundation work unless it directly supports MVP usability or prevents a documented refactoring trap.
|
||||
|
||||
Do not continue prompt/AI/workflow/MCP work until the operating model MVP is restored.
|
||||
|
||||
---
|
||||
|
||||
## Gate for new tasks
|
||||
|
||||
Every new task must answer:
|
||||
|
||||
1. Does it support the operational Program Director vision?
|
||||
2. Does it improve real initiative steering?
|
||||
3. Does it prevent a concrete refactoring trap?
|
||||
4. Is it a small verifiable slice?
|
||||
5. Are non-goals explicit?
|
||||
|
||||
If not, do not implement.
|
||||
@@ -0,0 +1,166 @@
|
||||
# KAIRO-ARCH-01 – Abschlussbericht
|
||||
|
||||
**Status:** abgeschlossen
|
||||
**Stand:** 2026-07-05
|
||||
**Auftrag:** `docs/architecture/Kairo_Target_Architecture_Assignment_Method_Driven_Adaptive_Steering_Core_v0.2.md`
|
||||
**Ergebnis:** Zielarchitektur v0.1 (Nordstern, keine Implementierung)
|
||||
|
||||
---
|
||||
|
||||
## 1. Erstellte Dateien
|
||||
|
||||
| Datei | Zweck |
|
||||
|-------|-------|
|
||||
| `docs/architecture/Kairo_Target_Architecture_Method_Driven_Adaptive_Steering_Core_v0.1.md` | Technische Zielarchitektur (20 Kapitel) |
|
||||
| `docs/architecture/KAIRO-ARCH-01_Completion_Report_v0.1.md` | Dieser Abschlussbericht |
|
||||
|
||||
**Gelesene Grundlagen (alle vorhanden):**
|
||||
|
||||
- `docs/architecture/Kairo_Core_Model_Decision_v0.2.md`
|
||||
- `docs/architecture/Kairo_Method_Design_Principles_v0.1.md`
|
||||
- `docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md`
|
||||
- `docs/product/Kairo_Canonical_Operating_Model_v0.1.md`
|
||||
- `docs/product/Kairo_Corrected_MVP_Roadmap_v0.1.md`
|
||||
- `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||
- `docs/sprints/Sprint0_AP0_7_Completion_Report_v0.2.md`
|
||||
|
||||
**Fehlende Dokumente:** keine — alle im Auftrag genannten Grundlagen waren im Repo vorhanden.
|
||||
|
||||
---
|
||||
|
||||
## 2. Wichtigste Architekturentscheidungen
|
||||
|
||||
| # | Entscheidung |
|
||||
|---|--------------|
|
||||
| 1 | **Kairo ist methodengeführter Steuerungskern**, keine freie Workflow Engine |
|
||||
| 2 | **Drei Ebenen:** Steering Method → Steering Workflow (Lifecycle/Hooks) → Workflow Runtime (später) |
|
||||
| 3 | **Method Registry** als zentraler Erweiterungspunkt — analog zu bestehendem Capability/Feature-Registry-Muster |
|
||||
| 4 | **Hook Slugs** als stabile Einhängepunkte zwischen Core, Methoden und späteren Workflow-Fragmenten |
|
||||
| 5 | **Standard Lifecycle** (12 Schritte) als gemeinsame Basis; Methoden aktivieren/spezialisieren |
|
||||
| 6 | **Gemeinsame Kernstrukturen** — RoadmapItem als generisches Strukturelement (Milestone, Feature, Kapitel, Reifegradstufe) |
|
||||
| 7 | **Attention/NextAction** als erklärbare Read Models im Data Layer; Signal Rule Providers methodenregistrierbar |
|
||||
| 8 | **Kairo bleibt Steering Authority** — Agenten sind Actors/Provider, nicht eigenständige Steuerungsinstanzen |
|
||||
| 9 | **Prompt/Workflow-Runtime bleibt eingefroren** bis Operating-Model-MVP (AP0.8–0.10) trägt |
|
||||
| 10 | **Neue Schicht `backend/steering/`** — schrittweise nach AP0.8, ohne Foundation-Umbau |
|
||||
|
||||
---
|
||||
|
||||
## 3. Kritische Bewertung der fachlichen Annahmen
|
||||
|
||||
### 3.1 Bestätigt
|
||||
|
||||
Die fachliche Präferenz **„methodengeführter Steuerungskern statt freier Workflow-Baukasten“** ist aus Sicht der Codebase **tragfähig**:
|
||||
|
||||
- Registry-Muster (Capabilities, Features, Prompts) ist etabliert und erprobt
|
||||
- Tenant/Actor/Capability-Foundation ist produktionsreif (AP0.7)
|
||||
- Data Layer als Read-Schicht passt zur Attention-/Signal-Architektur
|
||||
- Product Reset und Principle Gate verbieten vorzeitige Workflow/KI-Ausbauten — konsistent mit Zielarchitektur
|
||||
|
||||
### 3.2 Präzisiert
|
||||
|
||||
| Annahme | Bewertung |
|
||||
|---------|-----------|
|
||||
| Standard Lifecycle (12 Schritte) | Tragfähig als **generische Steuerungslogik**; UI muss fachliche Labels zeigen, nicht technische States |
|
||||
| Hook Registry | Sinnvoll; Versionierung über `since_version` + Deprecation, nicht über Slug-Änderung |
|
||||
| Structure Builder | Korrekt als methodenspezifische Erweiterung; **muss Domain Services nutzen**, nicht Router/SQL |
|
||||
| Milestone als eigenes Objekt (AP0.8) | MVP-pragmatisch; Zielarchitektur empfiehlt **Konsolidierung zu RoadmapItem** in Phase C |
|
||||
| Methoden sofort im MVP | **Nein** — erst Operating-Model-Entitäten, dann SteeringContext + erste Built-in Method |
|
||||
|
||||
### 3.3 Abweichung von Method Design Principles
|
||||
|
||||
Keine inhaltliche Abweichung. Technische Präzisierung: AP0.8 Attention startet als **globaler Rule Provider** in `data_layer/attention.py` und wird später in die Signal Engine refactored — bewusste Brücke, kein Widerspruch.
|
||||
|
||||
---
|
||||
|
||||
## 4. Empfohlene Zielarchitektur
|
||||
|
||||
**Kurzfassung:**
|
||||
|
||||
```text
|
||||
Foundation (bestehend)
|
||||
+ Domain Operating Model (AP0.8 → AP0.9)
|
||||
+ Steering Core (Method/Hooks/Lifecycle/Signals)
|
||||
+ Method Packages (Built-in)
|
||||
+ später: Workflow Fragments + Runtime + Agent/LLM Nodes
|
||||
```
|
||||
|
||||
**Kernmodell:**
|
||||
|
||||
```text
|
||||
Initiative
|
||||
→ SteeringContext (method_key, version, lifecycle_state)
|
||||
→ Method Registry → Structure Builders + Strategies + Signal Rules
|
||||
→ gemeinsame Strukturen (Roadmap, Backlog, Action, Blocker, Evidence, Review, …)
|
||||
→ Attention / NextAction (Read Models)
|
||||
→ Assignment → Waiting → Result Intake → Review → Adaptation
|
||||
```
|
||||
|
||||
Das vollständige Dokument: `Kairo_Target_Architecture_Method_Driven_Adaptive_Steering_Core_v0.1.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Was gegenüber der bisherigen Architektur geändert werden sollte
|
||||
|
||||
| Bereich | Bisher | Soll (Ziel) |
|
||||
|---------|--------|-------------|
|
||||
| Produktkern | Initiative → Action (flach) | Methodengeführter SteeringContext + Operating Model |
|
||||
| Steuerungslogik | verstreut in Services/Data Layer | `backend/steering/` mit Registry, Lifecycle, Hooks, Signals |
|
||||
| Blocker | nur Action-Status | eigenes Objekt (AP0.8) |
|
||||
| Struktur | keine Roadmap/Backlog/Milestone | Operating Model + RoadmapItem-Generik |
|
||||
| Attention | fehlt | Data Layer + später Signal Engine |
|
||||
| Methoden | nicht modelliert | Method Registry + Built-in Methods |
|
||||
| Workflow/Prompt | technisch vorhanden, eingefroren | später hook-gebundene Fragmente, nicht Produktkern |
|
||||
| Milestone (AP0.8) | — | eigene Tabelle als Brücke → RoadmapItem konsolidieren |
|
||||
|
||||
**Was bleibt unverändert:**
|
||||
|
||||
- TenantContext, Actor-Modell, Capabilities, Audit-Grundlage
|
||||
- Router dünn / Services Write / Data Layer Read
|
||||
- Frontend Widget/View Registry
|
||||
- Nummerierte Migrationen, Registry-first Capabilities
|
||||
|
||||
---
|
||||
|
||||
## 6. Risiken
|
||||
|
||||
| Risiko | Schwere | Hinweis |
|
||||
|--------|---------|---------|
|
||||
| Vorzeitige Workflow-Runtime | hoch | Operating Model MVP zuerst |
|
||||
| Over-Engineering Steering-Schicht | mittel | Skeleton erst nach AP0.8 |
|
||||
| Doppelmodell Milestone/RoadmapItem | mittel | ADP vor Konsolidierung |
|
||||
| Lifecycle zu abstrakt für Nutzer | mittel | Fachliche UI-Labels |
|
||||
| Methoden-Explosion | mittel | Built-in only, Review-Gate |
|
||||
| Agenten ohne klare Authority-Grenze | hoch | Canonical Model §11 durchsetzen |
|
||||
|
||||
---
|
||||
|
||||
## 7. Offene Entscheidungen
|
||||
|
||||
1. **SteeringContext-Einführung** — mit AP0.9 oder als AP1.0?
|
||||
2. **Milestone → RoadmapItem Migration** — Zeitpunkt und Strategie
|
||||
3. **Generisches Assignment** — über Actions hinaus, wann?
|
||||
4. **Scheduler für Waiting/Reminder** — Infrastruktur-Wahl
|
||||
5. **Audit `actor_id`-Spalte** — Nachzug vor Agent-Integration
|
||||
6. **Erste Built-in Method** — `generic_operating` vs. direkt `product_milestone_driven`?
|
||||
|
||||
Diese Punkte sollten als Architecture Decision Proposals vor der Steering-Core-Implementierung geklärt werden.
|
||||
|
||||
---
|
||||
|
||||
## 8. Empfehlung für den nächsten Schritt
|
||||
|
||||
**Nicht** sofort `backend/steering/` implementieren.
|
||||
|
||||
**Empfohlene Reihenfolge:**
|
||||
|
||||
1. **AP0.8 freigeben und umsetzen** (`Sprint0_AP0_8_Assignment_v0.1.md`) — Attention, Blocker, BacklogItem, Milestone
|
||||
2. **AP0.9** — Evidence, Decision, Review, RecurringElement
|
||||
3. **AP0.10** — Validierung mit realem Testvorhaben
|
||||
4. **ADP:** SteeringContext-Einführung + Milestone/RoadmapItem-Strategie
|
||||
5. **Danach:** `backend/steering/` Skeleton + erste Built-in Method
|
||||
|
||||
Die Zielarchitektur dient als **Nordstern** für AP0.8–AP0.10 und verhindert Rückfall auf reines Initiative→Action sowie vorzeitige Workflow-Engine-Arbeit.
|
||||
|
||||
---
|
||||
|
||||
*KAIRO-ARCH-01 abgeschlossen — reine Architekturarbeit, keine Code-Änderungen.*
|
||||
@@ -0,0 +1,642 @@
|
||||
# Kairo – Core Model Decision
|
||||
## v0.2 – Adaptive Steering Core mit methodengeführten Steuerungsworkflows
|
||||
|
||||
**Status:** fachliche Architekturentscheidung
|
||||
**Stand:** 2026-07-05
|
||||
**Ersetzt / präzisiert:** `Kairo_Universal_Steering_Engine_Decision_v0.1.md` und `Kairo_Steering_Engine_Roadmap_Discussion_v0.1.md` in Bezug auf den fachlichen Produktkern
|
||||
**Zweck:** Präzisierung des Kairo-Kerns vor der technischen Zielarchitektur
|
||||
|
||||
---
|
||||
|
||||
## 1. Anlass der Präzisierung
|
||||
|
||||
In der bisherigen Diskussion wurde Kairo teilweise als universelle Steuerungs- und Workflow-Engine beschrieben.
|
||||
|
||||
Diese Beschreibung war in der Tendenz richtig, aber noch missverständlich.
|
||||
|
||||
Der Begriff „Workflow Engine“ kann technisch verstanden werden als:
|
||||
|
||||
```text
|
||||
Trigger → Nodes → Transitions → Runs → Step Results
|
||||
```
|
||||
|
||||
Das wäre für Kairo als Produktkern zu eng und zugleich zu technisch.
|
||||
|
||||
Der Nutzer meint mit „Workflow“ jedoch nicht primär eine technische Automatisierungsruntime, sondern den **fachlichen Steuerungsablauf**, nach dem ein steuerbarer Kontext aufgebaut, geführt, überprüft und weiterentwickelt wird.
|
||||
|
||||
Beispielhafter Steuerungsablauf:
|
||||
|
||||
```text
|
||||
Ziel erfassen
|
||||
→ Name / Scope definieren
|
||||
→ Basismethode wählen
|
||||
→ Steuerungsstruktur gemäß Methode anlegen
|
||||
→ Roadmap / Backlog / WBS / Reifegradpfad / Kapitelstruktur erzeugen
|
||||
→ Next Best Action ableiten
|
||||
→ Actor zuweisen
|
||||
→ auf Ergebnis warten
|
||||
→ erinnern / eskalieren / prüfen
|
||||
→ Ergebnis zurückführen
|
||||
→ nächste Steuerungsentscheidung treffen
|
||||
```
|
||||
|
||||
Dieser Ablauf ist tatsächlich fachlicher Kern von Kairo.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zentrale Entscheidung
|
||||
|
||||
Kairo ist im Kern **keine freie Workflow-Plattform**.
|
||||
|
||||
Kairo ist im Kern eine:
|
||||
|
||||
```text
|
||||
Adaptive Development Steering Platform
|
||||
```
|
||||
|
||||
mit einem:
|
||||
|
||||
```text
|
||||
Method-driven Adaptive Steering Core
|
||||
```
|
||||
|
||||
Deutsch:
|
||||
|
||||
```text
|
||||
methodengeführter adaptiver Steuerungskern
|
||||
```
|
||||
|
||||
Dieser Kern führt steuerbare Kontexte über methodenspezifische Steuerungsabläufe.
|
||||
|
||||
---
|
||||
|
||||
## 3. Was ist der Adaptive Steering Core?
|
||||
|
||||
Der Adaptive Steering Core beantwortet dauerhaft:
|
||||
|
||||
```text
|
||||
Was wird gesteuert?
|
||||
Was ist das Ziel?
|
||||
Welche Methode gilt?
|
||||
Welche Steuerungsstruktur braucht diese Methode?
|
||||
Welche Roadmap / WBS / Backlog / Reifegradstruktur / Kapitelstruktur ist anzulegen?
|
||||
Was ist der aktuelle Zustand?
|
||||
Was fehlt?
|
||||
Was blockiert?
|
||||
Was braucht Aufmerksamkeit?
|
||||
Was ist die nächste wirksame Aktion?
|
||||
Wer oder welcher Agent soll handeln?
|
||||
Worauf wartet Kairo?
|
||||
Wann muss erinnert, eskaliert, geprüft oder neu geplant werden?
|
||||
Welche Ergebnisse, Nachweise, Entscheidungen oder Reviews müssen zurückgeführt werden?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Abgrenzung zur technischen Workflow Runtime
|
||||
|
||||
Es gibt drei Ebenen:
|
||||
|
||||
```text
|
||||
1. Steering Method
|
||||
= fachliche Logik, wie ein Kontext geführt wird
|
||||
|
||||
2. Steering Workflow
|
||||
= methodenspezifischer Steuerungsablauf über definierte Lifecycle- und Hook-Schritte
|
||||
|
||||
3. Workflow Runtime
|
||||
= technische Maschine, die später Schritte, Zustände, Trigger, Wait States, Agentenaufrufe und Ergebnisse ausführt
|
||||
```
|
||||
|
||||
Die technische Workflow Runtime ist wichtig, aber nicht identisch mit dem Produktkern.
|
||||
|
||||
Der Produktkern ist der methodengeführte Steuerungsablauf.
|
||||
|
||||
---
|
||||
|
||||
## 5. Zielmodell
|
||||
|
||||
```text
|
||||
Steerable Object
|
||||
→ Steering Context
|
||||
→ Steering Method
|
||||
→ Standard Lifecycle / Method Lifecycle
|
||||
→ Hook Slugs
|
||||
→ Structure Builder
|
||||
→ Signal Rules
|
||||
→ NextAction Strategy
|
||||
→ Assignment Strategy
|
||||
→ Waiting / Reminder / Escalation Strategy
|
||||
→ Result Intake
|
||||
→ Review / Adaptation
|
||||
→ optionale Workflow-Fragmente
|
||||
→ optionale Human / Agent / LLM / Tool Steps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Minimaler Standard Lifecycle
|
||||
|
||||
Kairo benötigt einen minimalen Standard Lifecycle, der von Methoden genutzt, erweitert oder spezialisiert werden kann.
|
||||
|
||||
Dieser Standard Lifecycle ist nicht als starrer Projektprozess zu verstehen, sondern als generische Steuerungslogik.
|
||||
|
||||
```text
|
||||
intake
|
||||
method_selection
|
||||
structure_setup
|
||||
planning
|
||||
action_selection
|
||||
assignment
|
||||
waiting
|
||||
result_intake
|
||||
validation
|
||||
review
|
||||
adaptation
|
||||
closure
|
||||
```
|
||||
|
||||
### 6.1 Intake
|
||||
|
||||
Ziel, Name, Kontext und initialer Scope werden erfasst.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_goal_captured
|
||||
on_scope_named
|
||||
on_initial_context_created
|
||||
```
|
||||
|
||||
### 6.2 Method Selection
|
||||
|
||||
Eine Basismethode wird gewählt oder vorgeschlagen.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_method_selection_required
|
||||
on_method_selected
|
||||
on_method_profile_required
|
||||
```
|
||||
|
||||
### 6.3 Structure Setup
|
||||
|
||||
Gemäß Methode wird die Steuerungsstruktur angelegt.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
Backlog
|
||||
WBS
|
||||
Roadmap / Meilensteinplan
|
||||
Reifegradpfad
|
||||
Kapitelstruktur
|
||||
Feature Landscape
|
||||
WorkCycles
|
||||
Review Gates
|
||||
```
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_structure_required
|
||||
on_roadmap_required
|
||||
on_backlog_required
|
||||
on_wbs_required
|
||||
on_maturity_path_required
|
||||
on_content_structure_required
|
||||
on_cycle_structure_required
|
||||
```
|
||||
|
||||
### 6.4 Planning
|
||||
|
||||
Die nächste steuerbare Planungsebene wird konkretisiert.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_plan_required
|
||||
on_dependency_analysis_required
|
||||
on_dod_definition_required
|
||||
on_evidence_policy_required
|
||||
```
|
||||
|
||||
### 6.5 Action Selection
|
||||
|
||||
Kairo leitet Next Best Actions oder NextActionCandidates ab.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_next_action_requested
|
||||
on_attention_scan_requested
|
||||
```
|
||||
|
||||
### 6.6 Assignment
|
||||
|
||||
Ein Actor wird zugewiesen.
|
||||
|
||||
Actors können sein:
|
||||
|
||||
```text
|
||||
human
|
||||
agent
|
||||
working_group
|
||||
external_system
|
||||
```
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_assignment_required
|
||||
on_actor_selection_required
|
||||
```
|
||||
|
||||
### 6.7 Waiting
|
||||
|
||||
Kairo wartet auf Ergebnis, Termin, Rückmeldung, externes Ereignis oder Statusänderung.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_wait_started
|
||||
on_due_date_reached
|
||||
on_result_overdue
|
||||
on_reminder_required
|
||||
on_escalation_required
|
||||
```
|
||||
|
||||
### 6.8 Result Intake
|
||||
|
||||
Ein Ergebnis wird zurückgeführt.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_result_received
|
||||
on_actor_update_received
|
||||
on_agent_result_received
|
||||
```
|
||||
|
||||
### 6.9 Validation
|
||||
|
||||
Ergebnis, DoD, Evidence oder Qualität werden geprüft.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_dod_check_required
|
||||
on_evidence_required
|
||||
on_quality_gate_required
|
||||
```
|
||||
|
||||
### 6.10 Review
|
||||
|
||||
Ein Review, Assessment oder eine Reflexion wird ausgelöst.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_review_due
|
||||
on_reassessment_required
|
||||
on_reflection_required
|
||||
```
|
||||
|
||||
### 6.11 Adaptation
|
||||
|
||||
Kairo entscheidet über Nachsteuerung.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_replan_required
|
||||
on_structure_update_required
|
||||
on_method_adjustment_required
|
||||
```
|
||||
|
||||
### 6.12 Closure
|
||||
|
||||
Ein Kontext, RoadmapItem, WorkCycle, Review oder Action wird abgeschlossen.
|
||||
|
||||
Typische Hooks:
|
||||
|
||||
```text
|
||||
on_closure_requested
|
||||
on_close_allowed
|
||||
on_archive_required
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Methodengeführte Steuerungsworkflows
|
||||
|
||||
Jede Methode definiert, wie der Standard Lifecycle genutzt wird.
|
||||
|
||||
Eine Methode kann:
|
||||
|
||||
```text
|
||||
- Lifecycle-Schritte aktivieren/deaktivieren
|
||||
- eigene Hook Slugs ergänzen
|
||||
- bestimmte Steuerungsstrukturen verlangen
|
||||
- bestimmte Structure Builder bereitstellen
|
||||
- NextAction-Strategien definieren
|
||||
- Review-/Evidence-Policies definieren
|
||||
- Assignment-/Waiting-Strategien definieren
|
||||
- erlaubte Workflow-Fragmente an Hooks registrieren
|
||||
```
|
||||
|
||||
Beispiel:
|
||||
|
||||
```text
|
||||
Methode: maturity_progression
|
||||
|
||||
nutzt:
|
||||
- intake
|
||||
- method_selection
|
||||
- structure_setup
|
||||
- action_selection
|
||||
- assignment
|
||||
- waiting
|
||||
- result_intake
|
||||
- validation
|
||||
- review
|
||||
- adaptation
|
||||
|
||||
Structure Builder:
|
||||
- Roadmap Lane: Reifegradstufen
|
||||
- Roadmap Lane: Fähigkeiten
|
||||
- Roadmap Lane: Praxis
|
||||
- Roadmap Lane: Evidence
|
||||
- Roadmap Lane: Reflexion
|
||||
|
||||
NextAction Strategy:
|
||||
- aktuellen Reifegrad bewerten
|
||||
- Zielreifegrad definieren
|
||||
- Gap identifizieren
|
||||
- Praxisaufgabe auswählen
|
||||
- Evidence sammeln
|
||||
- Review durchführen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Keine beliebige freie Workflow-Konfiguration als Startpunkt
|
||||
|
||||
Kairo soll langfristig konfigurierbar sein, aber nicht durch beliebige Nutzer-Workflows beliebig werden.
|
||||
|
||||
Entscheidung:
|
||||
|
||||
```text
|
||||
Initial keine frei modellierbaren Methoden durch Nutzer.
|
||||
```
|
||||
|
||||
Stattdessen:
|
||||
|
||||
```text
|
||||
- Built-in Methods mit method_key / slug
|
||||
- definierte Hook Slugs
|
||||
- definierte Structure Builder
|
||||
- definierte Rule Provider
|
||||
- definierte Signal Generatoren
|
||||
- definierte NextAction Strategies
|
||||
- definierte erlaubte Workflow-Fragmente
|
||||
- später Method Profiles und konfigurierbare Bindings
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Rollen der technischen Komponenten
|
||||
|
||||
### 9.1 Method Registry
|
||||
|
||||
Zentrales Register, in dem Methoden angemeldet werden.
|
||||
|
||||
Ähnlich einem Widget-System.
|
||||
|
||||
Eine Methode muss sich registrieren mit:
|
||||
|
||||
```text
|
||||
method_key
|
||||
version
|
||||
supported_domains
|
||||
supported_scope_types
|
||||
default_lifecycle
|
||||
required_structures
|
||||
allowed_structures
|
||||
hook_slugs
|
||||
structure_builders
|
||||
signal_rules
|
||||
next_action_strategy
|
||||
assignment_strategy
|
||||
waiting_strategy
|
||||
review_strategy
|
||||
evidence_policy
|
||||
allowed_workflow_fragments
|
||||
allowed_node_types
|
||||
```
|
||||
|
||||
### 9.2 Hook Registry
|
||||
|
||||
Register bekannter Hook Slugs.
|
||||
|
||||
Sie dient zur Stabilisierung der Einhängepunkte.
|
||||
|
||||
### 9.3 Structure Builder
|
||||
|
||||
Ein Structure Builder legt methodenspezifische Steuerungsstrukturen an.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
Roadmap Builder
|
||||
Backlog Builder
|
||||
WBS Builder
|
||||
Maturity Path Builder
|
||||
Chapter Structure Builder
|
||||
Cycle Builder
|
||||
Review Gate Builder
|
||||
```
|
||||
|
||||
### 9.4 Signal Engine
|
||||
|
||||
Erzeugt Attention, NextActionCandidate und später weitere Signals.
|
||||
|
||||
### 9.5 Strategy Interfaces
|
||||
|
||||
Methoden liefern oder referenzieren Strategien:
|
||||
|
||||
```text
|
||||
NextActionStrategy
|
||||
AssignmentStrategy
|
||||
WaitingStrategy
|
||||
ReminderStrategy
|
||||
EscalationStrategy
|
||||
ReviewStrategy
|
||||
EvidencePolicy
|
||||
ClosurePolicy
|
||||
```
|
||||
|
||||
### 9.6 Workflow Fragment Layer
|
||||
|
||||
An Hooks können später kleinere Workflow-Fragmente eingehängt werden.
|
||||
|
||||
Diese sind nicht beliebig global, sondern methoden- und hookgebunden.
|
||||
|
||||
---
|
||||
|
||||
## 10. Beispiele für Methoden
|
||||
|
||||
### 10.1 Produktentwicklung / Softwareentwicklung
|
||||
|
||||
```text
|
||||
method_key: product_milestone_driven
|
||||
domain: product_development
|
||||
default_lifecycle: standard_development_lifecycle
|
||||
|
||||
Structures:
|
||||
- Roadmap
|
||||
- Feature Landscape
|
||||
- Architecture Lane
|
||||
- Release Lane
|
||||
- Backlog
|
||||
- Actions
|
||||
- Blockers
|
||||
|
||||
NextAction Strategy:
|
||||
- wenn Roadmap fehlt → Roadmap anlegen
|
||||
- wenn Feature ohne Backlog → BacklogItem erzeugen
|
||||
- wenn accepted BacklogItem ohne Action → Action erstellen
|
||||
- wenn Action blockiert → Blocker klären
|
||||
- wenn Release at_risk → Review / Replan
|
||||
```
|
||||
|
||||
### 10.2 Buchentwicklung
|
||||
|
||||
```text
|
||||
method_key: content_chapter_based
|
||||
domain: content_development
|
||||
|
||||
Structures:
|
||||
- Roadmap Lane: Buchstruktur
|
||||
- Roadmap Lane: Kapitel
|
||||
- Roadmap Lane: Recherche
|
||||
- Roadmap Lane: Review
|
||||
- Backlog für Themen / Lücken / Recherchefragen
|
||||
- Actions für Schreib- und Reviewaufgaben
|
||||
|
||||
NextAction Strategy:
|
||||
- Konzept klären
|
||||
- Kapitelstruktur anlegen
|
||||
- nächstes Kapitel auswählen
|
||||
- Recherchebedarf erzeugen
|
||||
- Draft schreiben
|
||||
- Review durchführen
|
||||
```
|
||||
|
||||
### 10.3 Persönliche Reifegradentwicklung
|
||||
|
||||
```text
|
||||
method_key: maturity_progression
|
||||
domain: maturity_development
|
||||
|
||||
Structures:
|
||||
- Roadmap Lane: Reifegradstufen
|
||||
- Roadmap Lane: Fähigkeiten
|
||||
- Roadmap Lane: Praxis
|
||||
- Roadmap Lane: Evidence
|
||||
- Roadmap Lane: Reflexion
|
||||
|
||||
NextAction Strategy:
|
||||
- aktuellen Reifegrad bewerten
|
||||
- Zielreifegrad definieren
|
||||
- Gap identifizieren
|
||||
- Übung/Praxis auswählen
|
||||
- Evidence sammeln
|
||||
- Review/Reassessment durchführen
|
||||
```
|
||||
|
||||
### 10.4 Routine Control
|
||||
|
||||
```text
|
||||
method_key: recurring_control
|
||||
domain: routine_operations
|
||||
|
||||
Structures:
|
||||
- Routine Definition
|
||||
- Run Schedule
|
||||
- Checklist
|
||||
- Exceptions
|
||||
- Review
|
||||
|
||||
NextAction Strategy:
|
||||
- nächster Run fällig
|
||||
- Run verpasst
|
||||
- Exception klären
|
||||
- Routine anpassen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Konsequenz für die Zielarchitektur
|
||||
|
||||
Die technische Zielarchitektur soll nicht als freie Workflow Engine beginnen.
|
||||
|
||||
Sie soll den folgenden Kern entwerfen:
|
||||
|
||||
```text
|
||||
Target Architecture for Method-driven Adaptive Steering Core
|
||||
```
|
||||
|
||||
Darin enthalten:
|
||||
|
||||
```text
|
||||
- Standard Lifecycle
|
||||
- Method Registry
|
||||
- Hook Registry
|
||||
- Structure Builder Layer
|
||||
- Strategy Interfaces
|
||||
- Signal Engine
|
||||
- NextAction Engine
|
||||
- Assignment / Waiting / Reminder / Escalation Layer
|
||||
- Result Intake
|
||||
- Review / Adaptation Layer
|
||||
- Workflow Fragment Model
|
||||
- Agent / LLM / Tool Provider Integration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Kernaussage
|
||||
|
||||
Kairo ist nicht einfach:
|
||||
|
||||
```text
|
||||
Roadmap Tool
|
||||
Projektmanagement Tool
|
||||
Workflow Engine
|
||||
Agentenplattform
|
||||
```
|
||||
|
||||
Kairo ist:
|
||||
|
||||
```text
|
||||
eine adaptive, methodengeführte Entwicklungs- und Steuerungsplattform.
|
||||
```
|
||||
|
||||
Der Kern ist:
|
||||
|
||||
```text
|
||||
Adaptive Steering Core
|
||||
```
|
||||
|
||||
mit:
|
||||
|
||||
```text
|
||||
methodengeführten Steuerungsworkflows
|
||||
definierten Hook Slugs
|
||||
registrierbaren Methoden
|
||||
zentralen gemeinsamen Strukturen
|
||||
später konfigurierbaren Method Profiles
|
||||
```
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
# Jinkendo Kairo
|
||||
## Current State & Gap Analysis AP0.1–AP0.6b v0.1
|
||||
|
||||
Status: Arbeitsstand / Reset-Grundlage
|
||||
Stand: 2026-07-05
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Dieses Dokument ordnet den aktuellen Implementierungsstand gegen das kanonische Kairo Operating Model ein.
|
||||
|
||||
---
|
||||
|
||||
## 2. Aktueller Stand
|
||||
|
||||
### AP0.1 / AP0.1b
|
||||
|
||||
Technische Runtime:
|
||||
|
||||
- Deployment
|
||||
- Docker
|
||||
- FastAPI
|
||||
- PostgreSQL
|
||||
- Migration Runner
|
||||
- Health
|
||||
- Tests
|
||||
|
||||
Bewertung: gültig.
|
||||
|
||||
### AP0.2
|
||||
|
||||
Auth, Identity, Tenant und Actor:
|
||||
|
||||
- User
|
||||
- Sessions
|
||||
- Login/Logout
|
||||
- Tenant
|
||||
- Membership
|
||||
- Actor
|
||||
- TenantContext
|
||||
- Bootstrap
|
||||
- Audit bei Auth
|
||||
|
||||
Bewertung: gültig und zentral.
|
||||
|
||||
### AP0.3
|
||||
|
||||
Capability / Rights Registry:
|
||||
|
||||
- Capabilities
|
||||
- Grants
|
||||
- TenantContext.capabilities
|
||||
- require_capability
|
||||
- Entitlements Snapshot
|
||||
|
||||
Bewertung: gültig und zentral.
|
||||
|
||||
### AP0.4
|
||||
|
||||
Prompt / Feature / Config Registry:
|
||||
|
||||
- Feature Registry
|
||||
- PromptDefinition/Version/Step
|
||||
- Placeholder
|
||||
- Config
|
||||
- Single Render
|
||||
|
||||
Bewertung: technisch brauchbar, aber aktuell eingefroren. Nicht weiter ausbauen, bis MVP-Fachkern trägt.
|
||||
|
||||
### AP0.5
|
||||
|
||||
Minimaler Vorhaben-/Maßnahmen-Slice:
|
||||
|
||||
- Initiatives
|
||||
- Actions
|
||||
- Assignments
|
||||
- Status
|
||||
- Priority
|
||||
- Meine offenen Maßnahmen
|
||||
- Audit
|
||||
- Tests
|
||||
|
||||
Bewertung: gültiger technischer Start, aber zu flach als Kairo-MVP.
|
||||
|
||||
### AP0.6 / AP0.6b
|
||||
|
||||
Workspace UX / PWA Remediation:
|
||||
|
||||
- Jinkendo Look & Feel
|
||||
- App Shell
|
||||
- PWA-Grundlagen
|
||||
- responsive Desktop/Mobile
|
||||
- Widget/View Registry
|
||||
- Workspace/Vorhaben/Meine Maßnahmen
|
||||
|
||||
Bewertung: gültig und notwendig für Produktprüfung.
|
||||
|
||||
---
|
||||
|
||||
## 3. Gap-Matrix
|
||||
|
||||
| Konzept | Status | Bewertung |
|
||||
|---|---:|---|
|
||||
| Tenant | implementiert | gültig |
|
||||
| Actor | implementiert | Directory fehlt |
|
||||
| TenantContext | implementiert | gültig |
|
||||
| Capabilities | implementiert | gültig |
|
||||
| Initiative | implementiert | Status ggf. um draft ergänzen |
|
||||
| Action | implementiert | Status ggf. um ready/review_required ergänzen |
|
||||
| ActionAssignment | implementiert | ActorSelect braucht echtes Directory |
|
||||
| Project | fehlt | optional, aber Modell muss vorbereitet werden |
|
||||
| Milestone | fehlt | MVP-relevant minimal |
|
||||
| BacklogItem | fehlt | MVP-relevant |
|
||||
| Blocker | fehlt | MVP-relevant |
|
||||
| Evidence | fehlt | MVP-relevant minimal |
|
||||
| Decision | fehlt | MVP-relevant minimal |
|
||||
| Review | fehlt | MVP-relevant minimal |
|
||||
| RecurringElement | fehlt | MVP-relevant vorbereiten |
|
||||
| NextActionCandidate | fehlt | MVP-kritisches Read Model |
|
||||
| AttentionItem | fehlt | MVP-kritisches Read Model |
|
||||
| Data Layer | fehlt | Umbaufalle |
|
||||
| Tenant Invariants Doc | fehlt | Umbaufalle |
|
||||
| Actor Directory | fehlt | Actor-first nicht vollständig |
|
||||
| Prompt Workflow | vorbereitet | nicht MVP-kritisch |
|
||||
| MCP | fehlt | später |
|
||||
| KI-Priorisierung | fehlt | später |
|
||||
|
||||
---
|
||||
|
||||
## 4. Was bleibt gültig?
|
||||
|
||||
Gültig bleiben:
|
||||
|
||||
- technische Runtime
|
||||
- Auth
|
||||
- Tenant
|
||||
- Actor
|
||||
- Capability Registry
|
||||
- Entitlements
|
||||
- Prompt Kernel als eingefrorene Vorleistung
|
||||
- Initiative/Action als erster Slice
|
||||
- Jinkendo Workspace UX
|
||||
- Widget/View Registry
|
||||
|
||||
---
|
||||
|
||||
## 5. Was muss korrigiert werden?
|
||||
|
||||
Korrigiert werden muss die implizite Produktlinie.
|
||||
|
||||
Die aktuelle UI und API dürfen nicht den Eindruck erzeugen:
|
||||
|
||||
```text
|
||||
Kairo = Vorhaben + Aufgaben
|
||||
```
|
||||
|
||||
Kairo muss sichtbar werden als:
|
||||
|
||||
```text
|
||||
Kairo = operative Steuerung von Vorhaben
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Zwingende nächste Grundlagen
|
||||
|
||||
Vor weiterem Fachausbau:
|
||||
|
||||
1. Tenant Invariants
|
||||
2. Actor Directory
|
||||
3. Data Layer Minimum
|
||||
4. Attention/Next-Action Read Model
|
||||
5. Operating Model Extension I
|
||||
|
||||
---
|
||||
|
||||
## 7. Nächste Implementierungsvorschläge
|
||||
|
||||
### AP0.7 — Tenant Hardening, Actor Directory & Data Layer Minimum
|
||||
|
||||
Klein halten, aber zwingend.
|
||||
|
||||
### AP0.8 — Operating Model Extension I
|
||||
|
||||
BacklogItem, Blocker, Milestone minimal, Attention Items.
|
||||
|
||||
### AP0.9 — Operating Model Extension II
|
||||
|
||||
Evidence, Decision, Review, RecurringElement minimal.
|
||||
|
||||
---
|
||||
|
||||
## 8. Risiko, wenn wir nicht korrigieren
|
||||
|
||||
Ohne Korrektur wird Kairo:
|
||||
|
||||
- eine bessere To-do-Liste
|
||||
- ein generischer Workspace
|
||||
- technisch überfundiert
|
||||
- fachlich zu flach
|
||||
- später schwer auf Program Director umzubauen
|
||||
|
||||
---
|
||||
|
||||
## 9. Empfehlung
|
||||
|
||||
Keine weitere Prompt-/Foundation-/Admin-Arbeit starten.
|
||||
|
||||
Erst kanonisches Operating Model und Data Layer wieder in die Implementierungsroadmap bringen.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Jinkendo Kairo
|
||||
## Current State & Gap Analysis v0.2
|
||||
|
||||
**Status:** Gap-Analyse (living document)
|
||||
**Stand:** 2026-07-05 (nach AP1.1b + DOC Welle 1)
|
||||
**Ersetzt für Ist-Stand:** `Kairo_Current_State_Gap_Analysis_AP0.1_AP0.6b_v0.1.md`
|
||||
**Detail-Tabelle:** `Kairo_Implementation_Truth_Table_v0.1.md`
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Ordnet **Implementierungsstand** gegen **Vision v0.2** ein — nicht gegen veraltetes „Milestone minimal = fertig“.
|
||||
|
||||
---
|
||||
|
||||
## 2. Was seit v0.1 dazugekommen ist
|
||||
|
||||
| Paket | Geliefert | Produktwert |
|
||||
|-------|-----------|-------------|
|
||||
| AP0.7 | Tenant-Invarianten, Actor Directory, Data Layer | ✓ tragfähig |
|
||||
| AP0.8–0.9 | OM-Tabellen + CRUD-APIs + Workspace Attention | ◐ Inventar |
|
||||
| AP0.10b | NextAction/Heute-Widgets, Snapshot v2 | ◐ Workspace |
|
||||
| AP1.0 | steering_contexts, Lifecycle, Signals | ◐ Backend |
|
||||
| AP1.1 | Method Registry, product_milestone_driven | ◐ |
|
||||
| AP1.1b | InitiativeDetail Action-Hub | ◐ falsches IA-Pattern |
|
||||
| DOC W1 | Vision v0.2, Canonical OM v0.2, Truth Table | ✓ Richtung |
|
||||
|
||||
---
|
||||
|
||||
## 3. Gap-Matrix (Vision v0.2)
|
||||
|
||||
| Konzept | Technisch | Produkt (Alltag) | Nächstes Paket |
|
||||
|---------|-----------|------------------|----------------|
|
||||
| Tenant / Actor / Capabilities | ✓ | ✓ | — |
|
||||
| Initiative | ✓ | ◐ | AP1.2c Übersicht |
|
||||
| Action (Arbeitspaket) | ✓ | ◐ | AP1.2c Detail-Route |
|
||||
| Backlog / Blocker / Evidence / Decision / Review | ✓ API | ◐ CRUD-Wand | AP1.2c Unterseiten |
|
||||
| Milestone | ◐ Tabelle | ✗ kein Gate | AP1.4 |
|
||||
| RoadmapItem | ✗ | ✗ | AP1.4 |
|
||||
| Plan vs. Ist | ✗ | ✗ | AP1.4–AP1.6 |
|
||||
| Steering / Lifecycle | ◐ | ◐ Snapshot | AP1.2 |
|
||||
| NextAction | ◐ API | ◐ Widget | AP1.2c konfigurierbar |
|
||||
| Portfolio-Priorität | ✗ | ✗ | AP1.8 |
|
||||
| Situativer Kontext | ✗ | ✗ | AP1.8 |
|
||||
| IA Workspace Portfolio | ✗ | ✗ | AP1.2c |
|
||||
| IA Initiative-Übersicht | ✗ | ✗ | AP1.2c |
|
||||
| IA Unterseiten | ✗ | ✗ | AP1.2c |
|
||||
| Modal/Detail-Bearbeitung | ✗ | ✗ | AP1.2c |
|
||||
| Operational Actor API | ✗ | ✗ | AP1.7 |
|
||||
| Project / Task | ○ / ✗ | ✗ | AP1.5 |
|
||||
| Journey | ✗ | ✗ | AP1.6 |
|
||||
|
||||
---
|
||||
|
||||
## 4. Dokumenten-Gap (behoben / offen)
|
||||
|
||||
| Gap | Status |
|
||||
|-----|--------|
|
||||
| Zielbild vs. Ist vermischt | ◐ Welle 1 ✓, Welle 2 ◐ |
|
||||
| Roadmap suggerierte falsche Nähe zum Ziel | ◐ Roadmap v0.2 ✓ |
|
||||
| Kein Gate-ADP | ◐ Welle 2 |
|
||||
| Kein Agent-Interface-ADP | ◐ Welle 2 |
|
||||
| Target State ohne Implementierungs-Marker | ◐ Implementation Map v0.2 |
|
||||
|
||||
---
|
||||
|
||||
## 5. Zwingende nächste Schritte
|
||||
|
||||
1. **DOC Welle 2 abschließen** (ADPs, Handover)
|
||||
2. **AP1.2** — `operating_phase` entfernen
|
||||
3. **AP1.2c** — IA-Skeleton (größter Produkt-Hebel)
|
||||
4. **AP0.10d** — Validation mit neuen Fragen
|
||||
5. **AP1.4** — nur nach PO-Go
|
||||
|
||||
---
|
||||
|
||||
## 6. Risiko bei Verzögerung von IA
|
||||
|
||||
Ohne AP1.2c:
|
||||
|
||||
- weitere Features landen auf Omnibus-Seite
|
||||
- Vibe-Coder bekommen keine klare API-Oberfläche
|
||||
- Gate-Migration (AP1.4) baut auf falscher Navigation auf
|
||||
|
||||
---
|
||||
|
||||
## 7. Empfehlung
|
||||
|
||||
**Kein** AP1.1c, kein weiteres InitiativeDetail-Layout.
|
||||
|
||||
**Ja:** Welle 2 Docs → AP1.2 → AP1.2c in einem Sprint-Fokus.
|
||||
|
||||
---
|
||||
|
||||
*v0.1 Gap-Matrix (AP0.6b) historisch — viele „fehlt“-Zeilen sind inzwischen API-erledigt, aber produktlich unzureichend.*
|
||||
@@ -0,0 +1,590 @@
|
||||
# Kairo – Method Design Principles
|
||||
## v0.1 – Designprinzipien für registrierbare Steuerungsmethoden
|
||||
|
||||
**Status:** verbindlicher Architektur- und Methodendesign-Entwurf
|
||||
**Stand:** 2026-07-05
|
||||
**Zweck:** Definition der Designprinzipien, nach denen Kairo-Methoden künftig entwickelt, registriert, erweitert und versioniert werden.
|
||||
|
||||
---
|
||||
|
||||
## 1. Ziel
|
||||
|
||||
Kairo soll im Lauf der Zeit viele unterschiedliche Steuerungsmethoden unterstützen, ohne dass für jede Methode der komplette Codekern angepasst werden muss.
|
||||
|
||||
Methoden sollen sich ähnlich wie Widgets an einem klaren Abstraktionslayer anmelden können.
|
||||
|
||||
Die Architektur muss ermöglichen:
|
||||
|
||||
```text
|
||||
- neue Methoden hinzufügen
|
||||
- bestehende Methoden versionieren
|
||||
- methodenspezifische Steuerungsstrukturen erzeugen
|
||||
- methodenspezifische NextAction-Logik einhängen
|
||||
- methodenspezifische Review-/Evidence-Logik einhängen
|
||||
- später Method Profiles konfigurieren
|
||||
- später Workflow-Fragmente an Hooks binden
|
||||
- später Agent/LLM/Tool-Steps pro Methode erlauben
|
||||
```
|
||||
|
||||
Gleichzeitig darf die Methodenarchitektur nicht beliebig und untestbar werden.
|
||||
|
||||
---
|
||||
|
||||
## 2. Grundprinzip
|
||||
|
||||
Eine Kairo-Methode ist kein Label.
|
||||
|
||||
Eine Kairo-Methode ist ein registriertes Steuerungspaket.
|
||||
|
||||
Sie beschreibt:
|
||||
|
||||
```text
|
||||
- für welche Domains sie gilt
|
||||
- welche Scope Types sie steuern kann
|
||||
- welchen Standard Lifecycle sie nutzt oder erweitert
|
||||
- welche Steuerungsstrukturen sie benötigt
|
||||
- welche Hook Slugs sie unterstützt
|
||||
- welche Structure Builder sie bereitstellt
|
||||
- welche Signal Rules sie registriert
|
||||
- welche NextAction Strategy sie nutzt
|
||||
- welche Assignment / Waiting / Reminder / Escalation Strategy sie nutzt
|
||||
- welche Review- und Evidence-Policies gelten
|
||||
- welche Workflow-Fragmente später erlaubt sind
|
||||
- welche Node Types später erlaubt sind
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Method Registry als zentraler Erweiterungspunkt
|
||||
|
||||
Alle Methoden registrieren sich in einer zentralen Method Registry.
|
||||
|
||||
Zielbild:
|
||||
|
||||
```text
|
||||
backend/steering/methods/registry.py
|
||||
```
|
||||
|
||||
Beispielhafte Registrierung:
|
||||
|
||||
```python
|
||||
register_method(
|
||||
MethodDefinition(
|
||||
method_key="maturity_progression",
|
||||
version="v1",
|
||||
label="Maturity Progression",
|
||||
supported_domains=["maturity_development", "personal_development"],
|
||||
supported_scope_types=["initiative", "roadmap_item", "action"],
|
||||
default_lifecycle="standard_development_lifecycle",
|
||||
required_structures=["roadmap", "roadmap_lanes", "roadmap_items", "backlog", "actions"],
|
||||
hook_slugs=[
|
||||
"on_goal_captured",
|
||||
"on_structure_required",
|
||||
"on_maturity_path_required",
|
||||
"on_next_action_requested",
|
||||
"on_evidence_required",
|
||||
"on_review_due",
|
||||
"on_reassessment_required",
|
||||
],
|
||||
structure_builders=[
|
||||
"maturity_path_builder",
|
||||
"practice_backlog_builder",
|
||||
],
|
||||
signal_rule_providers=[
|
||||
"maturity_gap_attention_rules",
|
||||
"evidence_required_rules",
|
||||
],
|
||||
next_action_strategy="maturity_next_action_strategy",
|
||||
assignment_strategy="default_actor_assignment_strategy",
|
||||
waiting_strategy="default_waiting_strategy",
|
||||
review_strategy="maturity_review_strategy",
|
||||
evidence_policy="maturity_evidence_policy",
|
||||
allowed_node_types=[
|
||||
"human_task",
|
||||
"evidence_check",
|
||||
"review",
|
||||
"reflection",
|
||||
"llm_prompt",
|
||||
"agent_task",
|
||||
],
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Built-in zuerst, konfigurierbar später
|
||||
|
||||
Die Methodenarchitektur folgt einem Stufenmodell.
|
||||
|
||||
### Stufe 1 – Built-in Methods
|
||||
|
||||
```text
|
||||
- Methoden code-seitig definiert
|
||||
- klare Slugs
|
||||
- testbar
|
||||
- keine freie Nutzerkonfiguration
|
||||
```
|
||||
|
||||
### Stufe 2 – Built-in Method Profiles
|
||||
|
||||
```text
|
||||
- vordefinierte Profile pro Methode
|
||||
- z. B. "einfach", "evidence_strict", "review_driven"
|
||||
```
|
||||
|
||||
### Stufe 3 – Tenant Method Profiles
|
||||
|
||||
```text
|
||||
- tenant-spezifische Konfiguration
|
||||
- begrenzte Parameter
|
||||
- keine freie Ausführungslogik
|
||||
```
|
||||
|
||||
### Stufe 4 – Workflow Bindings an Hooks
|
||||
|
||||
```text
|
||||
- kleine Workflow-Fragmente an definierte Hooks
|
||||
- nur erlaubte Node Types
|
||||
- nur innerhalb Method Governance
|
||||
```
|
||||
|
||||
### Stufe 5 – Method Designer
|
||||
|
||||
```text
|
||||
- spätere UI
|
||||
- nur für fortgeschrittene Nutzung
|
||||
- Governance, Tests und Freigaben erforderlich
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Zentrale gemeinsame Strukturen
|
||||
|
||||
Alle Methoden müssen auf gemeinsamen Kairo-Strukturen aufbauen.
|
||||
|
||||
Gemeinsame Kernstrukturen:
|
||||
|
||||
```text
|
||||
SteeringContext
|
||||
Roadmap
|
||||
RoadmapLane
|
||||
RoadmapItem
|
||||
BacklogItem
|
||||
Action
|
||||
ActionAssignment
|
||||
Blocker
|
||||
Signal
|
||||
AttentionItem
|
||||
NextActionCandidate
|
||||
Evidence
|
||||
Review
|
||||
Decision
|
||||
Actor
|
||||
Capability
|
||||
AuditEvent
|
||||
```
|
||||
|
||||
Eine Methode darf keine parallelen Kernmodelle erfinden.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
Meilenstein = RoadmapItem(type = milestone)
|
||||
Reifegrad = RoadmapItem(type = maturity_stage)
|
||||
Feature = RoadmapItem(type = feature)
|
||||
Kapitel = RoadmapItem(type = chapter)
|
||||
Sprint-Grobplanung = RoadmapItem(type = work_cycle)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Minimaler Standard Lifecycle
|
||||
|
||||
Alle Methoden basieren auf einem gemeinsamen minimalen Lifecycle.
|
||||
|
||||
```text
|
||||
intake
|
||||
method_selection
|
||||
structure_setup
|
||||
planning
|
||||
action_selection
|
||||
assignment
|
||||
waiting
|
||||
result_intake
|
||||
validation
|
||||
review
|
||||
adaptation
|
||||
closure
|
||||
```
|
||||
|
||||
Eine Methode darf:
|
||||
|
||||
```text
|
||||
- Schritte auslassen
|
||||
- Schritte spezialisieren
|
||||
- zusätzliche Hook Slugs ergänzen
|
||||
- eigene Structure Builder an bestimmten Schritten registrieren
|
||||
```
|
||||
|
||||
Eine Methode darf nicht:
|
||||
|
||||
```text
|
||||
- Tenant-Sicherheit umgehen
|
||||
- eigene Actor-Logik außerhalb des Actor-Modells einführen
|
||||
- eigene Rechteprüfung außerhalb der Capability-Schicht einführen
|
||||
- persistente Kernobjekte ohne Service-/Audit-Schicht verändern
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Hook Slugs
|
||||
|
||||
Hook Slugs sind stabile Einhängepunkte.
|
||||
|
||||
Sie sind die Hauptabstraktion, über die Methoden erweitert werden.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
on_goal_captured
|
||||
on_method_selection_required
|
||||
on_method_selected
|
||||
on_structure_required
|
||||
on_roadmap_required
|
||||
on_backlog_required
|
||||
on_wbs_required
|
||||
on_maturity_path_required
|
||||
on_content_structure_required
|
||||
on_plan_required
|
||||
on_dependency_analysis_required
|
||||
on_dod_definition_required
|
||||
on_next_action_requested
|
||||
on_assignment_required
|
||||
on_wait_started
|
||||
on_due_date_reached
|
||||
on_result_overdue
|
||||
on_reminder_required
|
||||
on_escalation_required
|
||||
on_result_received
|
||||
on_dod_check_required
|
||||
on_evidence_required
|
||||
on_quality_gate_required
|
||||
on_review_due
|
||||
on_reassessment_required
|
||||
on_reflection_required
|
||||
on_replan_required
|
||||
on_structure_update_required
|
||||
on_closure_requested
|
||||
```
|
||||
|
||||
Hook Slugs müssen:
|
||||
|
||||
```text
|
||||
- eindeutig sein
|
||||
- versionierbar bleiben
|
||||
- fachlich benannt sein
|
||||
- in Method Definitions referenziert werden
|
||||
- in Signals als Ursache auftauchen können
|
||||
- später Workflow Bindings tragen können
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Structure Builder
|
||||
|
||||
Structure Builder legen die methodenspezifische Steuerungsstruktur an.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
roadmap_builder
|
||||
milestone_plan_builder
|
||||
feature_landscape_builder
|
||||
wbs_builder
|
||||
backlog_builder
|
||||
maturity_path_builder
|
||||
chapter_structure_builder
|
||||
cycle_structure_builder
|
||||
review_gate_builder
|
||||
routine_structure_builder
|
||||
```
|
||||
|
||||
Ein Structure Builder darf:
|
||||
|
||||
```text
|
||||
- Roadmaps anlegen
|
||||
- RoadmapLanes anlegen
|
||||
- RoadmapItems anlegen
|
||||
- initiale BacklogItems vorschlagen oder erzeugen
|
||||
- methodenspezifische Startstruktur erzeugen
|
||||
```
|
||||
|
||||
Ein Structure Builder darf nicht:
|
||||
|
||||
```text
|
||||
- ungeprüft produktive Actions erzeugen, wenn ein Gate vorgesehen ist
|
||||
- Actors ohne Assignment Strategy zuweisen
|
||||
- Tenant-Kontext aus Client Input übernehmen
|
||||
- Rechteprüfung umgehen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Strategies
|
||||
|
||||
Methoden nutzen austauschbare Strategies.
|
||||
|
||||
Wichtige Strategy Interfaces:
|
||||
|
||||
```text
|
||||
NextActionStrategy
|
||||
AttentionRuleProvider
|
||||
AssignmentStrategy
|
||||
WaitingStrategy
|
||||
ReminderStrategy
|
||||
EscalationStrategy
|
||||
ResultIntakeStrategy
|
||||
EvidencePolicy
|
||||
ReviewStrategy
|
||||
ClosurePolicy
|
||||
```
|
||||
|
||||
Diese Strategies sind zentrale Erweiterungspunkte.
|
||||
|
||||
Sie verhindern, dass methodenspezifische Logik monolithisch in Services oder Data Layer wächst.
|
||||
|
||||
---
|
||||
|
||||
## 10. Signal Rules
|
||||
|
||||
Signal Rules erzeugen AttentionItems und NextActionCandidates.
|
||||
|
||||
Sie müssen erklären können:
|
||||
|
||||
```text
|
||||
- warum ein Signal erzeugt wurde
|
||||
- welcher Hook relevant ist
|
||||
- welche Methode/Domain beteiligt ist
|
||||
- welcher Scope betroffen ist
|
||||
- welche Datenquelle genutzt wurde
|
||||
- welche nächste Handlung empfohlen wird
|
||||
```
|
||||
|
||||
Signal Rules müssen tenant-sicher sein und dürfen nicht quer über Tenants lesen.
|
||||
|
||||
---
|
||||
|
||||
## 11. Method Definition Contract
|
||||
|
||||
Eine MethodDefinition sollte mindestens enthalten:
|
||||
|
||||
```text
|
||||
method_key
|
||||
version
|
||||
label
|
||||
description
|
||||
supported_domains
|
||||
supported_scope_types
|
||||
default_lifecycle
|
||||
required_structures
|
||||
allowed_structures
|
||||
hook_slugs
|
||||
structure_builders
|
||||
attention_rule_providers
|
||||
next_action_strategy
|
||||
assignment_strategy
|
||||
waiting_strategy
|
||||
reminder_strategy
|
||||
escalation_strategy
|
||||
result_intake_strategy
|
||||
review_strategy
|
||||
evidence_policy
|
||||
closure_policy
|
||||
allowed_workflow_fragments
|
||||
allowed_node_types
|
||||
default_configuration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Method Versioning
|
||||
|
||||
Methoden müssen versionierbar sein.
|
||||
|
||||
Regeln:
|
||||
|
||||
```text
|
||||
- method_key bleibt stabil
|
||||
- version beschreibt fachliche/technische Methode
|
||||
- bestehende SteeringContexts referenzieren method_key + version
|
||||
- neue Versionen dürfen bestehende Kontexte nicht stillschweigend verändern
|
||||
- Migration oder Upgrade muss explizit sein
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 13. Method Profiles
|
||||
|
||||
Method Profiles sind spätere konkrete Konfigurationen.
|
||||
|
||||
Sie dürfen Parameter anpassen, aber nicht den Kairo-Kern umgehen.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
maturity_progression.basic
|
||||
maturity_progression.evidence_strict
|
||||
content_chapter_based.light_review
|
||||
product_milestone_driven.release_focused
|
||||
routine_control.escalation_strict
|
||||
```
|
||||
|
||||
Ein Method Profile darf z. B. konfigurieren:
|
||||
|
||||
```text
|
||||
- welche Hooks aktiv sind
|
||||
- welche Review-Frequenz gilt
|
||||
- ob Evidence erforderlich ist
|
||||
- welche Reminder-Strategie gilt
|
||||
- welche Node Types erlaubt sind
|
||||
- ob Agent Steps erlaubt sind
|
||||
```
|
||||
|
||||
Ein Method Profile darf nicht:
|
||||
|
||||
```text
|
||||
- beliebigen Code ausführen
|
||||
- Tenant-Sicherheit umgehen
|
||||
- Capabilities außer Kraft setzen
|
||||
- systemgeschützte Hooks überschreiben
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. Methodenbeispiele
|
||||
|
||||
### 14.1 product_milestone_driven
|
||||
|
||||
```text
|
||||
Domain:
|
||||
- product_development
|
||||
- project
|
||||
|
||||
Structures:
|
||||
- Roadmap
|
||||
- Feature Lane
|
||||
- Architecture Lane
|
||||
- Release Lane
|
||||
- Backlog
|
||||
- Actions
|
||||
- Blockers
|
||||
|
||||
Primary Hooks:
|
||||
- on_goal_captured
|
||||
- on_roadmap_required
|
||||
- on_backlog_required
|
||||
- on_next_action_requested
|
||||
- on_review_due
|
||||
```
|
||||
|
||||
### 14.2 content_chapter_based
|
||||
|
||||
```text
|
||||
Domain:
|
||||
- content_development
|
||||
|
||||
Structures:
|
||||
- Roadmap
|
||||
- Chapter Lane
|
||||
- Research Lane
|
||||
- Draft Lane
|
||||
- Review Lane
|
||||
- Backlog
|
||||
- Actions
|
||||
|
||||
Primary Hooks:
|
||||
- on_content_structure_required
|
||||
- on_next_action_requested
|
||||
- on_review_due
|
||||
```
|
||||
|
||||
### 14.3 maturity_progression
|
||||
|
||||
```text
|
||||
Domain:
|
||||
- maturity_development
|
||||
- personal_development
|
||||
|
||||
Structures:
|
||||
- Roadmap
|
||||
- Maturity Stage Lane
|
||||
- Capability Lane
|
||||
- Practice Lane
|
||||
- Evidence Lane
|
||||
- Reflection Lane
|
||||
|
||||
Primary Hooks:
|
||||
- on_maturity_path_required
|
||||
- on_evidence_required
|
||||
- on_review_due
|
||||
- on_reassessment_required
|
||||
```
|
||||
|
||||
### 14.4 wbs_driven
|
||||
|
||||
```text
|
||||
Domain:
|
||||
- project
|
||||
- program
|
||||
|
||||
Structures:
|
||||
- WBS Roadmap
|
||||
- Work Package Items
|
||||
- Dependencies
|
||||
- Backlog
|
||||
- Actions
|
||||
|
||||
Primary Hooks:
|
||||
- on_wbs_required
|
||||
- on_dependency_analysis_required
|
||||
- on_next_action_requested
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. Designprinzipien kurz
|
||||
|
||||
```text
|
||||
1. Methoden sind registrierte Steuerungspakete, keine Labels.
|
||||
2. Neue Methoden melden sich an einer Registry an.
|
||||
3. Alle Methoden nutzen gemeinsame Kairo-Kernstrukturen.
|
||||
4. Der Standard Lifecycle ist die gemeinsame Basis.
|
||||
5. Erweiterung erfolgt über Hook Slugs, Structure Builder und Strategies.
|
||||
6. Built-in Methods kommen vor freier Konfiguration.
|
||||
7. Profiles konfigurieren, aber ersetzen nicht den Kern.
|
||||
8. Signals müssen erklärbar und tenant-sicher sein.
|
||||
9. Agenten und LLMs sind spätere Step Provider, nicht Methoden selbst.
|
||||
10. Keine Methode darf Capabilities, TenantContext oder Actor-Modell umgehen.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. Konsequenz für die technische Zielarchitektur
|
||||
|
||||
Die technische Zielarchitektur muss diese Methodendesign-Prinzipien als verbindlich übernehmen.
|
||||
|
||||
Insbesondere muss sie definieren:
|
||||
|
||||
```text
|
||||
- Method Registry
|
||||
- Hook Registry
|
||||
- MethodDefinition Contract
|
||||
- Standard Lifecycle
|
||||
- Structure Builder Interfaces
|
||||
- Strategy Interfaces
|
||||
- Signal Rule Provider Interfaces
|
||||
- Method Versioning
|
||||
- Method Profiles als spätere Konfigurationsebene
|
||||
```
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
# Kairo — Operating Model → Steering Bridge
|
||||
|
||||
**Status:** Architektur-Einordnung
|
||||
**Stand:** 2026-07-05
|
||||
**Zweck:** Ehrliche Antwort auf die Frage, ob AP0.8/0.9 auf spätere Steuerungslogik einzahlen — und was noch fehlt.
|
||||
|
||||
---
|
||||
|
||||
## 1. Kurzantwort
|
||||
|
||||
**Ja, aber indirekt.** AP0.8/0.9 haben das **Vokabular und die Persistenzschicht** des kanonischen Operating Models geliefert — nicht den **Steuerungsgraph**, nicht den **Lifecycle-Orchestrator** und nicht die **Method Registry**.
|
||||
|
||||
Das ist kein Versehen, sondern die dokumentierte Reihenfolge:
|
||||
|
||||
```text
|
||||
Foundation (AP0.1–0.7)
|
||||
→ Operating Model Entitäten (AP0.8–0.9) ← wir sind hier
|
||||
→ Integration & Validation (AP0.10)
|
||||
→ Steering Core Foundation (Sprint 1 / AP1.x)
|
||||
→ Method Registry, Hooks, Lifecycle Runtime
|
||||
```
|
||||
|
||||
Ohne die Entitäten hätte Steering nichts zu lesen und zu steuern.
|
||||
Mit nur den Entitäten **ohne Verbindungslogik** wirkt Kairo zu Recht wie eine Sammlung paralleler Tabellen.
|
||||
|
||||
---
|
||||
|
||||
## 2. Was AP0.8/0.9 tatsächlich vorbereitet
|
||||
|
||||
| Baustein | Beitrag für späteres Steering | Noch nicht da |
|
||||
|----------|------------------------------|---------------|
|
||||
| **Entitäten** | Blocker, Backlog, Milestone, Evidence, Decision, Review, Recurring | SteeringContext, Project, Dependency |
|
||||
| **Schwache FKs** | `blocker.action_id`, `evidence.action_id`, `review.action_id` | Pflicht-Struktur, Graph-Traversierung in UI |
|
||||
| **Attention (Regeln 1–9)** | Proto-Signal-Engine, erklärbare DTOs | Methoden-spezifische Signal Rules, Ranking |
|
||||
| **NextActionCandidates** | Regelbasierte Empfehlungen | Hook `on_next_action_requested`, Strategien |
|
||||
| **Audit-Events** | Nachvollziehbarkeit für Agenten/Steering | Lifecycle-Audit-Kette |
|
||||
| **Actor-Assignments** | Wer handelt | Waiting/Reminder/Escalation |
|
||||
| **Status-Enums** | Anknüpfpunkte für Lifecycle-Transitions | State Machine + Guards |
|
||||
|
||||
**Fazit:** AP0.8/0.9 = **System of Record für OM-Objekte** + **regelbasierte Signale**.
|
||||
Das ist Schritt 5–7 der Evolutionslinie (`Kairo_System_Target_State_v0.1.md` §24), **nicht** Schritt 2–4 (Steering Core, Method Registry, Lifecycle).
|
||||
|
||||
---
|
||||
|
||||
## 3. Kanonisches Modell vs. Ist-Implementierung
|
||||
|
||||
### Soll (Canonical Operating Model)
|
||||
|
||||
```text
|
||||
Initiative
|
||||
├── Milestone
|
||||
├── BacklogItem
|
||||
├── Action
|
||||
│ ├── Assignment
|
||||
│ ├── Blocker ← primär an Maßnahme
|
||||
│ └── Evidence ← primär an Maßnahme
|
||||
├── Decision
|
||||
├── Review
|
||||
└── RecurringElement
|
||||
```
|
||||
|
||||
### Ist (AP0.9)
|
||||
|
||||
```text
|
||||
Initiative
|
||||
├── [parallele Sektionen in UI]
|
||||
├── Action (Liste)
|
||||
├── Blocker (Liste, action_id optional)
|
||||
├── Evidence (Liste, action_id optional)
|
||||
├── …
|
||||
```
|
||||
|
||||
**Lücke:** Objekte existieren, aber **Struktur und Flow sind nicht sichtbar**.
|
||||
Der Nutzer sieht Listen, keinen **Steuerungszustand** eines Vorhabens.
|
||||
|
||||
---
|
||||
|
||||
## 4. Was „Steuerungslogik“ später bedeutet
|
||||
|
||||
Aus `Kairo_Target_Architecture_Method_Driven_Adaptive_Steering_Core_v0.1.md`:
|
||||
|
||||
| Komponente | Rolle |
|
||||
|------------|-------|
|
||||
| **SteeringContext** | Bindet Initiative an Methode, Lifecycle, Domain |
|
||||
| **Method Registry** | Liefert Structure Builder, Signal Rules, Strategien |
|
||||
| **Standard Lifecycle** | intake → … → closure mit Guards |
|
||||
| **Hook Registry** | `on_review_due`, `on_blocker_open`, `on_next_action_requested` |
|
||||
| **Signal Engine** | Attention + NextAction aus Methode + Kontext |
|
||||
| **Transition Orchestrator** | Statusänderung → Side Effects (unblock, review anstoßen) |
|
||||
|
||||
AP0.8/0.9 **ersetzen** das nicht — sie liefern die **Daten**, an die Hooks und Regeln andocken.
|
||||
|
||||
---
|
||||
|
||||
## 5. AP0.10 — Integration statt nur Validation
|
||||
|
||||
AP0.10 wird daher **zweigeteilt**:
|
||||
|
||||
### A) Operating Model Integration (technisch)
|
||||
|
||||
- **Steering-Snapshot** Read-Model: Initiative als verknüpfter Graph (Actions mit Blockern/Evidence/Reviews)
|
||||
- **Operating Cycle Phase** (heuristisch, erklärbar): triage / execute / verify / review / adapt
|
||||
- **Transition-Orchestrierung minimal:** z. B. Blocker gelöst → verknüpfte Maßnahme entblocken; Review abgeschlossen → Maßnahme weiterführen
|
||||
- **UI:** Verknüpfungen sichtbar (Maßnahme ↔ Blocker/Evidence), nicht nur parallele Sektionen
|
||||
- **Attention:** Regeln, die **Beziehungen** nutzen (Maßnahme blockiert + offener Blocker auf derselben Maßnahme)
|
||||
|
||||
### B) MVP Validation (fachlich)
|
||||
|
||||
Testvorhaben aus Roadmap (Kairo, Gewaltschutzkurs, …) — Prüffragen: Hilft es bei täglicher Steuerung? Fehlt was **wirklich** als Nächstes?
|
||||
|
||||
---
|
||||
|
||||
## 6. Evolutionspfad (konkret)
|
||||
|
||||
```text
|
||||
AP0.10 Integration + Validation ← nächster Schritt
|
||||
AP1.0 backend/steering/ Foundation (SteeringContext, Lifecycle stub)
|
||||
AP1.1 Method Registry minimal + Hook Registry
|
||||
AP1.2 Signal Engine aus attention.py → steering/signals/
|
||||
AP1.3 Transition Orchestrator (ersetzt operating_transitions.py)
|
||||
Sprint 2+ Dependencies, Waiting, Method Profiles
|
||||
```
|
||||
|
||||
**Regel:** Keine neuen parallelen Tabellen ohne OM-Bezug.
|
||||
Neue Arbeit muss either **verbinden**, **orchestratieren** oder **validieren**.
|
||||
|
||||
---
|
||||
|
||||
## 7. Leitfrage-Check
|
||||
|
||||
> Zahlt jede Entität auf „Welcher nächste Schritt bringt das Vorhaben voran?“ ein?
|
||||
|
||||
| Entität | Heute | Nach AP0.10 | Nach Steering Core |
|
||||
|---------|-------|-------------|-------------------|
|
||||
| Action | ✓ Commit/Execute | ✓ mit Kontext | ✓ NextAction-Ziel |
|
||||
| Blocker | △ Signal | ✓ an Maßnahme | ✓ Hook on_blocker_open |
|
||||
| Backlog | ✓ Triage | ✓ Convert-Flow | ✓ Structure Builder |
|
||||
| Milestone | △ Signal at_risk | ✓ mit Reviews | ✓ Roadmap-Lane |
|
||||
| Evidence | △ passive | ✓ an Maßnahme | ✓ Verify-Phase |
|
||||
| Review | △ due signal | ✓ schließt Execute | ✓ Review Strategy |
|
||||
| Decision | △ passive | △ Adapt-Hinweis | ✓ Adapt-Hook |
|
||||
| Recurring | △ due signal | △ Routine-Hinweis | ✓ routine_control |
|
||||
|
||||
---
|
||||
|
||||
*v0.1 — Referenz für AP0.10 und Sprint-1-Planung*
|
||||
@@ -0,0 +1,73 @@
|
||||
# Kairo System Target State — Implementation Map v0.2
|
||||
|
||||
**Status:** Ergänzung zu Target State v0.1
|
||||
**Stand:** 2026-07-05
|
||||
**Zielbild-Inhalt:** unverändert in `Kairo_System_Target_State_v0.1.md`
|
||||
**Ist-Detail:** `Kairo_Implementation_Truth_Table_v0.1.md`
|
||||
|
||||
---
|
||||
|
||||
## Legende
|
||||
|
||||
| Status | Bedeutung |
|
||||
|--------|-----------|
|
||||
| **target** | Nur dokumentiert — Zielbild |
|
||||
| **partial** | Anfang implementiert, Vision nicht erfüllt |
|
||||
| **done** | Für MVP-Ausschnitt ausreichend |
|
||||
| **n/a** | Bewusst später (Phase C+) |
|
||||
|
||||
---
|
||||
|
||||
## Kapitel-Mapping (Target State v0.1)
|
||||
|
||||
| § | Thema | Status | Anmerkung |
|
||||
|---|-------|--------|-----------|
|
||||
| 1 | Executive Summary | target | Leitfrage ✓ in Steering |
|
||||
| 2 | Grundverständnis | target | — |
|
||||
| 3 | Produktidentität | partial | Program Director dokumentiert, UI To-do-artig |
|
||||
| 4 | Kernmodell | partial | Initiative/Action ✓; Roadmap ✗ |
|
||||
| 5 | Steering Core | partial | AP1.0 Skeleton |
|
||||
| 6 | Standard Lifecycle | partial | steering_contexts ✓; Hooks stub |
|
||||
| 7 | Steering Methods | partial | 2 Methoden registriert |
|
||||
| 8 | Method Registry | partial | Registry ✓; kein Designer |
|
||||
| 9 | Steering Domains | target | — |
|
||||
| 10 | Steerable Objects | partial | OM-Tabellen, nicht RoadmapItem |
|
||||
| 11 | Steering Context | done | Migration 009 |
|
||||
| 12 | Roadmap / Development Model | target | Milestone-Brücke only |
|
||||
| 13 | Roadmap vs Backlog vs Action | target | Konzept ✗ in UI |
|
||||
| 14 | Structure Builder | n/a | Phase C+ |
|
||||
| 15 | Hooks | partial | Stub AP1.0 |
|
||||
| 16 | Strategies | partial | next_action strategies minimal |
|
||||
| 17 | Signals | partial | AP1.0; AP1.2 konsolidieren |
|
||||
| 18 | Assignment / Waiting / Reminder | partial | Assignment ✓; Rest n/a |
|
||||
| 19 | Evidence / Review / Decision | partial | CRUD ✓; Gate-Verify ✗ |
|
||||
| 20 | Workflow-Fragmente | n/a | eingefroren |
|
||||
| 21 | Agenten / LLMs / Tools | partial | Actors ✓; AP1.7 API ✗ |
|
||||
| 22 | Security / Governance / Audit | partial | Auth/Cap ✓ |
|
||||
| 23 | UI-Zielbild | target | Vision §7; AP1.2c |
|
||||
| 24 | Architektur-Evolutionslinie | target | Roadmap v0.2 |
|
||||
| 25 | Zielzustand Satz | target | — |
|
||||
|
||||
---
|
||||
|
||||
## UI-Zielbild (§23) — Detail-Mapping Vision §7
|
||||
|
||||
| Vision-Element | Target State | Implementierung |
|
||||
|----------------|--------------|-----------------|
|
||||
| Workspace Portfolio | §23 | ✗ → AP1.2c |
|
||||
| Initiative-Übersicht | §23 | ✗ → AP1.2c |
|
||||
| Unterseiten Plan/Ausführung/… | §23 | ✗ → AP1.2c |
|
||||
| Next-Action-Widget konfigurierbar | §16–17 | ◐ → AP1.2c |
|
||||
| Roadmap/Gates UI | §12–13 | ✗ → AP1.4 |
|
||||
| Journey | §19 | ✗ → AP1.6 |
|
||||
| Agent Interface | §21 | ✗ → AP1.7 |
|
||||
|
||||
---
|
||||
|
||||
## Nächste Status-Updates
|
||||
|
||||
Nach jedem AP diese Map + Truth Table aktualisieren.
|
||||
|
||||
---
|
||||
|
||||
*Vollständiges Zielbild weiterhin: `Kairo_System_Target_State_v0.1.md`*
|
||||
@@ -0,0 +1,810 @@
|
||||
# Kairo – System Target State
|
||||
## v0.1 – Zielzustand des angedachten Gesamtsystems
|
||||
|
||||
> **Hinweis (2026-07-05):** Beschreibt das **Zielbild**, nicht den Implementierungsstand. Ist-Stand: [`Kairo_Implementation_Truth_Table_v0.1.md`](../product/Kairo_Implementation_Truth_Table_v0.1.md). v0.2 wird explizite Implementierungs-Marker pro Kapitel ergänzen.
|
||||
|
||||
**Status:** konsolidiertes Zielbild / Nordstern-Dokument
|
||||
**Stand:** 2026-07-05
|
||||
**Zweck:** Beschreibung des angedachten späteren Zielzustands von Kairo als System, unabhängig von konkreten Implementierungsschnitten.
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
Kairo ist langfristig keine einfache Aufgabenliste, keine reine Projektmanagement-App, kein Roadmap-Tool und keine freie Workflow-Automatisierungsplattform.
|
||||
|
||||
Kairo ist eine:
|
||||
|
||||
```text
|
||||
adaptive, methodengeführte Entwicklungs- und Steuerungsplattform
|
||||
```
|
||||
|
||||
Der Kern ist ein:
|
||||
|
||||
```text
|
||||
Method-driven Adaptive Steering Core
|
||||
```
|
||||
|
||||
Kairo soll unterschiedliche Entwicklungs- und Steuerungskontexte führen können:
|
||||
|
||||
```text
|
||||
- Software- und Produktentwicklung
|
||||
- Buch- und Content-Entwicklung
|
||||
- Programmsteuerung
|
||||
- Projekt- und Initiativensteuerung
|
||||
- persönliche Entwicklung
|
||||
- Reifegradentwicklung
|
||||
- Lernpfade
|
||||
- Routinen / Betrieb
|
||||
- Review- und Auditkontexte
|
||||
- Agentenläufe
|
||||
- KI-/Tool-gestützte Steuerung
|
||||
```
|
||||
|
||||
Die zentrale Leitfrage lautet:
|
||||
|
||||
```text
|
||||
Welcher nächste Schritt bringt diesen steuerbaren Kontext jetzt am wirksamsten voran?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Grundverständnis
|
||||
|
||||
Kairo steuert nicht nur Aufgaben.
|
||||
|
||||
Kairo steuert Entwicklungen.
|
||||
|
||||
Eine Entwicklung kann sein:
|
||||
|
||||
```text
|
||||
- ein Produkt
|
||||
- ein Programm
|
||||
- ein Projekt
|
||||
- eine Initiative
|
||||
- ein Buch
|
||||
- eine Fähigkeit
|
||||
- ein Reifegradziel
|
||||
- eine Routine
|
||||
- ein Review
|
||||
- ein Audit
|
||||
- ein Agentenauftrag
|
||||
```
|
||||
|
||||
Kairo hält dabei fest:
|
||||
|
||||
```text
|
||||
- Was soll entwickelt werden?
|
||||
- Warum ist es relevant?
|
||||
- Welche Methode gilt?
|
||||
- Welche Struktur braucht diese Methode?
|
||||
- Wo steht der Kontext aktuell?
|
||||
- Was fehlt?
|
||||
- Was blockiert?
|
||||
- Was braucht Aufmerksamkeit?
|
||||
- Was ist der nächste wirksame Schritt?
|
||||
- Wer oder welcher Agent soll handeln?
|
||||
- Worauf wartet Kairo?
|
||||
- Welche Nachweise, Reviews oder Entscheidungen sind nötig?
|
||||
- Wann wird angepasst, eskaliert oder abgeschlossen?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Produktidentität
|
||||
|
||||
Kairo ist:
|
||||
|
||||
```text
|
||||
System of Record
|
||||
Steering Authority
|
||||
Actor-/Tenant-sicherer Kontextgeber
|
||||
methodengeführter Steuerungskern
|
||||
Roadmap- und Entwicklungsstrukturmodell
|
||||
Signal- und NextAction-System
|
||||
später Workflow-/Agenten-/Tool-orchestrierend
|
||||
```
|
||||
|
||||
Kairo ist nicht:
|
||||
|
||||
```text
|
||||
freie Workflow-Plattform
|
||||
beliebiger Automatisierungsbaukasten
|
||||
reines Projektmanagementsystem
|
||||
reine To-do-Liste
|
||||
reines Roadmap-Tool
|
||||
reine KI-Agentenplattform
|
||||
reines Prompt-System
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Kernmodell
|
||||
|
||||
Das Zielmodell:
|
||||
|
||||
```text
|
||||
Steerable Object
|
||||
→ Steering Context
|
||||
→ Steering Method
|
||||
→ Standard Lifecycle / Method Lifecycle
|
||||
→ Hook Slugs
|
||||
→ Structure Builder
|
||||
→ Signal Rules
|
||||
→ NextAction Strategy
|
||||
→ Assignment Strategy
|
||||
→ Waiting / Reminder / Escalation Strategy
|
||||
→ Result Intake
|
||||
→ Evidence / Review / Decision
|
||||
→ Adaptation / Closure
|
||||
→ optionale Workflow-Fragmente
|
||||
→ optionale Human / Agent / LLM / Tool Steps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Method-driven Adaptive Steering Core
|
||||
|
||||
Der Adaptive Steering Core ist der fachliche und technische Kern von Kairo.
|
||||
|
||||
Er führt steuerbare Kontexte durch methodengeführte Steuerungsabläufe.
|
||||
|
||||
Typischer Ablauf:
|
||||
|
||||
```text
|
||||
1. Ziel / Entwicklungsabsicht erfassen
|
||||
2. Name, Scope und Kontext definieren
|
||||
3. passende Basismethode wählen oder vorschlagen
|
||||
4. gemäß Methode eine Steuerungsstruktur erzeugen
|
||||
- Roadmap
|
||||
- Backlog
|
||||
- WBS
|
||||
- Reifegradpfad
|
||||
- Kapitelstruktur
|
||||
- Feature Landscape
|
||||
- WorkCycles
|
||||
- Review Gates
|
||||
5. Next Best Action ableiten
|
||||
6. Actor zuweisen
|
||||
7. auf Ergebnis, Rückmeldung, Termin oder Ereignis warten
|
||||
8. erinnern, eskalieren oder nachsteuern
|
||||
9. Ergebnis zurückführen
|
||||
10. prüfen, reviewen, adaptieren oder abschließen
|
||||
```
|
||||
|
||||
Dieser Ablauf ist der methodengeführte Steuerungsworkflow.
|
||||
|
||||
Er ist nicht gleichbedeutend mit einer freien technischen Workflow Engine.
|
||||
|
||||
---
|
||||
|
||||
## 6. Standard Lifecycle
|
||||
|
||||
Kairo besitzt einen minimalen Standard Lifecycle als gemeinsame Basis.
|
||||
|
||||
```text
|
||||
intake
|
||||
method_selection
|
||||
structure_setup
|
||||
planning
|
||||
action_selection
|
||||
assignment
|
||||
waiting
|
||||
result_intake
|
||||
validation
|
||||
review
|
||||
adaptation
|
||||
closure
|
||||
```
|
||||
|
||||
Methoden können diesen Lifecycle:
|
||||
|
||||
```text
|
||||
- verwenden
|
||||
- teilweise überspringen
|
||||
- spezialisieren
|
||||
- erweitern
|
||||
- eigene Hooks ergänzen
|
||||
```
|
||||
|
||||
Der Standard Lifecycle ist kein starrer Projektprozess, sondern ein gemeinsames Steuerungsraster.
|
||||
|
||||
---
|
||||
|
||||
## 7. Steering Methods
|
||||
|
||||
Eine Methode ist kein Label, sondern ein registriertes Steuerungspaket.
|
||||
|
||||
Eine Methode definiert:
|
||||
|
||||
```text
|
||||
- supported_domains
|
||||
- supported_scope_types
|
||||
- default_lifecycle
|
||||
- required_structures
|
||||
- allowed_structures
|
||||
- hook_slugs
|
||||
- structure_builders
|
||||
- attention_rule_providers
|
||||
- next_action_strategy
|
||||
- assignment_strategy
|
||||
- waiting_strategy
|
||||
- reminder_strategy
|
||||
- escalation_strategy
|
||||
- result_intake_strategy
|
||||
- review_strategy
|
||||
- evidence_policy
|
||||
- closure_policy
|
||||
- allowed_workflow_fragments
|
||||
- allowed_node_types
|
||||
- default_configuration
|
||||
```
|
||||
|
||||
Methoden werden zunächst built-in und code-first angelegt, später versioniert und begrenzt konfigurierbar.
|
||||
|
||||
Langfristig können Method Profiles entstehen.
|
||||
|
||||
---
|
||||
|
||||
## 8. Method Registry
|
||||
|
||||
Kairo benötigt eine Method Registry.
|
||||
|
||||
Sie funktioniert ähnlich einem Widget-System:
|
||||
|
||||
```text
|
||||
Eine Methode meldet sich mit Slug, Version, unterstützten Domains,
|
||||
Lifecycle, Hooks, Structure Builders, Strategies und Policies an.
|
||||
```
|
||||
|
||||
Ziel:
|
||||
|
||||
```text
|
||||
Neue Methoden sollen ergänzt werden können,
|
||||
ohne den Core jedes Mal umzubauen.
|
||||
```
|
||||
|
||||
Beispiele für Methoden:
|
||||
|
||||
```text
|
||||
simple_action_driven
|
||||
product_milestone_driven
|
||||
backlog_driven
|
||||
wbs_driven
|
||||
cycle_based
|
||||
content_chapter_based
|
||||
maturity_progression
|
||||
routine_control
|
||||
review_driven
|
||||
audit_driven
|
||||
agent_controlled
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Steering Domains
|
||||
|
||||
Kairo unterstützt unterschiedliche Steuerungsdomänen.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
program
|
||||
project
|
||||
product_development
|
||||
content_development
|
||||
personal_development
|
||||
maturity_development
|
||||
routine_operations
|
||||
audit_review
|
||||
agent_execution
|
||||
custom
|
||||
```
|
||||
|
||||
Jede Domain kann eigene typische Lifecycles, Roadmap-Strukturen, Methoden, Hooks und Signals haben.
|
||||
|
||||
---
|
||||
|
||||
## 10. Steerable Objects
|
||||
|
||||
Steuerbar sind nicht nur Initiativen.
|
||||
|
||||
Mögliche steuerbare Objekte:
|
||||
|
||||
```text
|
||||
program
|
||||
initiative
|
||||
project
|
||||
roadmap
|
||||
roadmap_item
|
||||
backlog_item
|
||||
action
|
||||
blocker
|
||||
review
|
||||
evidence
|
||||
decision
|
||||
recurring_element
|
||||
work_cycle
|
||||
agent_run
|
||||
custom
|
||||
```
|
||||
|
||||
Diese Objekte werden über Steering Contexts an Methoden und Domains gebunden.
|
||||
|
||||
---
|
||||
|
||||
## 11. Steering Context
|
||||
|
||||
Ein Steering Context beschreibt:
|
||||
|
||||
```text
|
||||
Für welches steuerbare Objekt gilt welche Methode, Domain und Lifecycle-Logik?
|
||||
```
|
||||
|
||||
Konzeptuell:
|
||||
|
||||
```text
|
||||
SteeringContext
|
||||
- tenant_id
|
||||
- scope_type
|
||||
- scope_id
|
||||
- steering_domain
|
||||
- lifecycle_model
|
||||
- steering_method
|
||||
- method_profile_id optional
|
||||
- method_version
|
||||
- configuration_json
|
||||
- inherits_from_parent
|
||||
- is_active
|
||||
```
|
||||
|
||||
Untergeordnete Objekte können den Steering Context ihres Parents erben oder überschreiben.
|
||||
|
||||
---
|
||||
|
||||
## 12. Roadmap / Development Model
|
||||
|
||||
Roadmap ist ein Kernmodell, nicht nur eine UI-Ansicht.
|
||||
|
||||
Kairo braucht Roadmaps, um Entwicklungsrichtung und Entwicklungsstruktur abzubilden.
|
||||
|
||||
Roadmap-Struktur:
|
||||
|
||||
```text
|
||||
Roadmap
|
||||
→ Roadmap Lane
|
||||
→ Roadmap Item
|
||||
```
|
||||
|
||||
RoadmapItems können sein:
|
||||
|
||||
```text
|
||||
milestone
|
||||
maturity_stage
|
||||
feature
|
||||
capability
|
||||
phase
|
||||
release
|
||||
chapter
|
||||
research_topic
|
||||
work_cycle
|
||||
learning_step
|
||||
review_gate
|
||||
decision_gate
|
||||
architecture_step
|
||||
dependency
|
||||
risk_reduction
|
||||
custom
|
||||
```
|
||||
|
||||
Entscheidung:
|
||||
|
||||
```text
|
||||
Milestone = RoadmapItem(type = milestone)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 13. Roadmap vs. Backlog vs. Action
|
||||
|
||||
Zentrale Unterscheidung:
|
||||
|
||||
```text
|
||||
RoadmapItem = Entwicklungsziel / Orientierung / geplanter Entwicklungsschritt
|
||||
BacklogItem = konkreter möglicher Handlungsbedarf
|
||||
Action = freigegebene operative Maßnahme
|
||||
```
|
||||
|
||||
Beispiel Softwareentwicklung:
|
||||
|
||||
```text
|
||||
RoadmapItem:
|
||||
Attention Engine regelbasiert
|
||||
|
||||
BacklogItems:
|
||||
- Attention DTO definieren
|
||||
- Blockierte Maßnahmen auswerten
|
||||
- Widget bauen
|
||||
|
||||
Actions:
|
||||
- Endpoint implementieren
|
||||
- Tests schreiben
|
||||
```
|
||||
|
||||
Beispiel Buchentwicklung:
|
||||
|
||||
```text
|
||||
RoadmapItem:
|
||||
Kapitel 3 – Argumentation ausarbeiten
|
||||
|
||||
BacklogItems:
|
||||
- Recherche zur These prüfen
|
||||
- Beispiel suchen
|
||||
- Rohfassung schreiben
|
||||
|
||||
Actions:
|
||||
- Heute Abschnitt 3.1 entwerfen
|
||||
```
|
||||
|
||||
Beispiel Reifegradentwicklung:
|
||||
|
||||
```text
|
||||
RoadmapItem:
|
||||
Reifegrad: stabile Seitkick-Beweglichkeit
|
||||
|
||||
BacklogItems:
|
||||
- Hüftmobilität prüfen
|
||||
- Dehnroutine auswählen
|
||||
- Technikvideo aufnehmen
|
||||
|
||||
Actions:
|
||||
- 10 Minuten Mobility durchführen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. Structure Builder
|
||||
|
||||
Structure Builder erzeugen methodenspezifische Steuerungsstrukturen.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
roadmap_builder
|
||||
milestone_plan_builder
|
||||
feature_landscape_builder
|
||||
wbs_builder
|
||||
backlog_builder
|
||||
maturity_path_builder
|
||||
chapter_structure_builder
|
||||
cycle_structure_builder
|
||||
review_gate_builder
|
||||
routine_structure_builder
|
||||
```
|
||||
|
||||
Sie sind zentrale Erweiterungspunkte für Methoden.
|
||||
|
||||
Ein Structure Builder legt z. B. an:
|
||||
|
||||
```text
|
||||
- Roadmap
|
||||
- Roadmap Lanes
|
||||
- Roadmap Items
|
||||
- initiale BacklogItems
|
||||
- Review Gates
|
||||
- WorkCycles
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. Hooks
|
||||
|
||||
Hooks sind stabile Einhängepunkte in Steuerungsabläufen.
|
||||
|
||||
Beispiele:
|
||||
|
||||
```text
|
||||
on_goal_captured
|
||||
on_scope_named
|
||||
on_method_selection_required
|
||||
on_method_selected
|
||||
on_structure_required
|
||||
on_roadmap_required
|
||||
on_backlog_required
|
||||
on_wbs_required
|
||||
on_maturity_path_required
|
||||
on_content_structure_required
|
||||
on_plan_required
|
||||
on_dependency_analysis_required
|
||||
on_dod_definition_required
|
||||
on_next_action_requested
|
||||
on_assignment_required
|
||||
on_wait_started
|
||||
on_due_date_reached
|
||||
on_result_overdue
|
||||
on_reminder_required
|
||||
on_escalation_required
|
||||
on_result_received
|
||||
on_evidence_required
|
||||
on_review_due
|
||||
on_reassessment_required
|
||||
on_replan_required
|
||||
on_closure_requested
|
||||
```
|
||||
|
||||
An Hooks können später kleine Workflow-Fragmente, Rules, Prompts, Agent Steps oder Tool Steps gebunden werden.
|
||||
|
||||
Hooks sind nicht beliebige technische Events, sondern fachlich stabile Steuerungspunkte.
|
||||
|
||||
---
|
||||
|
||||
## 16. Strategies
|
||||
|
||||
Methoden bringen oder referenzieren Strategies.
|
||||
|
||||
Zentrale Strategy-Typen:
|
||||
|
||||
```text
|
||||
NextActionStrategy
|
||||
AttentionRuleProvider
|
||||
AssignmentStrategy
|
||||
WaitingStrategy
|
||||
ReminderStrategy
|
||||
EscalationStrategy
|
||||
ResultIntakeStrategy
|
||||
EvidencePolicy
|
||||
ReviewStrategy
|
||||
ClosurePolicy
|
||||
```
|
||||
|
||||
Diese verhindern, dass methodenspezifische Logik monolithisch im Core wächst.
|
||||
|
||||
---
|
||||
|
||||
## 17. Signals
|
||||
|
||||
Signals sind sichtbare Ausgaben des Steuerungskerns.
|
||||
|
||||
Signal Types:
|
||||
|
||||
```text
|
||||
attention
|
||||
next_action
|
||||
review_due
|
||||
evidence_required
|
||||
escalation
|
||||
blocker_signal
|
||||
progress_signal
|
||||
risk_signal
|
||||
decision_required
|
||||
dependency_signal
|
||||
dod_signal
|
||||
workflow_trigger
|
||||
```
|
||||
|
||||
### Attention
|
||||
|
||||
Beantwortet:
|
||||
|
||||
```text
|
||||
Was braucht Aufmerksamkeit?
|
||||
```
|
||||
|
||||
### NextActionCandidate
|
||||
|
||||
Beantwortet:
|
||||
|
||||
```text
|
||||
Was ist der nächste wirksame Schritt?
|
||||
```
|
||||
|
||||
Signals müssen erklärbar sein:
|
||||
|
||||
```text
|
||||
- warum erzeugt?
|
||||
- durch welche Methode?
|
||||
- durch welchen Hook?
|
||||
- auf welchen Scope bezogen?
|
||||
- welche Datenquelle?
|
||||
- welche empfohlene Handlung?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 18. Assignment / Waiting / Reminder / Escalation
|
||||
|
||||
Der Steuerungskern endet nicht mit dem Erzeugen einer Action.
|
||||
|
||||
Kairo muss steuern:
|
||||
|
||||
```text
|
||||
- Actor auswählen
|
||||
- Actor zuweisen
|
||||
- auf Ergebnis warten
|
||||
- Fälligkeit überwachen
|
||||
- erinnern
|
||||
- eskalieren
|
||||
- externe Ereignisse aufnehmen
|
||||
- Agentenergebnisse zurückführen
|
||||
```
|
||||
|
||||
Actors können sein:
|
||||
|
||||
```text
|
||||
human
|
||||
agent
|
||||
working_group
|
||||
external_system
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 19. Result Intake / Evidence / Review / Decision
|
||||
|
||||
Kairo führt Ergebnisse zurück und entscheidet, was daraus folgt.
|
||||
|
||||
Mögliche Rückführungen:
|
||||
|
||||
```text
|
||||
- Action erledigt
|
||||
- Ergebnis unvollständig
|
||||
- Evidence erforderlich
|
||||
- Review erforderlich
|
||||
- Decision erforderlich
|
||||
- Blocker entstanden
|
||||
- RoadmapItem erreicht
|
||||
- Reifegrad plausibel erhöht
|
||||
- neue NextAction nötig
|
||||
```
|
||||
|
||||
Evidence, Reviews und Decisions sind zentrale Qualitätssicherungs- und Steuerungsobjekte.
|
||||
|
||||
---
|
||||
|
||||
## 20. Workflow-Fragmente und Runtime
|
||||
|
||||
Kairo soll langfristig Workflow-Fähigkeit haben.
|
||||
|
||||
Aber:
|
||||
|
||||
```text
|
||||
Workflows sind methodengeführte Steuerungsabläufe,
|
||||
keine beliebige freie Automatisierungsplattform als Produktkern.
|
||||
```
|
||||
|
||||
Zielmodell:
|
||||
|
||||
```text
|
||||
Hook
|
||||
→ Workflow Fragment
|
||||
→ Node / Step
|
||||
→ Result
|
||||
→ Rückführung in Kairo
|
||||
```
|
||||
|
||||
Workflow-Fragmente können später enthalten:
|
||||
|
||||
```text
|
||||
human_task
|
||||
approval
|
||||
decision_gate
|
||||
review
|
||||
reflection
|
||||
llm_prompt
|
||||
agent_task
|
||||
tool_call
|
||||
state_transition
|
||||
evidence_check
|
||||
dod_check
|
||||
dependency_analysis
|
||||
notification
|
||||
reminder
|
||||
escalation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 21. Agenten / LLMs / Tools
|
||||
|
||||
Kairo bleibt Steering Authority.
|
||||
|
||||
Agenten, LLMs und Tools sind Provider.
|
||||
|
||||
Sie können später an Hooks und Workflow-Fragmente angebunden werden.
|
||||
|
||||
Grundsatz:
|
||||
|
||||
```text
|
||||
Kairo entscheidet Kontext, Methode, Auftrag und Rückführung.
|
||||
Agenten / LLMs / Tools führen einzelne Steps aus.
|
||||
```
|
||||
|
||||
Agenten sind Actors.
|
||||
|
||||
Das ist wichtig für:
|
||||
|
||||
```text
|
||||
- Verantwortlichkeit
|
||||
- Audit
|
||||
- Assignments
|
||||
- Sichtbarkeit
|
||||
- Tenant-Kontext
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 22. Security / Governance / Audit
|
||||
|
||||
Kairo muss tenant- und actor-sicher bleiben.
|
||||
|
||||
Grundsätze:
|
||||
|
||||
```text
|
||||
- tenant_id immer aus TenantContext
|
||||
- keine tenant_id aus Client Input vertrauen
|
||||
- Actor-Bezüge tenant-intern validieren
|
||||
- Capabilities prüfen
|
||||
- Router dünn
|
||||
- Services schreiben
|
||||
- Data Layer liest
|
||||
- Audit-by-design
|
||||
- Signals und NextActions erklärbar
|
||||
- Agentenaktionen nachvollziehbar
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 23. UI-Zielbild
|
||||
|
||||
Die UI dient als Steuerungs- und Interaktionsschicht.
|
||||
|
||||
Langfristige Views:
|
||||
|
||||
```text
|
||||
Workspace
|
||||
Steering View
|
||||
Roadmap View
|
||||
Method View
|
||||
Attention / NextAction View
|
||||
Backlog View
|
||||
Action View
|
||||
Waiting / Reminder View
|
||||
Evidence / Review / Decision View
|
||||
Workflow Run View später
|
||||
Method/Profile Admin später
|
||||
Agent Run View später
|
||||
```
|
||||
|
||||
Die UI darf nicht die Methode hart kodieren.
|
||||
|
||||
Sie muss methodenbewusst und strukturgetrieben sein.
|
||||
|
||||
---
|
||||
|
||||
## 24. Architektur-Evolutionslinie
|
||||
|
||||
Grobe Evolutionslinie:
|
||||
|
||||
```text
|
||||
1. Existing Foundation
|
||||
2. Adaptive Steering Core Foundation
|
||||
3. Method Registry / Hook Registry / Standard Lifecycle
|
||||
4. Roadmap / Structure Builder Foundation
|
||||
5. Signal / NextAction Engine
|
||||
6. Assignment / Waiting / Reminder / Escalation
|
||||
7. Evidence / Review / Decision
|
||||
8. Workflow Fragments and Bindings
|
||||
9. Workflow Runtime
|
||||
10. Agent / LLM / Tool Providers
|
||||
11. Method Profiles
|
||||
12. Method Designer / Advanced Configuration
|
||||
13. Advanced AI Steering / Next Best Action Ranking
|
||||
```
|
||||
|
||||
Dies ist keine Sprintplanung, sondern ein Zielbild der technischen Entwicklung.
|
||||
|
||||
---
|
||||
|
||||
## 25. Zielzustand in einem Satz
|
||||
|
||||
Kairo soll ein methodengeführter adaptiver Steuerungskern werden, der Entwicklungen unterschiedlichster Art über registrierbare Methoden, gemeinsame Kernstrukturen, Roadmaps, Hooks, Signals, NextActions, Assignments, Waiting-/Reminder-/Escalation-Mechanismen und später Agent-/Workflow-Fragmente wirksam und nachvollziehbar steuert.
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
# KAIRO-ARCH-01 – Zielarchitektur für den methodengeführten adaptiven Steuerungskern
|
||||
## v0.2 – schlanker Architekturauftrag
|
||||
|
||||
**Status:** Auftrag an Coding-/Architektur-Agent
|
||||
**Ziel:** technische Zielarchitektur, keine Implementierung
|
||||
**Wichtig:** Dieser Auftrag ersetzt die überdetaillierte Fassung `v0.1` als führenden Prompt.
|
||||
|
||||
---
|
||||
|
||||
## 1. Kontext
|
||||
|
||||
Kairo soll langfristig keine einfache Aufgaben-, Projekt- oder Roadmap-App sein.
|
||||
|
||||
Kairo soll eine adaptive, methodengeführte Entwicklungs- und Steuerungsplattform werden.
|
||||
|
||||
Der bisherige Slice `Initiative → Action` ist als technischer Startpunkt gültig, aber als Zielarchitektur zu flach.
|
||||
|
||||
Kairo soll unterschiedliche Arten von Entwicklungen steuern können, z. B.:
|
||||
|
||||
- Software- und Produktentwicklung
|
||||
- Buchentwicklung
|
||||
- Programm- und Initiativensteuerung
|
||||
- persönliche Entwicklung
|
||||
- Reifegradentwicklung
|
||||
- Routinen / Betrieb
|
||||
- Review- und Auditkontexte
|
||||
- später auch KI-/Agenten-gestützte Steuerung
|
||||
|
||||
---
|
||||
|
||||
## 2. Verbindliche fachliche Grundlagen
|
||||
|
||||
Lies zuerst:
|
||||
|
||||
```text
|
||||
docs/architecture/Kairo_Core_Model_Decision_v0.2.md
|
||||
docs/architecture/Kairo_Method_Design_Principles_v0.1.md
|
||||
```
|
||||
|
||||
Berücksichtige zusätzlich den bestehenden Produkt- und Architekturstand im Repo, insbesondere:
|
||||
|
||||
```text
|
||||
docs/product/Kairo_Product_Definition_and_MVP_Reset_v0.1.md
|
||||
docs/product/Kairo_Canonical_Operating_Model_v0.1.md
|
||||
docs/product/Kairo_Corrected_MVP_Roadmap_v0.1.md
|
||||
docs/architecture/Kairo_Tenant_Invariants_v0.1.md
|
||||
docs/sprints/Sprint0_AP0_7_Completion_Report_v0.2.md
|
||||
```
|
||||
|
||||
Falls Dokumente fehlen, liste sie im Abschlussbericht auf und arbeite mit den vorhandenen Grundlagen weiter.
|
||||
|
||||
---
|
||||
|
||||
## 3. Ziel dieses Auftrags
|
||||
|
||||
Erarbeite eine technische Zielarchitektur für Kairo als:
|
||||
|
||||
```text
|
||||
Method-driven Adaptive Steering Platform
|
||||
```
|
||||
|
||||
Es geht ausdrücklich nicht um die nächste Implementierung, nicht um AP0.8 und nicht um MVP-Minimierung.
|
||||
|
||||
Es geht um den technischen Nordstern:
|
||||
|
||||
```text
|
||||
Wie muss Kairo grundsätzlich aufgebaut sein, damit unterschiedliche Steuerungsmethoden langfristig ergänzt, weiterentwickelt, konfiguriert und ausgeführt werden können, ohne den Core ständig umzubauen?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Fachliche Kernanforderung
|
||||
|
||||
Die Zielarchitektur muss erklären, wie Kairo diesen methodengeführten Steuerungsablauf unterstützt:
|
||||
|
||||
```text
|
||||
1. Ziel / Entwicklungsabsicht erfassen
|
||||
2. Name, Scope und Kontext definieren
|
||||
3. passende Basismethode wählen oder vorschlagen
|
||||
4. gemäß Methode eine Steuerungsstruktur erzeugen
|
||||
- z. B. Roadmap, Backlog, WBS, Reifegradpfad, Kapitelstruktur, WorkCycles
|
||||
5. Next Best Action ableiten
|
||||
6. Actor zuweisen
|
||||
- human, agent, working_group oder external_system
|
||||
7. auf Ergebnis, Rückmeldung, Termin oder Ereignis warten
|
||||
8. erinnern, eskalieren oder nachsteuern
|
||||
9. Ergebnis zurückführen
|
||||
10. prüfen, reviewen, adaptieren oder abschließen
|
||||
```
|
||||
|
||||
Dieser Ablauf ist als methodengeführter Steuerungsworkflow zu verstehen, nicht als freie generische Automatisierungsplattform.
|
||||
|
||||
---
|
||||
|
||||
## 5. Kritische Leitfrage
|
||||
|
||||
Prüfe und beantworte kritisch:
|
||||
|
||||
```text
|
||||
Soll Kairo im Kern eine freie Workflow Engine sein,
|
||||
oder ein methodengeführter adaptiver Steuerungskern,
|
||||
an den später Workflow-Fragmente, Agenten, LLMs und Tools angebunden werden können?
|
||||
```
|
||||
|
||||
Die fachliche Präferenz lautet:
|
||||
|
||||
```text
|
||||
Kairo soll kein freier Workflow-Baukasten sein.
|
||||
Kairo soll einen methodengeführten Steuerungskern haben.
|
||||
Methoden sollen sich wie registrierbare Erweiterungen anmelden können.
|
||||
Hooks sind stabile Einhängepunkte.
|
||||
Workflow-Fragmente, Agenten, LLMs und Tools werden später an diese Hooks gebunden.
|
||||
```
|
||||
|
||||
Bestätige diese Präferenz nur, wenn sie aus Sicht der bestehenden Codebase und Architektur tragfähig ist. Falls eine bessere Zielarchitektur naheliegt, beschreibe und begründe sie.
|
||||
|
||||
---
|
||||
|
||||
## 6. Erwartete Architekturfragen
|
||||
|
||||
Entwickle eine Zielarchitektur zu folgenden Fragen.
|
||||
|
||||
### 6.1 Core-Verantwortung
|
||||
|
||||
Was ist der stabile Kairo-Core?
|
||||
|
||||
Welche Verantwortung gehört in den Core, welche in Methoden, welche in spätere Workflow-/Agenten-/Provider-Schichten?
|
||||
|
||||
### 6.2 Methoden-Erweiterbarkeit
|
||||
|
||||
Wie können neue Methoden ergänzt werden, ohne den Core jedes Mal umzubauen?
|
||||
|
||||
Berücksichtige fachlich:
|
||||
|
||||
```text
|
||||
Method Registry
|
||||
Method Definition
|
||||
Method Versioning
|
||||
Method Profiles
|
||||
Hook Slugs
|
||||
Structure Builder
|
||||
Strategies
|
||||
Signal Rules
|
||||
```
|
||||
|
||||
Du musst diese Begriffe nicht exakt übernehmen, wenn die bestehende Architektur eine bessere Lösung nahelegt. Wichtig ist die Fähigkeit: Methoden müssen registrierbar, versionierbar, testbar und später begrenzt konfigurierbar sein.
|
||||
|
||||
### 6.3 Gemeinsame Kernstrukturen
|
||||
|
||||
Welche zentralen Strukturen brauchen alle oder die meisten Methoden?
|
||||
|
||||
Zu prüfen sind insbesondere:
|
||||
|
||||
```text
|
||||
Steering Context
|
||||
Roadmap / Roadmap Items
|
||||
Backlog
|
||||
Actions / Assignments
|
||||
Blocker
|
||||
Signals / Attention / NextAction
|
||||
Evidence
|
||||
Reviews
|
||||
Decisions
|
||||
Waiting / Reminder / Escalation
|
||||
```
|
||||
|
||||
Entscheide, welche davon Core-Strukturen sind und welche methodenspezifisch bleiben sollten.
|
||||
|
||||
### 6.4 Minimaler Standard Lifecycle
|
||||
|
||||
Prüfe, ob ein minimaler Standard Lifecycle als gemeinsame Basis sinnvoll ist.
|
||||
|
||||
Fachlicher Vorschlag:
|
||||
|
||||
```text
|
||||
intake
|
||||
method_selection
|
||||
structure_setup
|
||||
planning
|
||||
action_selection
|
||||
assignment
|
||||
waiting
|
||||
result_intake
|
||||
validation
|
||||
review
|
||||
adaptation
|
||||
closure
|
||||
```
|
||||
|
||||
Bewerte:
|
||||
|
||||
```text
|
||||
Ist dieser Lifecycle als Basismodell tragfähig?
|
||||
Welche Teile gehören in den Core?
|
||||
Welche Teile sollten Methoden überschreiben oder spezialisieren können?
|
||||
Wie lassen sich Softwareentwicklung, Buchentwicklung und Reifegradentwicklung damit abbilden?
|
||||
```
|
||||
|
||||
### 6.5 Hooks und Steuerungsabläufe
|
||||
|
||||
Wie sollten Hooks technisch modelliert werden?
|
||||
|
||||
Hooks sollen stabile Einhängepunkte sein, z. B.:
|
||||
|
||||
```text
|
||||
on_goal_captured
|
||||
on_method_selected
|
||||
on_structure_required
|
||||
on_next_action_requested
|
||||
on_assignment_required
|
||||
on_wait_started
|
||||
on_result_received
|
||||
on_evidence_required
|
||||
on_review_due
|
||||
on_replan_required
|
||||
on_closure_requested
|
||||
```
|
||||
|
||||
Prüfe:
|
||||
|
||||
```text
|
||||
Soll es eine Hook Registry geben?
|
||||
Wie werden Hooks versioniert?
|
||||
Wie registrieren Methoden Logik an Hooks?
|
||||
Wie werden spätere Workflow-Fragmente angebunden?
|
||||
Wie bleibt das testbar und erklärbar?
|
||||
```
|
||||
|
||||
### 6.6 Structure Builder
|
||||
|
||||
Methoden müssen unterschiedliche Steuerungsstrukturen erzeugen können:
|
||||
|
||||
```text
|
||||
Roadmap / Meilensteinplan
|
||||
Backlog
|
||||
WBS
|
||||
Reifegradpfad
|
||||
Kapitelstruktur
|
||||
Feature Landscape
|
||||
WorkCycles
|
||||
Review Gates
|
||||
```
|
||||
|
||||
Entwirf eine Architektur, wie solche Structure Builder methodenspezifisch, aber core-kompatibel eingebunden werden können.
|
||||
|
||||
### 6.7 Signals und Next Best Action
|
||||
|
||||
Kairo muss methodenspezifisch ableiten können:
|
||||
|
||||
```text
|
||||
Was braucht Aufmerksamkeit?
|
||||
Was ist der nächste wirksame Schritt?
|
||||
```
|
||||
|
||||
Beschreibe die Zielarchitektur für:
|
||||
|
||||
```text
|
||||
Attention
|
||||
NextActionCandidates
|
||||
Signal Rules
|
||||
methodenspezifische Strategien
|
||||
Erklärbarkeit
|
||||
Ranking / Priorisierung später
|
||||
```
|
||||
|
||||
### 6.8 Assignment, Waiting, Reminder und Escalation
|
||||
|
||||
Der Steuerungskern darf nicht bei „Action erzeugt“ enden.
|
||||
|
||||
Er muss abbilden können:
|
||||
|
||||
```text
|
||||
Actor zuweisen
|
||||
auf Ergebnis warten
|
||||
Fälligkeit überwachen
|
||||
erinnern
|
||||
eskalieren
|
||||
externe Ereignisse oder Agentenergebnisse aufnehmen
|
||||
```
|
||||
|
||||
Beschreibe, welche Architektur dafür langfristig nötig ist.
|
||||
|
||||
### 6.9 Workflow-Fragmente und spätere Runtime
|
||||
|
||||
Beschreibe die Rolle einer späteren technischen Workflow Runtime.
|
||||
|
||||
Wichtig:
|
||||
|
||||
```text
|
||||
Die Runtime soll methodengeführte Steuerungsabläufe unterstützen.
|
||||
Sie soll nicht als beliebiger freier Workflow-Baukasten den Kairo-Core ersetzen.
|
||||
```
|
||||
|
||||
Kläre:
|
||||
|
||||
```text
|
||||
Was ist Core-Logik?
|
||||
Was ist Methode?
|
||||
Was ist Hook?
|
||||
Was ist Workflow-Fragment?
|
||||
Was ist spätere Runtime?
|
||||
Wie werden LLM-/Agent-/Tool-Steps angebunden?
|
||||
```
|
||||
|
||||
### 6.10 Agenten, LLMs und Tools
|
||||
|
||||
Kairo soll später Agenten, LLMs und Tools nutzen können.
|
||||
|
||||
Kläre:
|
||||
|
||||
```text
|
||||
Bleibt Kairo Steering Authority?
|
||||
Sind Agenten Provider oder eigenständige Steuerungsinstanzen?
|
||||
Wie werden Agenten als Actors eingebunden?
|
||||
Wie werden Ergebnisse zurückgeführt?
|
||||
Wie werden Freigaben, Audit und Fehler behandelt?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Erwartetes Ergebnis
|
||||
|
||||
Erstelle ein Architektur-Dokument:
|
||||
|
||||
```text
|
||||
docs/architecture/Kairo_Target_Architecture_Method_Driven_Adaptive_Steering_Core_v0.1.md
|
||||
```
|
||||
|
||||
Das Dokument soll eine konsistente Zielarchitektur darstellen, keine bloße Checkliste.
|
||||
|
||||
Es soll mindestens enthalten:
|
||||
|
||||
```markdown
|
||||
# Kairo Target Architecture – Method-driven Adaptive Steering Core v0.1
|
||||
|
||||
## 1. Executive Summary
|
||||
## 2. Fachliches Zielbild
|
||||
## 3. Bewertung: Workflow Engine vs. methodengeführter Steuerungskern
|
||||
## 4. Zielarchitektur im Überblick
|
||||
## 5. Core-Verantwortung und Abgrenzung
|
||||
## 6. Methodenarchitektur und Erweiterbarkeit
|
||||
## 7. Standard Lifecycle und Hooks
|
||||
## 8. Structure Builder
|
||||
## 9. Gemeinsame Kernstrukturen
|
||||
## 10. Roadmap, Backlog, Action und Blocker
|
||||
## 11. Signals, Attention und Next Best Action
|
||||
## 12. Assignment, Waiting, Reminder und Escalation
|
||||
## 13. Workflow-Fragmente und spätere Runtime
|
||||
## 14. Agenten-, LLM- und Tool-Integration
|
||||
## 15. Datenmodell-Zielbild
|
||||
## 16. Modul-/Schichten-Zielbild
|
||||
## 17. Security, Tenant, Actor, Governance und Audit
|
||||
## 18. Architekturentscheidungen
|
||||
## 19. Risiken und offene Fragen
|
||||
## 20. Empfohlene nächste Schritte
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Abschlussbericht
|
||||
|
||||
Liefere zusätzlich einen Abschlussbericht:
|
||||
|
||||
```markdown
|
||||
# KAIRO-ARCH-01 – Abschlussbericht
|
||||
|
||||
## 1. Erstellte Dateien
|
||||
## 2. Wichtigste Architekturentscheidungen
|
||||
## 3. Kritische Bewertung der fachlichen Annahmen
|
||||
## 4. Empfohlene Zielarchitektur
|
||||
## 5. Was gegenüber der bisherigen Architektur geändert werden sollte
|
||||
## 6. Risiken
|
||||
## 7. Offene Entscheidungen
|
||||
## 8. Empfehlung für den nächsten Schritt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Arbeitsregel
|
||||
|
||||
Nicht vorschnell implementierungsnah werden.
|
||||
|
||||
Nutze deine Kenntnis der bestehenden Codebase und Architektur.
|
||||
|
||||
Wenn die fachlichen Vorgaben mit der bestehenden technischen Architektur kollidieren, benenne das ausdrücklich und schlage eine bessere Lösung vor.
|
||||
|
||||
Es geht um eine tragfähige Zielarchitektur, nicht um das Abarbeiten einer überdetaillierten Vorgabenliste.
|
||||
+1003
File diff suppressed because it is too large.
Load diff
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user