Compare commits

...
111 Commits
Author SHA1 Message Date
LarsandCursor a05bd34af3 feat(A1): Übungen als AP mit Wochentagsplan
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 5m3s
Test Suite / lint-backend (push) Successful in 3s
Gate- und Kit-Übungen legen ein Arbeitspaket plus Schedule an; Today zeigt nur fällige Wochentage, nicht die ganze Gate-Liste.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:06:41 +02:00
LarsandCursor ea0aa18b8d feat(schedule): einheitliche Rhythmus-Schicht an Gate und Arbeitspaket
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 49s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m57s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
Bestehende Recurring-Pfade bleiben kompatibel (interval_days-Fallback, Migration backfillt schedules), damit der aktuelle Betrieb nicht bricht und der Stand auf einem zweiten Rechner weitergebaut werden kann.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 09:23:00 +02:00
LarsandCursor 87ecee5301 feat(A1): Activity Set am Gate-Detail — Übungen an Zielzustand binden
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
Gate-Detail: Übungen anlegen mit Rhythmus, Gate aktivieren, Link zu Today. API: /roadmap-items/{id}/practices und roadmap_item_id auf Recurring-Create. Damit ist A1 ohne Starter-Kit manuell durchspielbar.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 19:36:50 +02:00
LarsandCursor 17add13d9d refactor(A1): Progression-Lanes aus Graph statt Strang=Project
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 53s
Test Suite / playwright-smoke (push) Successful in 31s
Test Suite / pytest-backend (push) Successful in 4m52s
Test Suite / lint-backend (push) Successful in 3s
Ersetzt strand_project_id/Stream-Projects in der A1-Steuerung durch graph-abgeleitete Lanes (requires-Ketten + Join). Recurring bindet nur noch am Gate; Re-Abnahme-Docs und ADP dokumentieren die Korrektur.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 18:51:17 +02:00
LarsandCursor 88a03a65f2 fix(A1): Join-Ausgaenge nach Schalten aktivieren
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m52s
Test Suite / lint-backend (push) Successful in 2s
Nach Join-reached item_by_id aktualisieren, damit _graph_ready fuer Ausgangs-Gates nicht mit veraltetem Join-Status scheitert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:54:37 +02:00
LarsandCursor cb165cd821 fix(A1): pytest Progression — legacy Stufen aus Join-Graph ausschließen
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Failing after 5m1s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
Retire Starter-Kit-Stufen ohne Strang beim Progression-Demo; active_work_gates zählt nur stranggebundene Gates wenn Join existiert. E2E-Test an maturity_transition-Struktur angepasst.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:41:28 +02:00
LarsandCursor 15f87eada2 feat(plan): Gate-Designer UX — Typ ändern, Löschen, Kanten, Status
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Macht den Zielzustands-Designer bedienbar: Overlay-Panel statt schmalem Split, Gate-Typ im Edit, Löschen mit Schutz für erreichte Gates, Kantentyp-Wechsel mit Legende und visuelle Kennzeichnung aktiv/blockiert/abgeschlossen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:39:15 +02:00
LarsandCursor b80f52cb50 feat(plan): Join-Gate im Gate-Designer für alle Archetypen
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m44s
Test Suite / lint-backend (push) Successful in 3s
Typ Join/Schaltknoten anlegbar, Detail ohne Verify, visuelle Kennzeichnung im Graph.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:17:39 +02:00
LarsandCursor 3a0ef3a734 feat(A1): Progression Join-Graph und Multi-Strang-Horizon
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 52s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 5m3s
Test Suite / lint-backend (push) Successful in 3s
join_gate, strand_project_id, Join-Auto-Schalten, multi-active Gates, Progression-Demo und PO-Lock-Spec. FE: Today strang-gruppiert, Join-Warteliste in Kontrolle.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 16:28:08 +02:00
LarsandCursor 192a65a798 fix(A1): enforce_single_active via roadmaps join (pytest)
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 1m1s
Test Suite / playwright-smoke (push) Successful in 16s
Test Suite / pytest-backend (push) Successful in 4m43s
Test Suite / lint-backend (push) Successful in 2s
roadmap_items hat kein initiative_id — Single-Active-Update join auf roadmaps. test_ap20e an Uebungssets angepasst.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 13:46:54 +02:00
LarsandCursor 19e962d8ec fix(A1): Übungen an Stufen binden, Gates entkoppeln, Tages-Abschluss
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 49s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m46s
Test Suite / lint-backend (push) Successful in 2s
Activity Set pro Stufe statt Gate-Titel-Recurring; Single-Active-Stufe bei Reopen; Complete heute schliesst Next Action; Heute-Panel fuer alle Uebungen der aktiven Stufe.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 13:00:06 +02:00
LarsandCursor b7d88ce24a feat(A1): Minimum Usability Slice — CadenceInstance, Today-Übung, Gate-Fortschritt
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
PO No-Go A1 adressieren: Tages-Tracking mit Messnotiz, Work-UI für Übung, Next-Action-Link, Gate-Fortschritt in Kontrolle, Eingang aus A1-Nav entfernt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 12:32:23 +02:00
LarsandCursor 0baa5952bc fix(AP1.7b): Audit user_id NULL bei Service-Token statt leerer UUID
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m38s
Test Suite / lint-backend (push) Successful in 2s
Operational convert-backlog und patch-recurring nutzen ctx.user_id or None;
log_audit normalisiert leere Strings fuer audit_log.user_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:33:35 +02:00
LarsandCursor 903304adf1 fix(AP1.7b): recurring-Capabilities fuer Service Tokens erlauben
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m41s
Test Suite / lint-backend (push) Successful in 3s
kairo.recurring.read/manage fehlten in ALLOWED_TOKEN_CAPABILITIES —
AP17b-Operational-Tests konnten Agent-Token nicht anlegen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:26:07 +02:00
LarsandCursor be0090d513 docs(AP2.1): MVP Validation Assignment und Report v0.3
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Failing after 4m39s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Bereitet PO-Abnahme Stufe A vor: Smoke-Checklisten fuer A1, A2, B2b+B3,
Go-Kriterien und Truth-Table/Execution-Plan auf Phase 5 aktualisiert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:19:37 +02:00
LarsandCursor 69c516dba4 feat(AP1.7b): Op-API fuer Backlog-Commit, Recurring-Status und Sprint-Zuweisung
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 52s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m37s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 18:06:46 +02:00
LarsandCursor 252b3f05f2 feat(AP1.9d, AP2.2d): Work-Default-UI, Sprint-Planung und Composition Work-Slots
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 47s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 18:05:15 +02:00
LarsandCursor 89ae15ca4c chore(seeds): Dogfooding-Seed explizit dev-only (.dev.py) und MIGRATIONS-Doku
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 18:04:52 +02:00
LarsandCursor 84d912b8ba docs(AP-BP-0): Vorhaben-Template/Blueprint Konzeption und Scope Lock
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 51s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m32s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 15:59:28 +02:00
LarsandCursor 02b6469c2d feat(AP2.2c): A1 Reifegrad E2E, Stufen-/Rhythmus-Panels und Composition-Kernel
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 15:59:18 +02:00
LarsandCursor 43d33d0edb feat(AP2.2b, UX): Linear E2E, Composition-Kernel und Steering-Paritaet
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 4m24s
Test Suite / lint-backend (push) Successful in 2s
AP2.2b: Integrationstests Neue-Kueche-Happy-Path, Truth Table und Execution Plan abgeschlossen. UX Composition Kernel (Control/Plan/Cockpit-Slots), CriticalPathPanel aus Kernel-Read-Model mit Gate-Horizont, Next Action elementgesteuert ohne Snapshot-Doppelung, Product-Continuous-Copy und Plan/Arbeit ueber Kernel planning_debt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 13:34:13 +02:00
LarsandCursor b6434bcc50 feat(steering): K-Ext-5 Portfolio-Kernel-Aggregation ueber Initiativen
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 4m14s
Test Suite / lint-backend (push) Successful in 2s
GET /api/workspace/steering; Portfolio-Widget nutzt Kernel-Attention, Vorschlaege und Agent-Slots.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 13:13:36 +02:00
LarsandCursor 390161e224 test: Assertions auf Kernel v0.4 und tech_debt-Vokabular anpassen
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 20s
Test Suite / pytest-backend (push) Successful in 4m15s
Test Suite / lint-backend (push) Successful in 2s
Behebt 6 CI-Failures nach Agent-Slots/Tech-Debt-Release.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 13:06:20 +02:00
LarsandCursor a5154cbd3b feat(steering): Kernel v0.4 Agent-Slots, Tech Debt und Review-Attention
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m15s
Test Suite / lint-backend (push) Successful in 2s
K-Ext-4/P8 deklarative Agent-Slots; P7 tech_debt Read Model und Vokabular; Review-Attention in den Kernel verlagert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:54:48 +02:00
LarsandCursor b747200f3a feat(steering): K-Ext-2 Attention-Registry, Gate/Intake-Proposals, generische UI
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 4m13s
Test Suite / lint-backend (push) Successful in 3s
Methodenuebergreifende Provider auf Kernel v0.3; verbindliche Coding Rules fuer Agenten in ADP und .cursor/rules.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:48:10 +02:00
LarsandCursor 1bbc5dbfce refactor(steering): Sprint-Vorschlaege mit austauschbarem Ranker und Abhaengigkeiten
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 4m8s
Test Suite / lint-backend (push) Successful in 2s
Keine feste Bug-zuerst-Policy: heuristic_v0 als Fallback, agent_v1-Slot vorbereitet, parent_action-Abhaengigkeiten und factors[] fuer spaetere KI-Steuerung.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:38:22 +02:00
LarsandCursor 20636f88d2 feat(steering): Kernel v0.3 mit Read-Model- und Proposal-Registry (K-Ext-1, P6)
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 15s
Test Suite / pytest-backend (push) Successful in 4m11s
Test Suite / lint-backend (push) Successful in 2s
Erweitert evaluate_steering um read_models und proposals, migriert epic_rollup auf Registry, liefert sprint_commit-Vorschlaege und UI auf Plan-Sprint.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:27:06 +02:00
LarsandCursor c5e2c69b1e docs: Steering Kernel Extension Model fuer Read Models, Proposals und Agent-Slots
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 4m13s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:14:19 +02:00
LarsandCursor ef5ee0d19b feat(steering): Epic Roll-up Read Model und Attention (ADP P4)
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / playwright-smoke (push) Blocked by required conditions
Test Suite / lint-backend (push) Waiting to run
Schliesst den Backlog/Epic-Track mit kernel-basiertem Fortschritt pro Epic, Steuerungs-Attention und UI-Fortschrittsanzeige im Plan-Eingang ab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 11:13:47 +02:00
LarsandCursor a13913f1a0 feat(ui): Geführter Eingang und Steuerungskurzinfo auf Plan-Profil
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m0s
Test Suite / lint-backend (push) Successful in 2s
BacklogIntakeGuide und PlanSteeringSummary leiten aus Operating Context — keine Archetyp-Ifs, klarere Commit-Pfade A/B.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 10:57:49 +02:00
LarsandCursor a3b14d9c00 feat(steering): Backlog-Vokabular aus Methoden-Vertrag (ADP P3)
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 3m56s
Test Suite / lint-backend (push) Successful in 2s
backlog_epic_hierarchy als Steuerungselement, effektive steering_elements im Operating Context, Backend-Guards und UI ohne Slice-Ifs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 10:44:38 +02:00
LarsandCursor f33135b87f feat(backlog): Epic-Hierarchie mit parent_backlog_id (ADP P2)
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m54s
Test Suite / playwright-smoke (push) Successful in 15s
Test Suite / lint-backend (push) Successful in 3s
Epics als Backlog-Container mit Baum-UI, Convert-Guard und pytest-Abdeckung — Roll-up bleibt für P4 offen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 09:22:20 +02:00
Lars dc6f25b673 feat(product): Plan-Arbeit fuer Direct-AP-Pfad (ADP P1)
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 49s
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m45s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
Product-Outline enthaelt work; planOutlineKeys-Reihenfolge steuert Sidebar; Product-spezifischer Lead auf Plan-Arbeit.
2026-07-26 18:25:12 +02:00
Lars f7d65dde01 docs: Backlog-Hierarchie, Dual Commit Path und Epic-Zielbild
ADP v0.1 plus Updates in B2b-Spec, agile_iteration, Katalog und Truth Table.
2026-07-26 18:25:12 +02:00
Lars 1c10e5b798 fix(tests): omCapabilities nach UI-Profil-Merge normalisieren
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 3m45s
Test Suite / lint-backend (push) Successful in 2s
test_resolve_ui_profile_merges_seed_slices_when_db_partial erwartet omCapabilities aus dataSlices wenn DB-Profil unvollstaendig ist.
2026-07-26 18:00:22 +02:00
Lars 97fab2c76d docs: Archetyp-gesteuerte UI-Navigation verankern
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m50s
Test Suite / lint-backend (push) Successful in 2s
ARCHETYPE_UI_NAVIGATION_v0.1 plus Verweise in Spec-Template, README und Programm-Dokument.
2026-07-26 16:52:48 +02:00
Lars 11b7128204 fix(ui): Plan-Navigation nicht mehr durch leere data_slices blockieren
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 44s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Archetyp-UI-Profil und Methoden-Schnittmenge werden korrekt gemerged; Frontend faellt bei leerem data_slices auf ui_profile.dataSlices zurueck, damit Eingang/Sprint/Gates erreichbar bleiben.
2026-07-26 16:49:02 +02:00
LarsandCursor fe1edb84f8 feat(steering): Kernel Spine v0.2 — Events, Slot-Provider, continuous_product
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 50s
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m49s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
apply_steering_event an Action done, Gate verify/reopen und Blocker resolve; lifecycle-Ketten methodenaware via slot_map; continuous_product slot_map; pytest v0.2.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 16:33:00 +02:00
LarsandCursor 606dd960b8 fix(steering): Gate-Horizont ignoriert aktive work_cycles
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 3m37s
Test Suite / lint-backend (push) Successful in 2s
first_active_gate_id schloss Sprint-Zeitboxen mit status=active ein und leerte Agile-Next bei Gate-Schnittmenge.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 16:22:44 +02:00
LarsandCursor 0443b734c1 fix(tests): pytest nach Kernel Spine und Starter-Kit bereinigen
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m33s
Test Suite / lint-backend (push) Successful in 3s
list_compatible_methods nur Primary-Methoden; Agile-Graph auf Sprint-Scope; Tests ohne Starter-Action-Kollision; TenantContext-Factory fuer Kernel-Tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 16:15:32 +02:00
LarsandCursor 75a6a63665 feat(steering): Kernel Spine v0.1.1 als zentraler Initiative-Einstieg
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m33s
Test Suite / lint-backend (push) Successful in 2s
evaluate_steering() vereinheitlicht Horizon, Next Work und Attention; Snapshot und Signal Engine delegieren dorthin; slot_map deklarativ fuer sequential_dependency und generic_operating.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 16:08:58 +02:00
LarsandCursor 753f178b0c docs: Archetyp-Vollspecs und Methodenkern vorlaeufig freigeben.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m23s
Test Suite / lint-backend (push) Successful in 3s
Decision-Lock, Spec-D-Methoden und C1-Massstab-Vollspecs als Zielbild; Steering-Registry/Compat und Horizon-Tests an die Normierung anbinden. Implementierungsausreichendheit bleibt bewusst offen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 15:02:04 +02:00
LarsandCursor 005b371ac0 docs: AP2.3/AP2.4 Plugin-Architektur verbindlich dokumentieren.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 3m15s
Test Suite / lint-backend (push) Successful in 2s
Guardrails, Truth Table und ADPs auf gelieferten Stand bringen; Spezifikationsprogramm und Archetyp-Template um steering_elements ergänzen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 11:48:13 +02:00
LarsandCursor 4fbb3b3469 fix(AP2.4): product_milestone_driven ohne work_cycles ? generic-kompatibel.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 3m13s
Test Suite / lint-backend (push) Successful in 2s
om_capabilities-Pruefung blockierte Methodenwechsel auf initiative.generic; Gate-Slices reichen fuer Meilenstein-Steuerung.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 11:34:26 +02:00
LarsandCursor d3bf3c36e0 AP2.4: Steuerungselement-Registry und Methoden-Vertrag.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Failing after 3m17s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
MethodDefinition traegt steering_elements/ui_features/graph_profile; operating-context und FE-Registry ohne Archetyp-Ifs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 11:27:59 +02:00
LarsandCursor ac475ab92c fix(test): AP2.3f dispute_case-Profil in operating-context-Tests abbilden.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 3m10s
Test Suite / lint-backend (push) Successful in 2s
Generic-Fallback testet initiative.generic; dispute_case erwartet explizite processSteps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:58:28 +02:00
LarsandCursor c79bfa844f AP2.3f: Restschuld ? uiFeatures, Route-Registry und slice-bewusste Mutationen.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Failing after 3m9s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Archetyp-Profile und Seitenlogik auf Operating Context migriert; methodUiDefaults nur noch Fallback.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:52:12 +02:00
LarsandCursor 44fda7beb9 fix(AP2.3e): product_milestone_driven auch fuer generic/linear/program — pytest AP1.1/AP14.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 3m10s
Test Suite / lint-backend (push) Successful in 7s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:34:02 +02:00
LarsandCursor 38fed379ae AP2.3e: Method Plugin Contract mit data_slices und Archetyp-Kompatibilitaetspruefung.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 49s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m12s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:27:40 +02:00
LarsandCursor 11e36e674e AP2.3d: Route Gating via OperatingRouteGate und Slice-basierte Seitenlogik.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:27:20 +02:00
LarsandCursor 1b55d8558c AP2.3c: Slice-bewusstes Laden und hoisted InitiativeOperationsProvider.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:26:56 +02:00
LarsandCursor 90934453e6 AP2.3b: Frontend Profile Resolver — Operating Context statt methodUiDefaults.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:26:37 +02:00
LarsandCursor 4ad908bfbf AP2.3a: Operating Context API mit ui_profile_json und Archetyp-Sync.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:26:17 +02:00
LarsandCursor ad6740ffa8 ADP: Archetyp- und Methoden-Plugin-Architektur v0.1.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 49s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 2m57s
Test Suite / lint-backend (push) Successful in 2s
Leitplan vor weiteren Archetypen — Operating Context, UI/Data-Slices, Registry-Erweiterung ohne Core-Änderungen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 18:05:11 +02:00
LarsandCursor ee1e1c0671 fix: Sprint-AP Bearbeiten, Sprint-Verschiebung und klarere Aktionsleiste.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / playwright-smoke (push) Blocked by required conditions
Test Suite / lint-backend (push) Waiting to run
Behebt editingActionId-Bug in Plan/Work-Sprint; Schnellzuweisung AP zu anderem Sprint ohne Voll-Reload.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 18:04:26 +02:00
LarsandCursor 04d1dbf1f9 AP2.2f: Scrum Sprint-Review, Reaktivierung und Carryover beim Abschluss.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 2m58s
Test Suite / lint-backend (push) Successful in 4s
Offene APs können beim Abschluss in den Eingang oder einen anderen Sprint überführt werden; abgeschlossene Sprints sind reaktivierbar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 17:40:59 +02:00
LarsandCursor e65838118c AP2.2e: Unplan, Bug/Issue-Referenz und Sprint-Lebenszyklus.
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 44s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m52s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / lint-backend (push) Successful in 2s
Ermöglicht APs zurück in den Eingang zu schieben, Bugs/Issues mit Feature-Bezug zu planen und den Scrum-Sprint-Ablauf in der UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-13 08:07:02 +02:00
LarsandCursor e221b5b09f fix: Sprint-Planung einsehbar und Eingang ohne Voll-Reload.
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 52s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m46s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
Geplante Sprints in Plan anwaehlbar, lokales Update beim Commit, Sprint-Auswahl bleibt erhalten.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 19:38:39 +02:00
LarsandCursor c19b6296ed fix: Sprint-Zuordnung im Eingang sichtbarer machen.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 2m52s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / lint-backend (push) Successful in 3s
Ziel-Sprint-Dropdown immer wenn Sprint existiert, Setup-Hinweis ohne Sprint, Planen fuer alle commit-faehigen Backlog-Status.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 19:30:36 +02:00
LarsandCursor 00567bb097 AP2.2b: Kritischer Pfad in Kontrolle für A2 Linear.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 20s
Test Suite / pytest-backend (push) Successful in 2m57s
Test Suite / lint-backend (push) Successful in 2s
CriticalPathPanel aus Execution Graph, Next-Action-Begruendung und Integrationstest fuer sequential_dependency.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 19:26:08 +02:00
LarsandCursor f6aba94864 AP2.2d: Sprint-Planung, Abschluss und Product-Fallback.
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m56s
Test Suite / playwright-smoke (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 2s
Backlog committet in gewaehlten Sprint, Sprint complete-Endpoint, continuous_product-Ansicht ohne aktiven Sprint.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 19:21:49 +02:00
LarsandCursor 09826d146e AP1.9d: Methoden-Default-UI und Product Language für Product-Flow.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 47s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Prozessleiste, archetypgebundene Modus-Defaults und Sprint/Arbeitspaket-Begriffe schließen den GUI-Kern für continuous_product vor Sprint-Planungs-Flows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 19:20:06 +02:00
LarsandCursor 82a5b9adec AP2.2d: B2b Product-Backlog und B3 Sprint-Backlog in UI.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 2m40s
Test Suite / lint-backend (push) Successful in 2s
Zeitbox-API im Frontend, Plan/Ausführen Sprint-Ansichten, Backlog-Convert in aktiven Sprint. agile_iteration bei aktiver Zeitbox für continuous_product.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 16:27:34 +02:00
LarsandCursor 0b57e2ec75 AP2.2b/c: A1-Stufenwechsel, Team-Fix, Agent-Anlage, Steuerungs-Hinweise.
AP2.0e rotiert Recurring bei maturity_stage reached. Maturity-Strategie priorisiert Routinen. Team zeigt Namen und Agent-Formular. Archetyp-Hints in Kontrolle und Stufe-A-Gruppierung bei Anlage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 16:19:55 +02:00
LarsandCursor 2b0d5dd3d9 AP2.2a: Archetyp-Starter-Kits und MVP Execution Plan v0.2.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 2m40s
Test Suite / lint-backend (push) Successful in 3s
Referenz-Vorhaben A1/A2/B2b/B2a per UI anlegbar mit gefuehrter Starter-Struktur; Dogfooding-Seed deprecated. Plan-Korrektur: Execution Plan v0.2 statt Seed-Spiegel als Prioritaet.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 16:02:09 +02:00
LarsandCursor a097a82e17 fix: Operational context nutzt korrekte Snapshot-Feldnamen.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m30s
Test Suite / lint-backend (push) Successful in 2s
initiative_title/initiative_status statt title/status — behebt test_operational_api_with_service_token.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 15:22:31 +02:00
LarsandCursor b8945556ad fix: Dogfooding-Seed ueberspringt bereits erreichte Gates.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 2m33s
Test Suite / lint-backend (push) Successful in 2s
verify_reached wird bei Re-Deploy nicht erneut auf terminalen Gates aufgerufen — behebt unhealthy Backend beim Seed-Lauf.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:56:09 +02:00
LarsandCursor d1bc725ab5 AP2.0f: work_cycle Zeitbox und actions.work_cycle_id.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Failing after 48s
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
RoadmapItem type work_cycle, Sprint-API, agile_iteration Next-Action-Strategie; Steering-Snapshot zeigt active_work_cycle.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:34:36 +02:00
LarsandCursor 5dc372c043 AP1.7: Operational API und Actor Service Tokens fuer Vibe-Coder.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Failing after 42s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 3s
Agenten authentifizieren per X-Actor-Token; /api/operational/ Fassade mit context, next-action, status, evidence; Token-Verwaltung unter /api/actors/{id}/service-tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:21:16 +02:00
LarsandCursor 2359cc8b59 Dogfooding R2: Seed spiegelt AP1.9c, AP1.16 und AP2.0d als done.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Failing after 52s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 2s
seed_004 aktualisiert Actions/Evidence und offene naechste Schritte; Gate-Beschreibungen und Docs sync.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:06:04 +02:00
LarsandCursor 284b9d50fe AP2.0d: Next-Action-Strategien nutzen Execution-Graph ready_actions.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 45s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Archetyp-Strategien priorisieren ausführungsbereite APs mit Begründung execution_ready/critical_path; continuous_product und program_delivery integriert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:04:40 +02:00
LarsandCursor b9bfa9e5bd AP1.16d + AP1.9c: Planning Debt in Attention und Cockpit-Signale.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m18s
Test Suite / lint-backend (push) Successful in 2s
Attention-Regeln planning_debt/execution_waiting; Portfolio-Kacheln zeigen Steuerungssignale.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 11:48:34 +02:00
LarsandCursor 8546c7021b AP1.16c: Durchführungsplan in Plan-Outline und Action-Detail.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m19s
Test Suite / lint-backend (push) Successful in 2s
Ready/blocked-Badges, Planning Debt, Vorgänger-Verwaltung — getrennt vom Gate-Designer.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 11:25:55 +02:00
LarsandCursor 1166a0c7f1 AP1.16a-b: Execution-Graph für Arbeitspaket-Abhängigkeiten.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-smoke (push) Successful in 14s
Test Suite / pytest-backend (push) Successful in 2m20s
Test Suite / lint-backend (push) Successful in 3s
Migration 023, Engine, API und ADP für Durchführungsplan getrennt vom Gate-Graph; Docs und Sprint-Assignment synchronisiert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 10:38:01 +02:00
LarsandCursor a1b353fcee fix: Dogfooding-Seed nutzt list_roadmap_items_for_initiative.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 51s
Test Suite / playwright-smoke (push) Successful in 14s
Test Suite / pytest-backend (push) Successful in 2m27s
Test Suite / lint-backend (push) Successful in 2s
Behebt Backend-Startup-Fehler beim Deploy durch falschen Import in seed_004.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 10:24:44 +02:00
LarsandCursor a26b534c34 DOC: Status-Review, Truth Table Sync und Dogfooding R1 Seed.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Failing after 45s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 2s
Review-Auswertung, aktualisierte Roadmap/Gap-Analyse und idempotenter Seed fuer Kairo-Jinkendo als Referenz-Vorhaben mit Gates, Actions und Gitea-Evidence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 10:17:57 +02:00
LarsandCursor b85a6ec0c7 AP1.6b: Journey um Gate-Fortschritt und Ist-Graph erweitern.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 2m23s
Test Suite / lint-backend (push) Successful in 2s
Fokus-Gates mit Kriterien-Checkliste und eingebetteter Graph-Sicht in Kontrolle; Abnahme-Reihenfolge in Roadmap dokumentiert.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 09:48:14 +02:00
LarsandCursor a19c6abd26 AP1.8a: Portfolio-Rang im Cockpit mit Reorder und Next-Action-Sortierung.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Successful in 21s
Test Suite / pytest-backend (push) Successful in 2m21s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 09:39:49 +02:00
LarsandCursor d7aefed0de AP1.15c: Join/Branch-Topologie mit parallel_group und optional_branch.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 50s
Test Suite / pytest-backend (push) Successful in 2m18s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / lint-backend (push) Successful in 3s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 09:27:56 +02:00
LarsandCursor 364ad44759 AP1.15b: Designer UX mit Drag-Kanten, Gate anlegen und Info-Panel.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 09:26:16 +02:00
LarsandCursor 0c2ca4a69d AP1.15a: Zielzustands-Designer mit Pan/Zoom und Kanten im Plan-Tab.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m19s
Test Suite / lint-backend (push) Successful in 2s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 08:28:15 +02:00
LarsandCursor 2843d8775a fix: graph-state Test beruecksichtigt Methodenprofil AP1.4e.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m16s
Test Suite / lint-backend (push) Successful in 2s
generic_operating liefert would_block statt blocked; harte Blockade erst unter product_milestone_driven pruefen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 08:14:34 +02:00
LarsandCursor 064779e187 AP1.14: Plan-Snapshot und Plan/Ist-Overlay in Kontrolle.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 2m18s
Test Suite / lint-backend (push) Successful in 3s
Revisionen mit Audit, getrennte Soll/Ist/Diff-Ansicht unter Kontrolle/Plan-Ist; API plan-ist-view und plan-snapshots.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 08:10:15 +02:00
LarsandCursor 1fa61b2dac AP1.4e: Methodenprofile am Gate-Graph.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 2m18s
Test Suite / lint-backend (push) Successful in 2s
generic_operating ohne harte Blockade, Reifegrad-Methoden mit Erfuellungsgrad; Attention gate_graph_blocked fuer gate-orientierte Methoden.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 08:06:42 +02:00
LarsandCursor 4f8725e234 AP1.4d: Graph Engine mit blocked/ready Read Models.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / pytest-backend (push) Successful in 2m17s
Test Suite / lint-backend (push) Successful in 2s
Migration 020 fuer Kantenarten und Parallelgruppe; steering/graph berechnet Fortschritt; UI zeigt Bereit/Blockiert in Liste und Graph.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 07:59:18 +02:00
LarsandCursor bd64340ca1 AP1.4c: Gate-Checkliste statt Freitext-DoD.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 2m13s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
Kriterien-Fortschritt in der Gate-Liste, Modal-UX fuer Checklisten und optionales Erst-Kriterium beim Anlegen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 07:53:38 +02:00
LarsandCursor dbe6f4f684 AP1.10c: Profil-Modal mit Archetyp, EFS und Owner.
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 45s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m13s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 2s
InitiativeForm laedt Felder nach gewaehltem Archetyp; Plan-Profil zeigt Standardfelder und Zusatzfelder; actor_ref und Owner-Auswahl.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 07:48:00 +02:00
LarsandCursor 43d30944aa AP1.5d: Aufgaben-Baum in der Plan-Outline unter Arbeit.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m12s
Test Suite / lint-backend (push) Successful in 3s
Offene Tasks erscheinen unter dem Arbeitspaket (max. 3 Ebenen, Tiefe 2 eingeklappt); Links fuehren zur Action-Detailseite #tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 07:43:33 +02:00
LarsandCursor 075cff00a2 Docs: Zielzustands-Graph ist kein Workflow; Plan vs. Ist.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 45s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Plan-Mode-Design und ADP praezisieren Graph-Semantik, MVP-Zwischenstand und vorgeschlagene Pakete AP1.14/15 fuer Plan-Ist-Parallelitaet und Modellierungswerkzeug.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 07:42:14 +02:00
LarsandCursor 7cd8f4b90e AP1.13b: Gate-Abhaengigkeiten auf der Detailseite pflegen.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m11s
Test Suite / lint-backend (push) Successful in 3s
DELETE fuer Roadmap-Kanten, Duplikat-Schutz beim Anlegen, GateDependenciesSection mit ausgehenden/eingehenden Kanten auf der Gate-Detailseite.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 15:53:03 +02:00
LarsandCursor 7f03504c2d AP1.13a: Read-only Gate-Graph aus Abhaengigkeiten.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Initiative-API fuer Roadmap-Dependencies, SVG-Layout mit Liste/Graph-Umschalter auf der Zielzustaende-Seite.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 15:50:20 +02:00
LarsandCursor 83fdb9a2a2 AP1.12c: Reihenfolge der Gates per DnD und Pfeiltasten.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 50s
Test Suite / playwright-smoke (push) Successful in 15s
Test Suite / pytest-backend (push) Successful in 2m6s
Test Suite / lint-backend (push) Successful in 3s
RoadmapPlanSection nutzt sort_order wie Backlog und Projekte; handleReorderRoadmapItems im Operations-Context.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 15:43:08 +02:00
LarsandCursor b1686f3a98 AP1.12b/d: Gates per Modal und Actions in der Plan-Outline.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
RoadmapPlanSection ist read-only mit Modal-Anlage; Stammdaten auf der Gate-Detailseite. Unter Arbeit zeigt die Outline offene Actions wie der Projektbaum unter Struktur.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 15:41:42 +02:00
LarsandCursor bcf6f83813 AP1.12a: Plan-Outline mit Projektbaum unter Struktur.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 51s
Test Suite / pytest-backend (push) Successful in 2m7s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 3s
Linke Outline zeigt rekursive Projects im Scope; Deep-Links zu /projects/:id markieren Struktur aktiv.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 14:27:28 +02:00
LarsandCursor 5e2ae9de31 Mitai analysis-split Sub-Nav und weniger Blend-UI bei Auspraegungen.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / lint-backend (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Modus-Subnav als linke Spalte (Plan/Kontrolle/Ausfuehren), Referenz-Auspraegungen aus Formularen entfernt, Hub-Karten auf Steuerung gestrichen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 14:26:14 +02:00
LarsandCursor b0594df5f2 Fix IndentationError in initiative_snapshot imports that blocked backend startup.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 2m6s
Test Suite / lint-backend (push) Successful in 3s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 12:45:00 +02:00
LarsandCursor efb45a3ee6 Erfassen und Transparent: Archetyp, Methode und Auspraegung in der UI sichtbar.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Has been skipped
Deploy Development / deploy (push) Failing after 50s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Method-Profiles-API und Auswahl beim Anlegen/Profil; Steuerungs-Meta in Listen und Plan; Projekt-Archetyp-Spiegel, Next-Action-Links und Umlaut-Fix fuer testbare Guidance.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 12:36:12 +02:00
LarsandCursor 95b743d6fd Fix: AP2.0 pytest — Snapshot statt nicht vorhandenem GET context.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-smoke (push) Successful in 17s
Test Suite / pytest-backend (push) Successful in 2m2s
Test Suite / lint-backend (push) Successful in 2s
Steering PATCH akzeptiert alle registrierten method_keys (nicht nur Legacy-Literal).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 10:56:26 +02:00
LarsandCursor 3bd983297b AP2.0: Archetyp-Katalog, Method-Stubs und sichtbare Steuerung in Kontrolle.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 2m2s
Test Suite / lint-backend (push) Successful in 3s
PO-Dokumente (ADP v0.2, MVP v0.3) und Minimal Complete Slice: Registry-Methoden, Initiative/Project-Spiegel, Default-Methode bei Anlage, Lagebild mit Archetyp und Guidance.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 10:44:38 +02:00
LarsandCursor 21d948634e Fix: Plan-Eingang crashte wegen fehlender Context-Handler.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 15s
Test Suite / pytest-backend (push) Successful in 2m0s
Test Suite / lint-backend (push) Successful in 3s
handleUpdateBacklog und handleReorderBacklog waren in InitiativeInboxPage nicht destructured — ReferenceError, leerer Screen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 06:39:03 +02:00
LarsandCursor 3e96b9c1e9 Fix: Task-Roll-up mit RealDictCursor kompatibel.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-smoke (push) Successful in 14s
Test Suite / pytest-backend (push) Successful in 1m58s
Test Suite / lint-backend (push) Successful in 2s
rollup_parent_status nutzte Index-Zugriff row[0]; pytest test_nested_tasks_and_rollup schlug fehl.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 06:31:41 +02:00
LarsandCursor ba28a86fe5 AP1.5d: Rekursive Tasks im Plan-Knoten Arbeit.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Failing after 1m57s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
parent_task_id mit Validierung und Roll-up; aufklappbarer Task-Baum unter Arbeitspaketen im Plan-Modus (max. 3 UI-Ebenen).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 06:18:55 +02:00
LarsandCursor a6fc86025c AP1.10b/10c: Entity Field System mit dynamischen Vorhaben-Zusatzfeldern.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-smoke (push) Successful in 15s
Test Suite / pytest-backend (push) Successful in 1m54s
Test Suite / lint-backend (push) Successful in 2s
EFS-Tabellen, Registry-Sync und Fields-API ermöglichen archetyp-spezifische Felder; Frontend rendert sie im Profil-Modal per FieldRenderer.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 13:53:07 +02:00
LarsandCursor 408050bcb8 AP1.10a: Initiative-Standardfelder vision, Zielzustand und Archetyp-Schlüssel.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 1m51s
Test Suite / lint-backend (push) Successful in 2s
Migration 016, Archetyp-Registry-API, erweitertes Profil-Modal und Plan-Profil-Ansicht.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:48:54 +02:00
LarsandCursor 495993cad6 Fix: test_backlog_sort_order setzt beide sort_order-Werte ohne Tie.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / pytest-backend (push) Successful in 1m49s
Test Suite / lint-backend (push) Successful in 2s
Einzel-PATCH auf 0 kollidierte mit dem ersten Item; entspricht dem Batch-Reorder aus AP1.12c.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:42:42 +02:00
LarsandCursor 4f2f801889 AP1.12d: Plan-Outline-Knoten Arbeit mit Actions-Liste im Plan-Kontext.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 56s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 1m48s
Test Suite / lint-backend (push) Successful in 2s
Route /plan/work, Modal-Anlage, Links zu Objektseiten; Outline zeigt Zähler für Eingang und Arbeit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:38:17 +02:00
LarsandCursor a99d4a8974 AP1.12c: Reorder für Projekte und Backlog per sort_order.
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 1m46s
Test Suite / lint-backend (push) Successful in 2s
Migration 015 für Backlog sort_order; DnD auf Desktop, Pfeile auf Mobile; PATCH-Batches für Geschwister.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:35:08 +02:00
LarsandCursor e50c04c96f AP1.12b: Modal-Bearbeitung für Profil, Projekte und Backlog im Plan-Modus.
Test Suite / compose-smoke (push) Has been skipped
Deploy Development / deploy (push) Successful in 53s
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 1m47s
Test Suite / playwright-smoke (push) Successful in 12s
Test Suite / lint-backend (push) Successful in 3s
Ersetzt Inline-Formulare durch Dialoge; Scope-Breadcrumb aktualisiert sich nach Profil-Speichern.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:26:48 +02:00
LarsandCursor bbadf22d39 AP1.12a: Plan-Outline-Shell ersetzt Untertabs im Planen-Modus.
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 2m4s
Test Suite / playwright-smoke (push) Successful in 13s
Test Suite / lint-backend (push) Successful in 2s
Linke Outline mit Profil, Struktur, Zielzuständen und Eingang; Portfolio-Einstieg ohne Scope; Vorhabens-Profil als Read-only-Vorschau.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:16:42 +02:00
LarsandCursor aa7e1626ea AP1.9b: Scope-Breadcrumb modus-sensitiv für Planen, Ausführen und Kontrolle.
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
Portfolio- und Vorhaben-Klicks bleiben im aktiven Modus; Objekt-Routen leiten auf passende Plan-/Work-Hubs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:14:33 +02:00
LarsandCursor afb07f70b9 docs: Plan-Modus-Design und ADP AP1.10 (Archetypen, Entity Field System).
Festlegung Vorhaben als Wurzel, Plan-Outline, Modal/DnD, Gate-Graph und Roadmap AP1.9b–AP1.13.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 11:13:54 +02:00
473 changed files with 52025 additions and 1503 deletions

No files matched your search

+1
View File
@@ -51,6 +51,7 @@ Referenzmaterial unter `docs/reference/design-principles/`. Nicht automatisch Sc
- Keine Mitai-/Shinkan-Domänenlogik kopieren
- Keine parallele Steuerungslogik außerhalb `backend/steering/`
- Keine neuen OM-Tabellen ohne ADP (Scope Lock bis RoadmapItem-ADP)
- **Archetyp-/Methoden-Plugin (AP2.3/AP2.4):** siehe `.cursor/rules/kairo-plugin-architecture.mdc` — keine Archetyp-Ifs in Pages, keine neuen Features in `methodUiDefaults.js`
## Abweichungen
+14 -1
View File
@@ -19,9 +19,22 @@ Praktische Verifikation erfolgt durch **Deployment auf ein entferntes System (Ra
2. Deployment wird dadurch ausgelöst (CI/Deploy-Pipeline auf dem Raspberry)
3. Dort laufen Migrationen, Backend-Tests und Smoke-Checks gegen echte Infrastruktur
**Dev-Instanz (kein localhost):** [https://dev.kairo.jinkendo.de](https://dev.kairo.jinkendo.de)
Schnellcheck: `GET https://dev.kairo.jinkendo.de/api/health` (Version + DB).
**Gitea Actions** (Test-Suite läuft nach Deploy automatisch):
- Übersicht: `http://192.168.2.144:3000/Lars/Kairo-Jinkendo/actions`
- Workflows: `deploy-dev.yml` (Deploy), `test.yml` (pytest, lint, k6, Playwright)
- Filter z. B. `?workflow=test.yml` oder `?workflow=deploy-dev.yml`
- Run-Detail: `/Lars/Kairo-Jinkendo/actions/runs/{id}`
Nach Push auf `develop`: Deploy-Run grün → Health auf Dev → Test-Suite in Gitea Actions prüfen.
## Konsequenz für Agenten
- Code und Tests **schreiben** und dokumentieren — aber fehlende lokale DB nicht als Implementierungsblocker behandeln
- Frontend: `npm test` / `vite build` lokal weiterhin sinnvoll, wenn Node verfügbar
- Backend: nach AP-Umsetzung Abschlussbericht mit „Remote-Verifikation nach Push auf develop“ kennzeichnen
- Backend: Abnahme über Gitea Actions (`test.yml`) + Dev-Health — nicht lokales pytest erzwingen
- Funktionale Checks gegen **https://dev.kairo.jinkendo.de**, nicht localhost
- **Nicht** proaktiv committen/pushen, es sei denn, der Nutzer bittet explizit darum
@@ -0,0 +1,61 @@
---
description: Archetyp-/Methoden-Plugin-Architektur (AP2.3/AP2.4) — verbindlich für neue Implementierungen
globs: backend/steering/**,backend/entity_archetypes/**,backend/services/operating_context.py,frontend/src/registry/**,frontend/src/pages/**,frontend/src/context/InitiativeOperationsContext.jsx
alwaysApply: true
---
# Kairo Plugin-Architektur (AP2.3 / AP2.4)
Verbindliche ADPs: `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `docs/architecture/ADP_Steering_Kernel_Spine_v0.1.md`, **`docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`**, **`.cursor/rules/kairo-steering-kernel.mdc`**
## Vier Schichten — Auflösung zur Laufzeit
| Schicht | Registry | Liefert |
|---------|----------|---------|
| **Archetyp** | `entity_archetypes` + `ui_profile_json` | Nav, Routen, Plan-Outline, `om_capabilities` |
| **Methode** | `steering/methods/registrations/` | `data_slices`, `steering_elements`, `ui_features`, `graph_profile`, Strategie |
| **Element** | `steering/elements/registry.py` + FE `steeringElementRegistry.js` | Control-/Work-Bausteine |
| **Runtime** | `GET /api/initiatives/:id/operating-context` + **`steering/kernel/evaluate_steering()`** | Plugin-Auflösung + **Herzmaschine** |
```text
data_slices = archetype.om_capabilities ∩ method.data_slices
steering_elements = method.steering_elements (nur Methode)
ui_features = method.ui_features (nur Methode)
nav / routes = archetype.ui_profile (nur Archetyp)
```
Archetyp-Default-Methode ist **Empfehlung**, nicht Lock — kompatible Methoden über `compatible_archetype_keys` + `om_capabilities`.
## Erweitern (Open/Closed)
**Neue Methode:** neues Modul unter `steering/methods/registrations/` → `MethodDefinition` vollständig → Import in `steering/__init__.py` → pytest. **Kein** Core-Edit.
**Neuer Archetyp:** Seed in `entity_archetypes/registry.py` + `ui_profiles.py` + optional EFS — **kein** React-If in Pages.
**Neues Steuerungselement:** Eintrag in `steering/elements/registry.py` + FE `steeringElementRegistry.js`; Methoden referenzieren nur registrierte Keys.
## Frontend — verbindlich
- UI aus `operating-context` via `resolveOperatingProfile.js`
- Control/Work: `hasSteeringElement(steeringElements, '…')` — **keine** `archetype_key === 'initiative.…'`-Ifs
- Daten: `loadOperatingSlices` / `refreshOm([…])` — **kein** Full-Reload nach Mutationen
- Route Gating: `OperatingRouteGate` + `MODE_ROUTE_GROUPS`
- Provider: `ScopedOperationsBridge` (ein Provider pro Vorhaben)
## Verboten
- `uiFeatures` am Archetyp-Profil (deprecated — nur Methode)
- Hardcodierte Methoden-UI in `methodUiDefaults.js` für **neue** Archetypen
- Parallele Steuerungslogik außerhalb `backend/steering/`
- Methoden-Dropdown ohne Archetyp-Filter (`GET /steering/methods?archetype_key=…`)
- **Initiative-Steuerung** (Next, Attention) außerhalb `steering/kernel/evaluate_steering()` — siehe `ADP_Steering_Kernel_Spine_v0.1.md`
## Fallback (legacy)
`methodUiDefaults.js` nur wenn Operating Context fehlt — nicht für neue Features erweitern.
## Abnahme neuer Archetyp-/Methoden-Slices
- Operating Context liefert `steering_elements` + `ui_features`
- pytest für Methoden-Vertrag (`test_ap24_*`) grün
- Spec unter `docs/product/archetypes/` referenziert Elemente und kompatible Methoden
+77
View File
@@ -0,0 +1,77 @@
---
description: Steering Kernel v0.4 — verbindliche Regeln für Read Models, Proposals, Attention, Agent-Slots, Ranker (alle Coding-Agenten)
globs: backend/steering/**,backend/data_layer/initiative_snapshot.py,frontend/src/components/SteeringProposalsPanel.jsx,frontend/src/components/AgentSlotsPanel.jsx,frontend/src/utils/steeringProposals.js,frontend/src/utils/agentSlots.js,frontend/src/utils/sprintCommitProposal.js,frontend/src/pages/initiative/InitiativeInboxPage.jsx,frontend/src/pages/initiative/InitiativePlanPage.jsx,frontend/src/pages/initiative/InitiativeOverviewPage.jsx,frontend/src/pages/modes/PlanSprintPage.jsx
alwaysApply: true
---
# Kairo Steering Kernel — Coding Rules (verbindlich)
**Primärdokument:** `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`
**Architektur:** `docs/architecture/ADP_Steering_Kernel_Extension_Model_v0.1.md`
## Herzmaschine
- Initiative-Steuerung **nur** via `evaluate_steering()` in `backend/steering/kernel/evaluate.py`
- Snapshot spiegelt `evaluation.read_models` + `evaluation.proposals` + `evaluation.agent_slots` — **kein** Duplikat-Rechnen
## Neue Fähigkeit = Provider registrieren
| Was | Wo |
|-----|-----|
| Read Model | `steering/read_models/registry.py` |
| Proposal | `steering/proposals/registry.py` |
| Attention | `steering/attention/contributors/*.py` + Registry |
| Agent-Slot | `steering/agent_slots/registry.py` |
| Sprint-Ranker | `register_sprint_commit_ranker()` — weitere Ranker analog |
Aktivierung über `steering_elements` / `data_slices` im Methoden-Vertrag — **nicht** über Page-Ifs oder `method_key`-Branches im Kernel.
## Proposals
- **Kein Auto-Commit** — Accept in UI/API
- **Keine feste Bug/Story-Policy** — `ranker_key` + `factors[]`; Heuristik = Fallback (`heuristic_v0`)
- Abhängigkeiten: `dependency_refs`, `dependency_blocked`
- KI: `agent_v1` Ranker + Actor-Slot — **keine** hardcodierten Prompts (Principle Gate)
## Agent-Slots
- Deklarative Fenster für Actors — **kein** Prompt, **keine** Auto-Ausführung
- Config: `operatingContext.agent_slot_config` (`enabled_slots`, `guardrail_pack`, `stale_debt_days`)
- UI: `AgentSlotsPanel` + Snapshot `steering_kernel.agent_slots`
## Portfolio (K-Ext-5)
- Aggregiert Kernel-Output über Initiativen: `GET /api/workspace/steering`
- Modul: `steering/portfolio/aggregate.py` — **kein** Duplikat-Rechnen außerhalb Kernel
- Legacy `/api/workspace/attention` bleibt (SQL-Regeln) bis vollständige Migration
## Frontend
- `SteeringProposalsPanel` + `PROPOSAL_UI_CONFIG` in `utils/steeringProposals.js`
- Daten aus `steeringSnapshot.steering_kernel.proposals`
- Keine neue Proposal-Page pro Methode
## Methoden-Parität (Ist)
| Provider | Element-Gate |
|----------|--------------|
| `sprint_commit` | `work_cycle_scope` |
| `gate_next_actions` | `gate_fulfillment` |
| `intake_triage` | `backlog` slice, **excludes** `work_cycle_scope` |
| `epic_rollup` | `backlog_epic_hierarchy` |
| `planning_debt` / `execution_graph` | `gate_fulfillment` / `critical_path` |
| `tech_debt_summary` | `backlog` + `actions` slices |
| `review.due` / `recurring.due` / `review.guardrail` | Agent-Slots (data_slices + elements) |
## Verboten
- Steuerungslogik außerhalb `backend/steering/`
- Archetyp-Ifs für Steuerungs-UI
- `evaluate_next_work` für Commit-Vorschläge (Plan ≠ Ist)
- OM-Tabellen für Vorschläge
## Tests
- Unit-Test pro Provider/Ranker
- Snapshot-Integration wenn DB-Test verfügbar
- Truth Table aktualisieren
+76
View File
@@ -0,0 +1,76 @@
---
description: Vibe-Coder Agent — Kairo Operational API mit Actor Service Token
alwaysApply: false
globs:
- "**/*"
---
# Kairo — Vibe-Coder API (AP1.7)
Du arbeitest als **Agent-Actor** an Kairo. Nutze die **Operational API** — nicht die volle UI-REST-API.
## Einmal-Setup (Nutzer, einmalig)
1. In Kairo als Tenant-Admin einloggen (Browser).
2. Actor `Cursor Agent` anlegen (Typ `agent`) — oder vorhandenen aus Actor-Verzeichnis nutzen.
3. Service Token erstellen:
```http
POST /api/actors/{actor_id}/service-tokens
X-Auth-Token: {session}
Content-Type: application/json
{"label": "Cursor Agent", "capabilities": []}
```
Antwort enthält **`token`** (nur einmal sichtbar) — Format: `kairo_at_{prefix}_{secret}`.
4. In Cursor **Environment Variables** (oder `.env` lokal, nicht committen):
```text
KAIRO_API_BASE=http://192.168.2.144:3097
KAIRO_ACTOR_TOKEN=kairo_at_...
```
Optional für Dogfooding:
```text
KAIRO_INITIATIVE_ID={uuid von „Jinkendo Kairo“}
```
## Authentifizierung
Jeder Operational-Request:
```http
X-Actor-Token: {KAIRO_ACTOR_TOKEN}
```
Alternativ: `Authorization: Bearer {KAIRO_ACTOR_TOKEN}`
**Nicht** Session-Token in Agent-Skripten hardcoden — Service Token ist tenant-scoped, capability-gebunden, widerrufbar.
## Typischer Agent-Loop
```text
GET /api/operational/me
GET /api/operational/initiatives/{id}/context → enthält active_work_cycle
GET /api/initiatives/{id}/work-cycles/active → aktive Sprint-Zeitbox
POST /api/initiatives/{id}/work-cycles → {"title","status":"active"}
GET /api/operational/next-action?initiative_id={id}&limit=5
… Arbeit …
PATCH /api/operational/actions/{id}/status {"status":"in_progress"}
PATCH /api/operational/actions/{id}/status {"status":"done","note":"Commit …"}
POST /api/operational/evidence {"initiative_id","action_id","title","body":"Commit-Link"}
```
## Guardrails
- Kein Gate `reached`, kein Lifecycle-Wechsel, kein Portfolio-Reorder über Operational API.
- Mutierende Calls werden auditiert (`actor_id` aus Token).
- Token-Leak → Token widerrufen: `DELETE /api/actors/service-tokens/{token_id}` (Session-Auth).
## Referenz
- `docs/architecture/ADP_Operational_Actor_Interface_Vibe_Coder_v0.1.md`
- OpenAPI: `{KAIRO_API_BASE}/api/docs` (Nicht-Prod)
+20 -3
View File
@@ -18,7 +18,9 @@ Foundation AP0.1–AP0.7 abgeschlossen. Operating Model AP0.8–AP0.10, Steering
- 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)
- `backend/steering/` (Lifecycle, Snapshot, Method Registry, **Plugin-Architektur AP2.3/AP2.4**)
- **Operating Context API** + slice-bewusstes Frontend-Laden (AP2.3)
- **Steuerungselement-Registry** + Methoden-Vertrag (AP2.4)
- Workspace-GUI, Data Layer, Actor Directory
**Produktlich fehlt (Vision):**
@@ -30,7 +32,7 @@ Foundation AP0.1–AP0.7 abgeschlossen. Operating Model AP0.8–AP0.10, Steering
**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.
Nächster Fokus: **Specs Welle 1 finalisieren**, dann **Stufe-A End-to-End** (AP2.2b/c/e, AP1.9d) und **AP2.1 Validation** — auf Plugin-Architektur AP2.3/4 aufsetzen, kein Layout-Patching auf InitiativeDetail.
---
@@ -48,6 +50,10 @@ Lies bei Projektstart in dieser Reihenfolge:
8. `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
9. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
10. `.cursor/rules/kairo-architecture.mdc`
11. **`.cursor/rules/kairo-steering-kernel.mdc`** + `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md` (Steering Kernel v0.3 — Read Models, Proposals, Ranker)
11. `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md` (AP2.3 — **geliefert**)
12. `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md` (AP2.4 — **geliefert**)
13. `.cursor/rules/kairo-plugin-architecture.mdc`
Historisch / Referenz (nicht führend bei Konflikt):
@@ -138,6 +144,14 @@ Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
11. Admin- und Agentenaktionen werden auditiert.
12. Migrationen sind nummeriert und reproduzierbar.
### Plugin-Architektur (AP2.3 / AP2.4 — verbindlich)
13. **Archetyp ≠ Methode:** Archetyp = IA-Hülle + `om_capabilities`; Methode = Steuerungsmotor (`steering_elements`, `ui_features`, Strategie).
14. Runtime-Auflösung über `GET …/operating-context` — kein hardcodiertes Methoden-/Archetyp-UI in React-Pages.
15. Neue Archetypen/Methoden nur über **Registrierungsmodule** (`entity_archetypes/`, `steering/methods/registrations/`) — Open/Closed.
16. Control-/Work-UI aus `steering_elements` + `steeringElementRegistry.js`, nicht aus Archetyp-Ifs.
17. Siehe `.cursor/rules/kairo-plugin-architecture.mdc` und ADP AP2.3 / AP2.4.
---
## 6. Nicht tun
@@ -155,6 +169,9 @@ Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
- kein Billing oder SSO bauen
- keine strategischen Produktentscheidungen eigenmächtig ändern
- keine Designprinzipien aus `docs/reference/` ohne Principle-Gate oder Architecture Decision in Scope ziehen
- **keine Archetyp-Ifs** in Pages für Steuerungs-UI (`initiative.product === …`) — AP2.4 `steering_elements`
- **`methodUiDefaults.js` nicht für neue Archetypen erweitern** — Operating Context + Resolver
- **kein Full-`load()`** nach OM-Mutationen — `refreshOm([sliceKeys])`
---
@@ -168,4 +185,4 @@ Bei notwendiger Abweichung erstelle ein Architecture Decision Proposal.
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`.
Foundation AP0.1–AP2.4 Plugin-Architektur geliefert. **Produkt:** Specs Welle 1 → AP2.2b/c/e + AP1.9d → AP2.1 Validation. Scope Lock: `ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`; Plugin: ADP AP2.3/AP2.4.
+103 -5
View File
@@ -10,16 +10,54 @@ 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 entity_archetypes.registry import archetype_label
from method_profiles.registry import get_method_profile
from steering.context import get_steering_context_dto
from steering.kernel import evaluate_steering
from steering.signals.snapshot_signals import derive_initiative_signals
from services.initiatives import get_initiative
from services.progression_graph import compute_progression_state
from tenant_context import TenantContext
OPEN_BLOCKER = ("open", "in_progress")
OPEN_ACTION = ("open", "ready", "in_progress", "blocked", "review_required")
ACTIVE_INITIATIVE = ("active", "paused")
_REASON_LABELS = {
"open_action_priority": "Offenes Arbeitspaket",
"milestone_at_risk_or_active": "Plan-Element aktiv oder gefährdet",
"blocked_action": "Blockiertes Arbeitspaket",
"backlog_triage": "Eingang triagieren",
}
def _steering_guidance(
*,
next_actions: list[dict[str, Any]],
signals: list[str],
method_key: str,
) -> str:
if next_actions:
item = next_actions[0]
title = item.get("title") or "Nächster Schritt"
hint = (
item.get("recommended_action")
or item.get("summary")
or _REASON_LABELS.get(item.get("reason_code", ""), "")
)
if hint:
return f"Als Nächstes: {title} — {hint}"
return f"Als Nächstes: {title}"
if signals:
return "Attention: Struktur oder Ist-Arbeit ergänzen, um Next Actions zu erzeugen."
return (
f"Methode {method_key}: Plan oder Eingang befüllen, dann committete Arbeit starten."
)
def _attention_items(signals: list[str]) -> list[dict[str, str]]:
return [{"code": code, "label": code.replace("_", " ")} for code in signals]
def _sid(value: Any) -> Optional[str]:
return str(value) if value else None
@@ -88,7 +126,8 @@ def get_initiative_steering_snapshot(
cur.execute(
"""
SELECT id, title, status, priority, converted_action_id, created_at, updated_at
SELECT id, title, status, priority, converted_action_id, item_kind,
parent_backlog_id, created_at, updated_at
FROM backlog_items
WHERE tenant_id = %s AND initiative_id = %s
ORDER BY updated_at DESC
@@ -256,25 +295,79 @@ def get_initiative_steering_snapshot(
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
)
evaluation = evaluate_steering(ctx, initiative_id=initiative_id, next_work_limit=5)
next_actions = evaluation.next_work
kernel_attention = evaluation.attention
epic_rollup = evaluation.read_models.get("epic_rollup") or []
sprint_commit_proposals = evaluation.proposals.get("sprint_commit") or []
steering = get_steering_context_dto(ctx, initiative_id=initiative_id)
metadata = steering.get("lifecycle_metadata") or {}
if isinstance(metadata, str):
metadata = {}
method_profile_key = metadata.get("method_profile_key")
method_profile_label = None
if method_profile_key:
profile = get_method_profile(method_profile_key)
if profile:
method_profile_label = profile.get("label")
initiative_archetype = initiative.get("archetype_key") or "initiative.generic"
from services.work_cycle import get_active_work_cycle
active_work_cycle = get_active_work_cycle(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
return {
"initiative_id": initiative_id,
"initiative_title": initiative["title"],
"initiative_status": initiative["status"],
"archetype_key": initiative_archetype,
"archetype_label": archetype_label(
entity_type="initiative", archetype_key=initiative_archetype
),
"method_profile_key": method_profile_key,
"method_profile_label": method_profile_label,
"lifecycle_state": steering["lifecycle_state"],
"lifecycle_label": steering["lifecycle_label"],
"method_key": steering["method_key"],
"method_label": steering.get("method_label"),
"method_version": steering["method_version"],
"steering_guidance": _steering_guidance(
next_actions=next_actions,
signals=signals,
method_key=steering["method_key"],
),
"attention_items": _attention_items(signals)
+ [
{
"code": item.get("reason_code") or item.get("kind", "attention"),
"label": item.get("summary") or item.get("title") or "Attention",
}
for item in kernel_attention[:5]
],
"signals": signals,
"steering_kernel": {
"horizon": evaluation.horizon.to_dict(),
"lifecycle": evaluation.lifecycle.to_dict(),
"primary_method_key": evaluation.binding.primary_method_key,
"composition_modifier": evaluation.binding.composition_modifier,
"data_source": evaluation.data_source,
"read_models": evaluation.read_models,
"proposals": evaluation.proposals,
"agent_slots": evaluation.agent_slots,
},
"upcoming_milestones": upcoming_milestones,
"upcoming_roadmap_items": upcoming_milestones,
"next_actions": next_actions,
"active_work_cycle": active_work_cycle,
"epic_rollup": epic_rollup,
"sprint_commit_proposals": sprint_commit_proposals,
"gate_next_actions_proposals": evaluation.proposals.get("gate_next_actions") or [],
"intake_triage_proposals": evaluation.proposals.get("intake_triage") or [],
"agent_slots": evaluation.agent_slots,
"tech_debt_summary": evaluation.read_models.get("tech_debt_summary") or {},
"counts": {
"actions_open": open_actions,
"actions_blocked": blocked_actions,
@@ -291,6 +384,9 @@ def get_initiative_steering_snapshot(
"actions": actions,
"roadmap_items": roadmap_items,
"milestones": roadmap_items,
"progression_state": compute_progression_state(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
),
"initiative_level": {
"blockers": unlinked_blockers,
"evidence": unlinked_evidence,
@@ -304,6 +400,8 @@ def get_initiative_steering_snapshot(
"id": _sid(b["id"]),
"title": b["title"],
"status": b["status"],
"item_kind": b.get("item_kind"),
"parent_backlog_id": _sid(b.get("parent_backlog_id")),
"converted_action_id": _sid(b.get("converted_action_id")),
}
for b in backlog
+3 -3
View File
@@ -21,11 +21,11 @@ def get_active_initiatives(
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
SELECT id, tenant_id, title, goal, vision, target_state_summary, archetype_key,
status, priority, portfolio_rank, owner_actor_id, created_at, updated_at
FROM initiatives
WHERE tenant_id = %s AND status IN ('active', 'paused')
ORDER BY updated_at DESC, title
ORDER BY portfolio_rank ASC NULLS LAST, updated_at DESC, title
"""
params: list[Any] = [ctx.tenant_id]
if limit is not None:
+23
View File
@@ -0,0 +1,23 @@
"""Portfolio steering read model — K-Ext-5."""
from __future__ import annotations
from typing import Any
from steering.portfolio.aggregate import aggregate_portfolio_steering
from tenant_context import TenantContext
def get_portfolio_steering(
ctx: TenantContext,
*,
max_initiatives: int = 50,
total_attention: int = 30,
total_next_work: int = 15,
) -> dict[str, Any]:
return aggregate_portfolio_steering(
ctx,
max_initiatives=max_initiatives,
total_attention=total_attention,
total_next_work=total_next_work,
)
+21
View File
@@ -0,0 +1,21 @@
from entity_archetypes.registry import (
ENTITY_ARCHETYPES,
INITIATIVE_ARCHETYPES,
PROJECT_ARCHETYPES,
archetype_label,
list_archetypes,
mirror_project_archetype_key,
resolve_default_method_key,
validate_archetype_key,
)
__all__ = [
"ENTITY_ARCHETYPES",
"INITIATIVE_ARCHETYPES",
"PROJECT_ARCHETYPES",
"archetype_label",
"list_archetypes",
"mirror_project_archetype_key",
"resolve_default_method_key",
"validate_archetype_key",
]
+211
View File
@@ -0,0 +1,211 @@
"""System-Archetypen (AP1.10 + AP2.0) — Seeds, Bindings, Spiegel Project."""
from __future__ import annotations
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from entity_archetypes.ui_profiles import INITIATIVE_UI_PROFILES, resolve_ui_profile
# initiative suffix → default method (shared by initiative + project mirror)
_METHOD_BY_SUFFIX: dict[str, str] = {
"generic": "generic_operating",
"maturity_journey": "maturity_progression",
"linear_project": "sequential_dependency",
"recurring_program": "recurring_control",
"support_queue": "queue_pull",
"program": "program_delivery",
"product": "continuous_product",
"dispute_case": "dispute_procedure",
"content_project": "chapter_based_progression",
}
_INITIATIVE_SPEC_META: tuple[tuple[str, str, str], ...] = (
("generic", "Allgemeines Vorhaben", "Fallback ohne spezielle Steuerungsvorlage."),
(
"maturity_journey",
"Reifegrad-Entwicklung",
"Mehrstufige Entwicklung, Routinen, Graph-Voraussetzungen.",
),
(
"linear_project",
"Lineares Vorhaben",
"Einmalprojekte mit Pfaden, Gates und Graph.",
),
(
"recurring_program",
"Dauerprogramm / Rhythmus",
"Haushalt, Rhythmen, Abweichungs-Steuerung.",
),
(
"support_queue",
"Inbox / Queue",
"Ad-hoc-Eingang, triage, thematische Zuordnung.",
),
(
"program",
"Programm (begrenzt)",
"Phasen, Release-Programm mit Abschluss.",
),
(
"product",
"Produkt (kontinuierlich)",
"Dauerbetrieb, Wartung, Issues, Weiterentwicklung.",
),
(
"dispute_case",
"Verfahren / Konflikt",
"Reaktive Steuerung, Fristen, Entscheidungen.",
),
(
"content_project",
"Inhalt / Kapitel",
"Bücher, Konzepte, Kapitelstruktur.",
),
)
def _build_specs() -> tuple[dict[str, Any], ...]:
specs: list[dict[str, Any]] = []
for suffix, label, description in _INITIATIVE_SPEC_META:
method = _METHOD_BY_SUFFIX[suffix]
initiative_key = f"initiative.{suffix}"
ui_profile = INITIATIVE_UI_PROFILES.get(initiative_key, {})
specs.append(
{
"key": initiative_key,
"entity_type": "initiative",
"label": label,
"description": description,
"is_system": True,
"default_method_key": method,
"default_method_profile_key": None,
"ui_profile_json": ui_profile,
}
)
specs.append(
{
"key": f"project.{suffix}",
"entity_type": "project",
"label": label,
"description": f"Project-Spiegel: {description}",
"is_system": True,
"default_method_key": method,
"default_method_profile_key": None,
"ui_profile_json": {},
}
)
return tuple(specs)
ENTITY_ARCHETYPES: tuple[dict[str, Any], ...] = _build_specs()
INITIATIVE_ARCHETYPES: tuple[dict[str, Any], ...] = tuple(
item for item in ENTITY_ARCHETYPES if item["entity_type"] == "initiative"
)
PROJECT_ARCHETYPES: tuple[dict[str, Any], ...] = tuple(
item for item in ENTITY_ARCHETYPES if item["entity_type"] == "project"
)
_ARCHETYPE_INDEX: dict[tuple[str, str], dict[str, Any]] = {
(item["entity_type"], item["key"]): item for item in ENTITY_ARCHETYPES
}
_KEY_INDEX: dict[str, dict[str, Any]] = {item["key"]: item for item in ENTITY_ARCHETYPES}
def _list_archetypes_from_memory(*, entity_type: Optional[str] = None) -> list[dict[str, Any]]:
items = ENTITY_ARCHETYPES
if entity_type is not None:
items = tuple(i for i in items if i["entity_type"] == entity_type)
return [_public_archetype(item) for item in items]
def _public_archetype(item: dict[str, Any]) -> dict[str, Any]:
return {
"key": item["key"],
"entity_type": item["entity_type"],
"label": item["label"],
"description": item["description"],
"is_system": item["is_system"],
"default_method_key": item["default_method_key"],
"default_method_profile_key": item.get("default_method_profile_key"),
}
def _enrich_row(row: dict[str, Any]) -> dict[str, Any]:
base = dict(row)
spec = _KEY_INDEX.get(base.get("key", ""))
if spec:
base.setdefault("default_method_key", spec["default_method_key"])
base.setdefault("default_method_profile_key", spec.get("default_method_profile_key"))
return base
def list_archetypes(*, entity_type: Optional[str] = None) -> list[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
if entity_type is None:
cur.execute(
"""
SELECT archetype_key AS key, entity_type, label, description, is_system
FROM entity_archetypes
ORDER BY entity_type ASC, archetype_key ASC
"""
)
else:
cur.execute(
"""
SELECT archetype_key AS key, entity_type, label, description, is_system
FROM entity_archetypes
WHERE entity_type = %s
ORDER BY archetype_key ASC
""",
(entity_type,),
)
rows = cur.fetchall()
if rows:
return [_enrich_row(dict(row)) for row in rows]
except Exception:
pass
finally:
conn.close()
return _list_archetypes_from_memory(entity_type=entity_type)
def validate_archetype_key(*, entity_type: str, archetype_key: str) -> None:
if (entity_type, archetype_key) not in _ARCHETYPE_INDEX:
raise ValueError(f"Unbekannter Archetyp: {archetype_key}")
def archetype_label(*, entity_type: str, archetype_key: str) -> Optional[str]:
item = _ARCHETYPE_INDEX.get((entity_type, archetype_key))
return item["label"] if item else None
def resolve_default_method_key(archetype_key: str) -> str:
spec = _KEY_INDEX.get(archetype_key)
if not spec:
return "generic_operating"
return spec.get("default_method_key", "generic_operating")
def get_ui_profile_json(archetype_key: str) -> dict[str, Any]:
"""UI-Profil aus Registry-Seed (DB-Sync-Quelle)."""
spec = _KEY_INDEX.get(archetype_key)
if spec and spec.get("ui_profile_json"):
return dict(spec["ui_profile_json"])
return resolve_ui_profile(archetype_key)
def mirror_project_archetype_key(initiative_archetype_key: str) -> str:
if initiative_archetype_key.startswith("initiative."):
suffix = initiative_archetype_key[len("initiative.") :]
candidate = f"project.{suffix}"
if ( "project", candidate) in _ARCHETYPE_INDEX:
return candidate
return "project.generic"
+238
View File
@@ -0,0 +1,238 @@
"""UI-Profile für Initiative-Archetypen — AP2.3a / AP2.3f."""
from __future__ import annotations
from typing import Any
_PRODUCT_PROCESS = (
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
{"key": "sprint-plan", "to": "/plan/sprint", "label": "Sprint planen", "mode": "plan"},
{"key": "sprint-work", "to": "/work/sprint", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_LINEAR_PROCESS = (
{"key": "gates", "to": "/plan/gates", "label": "Zielzustände", "mode": "plan"},
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_MATURITY_PROCESS = (
{"key": "gates", "to": "/plan/gates", "label": "Stufen", "mode": "plan"},
{"key": "journey", "to": "/control/journey", "label": "Rhythmen", "mode": "control"},
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_PROGRAM_PROCESS = (
{"key": "gates", "to": "/plan/gates", "label": "Phasen", "mode": "plan"},
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_SUPPORT_QUEUE_PROCESS = (
{"key": "inbox", "to": "/plan/inbox", "label": "Eingang", "mode": "plan"},
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_CONTENT_PROCESS = (
{"key": "gates", "to": "/plan/gates", "label": "Kapitel", "mode": "plan"},
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_DISPUTE_PROCESS = (
{"key": "work", "to": "/work/today", "label": "Ausführen", "mode": "work"},
{"key": "control", "to": "/control/status", "label": "Kontrolle", "mode": "control"},
)
_COMMON_OM_SLICES = (
"actions",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
)
GENERIC_UI_PROFILE: dict[str, Any] = {
"processSteps": [],
"planDefaultRoute": "/plan/profile",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": None,
"workNavKeys": None,
"dataSlices": [
"actions",
"backlog",
"roadmap",
"projects",
"blockers",
*_COMMON_OM_SLICES[1:],
],
"enabledModes": ["plan", "work", "control"],
}
INITIATIVE_UI_PROFILES: dict[str, dict[str, Any]] = {
"initiative.generic": dict(GENERIC_UI_PROFILE),
"initiative.product": {
"processSteps": list(_PRODUCT_PROCESS),
"planDefaultRoute": "/plan/inbox",
"workDefaultRoute": "/work/sprint",
"workDefaultRouteWithoutActiveWorkCycle": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "inbox", "work", "sprint", "gates"],
"workNavKeys": ["sprint", "today", "mine"],
"dataSlices": [
"backlog",
"actions",
"roadmap",
"work_cycles",
"projects",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.linear_project": {
"processSteps": list(_LINEAR_PROCESS),
"planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "structure", "gates", "inbox", "work"],
"workNavKeys": ["today", "mine", "sprint"],
"dataSlices": [
"backlog",
"actions",
"roadmap",
"projects",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.maturity_journey": {
"processSteps": list(_MATURITY_PROCESS),
"planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "gates", "work"],
"workNavKeys": ["today", "mine", "sprint"],
"dataSlices": [
"actions",
"roadmap",
"blockers",
"evidence",
"decisions",
"reviews",
"recurring",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.program": {
"processSteps": list(_PROGRAM_PROCESS),
"planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "structure", "gates", "inbox", "sprint", "work"],
"workNavKeys": ["today", "mine", "sprint"],
"dataSlices": [
"backlog",
"actions",
"roadmap",
"projects",
"work_cycles",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.support_queue": {
"processSteps": list(_SUPPORT_QUEUE_PROCESS),
"planDefaultRoute": "/plan/inbox",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "inbox", "work"],
"workNavKeys": ["today", "mine"],
"dataSlices": [
"backlog",
"actions",
"blockers",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.recurring_program": {
"processSteps": list(_MATURITY_PROCESS),
"planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
"workNavKeys": ["today", "mine"],
"dataSlices": [
"actions",
"roadmap",
"recurring",
"blockers",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.content_project": {
"processSteps": list(_CONTENT_PROCESS),
"planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
"workNavKeys": ["today", "mine"],
"dataSlices": [
"actions",
"roadmap",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
"initiative.dispute_case": {
"processSteps": list(_DISPUTE_PROCESS),
"planDefaultRoute": "/plan/profile",
"workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "work"],
"workNavKeys": ["today", "mine"],
"dataSlices": [
"actions",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
],
"enabledModes": ["plan", "work", "control"],
},
}
def resolve_ui_profile(archetype_key: str) -> dict[str, Any]:
"""UI-Profil aus Code-Seed; unbekannte Archetypen → Generic-Fallback."""
profile = INITIATIVE_UI_PROFILES.get(archetype_key)
resolved = dict(profile) if profile else dict(GENERIC_UI_PROFILE)
slices = resolved.get("dataSlices") or []
resolved["omCapabilities"] = list(resolved.get("omCapabilities") or slices)
resolved.pop("uiFeatures", None)
return resolved
+20
View File
@@ -0,0 +1,20 @@
from entity_fields.definitions import FIELD_DEFINITIONS
from entity_fields.service import (
get_entity_field_values,
get_initiative_archetype_key,
list_field_definitions,
patch_entity_field_values,
)
from entity_fields.sync import sync_entity_field_registry_to_db
from entity_fields.validation import normalize_field_value, validate_required_fields
__all__ = [
"FIELD_DEFINITIONS",
"get_entity_field_values",
"get_initiative_archetype_key",
"list_field_definitions",
"normalize_field_value",
"patch_entity_field_values",
"sync_entity_field_registry_to_db",
"validate_required_fields",
]
+88
View File
@@ -0,0 +1,88 @@
"""System-Felddefinitionen (Seed) — AP1.10b / AP2.0b."""
from __future__ import annotations
from typing import Any
FIELD_DEFINITIONS: tuple[dict[str, Any], ...] = (
{
"archetype_key": "initiative.program",
"field_key": "stakeholder_map",
"field_type": "longtext",
"label": "Stakeholder-Übersicht",
"required": False,
"searchable": True,
"sort_order": 10,
"validation_json": {},
},
{
"archetype_key": "initiative.program",
"field_key": "success_criteria",
"field_type": "longtext",
"label": "Erfolgskriterien",
"required": False,
"searchable": True,
"sort_order": 20,
"validation_json": {},
},
{
"archetype_key": "initiative.product",
"field_key": "release_theme",
"field_type": "text",
"label": "Release-Thema",
"required": False,
"searchable": True,
"sort_order": 10,
"validation_json": {},
},
{
"archetype_key": "initiative.product",
"field_key": "metrics",
"field_type": "longtext",
"label": "Metriken / KPIs",
"required": False,
"searchable": True,
"sort_order": 20,
"validation_json": {},
},
{
"archetype_key": "initiative.maturity_journey",
"field_key": "current_focus",
"field_type": "text",
"label": "Aktueller Fokus",
"required": False,
"searchable": True,
"sort_order": 10,
"validation_json": {},
},
{
"archetype_key": "initiative.maturity_journey",
"field_key": "training_frequency",
"field_type": "enum",
"label": "Trainingsfrequenz",
"required": False,
"searchable": False,
"sort_order": 20,
"validation_json": {"options": ["daily", "3x_week", "weekly", "flexible"]},
},
{
"archetype_key": "initiative.content_project",
"field_key": "manuscript_status",
"field_type": "text",
"label": "Manuskript-Status",
"required": False,
"searchable": True,
"sort_order": 10,
"validation_json": {},
},
{
"archetype_key": "initiative.content_project",
"field_key": "word_count_goal",
"field_type": "number",
"label": "Wortziel",
"required": False,
"searchable": False,
"sort_order": 20,
"validation_json": {},
},
)
+206
View File
@@ -0,0 +1,206 @@
"""Entity Field System — Lesen/Schreiben dynamischer Feldwerte — AP1.10b/10c."""
from __future__ import annotations
from typing import Any, Optional
from psycopg2.extras import Json, RealDictCursor
from db import get_connection
from entity_fields.validation import normalize_field_value, validate_required_fields
def _serialize_definition(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
if result.get("id"):
result["id"] = str(result["id"])
validation = result.get("validation_json")
if validation is None:
result["validation_json"] = {}
return result
def _api_value_from_row(row: dict[str, Any], field_type: str) -> Any:
if field_type == "number":
if row.get("value_number") is not None:
return float(row["value_number"])
return None
if field_type == "boolean":
if row.get("value_boolean") is not None:
return bool(row["value_boolean"])
return False
if field_type == "date":
value_date = row.get("value_date")
if value_date is not None:
return value_date.isoformat()
return None
text = row.get("value_text") or ""
return text
def list_field_definitions(
*,
archetype_key: str,
) -> list[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, archetype_key, field_key, field_type, label,
required, searchable, sort_order, validation_json
FROM field_definitions
WHERE archetype_key = %s
ORDER BY sort_order ASC, field_key ASC
""",
(archetype_key,),
)
return [_serialize_definition(dict(row)) for row in cur.fetchall()]
finally:
conn.close()
def get_entity_field_values(
*,
tenant_id: str,
entity_type: str,
entity_id: str,
definitions: list[dict[str, Any]],
) -> dict[str, Any]:
if not definitions:
return {}
field_keys = [item["field_key"] for item in definitions]
type_by_key = {item["field_key"]: item["field_type"] for item in definitions}
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT field_key, value_text, value_number, value_boolean, value_date
FROM field_values
WHERE tenant_id = %s
AND entity_type = %s
AND entity_id = %s
AND field_key = ANY(%s)
""",
(tenant_id, entity_type, entity_id, field_keys),
)
rows = {row["field_key"]: dict(row) for row in cur.fetchall()}
finally:
conn.close()
result: dict[str, Any] = {}
for field_key in field_keys:
row = rows.get(field_key)
if row is None:
field_type = type_by_key[field_key]
if field_type == "boolean":
result[field_key] = False
else:
result[field_key] = None if field_type in {"number", "date"} else ""
else:
result[field_key] = _api_value_from_row(row, type_by_key[field_key])
return result
def patch_entity_field_values(
*,
tenant_id: str,
entity_type: str,
entity_id: str,
definitions: list[dict[str, Any]],
values: dict[str, Any],
) -> dict[str, Any]:
if not values:
return get_entity_field_values(
tenant_id=tenant_id,
entity_type=entity_type,
entity_id=entity_id,
definitions=definitions,
)
allowed_keys = {item["field_key"] for item in definitions}
unknown = sorted(set(values.keys()) - allowed_keys)
if unknown:
raise ValueError(f"Unbekannte Felder: {', '.join(unknown)}")
definition_by_key = {item["field_key"]: item for item in definitions}
merged = get_entity_field_values(
tenant_id=tenant_id,
entity_type=entity_type,
entity_id=entity_id,
definitions=definitions,
)
merged.update(values)
validate_required_fields(definitions=definitions, values=merged)
conn = get_connection()
try:
with conn.cursor() as cur:
for field_key, raw_value in values.items():
definition = definition_by_key[field_key]
normalized = normalize_field_value(
field_type=definition["field_type"],
raw_value=raw_value,
validation_json=definition.get("validation_json"),
)
cur.execute(
"""
INSERT INTO field_values (
tenant_id, entity_type, entity_id, field_key,
value_json, value_text, value_number, value_boolean, value_date
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (tenant_id, entity_type, entity_id, field_key) DO UPDATE SET
value_json = EXCLUDED.value_json,
value_text = EXCLUDED.value_text,
value_number = EXCLUDED.value_number,
value_boolean = EXCLUDED.value_boolean,
value_date = EXCLUDED.value_date,
updated_at = NOW()
""",
(
tenant_id,
entity_type,
entity_id,
field_key,
Json(normalized["value_json"]) if normalized["value_json"] is not None else None,
normalized["value_text"],
normalized["value_number"],
normalized["value_boolean"],
normalized["value_date"],
),
)
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
return get_entity_field_values(
tenant_id=tenant_id,
entity_type=entity_type,
entity_id=entity_id,
definitions=definitions,
)
def get_initiative_archetype_key(*, tenant_id: str, initiative_id: str) -> Optional[str]:
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT archetype_key
FROM initiatives
WHERE tenant_id = %s AND id = %s
""",
(tenant_id, initiative_id),
)
row = cur.fetchone()
return row[0] if row else None
finally:
conn.close()
+82
View File
@@ -0,0 +1,82 @@
"""Sync Entity-Archetypen und Felddefinitionen in PostgreSQL — AP1.10b / AP2.0b."""
from __future__ import annotations
import json
from db import get_connection
from entity_archetypes.registry import ENTITY_ARCHETYPES
from entity_fields.definitions import FIELD_DEFINITIONS
def sync_entity_field_registry_to_db() -> int:
conn = get_connection()
try:
with conn.cursor() as cur:
for archetype in ENTITY_ARCHETYPES:
ui_profile = archetype.get("ui_profile_json") or {}
cur.execute(
"""
INSERT INTO entity_archetypes (
archetype_key, entity_type, label, description, is_system,
ui_profile_json
)
VALUES (%s, %s, %s, %s, %s, %s::jsonb)
ON CONFLICT (archetype_key) DO UPDATE SET
entity_type = EXCLUDED.entity_type,
label = EXCLUDED.label,
description = EXCLUDED.description,
is_system = EXCLUDED.is_system,
ui_profile_json = EXCLUDED.ui_profile_json,
updated_at = NOW()
""",
(
archetype["key"],
archetype["entity_type"],
archetype["label"],
archetype["description"],
archetype["is_system"],
json.dumps(ui_profile),
),
)
for field_def in FIELD_DEFINITIONS:
validation_json = field_def.get("validation_json") or {}
cur.execute(
"""
INSERT INTO field_definitions (
archetype_key, field_key, field_type, label,
required, searchable, sort_order, validation_json
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb)
ON CONFLICT (archetype_key, field_key) DO UPDATE SET
field_type = EXCLUDED.field_type,
label = EXCLUDED.label,
required = EXCLUDED.required,
searchable = EXCLUDED.searchable,
sort_order = EXCLUDED.sort_order,
validation_json = EXCLUDED.validation_json,
updated_at = NOW()
""",
(
field_def["archetype_key"],
field_def["field_key"],
field_def["field_type"],
field_def["label"],
field_def["required"],
field_def["searchable"],
field_def["sort_order"],
json.dumps(validation_json),
),
)
conn.commit()
print(
"[entity_fields] Sync OK — "
f"{len(ENTITY_ARCHETYPES)} Archetyp(en), "
f"{len(FIELD_DEFINITIONS)} Felddefinition(en)"
)
return 0
except Exception as exc:
conn.rollback()
print(f"[entity_fields] Sync FAIL: {exc}")
return 1
+153
View File
@@ -0,0 +1,153 @@
"""Validierung dynamischer Feldwerte gegen Definitionen — AP1.10b/10c."""
from __future__ import annotations
import re
from datetime import date, datetime
from typing import Any, Optional
from urllib.parse import urlparse
VALID_FIELD_TYPES = frozenset(
{"text", "longtext", "number", "boolean", "date", "enum", "actor_ref", "url"}
)
_URL_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
def _parse_date(value: str) -> date:
try:
return date.fromisoformat(value)
except ValueError as exc:
raise ValueError(f"Ungültiges Datum: {value}") from exc
def _validate_url(value: str) -> None:
if not value.strip():
return
parsed = urlparse(value.strip())
if parsed.scheme and parsed.netloc:
return
if _URL_SCHEME_RE.match(value.strip()):
return
raise ValueError(f"Ungültige URL: {value}")
def normalize_field_value(
*,
field_type: str,
raw_value: Any,
validation_json: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""Wert normalisieren und in DB-Spalten aufteilen."""
validation_json = validation_json or {}
if field_type in {"text", "longtext", "url", "actor_ref", "enum"}:
if raw_value is None:
text = ""
elif not isinstance(raw_value, str):
raise ValueError(f"Feld erwartet Text, erhalten: {type(raw_value).__name__}")
else:
text = raw_value.strip()
if field_type == "url" and text:
_validate_url(text)
if field_type == "enum" and text:
options = validation_json.get("options") or []
if options and text not in options:
raise ValueError(f"Ungültiger Enum-Wert: {text}")
return {
"value_json": None,
"value_text": text,
"value_number": None,
"value_boolean": None,
"value_date": None,
"api_value": text,
}
if field_type == "number":
if raw_value is None or raw_value == "":
return {
"value_json": None,
"value_text": "",
"value_number": None,
"value_boolean": None,
"value_date": None,
"api_value": None,
}
try:
number = float(raw_value)
except (TypeError, ValueError) as exc:
raise ValueError(f"Ungültige Zahl: {raw_value}") from exc
return {
"value_json": None,
"value_text": str(number),
"value_number": number,
"value_boolean": None,
"value_date": None,
"api_value": number,
}
if field_type == "boolean":
if raw_value is None:
bool_val = False
elif isinstance(raw_value, bool):
bool_val = raw_value
elif isinstance(raw_value, str):
lowered = raw_value.strip().lower()
if lowered in {"true", "1", "yes", "on"}:
bool_val = True
elif lowered in {"false", "0", "no", "off", ""}:
bool_val = False
else:
raise ValueError(f"Ungültiger Boolean-Wert: {raw_value}")
else:
bool_val = bool(raw_value)
return {
"value_json": None,
"value_text": "true" if bool_val else "false",
"value_number": None,
"value_boolean": bool_val,
"value_date": None,
"api_value": bool_val,
}
if field_type == "date":
if raw_value is None or raw_value == "":
return {
"value_json": None,
"value_text": "",
"value_number": None,
"value_boolean": None,
"value_date": None,
"api_value": None,
}
if isinstance(raw_value, date) and not isinstance(raw_value, datetime):
parsed = raw_value
elif isinstance(raw_value, str):
parsed = _parse_date(raw_value)
else:
raise ValueError(f"Ungültiges Datum: {raw_value}")
iso = parsed.isoformat()
return {
"value_json": None,
"value_text": iso,
"value_number": None,
"value_boolean": None,
"value_date": parsed,
"api_value": iso,
}
raise ValueError(f"Unbekannter Feldtyp: {field_type}")
def validate_required_fields(
*,
definitions: list[dict[str, Any]],
values: dict[str, Any],
) -> None:
for definition in definitions:
if not definition.get("required"):
continue
key = definition["field_key"]
raw = values.get(key)
if raw is None or (isinstance(raw, str) and not raw.strip()):
raise ValueError(f"Pflichtfeld fehlt: {definition.get('label') or key}")
+2 -1
View File
@@ -23,8 +23,9 @@ fi
if [ "${SKIP_REGISTRY_SYNC}" != "1" ] && [ "${SKIP_REGISTRY_SYNC}" != "true" ] && [ "${SKIP_REGISTRY_SYNC}" != "yes" ]; then
python sync_prompt_feature_config.py
python sync_entity_field_registry.py
else
echo "[SKIP_REGISTRY_SYNC] Feature/Prompt/Config-Sync übersprungen"
echo "[SKIP_REGISTRY_SYNC] Feature/Prompt/Config/EFS-Sync übersprungen"
fi
export KAIRO_DB_READY=1
+9
View File
@@ -63,7 +63,9 @@ from routers import ( # noqa: E402
blockers,
config,
decisions,
entity_archetypes,
evidence,
execution_plan,
features,
initiatives,
journey,
@@ -77,6 +79,8 @@ from routers import ( # noqa: E402
steering,
tasks,
workspace,
operational,
work_cycles,
)
app.include_router(auth.router)
@@ -85,6 +89,7 @@ app.include_router(features.router)
app.include_router(prompts.router)
app.include_router(config.router)
app.include_router(initiatives.router)
app.include_router(entity_archetypes.router)
app.include_router(journey.initiative_router)
app.include_router(journey.roadmap_router)
app.include_router(actions.router)
@@ -96,7 +101,9 @@ app.include_router(backlog.router)
app.include_router(milestones.router)
app.include_router(roadmap.initiative_router)
app.include_router(roadmap.items_router)
app.include_router(roadmap.deps_router)
app.include_router(roadmap.criteria_router)
app.include_router(execution_plan.initiative_router)
app.include_router(evidence.router)
app.include_router(decisions.router)
app.include_router(reviews.router)
@@ -104,6 +111,8 @@ app.include_router(recurring.router)
app.include_router(steering.router)
app.include_router(actors.router)
app.include_router(workspace.router)
app.include_router(operational.router)
app.include_router(work_cycles.initiative_router)
@app.get("/api/health")
+1
View File
@@ -0,0 +1 @@
"""Package marker for method profile seeds."""
+73
View File
@@ -0,0 +1,73 @@
"""Referenz-Ausprägungen (Method Profiles) — Code-Seeds AP2.0b."""
from __future__ import annotations
from typing import Any, Optional
METHOD_PROFILES: tuple[dict[str, Any], ...] = (
{
"key": "maturity.karate_kumite",
"label": "Karate Kumite",
"description": "Mehrere Fähigkeiten mit Stufen, Routinen und Voraussetzungs-Graph.",
"initiative_archetype_key": "initiative.maturity_journey",
"method_key": "maturity_progression",
"seed_hints": {
"skill_count": 8,
"stages_per_skill": "5-7",
"graph_prerequisites": True,
},
},
{
"key": "content.book_writing",
"label": "Buch schreiben",
"description": "Kapitelstruktur, Schreib-APs, Review-Gates.",
"initiative_archetype_key": "initiative.content_project",
"method_key": "chapter_based_progression",
"seed_hints": {
"roadmap_item_type": "chapter",
"review_gates": True,
},
},
{
"key": "product.kairo_dev",
"label": "Kairo Entwicklung",
"description": "Kontinuierliches Produkt mit Gate-Orientierung und optionaler Sprint-Zeitbox.",
"initiative_archetype_key": "initiative.product",
"method_key": "continuous_product",
"seed_hints": {
"agile_iteration_profile": True,
"default_actor_setup": "po_plus_vibe_coder",
},
},
{
"key": "project.agile_iteration",
"label": "Projekt mit Sprint",
"description": "Lineares Projekt (A2) mit optionaler Agile-Iteration.",
"initiative_archetype_key": "initiative.linear_project",
"method_key": "sequential_dependency",
"seed_hints": {
"agile_iteration_profile": True,
},
},
)
_PROFILE_INDEX = {item["key"]: item for item in METHOD_PROFILES}
def get_method_profile(key: str) -> Optional[dict[str, Any]]:
item = _PROFILE_INDEX.get(key)
return dict(item) if item else None
def list_method_profiles(*, initiative_archetype_key: Optional[str] = None) -> list[dict[str, Any]]:
items = METHOD_PROFILES
if initiative_archetype_key:
items = tuple(
i for i in items if i["initiative_archetype_key"] == initiative_archetype_key
)
return [dict(item) for item in items]
def resolve_method_for_profile(profile_key: str) -> Optional[str]:
profile = get_method_profile(profile_key)
return profile["method_key"] if profile else None
@@ -0,0 +1,21 @@
-- AP1.12c: Backlog sort_order für Reorder im Plan-Modus
ALTER TABLE backlog_items
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
WITH ranked AS (
SELECT
id,
(ROW_NUMBER() OVER (
PARTITION BY tenant_id, initiative_id
ORDER BY created_at ASC, id ASC
) - 1) * 10 AS next_order
FROM backlog_items
)
UPDATE backlog_items bi
SET sort_order = ranked.next_order
FROM ranked
WHERE bi.id = ranked.id;
CREATE INDEX IF NOT EXISTS idx_backlog_items_sort
ON backlog_items (tenant_id, initiative_id, sort_order);
@@ -0,0 +1,16 @@
-- AP1.10a: Initiative Standardfelder + Archetyp-Schlüssel
ALTER TABLE initiatives
ADD COLUMN IF NOT EXISTS vision TEXT NOT NULL DEFAULT '';
ALTER TABLE initiatives
ADD COLUMN IF NOT EXISTS target_state_summary TEXT NOT NULL DEFAULT '';
ALTER TABLE initiatives
ADD COLUMN IF NOT EXISTS archetype_key VARCHAR(64) NOT NULL DEFAULT 'initiative.generic';
CREATE INDEX IF NOT EXISTS idx_initiatives_archetype
ON initiatives (tenant_id, archetype_key);
CREATE INDEX IF NOT EXISTS idx_initiatives_status_tenant
ON initiatives (tenant_id, status);
@@ -0,0 +1,59 @@
-- AP1.10b: Entity Field System (EFS) — Archetypen, Felddefinitionen, Werte
CREATE TABLE IF NOT EXISTS entity_archetypes (
archetype_key VARCHAR(64) PRIMARY KEY,
entity_type VARCHAR(64) NOT NULL,
label VARCHAR(255) NOT NULL,
description TEXT NOT NULL DEFAULT '',
is_system BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_entity_archetypes_entity_type
ON entity_archetypes (entity_type);
CREATE TABLE IF NOT EXISTS field_definitions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
archetype_key VARCHAR(64) NOT NULL
REFERENCES entity_archetypes (archetype_key) ON DELETE CASCADE,
field_key VARCHAR(64) NOT NULL,
field_type VARCHAR(32) NOT NULL
CHECK (field_type IN (
'text', 'longtext', 'number', 'boolean', 'date', 'enum', 'actor_ref', 'url'
)),
label VARCHAR(255) NOT NULL,
required BOOLEAN NOT NULL DEFAULT FALSE,
searchable BOOLEAN NOT NULL DEFAULT FALSE,
sort_order INTEGER NOT NULL DEFAULT 0,
validation_json JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (archetype_key, field_key)
);
CREATE INDEX IF NOT EXISTS idx_field_definitions_archetype
ON field_definitions (archetype_key, sort_order);
CREATE TABLE IF NOT EXISTS field_values (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants (id) ON DELETE CASCADE,
entity_type VARCHAR(64) NOT NULL,
entity_id UUID NOT NULL,
field_key VARCHAR(64) NOT NULL,
value_json JSONB,
value_text TEXT NOT NULL DEFAULT '',
value_number NUMERIC,
value_boolean BOOLEAN,
value_date DATE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (tenant_id, entity_type, entity_id, field_key)
);
CREATE INDEX IF NOT EXISTS idx_field_values_entity
ON field_values (tenant_id, entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_field_values_search
ON field_values (tenant_id, entity_type, field_key)
WHERE value_text <> '';
+12
View File
@@ -0,0 +1,12 @@
-- AP1.5d: Rekursive Tasks unter Action
ALTER TABLE tasks
ADD COLUMN IF NOT EXISTS parent_task_id UUID NULL
REFERENCES tasks (id) ON DELETE CASCADE;
CREATE INDEX IF NOT EXISTS idx_tasks_parent
ON tasks (tenant_id, parent_task_id)
WHERE parent_task_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_tasks_action_parent
ON tasks (tenant_id, action_id, parent_task_id);
@@ -0,0 +1,27 @@
-- AP2.0b: Project archetype_key (Spiegel der Initiative)
ALTER TABLE projects
ADD COLUMN IF NOT EXISTS archetype_key VARCHAR(64) NULL;
CREATE INDEX IF NOT EXISTS idx_projects_archetype
ON projects (tenant_id, archetype_key)
WHERE archetype_key IS NOT NULL;
-- Bestehende Projects: Mirror aus Initiative (einmalig)
UPDATE projects p
SET archetype_key = CASE i.archetype_key
WHEN 'initiative.generic' THEN 'project.generic'
WHEN 'initiative.maturity_journey' THEN 'project.maturity_journey'
WHEN 'initiative.linear_project' THEN 'project.linear_project'
WHEN 'initiative.recurring_program' THEN 'project.recurring_program'
WHEN 'initiative.support_queue' THEN 'project.support_queue'
WHEN 'initiative.program' THEN 'project.program'
WHEN 'initiative.product' THEN 'project.product'
WHEN 'initiative.dispute_case' THEN 'project.dispute_case'
WHEN 'initiative.content_project' THEN 'project.content_project'
ELSE 'project.generic'
END
FROM initiatives i
WHERE p.initiative_id = i.id
AND p.tenant_id = i.tenant_id
AND p.archetype_key IS NULL;
@@ -0,0 +1,17 @@
-- AP1.4d: Graph Engine — erweiterte Kantenarten + Parallelgruppe
ALTER TABLE roadmap_item_dependencies
DROP CONSTRAINT IF EXISTS roadmap_item_dependencies_dependency_type_check;
ALTER TABLE roadmap_item_dependencies
ADD CONSTRAINT roadmap_item_dependencies_dependency_type_check
CHECK (dependency_type IN (
'requires', 'blocks', 'related', 'parallel_group', 'optional_branch'
));
ALTER TABLE roadmap_item_dependencies
ADD COLUMN IF NOT EXISTS group_key VARCHAR(128) NULL;
CREATE INDEX idx_roadmap_deps_group_key
ON roadmap_item_dependencies(tenant_id, group_key)
WHERE group_key IS NOT NULL;
@@ -0,0 +1,17 @@
-- AP1.14: Plan-Snapshots (Plan-Revision) — Soll-Zustand getrennt von Ist
CREATE TABLE roadmap_plan_snapshots (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
roadmap_id UUID NOT NULL REFERENCES roadmaps(id) ON DELETE CASCADE,
revision_number INT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
plan_payload JSONB NOT NULL,
created_by_user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (tenant_id, initiative_id, revision_number)
);
CREATE INDEX idx_roadmap_plan_snapshots_initiative
ON roadmap_plan_snapshots(tenant_id, initiative_id, created_at DESC);
+24
View File
@@ -0,0 +1,24 @@
-- AP1.8a: Portfolio-Priorität (relatives Ranking im Tenant)
ALTER TABLE initiatives
ADD COLUMN IF NOT EXISTS portfolio_rank INT;
WITH ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY tenant_id
ORDER BY updated_at DESC, title
) - 1 AS rn
FROM initiatives
)
UPDATE initiatives AS i
SET portfolio_rank = ranked.rn
FROM ranked
WHERE i.id = ranked.id AND i.portfolio_rank IS NULL;
CREATE INDEX IF NOT EXISTS idx_initiatives_tenant_portfolio_rank
ON initiatives (tenant_id, portfolio_rank);
COMMENT ON COLUMN initiatives.portfolio_rank IS
'Relatives Portfolio-Ranking (0 = höchste Aufmerksamkeit). AP1.8a';
@@ -0,0 +1,32 @@
-- AP1.16a: Durchführungsplan — Action-Reihenfolge, kind, Abhängigkeiten
ALTER TABLE actions
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
ALTER TABLE actions
ADD COLUMN IF NOT EXISTS action_kind VARCHAR(32) NOT NULL DEFAULT 'delivery'
CHECK (action_kind IN ('delivery', 'planning', 'review'));
CREATE INDEX idx_actions_initiative_sort
ON actions(tenant_id, initiative_id, sort_order);
CREATE TABLE action_dependencies (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
predecessor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
successor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
dependency_kind VARCHAR(32) NOT NULL DEFAULT 'requires'
CHECK (dependency_kind IN ('requires', 'blocks', 'relates')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (tenant_id, predecessor_action_id, successor_action_id, dependency_kind)
);
CREATE INDEX idx_action_deps_predecessor
ON action_dependencies(tenant_id, predecessor_action_id);
CREATE INDEX idx_action_deps_successor
ON action_dependencies(tenant_id, successor_action_id);
CREATE INDEX idx_action_deps_initiative
ON action_dependencies(tenant_id, initiative_id);
@@ -0,0 +1,22 @@
-- AP1.7c — Actor Service Tokens für Operational API (Vibe-Coder / Agenten)
CREATE TABLE actor_service_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
actor_id UUID NOT NULL REFERENCES actors(id) ON DELETE CASCADE,
label VARCHAR(255) NOT NULL,
token_prefix VARCHAR(16) NOT NULL,
token_hash VARCHAR(64) NOT NULL,
capabilities JSONB NOT NULL DEFAULT '[]'::jsonb,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
expires_at TIMESTAMPTZ NULL,
last_used_at TIMESTAMPTZ NULL,
created_by_user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
revoked_at TIMESTAMPTZ NULL,
UNIQUE (token_prefix)
);
CREATE INDEX idx_actor_service_tokens_tenant ON actor_service_tokens(tenant_id);
CREATE INDEX idx_actor_service_tokens_actor ON actor_service_tokens(actor_id);
CREATE INDEX idx_actor_service_tokens_hash ON actor_service_tokens(token_hash);
+11
View File
@@ -0,0 +1,11 @@
-- AP2.0f — work_cycle (Zeitbox/Sprint) + actions.work_cycle_id
ALTER TABLE roadmap_items DROP CONSTRAINT IF EXISTS roadmap_items_item_type_check;
ALTER TABLE roadmap_items ADD CONSTRAINT roadmap_items_item_type_check
CHECK (item_type IN ('milestone', 'review_gate', 'maturity_stage', 'work_cycle'));
ALTER TABLE actions
ADD COLUMN work_cycle_id UUID NULL REFERENCES roadmap_items(id) ON DELETE SET NULL;
CREATE INDEX idx_actions_work_cycle ON actions(tenant_id, work_cycle_id)
WHERE work_cycle_id IS NOT NULL;
@@ -0,0 +1,26 @@
-- AP2.2e: Sprint-Planung — Item-Arten, Feature-Referenz, Unplan-Support
ALTER TABLE actions DROP CONSTRAINT IF EXISTS actions_action_kind_check;
ALTER TABLE actions
ADD CONSTRAINT actions_action_kind_check
CHECK (action_kind IN ('delivery', 'planning', 'review', 'bug', 'issue'));
ALTER TABLE actions
ADD COLUMN IF NOT EXISTS parent_action_id UUID NULL
REFERENCES actions (id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_actions_parent
ON actions (tenant_id, initiative_id, parent_action_id)
WHERE parent_action_id IS NOT NULL;
ALTER TABLE backlog_items
ADD COLUMN IF NOT EXISTS item_kind VARCHAR(32) NOT NULL DEFAULT 'story'
CHECK (item_kind IN ('story', 'bug', 'issue'));
ALTER TABLE backlog_items
ADD COLUMN IF NOT EXISTS parent_action_id UUID NULL
REFERENCES actions (id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_backlog_parent_action
ON backlog_items (tenant_id, initiative_id, parent_action_id)
WHERE parent_action_id IS NOT NULL;
@@ -0,0 +1,4 @@
-- AP2.3a: UI-Profil pro Archetyp (Registry-Sync → Frontend Operating Context)
ALTER TABLE entity_archetypes
ADD COLUMN IF NOT EXISTS ui_profile_json JSONB NOT NULL DEFAULT '{}'::jsonb;
@@ -0,0 +1,14 @@
-- AP2.2f / ADP Backlog Epic-Hierarchie — parent_backlog_id + item_kind epic
ALTER TABLE backlog_items
ADD COLUMN IF NOT EXISTS parent_backlog_id UUID NULL
REFERENCES backlog_items (id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_backlog_parent_backlog
ON backlog_items (tenant_id, initiative_id, parent_backlog_id)
WHERE parent_backlog_id IS NOT NULL;
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
ALTER TABLE backlog_items
ADD CONSTRAINT backlog_items_item_kind_check
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic'));
@@ -0,0 +1,11 @@
-- P7: Technische Schuld — item_kind / action_kind tech_debt
ALTER TABLE actions DROP CONSTRAINT IF EXISTS actions_action_kind_check;
ALTER TABLE actions
ADD CONSTRAINT actions_action_kind_check
CHECK (action_kind IN ('delivery', 'planning', 'review', 'bug', 'issue', 'tech_debt'));
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
ALTER TABLE backlog_items
ADD CONSTRAINT backlog_items_item_kind_check
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic', 'tech_debt'));
@@ -0,0 +1,25 @@
-- AP A1.1 — CadenceInstance (minimal): eine offene Instanz pro Recurring, Tages-Tracking
CREATE TABLE cadence_instances (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
recurring_element_id UUID NOT NULL REFERENCES recurring_elements(id) ON DELETE CASCADE,
status VARCHAR(32) NOT NULL DEFAULT 'open'
CHECK (status IN ('open', 'completed')),
due_at TIMESTAMPTZ NOT NULL,
completed_at TIMESTAMPTZ NULL,
measurement_note TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_cadence_instances_tenant_recurring
ON cadence_instances(tenant_id, recurring_element_id);
CREATE INDEX idx_cadence_instances_open_due
ON cadence_instances(tenant_id, due_at)
WHERE status = 'open';
CREATE UNIQUE INDEX idx_cadence_instances_one_open_per_recurring
ON cadence_instances(recurring_element_id)
WHERE status = 'open';
@@ -0,0 +1,9 @@
-- AP A1.2 — RecurringElement an Reifegrad-Stufe binden (Activity Set)
ALTER TABLE recurring_elements
ADD COLUMN roadmap_item_id UUID NULL
REFERENCES roadmap_items(id) ON DELETE SET NULL;
CREATE INDEX idx_recurring_elements_stage
ON recurring_elements(tenant_id, roadmap_item_id)
WHERE roadmap_item_id IS NOT NULL;
@@ -0,0 +1,26 @@
-- AP-A1-PM-2: Progression graph — join_gate, strand binding, recurring strand
ALTER TABLE roadmap_items
DROP CONSTRAINT IF EXISTS roadmap_items_item_type_check;
ALTER TABLE roadmap_items
ADD CONSTRAINT roadmap_items_item_type_check
CHECK (item_type IN (
'milestone', 'review_gate', 'maturity_stage', 'work_cycle', 'join_gate'
));
ALTER TABLE roadmap_items
ADD COLUMN IF NOT EXISTS strand_project_id UUID NULL
REFERENCES projects(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_roadmap_items_strand
ON roadmap_items(tenant_id, strand_project_id)
WHERE strand_project_id IS NOT NULL;
ALTER TABLE recurring_elements
ADD COLUMN IF NOT EXISTS project_id UUID NULL
REFERENCES projects(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_recurring_elements_project
ON recurring_elements(tenant_id, project_id)
WHERE project_id IS NOT NULL;
@@ -0,0 +1,51 @@
-- Unified Schedule & Cadence Layer (ADP v0.1)
CREATE TABLE schedules (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
schedule_kind VARCHAR(16) NOT NULL DEFAULT 'interval'
CHECK (schedule_kind IN ('interval', 'weekdays')),
interval_days INT NULL CHECK (interval_days IS NULL OR interval_days > 0),
weekday_mask INT NOT NULL DEFAULT 0,
pause_until DATE NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_schedules_tenant ON schedules(tenant_id);
ALTER TABLE recurring_elements
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
REFERENCES schedules(id) ON DELETE SET NULL;
ALTER TABLE recurring_elements
ADD COLUMN IF NOT EXISTS action_id UUID NULL
REFERENCES actions(id) ON DELETE CASCADE;
CREATE UNIQUE INDEX idx_recurring_elements_action
ON recurring_elements(action_id)
WHERE action_id IS NOT NULL;
ALTER TABLE actions
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
REFERENCES schedules(id) ON DELETE SET NULL;
-- Backfill: one schedule per recurring without schedule_id
DO $$
DECLARE
r RECORD;
sid UUID;
idays INT;
BEGIN
FOR r IN
SELECT id, tenant_id, interval_days
FROM recurring_elements
WHERE schedule_id IS NULL
LOOP
idays := GREATEST(COALESCE(r.interval_days, 1), 1);
INSERT INTO schedules (tenant_id, schedule_kind, interval_days, weekday_mask)
VALUES (r.tenant_id, 'interval', idays, 0)
RETURNING id INTO sid;
UPDATE recurring_elements SET schedule_id = sid WHERE id = r.id;
END LOOP;
END $$;
+92
View File
@@ -0,0 +1,92 @@
"""Operational API auth — Session or Actor Service Token (AP1.7c)."""
from __future__ import annotations
from typing import Callable, Optional
from fastapi import Depends, Header, HTTPException
from auth import AUTH_HEADER, get_session
from capabilities import _enforce_capability
from services.actor_service_tokens import validate_service_token
from tenant_context import TenantContext, resolve_tenant_context
ACTOR_TOKEN_HEADER = "X-Actor-Token"
def _extract_actor_token(
x_actor_token: Optional[str],
authorization: Optional[str],
) -> Optional[str]:
if x_actor_token and x_actor_token.strip():
return x_actor_token.strip()
if authorization:
scheme, _, value = authorization.partition(" ")
if scheme.lower() == "bearer" and value.strip():
return value.strip()
return None
def resolve_service_token_context(raw_token: str) -> TenantContext:
resolved = validate_service_token(raw_token)
if not resolved:
raise HTTPException(status_code=401, detail="Ungültiger oder abgelaufener Actor-Token")
return TenantContext(
user_id="",
email="",
display_name=resolved["actor_name"],
portal_role="",
tenant_id=resolved["tenant_id"],
tenant_slug=resolved["tenant_slug"],
tenant_name=resolved["tenant_name"],
tenant_role=None,
actor_id=resolved["actor_id"],
actor_type=resolved["actor_type"],
session_token="",
capabilities=resolved["capabilities"],
auth_source="service_token",
service_token_id=resolved["token_id"],
)
def get_operational_context(
x_actor_token: Optional[str] = Header(default=None, alias=ACTOR_TOKEN_HEADER),
authorization: Optional[str] = Header(default=None),
x_auth_token: Optional[str] = Header(default=None, alias=AUTH_HEADER),
) -> TenantContext:
actor_token = _extract_actor_token(x_actor_token, authorization)
if actor_token:
return resolve_service_token_context(actor_token)
session_token = (x_auth_token or "").strip()
if not session_token:
raise HTTPException(
status_code=401,
detail="Authentifizierung erforderlich (X-Actor-Token oder X-Auth-Token)",
)
session = get_session(session_token)
if not session:
raise HTTPException(status_code=401, detail="Ungültige Session")
ctx = resolve_tenant_context(session)
if not ctx.tenant_id:
raise HTTPException(status_code=403, detail="Kein aktiver Tenant — Tenant wählen")
return ctx
def require_operational_capability(capability_key: str) -> Callable[..., TenantContext]:
"""Service tokens: always enforce. Sessions: probe/enforce per CAPABILITY_ENFORCE."""
def _dependency(
ctx: TenantContext = Depends(get_operational_context),
) -> TenantContext:
if ctx.auth_source == "service_token":
if capability_key not in ctx.capabilities:
raise HTTPException(
status_code=403,
detail=f"Capability fehlt auf Service Token: {capability_key}",
)
return ctx
return _enforce_capability(ctx, capability_key)
return _dependency
+77
View File
@@ -9,7 +9,9 @@ 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 schemas.schedule_payload import SchedulePayload
from services import actions as action_service
from services import scheduled_work as scheduled_work_service
from services import tasks as task_service
from tenant_context import TenantContext
@@ -29,12 +31,19 @@ class ActionUpdateRequest(BaseModel):
clear_project: bool = False
roadmap_item_id: Optional[str] = None
clear_roadmap_item: bool = False
sort_order: Optional[int] = None
action_kind: Optional[Literal["delivery", "planning", "review", "bug", "issue"]] = None
work_cycle_id: Optional[str] = None
clear_work_cycle: bool = False
parent_action_id: Optional[str] = None
clear_parent_action: bool = False
class TaskCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255)
description: str = ""
status: Literal["open", "in_progress", "done", "discarded"] = "open"
parent_task_id: Optional[str] = None
roadmap_item_id: Optional[str] = None
sort_order: int = 0
due_at: Optional[str] = None
@@ -87,6 +96,7 @@ def create_action_task(
title=body.title,
description=body.description,
status=body.status,
parent_task_id=body.parent_task_id,
roadmap_item_id=body.roadmap_item_id,
sort_order=body.sort_order,
due_at=due_at,
@@ -133,6 +143,12 @@ def update_action(
clear_project=body.clear_project,
roadmap_item_id=body.roadmap_item_id,
clear_roadmap_item=body.clear_roadmap_item,
work_cycle_id=body.work_cycle_id,
clear_work_cycle=body.clear_work_cycle,
sort_order=body.sort_order,
action_kind=body.action_kind,
parent_action_id=body.parent_action_id,
clear_parent_action=body.clear_parent_action,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -141,6 +157,47 @@ def update_action(
return item
@router.put("/{action_id}/schedule")
def upsert_action_schedule(
action_id: str,
body: SchedulePayload,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
try:
return scheduled_work_service.upsert_action_schedule(
tenant_id=ctx.tenant_id,
action_id=action_id,
user_id=ctx.user_id,
schedule_kind=body.schedule_kind,
interval_days=body.interval_days,
weekday_mask=body.weekday_mask,
pause_until=body.pause_until_date(),
)
except ValueError as exc:
detail = str(exc)
if detail == "Arbeitspaket nicht gefunden":
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@router.delete("/{action_id}/schedule", status_code=200)
def clear_action_schedule(
action_id: str,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
try:
return scheduled_work_service.clear_action_schedule(
tenant_id=ctx.tenant_id,
action_id=action_id,
user_id=ctx.user_id,
)
except ValueError as exc:
detail = str(exc)
if detail == "Arbeitspaket nicht gefunden":
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@router.put("/{action_id}/assignments")
def set_action_assignments(
action_id: str,
@@ -161,6 +218,26 @@ def set_action_assignments(
return item
@router.post("/{action_id}/unplan-to-backlog", status_code=200)
def unplan_action_to_backlog(
action_id: str,
carryover: bool = False,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
try:
return action_service.unplan_action_to_backlog(
tenant_id=ctx.tenant_id,
action_id=action_id,
user_id=ctx.user_id,
carryover=carryover,
)
except ValueError as exc:
detail = str(exc)
if detail == "Arbeitspaket nicht gefunden":
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@router.delete("/{action_id}", status_code=204)
def delete_action(
action_id: str,
+85 -1
View File
@@ -1,4 +1,4 @@
"""Actor directory API — AP0.7."""
"""Actor directory API — AP0.7 + AP1.7c Service Tokens."""
from __future__ import annotations
@@ -6,12 +6,25 @@ from typing import Literal, Optional
from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from services import actor_service_tokens
from services import actors as actor_service
from tenant_context import TenantContext
router = APIRouter(prefix="/api/actors", tags=["actors"])
class ServiceTokenCreateRequest(BaseModel):
label: str = Field(min_length=1, max_length=255)
capabilities: list[str] = Field(default_factory=list)
expires_in_days: Optional[int] = Field(default=365, ge=1, le=730)
class ActorCreateRequest(BaseModel):
name: str = Field(min_length=1, max_length=255)
actor_type: Literal["human", "agent", "working_group", "external_system"] = "agent"
@router.get("")
def list_actors(
actor_type: Optional[Literal["human", "agent", "working_group", "external_system"]] = None,
@@ -30,6 +43,26 @@ def list_actors(
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("", status_code=201)
def create_actor(
body: ActorCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.actor.manage")),
):
if body.actor_type == "human":
raise HTTPException(
status_code=400,
detail="Human-Actors werden über User-Provisioning angelegt",
)
try:
return actor_service.create_actor(
tenant_id=ctx.tenant_id,
actor_type=body.actor_type,
name=body.name.strip(),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.get("/{actor_id}")
def get_actor(
actor_id: str,
@@ -39,3 +72,54 @@ def get_actor(
if not item:
raise HTTPException(status_code=404, detail="Actor nicht gefunden")
return item
@router.get("/{actor_id}/service-tokens")
def list_actor_service_tokens(
actor_id: str,
include_revoked: bool = Query(default=False),
ctx: TenantContext = Depends(require_capability("kairo.actor.manage")),
):
actor = actor_service.get_actor(tenant_id=ctx.tenant_id, actor_id=actor_id)
if not actor:
raise HTTPException(status_code=404, detail="Actor nicht gefunden")
return actor_service_tokens.list_service_tokens_for_actor(
tenant_id=ctx.tenant_id,
actor_id=actor_id,
include_revoked=include_revoked,
)
@router.post("/{actor_id}/service-tokens", status_code=201)
def create_actor_service_token(
actor_id: str,
body: ServiceTokenCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.actor.manage")),
):
try:
return actor_service_tokens.create_service_token(
tenant_id=ctx.tenant_id,
actor_id=actor_id,
label=body.label,
created_by_user_id=ctx.user_id,
capabilities=body.capabilities,
expires_in_days=body.expires_in_days,
)
except ValueError as exc:
detail = str(exc)
if detail == "Actor nicht gefunden":
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@router.delete("/service-tokens/{token_id}", status_code=204)
def revoke_actor_service_token(
token_id: str,
ctx: TenantContext = Depends(require_capability("kairo.actor.manage")),
):
if not actor_service_tokens.revoke_service_token(
tenant_id=ctx.tenant_id,
token_id=token_id,
user_id=ctx.user_id,
):
raise HTTPException(status_code=404, detail="Token nicht gefunden")
+29 -5
View File
@@ -19,6 +19,10 @@ class BacklogCreateRequest(BaseModel):
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
priority: Literal["low", "normal", "high"] = "normal"
roadmap_item_id: Optional[str] = None
sort_order: Optional[int] = None
item_kind: Literal["story", "bug", "issue", "epic", "tech_debt"] = "story"
parent_action_id: Optional[str] = None
parent_backlog_id: Optional[str] = None
class BacklogUpdateRequest(BaseModel):
@@ -28,10 +32,18 @@ class BacklogUpdateRequest(BaseModel):
priority: Optional[Literal["low", "normal", "high"]] = None
roadmap_item_id: Optional[str] = None
clear_roadmap_item: bool = False
sort_order: Optional[int] = None
item_kind: Optional[Literal["story", "bug", "issue", "epic", "tech_debt"]] = None
parent_action_id: Optional[str] = None
clear_parent_action: bool = False
parent_backlog_id: Optional[str] = None
clear_parent_backlog: bool = False
class BacklogConvertRequest(BaseModel):
assigned_actor_ids: list[str] = Field(default_factory=list)
work_cycle_id: Optional[str] = None
assign_active_sprint: bool = True
@router.get("/{backlog_item_id}")
@@ -64,6 +76,12 @@ def update_backlog_item(
priority=body.priority,
roadmap_item_id=body.roadmap_item_id,
clear_roadmap_item=body.clear_roadmap_item,
sort_order=body.sort_order,
item_kind=body.item_kind,
parent_action_id=body.parent_action_id,
clear_parent_action=body.clear_parent_action,
parent_backlog_id=body.parent_backlog_id,
clear_parent_backlog=body.clear_parent_backlog,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -77,11 +95,15 @@ 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,
):
try:
deleted = backlog_service.delete_backlog_item(
tenant_id=ctx.tenant_id,
backlog_item_id=backlog_item_id,
user_id=ctx.user_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not deleted:
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
@@ -100,6 +122,8 @@ def convert_backlog_to_action(
backlog_item_id=backlog_item_id,
user_id=ctx.user_id,
assigned_actor_ids=assigned,
work_cycle_id=body.work_cycle_id,
assign_active_sprint=body.assign_active_sprint,
)
except ValueError as exc:
detail = str(exc)
+53
View File
@@ -0,0 +1,53 @@
"""Entity-Archetypen API — AP1.10a/10b."""
from __future__ import annotations
from typing import Optional
from capabilities import require_capability
from entity_archetypes import list_archetypes, validate_archetype_key
from services.archetype_starter_kit import get_starter_preview
from entity_fields.service import list_field_definitions
from fastapi import APIRouter, Depends, HTTPException, Query
from tenant_context import TenantContext
router = APIRouter(prefix="/api/entity-archetypes", tags=["entity-archetypes"])
@router.get("")
def get_entity_archetypes(
entity_type: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
_ = ctx
return list_archetypes(entity_type=entity_type)
@router.get("/field-definitions")
def get_archetype_field_definitions(
entity_type: str = Query(..., min_length=1),
archetype_key: str = Query(..., min_length=1),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
_ = ctx
archetypes = list_archetypes(entity_type=entity_type)
if not any(item["key"] == archetype_key for item in archetypes):
raise HTTPException(status_code=404, detail="Archetyp nicht gefunden")
return list_field_definitions(archetype_key=archetype_key)
@router.get("/{archetype_key}/starter-preview")
def get_archetype_starter_preview(
archetype_key: str,
method_profile_key: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
_ = ctx
try:
validate_archetype_key(entity_type="initiative", archetype_key=archetype_key)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return get_starter_preview(
archetype_key=archetype_key,
method_profile_key=method_profile_key,
)
+119
View File
@@ -0,0 +1,119 @@
"""Execution plan API — AP1.16b."""
from __future__ import annotations
from typing import Literal, Optional
from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from services import actions as action_service
from services import execution_plan as execution_plan_service
from steering.graph.execution_engine import load_initiative_execution_graph_state
from tenant_context import TenantContext
initiative_router = APIRouter(prefix="/api/initiatives", tags=["execution-plan"])
class ActionDependencyCreateRequest(BaseModel):
predecessor_action_id: str
successor_action_id: str
dependency_kind: Literal["requires", "blocks", "relates"] = "requires"
@initiative_router.get("/{initiative_id}/execution/graph-state")
def get_initiative_execution_graph_state(
initiative_id: str,
scope_roadmap_item_id: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
):
try:
state = load_initiative_execution_graph_state(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
scope_roadmap_item_id=scope_roadmap_item_id,
)
if scope_roadmap_item_id is None:
from services import actions as action_service
from services import roadmap as roadmap_service
all_actions = action_service.list_actions_for_initiative(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
from steering.graph.execution_engine import compute_planning_debt
state["planning_debt"] = compute_planning_debt(
actions=all_actions,
roadmap_items=roadmap_items,
)
return state
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@initiative_router.get("/{initiative_id}/execution/dependencies")
def list_initiative_action_dependencies(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
):
try:
return execution_plan_service.list_dependencies_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}/execution/dependencies", status_code=201)
def create_initiative_action_dependency(
initiative_id: str,
body: ActionDependencyCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
try:
predecessor = action_service.get_action(
tenant_id=ctx.tenant_id, action_id=body.predecessor_action_id
)
successor = action_service.get_action(
tenant_id=ctx.tenant_id, action_id=body.successor_action_id
)
if not predecessor or not successor:
raise ValueError("Action nicht gefunden")
if (
predecessor["initiative_id"] != initiative_id
or successor["initiative_id"] != initiative_id
):
raise ValueError("Actions gehören nicht zum angegebenen Vorhaben")
return execution_plan_service.add_dependency(
tenant_id=ctx.tenant_id,
predecessor_action_id=body.predecessor_action_id,
successor_action_id=body.successor_action_id,
dependency_kind=body.dependency_kind,
user_id=ctx.user_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@initiative_router.delete(
"/{initiative_id}/execution/dependencies/{dependency_id}",
status_code=204,
)
def delete_initiative_action_dependency(
initiative_id: str,
dependency_id: str,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
del initiative_id # scope validated via tenant + dependency row
try:
execution_plan_service.delete_dependency(
tenant_id=ctx.tenant_id,
dependency_id=dependency_id,
user_id=ctx.user_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+108
View File
@@ -7,6 +7,11 @@ from typing import Literal, Optional
from capabilities import require_capability
from data_layer import initiative_snapshot as dl_initiative_snapshot
from entity_fields.service import (
get_entity_field_values,
list_field_definitions,
patch_entity_field_values,
)
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from steering.context import get_steering_context_dto
@@ -16,6 +21,7 @@ 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 operating_context as operating_context_service
from services import milestones as milestone_service
from services import recurring as recurring_service
from services import reviews as review_service
@@ -27,19 +33,31 @@ router = APIRouter(prefix="/api/initiatives", tags=["initiatives"])
class InitiativeCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255)
goal: str = ""
vision: str = ""
target_state_summary: str = ""
archetype_key: str = "initiative.generic"
status: Literal["active", "paused", "completed", "archived"] = "active"
priority: Literal["low", "normal", "high"] = "normal"
owner_actor_id: Optional[str] = None
method_profile_key: Optional[str] = Field(default=None, min_length=1)
apply_starter_kit: bool = True
class InitiativeUpdateRequest(BaseModel):
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
goal: Optional[str] = None
vision: Optional[str] = None
target_state_summary: Optional[str] = None
archetype_key: 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 InitiativeFieldsPatchRequest(BaseModel):
fields: dict[str, object] = Field(default_factory=dict)
class ActionCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255)
description: str = ""
@@ -50,7 +68,11 @@ class ActionCreateRequest(BaseModel):
due_at: Optional[str] = None
project_id: Optional[str] = None
roadmap_item_id: Optional[str] = None
work_cycle_id: Optional[str] = None
assigned_actor_ids: list[str] = Field(default_factory=list)
sort_order: int = 0
action_kind: Literal["delivery", "planning", "review", "bug", "issue"] = "delivery"
parent_action_id: Optional[str] = None
class BlockerCreateRequest(BaseModel):
@@ -67,6 +89,9 @@ class BacklogCreateRequest(BaseModel):
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
priority: Literal["low", "normal", "high"] = "normal"
roadmap_item_id: Optional[str] = None
item_kind: Literal["story", "bug", "issue", "epic"] = "story"
parent_action_id: Optional[str] = None
parent_backlog_id: Optional[str] = None
class MilestoneCreateRequest(BaseModel):
@@ -107,6 +132,7 @@ class RecurringCreateRequest(BaseModel):
status: Literal["active", "paused", "ended"] = "active"
interval_days: Optional[int] = Field(default=None, gt=0)
next_due_at: Optional[str] = None
roadmap_item_id: Optional[str] = None
def _parse_optional_datetime(value: Optional[str], field_name: str) -> Optional[datetime]:
@@ -138,10 +164,15 @@ def create_initiative(
tenant_id=ctx.tenant_id,
title=body.title,
goal=body.goal,
vision=body.vision,
target_state_summary=body.target_state_summary,
archetype_key=body.archetype_key,
status=body.status,
priority=body.priority,
owner_actor_id=owner_actor_id,
user_id=ctx.user_id,
method_profile_key=body.method_profile_key,
apply_starter_kit=body.apply_starter_kit,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -185,6 +216,72 @@ def get_initiative_steering_context(
return get_steering_context_dto(ctx, initiative_id=initiative_id)
@router.get("/{initiative_id}/operating-context")
def get_initiative_operating_context(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
context = operating_context_service.get_operating_context(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
if not context:
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
return context
def _require_initiative(*, tenant_id: str, initiative_id: str) -> dict:
initiative = initiative_service.get_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if not initiative:
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
return initiative
@router.get("/{initiative_id}/field-definitions")
def get_initiative_field_definitions(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
initiative = _require_initiative(tenant_id=ctx.tenant_id, initiative_id=initiative_id)
return list_field_definitions(archetype_key=initiative["archetype_key"])
@router.get("/{initiative_id}/fields")
def get_initiative_fields(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
initiative = _require_initiative(tenant_id=ctx.tenant_id, initiative_id=initiative_id)
definitions = list_field_definitions(archetype_key=initiative["archetype_key"])
return get_entity_field_values(
tenant_id=ctx.tenant_id,
entity_type="initiative",
entity_id=initiative_id,
definitions=definitions,
)
@router.patch("/{initiative_id}/fields")
def patch_initiative_fields(
initiative_id: str,
body: InitiativeFieldsPatchRequest,
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
):
initiative = _require_initiative(tenant_id=ctx.tenant_id, initiative_id=initiative_id)
definitions = list_field_definitions(archetype_key=initiative["archetype_key"])
try:
return patch_entity_field_values(
tenant_id=ctx.tenant_id,
entity_type="initiative",
entity_id=initiative_id,
definitions=definitions,
values=body.fields,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.patch("/{initiative_id}")
def update_initiative(
initiative_id: str,
@@ -198,6 +295,9 @@ def update_initiative(
user_id=ctx.user_id,
title=body.title,
goal=body.goal,
vision=body.vision,
target_state_summary=body.target_state_summary,
archetype_key=body.archetype_key,
status=body.status,
priority=body.priority,
owner_actor_id=body.owner_actor_id,
@@ -254,7 +354,11 @@ def create_initiative_action(
due_at=due_at,
project_id=body.project_id,
roadmap_item_id=body.roadmap_item_id,
work_cycle_id=body.work_cycle_id,
assigned_actor_ids=body.assigned_actor_ids,
sort_order=body.sort_order,
action_kind=body.action_kind,
parent_action_id=body.parent_action_id,
user_id=ctx.user_id,
)
except ValueError as exc:
@@ -334,6 +438,9 @@ def create_initiative_backlog_item(
status=body.status,
priority=body.priority,
roadmap_item_id=body.roadmap_item_id,
item_kind=body.item_kind,
parent_action_id=body.parent_action_id,
parent_backlog_id=body.parent_backlog_id,
user_id=ctx.user_id,
)
except ValueError as exc:
@@ -542,6 +649,7 @@ def create_initiative_recurring(
status=body.status,
interval_days=body.interval_days,
next_due_at=next_due_at,
roadmap_item_id=body.roadmap_item_id,
user_id=ctx.user_id,
)
except ValueError as exc:
+429
View File
@@ -0,0 +1,429 @@
"""Operational Actor API — AP1.7 (Vibe-Coder / Agenten)."""
from __future__ import annotations
from typing import Any, Literal, Optional
from data_layer.attention import get_next_action_candidates_for_initiative
from data_layer.initiative_snapshot import get_initiative_steering_snapshot
from fastapi import APIRouter, Depends, HTTPException, Query
from operational_auth import require_operational_capability
from pydantic import BaseModel, Field
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 recurring as recurring_service
from services.audit import log_audit
from tenant_context import TenantContext
router = APIRouter(prefix="/api/operational", tags=["operational"])
def _ok(ctx: TenantContext, data: Any) -> dict[str, Any]:
return {
"ok": True,
"data": data,
"actor_id": ctx.actor_id,
}
class ActionStatusPatch(BaseModel):
status: Literal[
"open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"
]
note: Optional[str] = None
class ActionAssignmentsBody(BaseModel):
actor_ids: list[str] = Field(default_factory=list)
class BlockerCreateBody(BaseModel):
initiative_id: str
title: str = Field(min_length=1, max_length=255)
description: str = ""
action_id: Optional[str] = None
status: Literal["open", "in_progress"] = "open"
class BlockerPatchBody(BaseModel):
status: Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"]
class EvidenceCreateBody(BaseModel):
initiative_id: str
title: str = Field(min_length=1, max_length=255)
body: str = ""
action_id: Optional[str] = None
roadmap_item_id: Optional[str] = None
status: Literal["submitted", "accepted", "rejected"] = "submitted"
class DecisionProposalBody(BaseModel):
initiative_id: str
title: str = Field(min_length=1, max_length=255)
rationale: str = ""
proposed_status: Literal["proposed"] = "proposed"
class BacklogProposalBody(BaseModel):
initiative_id: str
title: str = Field(min_length=1, max_length=255)
description: str = ""
roadmap_item_id: Optional[str] = None
class BacklogConvertBody(BaseModel):
work_cycle_id: Optional[str] = None
assign_active_sprint: bool = True
assigned_actor_ids: list[str] = Field(default_factory=list)
class RecurringStatusPatch(BaseModel):
status: Literal["active", "paused", "ended"]
class ActionWorkCyclePatch(BaseModel):
work_cycle_id: Optional[str] = None
clear_work_cycle: bool = False
@router.get("/me")
def operational_me(ctx: TenantContext = Depends(require_operational_capability("kairo.action.read"))):
return _ok(
ctx,
{
"auth_source": ctx.auth_source,
"tenant_id": ctx.tenant_id,
"tenant_slug": ctx.tenant_slug,
"actor_id": ctx.actor_id,
"actor_type": ctx.actor_type,
"display_name": ctx.display_name,
"capabilities": sorted(ctx.capabilities),
},
)
@router.get("/initiatives/{initiative_id}/context")
def operational_context(
initiative_id: str,
ctx: TenantContext = Depends(require_operational_capability("kairo.initiative.read")),
):
snapshot = get_initiative_steering_snapshot(ctx, initiative_id=initiative_id)
if not snapshot:
raise HTTPException(status_code=404, detail="Vorhaben nicht gefunden")
subset = {
"initiative_id": snapshot.get("initiative_id"),
"title": snapshot.get("initiative_title"),
"status": snapshot.get("initiative_status"),
"method_key": snapshot.get("method_key"),
"method_label": snapshot.get("method_label"),
"archetype_key": snapshot.get("archetype_key"),
"archetype_label": snapshot.get("archetype_label"),
"steering_guidance": snapshot.get("steering_guidance"),
"lifecycle_state": snapshot.get("lifecycle_state"),
"lifecycle_label": snapshot.get("lifecycle_label"),
"signals": snapshot.get("signals"),
"attention_items": snapshot.get("attention_items"),
"next_actions": snapshot.get("next_actions"),
"active_work_cycle": snapshot.get("active_work_cycle"),
}
return _ok(ctx, subset)
@router.get("/next-action")
def operational_next_action(
initiative_id: str = Query(...),
limit: int = Query(default=5, ge=1, le=20),
ctx: TenantContext = Depends(require_operational_capability("kairo.initiative.read")),
):
items = get_next_action_candidates_for_initiative(
ctx, initiative_id=initiative_id, limit=limit
)
return _ok(ctx, items)
@router.get("/actions/{action_id}")
def operational_get_action(
action_id: str,
ctx: TenantContext = Depends(require_operational_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="Arbeitspaket nicht gefunden")
return _ok(ctx, item)
@router.patch("/actions/{action_id}/status")
def operational_patch_action_status(
action_id: str,
body: ActionStatusPatch,
ctx: TenantContext = Depends(require_operational_capability("kairo.action.manage")),
):
description = None
if body.note:
description = body.note.strip()
try:
item = action_service.update_action(
tenant_id=ctx.tenant_id,
action_id=action_id,
user_id=ctx.user_id or None,
status=body.status,
description=description,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not item:
raise HTTPException(status_code=404, detail="Arbeitspaket nicht gefunden")
log_audit(
"operational.action.status",
user_id=ctx.user_id or None,
tenant_id=ctx.tenant_id,
details={
"action_id": action_id,
"status": body.status,
"actor_id": ctx.actor_id,
"auth_source": ctx.auth_source,
},
)
return _ok(ctx, item)
@router.post("/actions/{action_id}/assignments")
def operational_set_assignments(
action_id: str,
body: ActionAssignmentsBody,
ctx: TenantContext = Depends(require_operational_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 or None,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not item:
raise HTTPException(status_code=404, detail="Arbeitspaket nicht gefunden")
return _ok(ctx, item)
@router.post("/blockers", status_code=201)
def operational_create_blocker(
body: BlockerCreateBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.blocker.manage")),
):
try:
item = blocker_service.create_blocker(
tenant_id=ctx.tenant_id,
initiative_id=body.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 or None,
)
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
return _ok(ctx, item)
@router.patch("/blockers/{blocker_id}")
def operational_patch_blocker(
blocker_id: str,
body: BlockerPatchBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.blocker.manage")),
):
try:
item = blocker_service.update_blocker(
tenant_id=ctx.tenant_id,
blocker_id=blocker_id,
user_id=ctx.user_id or None,
status=body.status,
)
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 _ok(ctx, item)
@router.post("/evidence", status_code=201)
def operational_create_evidence(
body: EvidenceCreateBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.evidence.manage")),
):
try:
item = evidence_service.create_evidence(
tenant_id=ctx.tenant_id,
initiative_id=body.initiative_id,
title=body.title,
description=body.body,
status=body.status,
action_id=body.action_id,
roadmap_item_id=body.roadmap_item_id,
submitted_by_actor_id=ctx.actor_id,
user_id=ctx.user_id or None,
)
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
return _ok(ctx, item)
@router.post("/decisions/proposals", status_code=201)
def operational_decision_proposal(
body: DecisionProposalBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.decision.manage")),
):
try:
item = decision_service.create_decision(
tenant_id=ctx.tenant_id,
initiative_id=body.initiative_id,
title=body.title,
description=body.rationale,
status=body.proposed_status,
decided_by_actor_id=ctx.actor_id,
user_id=ctx.user_id or None,
)
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
return _ok(ctx, item)
@router.post("/backlog/proposals", status_code=201)
def operational_backlog_proposal(
body: BacklogProposalBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.backlog.manage")),
):
try:
item = backlog_service.create_backlog_item(
tenant_id=ctx.tenant_id,
initiative_id=body.initiative_id,
title=body.title,
description=body.description,
status="new",
roadmap_item_id=body.roadmap_item_id,
user_id=ctx.user_id or None,
)
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
return _ok(ctx, item)
@router.post("/backlog/{backlog_item_id}/convert-to-action", status_code=201)
def operational_convert_backlog(
backlog_item_id: str,
body: BacklogConvertBody,
ctx: TenantContext = Depends(require_operational_capability("kairo.backlog.manage")),
):
assigned = body.assigned_actor_ids
if not assigned and ctx.actor_id:
assigned = [ctx.actor_id]
try:
result = backlog_service.convert_backlog_to_action(
tenant_id=ctx.tenant_id,
backlog_item_id=backlog_item_id,
user_id=ctx.user_id or None,
assigned_actor_ids=assigned,
work_cycle_id=body.work_cycle_id,
assign_active_sprint=body.assign_active_sprint,
)
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
log_audit(
"operational.backlog.convert",
user_id=ctx.user_id or None,
tenant_id=ctx.tenant_id,
details={
"backlog_item_id": backlog_item_id,
"action_id": result.get("action", {}).get("id"),
"work_cycle_id": body.work_cycle_id,
"actor_id": ctx.actor_id,
},
)
return _ok(ctx, result)
@router.patch("/recurring/{recurring_id}")
def operational_patch_recurring(
recurring_id: str,
body: RecurringStatusPatch,
ctx: TenantContext = Depends(require_operational_capability("kairo.recurring.manage")),
):
try:
item = recurring_service.update_recurring_element(
tenant_id=ctx.tenant_id,
recurring_id=recurring_id,
user_id=ctx.user_id or None,
status=body.status,
)
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")
log_audit(
"operational.recurring.status",
user_id=ctx.user_id or None,
tenant_id=ctx.tenant_id,
details={
"recurring_id": recurring_id,
"status": body.status,
"actor_id": ctx.actor_id,
},
)
return _ok(ctx, item)
@router.patch("/actions/{action_id}/work-cycle")
def operational_patch_action_work_cycle(
action_id: str,
body: ActionWorkCyclePatch,
ctx: TenantContext = Depends(require_operational_capability("kairo.action.manage")),
):
try:
item = action_service.update_action(
tenant_id=ctx.tenant_id,
action_id=action_id,
user_id=ctx.user_id or None,
work_cycle_id=body.work_cycle_id,
clear_work_cycle=body.clear_work_cycle,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not item:
raise HTTPException(status_code=404, detail="Arbeitspaket nicht gefunden")
log_audit(
"operational.action.work_cycle",
user_id=ctx.user_id or None,
tenant_id=ctx.tenant_id,
details={
"action_id": action_id,
"work_cycle_id": body.work_cycle_id,
"clear_work_cycle": body.clear_work_cycle,
"actor_id": ctx.actor_id,
},
)
return _ok(ctx, item)
+39 -1
View File
@@ -8,6 +8,7 @@ from typing import Literal, Optional
from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from schemas.schedule_payload import SchedulePayload
from services import recurring as recurring_service
from tenant_context import TenantContext
@@ -22,6 +23,13 @@ class RecurringUpdateRequest(BaseModel):
clear_interval_days: bool = False
next_due_at: Optional[str] = None
clear_next_due_at: bool = False
roadmap_item_id: Optional[str] = None
clear_roadmap_item_id: bool = False
schedule: Optional[SchedulePayload] = None
class RecurringCompleteRequest(BaseModel):
measurement_note: Optional[str] = Field(default=None, max_length=2000)
def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
@@ -53,6 +61,7 @@ def update_recurring_element(
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
sched = body.schedule
try:
item = recurring_service.update_recurring_element(
tenant_id=ctx.tenant_id,
@@ -61,10 +70,16 @@ def update_recurring_element(
title=body.title,
description=body.description,
status=body.status,
interval_days=body.interval_days,
interval_days=body.interval_days if sched is None else sched.interval_days,
clear_interval_days=body.clear_interval_days,
next_due_at=next_due_at,
clear_next_due_at=body.clear_next_due_at,
roadmap_item_id=body.roadmap_item_id,
clear_roadmap_item_id=body.clear_roadmap_item_id,
schedule_kind=sched.schedule_kind if sched else None,
weekday_mask=sched.weekday_mask if sched else None,
pause_until=sched.pause_until_date() if sched else None,
clear_pause_until=sched is not None and sched.pause_until is None,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -73,6 +88,29 @@ def update_recurring_element(
return item
@router.post("/{recurring_id}/complete")
def complete_recurring_practice(
recurring_id: str,
body: RecurringCompleteRequest,
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
):
from services.cadence_instance import complete_open_instance
try:
result = complete_open_instance(
tenant_id=ctx.tenant_id,
recurring_element_id=recurring_id,
user_id=ctx.user_id or None,
measurement_note=body.measurement_note or "",
)
except ValueError as exc:
detail = str(exc)
if detail == "Recurring-Element nicht gefunden":
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
return result
@router.delete("/{recurring_id}", status_code=204)
def delete_recurring_element(
recurring_id: str,
+218 -6
View File
@@ -8,8 +8,10 @@ from typing import Any, Literal, Optional
from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from schemas.schedule_payload import SchedulePayload
from services import roadmap as roadmap_service
from services import roadmap_criteria as criteria_service
from services import roadmap_plan_snapshot as snapshot_service
from tenant_context import TenantContext
router = APIRouter(tags=["roadmap"])
@@ -17,7 +19,7 @@ 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"
item_type: Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"] = "milestone"
goal_description: str = ""
definition_of_done: list[Any] = Field(default_factory=list)
status: Literal[
@@ -26,11 +28,13 @@ class RoadmapItemCreateRequest(BaseModel):
sequencing_mode: Literal["sequential", "parallel", "optional"] = "sequential"
target_date: Optional[date] = None
sort_order: int = 0
strand_project_id: Optional[str] = None
initial_criterion_title: Optional[str] = Field(default=None, max_length=500)
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
item_type: Optional[Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]] = None
goal_description: Optional[str] = None
definition_of_done: Optional[list[Any]] = None
status: Optional[
@@ -40,11 +44,16 @@ class RoadmapItemUpdateRequest(BaseModel):
target_date: Optional[date] = None
clear_target_date: bool = False
sort_order: Optional[int] = None
strand_project_id: Optional[str] = None
clear_strand_project: bool = False
class DependencyCreateRequest(BaseModel):
to_item_id: str
dependency_type: Literal["requires", "blocks", "related"] = "requires"
dependency_type: Literal[
"requires", "blocks", "related", "parallel_group", "optional_branch"
] = "requires"
group_key: Optional[str] = Field(default=None, max_length=128)
class CriterionCreateRequest(BaseModel):
@@ -79,8 +88,21 @@ class ReopenRequest(BaseModel):
reason: str = ""
class GatePracticeCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255)
description: str = ""
status: Literal["active", "paused", "ended"] = "active"
interval_days: int = Field(default=1, gt=0)
schedule: Optional[SchedulePayload] = None
class PlanSnapshotCreateRequest(BaseModel):
reason: str = Field(default="", max_length=2000)
initiative_router = APIRouter(prefix="/api/initiatives", tags=["roadmap"])
items_router = APIRouter(prefix="/api/roadmap-items", tags=["roadmap"])
deps_router = APIRouter(prefix="/api/roadmap-dependencies", tags=["roadmap"])
@initiative_router.get("/{initiative_id}/roadmap")
@@ -115,6 +137,105 @@ def list_initiative_roadmap_items(
raise HTTPException(status_code=400, detail=str(exc)) from exc
@initiative_router.get("/{initiative_id}/roadmap/dependencies")
def list_initiative_roadmap_dependencies(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
return roadmap_service.list_dependencies_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.get("/{initiative_id}/roadmap/criteria-progress")
def list_initiative_roadmap_criteria_progress(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
return criteria_service.criteria_progress_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.get("/{initiative_id}/roadmap/graph-state")
def get_initiative_roadmap_graph_state(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
from steering.graph.roadmap_engine import load_initiative_graph_state
return load_initiative_graph_state(
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.get("/{initiative_id}/roadmap/progression-state")
def get_initiative_progression_state(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
from services.progression_graph import compute_progression_state
return compute_progression_state(
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.get("/{initiative_id}/roadmap/plan-ist-view")
def get_initiative_plan_ist_view(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
from steering.graph.plan_ist import load_plan_ist_view
return load_plan_ist_view(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.get("/{initiative_id}/roadmap/plan-snapshots")
def list_initiative_plan_snapshots(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
return snapshot_service.list_plan_snapshots(
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/plan-snapshots", status_code=201)
def create_initiative_plan_snapshot(
initiative_id: str,
body: PlanSnapshotCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
return snapshot_service.create_plan_snapshot(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
reason=body.reason,
user_id=ctx.user_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,
@@ -134,6 +255,8 @@ def create_initiative_roadmap_item(
sequencing_mode=body.sequencing_mode,
target_date=body.target_date,
sort_order=body.sort_order,
strand_project_id=body.strand_project_id,
initial_criterion_title=body.initial_criterion_title,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -170,6 +293,8 @@ def update_roadmap_item(
target_date=body.target_date,
clear_target_date=body.clear_target_date,
sort_order=body.sort_order,
strand_project_id=body.strand_project_id,
clear_strand_project=body.clear_strand_project,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -183,12 +308,83 @@ 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
):
try:
deleted = roadmap_service.delete_roadmap_item(
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
if not deleted:
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
def _work_gate_or_400(*, tenant_id: str, item_id: str) -> dict[str, Any]:
item = roadmap_service.get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
if not item:
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
if item.get("item_type") == "join_gate":
raise HTTPException(
status_code=400,
detail="Join-Gates haben kein Activity Set (Übungen)",
)
return item
@items_router.get("/{item_id}/practices")
def list_gate_practices(
item_id: str,
ctx: TenantContext = Depends(require_capability("kairo.recurring.read")),
):
from services import recurring as recurring_service
item = _work_gate_or_400(tenant_id=ctx.tenant_id, item_id=item_id)
try:
return recurring_service.list_recurring_for_gate(
tenant_id=ctx.tenant_id,
initiative_id=str(item["initiative_id"]),
gate_id=item_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@items_router.post("/{item_id}/practices", status_code=201)
def create_gate_practice(
item_id: str,
body: GatePracticeCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
):
item = _work_gate_or_400(tenant_id=ctx.tenant_id, item_id=item_id)
sched = body.schedule
try:
from services.scheduled_work import create_scheduled_action_at_gate
if sched:
return create_scheduled_action_at_gate(
tenant_id=ctx.tenant_id,
initiative_id=str(item["initiative_id"]),
gate_id=item_id,
title=body.title,
description=body.description,
user_id=ctx.user_id,
schedule_kind=sched.schedule_kind,
interval_days=sched.interval_days,
weekday_mask=sched.weekday_mask,
pause_until=sched.pause_until_date(),
)
return create_scheduled_action_at_gate(
tenant_id=ctx.tenant_id,
initiative_id=str(item["initiative_id"]),
gate_id=item_id,
title=body.title,
description=body.description,
user_id=ctx.user_id,
schedule_kind="weekdays",
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@items_router.post("/{item_id}/verify-reached")
def verify_roadmap_item_reached(
item_id: str,
@@ -257,6 +453,21 @@ def create_roadmap_item_criterion(
raise HTTPException(status_code=400, detail=str(exc)) from exc
@deps_router.delete("/{dependency_id}", status_code=204)
def delete_roadmap_dependency(
dependency_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
roadmap_service.delete_dependency(
tenant_id=ctx.tenant_id,
dependency_id=dependency_id,
user_id=ctx.user_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
criteria_router = APIRouter(prefix="/api/roadmap-criteria", tags=["roadmap"])
@@ -375,6 +586,7 @@ def add_roadmap_item_dependency(
from_item_id=item_id,
to_item_id=body.to_item_id,
dependency_type=body.dependency_type,
group_key=body.group_key,
user_id=ctx.user_id,
)
except ValueError as exc:
+84 -23
View File
@@ -1,40 +1,79 @@
"""Steering API — methods and context (AP1.1)."""
"""Steering API — methods, profiles and context (AP1.1 / AP2.0 / AP2.4)."""
from __future__ import annotations
from typing import Literal, Optional
from typing import Optional
from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from entity_archetypes.registry import resolve_default_method_key, resolve_ui_profile
from method_profiles.registry import list_method_profiles
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 steering.methods.registry import (
list_compatible_methods,
list_methods,
method_to_dict,
)
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
method_key: Optional[str] = Field(default=None, min_length=1)
method_profile_key: Optional[str] = Field(default=None, min_length=1)
clear_method_profile: bool = False
def _om_capabilities_for_archetype(archetype_key: str | None) -> frozenset[str] | None:
if not archetype_key:
return None
profile = resolve_ui_profile(archetype_key)
caps = profile.get("omCapabilities") or profile.get("dataSlices") or []
return frozenset(caps)
@router.get("/methods")
def list_steering_methods(
archetype_key: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
_ = ctx
om_caps = _om_capabilities_for_archetype(archetype_key)
if archetype_key:
methods = list_compatible_methods(archetype_key, om_capabilities=om_caps)
default_key = resolve_default_method_key(archetype_key)
else:
methods = list_methods()
default_key = None
return [
{
"key": m.key,
"version": m.version,
"label": m.label,
"description": m.description,
"next_action_strategy_key": m.next_action_strategy_key,
**method_to_dict(m),
"is_default": m.key == default_key if default_key else False,
}
for m in list_methods()
for m in methods
]
@router.get("/method-profiles")
def list_steering_method_profiles(
initiative_archetype_key: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
):
_ = ctx
return [
{
"key": p["key"],
"label": p["label"],
"description": p["description"],
"initiative_archetype_key": p["initiative_archetype_key"],
"method_key": p["method_key"],
}
for p in list_method_profiles(initiative_archetype_key=initiative_archetype_key)
]
@@ -44,19 +83,41 @@ def patch_initiative_steering_context(
body: SteeringContextUpdateRequest,
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
):
if not initiative_service.get_initiative(
initiative = initiative_service.get_initiative(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
):
)
if not initiative:
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,
if not body.method_key and not body.method_profile_key and not body.clear_method_profile:
raise HTTPException(
status_code=400,
detail="method_key, method_profile_key oder clear_method_profile erforderlich",
)
try:
if body.clear_method_profile:
sc_service.update_method_profile_key(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
method_profile_key=None,
user_id=ctx.user_id,
)
elif body.method_profile_key:
sc_service.update_method_profile_key(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
method_profile_key=body.method_profile_key,
user_id=ctx.user_id,
)
elif body.method_key:
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)
+11 -3
View File
@@ -18,6 +18,8 @@ class TaskUpdateRequest(BaseModel):
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
description: Optional[str] = None
status: Optional[Literal["open", "in_progress", "done", "discarded"]] = None
parent_task_id: Optional[str] = None
clear_parent_task: bool = False
roadmap_item_id: Optional[str] = None
clear_roadmap_item: bool = False
sort_order: Optional[int] = None
@@ -45,6 +47,8 @@ def update_task(
title=body.title,
description=body.description,
status=body.status,
parent_task_id=body.parent_task_id,
clear_parent_task=body.clear_parent_task,
roadmap_item_id=body.roadmap_item_id,
clear_roadmap_item=body.clear_roadmap_item,
sort_order=body.sort_order,
@@ -63,7 +67,11 @@ def delete_task(
task_id: str,
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
):
if not task_service.delete_task(
tenant_id=ctx.tenant_id, task_id=task_id, user_id=ctx.user_id
):
try:
deleted = task_service.delete_task(
tenant_id=ctx.tenant_id, task_id=task_id, user_id=ctx.user_id
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not deleted:
raise HTTPException(status_code=404, detail="Task nicht gefunden")
+166
View File
@@ -0,0 +1,166 @@
"""Work cycle (Sprint/Zeitbox) API — AP2.0f."""
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 work_cycle as work_cycle_service
from tenant_context import TenantContext
initiative_router = APIRouter(
prefix="/api/initiatives/{initiative_id}/work-cycles",
tags=["work-cycles"],
)
class WorkCycleCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255)
goal_description: str = ""
status: Literal["planned", "active"] = "planned"
target_date: Optional[date] = None
sort_order: int = 0
@initiative_router.get("")
def list_work_cycles(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
return work_cycle_service.list_work_cycles_for_initiative(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
@initiative_router.get("/active")
def get_active_work_cycle(
initiative_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
item = work_cycle_service.get_active_work_cycle(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
if not item:
return None
item["open_action_count"] = work_cycle_service.count_actions_in_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=item["id"],
)
return item
@initiative_router.post("", status_code=201)
def create_work_cycle(
initiative_id: str,
body: WorkCycleCreateRequest,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
item = work_cycle_service.create_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
title=body.title,
goal_description=body.goal_description,
status=body.status,
target_date=body.target_date,
sort_order=body.sort_order,
user_id=ctx.user_id,
)
if body.status == "active":
item = work_cycle_service.activate_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=item["id"],
user_id=ctx.user_id,
)
return item
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
@initiative_router.post("/{work_cycle_id}/complete")
def complete_work_cycle(
initiative_id: str,
work_cycle_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
return work_cycle_service.complete_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
user_id=ctx.user_id,
)
except ValueError as exc:
detail = str(exc)
if detail in ("Initiative nicht gefunden", "Sprint nicht gefunden oder bereits abgeschlossen"):
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@initiative_router.get("/{work_cycle_id}/open-actions")
def list_work_cycle_open_actions(
initiative_id: str,
work_cycle_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
):
try:
work_cycle_service.validate_work_cycle_in_initiative(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
return work_cycle_service.list_open_actions_in_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@initiative_router.post("/{work_cycle_id}/reactivate")
def reactivate_work_cycle(
initiative_id: str,
work_cycle_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
return work_cycle_service.reactivate_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
user_id=ctx.user_id,
)
except ValueError as exc:
detail = str(exc)
if detail in ("Initiative nicht gefunden", "Sprint nicht gefunden"):
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
@initiative_router.post("/{work_cycle_id}/activate")
def activate_work_cycle(
initiative_id: str,
work_cycle_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
):
try:
return work_cycle_service.activate_work_cycle(
tenant_id=ctx.tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
user_id=ctx.user_id,
)
except ValueError as exc:
detail = str(exc)
if detail in ("Initiative nicht gefunden", "Zeitbox nicht gefunden"):
raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc
+35
View File
@@ -9,13 +9,20 @@ 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 portfolio_steering as dl_portfolio_steering
from data_layer import workspace as dl_workspace
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from services import initiatives as initiative_service
from tenant_context import TenantContext
router = APIRouter(prefix="/api/workspace", tags=["workspace"])
class PortfolioReorderRequest(BaseModel):
initiative_ids: list[str] = Field(min_length=1)
def _require_actor_ctx(ctx: TenantContext) -> TenantContext:
if not ctx.actor_id:
raise HTTPException(status_code=400, detail="Kein Actor im TenantContext")
@@ -88,3 +95,31 @@ def workspace_next_actions(
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
):
return dl_attention.get_next_action_candidates(ctx, limit=limit or 10)
@router.get("/steering")
def workspace_steering(
limit: Optional[int] = Query(default=30, ge=1, le=100),
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
):
"""Portfolio-Steuerung — Kernel-Aggregation über alle aktiven Initiativen (K-Ext-5)."""
return dl_portfolio_steering.get_portfolio_steering(
ctx,
total_attention=limit or 30,
total_next_work=min(limit or 30, 15),
)
@router.post("/portfolio/reorder")
def workspace_portfolio_reorder(
body: PortfolioReorderRequest,
ctx: TenantContext = Depends(require_capability("kairo.initiative.manage")),
):
try:
return initiative_service.reorder_portfolio(
tenant_id=ctx.tenant_id,
initiative_ids=body.initiative_ids,
user_id=ctx.user_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+25
View File
@@ -0,0 +1,25 @@
"""Shared Pydantic models for Schedule API payloads."""
from __future__ import annotations
from typing import Literal, Optional
from pydantic import BaseModel, Field, model_validator
class SchedulePayload(BaseModel):
schedule_kind: Literal["interval", "weekdays"] = "interval"
interval_days: int = Field(default=1, gt=0)
weekday_mask: int = Field(default=0, ge=0, le=127)
pause_until: Optional[str] = Field(default=None, description="ISO date YYYY-MM-DD")
@model_validator(mode="after")
def validate_kind(self) -> "SchedulePayload":
if self.schedule_kind == "weekdays" and self.weekday_mask <= 0:
raise ValueError("Mindestens ein Wochentag auswählen")
return self
def pause_until_date(self):
from services.schedule import _parse_pause_until
return _parse_pause_until(self.pause_until)
@@ -0,0 +1,456 @@
"""Dogfooding R1 — Referenz-Vorhaben „Jinkendo Kairo“ (idempotent, Nicht-Prod).
DEPRECATED (2026-07-12): Nur Dev-Visualisierung. Produkt-Anlage über AP2.2a Starter-Kits.
Siehe Kairo_MVP_Execution_Plan_v0.2.md — nicht weiter ausbauen.
"""
from __future__ import annotations
import os
from typing import Any, Optional
GITEA_BASE = "http://192.168.2.144:3000/Lars/Kairo-Jinkendo"
INITIATIVE_TITLE = "Jinkendo Kairo"
TENANT_SLUG = "stommer"
def _gitea_commit(sha: str, label: str = "") -> str:
line = f"Commit: [{sha[:7]}]({GITEA_BASE}/commit/{sha})"
if label:
return f"{label}\n{line}\nBranch: develop"
return f"{line}\nBranch: develop"
def _resolve_context() -> tuple[str, str]:
from db import get_connection
from psycopg2.extras import RealDictCursor
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("SELECT id FROM tenants WHERE slug = %s", (TENANT_SLUG,))
row = cur.fetchone()
if not row:
raise RuntimeError(
f"Tenant '{TENANT_SLUG}' nicht gefunden — zuerst Portal-Admin/seed_003"
)
tenant_id = str(row["id"])
cur.execute(
"""
SELECT a.id
FROM actors a
WHERE a.tenant_id = %s AND a.actor_type = 'human' AND a.is_active = TRUE
ORDER BY a.created_at
LIMIT 1
""",
(tenant_id,),
)
actor_row = cur.fetchone()
if not actor_row:
raise RuntimeError("Kein Human-Actor im Tenant — seed_003 zuerst")
return tenant_id, str(actor_row["id"])
finally:
conn.close()
def _find_initiative(tenant_id: str) -> Optional[dict[str, Any]]:
from services.initiatives import list_initiatives
for item in list_initiatives(tenant_id=tenant_id):
if item["title"] == INITIATIVE_TITLE:
return item
return None
def _find_by_title(items: list[dict[str, Any]], title: str) -> Optional[dict[str, Any]]:
for item in items:
if item["title"] == title:
return item
return None
def _close_gate_and_verify(*, tenant_id: str, item_id: str) -> None:
from services.roadmap import get_roadmap_item, verify_reached
from services.roadmap_criteria import list_criteria_for_item, waive_criterion
item = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
if item and item.get("status") == "reached":
return
for criterion in list_criteria_for_item(tenant_id=tenant_id, item_id=item_id):
if criterion["status"] not in {"satisfied", "waived", "deferred"}:
waive_criterion(
tenant_id=tenant_id,
criterion_id=criterion["id"],
decision_title="Dogfooding R1 — historisches Gate",
decision_description="Rückwirkende Abnahme per Seed.",
)
verify_reached(tenant_id=tenant_id, item_id=item_id)
def _ensure_gate_chain(
*,
tenant_id: str,
initiative_id: str,
gates: list[tuple[str, str, str]],
) -> dict[str, str]:
"""gates: (title, status, goal) -> id map."""
from services.roadmap import add_dependency, create_roadmap_item, list_roadmap_items_for_initiative
existing = list_roadmap_items_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
ids: dict[str, str] = {}
ordered: list[str] = []
for index, (title, status, goal) in enumerate(gates):
found = _find_by_title(existing, title)
if found:
gate_id = found["id"]
else:
created = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="milestone",
goal_description=goal,
status="planned" if status == "reached" else status,
sort_order=index * 10,
initial_criterion_title=f"{title} — Abnahme",
)
gate_id = created["id"]
existing.append(created)
ids[title] = gate_id
ordered.append(gate_id)
if status == "reached":
_close_gate_and_verify(tenant_id=tenant_id, item_id=gate_id)
for i in range(1, len(ordered)):
try:
add_dependency(
tenant_id=tenant_id,
from_item_id=ordered[i],
to_item_id=ordered[i - 1],
dependency_type="requires",
)
except ValueError as exc:
if "existiert bereits" not in str(exc):
raise
return ids
def _ensure_projects(
*, tenant_id: str, initiative_id: str, titles: list[str]
) -> dict[str, str]:
from services.projects import create_project, list_projects_for_initiative
existing = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
ids: dict[str, str] = {}
for index, title in enumerate(titles):
found = _find_by_title(existing, title)
if found:
ids[title] = found["id"]
continue
created = create_project(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=f"Ist-Struktur — {title}",
sort_order=index,
)
ids[title] = created["id"]
existing.append(created)
return ids
def _ensure_action(
*,
tenant_id: str,
initiative_id: str,
title: str,
status: str,
roadmap_item_id: Optional[str] = None,
project_id: Optional[str] = None,
description: str = "",
) -> dict[str, Any]:
from services.actions import create_action, list_actions_for_initiative
existing = list_actions_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
found = _find_by_title(existing, title)
if found:
if found.get("status") != status:
from services.actions import update_action
updated = update_action(
tenant_id=tenant_id,
action_id=found["id"],
status=status,
)
if updated:
found = updated
return found
return create_action(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=description,
status=status,
roadmap_item_id=roadmap_item_id,
project_id=project_id,
)
def _ensure_evidence(
*,
tenant_id: str,
initiative_id: str,
title: str,
description: str,
roadmap_item_id: Optional[str] = None,
action_id: Optional[str] = None,
actor_id: Optional[str] = None,
) -> None:
from services.evidence import create_evidence, list_evidence_for_initiative
for item in list_evidence_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
if item["title"] == title:
return
create_evidence(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=description,
status="accepted",
roadmap_item_id=roadmap_item_id,
action_id=action_id,
submitted_by_actor_id=actor_id,
)
def _ensure_decision(
*,
tenant_id: str,
initiative_id: str,
title: str,
outcome: str,
) -> None:
from db import get_connection
from psycopg2.extras import RealDictCursor
from services.decisions import create_decision
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT 1 FROM decisions
WHERE tenant_id = %s AND initiative_id = %s AND title = %s
""",
(tenant_id, initiative_id, title),
)
if cur.fetchone():
return
finally:
conn.close()
create_decision(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=outcome,
status="decided",
outcome=outcome,
)
def _ensure_portfolio_first(*, tenant_id: str, initiative_id: str) -> None:
from services.initiatives import list_initiatives, reorder_portfolio
all_items = list_initiatives(tenant_id=tenant_id)
ids = [initiative_id] + [i["id"] for i in all_items if i["id"] != initiative_id]
reorder_portfolio(tenant_id=tenant_id, initiative_ids=ids)
def run() -> None:
if os.getenv("ENVIRONMENT", "development").strip().lower() == "production":
print("[dogfooding] Übersprungen in Production")
return
tenant_id, owner_actor_id = _resolve_context()
initiative = _find_initiative(tenant_id)
if not initiative:
from services.initiatives import create_initiative
initiative = create_initiative(
tenant_id=tenant_id,
title=INITIATIVE_TITLE,
owner_actor_id=owner_actor_id,
archetype_key="initiative.product",
method_profile_key="product.kairo_dev",
goal=(
"Operativer Program Director — MVP v0.3 Stufe A (B2b). "
f"Repository: {GITEA_BASE} (Branch develop)"
),
vision="Kairo steuert Kairo — Dogfooding Referenz-Vorhaben.",
target_state_summary="Leitfrage in ≤2 Min; Gates + Ist gespiegelt aus Git/Docs.",
priority="high",
)
print(f"[dogfooding] Initiative angelegt: {initiative['id']}")
else:
print(f"[dogfooding] Initiative vorhanden: {initiative['id']}")
initiative_id = initiative["id"]
gate_defs = [
("G1 — Foundation AP0", "reached", "Tenant, Actor, Auth, OM, Migrationen"),
("G2 — IA & Steering Skeleton", "reached", "AP1.2c, AP1.0, Snapshot, Signals"),
("G3 — Gates & Checkliste", "reached", "AP1.4/4b/4c, Verify, Kriterien"),
("G4 — Ist-Hierarchie & Plan/Ist", "reached", "AP1.5/5c, AP1.6, AP1.14, Journey"),
("G5 — PM Work Modes & Plan-Outline", "active", "AP1.9a/9c ✓; AP1.12 ◐; AP1.16 ◐"),
("G6 — Archetyp-Steuerung MVP", "active", "AP2.0 ◐; AP2.0d ✓; Execution-Graph ✓"),
("G7 — MVP-Abnahfe B2b", "planned", "Validation, Leitfrage, Cockpit-Signale"),
("G8 — Agent & Integration", "planned", "AP1.7, Gitea-Webhook, MCP"),
]
gate_ids = _ensure_gate_chain(
tenant_id=tenant_id,
initiative_id=initiative_id,
gates=gate_defs,
)
project_ids = _ensure_projects(
tenant_id=tenant_id,
initiative_id=initiative_id,
titles=["Backend", "Frontend", "Docs & ADPs", "Deploy / CI"],
)
g5 = gate_ids["G5 — PM Work Modes & Plan-Outline"]
g6 = gate_ids["G6 — Archetyp-Steuerung MVP"]
g4 = gate_ids["G4 — Ist-Hierarchie & Plan/Ist"]
done_actions = [
(
"AP1.6b — Journey Gate-Fortschritt",
"done",
g4,
project_ids["Frontend"],
"b85a6ec",
),
(
"AP1.8a — Portfolio-Rang Cockpit",
"done",
g5,
project_ids["Frontend"],
"a19c6ab",
),
(
"AP1.14 — Plan/Ist-Snapshots",
"done",
g4,
project_ids["Backend"],
"064779e",
),
(
"AP2.0 — Archetyp-Slice",
"done",
g6,
project_ids["Backend"],
"3bd9832",
),
(
"AP1.16 — Execution-Graph & Durchführungsplan",
"done",
g6,
project_ids["Backend"],
"b9bfa9e",
),
(
"AP1.9c — Cockpit-Signale auf Portfolio-Kacheln",
"done",
g5,
project_ids["Frontend"],
"b9bfa9e",
),
(
"AP2.0d — Next-Action-Strategien pro Archetyp",
"done",
g6,
project_ids["Backend"],
"284b9d5",
),
(
"DOC-Sync — Status-Review & Roadmap",
"done",
g6,
project_ids["Docs & ADPs"],
None,
),
]
for title, status, gate_id, project_id, sha in done_actions:
action = _ensure_action(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
status=status,
roadmap_item_id=gate_id,
project_id=project_id,
)
if sha:
_ensure_evidence(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=f"Merge {title}",
description=_gitea_commit(sha, title),
roadmap_item_id=gate_id,
action_id=action["id"],
actor_id=owner_actor_id,
)
open_actions = [
("Dogfooding R2 — Ist laufend pflegen", g6, project_ids["Docs & ADPs"]),
("AP1.7 — Operational Actor API", g6, project_ids["Backend"]),
("AP2.0f — work_cycle / Sprint-Zeitbox", g6, project_ids["Backend"]),
]
for title, gate_id, project_id in open_actions:
_ensure_action(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
status="open",
roadmap_item_id=gate_id,
project_id=project_id,
)
_ensure_decision(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Join/Branch Graph — deferred",
outcome="OR-Alternativpfade und volle Join-Logik erst bei Use Case (AP1.15d). "
"Siehe ADP_Roadmap_Graph_and_Gate_Checklist_v0.1.md",
)
_ensure_decision(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="MCP nach Operational API",
outcome="MCP-Adapter erst nach AP1.7 (/api/operational). Schicht 4 eingefroren bis B2b-Validation.",
)
_ensure_decision(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="MVP v0.3 PO-Freigabe",
outcome="Abnahfe Stufe A: A1, A2, B2b + B3 minimal. Dokument: Kairo_MVP_Definition_v0.3.md",
)
_ensure_portfolio_first(tenant_id=tenant_id, initiative_id=initiative_id)
from services.actors import create_actor, list_actors
agents = list_actors(tenant_id=tenant_id, actor_type="agent", q="Cursor")
if not any(a["name"] == "Cursor Agent" for a in agents):
create_actor(tenant_id=tenant_id, actor_type="agent", name="Cursor Agent")
print("[dogfooding] Agent „Cursor Agent“ angelegt — Service Token manuell erstellen")
print("[dogfooding] R2 sync — Ist-Stand gespiegelt (AP1.9c, AP1.16, AP2.0d done)")
+277 -8
View File
@@ -11,6 +11,7 @@ from services.audit import log_audit
from services.initiatives import PRIORITIES, get_initiative
from services.plan_ist import validate_roadmap_item_in_initiative
from services.projects import project_is_leaf
from services.work_cycle import validate_work_cycle_in_initiative
ActionStatus = Literal[
"open", "ready", "in_progress", "blocked", "review_required", "done", "discarded"
@@ -24,14 +25,31 @@ OPEN_ACTION_STATUSES = frozenset(
)
_ACTION_COLUMNS = """
id, tenant_id, initiative_id, project_id, roadmap_item_id, title, description,
status, priority, due_at, created_at, updated_at
id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, schedule_id,
title, description, status, priority, due_at, sort_order, action_kind, parent_action_id,
created_at, updated_at
"""
ACTION_KINDS = frozenset({"delivery", "planning", "review", "bug", "issue", "tech_debt"})
UNPLAN_ALLOWED_STATUSES = frozenset({"open", "ready"})
CARRYOVER_UNPLAN_STATUSES = frozenset(
{"open", "ready", "in_progress", "blocked", "review_required"}
)
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in ("id", "tenant_id", "initiative_id", "project_id", "roadmap_item_id", "owner_actor_id"):
for key in (
"id",
"tenant_id",
"initiative_id",
"project_id",
"roadmap_item_id",
"work_cycle_id",
"parent_action_id",
"owner_actor_id",
"schedule_id",
):
if result.get(key):
result[key] = str(result[key])
if result.get("created_at"):
@@ -43,6 +61,49 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
return result
def _validate_parent_action_in_initiative(
*,
cur,
tenant_id: str,
initiative_id: str,
parent_action_id: Optional[str],
action_id: Optional[str] = None,
) -> None:
if not parent_action_id:
return
if action_id and parent_action_id == action_id:
raise ValueError("Arbeitspaket kann nicht auf sich selbst verweisen")
cur.execute(
"""
SELECT action_kind
FROM actions
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
""",
(parent_action_id, tenant_id, initiative_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Referenz-Arbeitspaket (Feature) nicht gefunden")
action_kind = row["action_kind"] if isinstance(row, dict) else row[0]
if action_kind in ("bug", "issue", "tech_debt"):
raise ValueError("Referenz muss ein Feature-Arbeitspaket sein, kein Bug/Issue/Schuld")
def _action_kind_to_item_kind(action_kind: str) -> str:
if action_kind == "bug":
return "bug"
if action_kind == "issue":
return "issue"
if action_kind == "tech_debt":
return "tech_debt"
return "story"
def _validate_action_kind(action_kind: str) -> None:
if action_kind not in ACTION_KINDS:
raise ValueError(f"Ungültiger action_kind: {action_kind}")
def _validate_action_status(status: str) -> None:
if status not in ACTION_STATUSES:
raise ValueError(f"Ungültiger Action-Status: {status}")
@@ -137,7 +198,11 @@ def create_action(
due_at: Optional[Any] = None,
project_id: Optional[str] = None,
roadmap_item_id: Optional[str] = None,
work_cycle_id: Optional[str] = None,
assigned_actor_ids: Optional[list[str]] = None,
sort_order: int = 0,
action_kind: str = "delivery",
parent_action_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
title = title.strip()
@@ -145,6 +210,7 @@ def create_action(
raise ValueError("Titel ist erforderlich")
_validate_action_status(status)
_validate_priority(priority)
_validate_action_kind(action_kind)
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden")
_validate_project_in_initiative(
@@ -165,13 +231,26 @@ def create_action(
initiative_id=initiative_id,
roadmap_item_id=roadmap_item_id,
)
validate_work_cycle_in_initiative(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
cur=cur,
)
_validate_parent_action_in_initiative(
cur=cur,
tenant_id=tenant_id,
initiative_id=initiative_id,
parent_action_id=parent_action_id,
)
cur.execute(
f"""
INSERT INTO actions (
tenant_id, initiative_id, project_id, roadmap_item_id, title, description,
status, priority, due_at
tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id,
title, description, status, priority, due_at, sort_order, action_kind,
parent_action_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_ACTION_COLUMNS}
""",
(
@@ -179,11 +258,15 @@ def create_action(
initiative_id,
project_id,
roadmap_item_id,
work_cycle_id,
title,
description,
status,
priority,
due_at,
sort_order,
action_kind,
parent_action_id,
),
)
row = _serialize_row(dict(cur.fetchone()))
@@ -228,7 +311,7 @@ def list_actions_for_initiative(
SELECT {_ACTION_COLUMNS}
FROM actions
WHERE tenant_id = %s AND initiative_id = %s
ORDER BY updated_at DESC, title
ORDER BY sort_order ASC, title ASC, created_at DESC
""",
(tenant_id, initiative_id),
)
@@ -256,7 +339,10 @@ def get_action(*, tenant_id: str, action_id: str) -> Optional[dict[str, Any]]:
action = _serialize_row(dict(row))
finally:
conn.close()
return _attach_assignments([action], tenant_id=tenant_id)[0]
enriched = _attach_assignments([action], tenant_id=tenant_id)[0]
from services.scheduled_work import attach_action_schedule_fields
return attach_action_schedule_fields(enriched, tenant_id=tenant_id)
def update_action(
@@ -274,6 +360,12 @@ def update_action(
clear_project: bool = False,
roadmap_item_id: Optional[str] = None,
clear_roadmap_item: bool = False,
work_cycle_id: Optional[str] = None,
clear_work_cycle: bool = False,
sort_order: Optional[int] = None,
action_kind: Optional[str] = None,
parent_action_id: Optional[str] = None,
clear_parent_action: bool = False,
) -> Optional[dict[str, Any]]:
existing = get_action(tenant_id=tenant_id, action_id=action_id)
if not existing:
@@ -331,6 +423,28 @@ def update_action(
conn.close()
updates.append("roadmap_item_id = %s")
params.append(roadmap_item_id)
if clear_work_cycle:
updates.append("work_cycle_id = NULL")
elif work_cycle_id is not None:
validate_work_cycle_in_initiative(
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
work_cycle_id=work_cycle_id,
)
updates.append("work_cycle_id = %s")
params.append(work_cycle_id)
if sort_order is not None:
updates.append("sort_order = %s")
params.append(sort_order)
if action_kind is not None:
_validate_action_kind(action_kind)
updates.append("action_kind = %s")
params.append(action_kind)
if clear_parent_action:
updates.append("parent_action_id = NULL")
elif parent_action_id is not None:
updates.append("parent_action_id = %s")
params.append(parent_action_id)
if not updates:
return existing
@@ -341,6 +455,14 @@ def update_action(
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
if parent_action_id is not None and not clear_parent_action:
_validate_parent_action_in_initiative(
cur=cur,
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
parent_action_id=parent_action_id,
action_id=action_id,
)
cur.execute(
f"""
UPDATE actions
@@ -377,6 +499,20 @@ def update_action(
"to_status": status,
},
)
if status == "done":
from services.steering_events import emit_steering_event
emit_steering_event(
tenant_id=tenant_id,
initiative_id=str(existing["initiative_id"]),
event_kind="actor_result",
payload={
"action_id": action_id,
"from_status": old_status,
"to_status": status,
},
user_id=user_id,
)
return result
@@ -491,3 +627,136 @@ def list_open_actions_for_actor(
finally:
conn.close()
return _attach_assignments(actions, tenant_id=tenant_id)
def unplan_action_to_backlog(
*,
tenant_id: str,
action_id: str,
user_id: Optional[str] = None,
carryover: bool = False,
) -> dict[str, Any]:
"""Entfernt ein Arbeitspaket aus dem Sprint und stellt es im Eingang wieder her."""
existing = get_action(tenant_id=tenant_id, action_id=action_id)
if not existing:
raise ValueError("Arbeitspaket nicht gefunden")
allowed = CARRYOVER_UNPLAN_STATUSES if carryover else UNPLAN_ALLOWED_STATUSES
if existing["status"] not in allowed:
raise ValueError(
"Arbeitspaket kann in diesem Status nicht zurück in den Eingang geschoben werden"
if carryover
else "Nur offene oder bereite Arbeitspakete können zurück in den Eingang"
)
initiative_id = existing["initiative_id"]
item_kind = _action_kind_to_item_kind(existing.get("action_kind") or "delivery")
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id
FROM backlog_items
WHERE tenant_id = %s AND converted_action_id = %s
""",
(tenant_id, action_id),
)
linked = cur.fetchone()
if linked:
backlog_id = str(linked["id"])
cur.execute(
"""
UPDATE backlog_items
SET status = 'accepted',
converted_action_id = NULL,
title = %s,
description = %s,
priority = %s,
roadmap_item_id = %s,
item_kind = %s,
parent_action_id = %s,
updated_at = NOW()
WHERE id = %s AND tenant_id = %s
RETURNING id, tenant_id, initiative_id, title, description, status,
priority, roadmap_item_id, converted_action_id, sort_order,
item_kind, parent_action_id, created_at, updated_at
""",
(
existing["title"],
existing.get("description") or "",
existing["priority"],
existing.get("roadmap_item_id"),
item_kind,
existing.get("parent_action_id"),
backlog_id,
tenant_id,
),
)
backlog_row = _serialize_row(dict(cur.fetchone()))
else:
cur.execute(
"""
SELECT COALESCE(MAX(sort_order), -10) + 10 AS next_order
FROM backlog_items
WHERE tenant_id = %s AND initiative_id = %s
""",
(tenant_id, initiative_id),
)
next_order = int(cur.fetchone()["next_order"])
cur.execute(
"""
INSERT INTO backlog_items (
tenant_id, initiative_id, title, description, status, priority,
roadmap_item_id, sort_order, item_kind, parent_action_id
)
VALUES (%s, %s, %s, %s, 'accepted', %s, %s, %s, %s, %s)
RETURNING id, tenant_id, initiative_id, title, description, status,
priority, roadmap_item_id, converted_action_id, sort_order,
item_kind, parent_action_id, created_at, updated_at
""",
(
tenant_id,
initiative_id,
existing["title"],
existing.get("description") or "",
existing["priority"],
existing.get("roadmap_item_id"),
next_order,
item_kind,
existing.get("parent_action_id"),
),
)
backlog_row = _serialize_row(dict(cur.fetchone()))
cur.execute(
"""
UPDATE actions
SET status = 'discarded',
work_cycle_id = NULL,
updated_at = NOW()
WHERE id = %s AND tenant_id = %s
RETURNING id, tenant_id, initiative_id, project_id, roadmap_item_id,
work_cycle_id, title, description, status, priority, due_at,
sort_order, action_kind, parent_action_id, created_at, updated_at
""",
(action_id, tenant_id),
)
action_row = _serialize_row(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
action_result = get_action(tenant_id=tenant_id, action_id=action_id)
log_audit(
"action.unplanned_to_backlog",
user_id=user_id,
tenant_id=tenant_id,
details={
"action_id": action_id,
"backlog_item_id": backlog_row["id"],
"initiative_id": initiative_id,
},
)
return {"backlog_item": backlog_row, "action": action_result or action_row}
+280
View File
@@ -0,0 +1,280 @@
"""Actor Service Tokens — AP1.7c (machine auth for Operational API)."""
from __future__ import annotations
import hashlib
import json
import secrets
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from services.audit import log_audit
TOKEN_PREFIX = "kairo_at_"
DEFAULT_AGENT_CAPABILITIES: tuple[str, ...] = (
"kairo.initiative.read",
"kairo.action.read",
"kairo.action.manage",
"kairo.blocker.read",
"kairo.blocker.manage",
"kairo.evidence.read",
"kairo.evidence.manage",
"kairo.backlog.read",
"kairo.backlog.manage",
"kairo.decision.read",
"kairo.decision.manage",
"kairo.recurring.read",
"kairo.recurring.manage",
)
ALLOWED_TOKEN_CAPABILITIES = frozenset(DEFAULT_AGENT_CAPABILITIES)
def _hash_token(raw_token: str) -> str:
return hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
def _generate_token_parts() -> tuple[str, str, str]:
prefix = secrets.token_hex(6)
secret = secrets.token_urlsafe(24)
raw = f"{TOKEN_PREFIX}{prefix}_{secret}"
return prefix, secret, raw
def _validate_capabilities(capabilities: list[str]) -> list[str]:
if not capabilities:
return list(DEFAULT_AGENT_CAPABILITIES)
invalid = [cap for cap in capabilities if cap not in ALLOWED_TOKEN_CAPABILITIES]
if invalid:
raise ValueError(f"Capabilities nicht erlaubt für Service Token: {', '.join(invalid)}")
return sorted(set(capabilities))
def _serialize_token_row(row: dict[str, Any], *, include_actor: bool = False) -> dict[str, Any]:
item = {
"id": str(row["id"]),
"tenant_id": str(row["tenant_id"]),
"actor_id": str(row["actor_id"]),
"label": row["label"],
"token_prefix": row["token_prefix"],
"capabilities": list(row.get("capabilities") or []),
"is_active": bool(row["is_active"]),
"expires_at": row["expires_at"].isoformat() if row.get("expires_at") else None,
"last_used_at": row["last_used_at"].isoformat() if row.get("last_used_at") else None,
"created_at": row["created_at"].isoformat() if row.get("created_at") else None,
"revoked_at": row["revoked_at"].isoformat() if row.get("revoked_at") else None,
}
if include_actor and row.get("actor_name"):
item["actor_name"] = row["actor_name"]
item["actor_type"] = row.get("actor_type")
return item
def create_service_token(
*,
tenant_id: str,
actor_id: str,
label: str,
created_by_user_id: Optional[str] = None,
capabilities: Optional[list[str]] = None,
expires_in_days: Optional[int] = 365,
) -> dict[str, Any]:
label = label.strip()
if not label:
raise ValueError("Label ist erforderlich")
caps = _validate_capabilities(list(capabilities or []))
prefix, _secret, raw_token = _generate_token_parts()
token_hash = _hash_token(raw_token)
expires_at = None
if expires_in_days and expires_in_days > 0:
expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, actor_type, name, is_active
FROM actors
WHERE id = %s AND tenant_id = %s
""",
(actor_id, tenant_id),
)
actor = cur.fetchone()
if not actor:
raise ValueError("Actor nicht gefunden")
if not actor["is_active"]:
raise ValueError("Actor ist inaktiv")
cur.execute(
"""
INSERT INTO actor_service_tokens (
tenant_id, actor_id, label, token_prefix, token_hash,
capabilities, expires_at, created_by_user_id
)
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s)
RETURNING id, tenant_id, actor_id, label, token_prefix, capabilities,
is_active, expires_at, last_used_at, created_at, revoked_at
""",
(
tenant_id,
actor_id,
label,
prefix,
token_hash,
json.dumps(caps),
expires_at,
created_by_user_id,
),
)
row = dict(cur.fetchone())
conn.commit()
finally:
conn.close()
log_audit(
"actor_service_token.created",
user_id=created_by_user_id,
tenant_id=tenant_id,
details={"token_id": str(row["id"]), "actor_id": actor_id, "label": label},
)
result = _serialize_token_row(row)
result["token"] = raw_token
return result
def list_service_tokens_for_actor(
*, tenant_id: str, actor_id: str, include_revoked: bool = False
) -> list[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
conditions = ["t.tenant_id = %s", "t.actor_id = %s"]
params: list[Any] = [tenant_id, actor_id]
if not include_revoked:
conditions.append("t.revoked_at IS NULL")
where = " AND ".join(conditions)
cur.execute(
f"""
SELECT t.id, t.tenant_id, t.actor_id, t.label, t.token_prefix,
t.capabilities, t.is_active, t.expires_at, t.last_used_at,
t.created_at, t.revoked_at
FROM actor_service_tokens t
WHERE {where}
ORDER BY t.created_at DESC
""",
params,
)
return [_serialize_token_row(dict(row)) for row in cur.fetchall()]
finally:
conn.close()
def revoke_service_token(
*, tenant_id: str, token_id: str, user_id: Optional[str] = None
) -> bool:
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE actor_service_tokens
SET is_active = FALSE, revoked_at = NOW()
WHERE id = %s AND tenant_id = %s AND revoked_at IS NULL
""",
(token_id, tenant_id),
)
updated = cur.rowcount > 0
conn.commit()
finally:
conn.close()
if updated:
log_audit(
"actor_service_token.revoked",
user_id=user_id,
tenant_id=tenant_id,
details={"token_id": token_id},
)
return updated
def validate_service_token(raw_token: str) -> Optional[dict[str, Any]]:
"""Resolve token → auth context dict or None."""
token = (raw_token or "").strip()
if not token.startswith(TOKEN_PREFIX) or len(token) < 20:
return None
token_hash = _hash_token(token)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT
t.id,
t.tenant_id,
t.actor_id,
t.capabilities,
t.is_active,
t.expires_at,
t.revoked_at,
a.name AS actor_name,
a.actor_type,
a.is_active AS actor_is_active,
tn.slug AS tenant_slug,
tn.name AS tenant_name
FROM actor_service_tokens t
JOIN actors a ON a.id = t.actor_id AND a.tenant_id = t.tenant_id
JOIN tenants tn ON tn.id = t.tenant_id
WHERE t.token_hash = %s
LIMIT 1
""",
(token_hash,),
)
row = cur.fetchone()
if not row:
return None
row = dict(row)
if not row["is_active"] or row.get("revoked_at"):
return None
if not row["actor_is_active"] or not row.get("tenant_slug"):
return None
if row.get("expires_at"):
expires = row["expires_at"]
if expires.tzinfo is None:
expires = expires.replace(tzinfo=timezone.utc)
if expires <= datetime.now(timezone.utc):
return None
cur.execute(
"""
UPDATE actor_service_tokens
SET last_used_at = NOW()
WHERE id = %s
""",
(str(row["id"]),),
)
conn.commit()
caps = row.get("capabilities") or []
if isinstance(caps, str):
caps = json.loads(caps)
return {
"token_id": str(row["id"]),
"tenant_id": str(row["tenant_id"]),
"tenant_slug": row["tenant_slug"],
"tenant_name": row["tenant_name"],
"actor_id": str(row["actor_id"]),
"actor_name": row["actor_name"],
"actor_type": row["actor_type"],
"capabilities": frozenset(str(c) for c in caps),
}
finally:
conn.close()
+539
View File
@@ -0,0 +1,539 @@
"""Archetyp Starter-Kits — AP2.2a (guided creation without Structure Builder)."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Optional
from entity_archetypes import resolve_default_method_key
# Stufe-A Archetypen mit automatischem Starter-Kit bei Anlage
STARTER_KIT_ARCHETYPES = frozenset(
{
"initiative.maturity_journey",
"initiative.linear_project",
"initiative.product",
"initiative.program",
}
)
_GUIDANCE: dict[str, str] = {
"initiative.maturity_journey": (
"Aktuelle Stufe und heutige Übung steuern deinen nächsten Schritt."
),
"initiative.linear_project": (
"Kritischer Pfad und Abhängigkeiten steuern Next — nicht die Gesamtliste."
),
"initiative.product": (
"Eingang triagieren, dann committete Actions — optional Sprint-Zeitbox (B3)."
),
"initiative.program": (
"Programm mit Abschluss — Gate-Horizont in Kontrolle."
),
}
_PROFILE_HINTS: dict[str, list[str]] = {
"initiative.maturity_journey": ["maturity.karate_kumite"],
"initiative.linear_project": ["project.agile_iteration"],
"initiative.product": ["product.kairo_dev"],
"initiative.program": [],
}
def _find_by_title(items: list[dict[str, Any]], title: str) -> Optional[dict[str, Any]]:
for item in items:
if item.get("title") == title:
return item
return None
def supports_starter_kit(archetype_key: str) -> bool:
return archetype_key in STARTER_KIT_ARCHETYPES
def get_starter_preview(
*,
archetype_key: str,
method_profile_key: Optional[str] = None,
) -> dict[str, Any]:
method_key = resolve_default_method_key(archetype_key)
items: list[dict[str, Any]] = []
if archetype_key == "initiative.maturity_journey":
items = [
{"kind": "maturity_stage", "title": "Stufe 1 — Basis", "status": "active"},
{"kind": "maturity_stage", "title": "Stufe 2 — Aufbau", "status": "planned"},
{"kind": "maturity_stage", "title": "Stufe 3 — Ziel", "status": "planned"},
{"kind": "project", "title": "Training"},
{"kind": "recurring", "title": "Vorbeuge-Dehnung"},
{"kind": "recurring", "title": "Hüftöffner (Schmetterling)"},
]
elif archetype_key == "initiative.linear_project":
items = [
{"kind": "milestone", "title": "G1 — Planung", "status": "active"},
{"kind": "milestone", "title": "G2 — Vorbereitung", "status": "planned"},
{"kind": "milestone", "title": "G3 — Umsetzung", "status": "planned"},
{"kind": "milestone", "title": "G4 — Abschluss", "status": "planned"},
{"kind": "project", "title": "Hauptpfad"},
{"kind": "project", "title": "Begleitung"},
{"kind": "action", "title": "Erster Schritt — Planung konkretisieren"},
]
elif archetype_key == "initiative.product":
items = [
{"kind": "milestone", "title": "Orientierung", "status": "active"},
{"kind": "milestone", "title": "Nächster Release-Horizont", "status": "planned"},
{"kind": "project", "title": "Entwicklung"},
{"kind": "project", "title": "Betrieb"},
{"kind": "backlog_item", "title": "Idee / Issue"},
{"kind": "hint", "title": "Optional: Sprint-Zeitbox unter Plan anlegen (B3)"},
]
elif archetype_key == "initiative.program":
items = [
{"kind": "milestone", "title": "Phase 1 — Start", "status": "active"},
{"kind": "milestone", "title": "Phase 2 — Lieferung", "status": "planned"},
{"kind": "milestone", "title": "Abschluss", "status": "planned"},
]
return {
"archetype_key": archetype_key,
"method_key": method_key,
"method_profile_key": method_profile_key,
"supported": supports_starter_kit(archetype_key),
"guidance": _GUIDANCE.get(archetype_key, ""),
"method_profile_hints": _PROFILE_HINTS.get(archetype_key, []),
"items": items,
}
def apply_starter_kit(
*,
tenant_id: str,
initiative_id: str,
archetype_key: str,
owner_actor_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
"""Apply idempotent starter structure for supported Stufe-A archetypes."""
if not supports_starter_kit(archetype_key):
return {"applied": False, "reason": "unsupported_archetype"}
from services.roadmap import list_roadmap_items_for_initiative
existing = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if existing:
return {"applied": False, "reason": "structure_exists"}
created: dict[str, list[str]] = {
"roadmap_items": [],
"projects": [],
"recurring": [],
"backlog_items": [],
"actions": [],
}
if archetype_key == "initiative.maturity_journey":
created = _apply_a1(
tenant_id=tenant_id,
initiative_id=initiative_id,
user_id=user_id,
)
elif archetype_key == "initiative.linear_project":
created = _apply_a2(
tenant_id=tenant_id,
initiative_id=initiative_id,
user_id=user_id,
)
elif archetype_key == "initiative.product":
created = _apply_b2b(
tenant_id=tenant_id,
initiative_id=initiative_id,
user_id=user_id,
)
elif archetype_key == "initiative.program":
created = _apply_b2a(
tenant_id=tenant_id,
initiative_id=initiative_id,
user_id=user_id,
)
from services.audit import log_audit
log_audit(
"initiative.starter_kit_applied",
user_id=user_id,
tenant_id=tenant_id,
details={
"initiative_id": initiative_id,
"archetype_key": archetype_key,
"created": created,
},
)
return {
"applied": True,
"archetype_key": archetype_key,
"guidance": _GUIDANCE.get(archetype_key, ""),
"created": created,
}
def _apply_a1(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str],
) -> dict[str, list[str]]:
from services.projects import create_project, list_projects_for_initiative
from services.roadmap import create_roadmap_item
roadmap_ids: list[str] = []
stage_defs = [
("Stufe 1 — Basis", "active"),
("Stufe 2 — Aufbau", "planned"),
("Stufe 3 — Ziel", "planned"),
]
stage_items: list[dict[str, Any]] = []
for index, (title, status) in enumerate(stage_defs):
item = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="maturity_stage",
status=status, # type: ignore[arg-type]
sort_order=index * 10,
user_id=user_id,
)
roadmap_ids.append(item["id"])
stage_items.append(item)
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not _find_by_title(projects, "Training"):
create_project(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Training",
description="Übungs- und Trainingsstruktur",
sort_order=0,
user_id=user_id,
)
from services.maturity_practice import seed_practices_for_stage
exercises = seed_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage=stage_items[0],
user_id=user_id,
)
return {
"roadmap_items": roadmap_ids,
"projects": ["Training"],
"recurring": [e["title"] for e in exercises],
}
def _apply_a2(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str],
) -> dict[str, list[str]]:
from services.projects import create_project, list_projects_for_initiative
from services.roadmap import add_dependency, create_roadmap_item
gate_titles = [
("G1 — Planung", "active"),
("G2 — Vorbereitung", "planned"),
("G3 — Umsetzung", "planned"),
("G4 — Abschluss", "planned"),
]
gate_ids: list[str] = []
for index, (title, status) in enumerate(gate_titles):
item = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="milestone",
status=status, # type: ignore[arg-type]
sort_order=index * 10,
user_id=user_id,
)
gate_ids.append(item["id"])
for index in range(1, len(gate_ids)):
try:
add_dependency(
tenant_id=tenant_id,
from_item_id=gate_ids[index],
to_item_id=gate_ids[index - 1],
dependency_type="requires",
)
except ValueError as exc:
if "existiert bereits" not in str(exc):
raise
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
for index, title in enumerate(["Hauptpfad", "Begleitung"]):
if not _find_by_title(projects, title):
create_project(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=f"Ist-Struktur — {title}",
sort_order=index,
user_id=user_id,
)
from services.actions import create_action, list_actions_for_initiative
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
hauptpfad = _find_by_title(projects, "Hauptpfad")
actions = list_actions_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not _find_by_title(actions, "Erster Schritt — Planung konkretisieren"):
create_action(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Erster Schritt — Planung konkretisieren",
description="Starter-Arbeitspaket am ersten Gate",
status="open",
roadmap_item_id=gate_ids[0],
project_id=hauptpfad["id"] if hauptpfad else None,
sort_order=0,
user_id=user_id,
)
return {
"roadmap_items": gate_ids,
"projects": ["Hauptpfad", "Begleitung"],
"actions": ["Erster Schritt — Planung konkretisieren"],
}
def _retire_legacy_linear_stages_for_progression(
*,
tenant_id: str,
initiative_id: str,
keep_gate_ids: frozenset[str],
user_id: Optional[str] = None,
) -> None:
"""Starter-Kit-Stufen zurückstellen, wenn Join-Graph angelegt wird."""
from services.maturity_practice import list_practices_for_stage, update_recurring_element
from services.roadmap import list_roadmap_items_for_initiative, update_roadmap_item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
):
if item.get("item_type") != "maturity_stage":
continue
if str(item["id"]) in keep_gate_ids:
continue
if item.get("status") not in ("active", "at_risk"):
continue
update_roadmap_item(
tenant_id=tenant_id,
item_id=item["id"],
status="planned",
user_id=user_id,
)
for practice in list_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage_id=item["id"],
):
if practice.get("status") == "active":
update_recurring_element(
tenant_id=tenant_id,
recurring_id=practice["id"],
status="paused",
user_id=user_id,
)
def apply_a1_progression_demo(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
"""PO-Kernbild: 2 parallele Gates → Join → Ausgänge (AP-A1-PM-6). Idempotent wenn Struktur existiert."""
from services.maturity_practice import seed_practices_for_stage
from services.roadmap import add_dependency, create_roadmap_item, list_roadmap_items_for_initiative
existing = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if any(item.get("item_type") == "join_gate" for item in existing):
return {"applied": False, "reason": "progression_exists"}
d1 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Dehnung — Einstieg",
item_type="maturity_stage",
status="active",
sort_order=10,
user_id=user_id,
)
h1 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Hüftrotation — Einstieg",
item_type="maturity_stage",
status="active",
sort_order=20,
user_id=user_id,
)
join = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Mawashi Geri zur Hüfte",
item_type="join_gate",
status="planned",
sort_order=30,
user_id=user_id,
)
d2 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Dehnung — nach Join",
item_type="maturity_stage",
status="planned",
sort_order=40,
user_id=user_id,
)
h2 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Hüftrotation — nach Join",
item_type="maturity_stage",
status="planned",
sort_order=50,
user_id=user_id,
)
for from_id, to_id in (
(join["id"], d1["id"]),
(join["id"], h1["id"]),
(d2["id"], join["id"]),
(h2["id"], join["id"]),
):
try:
add_dependency(
tenant_id=tenant_id,
from_item_id=from_id,
to_item_id=to_id,
dependency_type="requires",
user_id=user_id,
)
except ValueError as exc:
if "existiert bereits" not in str(exc):
raise
seed_practices_for_stage(
tenant_id=tenant_id, initiative_id=initiative_id, stage=d1, user_id=user_id
)
seed_practices_for_stage(
tenant_id=tenant_id, initiative_id=initiative_id, stage=h1, user_id=user_id
)
_retire_legacy_linear_stages_for_progression(
tenant_id=tenant_id,
initiative_id=initiative_id,
keep_gate_ids=frozenset(
str(gate["id"]) for gate in (d1, h1, d2, h2)
),
user_id=user_id,
)
return {
"applied": True,
"join": join["title"],
"active_gates": [d1["title"], h1["title"]],
}
def _apply_b2b(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str],
) -> dict[str, list[str]]:
from services.backlog import create_backlog_item, list_backlog_for_initiative
from services.projects import create_project, list_projects_for_initiative
from services.roadmap import create_roadmap_item
roadmap_ids: list[str] = []
for index, (title, status) in enumerate(
[("Orientierung", "active"), ("Nächster Release-Horizont", "planned")]
):
item = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="milestone",
status=status, # type: ignore[arg-type]
sort_order=index * 10,
user_id=user_id,
)
roadmap_ids.append(item["id"])
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
for index, title in enumerate(["Entwicklung", "Betrieb"]):
if not _find_by_title(projects, title):
create_project(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=f"Ist-Struktur — {title}",
sort_order=index,
user_id=user_id,
)
backlog = list_backlog_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not _find_by_title(backlog, "Idee / Issue"):
create_backlog_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Idee / Issue",
description="Product Backlog — noch nicht committet",
user_id=user_id,
)
return {
"roadmap_items": roadmap_ids,
"projects": ["Entwicklung", "Betrieb"],
"backlog_items": ["Idee / Issue"],
}
def _apply_b2a(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str],
) -> dict[str, list[str]]:
from services.roadmap import create_roadmap_item
roadmap_ids: list[str] = []
for index, (title, status) in enumerate(
[
("Phase 1 — Start", "active"),
("Phase 2 — Lieferung", "planned"),
("Abschluss", "planned"),
]
):
item = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="milestone",
status=status, # type: ignore[arg-type]
sort_order=index * 10,
user_id=user_id,
)
roadmap_ids.append(item["id"])
return {"roadmap_items": roadmap_ids}
+1 -1
View File
@@ -23,7 +23,7 @@ def log_audit(
INSERT INTO audit_log (action, user_id, tenant_id, details)
VALUES (%s, %s, %s, %s::jsonb)
""",
(action, user_id, tenant_id, json.dumps(details or {})),
(action, user_id or None, tenant_id, json.dumps(details or {})),
)
conn.commit()
finally:
+269 -6
View File
@@ -10,21 +10,34 @@ from db import get_connection
from services.actions import create_action
from services.audit import log_audit
from services.initiatives import PRIORITIES, get_initiative
from services.operating_context import get_operating_context
from services.plan_ist import validate_roadmap_item_in_initiative
BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"]
BacklogItemKind = Literal["story", "bug", "issue", "epic", "tech_debt"]
BACKLOG_STATUSES = frozenset({"new", "triaged", "accepted", "rejected", "converted"})
BACKLOG_ITEM_KINDS = frozenset({"story", "bug", "issue", "epic", "tech_debt"})
CONVERTIBLE_ITEM_KINDS = frozenset({"story", "bug", "issue", "tech_debt"})
_BACKLOG_COLUMNS = """
id, tenant_id, initiative_id, title, description, status,
priority, roadmap_item_id, converted_action_id, created_at, updated_at
priority, roadmap_item_id, converted_action_id, sort_order, item_kind,
parent_action_id, parent_backlog_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", "converted_action_id", "roadmap_item_id"):
for key in (
"id",
"tenant_id",
"initiative_id",
"converted_action_id",
"roadmap_item_id",
"parent_action_id",
"parent_backlog_id",
):
if result.get(key):
result[key] = str(result[key])
if result.get("created_at"):
@@ -44,6 +57,117 @@ def _validate_priority(priority: str) -> None:
raise ValueError(f"Ungültige Priorität: {priority}")
def _validate_item_kind(item_kind: str) -> None:
if item_kind not in BACKLOG_ITEM_KINDS:
raise ValueError(f"Ungültiger Backlog-Typ: {item_kind}")
def _backlog_vocabulary_for_initiative(*, tenant_id: str, initiative_id: str) -> dict[str, Any]:
context = get_operating_context(tenant_id=tenant_id, initiative_id=initiative_id)
if not context:
raise ValueError("Initiative nicht gefunden")
return context.get("backlog_vocabulary") or {}
def _validate_item_kind_for_initiative(
*, tenant_id: str, initiative_id: str, item_kind: str
) -> dict[str, Any]:
_validate_item_kind(item_kind)
vocabulary = _backlog_vocabulary_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
allowed = vocabulary.get("kinds") or []
if allowed and item_kind not in allowed:
raise ValueError(
f"Backlog-Typ '{item_kind}' ist für dieses Vorhaben nicht erlaubt"
)
return vocabulary
def _item_kind_to_action_kind(item_kind: str) -> str:
if item_kind == "bug":
return "bug"
if item_kind == "issue":
return "issue"
if item_kind == "tech_debt":
return "tech_debt"
return "delivery"
def _validate_parent_action_in_initiative(
*,
cur,
tenant_id: str,
initiative_id: str,
parent_action_id: Optional[str],
) -> None:
if not parent_action_id:
return
cur.execute(
"""
SELECT action_kind, parent_action_id
FROM actions
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
""",
(parent_action_id, tenant_id, initiative_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Referenz-Arbeitspaket (Feature) nicht gefunden")
action_kind = row["action_kind"] if isinstance(row, dict) else row[0]
if action_kind in ("bug", "issue"):
raise ValueError("Referenz muss ein Feature-Arbeitspaket sein, kein Bug/Issue")
def _validate_backlog_hierarchy(
*,
cur,
tenant_id: str,
initiative_id: str,
item_kind: str,
parent_backlog_id: Optional[str],
parent_action_id: Optional[str],
backlog_item_id: Optional[str] = None,
epic_hierarchy: bool = True,
) -> None:
if item_kind == "epic" and not epic_hierarchy:
raise ValueError("Epic ist für dieses Vorhaben nicht verfügbar")
if item_kind == "epic":
if parent_backlog_id:
raise ValueError("Epic kann keinem übergeordneten Backlog-Item zugeordnet werden")
if parent_action_id:
raise ValueError("Epic kann keinem Arbeitspaket zugeordnet werden")
return
if not parent_backlog_id:
return
if not epic_hierarchy:
raise ValueError("Epic-Zuordnung ist für dieses Vorhaben nicht verfügbar")
if backlog_item_id and parent_backlog_id == backlog_item_id:
raise ValueError("Item kann nicht sich selbst als Epic referenzieren")
cur.execute(
"""
SELECT id, item_kind, initiative_id
FROM backlog_items
WHERE id = %s AND tenant_id = %s
""",
(parent_backlog_id, tenant_id),
)
parent = cur.fetchone()
if not parent:
raise ValueError("Epic-Referenz nicht gefunden")
parent_initiative = parent["initiative_id"] if isinstance(parent, dict) else parent[2]
parent_kind = parent["item_kind"] if isinstance(parent, dict) else parent[1]
if str(parent_initiative) != initiative_id:
raise ValueError("Epic gehört zu einem anderen Vorhaben")
if parent_kind != "epic":
raise ValueError("Übergeordnetes Item muss ein Epic sein")
def create_backlog_item(
*,
tenant_id: str,
@@ -53,6 +177,10 @@ def create_backlog_item(
status: BacklogStatus = "new",
priority: str = "normal",
roadmap_item_id: Optional[str] = None,
sort_order: Optional[int] = None,
item_kind: BacklogItemKind = "story",
parent_action_id: Optional[str] = None,
parent_backlog_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
title = title.strip()
@@ -60,6 +188,10 @@ def create_backlog_item(
raise ValueError("Titel ist erforderlich")
_validate_status(status)
_validate_priority(priority)
vocabulary = _validate_item_kind_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id, item_kind=item_kind
)
epic_hierarchy = bool((vocabulary.get("capabilities") or {}).get("epic_hierarchy"))
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden")
@@ -72,16 +204,52 @@ def create_backlog_item(
initiative_id=initiative_id,
roadmap_item_id=roadmap_item_id,
)
_validate_parent_action_in_initiative(
cur=cur,
tenant_id=tenant_id,
initiative_id=initiative_id,
parent_action_id=parent_action_id,
)
_validate_backlog_hierarchy(
cur=cur,
tenant_id=tenant_id,
initiative_id=initiative_id,
item_kind=item_kind,
parent_backlog_id=parent_backlog_id,
parent_action_id=parent_action_id,
epic_hierarchy=epic_hierarchy,
)
cur.execute(
"""
SELECT COALESCE(MAX(sort_order), -10) + 10 AS next_order
FROM backlog_items
WHERE tenant_id = %s AND initiative_id = %s
""",
(tenant_id, initiative_id),
)
next_order = int(cur.fetchone()["next_order"])
cur.execute(
f"""
INSERT INTO backlog_items (
tenant_id, initiative_id, title, description, status, priority,
roadmap_item_id
roadmap_item_id, sort_order, item_kind, parent_action_id, parent_backlog_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_BACKLOG_COLUMNS}
""",
(tenant_id, initiative_id, title, description, status, priority, roadmap_item_id),
(
tenant_id,
initiative_id,
title,
description,
status,
priority,
roadmap_item_id,
sort_order if sort_order is not None else next_order,
item_kind,
parent_action_id,
parent_backlog_id,
),
)
row = _serialize_row(dict(cur.fetchone()))
conn.commit()
@@ -109,7 +277,7 @@ def list_backlog_for_initiative(*, tenant_id: str, initiative_id: str) -> list[d
SELECT {_BACKLOG_COLUMNS}
FROM backlog_items
WHERE tenant_id = %s AND initiative_id = %s
ORDER BY updated_at DESC, title
ORDER BY sort_order ASC, created_at ASC, title
""",
(tenant_id, initiative_id),
)
@@ -147,6 +315,12 @@ def update_backlog_item(
priority: Optional[str] = None,
roadmap_item_id: Optional[str] = None,
clear_roadmap_item: bool = False,
sort_order: Optional[int] = None,
item_kind: Optional[BacklogItemKind] = None,
parent_action_id: Optional[str] = None,
clear_parent_action: bool = False,
parent_backlog_id: Optional[str] = None,
clear_parent_backlog: bool = False,
) -> Optional[dict[str, Any]]:
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
if not existing:
@@ -191,16 +365,74 @@ def update_backlog_item(
conn.close()
updates.append("roadmap_item_id = %s")
params.append(roadmap_item_id)
if sort_order is not None:
updates.append("sort_order = %s")
params.append(sort_order)
if item_kind is not None:
_validate_item_kind(item_kind)
updates.append("item_kind = %s")
params.append(item_kind)
effective_kind = item_kind if item_kind is not None else existing.get("item_kind") or "story"
vocabulary = _validate_item_kind_for_initiative(
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
item_kind=effective_kind,
)
epic_hierarchy = bool((vocabulary.get("capabilities") or {}).get("epic_hierarchy"))
if clear_parent_action:
updates.append("parent_action_id = NULL")
elif parent_action_id is not None:
updates.append("parent_action_id = %s")
params.append(parent_action_id)
if clear_parent_backlog:
updates.append("parent_backlog_id = NULL")
elif parent_backlog_id is not None:
updates.append("parent_backlog_id = %s")
params.append(parent_backlog_id)
if not updates:
return existing
effective_parent_backlog = (
None
if clear_parent_backlog
else parent_backlog_id
if parent_backlog_id is not None
else existing.get("parent_backlog_id")
)
effective_parent_action = (
None
if clear_parent_action
else parent_action_id
if parent_action_id is not None
else existing.get("parent_action_id")
)
updates.append("updated_at = NOW()")
params.extend([backlog_item_id, tenant_id])
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
_validate_backlog_hierarchy(
cur=cur,
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
item_kind=effective_kind,
parent_backlog_id=effective_parent_backlog,
parent_action_id=effective_parent_action,
backlog_item_id=backlog_item_id,
epic_hierarchy=epic_hierarchy,
)
if parent_action_id is not None and not clear_parent_action:
_validate_parent_action_in_initiative(
cur=cur,
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
parent_action_id=parent_action_id,
)
cur.execute(
f"""
UPDATE backlog_items
@@ -247,6 +479,18 @@ def delete_backlog_item(
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id FROM backlog_items
WHERE parent_backlog_id = %s AND tenant_id = %s AND status != 'converted'
LIMIT 1
""",
(backlog_item_id, tenant_id),
)
if cur.fetchone():
raise ValueError(
"Epic mit untergeordneten Items kann nicht gelöscht werden"
)
cur.execute(
"DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id",
(backlog_item_id, tenant_id),
@@ -272,6 +516,8 @@ def convert_backlog_to_action(
backlog_item_id: str,
user_id: Optional[str] = None,
assigned_actor_ids: Optional[list[str]] = None,
work_cycle_id: Optional[str] = None,
assign_active_sprint: bool = True,
) -> dict[str, Any]:
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
if not existing:
@@ -281,6 +527,20 @@ def convert_backlog_to_action(
if existing["status"] not in ("accepted", "triaged", "new"):
raise ValueError("Backlog-Item kann in diesem Status nicht konvertiert werden")
item_kind = existing.get("item_kind") or "story"
if item_kind not in CONVERTIBLE_ITEM_KINDS:
raise ValueError("Epic kann nicht direkt in ein Arbeitspaket umgewandelt werden")
resolved_cycle_id = work_cycle_id
if not resolved_cycle_id and assign_active_sprint:
from services.work_cycle import get_active_work_cycle
active = get_active_work_cycle(
tenant_id=tenant_id, initiative_id=existing["initiative_id"]
)
if active:
resolved_cycle_id = active["id"]
action = create_action(
tenant_id=tenant_id,
initiative_id=existing["initiative_id"],
@@ -288,7 +548,10 @@ def convert_backlog_to_action(
description=existing["description"] or "",
priority=existing["priority"],
roadmap_item_id=existing.get("roadmap_item_id"),
work_cycle_id=resolved_cycle_id,
assigned_actor_ids=assigned_actor_ids or [],
action_kind=_item_kind_to_action_kind(item_kind),
parent_action_id=existing.get("parent_action_id"),
user_id=user_id,
)
+278
View File
@@ -0,0 +1,278 @@
"""CadenceInstance service — AP A1.1 minimal daily practice tracking."""
from __future__ import annotations
from datetime import datetime, time, timedelta, timezone
from typing import Any, Literal, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from services.audit import log_audit
CadenceStatus = Literal["open", "completed"]
_CADENCE_COLUMNS = """
id, tenant_id, recurring_element_id, status, due_at,
completed_at, measurement_note, created_at, updated_at
"""
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in ("id", "tenant_id", "recurring_element_id"):
if result.get(key):
result[key] = str(result[key])
for ts_key in ("due_at", "completed_at", "created_at", "updated_at"):
if result.get(ts_key):
result[ts_key] = result[ts_key].isoformat()
return result
def get_open_instance(
*, tenant_id: str, recurring_element_id: str
) -> Optional[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
SELECT {_CADENCE_COLUMNS}
FROM cadence_instances
WHERE tenant_id = %s
AND recurring_element_id = %s
AND status = 'open'
LIMIT 1
""",
(tenant_id, recurring_element_id),
)
row = cur.fetchone()
return _serialize_row(dict(row)) if row else None
finally:
conn.close()
def ensure_open_instance(
*,
tenant_id: str,
recurring_element_id: str,
due_at: Optional[datetime] = None,
) -> dict[str, Any]:
"""Ensure exactly one open CadenceInstance (idempotent)."""
existing = get_open_instance(
tenant_id=tenant_id, recurring_element_id=recurring_element_id
)
if existing:
return existing
due = due_at or datetime.now(timezone.utc)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
INSERT INTO cadence_instances (
tenant_id, recurring_element_id, status, due_at
)
VALUES (%s, %s, 'open', %s)
RETURNING {_CADENCE_COLUMNS}
""",
(tenant_id, recurring_element_id, due),
)
row = _serialize_row(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
return row
def _next_due_at(
*,
now: datetime,
interval_days: int | None = None,
schedule: dict[str, Any] | None = None,
) -> datetime:
if schedule:
from services.schedule import next_due_after_completion
return next_due_after_completion(schedule=schedule, completed_at=now)
days = max(int(interval_days or 1), 1)
next_date = now.date() + timedelta(days=days)
return datetime.combine(next_date, time.min, tzinfo=timezone.utc)
def _parse_due(value: Any) -> Optional[datetime]:
if value is None:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
def complete_open_instance(
*,
tenant_id: str,
recurring_element_id: str,
user_id: Optional[str] = None,
measurement_note: str = "",
) -> dict[str, Any]:
"""
Close open instance, advance recurring next_due_at, open next instance.
Returns { completed, recurring, next_instance }.
"""
from services.recurring import get_recurring_element, update_recurring_element
recurring = get_recurring_element(
tenant_id=tenant_id, recurring_id=recurring_element_id
)
if not recurring:
raise ValueError("Recurring-Element nicht gefunden")
if recurring["status"] != "active":
raise ValueError("Recurring-Element ist nicht aktiv")
open_inst = get_open_instance(
tenant_id=tenant_id, recurring_element_id=recurring_element_id
)
if not open_inst:
open_inst = ensure_open_instance(
tenant_id=tenant_id,
recurring_element_id=recurring_element_id,
due_at=datetime.now(timezone.utc),
)
now = datetime.now(timezone.utc)
note = (measurement_note or "").strip()
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
UPDATE cadence_instances
SET status = 'completed',
completed_at = %s,
measurement_note = %s,
updated_at = NOW()
WHERE id = %s AND tenant_id = %s AND status = 'open'
RETURNING {_CADENCE_COLUMNS}
""",
(now, note, open_inst["id"], tenant_id),
)
completed_row = cur.fetchone()
if not completed_row:
raise ValueError("Keine offene Cadence-Instanz")
completed = _serialize_row(dict(completed_row))
conn.commit()
finally:
conn.close()
interval = recurring.get("interval_days") or 1
from services.schedule import resolve_schedule_for_recurring
schedule = resolve_schedule_for_recurring(recurring, tenant_id=tenant_id)
next_due = _next_due_at(now=now, interval_days=interval, schedule=schedule)
update_recurring_element(
tenant_id=tenant_id,
recurring_id=recurring_element_id,
user_id=user_id,
next_due_at=next_due,
)
log_audit(
"cadence_instance.completed",
user_id=user_id,
tenant_id=tenant_id,
details={
"cadence_instance_id": completed["id"],
"recurring_id": recurring_element_id,
"measurement_note": note[:200] if note else "",
},
)
updated_recurring = get_recurring_element(
tenant_id=tenant_id, recurring_id=recurring_element_id
)
return {
"completed_instance": completed,
"next_due_at": next_due.isoformat(),
"recurring": updated_recurring,
}
def attach_open_instances_to_recurring_list(
items: list[dict[str, Any]], *, tenant_id: str
) -> list[dict[str, Any]]:
if not items:
return items
ids = [item["id"] for item in items]
now = datetime.now(timezone.utc)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
SELECT {_CADENCE_COLUMNS}
FROM cadence_instances
WHERE tenant_id = %s
AND recurring_element_id = ANY(%s::uuid[])
AND status = 'open'
""",
(tenant_id, ids),
)
by_recurring = {
str(row["recurring_element_id"]): _serialize_row(dict(row))
for row in cur.fetchall()
}
cur.execute(
"""
SELECT DISTINCT ON (recurring_element_id)
recurring_element_id, measurement_note, completed_at
FROM cadence_instances
WHERE tenant_id = %s
AND recurring_element_id = ANY(%s::uuid[])
AND status = 'completed'
AND completed_at >= CURRENT_DATE
ORDER BY recurring_element_id, completed_at DESC
""",
(tenant_id, ids),
)
completed_today = {
str(row["recurring_element_id"]): {
"measurement_note": row.get("measurement_note") or "",
"completed_at": row["completed_at"].isoformat()
if row.get("completed_at")
else None,
}
for row in cur.fetchall()
}
finally:
conn.close()
enriched = []
for item in items:
copy = dict(item)
today = completed_today.get(item["id"])
copy["today_completed"] = today is not None
copy["today_measurement_note"] = today.get("measurement_note", "") if today else ""
open_inst = by_recurring.get(item["id"])
next_due = _parse_due(item.get("next_due_at"))
due_now = next_due is None or next_due <= now
if (
not open_inst
and item.get("status") == "active"
and due_now
and not copy["today_completed"]
):
open_inst = ensure_open_instance(
tenant_id=tenant_id,
recurring_element_id=item["id"],
due_at=next_due or now,
)
copy["open_cadence_instance"] = open_inst
enriched.append(copy)
return enriched
+225
View File
@@ -0,0 +1,225 @@
"""Execution plan — Action dependencies CRUD (AP1.16a/b)."""
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.actions import get_action
DependencyKind = Literal["requires", "blocks", "relates"]
DEPENDENCY_KINDS = frozenset({"requires", "blocks", "relates"})
def _validate_dependency_kind(kind: str) -> None:
if kind not in DEPENDENCY_KINDS:
raise ValueError(f"Ungültiger dependency_kind: {kind}")
def _serialize_dependency(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in (
"id",
"tenant_id",
"initiative_id",
"predecessor_action_id",
"successor_action_id",
):
if result.get(key):
result[key] = str(result[key])
if result.get("created_at"):
result["created_at"] = result["created_at"].isoformat()
return result
def _would_create_cycle(
*,
dependencies: list[dict[str, Any]],
predecessor_id: str,
successor_id: str,
) -> bool:
"""Prüft Zyklus wenn successor transitiv predecessor requires."""
graph: dict[str, list[str]] = {}
for dep in dependencies:
if dep.get("dependency_kind", "requires") != "requires":
continue
pred = str(dep["predecessor_action_id"])
succ = str(dep["successor_action_id"])
graph.setdefault(succ, []).append(pred)
graph.setdefault(successor_id, []).append(predecessor_id)
visiting: set[str] = set()
visited: set[str] = set()
def dfs(node: str) -> bool:
if node in visiting:
return True
if node in visited:
return False
visiting.add(node)
for upstream in graph.get(node, []):
if dfs(upstream):
return True
visiting.remove(node)
visited.add(node)
return False
return dfs(successor_id)
def list_dependencies_for_initiative(
*, tenant_id: str, initiative_id: str
) -> list[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, tenant_id, initiative_id,
predecessor_action_id, successor_action_id,
dependency_kind, created_at
FROM action_dependencies
WHERE tenant_id = %s AND initiative_id = %s
ORDER BY created_at
""",
(tenant_id, initiative_id),
)
return [_serialize_dependency(dict(row)) for row in cur.fetchall()]
finally:
conn.close()
def add_dependency(
*,
tenant_id: str,
predecessor_action_id: str,
successor_action_id: str,
dependency_kind: DependencyKind = "requires",
user_id: Optional[str] = None,
) -> dict[str, Any]:
_validate_dependency_kind(dependency_kind)
if predecessor_action_id == successor_action_id:
raise ValueError("Abhängigkeit auf sich selbst nicht erlaubt")
predecessor = get_action(tenant_id=tenant_id, action_id=predecessor_action_id)
successor = get_action(tenant_id=tenant_id, action_id=successor_action_id)
if not predecessor or not successor:
raise ValueError("Action nicht gefunden")
if predecessor["initiative_id"] != successor["initiative_id"]:
raise ValueError("Abhängigkeiten nur innerhalb eines Vorhabens")
initiative_id = predecessor["initiative_id"]
existing = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if _would_create_cycle(
dependencies=existing,
predecessor_id=predecessor_action_id,
successor_id=successor_action_id,
):
raise ValueError("Abhängigkeit würde Zyklus erzeugen")
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT 1 FROM action_dependencies
WHERE tenant_id = %s
AND predecessor_action_id = %s
AND successor_action_id = %s
AND dependency_kind = %s
""",
(
tenant_id,
predecessor_action_id,
successor_action_id,
dependency_kind,
),
)
if cur.fetchone():
raise ValueError("Abhängigkeit existiert bereits")
cur.execute(
"""
INSERT INTO action_dependencies (
tenant_id, initiative_id,
predecessor_action_id, successor_action_id,
dependency_kind
)
VALUES (%s, %s, %s, %s, %s)
RETURNING id, tenant_id, initiative_id,
predecessor_action_id, successor_action_id,
dependency_kind, created_at
""",
(
tenant_id,
initiative_id,
predecessor_action_id,
successor_action_id,
dependency_kind,
),
)
row = _serialize_dependency(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
log_audit(
"action.dependency_added",
user_id=user_id,
tenant_id=tenant_id,
details={
"predecessor_action_id": predecessor_action_id,
"successor_action_id": successor_action_id,
"dependency_kind": dependency_kind,
},
)
return row
def delete_dependency(
*, tenant_id: str, dependency_id: str, user_id: Optional[str] = None
) -> bool:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, predecessor_action_id, successor_action_id, dependency_kind
FROM action_dependencies
WHERE id = %s AND tenant_id = %s
""",
(dependency_id, tenant_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Abhängigkeit nicht gefunden")
cur.execute(
"""
DELETE FROM action_dependencies
WHERE id = %s AND tenant_id = %s
""",
(dependency_id, tenant_id),
)
conn.commit()
finally:
conn.close()
log_audit(
"action.dependency_removed",
user_id=user_id,
tenant_id=tenant_id,
details={
"dependency_id": dependency_id,
"predecessor_action_id": str(row["predecessor_action_id"]),
"successor_action_id": str(row["successor_action_id"]),
},
)
return True
+158 -16
View File
@@ -7,6 +7,7 @@ from typing import Any, Literal, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from entity_archetypes import validate_archetype_key
from services.audit import log_audit
InitiativeStatus = Literal["active", "paused", "completed", "archived"]
@@ -15,6 +16,11 @@ Priority = Literal["low", "normal", "high"]
INITIATIVE_STATUSES = frozenset({"active", "paused", "completed", "archived"})
PRIORITIES = frozenset({"low", "normal", "high"})
_INITIATIVE_COLUMNS = """
id, tenant_id, title, goal, vision, target_state_summary, archetype_key,
status, priority, portfolio_rank, owner_actor_id, created_at, updated_at
"""
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
@@ -51,21 +57,31 @@ def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
conn.close()
def _validate_archetype_key(archetype_key: str) -> None:
validate_archetype_key(entity_type="initiative", archetype_key=archetype_key)
def create_initiative(
*,
tenant_id: str,
title: str,
owner_actor_id: str,
goal: str = "",
vision: str = "",
target_state_summary: str = "",
archetype_key: str = "initiative.generic",
status: InitiativeStatus = "active",
priority: Priority = "normal",
user_id: Optional[str] = None,
method_profile_key: Optional[str] = None,
apply_starter_kit: bool = True,
) -> dict[str, Any]:
title = title.strip()
if not title:
raise ValueError("Titel ist erforderlich")
_validate_initiative_status(status)
_validate_priority(priority)
_validate_archetype_key(archetype_key)
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=owner_actor_id):
raise ValueError("Owner-Actor gehört nicht zum Tenant")
@@ -74,14 +90,34 @@ def create_initiative(
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
SELECT COALESCE(MAX(portfolio_rank), -1) + 1 AS next_rank
FROM initiatives
WHERE tenant_id = %s
""",
(tenant_id, title, goal, status, priority, owner_actor_id),
(tenant_id,),
)
next_rank = int(cur.fetchone()["next_rank"])
cur.execute(
f"""
INSERT INTO initiatives (
tenant_id, title, goal, vision, target_state_summary, archetype_key,
status, priority, portfolio_rank, owner_actor_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_INITIATIVE_COLUMNS}
""",
(
tenant_id,
title,
goal,
vision,
target_state_summary,
archetype_key,
status,
priority,
next_rank,
owner_actor_id,
),
)
row = _serialize_row(dict(cur.fetchone()))
conn.commit()
@@ -100,7 +136,20 @@ def create_initiative(
tenant_id=tenant_id,
initiative_id=row["id"],
user_id=user_id,
archetype_key=archetype_key,
method_profile_key=method_profile_key,
)
if apply_starter_kit:
from services.archetype_starter_kit import apply_starter_kit
starter = apply_starter_kit(
tenant_id=tenant_id,
initiative_id=row["id"],
archetype_key=archetype_key,
owner_actor_id=owner_actor_id,
user_id=user_id,
)
row["starter_kit"] = starter
return row
@@ -109,12 +158,11 @@ def list_initiatives(*, tenant_id: str) -> list[dict[str, Any]]:
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
f"""
SELECT {_INITIATIVE_COLUMNS}
FROM initiatives
WHERE tenant_id = %s
ORDER BY updated_at DESC, title
ORDER BY portfolio_rank ASC NULLS LAST, updated_at DESC, title
""",
(tenant_id,),
)
@@ -128,9 +176,8 @@ def get_initiative(*, tenant_id: str, initiative_id: str) -> Optional[dict[str,
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
f"""
SELECT {_INITIATIVE_COLUMNS}
FROM initiatives
WHERE id = %s AND tenant_id = %s
""",
@@ -149,6 +196,9 @@ def update_initiative(
user_id: Optional[str] = None,
title: Optional[str] = None,
goal: Optional[str] = None,
vision: Optional[str] = None,
target_state_summary: Optional[str] = None,
archetype_key: Optional[str] = None,
status: Optional[InitiativeStatus] = None,
priority: Optional[Priority] = None,
owner_actor_id: Optional[str] = None,
@@ -170,6 +220,16 @@ def update_initiative(
if goal is not None:
updates.append("goal = %s")
params.append(goal)
if vision is not None:
updates.append("vision = %s")
params.append(vision)
if target_state_summary is not None:
updates.append("target_state_summary = %s")
params.append(target_state_summary)
if archetype_key is not None:
_validate_archetype_key(archetype_key)
updates.append("archetype_key = %s")
params.append(archetype_key)
if status is not None:
_validate_initiative_status(status)
updates.append("status = %s")
@@ -198,8 +258,7 @@ def update_initiative(
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
RETURNING {_INITIATIVE_COLUMNS}
""",
params,
)
@@ -257,3 +316,86 @@ def delete_initiative(
details={"initiative_id": initiative_id},
)
return deleted
def load_portfolio_rank_map(*, tenant_id: str) -> dict[str, Optional[int]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, portfolio_rank
FROM initiatives
WHERE tenant_id = %s
""",
(tenant_id,),
)
return {
str(row["id"]): row["portfolio_rank"]
for row in cur.fetchall()
}
finally:
conn.close()
def reorder_portfolio(
*,
tenant_id: str,
initiative_ids: list[str],
user_id: Optional[str] = None,
) -> list[dict[str, Any]]:
"""Setzt portfolio_rank für alle übergebenen Initiativen (0 = höchste Prio)."""
if not initiative_ids:
raise ValueError("initiative_ids darf nicht leer sein")
unique_ids = list(dict.fromkeys(initiative_ids))
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id
FROM initiatives
WHERE tenant_id = %s
ORDER BY portfolio_rank ASC NULLS LAST, updated_at DESC, title
""",
(tenant_id,),
)
all_ids = [str(row["id"]) for row in cur.fetchall()]
all_set = set(all_ids)
if set(unique_ids) - all_set:
raise ValueError("Unbekannte Initiative im Tenant")
if len(unique_ids) != len(all_ids):
raise ValueError("Alle Initiativen des Tenants müssen enthalten sein")
for rank, initiative_id in enumerate(unique_ids):
cur.execute(
"""
UPDATE initiatives
SET portfolio_rank = %s, updated_at = NOW()
WHERE id = %s AND tenant_id = %s
""",
(rank, initiative_id, tenant_id),
)
cur.execute(
f"""
SELECT {_INITIATIVE_COLUMNS}
FROM initiatives
WHERE tenant_id = %s
ORDER BY portfolio_rank ASC NULLS LAST, updated_at DESC, title
""",
(tenant_id,),
)
rows = [_serialize_row(dict(row)) for row in cur.fetchall()]
conn.commit()
finally:
conn.close()
log_audit(
"portfolio.reordered",
user_id=user_id,
tenant_id=tenant_id,
details={"initiative_ids": unique_ids},
)
return rows
+248
View File
@@ -0,0 +1,248 @@
"""A1 — Stage-bound practice exercises (Activity Set)."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Optional
from services.recurring import (
list_recurring_for_initiative,
update_recurring_element,
)
# Starter exercise sets per stage title (Spagat reference path).
STAGE_PRACTICE_SETS: dict[str, list[tuple[str, str]]] = {
"Stufe 1 — Basis": [
("Vorbeuge-Dehnung", "3×30 Sek. — Hüfte und Beinrückseite"),
("Hüftöffner (Schmetterling)", "Sitzend, leichter Druck"),
],
"Stufe 2 — Aufbau": [
("Seitlicher Spagat — links", "Halten, optional Messwert (Grad)"),
("Seitlicher Spagat — rechts", "Halten, optional Messwert (Grad)"),
("Aktive Vorbeuge", "3× kurz halten"),
],
"Stufe 3 — Ziel": [
("Voller Spagat", "Zielposition — Messwert dokumentieren"),
],
"Dehnung — Einstieg": [
("Vorbeuge halten", "3×30 Sek."),
],
"Hüftrotation — Einstieg": [
("Hüftkreisen im Stand", "10 Wiederholungen je Richtung"),
],
"Dehnung — nach Join": [
("Enddehnung Mawashi-Vorbereitung", "2×45 Sek."),
],
"Hüftrotation — nach Join": [
("Explosive Hüftrotation", "3×8 Wiederholungen"),
],
}
def get_active_maturity_stages(
*, tenant_id: str, initiative_id: str
) -> list[dict[str, Any]]:
from services.roadmap import list_roadmap_items_for_initiative
stages = [
item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if item.get("item_type") == "maturity_stage" and item.get("status") == "active"
]
stages.sort(key=lambda s: (s.get("sort_order", 0), s.get("title", "")))
return stages
def get_active_maturity_stage(
*, tenant_id: str, initiative_id: str
) -> Optional[dict[str, Any]]:
stages = get_active_maturity_stages(
tenant_id=tenant_id, initiative_id=initiative_id
)
return stages[0] if stages else None
def list_practices_for_stage(
*,
tenant_id: str,
initiative_id: str,
stage_id: str,
) -> list[dict[str, Any]]:
items = list_recurring_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
return [
item
for item in items
if item.get("roadmap_item_id") == stage_id
]
def pause_all_practices(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str] = None,
) -> list[str]:
paused: list[str] = []
for item in list_recurring_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
):
if item.get("status") == "active":
update_recurring_element(
tenant_id=tenant_id,
recurring_id=item["id"],
status="paused",
user_id=user_id,
)
paused.append(item["title"])
return paused
def pause_practices_on_same_lane_except_stage(
*,
tenant_id: str,
initiative_id: str,
keep_stage_id: str,
user_id: Optional[str] = None,
) -> list[str]:
from services.progression_graph import progression_lanes_for_initiative
lanes = progression_lanes_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
keep_lane = lanes.get(str(keep_stage_id))
if not keep_lane:
return pause_all_practices(
tenant_id=tenant_id, initiative_id=initiative_id, user_id=user_id
)
lane_gate_ids = {
gate_id for gate_id, lane in lanes.items() if lane == keep_lane
}
paused: list[str] = []
for item in list_recurring_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
):
if item.get("status") != "active":
continue
if item.get("roadmap_item_id") == keep_stage_id:
continue
if str(item.get("roadmap_item_id") or "") not in lane_gate_ids:
continue
update_recurring_element(
tenant_id=tenant_id,
recurring_id=item["id"],
status="paused",
user_id=user_id,
)
paused.append(item["title"])
return paused
def pause_practices_except_stage(
*,
tenant_id: str,
initiative_id: str,
keep_stage_id: str,
strand_project_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> list[str]:
del strand_project_id
return pause_practices_on_same_lane_except_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
keep_stage_id=keep_stage_id,
user_id=user_id,
)
def seed_practices_for_stage(
*,
tenant_id: str,
initiative_id: str,
stage: dict[str, Any],
user_id: Optional[str] = None,
) -> list[dict[str, Any]]:
"""Idempotent: create missing exercises for a stage; activate existing."""
stage_id = stage["id"]
stage_title = stage.get("title") or ""
defs = STAGE_PRACTICE_SETS.get(stage_title)
if not defs:
defs = [
(
f"Übung — {stage_title}",
f"Routine für {stage_title}",
)
]
existing = list_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage_id=stage_id,
)
existing_by_title = {item["title"]: item for item in existing}
created: list[dict[str, Any]] = []
now = datetime.now(timezone.utc)
from services.scheduled_work import create_scheduled_action_at_gate
for title, description in defs:
if title in existing_by_title:
item = existing_by_title[title]
if item.get("status") != "active":
updated = update_recurring_element(
tenant_id=tenant_id,
recurring_id=item["id"],
status="active",
next_due_at=now,
user_id=user_id,
)
if updated:
created.append(updated)
else:
created.append(item)
continue
row = create_scheduled_action_at_gate(
tenant_id=tenant_id,
initiative_id=initiative_id,
gate_id=stage_id,
title=title,
description=description,
user_id=user_id,
schedule_kind="weekdays",
)
created.append(row)
return created
def activate_stage_practice_set(
*,
tenant_id: str,
initiative_id: str,
stage: dict[str, Any],
user_id: Optional[str] = None,
) -> dict[str, Any]:
paused = pause_practices_on_same_lane_except_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
keep_stage_id=stage["id"],
user_id=user_id,
)
exercises = seed_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage=stage,
user_id=user_id,
)
return {
"stage_id": stage["id"],
"stage_title": stage.get("title"),
"paused_practices": paused,
"active_practices": [e["title"] for e in exercises],
"practice_ids": [e["id"] for e in exercises],
}
@@ -0,0 +1,44 @@
"""AP2.0e — maturity stage transition on verify reached (delegates to progression_graph)."""
from __future__ import annotations
from typing import Any, Optional
def on_maturity_stage_reached(
*,
tenant_id: str,
initiative_id: str,
reached_item_id: str,
user_id: Optional[str] = None,
) -> Optional[dict[str, Any]]:
from services.progression_graph import on_work_gate_reached
return on_work_gate_reached(
tenant_id=tenant_id,
initiative_id=initiative_id,
reached_item_id=reached_item_id,
user_id=user_id,
)
def on_maturity_stage_reopened(
*,
tenant_id: str,
initiative_id: str,
stage_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
"""Re-enable exercise set for reopened stage; pause others on same strand."""
from services.maturity_practice import activate_stage_practice_set
from services.roadmap import get_roadmap_item
stage = get_roadmap_item(tenant_id=tenant_id, item_id=stage_id)
if not stage:
return {"stage_id": stage_id, "active_practices": []}
return activate_stage_practice_set(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage=stage,
user_id=user_id,
)
+248
View File
@@ -0,0 +1,248 @@
"""Operating Context read model — AP2.3a / AP2.4."""
from __future__ import annotations
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from entity_archetypes.registry import (
get_ui_profile_json,
resolve_default_method_key,
resolve_ui_profile,
)
from services.initiatives import get_initiative
from services.steering_context import ensure_steering_context, get_steering_context
from steering.graph.profiles import LIGHT, graph_profile_as_dict
from steering.backlog_vocabulary import resolve_backlog_vocabulary
from steering.effective_contract import resolve_effective_steering_elements
from steering.methods.registry import (
get_method,
list_compatible_methods,
list_composable_modifiers,
method_to_dict,
ui_features_as_dict,
)
def _load_ui_profile_from_db(archetype_key: str) -> Optional[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT ui_profile_json
FROM entity_archetypes
WHERE archetype_key = %s
""",
(archetype_key,),
)
row = cur.fetchone()
if not row:
return None
profile = row.get("ui_profile_json")
if isinstance(profile, dict) and profile:
return dict(profile)
return None
finally:
conn.close()
def _seed_ui_profile(archetype_key: str) -> dict[str, Any]:
seed_profile = get_ui_profile_json(archetype_key)
if seed_profile:
return seed_profile
return resolve_ui_profile(archetype_key)
def _normalize_ui_profile_capabilities(profile: dict[str, Any]) -> dict[str, Any]:
"""Spiegelt resolve_ui_profile: omCapabilities aus dataSlices falls fehlend."""
result = dict(profile)
slices = list(result.get("dataSlices") or [])
caps = list(result.get("omCapabilities") or slices)
result["dataSlices"] = slices
result["omCapabilities"] = caps
return result
def _resolve_ui_profile(archetype_key: str) -> dict[str, Any]:
seed_profile = _seed_ui_profile(archetype_key)
db_profile = _load_ui_profile_from_db(archetype_key)
if not db_profile:
return _normalize_ui_profile_capabilities(seed_profile)
merged = {**seed_profile, **db_profile}
if not (merged.get("omCapabilities") or merged.get("dataSlices")):
seed_slices = seed_profile.get("dataSlices") or []
merged["dataSlices"] = list(seed_slices)
return _normalize_ui_profile_capabilities(merged)
def _resolve_om_capabilities(ui_profile: dict[str, Any]) -> frozenset[str]:
caps = ui_profile.get("omCapabilities") or ui_profile.get("dataSlices") or []
return frozenset(caps)
def _resolve_data_slices(
*,
om_capabilities: frozenset[str],
method_key: str,
) -> list[str]:
"""Schnittmenge Archetyp-OM ∩ Method-Slices."""
method = get_method(method_key)
if method and method.data_slices:
method_slices = set(method.data_slices)
return [s for s in om_capabilities if s in method_slices]
return list(om_capabilities)
def _method_capabilities(method_key: str) -> dict[str, Any]:
method = get_method(method_key)
if not method:
return {
"lifecycle_steps": [],
"next_action_strategy_key": "default",
}
return {
"lifecycle_steps": list(method.default_lifecycle_steps),
"next_action_strategy_key": method.next_action_strategy_key,
}
def _resolve_method_contract(method_key: str) -> dict[str, Any]:
method = get_method(method_key)
if not method:
return {
"steering_elements": [],
"ui_features": {},
"graph_profile": graph_profile_as_dict(LIGHT),
}
return {
"steering_elements": sorted(method.steering_elements),
"ui_features": ui_features_as_dict(method.ui_features),
"graph_profile": graph_profile_as_dict(method.graph_profile),
}
def _compatible_methods_payload(
archetype_key: str,
*,
om_capabilities: frozenset[str],
active_method_key: str,
) -> list[dict[str, Any]]:
default_key = resolve_default_method_key(archetype_key)
methods = list_compatible_methods(
archetype_key, om_capabilities=om_capabilities
)
return [
{
**method_to_dict(m, include_compatibility=False),
"is_default": m.key == default_key,
"is_active": m.key == active_method_key,
}
for m in methods
]
def _resolve_agent_slot_config(metadata: dict[str, Any]) -> dict[str, Any]:
"""Governance-Konfiguration für Agent-Slots — keine Prompts."""
defaults: dict[str, Any] = {
"enabled_slots": ["review.due", "recurring.due", "review.guardrail"],
"guardrail_pack": "default_v0",
"stale_debt_days": 30,
}
custom = metadata.get("agent_slots") or metadata.get("agent_slot_config") or {}
if isinstance(custom, dict):
return {**defaults, **custom}
return defaults
def get_operating_context(
*, tenant_id: str, initiative_id: str
) -> Optional[dict[str, Any]]:
initiative = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not initiative:
return None
steering = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
if not steering:
steering = ensure_steering_context(
tenant_id=tenant_id, initiative_id=initiative_id
)
archetype_key = initiative["archetype_key"]
ui_profile = _resolve_ui_profile(archetype_key)
om_capabilities = _resolve_om_capabilities(ui_profile)
method_key = steering["method_key"]
metadata = steering.get("lifecycle_metadata") or {}
if isinstance(metadata, str):
metadata = {}
method_profile_key = metadata.get("method_profile_key")
data_slices = _resolve_data_slices(
om_capabilities=om_capabilities,
method_key=method_key,
)
method_contract = _resolve_method_contract(method_key)
active_composition_modifier = (
"agile_iteration"
if _resolve_active_agile_composition(
tenant_id=tenant_id,
initiative_id=initiative_id,
primary_method_key=method_key,
)
else None
)
effective_steering_elements = resolve_effective_steering_elements(
method_key,
data_slices=data_slices,
active_composition_modifier=active_composition_modifier,
)
backlog_vocabulary = resolve_backlog_vocabulary(
data_slices=data_slices,
method_key=method_key,
steering_elements=effective_steering_elements,
)
agent_slot_config = _resolve_agent_slot_config(metadata)
return {
"initiative_id": initiative_id,
"archetype_key": archetype_key,
"method_key": method_key,
"method_profile_key": method_profile_key,
"ui_profile": ui_profile,
"om_capabilities": sorted(om_capabilities),
"data_slices": data_slices,
"method_capabilities": _method_capabilities(method_key),
"steering_elements": sorted(effective_steering_elements),
"primary_steering_elements": method_contract["steering_elements"],
"ui_features": method_contract["ui_features"],
"graph_profile": method_contract["graph_profile"],
"compatible_methods": _compatible_methods_payload(
archetype_key,
om_capabilities=om_capabilities,
active_method_key=method_key,
),
"composable_modifiers": [
method_to_dict(m, include_compatibility=False)
for m in list_composable_modifiers(method_key)
],
"active_composition_modifier": active_composition_modifier,
"backlog_vocabulary": backlog_vocabulary,
"agent_slot_config": agent_slot_config,
}
def _resolve_active_agile_composition(
*,
tenant_id: str,
initiative_id: str,
primary_method_key: str,
) -> bool:
from services.work_cycle import get_active_work_cycle
from steering.methods.registry import get_method
agile = get_method("agile_iteration")
if not agile or primary_method_key not in agile.composes_with:
return False
return get_active_work_cycle(tenant_id=tenant_id, initiative_id=initiative_id) is not None
+5 -6
View File
@@ -99,14 +99,13 @@ def after_blocker_status_change(
user_id=user_id,
)
if initiative_id and user_id:
from steering.lifecycle.orchestrator import transition
from services.steering_events import emit_steering_event
transition(
None,
initiative_id,
"action_selection",
reason="blocker_resolved",
emit_steering_event(
tenant_id=tenant_id,
initiative_id=initiative_id,
event_kind="situational",
payload={"reason": "blocker_resolved", "blocker_id": blocker_id},
user_id=user_id,
)
+653
View File
@@ -0,0 +1,653 @@
"""A1 progression graph — multi-strand work gates, join switch nodes (PO-Lock §10)."""
from __future__ import annotations
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
WORK_GATE_TYPES = frozenset({"maturity_stage"})
JOIN_GATE_TYPE = "join_gate"
ACTIVE_WORK_STATUSES = frozenset({"active", "at_risk"})
TERMINAL_STATUSES = frozenset({"reached", "moved", "discarded"})
def is_work_gate(item: dict[str, Any]) -> bool:
return item.get("item_type") in WORK_GATE_TYPES
def is_join_gate(item: dict[str, Any]) -> bool:
return item.get("item_type") == JOIN_GATE_TYPE
def _requires_deps(dependencies: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [
dep
for dep in dependencies
if (dep.get("dependency_type") or "requires") == "requires"
]
def join_input_gate_ids(
join_id: str, dependencies: list[dict[str, Any]]
) -> list[str]:
"""Join requires input gates (from=join, to=input)."""
return [
str(dep["to_item_id"])
for dep in _requires_deps(dependencies)
if str(dep["from_item_id"]) == str(join_id)
]
def join_output_gate_ids(
join_id: str, dependencies: list[dict[str, Any]]
) -> list[str]:
"""Output gates require join (from=output, to=join)."""
return [
str(dep["from_item_id"])
for dep in _requires_deps(dependencies)
if str(dep["to_item_id"]) == str(join_id)
]
def successor_work_gate_ids(
gate_id: str, dependencies: list[dict[str, Any]]
) -> list[str]:
"""Work gates that require this gate (from=successor, to=gate)."""
return [
str(dep["from_item_id"])
for dep in _requires_deps(dependencies)
if str(dep["to_item_id"]) == str(gate_id)
]
def _work_gate_predecessor_ids(
gate_id: str,
*,
work_gate_ids: frozenset[str],
join_gate_ids: frozenset[str],
dependencies: list[dict[str, Any]],
) -> list[str]:
"""Direct requires predecessors that are work gates or join gates."""
preds: list[str] = []
for dep in _requires_deps(dependencies):
if str(dep["from_item_id"]) != str(gate_id):
continue
pred_id = str(dep["to_item_id"])
if pred_id in work_gate_ids or pred_id in join_gate_ids:
preds.append(pred_id)
return preds
def compute_progression_lanes(
*,
items: list[dict[str, Any]],
dependencies: list[dict[str, Any]],
) -> dict[str, str]:
"""
Graph-derived progression lane per work gate (not persisted).
Parallel active gates live on different lanes. Sequential gates on the same
requires-chain share a lane. First gate after a join starts a new lane.
"""
item_by_id = {str(item["id"]): item for item in items}
work_gate_ids = frozenset(
str(item["id"]) for item in items if is_work_gate(item)
)
join_gate_ids = frozenset(
str(item["id"]) for item in items if is_join_gate(item)
)
work_pred: dict[str, Optional[str]] = {}
for gate_id in work_gate_ids:
work_preds = [
pred_id
for pred_id in _work_gate_predecessor_ids(
gate_id,
work_gate_ids=work_gate_ids,
join_gate_ids=join_gate_ids,
dependencies=dependencies,
)
if pred_id in work_gate_ids
]
work_pred[gate_id] = work_preds[0] if len(work_preds) == 1 else None
lanes: dict[str, str] = {}
def resolve_lane(gate_id: str) -> str:
cached = lanes.get(gate_id)
if cached:
return cached
pred = work_pred.get(gate_id)
if pred:
lanes[gate_id] = resolve_lane(pred)
return lanes[gate_id]
join_preds = [
pred_id
for pred_id in _work_gate_predecessor_ids(
gate_id,
work_gate_ids=work_gate_ids,
join_gate_ids=join_gate_ids,
dependencies=dependencies,
)
if pred_id in join_gate_ids
]
if join_preds:
lanes[gate_id] = f"post-join:{gate_id}"
return lanes[gate_id]
lanes[gate_id] = f"source:{gate_id}"
return lanes[gate_id]
for gate_id in work_gate_ids:
resolve_lane(gate_id)
return lanes
def progression_lanes_for_initiative(
*, tenant_id: str, initiative_id: str
) -> dict[str, str]:
from services.roadmap import list_dependencies_for_initiative, list_roadmap_items_for_initiative
items = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
return compute_progression_lanes(items=items, dependencies=dependencies)
def list_active_work_gates(
*, tenant_id: str, initiative_id: str
) -> list[dict[str, Any]]:
from services.roadmap import list_roadmap_items_for_initiative
items = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
active = [
item
for item in items
if is_work_gate(item) and item.get("status") in ACTIVE_WORK_STATUSES
]
active.sort(key=lambda item: (item.get("sort_order", 0), item.get("title", "")))
return active
def compute_join_states(
*,
tenant_id: str,
initiative_id: str,
) -> list[dict[str, Any]]:
from services.roadmap import list_dependencies_for_initiative, list_roadmap_items_for_initiative
items = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
item_by_id = {str(item["id"]): item for item in items}
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
joins = [item for item in items if is_join_gate(item)]
states: list[dict[str, Any]] = []
for join in joins:
join_id = str(join["id"])
input_ids = join_input_gate_ids(join_id, dependencies)
output_ids = join_output_gate_ids(join_id, dependencies)
pending: list[dict[str, Any]] = []
for input_id in input_ids:
gate = item_by_id.get(input_id)
if not gate:
continue
if gate.get("status") != "reached":
pending.append(
{
"gate_id": input_id,
"title": gate.get("title") or input_id,
"status": gate.get("status"),
}
)
states.append(
{
"join_id": join_id,
"title": join.get("title") or "",
"status": join.get("status"),
"ready_to_switch": len(pending) == 0 and join.get("status") not in TERMINAL_STATUSES,
"pending_inputs": pending,
"output_gate_ids": output_ids,
"outputs": [
{
"gate_id": output_id,
"title": (item_by_id.get(output_id) or {}).get("title") or output_id,
}
for output_id in output_ids
if output_id in item_by_id
],
}
)
return states
def compute_progression_state(
*, tenant_id: str, initiative_id: str
) -> dict[str, Any]:
active_gates = list_active_work_gates(
tenant_id=tenant_id, initiative_id=initiative_id
)
return {
"active_work_gates": [
{
"id": gate["id"],
"title": gate.get("title"),
"status": gate.get("status"),
}
for gate in active_gates
],
"joins": compute_join_states(
tenant_id=tenant_id, initiative_id=initiative_id
),
}
def enforce_single_active_work_gate_per_lane(
cur,
*,
tenant_id: str,
initiative_id: str,
keep_active_id: str,
) -> None:
"""Revoke other active work gates on the same graph-derived progression lane."""
from services.roadmap import list_dependencies_for_initiative, list_roadmap_items_for_initiative
items = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
lanes = compute_progression_lanes(items=items, dependencies=dependencies)
keep_lane = lanes.get(str(keep_active_id))
if not keep_lane:
return
revoke_ids = [
gate_id
for gate_id, lane in lanes.items()
if lane == keep_lane and gate_id != str(keep_active_id)
]
if not revoke_ids:
return
cur.execute(
"""
UPDATE roadmap_items ri
SET status = 'planned', updated_at = NOW()
FROM roadmaps r
WHERE ri.roadmap_id = r.id
AND ri.tenant_id = %s
AND r.initiative_id = %s
AND ri.item_type = 'maturity_stage'
AND ri.status IN ('active', 'at_risk')
AND ri.id = ANY(%s::uuid[])
""",
(tenant_id, initiative_id, revoke_ids),
)
def enforce_single_active_work_gate_per_strand(
cur,
*,
tenant_id: str,
initiative_id: str,
keep_active_id: str,
strand_project_id: Optional[str] = None,
) -> None:
"""Deprecated — graph lanes replace strand/project grouping (ADP A1 lanes v0.1)."""
del strand_project_id
enforce_single_active_work_gate_per_lane(
cur,
tenant_id=tenant_id,
initiative_id=initiative_id,
keep_active_id=keep_active_id,
)
def _graph_ready(
item_id: str,
*,
item_by_id: dict[str, dict[str, Any]],
dependencies: list[dict[str, Any]],
) -> bool:
for dep in _requires_deps(dependencies):
if str(dep["from_item_id"]) != str(item_id):
continue
prereq = item_by_id.get(str(dep["to_item_id"]))
if not prereq:
continue
if prereq.get("status") != "reached":
return False
return True
def activate_work_gate(
*,
tenant_id: str,
initiative_id: str,
gate: dict[str, Any],
user_id: Optional[str] = None,
seed_practices: bool = True,
) -> dict[str, Any]:
from services.maturity_practice import activate_stage_practice_set
from services.roadmap import get_roadmap_item, update_roadmap_item
gate_id = gate["id"]
updated = update_roadmap_item(
tenant_id=tenant_id,
item_id=gate_id,
status="active",
user_id=user_id,
)
if not updated:
raise ValueError("Work-Gate konnte nicht aktiviert werden")
practice_result = None
if seed_practices:
fresh = get_roadmap_item(tenant_id=tenant_id, item_id=gate_id) or updated
practice_result = activate_stage_practice_set(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage=fresh,
user_id=user_id,
)
return {
"gate_id": gate_id,
"gate_title": updated.get("title"),
"practice_transition": practice_result,
}
def _mark_join_reached(
cur,
*,
tenant_id: str,
join_id: str,
) -> None:
cur.execute(
"""
UPDATE roadmap_items
SET status = 'reached', updated_at = NOW()
WHERE id = %s AND tenant_id = %s AND item_type = 'join_gate'
""",
(join_id, tenant_id),
)
def try_switch_join(
*,
tenant_id: str,
initiative_id: str,
join_id: str,
user_id: Optional[str] = None,
) -> Optional[dict[str, Any]]:
from services.audit import log_audit
from services.roadmap import get_roadmap_item, list_dependencies_for_initiative
join = get_roadmap_item(tenant_id=tenant_id, item_id=join_id)
if not join or not is_join_gate(join):
return None
if join.get("status") in TERMINAL_STATUSES:
return None
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
item_by_id = {
str(item["id"]): item
for item in __import__(
"services.roadmap", fromlist=["list_roadmap_items_for_initiative"]
).list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
}
pending = [
input_id
for input_id in join_input_gate_ids(join_id, dependencies)
if item_by_id.get(input_id, {}).get("status") != "reached"
]
if pending:
return None
output_ids = join_output_gate_ids(join_id, dependencies)
activated: list[dict[str, Any]] = []
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
_mark_join_reached(cur, tenant_id=tenant_id, join_id=join_id)
conn.commit()
finally:
conn.close()
join_id_str = str(join_id)
if join_id_str in item_by_id:
item_by_id[join_id_str] = {**item_by_id[join_id_str], "status": "reached"}
for output_id in output_ids:
output_gate = item_by_id.get(output_id)
if not output_gate or not is_work_gate(output_gate):
continue
if output_gate.get("status") in TERMINAL_STATUSES:
continue
if not _graph_ready(output_id, item_by_id=item_by_id, dependencies=dependencies):
continue
activated.append(
activate_work_gate(
tenant_id=tenant_id,
initiative_id=initiative_id,
gate=output_gate,
user_id=user_id,
)
)
log_audit(
"progression.join_switched",
user_id=user_id,
tenant_id=tenant_id,
details={
"initiative_id": initiative_id,
"join_id": join_id,
"join_title": join.get("title"),
"activated_gate_ids": [item["gate_id"] for item in activated],
},
)
return {
"join_id": join_id,
"join_title": join.get("title"),
"activated": activated,
}
def try_switch_joins_for_gate(
*,
tenant_id: str,
initiative_id: str,
gate_id: str,
user_id: Optional[str] = None,
) -> list[dict[str, Any]]:
from services.roadmap import list_dependencies_for_initiative, list_roadmap_items_for_initiative
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
joins = [
item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if is_join_gate(item)
]
switched: list[dict[str, Any]] = []
for join in joins:
join_id = str(join["id"])
inputs = join_input_gate_ids(join_id, dependencies)
if gate_id not in inputs:
continue
result = try_switch_join(
tenant_id=tenant_id,
initiative_id=initiative_id,
join_id=join_id,
user_id=user_id,
)
if result:
switched.append(result)
return switched
def _legacy_linear_next_stage(
*,
tenant_id: str,
initiative_id: str,
reached_item_id: str,
user_id: Optional[str] = None,
) -> Optional[dict[str, Any]]:
from services.roadmap import get_roadmap_item, list_roadmap_items_for_initiative, update_roadmap_item
stages = [
item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if is_work_gate(item)
]
stages.sort(key=lambda item: (item.get("sort_order", 0), item.get("title", "")))
reached_index = next(
(index for index, stage in enumerate(stages) if stage["id"] == reached_item_id),
None,
)
if reached_index is None:
return None
next_stage = None
for stage in stages[reached_index + 1 :]:
if stage.get("status") in {"planned", "active", "at_risk"}:
next_stage = stage
break
if not next_stage:
return None
update_roadmap_item(
tenant_id=tenant_id,
item_id=next_stage["id"],
status="active",
user_id=user_id,
)
fresh = get_roadmap_item(tenant_id=tenant_id, item_id=next_stage["id"])
if not fresh:
return None
return activate_work_gate(
tenant_id=tenant_id,
initiative_id=initiative_id,
gate=fresh,
user_id=user_id,
)
def on_work_gate_reached(
*,
tenant_id: str,
initiative_id: str,
reached_item_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
from services.maturity_practice import list_practices_for_stage, update_recurring_element
from services.roadmap import get_roadmap_item, list_dependencies_for_initiative, list_roadmap_items_for_initiative
reached = get_roadmap_item(tenant_id=tenant_id, item_id=reached_item_id)
if not reached or not is_work_gate(reached):
return {"reached_gate_id": reached_item_id}
for practice in list_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage_id=reached_item_id,
):
if practice.get("status") == "active":
update_recurring_element(
tenant_id=tenant_id,
recurring_id=practice["id"],
status="paused",
user_id=user_id,
)
dependencies = list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
has_progression_deps = any(
(dep.get("dependency_type") or "requires") == "requires"
for dep in dependencies
if str(dep["from_item_id"]) in {
str(reached_item_id),
*(str(item["id"]) for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
) if is_join_gate(item)),
}
or str(dep["to_item_id"]) == str(reached_item_id)
)
joined = try_switch_joins_for_gate(
tenant_id=tenant_id,
initiative_id=initiative_id,
gate_id=reached_item_id,
user_id=user_id,
)
activated_successors: list[dict[str, Any]] = []
if not joined:
item_by_id = {
str(item["id"]): item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
}
for successor_id in successor_work_gate_ids(reached_item_id, dependencies):
successor = item_by_id.get(successor_id)
if not successor or not is_work_gate(successor):
continue
if is_join_gate(successor):
continue
if successor.get("status") in TERMINAL_STATUSES:
continue
if not _graph_ready(
successor_id, item_by_id=item_by_id, dependencies=dependencies
):
continue
activated_successors.append(
activate_work_gate(
tenant_id=tenant_id,
initiative_id=initiative_id,
gate=successor,
user_id=user_id,
)
)
legacy = None
if not joined and not activated_successors and not has_progression_deps:
legacy = _legacy_linear_next_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
reached_item_id=reached_item_id,
user_id=user_id,
)
return {
"reached_gate_id": reached_item_id,
"joins_switched": joined,
"successors_activated": activated_successors,
"legacy_linear": legacy,
}
+13 -4
View File
@@ -9,6 +9,7 @@ from psycopg2.extras import RealDictCursor
from db import get_connection
from services.audit import log_audit
from entity_archetypes import mirror_project_archetype_key, validate_archetype_key
from services.initiatives import get_initiative
ProjectStatus = Literal["active", "paused", "completed", "archived"]
@@ -21,7 +22,7 @@ MAX_PROJECT_DEPTH = 5
_PROJECT_COLUMNS = """
id, tenant_id, initiative_id, parent_project_id, container_kind,
title, description, status,
archetype_key, title, description, status,
roadmap_item_id, sort_order, target_date, created_at, updated_at
"""
@@ -227,6 +228,7 @@ def create_project(
roadmap_item_id: Optional[str] = None,
sort_order: int = 0,
target_date: Optional[date] = None,
archetype_key: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
title = title.strip()
@@ -234,9 +236,15 @@ def create_project(
raise ValueError("Titel ist erforderlich")
_validate_status(status)
_validate_container_kind(container_kind)
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
initiative = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not initiative:
raise ValueError("Initiative nicht gefunden")
resolved_archetype = archetype_key or mirror_project_archetype_key(
initiative["archetype_key"]
)
validate_archetype_key(entity_type="project", archetype_key=resolved_archetype)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
@@ -257,10 +265,10 @@ def create_project(
f"""
INSERT INTO projects (
tenant_id, initiative_id, parent_project_id, container_kind,
title, description, status,
archetype_key, title, description, status,
roadmap_item_id, sort_order, target_date
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_PROJECT_COLUMNS}
""",
(
@@ -268,6 +276,7 @@ def create_project(
initiative_id,
parent_project_id,
container_kind,
resolved_archetype,
title,
description,
status,
+137 -11
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timezone
from typing import Any, Literal, Optional
from psycopg2.extras import RealDictCursor
@@ -16,14 +16,14 @@ 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
id, tenant_id, initiative_id, roadmap_item_id, project_id, action_id, schedule_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"):
for key in ("id", "tenant_id", "initiative_id", "roadmap_item_id", "project_id", "action_id", "schedule_id"):
if result.get(key):
result[key] = str(result[key])
for ts_key in ("created_at", "updated_at", "next_due_at"):
@@ -46,6 +46,12 @@ def create_recurring_element(
status: RecurringStatus = "active",
interval_days: Optional[int] = None,
next_due_at: Optional[datetime] = None,
roadmap_item_id: Optional[str] = None,
project_id: Optional[str] = None,
schedule_id: Optional[str] = None,
schedule_kind: str = "interval",
weekday_mask: int = 0,
pause_until=None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
title = title.strip()
@@ -57,21 +63,48 @@ def create_recurring_element(
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden")
from services.schedule import create_schedule, initial_due_at
schedule = None
if schedule_id:
from services.schedule import get_schedule
schedule = get_schedule(tenant_id=tenant_id, schedule_id=schedule_id)
if not schedule:
raise ValueError("Schedule nicht gefunden")
else:
days = interval_days if interval_days is not None else 1
schedule = create_schedule(
tenant_id=tenant_id,
schedule_kind=schedule_kind, # type: ignore[arg-type]
interval_days=days,
weekday_mask=weekday_mask,
pause_until=pause_until,
)
schedule_id = schedule["id"]
interval_days = schedule.get("interval_days") or days
if next_due_at is None:
next_due_at = initial_due_at(schedule=schedule)
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
tenant_id, initiative_id, roadmap_item_id, project_id, schedule_id,
title, description, status, interval_days, next_due_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_RECURRING_COLUMNS}
""",
(
tenant_id,
initiative_id,
roadmap_item_id,
project_id,
schedule_id,
title,
description,
status,
@@ -90,6 +123,16 @@ def create_recurring_element(
tenant_id=tenant_id,
details={"recurring_id": row["id"], "initiative_id": initiative_id},
)
from services.cadence_instance import ensure_open_instance
open_inst = ensure_open_instance(
tenant_id=tenant_id,
recurring_element_id=row["id"],
due_at=next_due_at,
)
row["open_cadence_instance"] = open_inst
row["schedule"] = schedule
return row
@@ -111,10 +154,25 @@ def list_recurring_for_initiative(
""",
(tenant_id, initiative_id),
)
return [_serialize_row(dict(r)) for r in cur.fetchall()]
rows = [_serialize_row(dict(r)) for r in cur.fetchall()]
finally:
conn.close()
from services.cadence_instance import attach_open_instances_to_recurring_list
from services.schedule import attach_schedules_to_items
rows = attach_schedules_to_items(rows, tenant_id=tenant_id)
return attach_open_instances_to_recurring_list(rows, tenant_id=tenant_id)
def list_recurring_for_gate(
*, tenant_id: str, initiative_id: str, gate_id: str
) -> list[dict[str, Any]]:
items = list_recurring_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
return [item for item in items if str(item.get("roadmap_item_id") or "") == str(gate_id)]
def get_recurring_element(
*, tenant_id: str, recurring_id: str
@@ -131,10 +189,17 @@ def get_recurring_element(
(recurring_id, tenant_id),
)
row = cur.fetchone()
return _serialize_row(dict(row)) if row else None
if not row:
return None
result = _serialize_row(dict(row))
finally:
conn.close()
from services.schedule import attach_schedules_to_items
enriched = attach_schedules_to_items([result], tenant_id=tenant_id)
return enriched[0] if enriched else result
def update_recurring_element(
*,
@@ -148,6 +213,14 @@ def update_recurring_element(
clear_interval_days: bool = False,
next_due_at: Optional[datetime] = None,
clear_next_due_at: bool = False,
roadmap_item_id: Optional[str] = None,
clear_roadmap_item_id: bool = False,
project_id: Optional[str] = None,
clear_project_id: bool = False,
schedule_kind: Optional[str] = None,
weekday_mask: Optional[int] = None,
pause_until=None,
clear_pause_until: bool = False,
) -> Optional[dict[str, Any]]:
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
if not existing:
@@ -182,8 +255,50 @@ def update_recurring_element(
elif next_due_at is not None:
updates.append("next_due_at = %s")
params.append(next_due_at)
if clear_roadmap_item_id:
updates.append("roadmap_item_id = NULL")
elif roadmap_item_id is not None:
updates.append("roadmap_item_id = %s")
params.append(roadmap_item_id)
if clear_project_id:
updates.append("project_id = NULL")
elif project_id is not None:
updates.append("project_id = %s")
params.append(project_id)
if not updates:
if not updates and schedule_kind is None and weekday_mask is None and not clear_pause_until and pause_until is None:
return existing
schedule_updated = False
if existing.get("schedule_id") and (
schedule_kind is not None
or weekday_mask is not None
or pause_until is not None
or clear_pause_until
or interval_days is not None
):
from services.schedule import initial_due_at, update_schedule
sched = update_schedule(
tenant_id=tenant_id,
schedule_id=str(existing["schedule_id"]),
schedule_kind=schedule_kind, # type: ignore[arg-type]
interval_days=interval_days,
weekday_mask=weekday_mask,
pause_until=pause_until,
clear_pause_until=clear_pause_until,
)
if sched:
schedule_updated = True
if interval_days is not None and sched.get("interval_days"):
updates.append("interval_days = %s")
params.append(sched["interval_days"])
if next_due_at is None:
next_due_at = initial_due_at(schedule=sched)
updates.append("next_due_at = %s")
params.append(next_due_at)
if not updates and not schedule_updated:
return existing
updates.append("updated_at = NOW()")
@@ -226,7 +341,7 @@ def update_recurring_element(
"to_status": status,
},
)
return result
return get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id) or result
def delete_recurring_element(
@@ -235,6 +350,17 @@ def delete_recurring_element(
recurring_id: str,
user_id: Optional[str] = None,
) -> bool:
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
if not existing:
return False
action_id = existing.get("action_id")
if action_id:
from services.actions import delete_action
return delete_action(
tenant_id=tenant_id, action_id=action_id, user_id=user_id
)
conn = get_connection()
try:
with conn.cursor() as cur:
+242 -36
View File
@@ -13,26 +13,26 @@ from services.audit import log_audit
from services.initiatives import get_initiative
from services.roadmap_criteria import create_default_criterion, prepare_criteria_for_verify
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage"]
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]
RoadmapItemStatus = Literal[
"planned", "active", "at_risk", "reached", "moved", "discarded"
]
SequencingMode = Literal["sequential", "parallel", "optional"]
DependencyType = Literal["requires", "blocks", "related"]
DependencyType = Literal["requires", "blocks", "related", "parallel_group", "optional_branch"]
ROADMAP_ITEM_TYPES = frozenset({"milestone", "review_gate", "maturity_stage"})
ROADMAP_ITEM_TYPES = frozenset({"milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"})
ROADMAP_ITEM_STATUSES = frozenset(
{"planned", "active", "at_risk", "reached", "moved", "discarded"}
)
SEQUENCING_MODES = frozenset({"sequential", "parallel", "optional"})
DEPENDENCY_TYPES = frozenset({"requires", "blocks", "related"})
DEPENDENCY_TYPES = frozenset({"requires", "blocks", "related", "parallel_group", "optional_branch"})
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"):
for key in ("id", "tenant_id", "roadmap_id", "initiative_id", "from_item_id", "to_item_id", "strand_project_id"):
if result.get(key):
result[key] = str(result[key])
if result.get("target_date"):
@@ -185,6 +185,7 @@ def list_roadmap_items_for_initiative(
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.strand_project_id,
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
@@ -208,6 +209,7 @@ def get_roadmap_item(*, tenant_id: str, item_id: str) -> Optional[dict[str, Any]
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.strand_project_id,
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
@@ -233,6 +235,8 @@ def create_roadmap_item(
sequencing_mode: SequencingMode = "sequential",
target_date: Optional[date] = None,
sort_order: int = 0,
strand_project_id: Optional[str] = None,
initial_criterion_title: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
title = title.strip()
@@ -254,12 +258,13 @@ def create_roadmap_item(
"""
INSERT INTO roadmap_items (
tenant_id, roadmap_id, item_type, title, goal_description,
definition_of_done, status, sequencing_mode, target_date, sort_order
definition_of_done, status, sequencing_mode, target_date, sort_order,
strand_project_id
)
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %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
sort_order, strand_project_id, created_at, updated_at
""",
(
tenant_id,
@@ -272,16 +277,20 @@ def create_roadmap_item(
sequencing_mode,
target_date,
sort_order,
strand_project_id,
),
)
row = _serialize_row(dict(cur.fetchone()))
row["initiative_id"] = initiative_id
create_default_criterion(
cur,
tenant_id=tenant_id,
roadmap_item_id=row["id"],
description=goal_description or "",
)
if item_type not in ("work_cycle", "join_gate"):
create_default_criterion(
cur,
tenant_id=tenant_id,
roadmap_item_id=row["id"],
title=(initial_criterion_title or "Gate allgemein").strip()
or "Gate allgemein",
description=goal_description or "",
)
_sync_milestone_compat_row(
cur,
tenant_id=tenant_id,
@@ -320,6 +329,8 @@ def update_roadmap_item(
target_date: Optional[date] = None,
clear_target_date: bool = False,
sort_order: Optional[int] = None,
strand_project_id: Optional[str] = None,
clear_strand_project: bool = False,
) -> Optional[dict[str, Any]]:
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
if not existing:
@@ -369,6 +380,11 @@ def update_roadmap_item(
if sort_order is not None:
updates.append("sort_order = %s")
params.append(sort_order)
if clear_strand_project:
updates.append("strand_project_id = NULL")
elif strand_project_id is not None:
updates.append("strand_project_id = %s")
params.append(strand_project_id)
if not updates:
return existing
@@ -379,6 +395,20 @@ def update_roadmap_item(
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
if (
status == "active"
and existing.get("item_type") == "maturity_stage"
):
from services.progression_graph import (
enforce_single_active_work_gate_per_lane,
)
enforce_single_active_work_gate_per_lane(
cur,
tenant_id=tenant_id,
initiative_id=str(existing["initiative_id"]),
keep_active_id=item_id,
)
cur.execute(
f"""
UPDATE roadmap_items
@@ -386,7 +416,7 @@ def update_roadmap_item(
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
sort_order, strand_project_id, created_at, updated_at
""",
params,
)
@@ -428,6 +458,14 @@ def update_roadmap_item(
def delete_roadmap_item(
*, tenant_id: str, item_id: str, user_id: Optional[str] = None
) -> bool:
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
if not existing:
return False
if existing.get("status") in TERMINAL_STATUSES:
raise ValueError(
"Erreichte oder terminal abgeschlossene Gates können nicht gelöscht werden"
)
conn = get_connection()
try:
with conn.cursor() as cur:
@@ -454,6 +492,18 @@ def delete_roadmap_item(
return deleted
def _serialize_dependency(row: dict[str, Any]) -> dict[str, Any]:
dep = dict(row)
for key in ("id", "tenant_id", "from_item_id", "to_item_id"):
if dep.get(key):
dep[key] = str(dep[key])
if dep.get("created_at"):
dep["created_at"] = dep["created_at"].isoformat()
if dep.get("group_key") is None:
dep.pop("group_key", None)
return dep
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:
@@ -464,22 +514,43 @@ def list_dependencies(*, tenant_id: str, item_id: str) -> list[dict[str, Any]]:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, tenant_id, from_item_id, to_item_id, dependency_type, created_at
SELECT id, tenant_id, from_item_id, to_item_id, dependency_type,
group_key, 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
return [_serialize_dependency(dict(row)) for row in cur.fetchall()]
finally:
conn.close()
def list_dependencies_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 d.id, d.tenant_id, d.from_item_id, d.to_item_id,
d.dependency_type, d.group_key, d.created_at
FROM roadmap_item_dependencies d
INNER JOIN roadmap_items fi
ON fi.id = d.from_item_id AND fi.tenant_id = d.tenant_id
INNER JOIN roadmaps r
ON r.id = fi.roadmap_id AND r.tenant_id = fi.tenant_id
WHERE d.tenant_id = %s AND r.initiative_id = %s
ORDER BY d.created_at ASC
""",
(tenant_id, initiative_id),
)
return [_serialize_dependency(dict(row)) for row in cur.fetchall()]
finally:
conn.close()
@@ -490,6 +561,7 @@ def add_dependency(
from_item_id: str,
to_item_id: str,
dependency_type: DependencyType = "requires",
group_key: Optional[str] = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
_validate_dependency_type(dependency_type)
@@ -503,23 +575,38 @@ def add_dependency(
if from_item["initiative_id"] != to_item["initiative_id"]:
raise ValueError("Abhängigkeiten nur innerhalb eines Vorhabens")
normalized_group_key: Optional[str] = None
if group_key is not None:
normalized_group_key = group_key.strip() or None
if dependency_type == "parallel_group" and not normalized_group_key:
raise ValueError("group_key ist für parallel_group erforderlich")
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
SELECT 1 FROM roadmap_item_dependencies
WHERE tenant_id = %s AND from_item_id = %s AND to_item_id = %s
AND dependency_type = %s
""",
(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()
if cur.fetchone():
raise ValueError("Abhängigkeit existiert bereits")
cur.execute(
"""
INSERT INTO roadmap_item_dependencies (
tenant_id, from_item_id, to_item_id, dependency_type, group_key
)
VALUES (%s, %s, %s, %s, %s)
RETURNING id, tenant_id, from_item_id, to_item_id, dependency_type,
group_key, created_at
""",
(tenant_id, from_item_id, to_item_id, dependency_type, normalized_group_key),
)
row = _serialize_dependency(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
@@ -532,11 +619,55 @@ def add_dependency(
"from_item_id": from_item_id,
"to_item_id": to_item_id,
"dependency_type": dependency_type,
"group_key": normalized_group_key,
},
)
return row
def delete_dependency(
*, tenant_id: str, dependency_id: str, user_id: Optional[str] = None
) -> bool:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, from_item_id, to_item_id, dependency_type
FROM roadmap_item_dependencies
WHERE id = %s AND tenant_id = %s
""",
(dependency_id, tenant_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Abhängigkeit nicht gefunden")
cur.execute(
"""
DELETE FROM roadmap_item_dependencies
WHERE id = %s AND tenant_id = %s
""",
(dependency_id, tenant_id),
)
conn.commit()
finally:
conn.close()
log_audit(
"roadmap_item.dependency_removed",
user_id=user_id,
tenant_id=tenant_id,
details={
"dependency_id": dependency_id,
"from_item_id": str(row["from_item_id"]),
"to_item_id": str(row["to_item_id"]),
"dependency_type": row["dependency_type"],
},
)
return True
def verify_reached(
*, tenant_id: str, item_id: str, user_id: Optional[str] = None
) -> dict[str, Any]:
@@ -546,6 +677,10 @@ def verify_reached(
raise ValueError("RoadmapItem nicht gefunden")
if item["status"] in TERMINAL_STATUSES:
raise ValueError(f"RoadmapItem bereits terminal: {item['status']}")
if item.get("item_type") == "join_gate":
raise ValueError(
"Join-Knoten schaltet automatisch, wenn alle Eingänge erreicht sind — kein manuelles Verify"
)
initiative_id = item["initiative_id"]
conn = get_connection()
@@ -588,7 +723,7 @@ def verify_reached(
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
sort_order, strand_project_id, created_at, updated_at
""",
(item_id, tenant_id),
)
@@ -611,6 +746,38 @@ def verify_reached(
tenant_id=tenant_id,
details={"roadmap_item_id": item_id, "verify_reason": verify_reason},
)
if row.get("item_type") == "maturity_stage":
from services.progression_graph import on_work_gate_reached
transition = on_work_gate_reached(
tenant_id=tenant_id,
initiative_id=initiative_id,
reached_item_id=item_id,
user_id=user_id,
)
if transition:
row["maturity_transition"] = transition
elif row.get("item_type") != "work_cycle":
from services.steering_events import emit_steering_event
steering = emit_steering_event(
tenant_id=tenant_id,
initiative_id=initiative_id,
event_kind="gate_verified",
payload={
"roadmap_item_id": item_id,
"item_type": row.get("item_type"),
"verify_reason": verify_reason,
},
user_id=user_id,
)
row["steering_event"] = {
"handled": steering.get("handled"),
"lifecycle_chain": steering.get("lifecycle_chain"),
"lifecycle_state": steering.get("evaluation", {})
.get("lifecycle", {})
.get("current_state"),
}
return row
@@ -631,6 +798,17 @@ def reopen_roadmap_item(
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
if item.get("item_type") == "maturity_stage":
from services.progression_graph import (
enforce_single_active_work_gate_per_lane,
)
enforce_single_active_work_gate_per_lane(
cur,
tenant_id=tenant_id,
initiative_id=str(item["initiative_id"]),
keep_active_id=item_id,
)
cur.execute(
"""
UPDATE roadmap_items
@@ -638,7 +816,7 @@ def reopen_roadmap_item(
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
sort_order, strand_project_id, created_at, updated_at
""",
(item_id, tenant_id),
)
@@ -654,6 +832,16 @@ def reopen_roadmap_item(
finally:
conn.close()
if row.get("item_type") == "maturity_stage":
from services.maturity_stage_transition import on_maturity_stage_reopened
row["maturity_practice"] = on_maturity_stage_reopened(
tenant_id=tenant_id,
initiative_id=str(item["initiative_id"]),
stage_id=item_id,
user_id=user_id,
)
log_audit(
"roadmap_item.reopened",
user_id=user_id,
@@ -665,4 +853,22 @@ def reopen_roadmap_item(
"to_status": "active",
},
)
if row.get("item_type") != "work_cycle":
from services.steering_events import emit_steering_event
steering = emit_steering_event(
tenant_id=tenant_id,
initiative_id=str(row["initiative_id"]),
event_kind="gate_reopened",
payload={
"roadmap_item_id": item_id,
"item_type": row.get("item_type"),
"reason": reason.strip() or None,
},
user_id=user_id,
)
row["steering_event"] = {
"handled": steering.get("handled"),
"lifecycle_chain": steering.get("lifecycle_chain"),
}
return row
+49
View File
@@ -73,6 +73,15 @@ def _reopen_item_if_reached(
) -> None:
if item["status"] != "reached":
return
if item.get("item_type") == "maturity_stage":
from services.progression_graph import enforce_single_active_work_gate_per_lane
enforce_single_active_work_gate_per_lane(
cur,
tenant_id=tenant_id,
initiative_id=str(item["initiative_id"]),
keep_active_id=item["id"],
)
cur.execute(
"""
UPDATE roadmap_items
@@ -562,6 +571,46 @@ def defer_criterion(
)
def criteria_progress_for_initiative(
*, tenant_id: str, initiative_id: str
) -> dict[str, dict[str, int]]:
from services.initiatives import get_initiative
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden")
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
ri.id::text,
COUNT(c.id) AS total,
COUNT(c.id) FILTER (
WHERE c.status IN ('satisfied', 'waived', 'deferred')
) AS closed
FROM roadmap_items ri
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
LEFT JOIN roadmap_item_criteria c
ON c.roadmap_item_id = ri.id AND c.tenant_id = ri.tenant_id
WHERE ri.tenant_id = %s AND r.initiative_id = %s
GROUP BY ri.id
""",
(tenant_id, initiative_id),
)
return {
row[0]: {
"total": row[1],
"closed": row[2],
"open": row[1] - row[2],
}
for row in cur.fetchall()
}
finally:
conn.close()
def criteria_progress(*, tenant_id: str, item_id: str) -> dict[str, int]:
conn = get_connection()
try:
+203
View File
@@ -0,0 +1,203 @@
"""Plan snapshot capture & persistence (AP1.14)."""
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 services import roadmap as roadmap_service
from services import roadmap_criteria as criteria_service
def _serialize_snapshot(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in ("id", "tenant_id", "initiative_id", "roadmap_id", "created_by_user_id"):
if result.get(key):
result[key] = str(result[key])
if result.get("created_at"):
result["created_at"] = result["created_at"].isoformat()
payload = result.get("plan_payload")
if isinstance(payload, str):
result["plan_payload"] = json.loads(payload)
return result
def capture_plan_payload(
*, tenant_id: str, initiative_id: str
) -> dict[str, Any]:
"""Soll-Struktur: Topologie + Kriterien-Definitionen ohne Ist-Status."""
items = roadmap_service.list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
dependencies = roadmap_service.list_dependencies_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
plan_items = []
for item in items:
plan_items.append(
{
"id": item["id"],
"title": item["title"],
"item_type": item["item_type"],
"goal_description": item.get("goal_description") or "",
"sort_order": item.get("sort_order", 0),
"target_date": item.get("target_date"),
"sequencing_mode": item.get("sequencing_mode", "sequential"),
}
)
plan_deps = []
for dep in dependencies:
plan_deps.append(
{
"from_item_id": dep["from_item_id"],
"to_item_id": dep["to_item_id"],
"dependency_type": dep["dependency_type"],
"group_key": dep.get("group_key"),
}
)
plan_criteria = []
for item in items:
for crit in criteria_service.list_criteria_for_item(
tenant_id=tenant_id, item_id=item["id"]
):
plan_criteria.append(
{
"id": crit["id"],
"roadmap_item_id": crit["roadmap_item_id"],
"title": crit["title"],
"description": crit.get("description") or "",
"criterion_kind": crit["criterion_kind"],
"sort_order": crit.get("sort_order", 0),
}
)
return {
"items": plan_items,
"dependencies": plan_deps,
"criteria": plan_criteria,
}
def list_plan_snapshots(
*, tenant_id: str, initiative_id: str, limit: int = 20
) -> 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, roadmap_id, revision_number,
reason, plan_payload, created_by_user_id, created_at
FROM roadmap_plan_snapshots
WHERE tenant_id = %s AND initiative_id = %s
ORDER BY revision_number DESC
LIMIT %s
""",
(tenant_id, initiative_id, limit),
)
return [_serialize_snapshot(dict(r)) for r in cur.fetchall()]
finally:
conn.close()
def get_plan_snapshot(
*, tenant_id: str, snapshot_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, roadmap_id, revision_number,
reason, plan_payload, created_by_user_id, created_at
FROM roadmap_plan_snapshots
WHERE id = %s AND tenant_id = %s
""",
(snapshot_id, tenant_id),
)
row = cur.fetchone()
return _serialize_snapshot(dict(row)) if row else None
finally:
conn.close()
def create_plan_snapshot(
*,
tenant_id: str,
initiative_id: str,
reason: str = "",
user_id: Optional[str] = None,
) -> dict[str, Any]:
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden")
roadmap = roadmap_service.get_roadmap_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if not roadmap:
raise ValueError("Roadmap nicht gefunden")
plan_payload = capture_plan_payload(tenant_id=tenant_id, initiative_id=initiative_id)
reason = reason.strip()
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT COALESCE(MAX(revision_number), 0) + 1 AS next_rev
FROM roadmap_plan_snapshots
WHERE tenant_id = %s AND initiative_id = %s
""",
(tenant_id, initiative_id),
)
revision_number = int(cur.fetchone()["next_rev"])
cur.execute(
"""
INSERT INTO roadmap_plan_snapshots (
tenant_id, initiative_id, roadmap_id, revision_number,
reason, plan_payload, created_by_user_id
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id, tenant_id, initiative_id, roadmap_id, revision_number,
reason, plan_payload, created_by_user_id, created_at
""",
(
tenant_id,
initiative_id,
roadmap["id"],
revision_number,
reason,
Json(plan_payload),
user_id,
),
)
row = _serialize_snapshot(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
log_audit(
"roadmap_plan_snapshot.created",
user_id=user_id,
tenant_id=tenant_id,
details={
"snapshot_id": row["id"],
"initiative_id": initiative_id,
"revision_number": revision_number,
"reason": reason or None,
},
)
return row
+374
View File
@@ -0,0 +1,374 @@
"""Unified Schedule service — ADP v0.1."""
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
from typing import Any, Literal, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
ScheduleKind = Literal["interval", "weekdays"]
_SCHEDULE_COLUMNS = """
id, tenant_id, schedule_kind, interval_days, weekday_mask, pause_until,
created_at, updated_at
"""
WEEKDAY_LABELS = ("Mo", "Di", "Mi", "Do", "Fr", "Sa", "So")
def weekday_bit(weekday: int) -> int:
"""ISO weekday: Monday=0 … Sunday=6."""
return 1 << weekday
def weekday_mask_for_date(on_date: date) -> int:
return weekday_bit(on_date.weekday())
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in ("id", "tenant_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()
if result.get("pause_until"):
result["pause_until"] = result["pause_until"].isoformat()
return result
def validate_schedule_payload(
*,
schedule_kind: str,
interval_days: Optional[int],
weekday_mask: int,
) -> None:
if schedule_kind not in ("interval", "weekdays"):
raise ValueError("Ungültiger schedule_kind")
if schedule_kind == "interval":
days = int(interval_days or 1)
if days <= 0:
raise ValueError("interval_days muss positiv sein")
elif weekday_mask <= 0 or weekday_mask > 127:
raise ValueError("Mindestens ein Wochentag auswählen")
def format_schedule_label(schedule: dict[str, Any]) -> str:
kind = schedule.get("schedule_kind") or "interval"
if kind == "weekdays":
mask = int(schedule.get("weekday_mask") or 0)
days = [WEEKDAY_LABELS[i] for i in range(7) if mask & weekday_bit(i)]
label = ", ".join(days) if days else "Wochentage"
else:
days = max(int(schedule.get("interval_days") or 1), 1)
if days == 1:
label = "Täglich"
else:
label = f"Alle {days} Tage"
pause = schedule.get("pause_until")
if pause:
label = f"{label} (Pause bis {pause})"
return label
def _parse_pause_until(value: Any) -> Optional[date]:
if value is None:
return None
if isinstance(value, date) and not isinstance(value, datetime):
return value
if isinstance(value, datetime):
return value.date()
text = str(value).strip()
if not text:
return None
return date.fromisoformat(text[:10])
def is_paused_on(schedule: dict[str, Any], on_date: date) -> bool:
pause = _parse_pause_until(schedule.get("pause_until"))
return pause is not None and on_date <= pause
def _weekday_matches(schedule: dict[str, Any], on_date: date) -> bool:
mask = int(schedule.get("weekday_mask") or 0)
return bool(mask & weekday_bit(on_date.weekday()))
def _as_utc_midnight(d: date) -> datetime:
return datetime.combine(d, time.min, tzinfo=timezone.utc)
def _next_weekday_on_or_after(
start: date, *, weekday_mask: int, pause_until: Optional[date]
) -> date:
for offset in range(366):
candidate = start + timedelta(days=offset)
if pause_until is not None and candidate <= pause_until:
continue
if weekday_mask & weekday_bit(candidate.weekday()):
return candidate
return start + timedelta(days=7)
def initial_due_at(*, schedule: dict[str, Any], now: Optional[datetime] = None) -> datetime:
now = now or datetime.now(timezone.utc)
today = now.date()
if is_paused_on(schedule, today):
pause = _parse_pause_until(schedule.get("pause_until"))
assert pause is not None
start = pause + timedelta(days=1)
else:
start = today
kind = schedule.get("schedule_kind") or "interval"
if kind == "weekdays":
mask = int(schedule.get("weekday_mask") or 0)
pause = _parse_pause_until(schedule.get("pause_until"))
due_date = _next_weekday_on_or_after(start, weekday_mask=mask, pause_until=pause)
return _as_utc_midnight(due_date)
return _as_utc_midnight(start)
def next_due_after_completion(
*, schedule: dict[str, Any], completed_at: Optional[datetime] = None
) -> datetime:
now = completed_at or datetime.now(timezone.utc)
today = now.date()
kind = schedule.get("schedule_kind") or "interval"
if kind == "weekdays":
mask = int(schedule.get("weekday_mask") or 0)
pause = _parse_pause_until(schedule.get("pause_until"))
start = today + timedelta(days=1)
due_date = _next_weekday_on_or_after(start, weekday_mask=mask, pause_until=pause)
return _as_utc_midnight(due_date)
days = max(int(schedule.get("interval_days") or 1), 1)
next_date = today + timedelta(days=days)
pause = _parse_pause_until(schedule.get("pause_until"))
if pause is not None and next_date <= pause:
next_date = pause + timedelta(days=1)
return _as_utc_midnight(next_date)
def is_due_on_date(
*,
schedule: Optional[dict[str, Any]] = None,
next_due_at: Optional[datetime] = None,
on_date: Optional[date] = None,
) -> bool:
"""True if the series should appear as due on on_date (includes overdue)."""
on_date = on_date or date.today()
schedule = schedule or {}
if is_paused_on(schedule, on_date):
return False
due_date: Optional[date] = None
if isinstance(next_due_at, datetime):
due_date = next_due_at.date()
elif next_due_at is not None:
parsed = datetime.fromisoformat(str(next_due_at).replace("Z", "+00:00"))
due_date = parsed.date()
if due_date is not None and due_date > on_date:
return False
kind = schedule.get("schedule_kind") or "interval"
if kind == "weekdays":
if due_date is not None:
return True
return _weekday_matches(schedule, on_date)
return True
def create_schedule(
*,
tenant_id: str,
schedule_kind: ScheduleKind = "interval",
interval_days: Optional[int] = 1,
weekday_mask: int = 0,
pause_until: Optional[date] = None,
) -> dict[str, Any]:
validate_schedule_payload(
schedule_kind=schedule_kind,
interval_days=interval_days,
weekday_mask=weekday_mask,
)
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
INSERT INTO schedules (
tenant_id, schedule_kind, interval_days, weekday_mask, pause_until
)
VALUES (%s, %s, %s, %s, %s)
RETURNING {_SCHEDULE_COLUMNS}
""",
(
tenant_id,
schedule_kind,
interval_days if schedule_kind == "interval" else None,
weekday_mask,
pause_until,
),
)
row = _serialize_row(dict(cur.fetchone()))
conn.commit()
finally:
conn.close()
row["label"] = format_schedule_label(row)
return row
def get_schedule(*, tenant_id: str, schedule_id: str) -> Optional[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
SELECT {_SCHEDULE_COLUMNS}
FROM schedules
WHERE id = %s AND tenant_id = %s
""",
(schedule_id, tenant_id),
)
row = cur.fetchone()
if not row:
return None
result = _serialize_row(dict(row))
result["label"] = format_schedule_label(result)
return result
finally:
conn.close()
def update_schedule(
*,
tenant_id: str,
schedule_id: str,
schedule_kind: Optional[ScheduleKind] = None,
interval_days: Optional[int] = None,
weekday_mask: Optional[int] = None,
pause_until: Optional[date] = None,
clear_pause_until: bool = False,
) -> Optional[dict[str, Any]]:
existing = get_schedule(tenant_id=tenant_id, schedule_id=schedule_id)
if not existing:
return None
kind = schedule_kind or existing["schedule_kind"]
interval = interval_days if interval_days is not None else existing.get("interval_days")
mask = weekday_mask if weekday_mask is not None else int(existing.get("weekday_mask") or 0)
validate_schedule_payload(
schedule_kind=kind, interval_days=interval, weekday_mask=mask
)
updates: list[str] = []
params: list[Any] = []
if schedule_kind is not None:
updates.append("schedule_kind = %s")
params.append(schedule_kind)
if interval_days is not None or schedule_kind == "weekdays":
updates.append("interval_days = %s")
params.append(None if kind == "weekdays" else interval)
if weekday_mask is not None:
updates.append("weekday_mask = %s")
params.append(mask)
if clear_pause_until:
updates.append("pause_until = NULL")
elif pause_until is not None:
updates.append("pause_until = %s")
params.append(pause_until)
if not updates:
return existing
updates.append("updated_at = NOW()")
params.extend([schedule_id, tenant_id])
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
UPDATE schedules
SET {", ".join(updates)}
WHERE id = %s AND tenant_id = %s
RETURNING {_SCHEDULE_COLUMNS}
""",
params,
)
row = cur.fetchone()
if not row:
return None
result = _serialize_row(dict(row))
conn.commit()
finally:
conn.close()
result["label"] = format_schedule_label(result)
return result
def attach_schedules_to_items(
items: list[dict[str, Any]], *, tenant_id: str, schedule_id_key: str = "schedule_id"
) -> list[dict[str, Any]]:
ids = [
str(item[schedule_id_key])
for item in items
if item.get(schedule_id_key)
]
if not ids:
return [dict(item, schedule=None) for item in items]
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
f"""
SELECT {_SCHEDULE_COLUMNS}
FROM schedules
WHERE tenant_id = %s AND id = ANY(%s::uuid[])
""",
(tenant_id, ids),
)
by_id = {}
for row in cur.fetchall():
sched = _serialize_row(dict(row))
sched["label"] = format_schedule_label(sched)
by_id[str(row["id"])] = sched
finally:
conn.close()
enriched = []
for item in items:
copy = dict(item)
sid = copy.get(schedule_id_key)
copy["schedule"] = by_id.get(str(sid)) if sid else None
enriched.append(copy)
return enriched
def resolve_schedule_for_recurring(
recurring: dict[str, Any], *, tenant_id: str
) -> Optional[dict[str, Any]]:
sid = recurring.get("schedule_id")
if sid:
return get_schedule(tenant_id=tenant_id, schedule_id=str(sid))
interval = recurring.get("interval_days")
if interval is None:
return None
return {
"schedule_kind": "interval",
"interval_days": max(int(interval), 1),
"weekday_mask": 0,
"pause_until": None,
"label": format_schedule_label(
{"schedule_kind": "interval", "interval_days": interval, "weekday_mask": 0}
),
}
+309
View File
@@ -0,0 +1,309 @@
"""Action ↔ Recurring bridge for unified schedules (ADP v0.1 Slice 2)."""
from __future__ import annotations
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from services.audit import log_audit
from services.cadence_instance import ensure_open_instance
from services.recurring import (
create_recurring_element,
get_recurring_element,
update_recurring_element,
)
from services.schedule import (
create_schedule,
get_schedule,
initial_due_at,
update_schedule,
)
def _get_action_row(*, tenant_id: str, action_id: str) -> dict[str, Any]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, tenant_id, initiative_id, project_id, roadmap_item_id, schedule_id,
title, description
FROM actions
WHERE id = %s AND tenant_id = %s
""",
(action_id, tenant_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Arbeitspaket nicht gefunden")
result = dict(row)
for key in (
"id",
"tenant_id",
"initiative_id",
"project_id",
"roadmap_item_id",
"schedule_id",
):
if result.get(key):
result[key] = str(result[key])
return result
finally:
conn.close()
def _find_recurring_for_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(
"""
SELECT id
FROM recurring_elements
WHERE tenant_id = %s AND action_id = %s
LIMIT 1
""",
(tenant_id, action_id),
)
row = cur.fetchone()
if not row:
return None
return get_recurring_element(tenant_id=tenant_id, recurring_id=str(row["id"]))
finally:
conn.close()
def attach_action_schedule_fields(
action: dict[str, Any], *, tenant_id: str
) -> dict[str, Any]:
schedule = None
if action.get("schedule_id"):
schedule = get_schedule(tenant_id=tenant_id, schedule_id=str(action["schedule_id"]))
bridge = _find_recurring_for_action(tenant_id=tenant_id, action_id=str(action["id"]))
copy = dict(action)
copy["schedule"] = schedule
copy["recurring_id"] = bridge["id"] if bridge else None
return copy
def get_action_schedule_bundle(*, tenant_id: str, action_id: str) -> dict[str, Any]:
action = _get_action_row(tenant_id=tenant_id, action_id=action_id)
enriched = attach_action_schedule_fields(action, tenant_id=tenant_id)
bridge = _find_recurring_for_action(tenant_id=tenant_id, action_id=action_id)
return {
"action_id": action_id,
"schedule": enriched.get("schedule"),
"recurring_id": enriched.get("recurring_id"),
"recurring": bridge,
}
def upsert_action_schedule(
*,
tenant_id: str,
action_id: str,
user_id: Optional[str] = None,
schedule_kind: str = "interval",
interval_days: Optional[int] = 1,
weekday_mask: int = 0,
pause_until=None,
) -> dict[str, Any]:
action = _get_action_row(tenant_id=tenant_id, action_id=action_id)
existing_schedule_id = action.get("schedule_id")
if existing_schedule_id:
schedule = update_schedule(
tenant_id=tenant_id,
schedule_id=str(existing_schedule_id),
schedule_kind=schedule_kind, # type: ignore[arg-type]
interval_days=interval_days,
weekday_mask=weekday_mask,
pause_until=pause_until,
clear_pause_until=pause_until is None,
)
else:
schedule = create_schedule(
tenant_id=tenant_id,
schedule_kind=schedule_kind, # type: ignore[arg-type]
interval_days=interval_days,
weekday_mask=weekday_mask,
pause_until=pause_until,
)
if not schedule:
raise ValueError("Schedule konnte nicht gespeichert werden")
next_due = initial_due_at(schedule=schedule)
interval = schedule.get("interval_days") or 1
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE actions
SET schedule_id = %s, updated_at = NOW()
WHERE id = %s AND tenant_id = %s
""",
(schedule["id"], action_id, tenant_id),
)
conn.commit()
finally:
conn.close()
bridge = _find_recurring_for_action(tenant_id=tenant_id, action_id=action_id)
if bridge:
update_recurring_element(
tenant_id=tenant_id,
recurring_id=bridge["id"],
user_id=user_id,
status="active",
interval_days=int(interval),
next_due_at=next_due,
)
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE recurring_elements
SET schedule_id = %s, updated_at = NOW()
WHERE id = %s AND tenant_id = %s
""",
(schedule["id"], bridge["id"], tenant_id),
)
conn.commit()
finally:
conn.close()
recurring = get_recurring_element(tenant_id=tenant_id, recurring_id=bridge["id"])
else:
recurring = create_recurring_element(
tenant_id=tenant_id,
initiative_id=str(action["initiative_id"]),
title=action["title"],
description=action.get("description") or "",
status="active",
interval_days=int(interval),
next_due_at=next_due,
roadmap_item_id=action.get("roadmap_item_id"),
project_id=action.get("project_id"),
schedule_id=str(schedule["id"]),
user_id=user_id,
)
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE recurring_elements
SET action_id = %s
WHERE id = %s AND tenant_id = %s
""",
(action_id, recurring["id"], tenant_id),
)
conn.commit()
finally:
conn.close()
ensure_open_instance(
tenant_id=tenant_id,
recurring_element_id=recurring["id"],
due_at=next_due,
)
log_audit(
"action.schedule_set",
user_id=user_id,
tenant_id=tenant_id,
details={"action_id": action_id, "schedule_id": schedule["id"]},
)
return get_action_schedule_bundle(tenant_id=tenant_id, action_id=action_id)
def clear_action_schedule(
*,
tenant_id: str,
action_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
bundle = get_action_schedule_bundle(tenant_id=tenant_id, action_id=action_id)
bridge = bundle.get("recurring")
if bridge:
update_recurring_element(
tenant_id=tenant_id,
recurring_id=bridge["id"],
user_id=user_id,
status="ended",
)
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE actions
SET schedule_id = NULL, updated_at = NOW()
WHERE id = %s AND tenant_id = %s
""",
(action_id, tenant_id),
)
conn.commit()
finally:
conn.close()
log_audit(
"action.schedule_cleared",
user_id=user_id,
tenant_id=tenant_id,
details={"action_id": action_id},
)
return {"action_id": action_id, "schedule": None, "recurring_id": None}
def create_scheduled_action_at_gate(
*,
tenant_id: str,
initiative_id: str,
gate_id: str,
title: str,
description: str = "",
user_id: Optional[str] = None,
schedule_kind: str = "weekdays",
interval_days: Optional[int] = 1,
weekday_mask: int = 0,
pause_until=None,
) -> dict[str, Any]:
"""Plan a repeating AP at a work-gate. RecurringElement is the cadence bridge."""
from datetime import date
from services.actions import create_action
from services.schedule import weekday_mask_for_date
if schedule_kind == "weekdays" and weekday_mask <= 0:
weekday_mask = weekday_mask_for_date(date.today())
action = create_action(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
description=description,
status="open",
roadmap_item_id=gate_id,
user_id=user_id,
)
bundle = upsert_action_schedule(
tenant_id=tenant_id,
action_id=str(action["id"]),
user_id=user_id,
schedule_kind=schedule_kind,
interval_days=interval_days,
weekday_mask=weekday_mask,
pause_until=pause_until,
)
recurring = bundle.get("recurring")
if not recurring:
raise ValueError("Cadence-Brücke für Arbeitspaket fehlt")
return recurring
+150 -5
View File
@@ -16,6 +16,14 @@ DEFAULT_METHOD_KEY = "generic_operating"
DEFAULT_METHOD_VERSION = "0.1.0"
def _resolve_om_capabilities_for_initiative(initiative: dict[str, Any]) -> frozenset[str]:
from entity_archetypes.registry import resolve_ui_profile
profile = resolve_ui_profile(initiative["archetype_key"])
caps = profile.get("omCapabilities") or profile.get("dataSlices") or []
return frozenset(caps)
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row)
for key in ("id", "tenant_id", "initiative_id"):
@@ -100,6 +108,8 @@ def ensure_steering_context(
initiative_id: str,
initial_state: Optional[str] = None,
user_id: Optional[str] = None,
method_key: Optional[str] = None,
lifecycle_metadata: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
if existing:
@@ -113,6 +123,16 @@ def ensure_steering_context(
)
validate_lifecycle_state(state)
resolved_method = method_key or DEFAULT_METHOD_KEY
from steering.methods.registry import get_method
method = get_method(resolved_method)
if not method:
resolved_method = DEFAULT_METHOD_KEY
method = get_method(resolved_method)
method_version = method.version if method else DEFAULT_METHOD_VERSION
metadata = lifecycle_metadata or {}
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
@@ -129,10 +149,10 @@ def ensure_steering_context(
(
tenant_id,
initiative_id,
DEFAULT_METHOD_KEY,
DEFAULT_METHOD_VERSION,
resolved_method,
method_version,
state,
Json({}),
Json(metadata),
),
)
row = _serialize_row(dict(cur.fetchone()))
@@ -144,7 +164,11 @@ def ensure_steering_context(
"steering_context.created",
user_id=user_id,
tenant_id=tenant_id,
details={"initiative_id": initiative_id, "lifecycle_state": state},
details={
"initiative_id": initiative_id,
"lifecycle_state": state,
"method_key": resolved_method,
},
)
return row
@@ -201,12 +225,28 @@ def update_method_key(
method_key: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
from steering.methods.registry import get_method
from entity_archetypes.registry import resolve_default_method_key
from method_profiles.registry import get_method_profile
from steering.methods.registry import get_method, method_compatible_with_archetype
from services.initiatives import get_initiative
method = get_method(method_key)
if not method:
raise ValueError(f"Unbekannte Methode: {method_key}")
initiative = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not initiative:
raise ValueError("Vorhaben nicht gefunden")
if not method_compatible_with_archetype(
method,
initiative["archetype_key"],
om_capabilities=_resolve_om_capabilities_for_initiative(initiative),
):
raise ValueError(
f"Methode {method_key} ist nicht kompatibel mit Archetyp "
f"{initiative['archetype_key']}"
)
existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
if not existing:
raise ValueError("SteeringContext nicht gefunden")
@@ -245,15 +285,120 @@ def update_method_key(
return result
def update_method_profile_key(
*,
tenant_id: str,
initiative_id: str,
method_profile_key: Optional[str],
user_id: Optional[str] = None,
) -> dict[str, Any]:
"""Setzt oder entfernt method_profile_key; passt method_key aus Profile/Archetyp an."""
from entity_archetypes.registry import resolve_default_method_key
from method_profiles.registry import get_method_profile
from steering.methods.registry import get_method
initiative = get_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not initiative:
raise ValueError("Vorhaben nicht gefunden")
existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
if not existing:
raise ValueError("SteeringContext nicht gefunden")
metadata = dict(existing.get("lifecycle_metadata") or {})
previous_profile = metadata.get("method_profile_key")
if method_profile_key:
profile = get_method_profile(method_profile_key)
if not profile:
raise ValueError(f"Unbekannte Ausprägung: {method_profile_key}")
if profile["initiative_archetype_key"] != initiative["archetype_key"]:
raise ValueError("Ausprägung passt nicht zum Archetyp des Vorhabens")
metadata["method_profile_key"] = method_profile_key
resolved_method = profile["method_key"]
else:
metadata.pop("method_profile_key", None)
resolved_method = resolve_default_method_key(initiative["archetype_key"])
method = get_method(resolved_method)
if not method:
raise ValueError(f"Unbekannte Methode: {resolved_method}")
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
UPDATE steering_contexts
SET method_key = %s,
method_version = %s,
lifecycle_metadata = %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,
Json(metadata),
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_profile_changed",
user_id=user_id,
tenant_id=tenant_id,
details={
"initiative_id": initiative_id,
"from_profile": previous_profile,
"to_profile": method_profile_key,
"method_key": method.key,
},
)
return result
def create_context_for_new_initiative(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str] = None,
archetype_key: str = "initiative.generic",
method_profile_key: Optional[str] = None,
) -> dict[str, Any]:
from entity_archetypes.registry import resolve_default_method_key
from method_profiles.registry import resolve_method_for_profile
method_key = resolve_default_method_key(archetype_key)
lifecycle_metadata: dict[str, Any] = {}
if method_profile_key:
from method_profiles.registry import get_method_profile
profile = get_method_profile(method_profile_key)
if not profile:
raise ValueError(f"Unbekannte Ausprägung: {method_profile_key}")
if profile["initiative_archetype_key"] != archetype_key:
raise ValueError("Ausprägung passt nicht zum Archetyp des Vorhabens")
profile_method = resolve_method_for_profile(method_profile_key)
if profile_method:
method_key = profile_method
lifecycle_metadata["method_profile_key"] = method_profile_key
return ensure_steering_context(
tenant_id=tenant_id,
initiative_id=initiative_id,
initial_state="intake",
user_id=user_id,
method_key=method_key,
lifecycle_metadata=lifecycle_metadata or None,
)
+26
View File
@@ -0,0 +1,26 @@
"""Emit steering kernel events from OM mutations — Spine v0.2."""
from __future__ import annotations
from typing import Any, Optional
from steering.kernel.context import resolve_minimal_tenant_context
from steering.kernel.events import apply_steering_event
from steering.lifecycle.event_transitions import EventKind
def emit_steering_event(
*,
tenant_id: str,
initiative_id: str,
event_kind: EventKind,
payload: dict[str, Any] | None = None,
user_id: Optional[str] = None,
) -> dict[str, Any]:
ctx = resolve_minimal_tenant_context(tenant_id=tenant_id, user_id=user_id)
return apply_steering_event(
ctx,
initiative_id=initiative_id,
event_kind=event_kind,
payload=payload,
)
+220 -26
View File
@@ -1,4 +1,4 @@
"""Task service — kleinste Einheit unter Action (AP1.5)."""
"""Task service — kleinste Einheit unter Action (AP1.5, AP1.5d rekursiv)."""
from __future__ import annotations
@@ -13,16 +13,18 @@ from services.audit import log_audit
TaskStatus = Literal["open", "in_progress", "done", "discarded"]
TASK_STATUSES = frozenset({"open", "in_progress", "done", "discarded"})
TERMINAL_TASK_STATUSES = frozenset({"done", "discarded"})
MAX_TASK_DEPTH = 10
_TASK_COLUMNS = """
id, tenant_id, action_id, title, description, status,
id, tenant_id, action_id, parent_task_id, title, description, status,
roadmap_item_id, sort_order, 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", "action_id", "roadmap_item_id"):
for key in ("id", "tenant_id", "action_id", "parent_task_id", "roadmap_item_id"):
if result.get(key):
result[key] = str(result[key])
if result.get("due_at"):
@@ -62,6 +64,147 @@ def _validate_roadmap_item_for_action(
raise ValueError("Gate gehört nicht zum Vorhaben des Arbeitspakets")
def _load_action_task_maps(
cur, *, tenant_id: str, action_id: str
) -> tuple[dict[str, dict[str, Any]], dict[str, list[str]]]:
cur.execute(
f"""
SELECT {_TASK_COLUMNS}
FROM tasks
WHERE tenant_id = %s AND action_id = %s
""",
(tenant_id, action_id),
)
rows = [dict(r) for r in cur.fetchall()]
by_id = {str(r["id"]): r for r in rows}
by_parent: dict[str, list[str]] = {}
for row in rows:
parent_id = row.get("parent_task_id")
if parent_id:
by_parent.setdefault(str(parent_id), []).append(str(row["id"]))
return by_id, by_parent
def _collect_descendant_ids(task_id: str, by_parent: dict[str, list[str]]) -> set[str]:
result: set[str] = set()
stack = list(by_parent.get(task_id, []))
while stack:
child_id = stack.pop()
if child_id in result:
continue
result.add(child_id)
stack.extend(by_parent.get(child_id, []))
return result
def _task_depth_from_map(
task_id: str,
by_id: dict[str, dict[str, Any]],
memo: dict[str, int],
) -> int:
if task_id in memo:
return memo[task_id]
row = by_id.get(task_id)
if not row or not row.get("parent_task_id"):
memo[task_id] = 1
return 1
parent_id = str(row["parent_task_id"])
depth = 1 + _task_depth_from_map(parent_id, by_id, memo)
memo[task_id] = depth
return depth
def _subtree_height(task_id: str, by_parent: dict[str, list[str]]) -> int:
children = by_parent.get(task_id, [])
if not children:
return 1
return 1 + max(_subtree_height(child_id, by_parent) for child_id in children)
def _validate_parent_task(
cur,
*,
tenant_id: str,
action_id: str,
task_id: Optional[str],
parent_task_id: Optional[str],
) -> None:
if not parent_task_id:
return
if task_id and parent_task_id == task_id:
raise ValueError("Task kann nicht sein eigener Parent sein")
cur.execute(
f"""
SELECT {_TASK_COLUMNS}
FROM tasks
WHERE id = %s AND tenant_id = %s AND action_id = %s
""",
(parent_task_id, tenant_id, action_id),
)
parent = cur.fetchone()
if not parent:
raise ValueError("Parent-Task gehört nicht zu diesem Arbeitspaket")
by_id, by_parent = _load_action_task_maps(cur, tenant_id=tenant_id, action_id=action_id)
if task_id:
descendants = _collect_descendant_ids(task_id, by_parent)
if parent_task_id in descendants:
raise ValueError("Zyklus: Parent darf kein Nachfahr sein")
memo: dict[str, int] = {}
parent_depth = _task_depth_from_map(parent_task_id, by_id, memo)
subtree_height = _subtree_height(task_id, by_parent) if task_id else 1
if parent_depth + subtree_height > MAX_TASK_DEPTH:
raise ValueError(f"Maximale Task-Tiefe ({MAX_TASK_DEPTH}) würde überschritten")
def _has_open_children(cur, *, tenant_id: str, task_id: str) -> bool:
cur.execute(
"""
SELECT 1 FROM tasks
WHERE tenant_id = %s AND parent_task_id = %s
AND status NOT IN ('done', 'discarded')
LIMIT 1
""",
(tenant_id, task_id),
)
return cur.fetchone() is not None
def _rollup_parent_status(cur, *, tenant_id: str, parent_task_id: str) -> None:
cur.execute(
"""
SELECT status FROM tasks
WHERE tenant_id = %s AND parent_task_id = %s
""",
(tenant_id, parent_task_id),
)
child_statuses = [
row["status"] if isinstance(row, dict) else row[0] for row in cur.fetchall()
]
if not child_statuses:
return
if any(status not in TERMINAL_TASK_STATUSES for status in child_statuses):
return
cur.execute(
"""
UPDATE tasks
SET status = 'done', updated_at = NOW()
WHERE id = %s AND tenant_id = %s AND status NOT IN ('done', 'discarded')
RETURNING parent_task_id
""",
(parent_task_id, tenant_id),
)
row = cur.fetchone()
if not row:
return
next_parent = row["parent_task_id"] if isinstance(row, dict) else row[0]
if next_parent:
_rollup_parent_status(cur, tenant_id=tenant_id, parent_task_id=str(next_parent))
def create_task(
*,
tenant_id: str,
@@ -69,6 +212,7 @@ def create_task(
title: str,
description: str = "",
status: TaskStatus = "open",
parent_task_id: Optional[str] = None,
roadmap_item_id: Optional[str] = None,
sort_order: int = 0,
due_at: Optional[datetime] = None,
@@ -83,6 +227,13 @@ def create_task(
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
_validate_parent_task(
cur,
tenant_id=tenant_id,
action_id=action_id,
task_id=None,
parent_task_id=parent_task_id,
)
_validate_roadmap_item_for_action(
cur,
tenant_id=tenant_id,
@@ -92,15 +243,16 @@ def create_task(
cur.execute(
f"""
INSERT INTO tasks (
tenant_id, action_id, title, description, status,
tenant_id, action_id, parent_task_id, title, description, status,
roadmap_item_id, sort_order, due_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_TASK_COLUMNS}
""",
(
tenant_id,
action_id,
parent_task_id,
title,
description,
status,
@@ -118,7 +270,12 @@ def create_task(
"task.created",
user_id=user_id,
tenant_id=tenant_id,
details={"task_id": row["id"], "action_id": action_id, "title": title},
details={
"task_id": row["id"],
"action_id": action_id,
"title": title,
"parent_task_id": parent_task_id,
},
)
return row
@@ -164,6 +321,8 @@ def update_task(
title: Optional[str] = None,
description: Optional[str] = None,
status: Optional[TaskStatus] = None,
parent_task_id: Optional[str] = None,
clear_parent_task: bool = False,
roadmap_item_id: Optional[str] = None,
clear_roadmap_item: bool = False,
sort_order: Optional[int] = None,
@@ -189,22 +348,14 @@ def update_task(
params.append(description)
if status is not None:
_validate_status(status)
updates.append("status = %s")
params.append(status)
if clear_parent_task:
updates.append("parent_task_id = NULL")
elif parent_task_id is not None:
updates.append("parent_task_id = %s")
params.append(parent_task_id)
if clear_roadmap_item:
updates.append("roadmap_item_id = NULL")
elif roadmap_item_id is not None:
conn = get_connection()
try:
with conn.cursor() as cur:
_validate_roadmap_item_for_action(
cur,
tenant_id=tenant_id,
initiative_id=action["initiative_id"],
roadmap_item_id=roadmap_item_id,
)
finally:
conn.close()
updates.append("roadmap_item_id = %s")
params.append(roadmap_item_id)
if sort_order is not None:
@@ -216,15 +367,39 @@ def update_task(
updates.append("due_at = %s")
params.append(due_at)
if not updates:
return existing
updates.append("updated_at = NOW()")
params.extend([task_id, tenant_id])
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
if parent_task_id is not None and not clear_parent_task:
_validate_parent_task(
cur,
tenant_id=tenant_id,
action_id=existing["action_id"],
task_id=task_id,
parent_task_id=parent_task_id,
)
if roadmap_item_id is not None and not clear_roadmap_item:
_validate_roadmap_item_for_action(
cur,
tenant_id=tenant_id,
initiative_id=action["initiative_id"],
roadmap_item_id=roadmap_item_id,
)
if status is not None:
if status == "done" and _has_open_children(
cur, tenant_id=tenant_id, task_id=task_id
):
raise ValueError(
"Task kann nicht abgeschlossen werden — offene Unteraufgaben vorhanden"
)
updates.append("status = %s")
params.append(status)
if not updates:
return existing
updates.append("updated_at = NOW()")
params.extend([task_id, tenant_id])
cur.execute(
f"""
UPDATE tasks SET {", ".join(updates)}
@@ -237,6 +412,13 @@ def update_task(
if not row:
return None
result = _serialize_row(dict(row))
if status == "done" and result.get("parent_task_id"):
_rollup_parent_status(
cur,
tenant_id=tenant_id,
parent_task_id=str(result["parent_task_id"]),
)
conn.commit()
finally:
conn.close()
@@ -247,13 +429,25 @@ def update_task(
tenant_id=tenant_id,
details={"task_id": task_id},
)
return result
return get_task(tenant_id=tenant_id, task_id=task_id)
def delete_task(*, tenant_id: str, task_id: str, user_id: Optional[str] = None) -> bool:
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT 1 FROM tasks
WHERE parent_task_id = %s AND tenant_id = %s
LIMIT 1
""",
(task_id, tenant_id),
)
if cur.fetchone():
raise ValueError(
"Task hat Unteraufgaben — zuerst löschen oder verschieben"
)
cur.execute(
"DELETE FROM tasks WHERE id = %s AND tenant_id = %s RETURNING id",
(task_id, tenant_id),
+336
View File
@@ -0,0 +1,336 @@
"""Work cycle (Sprint/Zeitbox) — AP2.0f on RoadmapItem(type=work_cycle)."""
from __future__ import annotations
from datetime import date
from typing import Any, Optional
from psycopg2.extras import RealDictCursor
from db import get_connection
from services.audit import log_audit
from services.initiatives import get_initiative
from services.roadmap import create_roadmap_item, list_roadmap_items_for_initiative
WORK_CYCLE_TYPE = "work_cycle"
OPEN_CYCLE_STATUSES = frozenset({"planned", "active", "at_risk"})
def _serialize_cycle(item: dict[str, Any]) -> dict[str, Any]:
return {
"id": item["id"],
"initiative_id": item.get("initiative_id"),
"title": item["title"],
"goal_description": item.get("goal_description") or "",
"status": item["status"],
"target_date": item.get("target_date"),
"sort_order": item.get("sort_order", 0),
"item_type": item.get("item_type", WORK_CYCLE_TYPE),
}
def list_work_cycles_for_initiative(
*, tenant_id: str, initiative_id: str
) -> list[dict[str, Any]]:
items = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
return [
_serialize_cycle(item)
for item in items
if item.get("item_type") == WORK_CYCLE_TYPE
]
def get_active_work_cycle(
*, tenant_id: str, initiative_id: str
) -> Optional[dict[str, Any]]:
cycles = list_work_cycles_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
active = [c for c in cycles if c["status"] == "active"]
if not active:
return None
active.sort(key=lambda c: (c.get("sort_order", 0), c["id"]))
return active[0]
def validate_work_cycle_in_initiative(
*,
tenant_id: str,
initiative_id: str,
work_cycle_id: Optional[str],
cur=None,
) -> None:
if not work_cycle_id:
return
sql = """
SELECT ri.item_type
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
"""
params = (work_cycle_id, tenant_id, initiative_id)
if cur is not None:
cur.execute(sql, params)
row = cur.fetchone()
else:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cursor:
cursor.execute(sql, params)
row = cursor.fetchone()
finally:
conn.close()
if not row:
raise ValueError("Zeitbox gehört nicht zu diesem Vorhaben")
item_type = row["item_type"] if isinstance(row, dict) else row[0]
if item_type != WORK_CYCLE_TYPE:
raise ValueError("work_cycle_id muss auf RoadmapItem(type=work_cycle) verweisen")
def create_work_cycle(
*,
tenant_id: str,
initiative_id: str,
title: str,
goal_description: str = "",
status: str = "planned",
target_date: Optional[date] = None,
sort_order: int = 0,
user_id: Optional[str] = None,
) -> dict[str, Any]:
if status == "reached":
raise ValueError("Status 'reached' für work_cycle über complete-Endpoint")
item = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title=title,
item_type="work_cycle",
goal_description=goal_description,
status=status, # type: ignore[arg-type]
target_date=target_date,
sort_order=sort_order,
initial_criterion_title=None,
user_id=user_id,
)
return _serialize_cycle(item)
def activate_work_cycle(
*,
tenant_id: str,
initiative_id: str,
work_cycle_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
validate_work_cycle_in_initiative(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
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(
"""
UPDATE roadmap_items ri
SET status = 'planned', updated_at = NOW()
FROM roadmaps r
WHERE ri.roadmap_id = r.id
AND r.initiative_id = %s AND ri.tenant_id = %s
AND ri.item_type = %s AND ri.status = 'active'
AND ri.id <> %s
""",
(initiative_id, tenant_id, WORK_CYCLE_TYPE, work_cycle_id),
)
cur.execute(
"""
UPDATE roadmap_items
SET status = 'active', updated_at = NOW()
WHERE id = %s AND tenant_id = %s
RETURNING id, title, goal_description, status, target_date, sort_order, item_type
""",
(work_cycle_id, tenant_id),
)
row = cur.fetchone()
if not row:
raise ValueError("Zeitbox nicht gefunden")
conn.commit()
finally:
conn.close()
result = _serialize_cycle({**dict(row), "initiative_id": initiative_id})
log_audit(
"work_cycle.activated",
user_id=user_id,
tenant_id=tenant_id,
details={"work_cycle_id": work_cycle_id, "initiative_id": initiative_id},
)
return result
def complete_work_cycle(
*,
tenant_id: str,
initiative_id: str,
work_cycle_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
validate_work_cycle_in_initiative(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
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(
"""
UPDATE roadmap_items
SET status = 'reached', updated_at = NOW()
WHERE id = %s AND tenant_id = %s
AND item_type = %s
AND status IN ('planned', 'active', 'at_risk')
RETURNING id, title, goal_description, status, target_date, sort_order, item_type
""",
(work_cycle_id, tenant_id, WORK_CYCLE_TYPE),
)
row = cur.fetchone()
if not row:
raise ValueError("Sprint nicht gefunden oder bereits abgeschlossen")
conn.commit()
finally:
conn.close()
result = _serialize_cycle({**dict(row), "initiative_id": initiative_id})
open_count = count_actions_in_work_cycle(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
result["open_action_count_at_completion"] = open_count
log_audit(
"work_cycle.completed",
user_id=user_id,
tenant_id=tenant_id,
details={"work_cycle_id": work_cycle_id, "initiative_id": initiative_id},
)
return result
def count_actions_in_work_cycle(
*, tenant_id: str, initiative_id: str, work_cycle_id: str
) -> int:
return len(
list_open_actions_in_work_cycle(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
)
def list_open_actions_in_work_cycle(
*, tenant_id: str, initiative_id: str, work_cycle_id: str
) -> list[dict[str, Any]]:
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT id, title, status, priority, action_kind, work_cycle_id
FROM actions
WHERE tenant_id = %s AND initiative_id = %s AND work_cycle_id = %s
AND status NOT IN ('done', 'discarded')
ORDER BY sort_order ASC, title ASC
""",
(tenant_id, initiative_id, work_cycle_id),
)
rows = [dict(row) for row in cur.fetchall()]
finally:
conn.close()
for row in rows:
for key in ("id", "work_cycle_id"):
if row.get(key):
row[key] = str(row[key])
return rows
def reactivate_work_cycle(
*,
tenant_id: str,
initiative_id: str,
work_cycle_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
validate_work_cycle_in_initiative(
tenant_id=tenant_id,
initiative_id=initiative_id,
work_cycle_id=work_cycle_id,
)
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 status FROM roadmap_items
WHERE id = %s AND tenant_id = %s AND item_type = %s
""",
(work_cycle_id, tenant_id, WORK_CYCLE_TYPE),
)
row = cur.fetchone()
if not row:
raise ValueError("Sprint nicht gefunden")
if row["status"] != "reached":
raise ValueError("Nur abgeschlossene Sprints können reaktiviert werden")
cur.execute(
"""
UPDATE roadmap_items ri
SET status = 'planned', updated_at = NOW()
FROM roadmaps r
WHERE ri.roadmap_id = r.id
AND r.initiative_id = %s AND ri.tenant_id = %s
AND ri.item_type = %s AND ri.status = 'active'
AND ri.id <> %s
""",
(initiative_id, tenant_id, WORK_CYCLE_TYPE, work_cycle_id),
)
cur.execute(
"""
UPDATE roadmap_items
SET status = 'active', updated_at = NOW()
WHERE id = %s AND tenant_id = %s
AND item_type = %s AND status = 'reached'
RETURNING id, title, goal_description, status, target_date, sort_order, item_type
""",
(work_cycle_id, tenant_id, WORK_CYCLE_TYPE),
)
updated = cur.fetchone()
if not updated:
raise ValueError("Sprint konnte nicht reaktiviert werden")
conn.commit()
finally:
conn.close()
result = _serialize_cycle({**dict(updated), "initiative_id": initiative_id})
log_audit(
"work_cycle.reactivated",
user_id=user_id,
tenant_id=tenant_id,
details={"work_cycle_id": work_cycle_id, "initiative_id": initiative_id},
)
return result
+17 -2
View File
@@ -1,9 +1,15 @@
"""Adaptive Steering Core — AP1.0 Foundation."""
"""Adaptive Steering Core — AP1.0 Foundation + AP2.0 methods."""
from __future__ import annotations
from steering.hooks.registry import register_builtin_hooks
from steering.methods.registrations import generic_operating, product_milestone_driven
from steering.methods.registrations import (
ap20_method_stubs,
continuous_product,
generic_operating,
product_milestone_driven,
program_delivery,
)
from steering.strategies.next_action import register_builtin_strategies
@@ -13,6 +19,15 @@ def bootstrap_steering() -> None:
register_builtin_strategies()
generic_operating.register()
product_milestone_driven.register()
program_delivery.register()
continuous_product.register()
ap20_method_stubs.register()
from steering.lifecycle.slot_providers import register_default_slot_providers
register_default_slot_providers()
from steering.methods.registry import validate_method_registry
validate_method_registry()
bootstrap_steering()
+1
View File
@@ -0,0 +1 @@
"""Agent slot providers — K-Ext-4 / P8."""
@@ -0,0 +1,54 @@
"""Agent slots for architecture guardrail reviews at active gates."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
def resolve_guardrail_review_slots(
ctx: SteeringEvalContext,
read_models: dict[str, Any],
) -> list[dict[str, Any]]:
"""Emit guardrail slot when active gate has planning debt or open review actions."""
horizon = ctx.horizon
if horizon.kind != "gate" or not horizon.gate_roadmap_item_id:
return []
gate_id = str(horizon.gate_roadmap_item_id)
guardrail_pack = ctx.agent_slot_config.get("guardrail_pack") or "default_v0"
has_planned_guardrail = any(
review.get("status") == "planned"
and str(review.get("milestone_id") or "") == gate_id
for review in ctx.reviews
)
if has_planned_guardrail:
return []
planning_debt = read_models.get("planning_debt") or []
gate_debt = any(str(d.get("roadmap_item_id") or "") == gate_id for d in planning_debt)
open_review_actions = any(
action.get("action_kind") == "review"
and str(action.get("roadmap_item_id") or "") == gate_id
and action.get("status") in ("open", "ready", "in_progress", "review_required")
for action in ctx.actions
)
if not gate_debt and not open_review_actions:
return []
return [
{
"slot_key": "review.guardrail",
"scope_type": "roadmap_item",
"scope_id": gate_id,
"title": horizon.gate_title or "Guardrail-Review",
"summary": "Architektur-Guardrail für aktives Gate prüfen",
"actor_role_hint": "architecture_reviewer",
"payload_keys": ["checklist_id", "guardrail_pack"],
"guardrail_pack": guardrail_pack,
"priority": "normal",
"roadmap_item_id": gate_id,
}
]
@@ -0,0 +1,48 @@
"""Agent slots for due recurring elements."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from steering.eval_context import SteeringEvalContext
def _parse_due(value: Any) -> datetime | None:
if not value:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
text = str(value).replace("Z", "+00:00")
parsed = datetime.fromisoformat(text)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
except ValueError:
return None
def resolve_recurring_due_slots(ctx: SteeringEvalContext) -> list[dict[str, Any]]:
now = datetime.now(timezone.utc)
slots: list[dict[str, Any]] = []
for element in ctx.recurring_elements:
if element.get("status") != "active":
continue
due = _parse_due(element.get("next_due_at"))
if due is None or due > now:
continue
slots.append(
{
"slot_key": "recurring.due",
"scope_type": "recurring_element",
"scope_id": str(element["id"]),
"title": element.get("title") or "Rhythmus",
"summary": "Wiederkehrendes Element ist fällig",
"actor_role_hint": "operator",
"payload_keys": ["recurring_id", "interval_days"],
"priority": "normal",
"recurring_element_id": str(element["id"]),
}
)
return slots
+107
View File
@@ -0,0 +1,107 @@
"""Agent slot provider registry — K-Ext-4."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Callable
from steering.eval_context import SteeringEvalContext
AgentSlotResolve = Callable[[SteeringEvalContext, dict[str, Any], dict[str, Any]], list[dict]]
@dataclass(frozen=True)
class AgentSlotProvider:
slot_key: str
requires_elements: frozenset[str]
requires_data_slices: frozenset[str]
resolve: AgentSlotResolve
requires_any_element: frozenset[str] = field(default_factory=frozenset)
excludes_elements: frozenset[str] = field(default_factory=frozenset)
_PROVIDERS: list[AgentSlotProvider] = []
def register_agent_slot(provider: AgentSlotProvider) -> None:
_PROVIDERS.append(provider)
def _slot_enabled(ctx: SteeringEvalContext, slot_key: str) -> bool:
config = ctx.agent_slot_config
enabled = config.get("enabled_slots")
if enabled is None:
return True
return slot_key in enabled
def compute_agent_slots(
ctx: SteeringEvalContext,
*,
read_models: dict[str, Any],
proposals: dict[str, Any],
) -> list[dict[str, Any]]:
elements = ctx.steering_elements
slices = frozenset(ctx.data_slices)
slots: list[dict[str, Any]] = []
for provider in _PROVIDERS:
if not _slot_enabled(ctx, provider.slot_key):
continue
if provider.requires_elements and not provider.requires_elements <= elements:
continue
if provider.excludes_elements and provider.excludes_elements & elements:
continue
if provider.requires_any_element and not (
provider.requires_any_element & elements
):
continue
if provider.requires_data_slices and not provider.requires_data_slices <= slices:
continue
slots.extend(provider.resolve(ctx, read_models, proposals))
for slot in slots:
slot.setdefault("data_source", "steering_kernel")
slot.setdefault("initiative_id", ctx.initiative_id)
slot.setdefault("context_refs", ["steering_snapshot", "operating_context"])
slots.sort(
key=lambda s: {"high": 0, "normal": 1, "low": 2}.get(s.get("priority", "normal"), 9)
)
return slots
def _register_builtin_agent_slots() -> None:
from steering.agent_slots.guardrail_review import resolve_guardrail_review_slots
from steering.agent_slots.recurring_due import resolve_recurring_due_slots
from steering.agent_slots.review_due import resolve_review_due_slots
register_agent_slot(
AgentSlotProvider(
slot_key="review.due",
requires_elements=frozenset(),
requires_data_slices=frozenset({"reviews"}),
resolve=lambda ctx, read_models, proposals: resolve_review_due_slots(ctx),
)
)
register_agent_slot(
AgentSlotProvider(
slot_key="recurring.due",
requires_elements=frozenset({"recurring_rhythm"}),
requires_data_slices=frozenset({"recurring"}),
resolve=lambda ctx, read_models, proposals: resolve_recurring_due_slots(ctx),
)
)
register_agent_slot(
AgentSlotProvider(
slot_key="review.guardrail",
requires_elements=frozenset({"gate_fulfillment"}),
requires_data_slices=frozenset({"reviews", "roadmap"}),
resolve=lambda ctx, read_models, proposals: resolve_guardrail_review_slots(
ctx, read_models
),
)
)
_register_builtin_agent_slots()
@@ -0,0 +1,54 @@
"""Agent slots for due planned reviews."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from steering.eval_context import SteeringEvalContext
def _parse_due(value: Any) -> datetime | None:
if not value:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
text = str(value).replace("Z", "+00:00")
parsed = datetime.fromisoformat(text)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
except ValueError:
return None
def resolve_review_due_slots(ctx: SteeringEvalContext) -> list[dict[str, Any]]:
now = datetime.now(timezone.utc)
slots: list[dict[str, Any]] = []
for review in ctx.reviews:
if review.get("status") != "planned":
continue
due = _parse_due(review.get("due_at"))
if due is None or due > now:
continue
slots.append(
{
"slot_key": "review.due",
"scope_type": "review",
"scope_id": str(review["id"]),
"title": review.get("title") or "Review",
"summary": "Geplantes Review ist fällig",
"actor_role_hint": "reviewer",
"payload_keys": ["review_id", "checklist_id"],
"priority": "high" if due < now else "normal",
"review_id": str(review["id"]),
"action_id": (
str(review["action_id"]) if review.get("action_id") else None
),
"milestone_id": (
str(review["milestone_id"]) if review.get("milestone_id") else None
),
}
)
return slots
+1
View File
@@ -0,0 +1 @@
"""Attention contributors — K-Ext-2."""
+109
View File
@@ -0,0 +1,109 @@
"""Attention evaluation context — shared caches for contributors."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from steering.eval_context import SteeringEvalContext
from steering.kernel.models import HorizonMarker, SteeringBinding
from tenant_context import TenantContext
@dataclass
class AttentionEvalContext:
tenant_ctx: TenantContext
initiative_id: str
binding: SteeringBinding
horizon: HorizonMarker
next_work: list[dict[str, Any]]
read_models: dict[str, Any]
proposals: dict[str, Any]
eval_ctx: SteeringEvalContext | None = None
_actions: list[dict[str, Any]] | None = field(default=None, repr=False)
_blockers: list[dict[str, Any]] | None = field(default=None, repr=False)
_roadmap_items: list[dict[str, Any]] | None = field(default=None, repr=False)
_dependencies: list[dict[str, Any]] | None = field(default=None, repr=False)
_graph_state: dict[str, Any] | None = field(default=None, repr=False)
_gate_scope: str | None = field(default=None, repr=False)
@property
def steering_elements(self) -> frozenset[str]:
if self.eval_ctx:
return self.eval_ctx.steering_elements
return frozenset()
@property
def actions(self) -> list[dict[str, Any]]:
if self._actions is None:
if self.eval_ctx:
self._actions = self.eval_ctx.actions
else:
from services import actions as action_service
self._actions = action_service.list_actions_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._actions
@property
def blockers(self) -> list[dict[str, Any]]:
if self._blockers is None:
from services import blockers as blocker_service
self._blockers = blocker_service.list_blockers_for_initiative(
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
)
return self._blockers
@property
def roadmap_items(self) -> list[dict[str, Any]]:
if self._roadmap_items is None:
from services import roadmap as roadmap_service
self._roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
)
return self._roadmap_items
@property
def gate_scope(self) -> str | None:
if self._gate_scope is None:
from steering.strategies.next_action.execution_ready import (
gate_horizon_scope_for_method,
)
self._gate_scope = gate_horizon_scope_for_method(
self.binding.primary_method_key,
self.tenant_ctx,
self.initiative_id,
)
return self._gate_scope
@property
def dependencies(self) -> list[dict[str, Any]]:
if self._dependencies is None:
from services.execution_plan import list_dependencies_for_initiative
self._dependencies = list_dependencies_for_initiative(
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
)
return self._dependencies
@property
def graph_state(self) -> dict[str, Any]:
if self._graph_state is None:
cached = self.read_models.get("execution_graph")
if cached is not None:
self._graph_state = cached
else:
from steering.graph.execution_engine import compute_execution_graph_state
self._graph_state = compute_execution_graph_state(
actions=self.actions,
dependencies=self.dependencies,
scope_roadmap_item_id=self.gate_scope,
)
return self._graph_state
@@ -0,0 +1 @@
"""Attention contributors package."""
@@ -0,0 +1,62 @@
"""Core attention contributors — blockers, blocked actions."""
from __future__ import annotations
from steering.attention.context import AttentionEvalContext
from steering.attention.contributors.registry import (
AttentionContributor,
register_attention_contributor,
)
def _open_blockers(ctx: AttentionEvalContext) -> list[dict]:
items: list[dict] = []
for blocker in ctx.blockers:
if blocker.get("status") not in ("open", "in_progress"):
continue
items.append(
{
"kind": "open_blocker",
"severity": "warning",
"title": blocker.get("title") or "Blocker",
"summary": "Offener Blocker im Vorhaben",
"scope_type": "blocker",
"scope_id": str(blocker["id"]),
"initiative_id": ctx.initiative_id,
"action_id": (
str(blocker["action_id"]) if blocker.get("action_id") else None
),
"blocker_id": str(blocker["id"]),
"reason_code": "path_blocked",
}
)
return items
def _blocked_actions(ctx: AttentionEvalContext) -> list[dict]:
items: list[dict] = []
for action in ctx.actions:
if action.get("status") != "blocked":
continue
items.append(
{
"kind": "blocked_action",
"severity": "critical",
"title": action.get("title") or "Arbeitspaket",
"summary": "Maßnahme ist blockiert",
"scope_type": "action",
"scope_id": str(action["id"]),
"initiative_id": ctx.initiative_id,
"action_id": str(action["id"]),
"reason_code": "path_blocked",
}
)
return items
register_attention_contributor(
AttentionContributor(key="open_blockers", contribute=_open_blockers)
)
register_attention_contributor(
AttentionContributor(key="blocked_actions", contribute=_blocked_actions)
)
@@ -0,0 +1,105 @@
"""Gate / execution graph attention — planning_debt, execution_waiting."""
from __future__ import annotations
from steering.attention.context import AttentionEvalContext
from steering.attention.contributors.registry import (
AttentionContributor,
register_attention_contributor,
)
from steering.graph.execution_engine import (
execution_waiting_to_attention_items,
planning_debt_to_attention_items,
)
_GATE_METHODS = frozenset(
{"sequential_dependency", "program_delivery", "maturity_progression"}
)
def _planning_debt(ctx: AttentionEvalContext) -> list[dict]:
if ctx.binding.primary_method_key not in _GATE_METHODS:
return []
debts = ctx.read_models.get("planning_debt")
if debts is None:
from steering.graph.execution_engine import compute_planning_debt
gate_scope = ctx.gate_scope
scoped_roadmap = ctx.roadmap_items
scoped_actions = ctx.actions
if gate_scope:
scoped_roadmap = [
ri for ri in ctx.roadmap_items if str(ri.get("id")) == str(gate_scope)
]
scoped_actions = [
a
for a in ctx.actions
if a.get("roadmap_item_id")
and str(a["roadmap_item_id"]) == str(gate_scope)
]
debts = compute_planning_debt(
actions=scoped_actions, roadmap_items=scoped_roadmap
)
return planning_debt_to_attention_items(
initiative_id=ctx.initiative_id, debts=debts or []
)
def _execution_waiting(ctx: AttentionEvalContext) -> list[dict]:
if "critical_path" not in ctx.steering_elements and "gate_fulfillment" not in ctx.steering_elements:
return []
return execution_waiting_to_attention_items(
initiative_id=ctx.initiative_id,
actions=ctx.actions,
graph_state=ctx.graph_state,
)
def _horizon_no_ready_work(ctx: AttentionEvalContext) -> list[dict]:
if ctx.next_work:
return []
if ctx.binding.primary_method_key not in _GATE_METHODS:
return []
if ctx.horizon.kind != "gate":
return []
debts = ctx.read_models.get("planning_debt") or []
has_planning = len(debts) > 0
has_waiting = bool(ctx.graph_state.get("blocked_actions"))
if not has_planning and not has_waiting and not ctx.graph_state.get("ready_actions"):
return [
{
"kind": "initiative_without_next_action",
"severity": "info",
"title": ctx.horizon.gate_title or "Aktiver Horizont",
"summary": "Keine ausführungsbereite Arbeit im aktiven Horizont",
"scope_type": "milestone",
"scope_id": ctx.horizon.gate_roadmap_item_id,
"initiative_id": ctx.initiative_id,
"reason_code": "horizon_no_ready_work",
}
]
return []
register_attention_contributor(
AttentionContributor(
key="planning_debt",
requires_elements=frozenset({"gate_fulfillment"}),
contribute=_planning_debt,
)
)
register_attention_contributor(
AttentionContributor(
key="execution_waiting",
requires_any_element=frozenset({"critical_path", "gate_fulfillment"}),
contribute=_execution_waiting,
)
)
register_attention_contributor(
AttentionContributor(
key="horizon_no_ready_work",
requires_elements=frozenset({"gate_fulfillment"}),
contribute=_horizon_no_ready_work,
)
)
@@ -0,0 +1,80 @@
"""Read-model / proposal derived attention."""
from __future__ import annotations
from steering.attention.context import AttentionEvalContext
from steering.attention.contributors.registry import (
AttentionContributor,
register_attention_contributor,
)
from steering.proposals.gate_next_actions import gate_next_actions_attention_items
from steering.proposals.intake_triage import intake_triage_attention_items
from steering.proposals.sprint_commit import sprint_commit_attention_items
from steering.read_models.epic_rollup import epic_rollup_attention_items
def _epic_rollup(ctx: AttentionEvalContext) -> list[dict]:
rollups = ctx.read_models.get("epic_rollup")
if not rollups:
return []
return epic_rollup_attention_items(
initiative_id=ctx.initiative_id, rollups=rollups
)
def _sprint_commit(ctx: AttentionEvalContext) -> list[dict]:
proposals = ctx.proposals.get("sprint_commit")
if not proposals:
return []
return sprint_commit_attention_items(
initiative_id=ctx.initiative_id,
proposals=proposals,
actions=ctx.actions,
)
def _gate_next_actions(ctx: AttentionEvalContext) -> list[dict]:
proposals = ctx.proposals.get("gate_next_actions")
if not proposals:
return []
return gate_next_actions_attention_items(
initiative_id=ctx.initiative_id, proposals=proposals
)
def _intake_triage(ctx: AttentionEvalContext) -> list[dict]:
proposals = ctx.proposals.get("intake_triage")
if not proposals:
return []
return intake_triage_attention_items(
initiative_id=ctx.initiative_id, proposals=proposals
)
register_attention_contributor(
AttentionContributor(
key="epic_rollup",
requires_elements=frozenset({"backlog_epic_hierarchy"}),
contribute=_epic_rollup,
)
)
register_attention_contributor(
AttentionContributor(
key="sprint_commit",
requires_elements=frozenset({"work_cycle_scope"}),
contribute=_sprint_commit,
)
)
register_attention_contributor(
AttentionContributor(
key="gate_next_actions",
requires_elements=frozenset({"gate_fulfillment"}),
contribute=_gate_next_actions,
)
)
register_attention_contributor(
AttentionContributor(
key="intake_triage",
contribute=_intake_triage,
)
)
@@ -0,0 +1,59 @@
"""Attention contributor registry — K-Ext-2."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable
from steering.attention.context import AttentionEvalContext
AttentionContribute = Callable[[AttentionEvalContext], list[dict]]
@dataclass(frozen=True)
class AttentionContributor:
key: str
requires_elements: frozenset[str] = field(default_factory=frozenset)
requires_any_element: frozenset[str] = field(default_factory=frozenset)
requires_primary_methods: frozenset[str] = field(default_factory=frozenset)
contribute: AttentionContribute = lambda _ctx: []
_CONTRIBUTORS: list[AttentionContributor] = []
def register_attention_contributor(contributor: AttentionContributor) -> None:
_CONTRIBUTORS.append(contributor)
def collect_attention_items(ctx: AttentionEvalContext) -> list[dict]:
elements = ctx.steering_elements
primary = ctx.binding.primary_method_key
items: list[dict] = []
for contributor in _CONTRIBUTORS:
if (
contributor.requires_elements
and not contributor.requires_elements <= elements
):
continue
if contributor.requires_any_element and not (
contributor.requires_any_element & elements
):
continue
if (
contributor.requires_primary_methods
and primary not in contributor.requires_primary_methods
):
continue
items.extend(contributor.contribute(ctx))
for item in items:
item.setdefault("data_source", "steering_kernel")
items.sort(
key=lambda x: {"critical": 0, "warning": 1, "info": 2}.get(
x.get("severity", "info"), 9
)
)
return items
@@ -0,0 +1,148 @@
"""Attention contributors for reviews, recurring, tech debt."""
from __future__ import annotations
from datetime import datetime, timezone
from steering.attention.context import AttentionEvalContext
from steering.attention.contributors.registry import (
AttentionContributor,
register_attention_contributor,
)
def _parse_due(value) -> datetime | None:
if not value:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
text = str(value).replace("Z", "+00:00")
parsed = datetime.fromisoformat(text)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
except ValueError:
return None
def _reviews_due(ctx: AttentionEvalContext) -> list[dict]:
if not ctx.eval_ctx or "reviews" not in ctx.eval_ctx.data_slices:
return []
now = datetime.now(timezone.utc)
items: list[dict] = []
for review in ctx.eval_ctx.reviews:
if review.get("status") != "planned":
continue
due = _parse_due(review.get("due_at"))
if due is None or due > now:
continue
items.append(
{
"kind": "review_due",
"severity": "warning",
"title": review.get("title") or "Review",
"summary": "Review fällig",
"scope_type": "review",
"scope_id": str(review["id"]),
"initiative_id": ctx.initiative_id,
"review_id": str(review["id"]),
"reason_code": "review_due",
}
)
return items
def _recurring_due(ctx: AttentionEvalContext) -> list[dict]:
if not ctx.eval_ctx or "recurring" not in ctx.eval_ctx.data_slices:
return []
now = datetime.now(timezone.utc)
items: list[dict] = []
for element in ctx.eval_ctx.recurring_elements:
if element.get("status") != "active":
continue
due = _parse_due(element.get("next_due_at"))
if due is None or due > now:
continue
items.append(
{
"kind": "recurring_due",
"severity": "info",
"title": element.get("title") or "Rhythmus",
"summary": "Wiederkehrendes Element fällig",
"scope_type": "recurring_element",
"scope_id": str(element["id"]),
"initiative_id": ctx.initiative_id,
"recurring_element_id": str(element["id"]),
"reason_code": "recurring_due",
}
)
return items
def _action_review_required(ctx: AttentionEvalContext) -> list[dict]:
if not ctx.eval_ctx or "reviews" not in ctx.eval_ctx.data_slices:
return []
planned_by_action = {
str(review["action_id"])
for review in ctx.eval_ctx.reviews
if review.get("status") == "planned" and review.get("action_id")
}
items: list[dict] = []
for action in ctx.actions:
if action.get("status") != "review_required":
continue
action_id = str(action["id"])
if action_id in planned_by_action:
continue
items.append(
{
"kind": "action_review_required",
"severity": "warning",
"title": action.get("title") or "Arbeitspaket",
"summary": "Maßnahme wartet auf Review — kein geplantes Review verknüpft",
"scope_type": "action",
"scope_id": action_id,
"initiative_id": ctx.initiative_id,
"action_id": action_id,
"reason_code": "action_review_required_no_review",
}
)
return items
def _architecture_debt_stale(ctx: AttentionEvalContext) -> list[dict]:
summary = ctx.read_models.get("tech_debt_summary") or {}
if not summary.get("enabled") or not summary.get("stale_count"):
return []
return [
{
"kind": "architecture_debt_stale",
"severity": "warning",
"title": "Technische Schuld",
"summary": (
f"{summary['stale_count']} offene Schuld-Einträge älter als "
f"{summary.get('stale_days', 30)} Tage ohne Fortschritt"
),
"scope_type": "initiative",
"scope_id": ctx.initiative_id,
"initiative_id": ctx.initiative_id,
"reason_code": "architecture_debt_stale",
}
]
register_attention_contributor(
AttentionContributor(key="review_due", contribute=_reviews_due)
)
register_attention_contributor(
AttentionContributor(
key="recurring_due",
requires_elements=frozenset({"recurring_rhythm"}),
contribute=_recurring_due,
)
)
register_attention_contributor(
AttentionContributor(key="action_review_required", contribute=_action_review_required)
)
register_attention_contributor(
AttentionContributor(key="architecture_debt_stale", contribute=_architecture_debt_stale)
)
+98
View File
@@ -0,0 +1,98 @@
"""Profilgebundenes Backlog-Vokabular — ADP P3 / AP2.4 Methoden-Vertrag."""
from __future__ import annotations
from typing import Any
_EMPTY: dict[str, Any] = {
"profile_key": "none",
"kinds": [],
"labels": {},
"default_kind": "story",
"epic_hierarchy": False,
"convertible_kinds": [],
"capabilities": {
"sprint_commit": False,
"epic_hierarchy": False,
},
}
_AGILE_INTAKE: dict[str, Any] = {
"profile_key": "agile_intake",
"kinds": ["epic", "story", "bug", "issue", "tech_debt"],
"labels": {
"epic": "Epic",
"story": "Story",
"bug": "Bug",
"issue": "Issue",
"tech_debt": "Technische Schuld",
},
"default_kind": "story",
"epic_hierarchy": True,
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
}
_CONTINUOUS_INTAKE: dict[str, Any] = {
"profile_key": "continuous_intake",
"kinds": ["story", "bug", "issue", "tech_debt"],
"labels": {
"story": "Idee",
"bug": "Bug",
"issue": "Störung",
"tech_debt": "Technische Schuld",
},
"default_kind": "story",
"epic_hierarchy": False,
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
}
_STANDARD_INTAKE: dict[str, Any] = {
"profile_key": "standard_intake",
"kinds": ["story", "bug", "issue", "tech_debt"],
"labels": {
"story": "Story",
"bug": "Bug",
"issue": "Issue",
"tech_debt": "Technische Schuld",
},
"default_kind": "story",
"epic_hierarchy": False,
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
}
def _with_capabilities(
vocabulary: dict[str, Any],
*,
steering_elements: frozenset[str],
) -> dict[str, Any]:
result = dict(vocabulary)
sprint_commit = "work_cycle_scope" in steering_elements
epic_hierarchy = "backlog_epic_hierarchy" in steering_elements
result["epic_hierarchy"] = epic_hierarchy
result["capabilities"] = {
"sprint_commit": sprint_commit,
"epic_hierarchy": epic_hierarchy,
}
return result
def resolve_backlog_vocabulary(
*,
data_slices: list[str],
method_key: str,
steering_elements: frozenset[str],
) -> dict[str, Any]:
"""Backlog-Typen/Labels aus effektivem Methoden-Vertrag — nicht aus Page-Ifs."""
if "backlog" not in data_slices:
return dict(_EMPTY)
if "backlog_epic_hierarchy" in steering_elements:
return _with_capabilities(dict(_AGILE_INTAKE), steering_elements=steering_elements)
if method_key == "continuous_product":
return _with_capabilities(
dict(_CONTINUOUS_INTAKE), steering_elements=steering_elements
)
return _with_capabilities(dict(_STANDARD_INTAKE), steering_elements=steering_elements)
+13
View File
@@ -22,10 +22,23 @@ def get_steering_context_dto(
initiative_id=initiative_id,
)
method = get_method(row["method_key"])
metadata = row.get("lifecycle_metadata") or {}
if isinstance(metadata, str):
metadata = {}
method_profile_key = metadata.get("method_profile_key")
method_profile_label = None
if method_profile_key:
from method_profiles.registry import get_method_profile
profile = get_method_profile(method_profile_key)
if profile:
method_profile_label = profile.get("label")
return {
**row,
"lifecycle_label": lifecycle_label(row["lifecycle_state"]),
"method_label": method.label if method else row["method_key"],
"method_profile_key": method_profile_key,
"method_profile_label": method_profile_label,
}
+36
View File
@@ -0,0 +1,36 @@
"""Effective method contract — primary + composition modifier (AP2.4)."""
from __future__ import annotations
from steering.methods.registry import get_method
PLAN_PHASE_MODIFIER_KEY = "agile_iteration"
def resolve_effective_steering_elements(
primary_method_key: str,
*,
data_slices: list[str],
active_composition_modifier: str | None,
) -> frozenset[str]:
"""
Primärmethode + aktiver Modifier; Plan-Phase: agile_iteration wenn work_cycles
Slice aktiv und Methode komponierbar (Epic-Planung vor aktivem Sprint).
"""
primary = get_method(primary_method_key)
elements: set[str] = set(primary.steering_elements if primary else [])
modifier_keys: list[str] = []
if active_composition_modifier:
modifier_keys.append(active_composition_modifier)
elif "work_cycles" in data_slices:
agile = get_method(PLAN_PHASE_MODIFIER_KEY)
if agile and primary_method_key in agile.composes_with:
modifier_keys.append(PLAN_PHASE_MODIFIER_KEY)
for modifier_key in modifier_keys:
modifier = get_method(modifier_key)
if modifier:
elements.update(modifier.steering_elements)
return frozenset(elements)
+15
View File
@@ -0,0 +1,15 @@
"""Steering element catalog — AP2.4."""
from steering.elements.registry import (
STEERING_ELEMENTS,
get_steering_element,
list_steering_elements,
validate_steering_element_keys,
)
__all__ = [
"STEERING_ELEMENTS",
"get_steering_element",
"list_steering_elements",
"validate_steering_element_keys",
]
+96
View File
@@ -0,0 +1,96 @@
"""Steering element catalog — AP2.4."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
ModeKey = Literal["plan", "work", "control"]
@dataclass(frozen=True)
class SteeringElementDefinition:
key: str
label: str
description: str
modes: tuple[ModeKey, ...]
STEERING_ELEMENTS: dict[str, SteeringElementDefinition] = {
"next_action_primary": SteeringElementDefinition(
key="next_action_primary",
label="Nächster Schritt",
description="Next-Action-Widget als primäre Steuerungsansicht",
modes=("control", "work"),
),
"critical_path": SteeringElementDefinition(
key="critical_path",
label="Kritischer Pfad",
description="Execution-Graph und Pfad-Priorisierung",
modes=("control",),
),
"gate_fulfillment": SteeringElementDefinition(
key="gate_fulfillment",
label="Gate-Erfüllung",
description="Zielzustände, Verify und Fortschritt",
modes=("control", "plan"),
),
"work_cycle_scope": SteeringElementDefinition(
key="work_cycle_scope",
label="Sprint-Zeitbox",
description="Aktive work_cycle und Sprint-Backlog",
modes=("work", "plan"),
),
"backlog_epic_hierarchy": SteeringElementDefinition(
key="backlog_epic_hierarchy",
label="Epic-Hierarchie",
description="Epic-Container und Story-Baum im Plan-Eingang (Agile-Modifier)",
modes=("plan",),
),
"recurring_rhythm": SteeringElementDefinition(
key="recurring_rhythm",
label="Rhythmen",
description="RecurringElement und Journey-Fokus",
modes=("control",),
),
"queue_inbox": SteeringElementDefinition(
key="queue_inbox",
label="Queue / Eingang",
description="Pull-Steuerung aus Backlog/Queue",
modes=("plan", "work"),
),
"maturity_stage": SteeringElementDefinition(
key="maturity_stage",
label="Reifegrad-Stufen",
description="Stufen und Routinen in Plan/Kontrolle",
modes=("plan", "control"),
),
"chapter_progression": SteeringElementDefinition(
key="chapter_progression",
label="Kapitel-Fortschritt",
description="Kapitel-basierte Progression",
modes=("plan", "control"),
),
"dispute_timeline": SteeringElementDefinition(
key="dispute_timeline",
label="Verfahren / Fristen",
description="Fristen, Entscheidungen, Verfahrensstrang",
modes=("control",),
),
}
def get_steering_element(key: str) -> SteeringElementDefinition | None:
return STEERING_ELEMENTS.get(key)
def list_steering_elements() -> tuple[SteeringElementDefinition, ...]:
return tuple(STEERING_ELEMENTS.values())
def validate_steering_element_keys(keys: frozenset[str]) -> None:
unknown = [k for k in keys if k not in STEERING_ELEMENTS]
if unknown:
raise ValueError(
f"Unbekannte steering_elements: {', '.join(sorted(unknown))}"
)
+124
View File
@@ -0,0 +1,124 @@
"""Shared evaluation context for steering read models and proposals (K-Ext-1)."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding
from tenant_context import TenantContext
@dataclass
class SteeringEvalContext:
"""Tenant-scoped context — lazy OM loads for extension providers."""
tenant_ctx: TenantContext
initiative_id: str
binding: SteeringBinding
horizon: HorizonMarker
lifecycle: LifecycleContext
operating_context: dict[str, Any]
_actions: list[dict[str, Any]] | None = field(default=None, repr=False)
_backlog_items: list[dict[str, Any]] | None = field(default=None, repr=False)
_work_cycles: list[dict[str, Any]] | None = field(default=None, repr=False)
_reviews: list[dict[str, Any]] | None = field(default=None, repr=False)
_recurring_elements: list[dict[str, Any]] | None = field(default=None, repr=False)
@property
def steering_elements(self) -> frozenset[str]:
return frozenset(self.operating_context.get("steering_elements") or [])
@property
def data_slices(self) -> list[str]:
return list(self.operating_context.get("data_slices") or [])
@property
def backlog_vocabulary(self) -> dict[str, Any]:
return dict(self.operating_context.get("backlog_vocabulary") or {})
@property
def agent_slot_config(self) -> dict[str, Any]:
return dict(self.operating_context.get("agent_slot_config") or {})
@property
def actions(self) -> list[dict[str, Any]]:
if self._actions is None:
from services import actions as action_service
self._actions = action_service.list_actions_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._actions
@property
def backlog_items(self) -> list[dict[str, Any]]:
if self._backlog_items is None:
from services import backlog as backlog_service
self._backlog_items = backlog_service.list_backlog_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._backlog_items
@property
def work_cycles(self) -> list[dict[str, Any]]:
if self._work_cycles is None:
from services.work_cycle import list_work_cycles_for_initiative
self._work_cycles = list_work_cycles_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._work_cycles
@property
def reviews(self) -> list[dict[str, Any]]:
if self._reviews is None:
from services.reviews import list_reviews_for_initiative
self._reviews = list_reviews_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._reviews
@property
def recurring_elements(self) -> list[dict[str, Any]]:
if self._recurring_elements is None:
from services.recurring import list_recurring_for_initiative
self._recurring_elements = list_recurring_for_initiative(
tenant_id=self.tenant_ctx.tenant_id,
initiative_id=self.initiative_id,
)
return self._recurring_elements
def build_steering_eval_context(
tenant_ctx: TenantContext,
*,
initiative_id: str,
binding: SteeringBinding,
horizon: HorizonMarker,
lifecycle: LifecycleContext,
) -> SteeringEvalContext:
from services.operating_context import get_operating_context
operating = (
get_operating_context(
tenant_id=tenant_ctx.tenant_id, initiative_id=initiative_id
)
or {}
)
return SteeringEvalContext(
tenant_ctx=tenant_ctx,
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
lifecycle=lifecycle,
operating_context=operating,
)
Loaded 100 of 473 files, more files were not shown because too many files have changed in this diff. Show more