Compare commits

...
62 Commits
Author SHA1 Message Date
LarsandCursor a05bd34af3 feat(A1): Übungen als AP mit Wochentagsplan
Deploy Development / deploy (push) Successful in 46s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 5m3s
Test Suite / lint-backend (push) Successful in 3s
Test Suite / playwright-smoke (push) Successful in 13s
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
Deploy Development / deploy (push) Successful in 49s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m57s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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
Deploy Development / deploy (push) Successful in 50s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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
Deploy Development / deploy (push) Successful in 53s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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
Deploy Development / deploy (push) Successful in 46s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 4m52s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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
Deploy Development / deploy (push) Successful in 49s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m44s
Test Suite / playwright-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 52s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / compose-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)
Deploy Development / deploy (push) Successful in 1m1s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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
Deploy Development / deploy (push) Successful in 49s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / compose-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
Deploy Development / deploy (push) Successful in 44s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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
Deploy Development / deploy (push) Successful in 46s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m41s
Test Suite / playwright-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 52s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m37s
Test Suite / playwright-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 51s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 4m32s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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
Deploy Development / deploy (push) Successful in 48s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m14s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 4m15s
Test Suite / playwright-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 46s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 4m13s
Test Suite / lint-backend (push) Successful in 3s
Test Suite / playwright-smoke (push) Successful in 12s
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
Deploy Development / deploy (push) Successful in 46s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
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)
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m13s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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 / lint-backend (push) Waiting to run
Test Suite / playwright-smoke (push) Blocked by required conditions
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 4m0s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 18s
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)
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m56s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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)
Deploy Development / deploy (push) Successful in 48s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m54s
Test Suite / lint-backend (push) Successful in 3s
Test Suite / playwright-smoke (push) Successful in 15s
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)
Deploy Development / deploy (push) Successful in 49s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m45s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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
Deploy Development / deploy (push) Successful in 46s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
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
Deploy Development / deploy (push) Successful in 50s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m50s
Test Suite / playwright-smoke (push) Has been skipped
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
Deploy Development / deploy (push) Successful in 50s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m49s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m37s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Has been cancelled
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
Deploy Development / deploy (push) Successful in 45s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / compose-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
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m33s
Test Suite / playwright-smoke (push) Has been skipped
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.
Deploy Development / deploy (push) Successful in 48s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
Test Suite / pytest-backend (push) Failing after 3m23s
Test Suite / playwright-smoke (push) Has been skipped
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.
Deploy Development / deploy (push) Successful in 45s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
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.
Deploy Development / deploy (push) Successful in 43s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 3m13s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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.
Deploy Development / deploy (push) Successful in 46s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
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.
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / pytest-backend (push) Successful in 3m10s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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.
Deploy Development / deploy (push) Successful in 46s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / compose-smoke (push) Has been skipped
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.
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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.
Deploy Development / deploy (push) Successful in 49s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / compose-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
Deploy Development / deploy (push) Has been cancelled
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
Test Suite / playwright-smoke (push) Blocked by required conditions
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.
Deploy Development / deploy (push) Successful in 49s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m57s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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 / lint-backend (push) Waiting to run
Test Suite / playwright-smoke (push) Blocked by required conditions
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.
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
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.
Deploy Development / deploy (push) Successful in 44s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m52s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 13s
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.
Deploy Development / deploy (push) Successful in 52s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m46s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Successful in 12s
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.
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m52s
Test Suite / lint-backend (push) Successful in 3s
Test Suite / playwright-smoke (push) Successful in 13s
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.
Deploy Development / deploy (push) Successful in 47s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
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.
Deploy Development / deploy (push) Successful in 48s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 18s
Test Suite / pytest-backend (push) Successful in 2m56s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / playwright-smoke (push) Has been cancelled
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
317 changed files with 30656 additions and 1102 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 Mitai-/Shinkan-Domänenlogik kopieren
- Keine parallele Steuerungslogik außerhalb `backend/steering/` - Keine parallele Steuerungslogik außerhalb `backend/steering/`
- Keine neuen OM-Tabellen ohne ADP (Scope Lock bis RoadmapItem-ADP) - 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 ## Abweichungen
@@ -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
+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 - Tenant, User, Actor, TenantContext, Auth, Capabilities
- OM-Entitäten (Backlog, Blocker, Milestone-Brücke, Evidence, Decision, Review, Recurring) - 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 - Workspace-GUI, Data Layer, Actor Directory
**Produktlich fehlt (Vision):** **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` **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` 8. `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
9. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md` 9. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
10. `.cursor/rules/kairo-architecture.mdc` 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): 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. 11. Admin- und Agentenaktionen werden auditiert.
12. Migrationen sind nummeriert und reproduzierbar. 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 ## 6. Nicht tun
@@ -155,6 +169,9 @@ Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
- kein Billing oder SSO bauen - kein Billing oder SSO bauen
- keine strategischen Produktentscheidungen eigenmächtig ändern - keine strategischen Produktentscheidungen eigenmächtig ändern
- keine Designprinzipien aus `docs/reference/` ohne Principle-Gate oder Architecture Decision in Scope ziehen - 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`. 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.
+38 -6
View File
@@ -10,12 +10,13 @@ from typing import Any, Optional
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from db import get_connection from db import get_connection
from data_layer.attention import get_next_action_candidates_for_initiative
from entity_archetypes.registry import archetype_label from entity_archetypes.registry import archetype_label
from method_profiles.registry import get_method_profile from method_profiles.registry import get_method_profile
from steering.context import get_steering_context_dto from steering.context import get_steering_context_dto
from steering.kernel import evaluate_steering
from steering.signals.snapshot_signals import derive_initiative_signals from steering.signals.snapshot_signals import derive_initiative_signals
from services.initiatives import get_initiative from services.initiatives import get_initiative
from services.progression_graph import compute_progression_state
from tenant_context import TenantContext from tenant_context import TenantContext
OPEN_BLOCKER = ("open", "in_progress") OPEN_BLOCKER = ("open", "in_progress")
@@ -125,7 +126,8 @@ def get_initiative_steering_snapshot(
cur.execute( 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 FROM backlog_items
WHERE tenant_id = %s AND initiative_id = %s WHERE tenant_id = %s AND initiative_id = %s
ORDER BY updated_at DESC ORDER BY updated_at DESC
@@ -293,9 +295,11 @@ def get_initiative_steering_snapshot(
key=lambda m: (m["target_date"] is None, m["target_date"] or ""), key=lambda m: (m["target_date"] is None, m["target_date"] or ""),
)[:5] )[:5]
next_actions = get_next_action_candidates_for_initiative( evaluation = evaluate_steering(ctx, initiative_id=initiative_id, next_work_limit=5)
ctx, initiative_id=initiative_id, 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) steering = get_steering_context_dto(ctx, initiative_id=initiative_id)
metadata = steering.get("lifecycle_metadata") or {} metadata = steering.get("lifecycle_metadata") or {}
@@ -335,12 +339,35 @@ def get_initiative_steering_snapshot(
signals=signals, signals=signals,
method_key=steering["method_key"], method_key=steering["method_key"],
), ),
"attention_items": _attention_items(signals), "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, "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_milestones": upcoming_milestones,
"upcoming_roadmap_items": upcoming_milestones, "upcoming_roadmap_items": upcoming_milestones,
"next_actions": next_actions, "next_actions": next_actions,
"active_work_cycle": active_work_cycle, "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": { "counts": {
"actions_open": open_actions, "actions_open": open_actions,
"actions_blocked": blocked_actions, "actions_blocked": blocked_actions,
@@ -357,6 +384,9 @@ def get_initiative_steering_snapshot(
"actions": actions, "actions": actions,
"roadmap_items": roadmap_items, "roadmap_items": roadmap_items,
"milestones": roadmap_items, "milestones": roadmap_items,
"progression_state": compute_progression_state(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
),
"initiative_level": { "initiative_level": {
"blockers": unlinked_blockers, "blockers": unlinked_blockers,
"evidence": unlinked_evidence, "evidence": unlinked_evidence,
@@ -370,6 +400,8 @@ def get_initiative_steering_snapshot(
"id": _sid(b["id"]), "id": _sid(b["id"]),
"title": b["title"], "title": b["title"],
"status": b["status"], "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")), "converted_action_id": _sid(b.get("converted_action_id")),
} }
for b in backlog for b in backlog
+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,
)
+14 -1
View File
@@ -7,6 +7,7 @@ from typing import Any, Optional
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from db import get_connection 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) # initiative suffix → default method (shared by initiative + project mirror)
_METHOD_BY_SUFFIX: dict[str, str] = { _METHOD_BY_SUFFIX: dict[str, str] = {
@@ -70,15 +71,18 @@ def _build_specs() -> tuple[dict[str, Any], ...]:
specs: list[dict[str, Any]] = [] specs: list[dict[str, Any]] = []
for suffix, label, description in _INITIATIVE_SPEC_META: for suffix, label, description in _INITIATIVE_SPEC_META:
method = _METHOD_BY_SUFFIX[suffix] method = _METHOD_BY_SUFFIX[suffix]
initiative_key = f"initiative.{suffix}"
ui_profile = INITIATIVE_UI_PROFILES.get(initiative_key, {})
specs.append( specs.append(
{ {
"key": f"initiative.{suffix}", "key": initiative_key,
"entity_type": "initiative", "entity_type": "initiative",
"label": label, "label": label,
"description": description, "description": description,
"is_system": True, "is_system": True,
"default_method_key": method, "default_method_key": method,
"default_method_profile_key": None, "default_method_profile_key": None,
"ui_profile_json": ui_profile,
} }
) )
specs.append( specs.append(
@@ -90,6 +94,7 @@ def _build_specs() -> tuple[dict[str, Any], ...]:
"is_system": True, "is_system": True,
"default_method_key": method, "default_method_key": method,
"default_method_profile_key": None, "default_method_profile_key": None,
"ui_profile_json": {},
} }
) )
return tuple(specs) return tuple(specs)
@@ -189,6 +194,14 @@ def resolve_default_method_key(archetype_key: str) -> str:
return spec.get("default_method_key", "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: def mirror_project_archetype_key(initiative_archetype_key: str) -> str:
if initiative_archetype_key.startswith("initiative."): if initiative_archetype_key.startswith("initiative."):
suffix = initiative_archetype_key[len("initiative.") :] suffix = initiative_archetype_key[len("initiative.") :]
+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
+6 -2
View File
@@ -14,17 +14,20 @@ def sync_entity_field_registry_to_db() -> int:
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
for archetype in ENTITY_ARCHETYPES: for archetype in ENTITY_ARCHETYPES:
ui_profile = archetype.get("ui_profile_json") or {}
cur.execute( cur.execute(
""" """
INSERT INTO entity_archetypes ( INSERT INTO entity_archetypes (
archetype_key, entity_type, label, description, is_system archetype_key, entity_type, label, description, is_system,
ui_profile_json
) )
VALUES (%s, %s, %s, %s, %s) VALUES (%s, %s, %s, %s, %s, %s::jsonb)
ON CONFLICT (archetype_key) DO UPDATE SET ON CONFLICT (archetype_key) DO UPDATE SET
entity_type = EXCLUDED.entity_type, entity_type = EXCLUDED.entity_type,
label = EXCLUDED.label, label = EXCLUDED.label,
description = EXCLUDED.description, description = EXCLUDED.description,
is_system = EXCLUDED.is_system, is_system = EXCLUDED.is_system,
ui_profile_json = EXCLUDED.ui_profile_json,
updated_at = NOW() updated_at = NOW()
""", """,
( (
@@ -33,6 +36,7 @@ def sync_entity_field_registry_to_db() -> int:
archetype["label"], archetype["label"],
archetype["description"], archetype["description"],
archetype["is_system"], archetype["is_system"],
json.dumps(ui_profile),
), ),
) )
+10
View File
@@ -39,6 +39,16 @@ METHOD_PROFILES: tuple[dict[str, Any], ...] = (
"default_actor_setup": "po_plus_vibe_coder", "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} _PROFILE_INDEX = {item["key"]: item for item in METHOD_PROFILES}
@@ -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 $$;
+68 -1
View File
@@ -9,7 +9,9 @@ from capabilities import require_capability
from data_layer import actions as dl_actions from data_layer import actions as dl_actions
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from schemas.schedule_payload import SchedulePayload
from services import actions as action_service from services import actions as action_service
from services import scheduled_work as scheduled_work_service
from services import tasks as task_service from services import tasks as task_service
from tenant_context import TenantContext from tenant_context import TenantContext
@@ -30,9 +32,11 @@ class ActionUpdateRequest(BaseModel):
roadmap_item_id: Optional[str] = None roadmap_item_id: Optional[str] = None
clear_roadmap_item: bool = False clear_roadmap_item: bool = False
sort_order: Optional[int] = None sort_order: Optional[int] = None
action_kind: Optional[Literal["delivery", "planning", "review"]] = None action_kind: Optional[Literal["delivery", "planning", "review", "bug", "issue"]] = None
work_cycle_id: Optional[str] = None work_cycle_id: Optional[str] = None
clear_work_cycle: bool = False clear_work_cycle: bool = False
parent_action_id: Optional[str] = None
clear_parent_action: bool = False
class TaskCreateRequest(BaseModel): class TaskCreateRequest(BaseModel):
@@ -143,6 +147,8 @@ def update_action(
clear_work_cycle=body.clear_work_cycle, clear_work_cycle=body.clear_work_cycle,
sort_order=body.sort_order, sort_order=body.sort_order,
action_kind=body.action_kind, action_kind=body.action_kind,
parent_action_id=body.parent_action_id,
clear_parent_action=body.clear_parent_action,
) )
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -151,6 +157,47 @@ def update_action(
return item 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") @router.put("/{action_id}/assignments")
def set_action_assignments( def set_action_assignments(
action_id: str, action_id: str,
@@ -171,6 +218,26 @@ def set_action_assignments(
return item 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) @router.delete("/{action_id}", status_code=204)
def delete_action( def delete_action(
action_id: str, action_id: str,
+22 -5
View File
@@ -20,6 +20,9 @@ class BacklogCreateRequest(BaseModel):
priority: Literal["low", "normal", "high"] = "normal" priority: Literal["low", "normal", "high"] = "normal"
roadmap_item_id: Optional[str] = None roadmap_item_id: Optional[str] = None
sort_order: Optional[int] = 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): class BacklogUpdateRequest(BaseModel):
@@ -30,6 +33,11 @@ class BacklogUpdateRequest(BaseModel):
roadmap_item_id: Optional[str] = None roadmap_item_id: Optional[str] = None
clear_roadmap_item: bool = False clear_roadmap_item: bool = False
sort_order: Optional[int] = None 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): class BacklogConvertRequest(BaseModel):
@@ -69,6 +77,11 @@ def update_backlog_item(
roadmap_item_id=body.roadmap_item_id, roadmap_item_id=body.roadmap_item_id,
clear_roadmap_item=body.clear_roadmap_item, clear_roadmap_item=body.clear_roadmap_item,
sort_order=body.sort_order, 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: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -82,11 +95,15 @@ def delete_backlog_item(
backlog_item_id: str, backlog_item_id: str,
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")), ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
): ):
if not backlog_service.delete_backlog_item( try:
tenant_id=ctx.tenant_id, deleted = backlog_service.delete_backlog_item(
backlog_item_id=backlog_item_id, tenant_id=ctx.tenant_id,
user_id=ctx.user_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") raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
+25 -1
View File
@@ -21,6 +21,7 @@ from services import blockers as blocker_service
from services import decisions as decision_service from services import decisions as decision_service
from services import evidence as evidence_service from services import evidence as evidence_service
from services import initiatives as initiative_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 milestones as milestone_service
from services import recurring as recurring_service from services import recurring as recurring_service
from services import reviews as review_service from services import reviews as review_service
@@ -70,7 +71,8 @@ class ActionCreateRequest(BaseModel):
work_cycle_id: Optional[str] = None work_cycle_id: Optional[str] = None
assigned_actor_ids: list[str] = Field(default_factory=list) assigned_actor_ids: list[str] = Field(default_factory=list)
sort_order: int = 0 sort_order: int = 0
action_kind: Literal["delivery", "planning", "review"] = "delivery" action_kind: Literal["delivery", "planning", "review", "bug", "issue"] = "delivery"
parent_action_id: Optional[str] = None
class BlockerCreateRequest(BaseModel): class BlockerCreateRequest(BaseModel):
@@ -87,6 +89,9 @@ class BacklogCreateRequest(BaseModel):
status: Literal["new", "triaged", "accepted", "rejected"] = "new" status: Literal["new", "triaged", "accepted", "rejected"] = "new"
priority: Literal["low", "normal", "high"] = "normal" priority: Literal["low", "normal", "high"] = "normal"
roadmap_item_id: Optional[str] = None 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): class MilestoneCreateRequest(BaseModel):
@@ -127,6 +132,7 @@ class RecurringCreateRequest(BaseModel):
status: Literal["active", "paused", "ended"] = "active" status: Literal["active", "paused", "ended"] = "active"
interval_days: Optional[int] = Field(default=None, gt=0) interval_days: Optional[int] = Field(default=None, gt=0)
next_due_at: Optional[str] = None next_due_at: Optional[str] = None
roadmap_item_id: Optional[str] = None
def _parse_optional_datetime(value: Optional[str], field_name: str) -> Optional[datetime]: def _parse_optional_datetime(value: Optional[str], field_name: str) -> Optional[datetime]:
@@ -210,6 +216,19 @@ def get_initiative_steering_context(
return get_steering_context_dto(ctx, initiative_id=initiative_id) 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: def _require_initiative(*, tenant_id: str, initiative_id: str) -> dict:
initiative = initiative_service.get_initiative( initiative = initiative_service.get_initiative(
tenant_id=tenant_id, initiative_id=initiative_id tenant_id=tenant_id, initiative_id=initiative_id
@@ -339,6 +358,7 @@ def create_initiative_action(
assigned_actor_ids=body.assigned_actor_ids, assigned_actor_ids=body.assigned_actor_ids,
sort_order=body.sort_order, sort_order=body.sort_order,
action_kind=body.action_kind, action_kind=body.action_kind,
parent_action_id=body.parent_action_id,
user_id=ctx.user_id, user_id=ctx.user_id,
) )
except ValueError as exc: except ValueError as exc:
@@ -418,6 +438,9 @@ def create_initiative_backlog_item(
status=body.status, status=body.status,
priority=body.priority, priority=body.priority,
roadmap_item_id=body.roadmap_item_id, 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, user_id=ctx.user_id,
) )
except ValueError as exc: except ValueError as exc:
@@ -626,6 +649,7 @@ def create_initiative_recurring(
status=body.status, status=body.status,
interval_days=body.interval_days, interval_days=body.interval_days,
next_due_at=next_due_at, next_due_at=next_due_at,
roadmap_item_id=body.roadmap_item_id,
user_id=ctx.user_id, user_id=ctx.user_id,
) )
except ValueError as exc: except ValueError as exc:
+118
View File
@@ -14,6 +14,7 @@ from services import backlog as backlog_service
from services import blockers as blocker_service from services import blockers as blocker_service
from services import decisions as decision_service from services import decisions as decision_service
from services import evidence as evidence_service from services import evidence as evidence_service
from services import recurring as recurring_service
from services.audit import log_audit from services.audit import log_audit
from tenant_context import TenantContext from tenant_context import TenantContext
@@ -74,6 +75,21 @@ class BacklogProposalBody(BaseModel):
roadmap_item_id: Optional[str] = None 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") @router.get("/me")
def operational_me(ctx: TenantContext = Depends(require_operational_capability("kairo.action.read"))): def operational_me(ctx: TenantContext = Depends(require_operational_capability("kairo.action.read"))):
return _ok( return _ok(
@@ -309,3 +325,105 @@ def operational_backlog_proposal(
raise HTTPException(status_code=404, detail=detail) from exc raise HTTPException(status_code=404, detail=detail) from exc
raise HTTPException(status_code=400, detail=detail) from exc raise HTTPException(status_code=400, detail=detail) from exc
return _ok(ctx, item) 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 capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from schemas.schedule_payload import SchedulePayload
from services import recurring as recurring_service from services import recurring as recurring_service
from tenant_context import TenantContext from tenant_context import TenantContext
@@ -22,6 +23,13 @@ class RecurringUpdateRequest(BaseModel):
clear_interval_days: bool = False clear_interval_days: bool = False
next_due_at: Optional[str] = None next_due_at: Optional[str] = None
clear_next_due_at: bool = False 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]: def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
@@ -53,6 +61,7 @@ def update_recurring_element(
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")), 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 next_due_at = _parse_datetime(body.next_due_at) if body.next_due_at is not None else None
sched = body.schedule
try: try:
item = recurring_service.update_recurring_element( item = recurring_service.update_recurring_element(
tenant_id=ctx.tenant_id, tenant_id=ctx.tenant_id,
@@ -61,10 +70,16 @@ def update_recurring_element(
title=body.title, title=body.title,
description=body.description, description=body.description,
status=body.status, 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, clear_interval_days=body.clear_interval_days,
next_due_at=next_due_at, next_due_at=next_due_at,
clear_next_due_at=body.clear_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: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -73,6 +88,29 @@ def update_recurring_element(
return item 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) @router.delete("/{recurring_id}", status_code=204)
def delete_recurring_element( def delete_recurring_element(
recurring_id: str, recurring_id: str,
+106 -5
View File
@@ -8,6 +8,7 @@ from typing import Any, Literal, Optional
from capabilities import require_capability from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from schemas.schedule_payload import SchedulePayload
from services import roadmap as roadmap_service from services import roadmap as roadmap_service
from services import roadmap_criteria as criteria_service from services import roadmap_criteria as criteria_service
from services import roadmap_plan_snapshot as snapshot_service from services import roadmap_plan_snapshot as snapshot_service
@@ -18,7 +19,7 @@ router = APIRouter(tags=["roadmap"])
class RoadmapItemCreateRequest(BaseModel): class RoadmapItemCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=255) title: str = Field(min_length=1, max_length=255)
item_type: Literal["milestone", "review_gate", "maturity_stage", "work_cycle"] = "milestone" item_type: Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"] = "milestone"
goal_description: str = "" goal_description: str = ""
definition_of_done: list[Any] = Field(default_factory=list) definition_of_done: list[Any] = Field(default_factory=list)
status: Literal[ status: Literal[
@@ -27,12 +28,13 @@ class RoadmapItemCreateRequest(BaseModel):
sequencing_mode: Literal["sequential", "parallel", "optional"] = "sequential" sequencing_mode: Literal["sequential", "parallel", "optional"] = "sequential"
target_date: Optional[date] = None target_date: Optional[date] = None
sort_order: int = 0 sort_order: int = 0
strand_project_id: Optional[str] = None
initial_criterion_title: Optional[str] = Field(default=None, max_length=500) initial_criterion_title: Optional[str] = Field(default=None, max_length=500)
class RoadmapItemUpdateRequest(BaseModel): class RoadmapItemUpdateRequest(BaseModel):
title: Optional[str] = Field(default=None, min_length=1, max_length=255) title: Optional[str] = Field(default=None, min_length=1, max_length=255)
item_type: Optional[Literal["milestone", "review_gate", "maturity_stage", "work_cycle"]] = None item_type: Optional[Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]] = None
goal_description: Optional[str] = None goal_description: Optional[str] = None
definition_of_done: Optional[list[Any]] = None definition_of_done: Optional[list[Any]] = None
status: Optional[ status: Optional[
@@ -42,6 +44,8 @@ class RoadmapItemUpdateRequest(BaseModel):
target_date: Optional[date] = None target_date: Optional[date] = None
clear_target_date: bool = False clear_target_date: bool = False
sort_order: Optional[int] = None sort_order: Optional[int] = None
strand_project_id: Optional[str] = None
clear_strand_project: bool = False
class DependencyCreateRequest(BaseModel): class DependencyCreateRequest(BaseModel):
@@ -84,6 +88,14 @@ class ReopenRequest(BaseModel):
reason: str = "" 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): class PlanSnapshotCreateRequest(BaseModel):
reason: str = Field(default="", max_length=2000) reason: str = Field(default="", max_length=2000)
@@ -166,6 +178,21 @@ def get_initiative_roadmap_graph_state(
raise HTTPException(status_code=400, detail=str(exc)) from 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") @initiative_router.get("/{initiative_id}/roadmap/plan-ist-view")
def get_initiative_plan_ist_view( def get_initiative_plan_ist_view(
initiative_id: str, initiative_id: str,
@@ -228,6 +255,7 @@ def create_initiative_roadmap_item(
sequencing_mode=body.sequencing_mode, sequencing_mode=body.sequencing_mode,
target_date=body.target_date, target_date=body.target_date,
sort_order=body.sort_order, sort_order=body.sort_order,
strand_project_id=body.strand_project_id,
initial_criterion_title=body.initial_criterion_title, initial_criterion_title=body.initial_criterion_title,
) )
except ValueError as exc: except ValueError as exc:
@@ -265,6 +293,8 @@ def update_roadmap_item(
target_date=body.target_date, target_date=body.target_date,
clear_target_date=body.clear_target_date, clear_target_date=body.clear_target_date,
sort_order=body.sort_order, sort_order=body.sort_order,
strand_project_id=body.strand_project_id,
clear_strand_project=body.clear_strand_project,
) )
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -278,12 +308,83 @@ def delete_roadmap_item(
item_id: str, item_id: str,
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")), ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
): ):
if not roadmap_service.delete_roadmap_item( try:
tenant_id=ctx.tenant_id, item_id=item_id, user_id=ctx.user_id 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") 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") @items_router.post("/{item_id}/verify-reached")
def verify_roadmap_item_reached( def verify_roadmap_item_reached(
item_id: str, item_id: str,
+27 -8
View File
@@ -1,4 +1,4 @@
"""Steering API — methods, profiles and context (AP1.1 / AP2.0).""" """Steering API — methods, profiles and context (AP1.1 / AP2.0 / AP2.4)."""
from __future__ import annotations from __future__ import annotations
@@ -7,11 +7,16 @@ from typing import Optional
from capabilities import require_capability from capabilities import require_capability
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field 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 method_profiles.registry import list_method_profiles
from services import initiatives as initiative_service from services import initiatives as initiative_service
from services import steering_context as sc_service from services import steering_context as sc_service
from steering.context import get_steering_context_dto 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 from tenant_context import TenantContext
router = APIRouter(prefix="/api/steering", tags=["steering"]) router = APIRouter(prefix="/api/steering", tags=["steering"])
@@ -23,20 +28,34 @@ class SteeringContextUpdateRequest(BaseModel):
clear_method_profile: bool = False 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") @router.get("/methods")
def list_steering_methods( def list_steering_methods(
archetype_key: Optional[str] = Query(default=None),
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")), ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
): ):
_ = ctx _ = 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 [ return [
{ {
"key": m.key, **method_to_dict(m),
"version": m.version, "is_default": m.key == default_key if default_key else False,
"label": m.label,
"description": m.description,
"next_action_strategy_key": m.next_action_strategy_key,
} }
for m in list_methods() for m in methods
] ]
+61
View File
@@ -85,6 +85,67 @@ def create_work_cycle(
raise HTTPException(status_code=400, 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") @initiative_router.post("/{work_cycle_id}/activate")
def activate_work_cycle( def activate_work_cycle(
initiative_id: str, initiative_id: str,
+14
View File
@@ -9,6 +9,7 @@ from data_layer import actions as dl_actions
from data_layer import actors as dl_actors from data_layer import actors as dl_actors
from data_layer import attention as dl_attention from data_layer import attention as dl_attention
from data_layer import initiatives as dl_initiatives 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 data_layer import workspace as dl_workspace
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -96,6 +97,19 @@ def workspace_next_actions(
return dl_attention.get_next_action_candidates(ctx, limit=limit or 10) 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") @router.post("/portfolio/reorder")
def workspace_portfolio_reorder( def workspace_portfolio_reorder(
body: PortfolioReorderRequest, body: PortfolioReorderRequest,
+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)
+234 -7
View File
@@ -25,16 +25,31 @@ OPEN_ACTION_STATUSES = frozenset(
) )
_ACTION_COLUMNS = """ _ACTION_COLUMNS = """
id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, title, description, id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, schedule_id,
status, priority, due_at, sort_order, action_kind, created_at, updated_at title, description, status, priority, due_at, sort_order, action_kind, parent_action_id,
created_at, updated_at
""" """
ACTION_KINDS = frozenset({"delivery", "planning", "review"}) 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]: def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row) result = dict(row)
for key in ("id", "tenant_id", "initiative_id", "project_id", "roadmap_item_id", "work_cycle_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): if result.get(key):
result[key] = str(result[key]) result[key] = str(result[key])
if result.get("created_at"): if result.get("created_at"):
@@ -46,6 +61,44 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
return result 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: def _validate_action_kind(action_kind: str) -> None:
if action_kind not in ACTION_KINDS: if action_kind not in ACTION_KINDS:
raise ValueError(f"Ungültiger action_kind: {action_kind}") raise ValueError(f"Ungültiger action_kind: {action_kind}")
@@ -149,6 +202,7 @@ def create_action(
assigned_actor_ids: Optional[list[str]] = None, assigned_actor_ids: Optional[list[str]] = None,
sort_order: int = 0, sort_order: int = 0,
action_kind: str = "delivery", action_kind: str = "delivery",
parent_action_id: Optional[str] = None,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
title = title.strip() title = title.strip()
@@ -183,13 +237,20 @@ def create_action(
work_cycle_id=work_cycle_id, work_cycle_id=work_cycle_id,
cur=cur, 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( cur.execute(
f""" f"""
INSERT INTO actions ( INSERT INTO actions (
tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id,
title, description, status, priority, due_at, sort_order, action_kind title, description, status, priority, due_at, sort_order, action_kind,
parent_action_id
) )
VALUES (%s, %s, %s, %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} RETURNING {_ACTION_COLUMNS}
""", """,
( (
@@ -205,6 +266,7 @@ def create_action(
due_at, due_at,
sort_order, sort_order,
action_kind, action_kind,
parent_action_id,
), ),
) )
row = _serialize_row(dict(cur.fetchone())) row = _serialize_row(dict(cur.fetchone()))
@@ -277,7 +339,10 @@ def get_action(*, tenant_id: str, action_id: str) -> Optional[dict[str, Any]]:
action = _serialize_row(dict(row)) action = _serialize_row(dict(row))
finally: finally:
conn.close() 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( def update_action(
@@ -299,6 +364,8 @@ def update_action(
clear_work_cycle: bool = False, clear_work_cycle: bool = False,
sort_order: Optional[int] = None, sort_order: Optional[int] = None,
action_kind: Optional[str] = None, action_kind: Optional[str] = None,
parent_action_id: Optional[str] = None,
clear_parent_action: bool = False,
) -> Optional[dict[str, Any]]: ) -> Optional[dict[str, Any]]:
existing = get_action(tenant_id=tenant_id, action_id=action_id) existing = get_action(tenant_id=tenant_id, action_id=action_id)
if not existing: if not existing:
@@ -373,6 +440,11 @@ def update_action(
_validate_action_kind(action_kind) _validate_action_kind(action_kind)
updates.append("action_kind = %s") updates.append("action_kind = %s")
params.append(action_kind) 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: if not updates:
return existing return existing
@@ -383,6 +455,14 @@ def update_action(
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: 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( cur.execute(
f""" f"""
UPDATE actions UPDATE actions
@@ -419,6 +499,20 @@ def update_action(
"to_status": status, "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 return result
@@ -533,3 +627,136 @@ def list_open_actions_for_actor(
finally: finally:
conn.close() conn.close()
return _attach_assignments(actions, tenant_id=tenant_id) 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}
+2
View File
@@ -26,6 +26,8 @@ DEFAULT_AGENT_CAPABILITIES: tuple[str, ...] = (
"kairo.backlog.manage", "kairo.backlog.manage",
"kairo.decision.read", "kairo.decision.read",
"kairo.decision.manage", "kairo.decision.manage",
"kairo.recurring.read",
"kairo.recurring.manage",
) )
ALLOWED_TOKEN_CAPABILITIES = frozenset(DEFAULT_AGENT_CAPABILITIES) ALLOWED_TOKEN_CAPABILITIES = frozenset(DEFAULT_AGENT_CAPABILITIES)
+183 -16
View File
@@ -22,7 +22,7 @@ _GUIDANCE: dict[str, str] = {
"Aktuelle Stufe und heutige Übung steuern deinen nächsten Schritt." "Aktuelle Stufe und heutige Übung steuern deinen nächsten Schritt."
), ),
"initiative.linear_project": ( "initiative.linear_project": (
"Nächster Schritt am kritischen Pfad — Abhängigkeiten im Plan-Graph." "Kritischer Pfad und Abhängigkeiten steuern Next — nicht die Gesamtliste."
), ),
"initiative.product": ( "initiative.product": (
"Eingang triagieren, dann committete Actions — optional Sprint-Zeitbox (B3)." "Eingang triagieren, dann committete Actions — optional Sprint-Zeitbox (B3)."
@@ -34,7 +34,7 @@ _GUIDANCE: dict[str, str] = {
_PROFILE_HINTS: dict[str, list[str]] = { _PROFILE_HINTS: dict[str, list[str]] = {
"initiative.maturity_journey": ["maturity.karate_kumite"], "initiative.maturity_journey": ["maturity.karate_kumite"],
"initiative.linear_project": [], "initiative.linear_project": ["project.agile_iteration"],
"initiative.product": ["product.kairo_dev"], "initiative.product": ["product.kairo_dev"],
"initiative.program": [], "initiative.program": [],
} }
@@ -65,7 +65,8 @@ def get_starter_preview(
{"kind": "maturity_stage", "title": "Stufe 2 — Aufbau", "status": "planned"}, {"kind": "maturity_stage", "title": "Stufe 2 — Aufbau", "status": "planned"},
{"kind": "maturity_stage", "title": "Stufe 3 — Ziel", "status": "planned"}, {"kind": "maturity_stage", "title": "Stufe 3 — Ziel", "status": "planned"},
{"kind": "project", "title": "Training"}, {"kind": "project", "title": "Training"},
{"kind": "recurring", "title": "Tägliche Übung"}, {"kind": "recurring", "title": "Vorbeuge-Dehnung"},
{"kind": "recurring", "title": "Hüftöffner (Schmetterling)"},
] ]
elif archetype_key == "initiative.linear_project": elif archetype_key == "initiative.linear_project":
items = [ items = [
@@ -75,6 +76,7 @@ def get_starter_preview(
{"kind": "milestone", "title": "G4 — Abschluss", "status": "planned"}, {"kind": "milestone", "title": "G4 — Abschluss", "status": "planned"},
{"kind": "project", "title": "Hauptpfad"}, {"kind": "project", "title": "Hauptpfad"},
{"kind": "project", "title": "Begleitung"}, {"kind": "project", "title": "Begleitung"},
{"kind": "action", "title": "Erster Schritt — Planung konkretisieren"},
] ]
elif archetype_key == "initiative.product": elif archetype_key == "initiative.product":
items = [ items = [
@@ -128,6 +130,7 @@ def apply_starter_kit(
"projects": [], "projects": [],
"recurring": [], "recurring": [],
"backlog_items": [], "backlog_items": [],
"actions": [],
} }
if archetype_key == "initiative.maturity_journey": if archetype_key == "initiative.maturity_journey":
@@ -183,7 +186,6 @@ def _apply_a1(
user_id: Optional[str], user_id: Optional[str],
) -> dict[str, list[str]]: ) -> dict[str, list[str]]:
from services.projects import create_project, list_projects_for_initiative from services.projects import create_project, list_projects_for_initiative
from services.recurring import create_recurring_element, list_recurring_for_initiative
from services.roadmap import create_roadmap_item from services.roadmap import create_roadmap_item
roadmap_ids: list[str] = [] roadmap_ids: list[str] = []
@@ -192,6 +194,7 @@ def _apply_a1(
("Stufe 2 — Aufbau", "planned"), ("Stufe 2 — Aufbau", "planned"),
("Stufe 3 — Ziel", "planned"), ("Stufe 3 — Ziel", "planned"),
] ]
stage_items: list[dict[str, Any]] = []
for index, (title, status) in enumerate(stage_defs): for index, (title, status) in enumerate(stage_defs):
item = create_roadmap_item( item = create_roadmap_item(
tenant_id=tenant_id, tenant_id=tenant_id,
@@ -203,6 +206,7 @@ def _apply_a1(
user_id=user_id, user_id=user_id,
) )
roadmap_ids.append(item["id"]) roadmap_ids.append(item["id"])
stage_items.append(item)
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id) projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
if not _find_by_title(projects, "Training"): if not _find_by_title(projects, "Training"):
@@ -215,19 +219,20 @@ def _apply_a1(
user_id=user_id, user_id=user_id,
) )
recurring = list_recurring_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id) from services.maturity_practice import seed_practices_for_stage
if not _find_by_title(recurring, "Tägliche Übung"):
create_recurring_element(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Tägliche Übung",
description="Regelmäßige Übung für die aktuelle Reifegrad-Stufe",
interval_days=1,
next_due_at=datetime.now(timezone.utc),
user_id=user_id,
)
return {"roadmap_items": roadmap_ids, "projects": ["Training"], "recurring": ["Tägliche Übung"]} 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( def _apply_a2(
@@ -282,9 +287,171 @@ def _apply_a2(
user_id=user_id, 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 { return {
"roadmap_items": gate_ids, "roadmap_items": gate_ids,
"projects": ["Hauptpfad", "Begleitung"], "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"]],
} }
+1 -1
View File
@@ -23,7 +23,7 @@ def log_audit(
INSERT INTO audit_log (action, user_id, tenant_id, details) INSERT INTO audit_log (action, user_id, tenant_id, details)
VALUES (%s, %s, %s, %s::jsonb) 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() conn.commit()
finally: finally:
+231 -4
View File
@@ -10,21 +10,34 @@ from db import get_connection
from services.actions import create_action from services.actions import create_action
from services.audit import log_audit from services.audit import log_audit
from services.initiatives import PRIORITIES, get_initiative 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 from services.plan_ist import validate_roadmap_item_in_initiative
BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"] BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"]
BacklogItemKind = Literal["story", "bug", "issue", "epic", "tech_debt"]
BACKLOG_STATUSES = frozenset({"new", "triaged", "accepted", "rejected", "converted"}) 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 = """ _BACKLOG_COLUMNS = """
id, tenant_id, initiative_id, title, description, status, id, tenant_id, initiative_id, title, description, status,
priority, roadmap_item_id, converted_action_id, sort_order, 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]: def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row) 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): if result.get(key):
result[key] = str(result[key]) result[key] = str(result[key])
if result.get("created_at"): if result.get("created_at"):
@@ -44,6 +57,117 @@ def _validate_priority(priority: str) -> None:
raise ValueError(f"Ungültige Priorität: {priority}") 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( def create_backlog_item(
*, *,
tenant_id: str, tenant_id: str,
@@ -54,6 +178,9 @@ def create_backlog_item(
priority: str = "normal", priority: str = "normal",
roadmap_item_id: Optional[str] = None, roadmap_item_id: Optional[str] = None,
sort_order: Optional[int] = 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, user_id: Optional[str] = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
title = title.strip() title = title.strip()
@@ -61,6 +188,10 @@ def create_backlog_item(
raise ValueError("Titel ist erforderlich") raise ValueError("Titel ist erforderlich")
_validate_status(status) _validate_status(status)
_validate_priority(priority) _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): if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden") raise ValueError("Initiative nicht gefunden")
@@ -73,6 +204,21 @@ def create_backlog_item(
initiative_id=initiative_id, initiative_id=initiative_id,
roadmap_item_id=roadmap_item_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( cur.execute(
""" """
SELECT COALESCE(MAX(sort_order), -10) + 10 AS next_order SELECT COALESCE(MAX(sort_order), -10) + 10 AS next_order
@@ -86,9 +232,9 @@ def create_backlog_item(
f""" f"""
INSERT INTO backlog_items ( INSERT INTO backlog_items (
tenant_id, initiative_id, title, description, status, priority, tenant_id, initiative_id, title, description, status, priority,
roadmap_item_id, sort_order roadmap_item_id, sort_order, item_kind, parent_action_id, parent_backlog_id
) )
VALUES (%s, %s, %s, %s, %s, %s, %s, %s) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING {_BACKLOG_COLUMNS} RETURNING {_BACKLOG_COLUMNS}
""", """,
( (
@@ -100,6 +246,9 @@ def create_backlog_item(
priority, priority,
roadmap_item_id, roadmap_item_id,
sort_order if sort_order is not None else next_order, 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())) row = _serialize_row(dict(cur.fetchone()))
@@ -167,6 +316,11 @@ def update_backlog_item(
roadmap_item_id: Optional[str] = None, roadmap_item_id: Optional[str] = None,
clear_roadmap_item: bool = False, clear_roadmap_item: bool = False,
sort_order: Optional[int] = None, 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]]: ) -> Optional[dict[str, Any]]:
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id) existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
if not existing: if not existing:
@@ -214,16 +368,71 @@ def update_backlog_item(
if sort_order is not None: if sort_order is not None:
updates.append("sort_order = %s") updates.append("sort_order = %s")
params.append(sort_order) 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: if not updates:
return existing 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()") updates.append("updated_at = NOW()")
params.extend([backlog_item_id, tenant_id]) params.extend([backlog_item_id, tenant_id])
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: 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( cur.execute(
f""" f"""
UPDATE backlog_items UPDATE backlog_items
@@ -270,6 +479,18 @@ def delete_backlog_item(
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor() as cur: 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( cur.execute(
"DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id", "DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id",
(backlog_item_id, tenant_id), (backlog_item_id, tenant_id),
@@ -306,6 +527,10 @@ def convert_backlog_to_action(
if existing["status"] not in ("accepted", "triaged", "new"): if existing["status"] not in ("accepted", "triaged", "new"):
raise ValueError("Backlog-Item kann in diesem Status nicht konvertiert werden") 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 resolved_cycle_id = work_cycle_id
if not resolved_cycle_id and assign_active_sprint: if not resolved_cycle_id and assign_active_sprint:
from services.work_cycle import get_active_work_cycle from services.work_cycle import get_active_work_cycle
@@ -325,6 +550,8 @@ def convert_backlog_to_action(
roadmap_item_id=existing.get("roadmap_item_id"), roadmap_item_id=existing.get("roadmap_item_id"),
work_cycle_id=resolved_cycle_id, work_cycle_id=resolved_cycle_id,
assigned_actor_ids=assigned_actor_ids or [], 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, 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
+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],
}
+26 -69
View File
@@ -1,17 +1,9 @@
"""AP2.0e — Recurring transition when a maturity_stage is reached.""" """AP2.0e — maturity stage transition on verify reached (delegates to progression_graph)."""
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Optional from typing import Any, Optional
from services.recurring import (
create_recurring_element,
list_recurring_for_initiative,
update_recurring_element,
)
from services.roadmap import get_roadmap_item, list_roadmap_items_for_initiative, update_roadmap_item
def on_maturity_stage_reached( def on_maturity_stage_reached(
*, *,
@@ -20,68 +12,33 @@ def on_maturity_stage_reached(
reached_item_id: str, reached_item_id: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> Optional[dict[str, Any]]: ) -> Optional[dict[str, Any]]:
"""Pause old routines, activate next stage, seed new routine for next stage.""" from services.progression_graph import on_work_gate_reached
item = get_roadmap_item(tenant_id=tenant_id, item_id=reached_item_id)
if not item or item.get("item_type") != "maturity_stage":
return None
stages = [ return on_work_gate_reached(
s tenant_id=tenant_id,
for s in list_roadmap_items_for_initiative( initiative_id=initiative_id,
tenant_id=tenant_id, initiative_id=initiative_id reached_item_id=reached_item_id,
) user_id=user_id,
if s.get("item_type") == "maturity_stage"
]
stages.sort(key=lambda s: (s.get("sort_order", 0), s.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
paused: list[str] = [] def on_maturity_stage_reopened(
for recurring in list_recurring_for_initiative( *,
tenant_id=tenant_id, initiative_id=initiative_id tenant_id: str,
): initiative_id: str,
if recurring.get("status") == "active": stage_id: str,
update_recurring_element( user_id: Optional[str] = None,
tenant_id=tenant_id, ) -> dict[str, Any]:
recurring_id=recurring["id"], """Re-enable exercise set for reopened stage; pause others on same strand."""
status="paused", from services.maturity_practice import activate_stage_practice_set
user_id=user_id, from services.roadmap import get_roadmap_item
)
paused.append(recurring["title"])
created_recurring = None stage = get_roadmap_item(tenant_id=tenant_id, item_id=stage_id)
if next_stage: if not stage:
update_roadmap_item( return {"stage_id": stage_id, "active_practices": []}
tenant_id=tenant_id, return activate_stage_practice_set(
item_id=next_stage["id"], tenant_id=tenant_id,
status="active", initiative_id=initiative_id,
user_id=user_id, stage=stage,
) user_id=user_id,
created_recurring = create_recurring_element( )
tenant_id=tenant_id,
initiative_id=initiative_id,
title=f"Übung — {next_stage['title']}",
description=f"Routine für {next_stage['title']} (automatisch nach Stufenübergang)",
status="active",
interval_days=1,
next_due_at=datetime.now(timezone.utc),
user_id=user_id,
)
return {
"reached_stage_id": reached_item_id,
"next_stage_id": next_stage["id"] if next_stage else None,
"paused_recurring": paused,
"new_recurring_id": created_recurring["id"] if created_recurring else None,
}
+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, user_id=user_id,
) )
if initiative_id and user_id: if initiative_id and user_id:
from steering.lifecycle.orchestrator import transition from services.steering_events import emit_steering_event
transition( emit_steering_event(
None,
initiative_id,
"action_selection",
reason="blocker_resolved",
tenant_id=tenant_id, tenant_id=tenant_id,
initiative_id=initiative_id,
event_kind="situational",
payload={"reason": "blocker_resolved", "blocker_id": blocker_id},
user_id=user_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,
}
+137 -11
View File
@@ -2,7 +2,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import datetime, timezone
from typing import Any, Literal, Optional from typing import Any, Literal, Optional
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
@@ -16,14 +16,14 @@ RecurringStatus = Literal["active", "paused", "ended"]
RECURRING_STATUSES = frozenset({"active", "paused", "ended"}) RECURRING_STATUSES = frozenset({"active", "paused", "ended"})
_RECURRING_COLUMNS = """ _RECURRING_COLUMNS = """
id, tenant_id, initiative_id, title, description, status, id, tenant_id, initiative_id, roadmap_item_id, project_id, action_id, schedule_id,
interval_days, next_due_at, created_at, updated_at title, description, status, interval_days, next_due_at, created_at, updated_at
""" """
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]: def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row) 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): if result.get(key):
result[key] = str(result[key]) result[key] = str(result[key])
for ts_key in ("created_at", "updated_at", "next_due_at"): for ts_key in ("created_at", "updated_at", "next_due_at"):
@@ -46,6 +46,12 @@ def create_recurring_element(
status: RecurringStatus = "active", status: RecurringStatus = "active",
interval_days: Optional[int] = None, interval_days: Optional[int] = None,
next_due_at: Optional[datetime] = 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, user_id: Optional[str] = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
title = title.strip() title = title.strip()
@@ -57,21 +63,48 @@ def create_recurring_element(
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id): if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
raise ValueError("Initiative nicht gefunden") 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() conn = get_connection()
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute( cur.execute(
f""" f"""
INSERT INTO recurring_elements ( INSERT INTO recurring_elements (
tenant_id, initiative_id, title, description, status, tenant_id, initiative_id, roadmap_item_id, project_id, schedule_id,
interval_days, next_due_at 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} RETURNING {_RECURRING_COLUMNS}
""", """,
( (
tenant_id, tenant_id,
initiative_id, initiative_id,
roadmap_item_id,
project_id,
schedule_id,
title, title,
description, description,
status, status,
@@ -90,6 +123,16 @@ def create_recurring_element(
tenant_id=tenant_id, tenant_id=tenant_id,
details={"recurring_id": row["id"], "initiative_id": initiative_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 return row
@@ -111,10 +154,25 @@ def list_recurring_for_initiative(
""", """,
(tenant_id, initiative_id), (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: finally:
conn.close() 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( def get_recurring_element(
*, tenant_id: str, recurring_id: str *, tenant_id: str, recurring_id: str
@@ -131,10 +189,17 @@ def get_recurring_element(
(recurring_id, tenant_id), (recurring_id, tenant_id),
) )
row = cur.fetchone() row = cur.fetchone()
return _serialize_row(dict(row)) if row else None if not row:
return None
result = _serialize_row(dict(row))
finally: finally:
conn.close() 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( def update_recurring_element(
*, *,
@@ -148,6 +213,14 @@ def update_recurring_element(
clear_interval_days: bool = False, clear_interval_days: bool = False,
next_due_at: Optional[datetime] = None, next_due_at: Optional[datetime] = None,
clear_next_due_at: bool = False, 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]]: ) -> Optional[dict[str, Any]]:
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id) existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
if not existing: if not existing:
@@ -182,8 +255,50 @@ def update_recurring_element(
elif next_due_at is not None: elif next_due_at is not None:
updates.append("next_due_at = %s") updates.append("next_due_at = %s")
params.append(next_due_at) 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 return existing
updates.append("updated_at = NOW()") updates.append("updated_at = NOW()")
@@ -226,7 +341,7 @@ def update_recurring_element(
"to_status": status, "to_status": status,
}, },
) )
return result return get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id) or result
def delete_recurring_element( def delete_recurring_element(
@@ -235,6 +350,17 @@ def delete_recurring_element(
recurring_id: str, recurring_id: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> bool: ) -> 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() conn = get_connection()
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
+110 -12
View File
@@ -13,14 +13,14 @@ from services.audit import log_audit
from services.initiatives import get_initiative from services.initiatives import get_initiative
from services.roadmap_criteria import create_default_criterion, prepare_criteria_for_verify from services.roadmap_criteria import create_default_criterion, prepare_criteria_for_verify
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage", "work_cycle"] RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]
RoadmapItemStatus = Literal[ RoadmapItemStatus = Literal[
"planned", "active", "at_risk", "reached", "moved", "discarded" "planned", "active", "at_risk", "reached", "moved", "discarded"
] ]
SequencingMode = Literal["sequential", "parallel", "optional"] SequencingMode = Literal["sequential", "parallel", "optional"]
DependencyType = Literal["requires", "blocks", "related", "parallel_group", "optional_branch"] DependencyType = Literal["requires", "blocks", "related", "parallel_group", "optional_branch"]
ROADMAP_ITEM_TYPES = frozenset({"milestone", "review_gate", "maturity_stage", "work_cycle"}) ROADMAP_ITEM_TYPES = frozenset({"milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"})
ROADMAP_ITEM_STATUSES = frozenset( ROADMAP_ITEM_STATUSES = frozenset(
{"planned", "active", "at_risk", "reached", "moved", "discarded"} {"planned", "active", "at_risk", "reached", "moved", "discarded"}
) )
@@ -32,7 +32,7 @@ TERMINAL_STATUSES = frozenset({"reached", "moved", "discarded"})
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]: def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row) 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): if result.get(key):
result[key] = str(result[key]) result[key] = str(result[key])
if result.get("target_date"): 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.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done, ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order, ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order,
ri.strand_project_id,
ri.created_at, ri.updated_at ri.created_at, ri.updated_at
FROM roadmap_items ri FROM roadmap_items ri
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id 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.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done, ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order, ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order,
ri.strand_project_id,
ri.created_at, ri.updated_at ri.created_at, ri.updated_at
FROM roadmap_items ri FROM roadmap_items ri
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
@@ -233,6 +235,7 @@ def create_roadmap_item(
sequencing_mode: SequencingMode = "sequential", sequencing_mode: SequencingMode = "sequential",
target_date: Optional[date] = None, target_date: Optional[date] = None,
sort_order: int = 0, sort_order: int = 0,
strand_project_id: Optional[str] = None,
initial_criterion_title: Optional[str] = None, initial_criterion_title: Optional[str] = None,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
@@ -255,12 +258,13 @@ def create_roadmap_item(
""" """
INSERT INTO roadmap_items ( INSERT INTO roadmap_items (
tenant_id, roadmap_id, item_type, title, goal_description, 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, RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
definition_of_done, status, sequencing_mode, target_date, 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, tenant_id,
@@ -273,11 +277,12 @@ def create_roadmap_item(
sequencing_mode, sequencing_mode,
target_date, target_date,
sort_order, sort_order,
strand_project_id,
), ),
) )
row = _serialize_row(dict(cur.fetchone())) row = _serialize_row(dict(cur.fetchone()))
row["initiative_id"] = initiative_id row["initiative_id"] = initiative_id
if item_type != "work_cycle": if item_type not in ("work_cycle", "join_gate"):
create_default_criterion( create_default_criterion(
cur, cur,
tenant_id=tenant_id, tenant_id=tenant_id,
@@ -324,6 +329,8 @@ def update_roadmap_item(
target_date: Optional[date] = None, target_date: Optional[date] = None,
clear_target_date: bool = False, clear_target_date: bool = False,
sort_order: Optional[int] = None, sort_order: Optional[int] = None,
strand_project_id: Optional[str] = None,
clear_strand_project: bool = False,
) -> Optional[dict[str, Any]]: ) -> Optional[dict[str, Any]]:
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id) existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
if not existing: if not existing:
@@ -373,6 +380,11 @@ def update_roadmap_item(
if sort_order is not None: if sort_order is not None:
updates.append("sort_order = %s") updates.append("sort_order = %s")
params.append(sort_order) 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: if not updates:
return existing return existing
@@ -383,6 +395,20 @@ def update_roadmap_item(
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: 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( cur.execute(
f""" f"""
UPDATE roadmap_items UPDATE roadmap_items
@@ -390,7 +416,7 @@ def update_roadmap_item(
WHERE id = %s AND tenant_id = %s WHERE id = %s AND tenant_id = %s
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description, RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
definition_of_done, status, sequencing_mode, target_date, definition_of_done, status, sequencing_mode, target_date,
sort_order, created_at, updated_at sort_order, strand_project_id, created_at, updated_at
""", """,
params, params,
) )
@@ -432,6 +458,14 @@ def update_roadmap_item(
def delete_roadmap_item( def delete_roadmap_item(
*, tenant_id: str, item_id: str, user_id: Optional[str] = None *, tenant_id: str, item_id: str, user_id: Optional[str] = None
) -> bool: ) -> 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() conn = get_connection()
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
@@ -643,6 +677,10 @@ def verify_reached(
raise ValueError("RoadmapItem nicht gefunden") raise ValueError("RoadmapItem nicht gefunden")
if item["status"] in TERMINAL_STATUSES: if item["status"] in TERMINAL_STATUSES:
raise ValueError(f"RoadmapItem bereits terminal: {item['status']}") 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"] initiative_id = item["initiative_id"]
conn = get_connection() conn = get_connection()
@@ -685,7 +723,7 @@ def verify_reached(
WHERE id = %s AND tenant_id = %s WHERE id = %s AND tenant_id = %s
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description, RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
definition_of_done, status, sequencing_mode, target_date, 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), (item_id, tenant_id),
) )
@@ -709,9 +747,9 @@ def verify_reached(
details={"roadmap_item_id": item_id, "verify_reason": verify_reason}, details={"roadmap_item_id": item_id, "verify_reason": verify_reason},
) )
if row.get("item_type") == "maturity_stage": if row.get("item_type") == "maturity_stage":
from services.maturity_stage_transition import on_maturity_stage_reached from services.progression_graph import on_work_gate_reached
transition = on_maturity_stage_reached( transition = on_work_gate_reached(
tenant_id=tenant_id, tenant_id=tenant_id,
initiative_id=initiative_id, initiative_id=initiative_id,
reached_item_id=item_id, reached_item_id=item_id,
@@ -719,6 +757,27 @@ def verify_reached(
) )
if transition: if transition:
row["maturity_transition"] = 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 return row
@@ -739,6 +798,17 @@ def reopen_roadmap_item(
conn = get_connection() conn = get_connection()
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: 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( cur.execute(
""" """
UPDATE roadmap_items UPDATE roadmap_items
@@ -746,7 +816,7 @@ def reopen_roadmap_item(
WHERE id = %s AND tenant_id = %s WHERE id = %s AND tenant_id = %s
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description, RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
definition_of_done, status, sequencing_mode, target_date, 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), (item_id, tenant_id),
) )
@@ -762,6 +832,16 @@ def reopen_roadmap_item(
finally: finally:
conn.close() 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( log_audit(
"roadmap_item.reopened", "roadmap_item.reopened",
user_id=user_id, user_id=user_id,
@@ -773,4 +853,22 @@ def reopen_roadmap_item(
"to_status": "active", "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 return row
+9
View File
@@ -73,6 +73,15 @@ def _reopen_item_if_reached(
) -> None: ) -> None:
if item["status"] != "reached": if item["status"] != "reached":
return 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( cur.execute(
""" """
UPDATE roadmap_items UPDATE roadmap_items
+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
+25 -1
View File
@@ -16,6 +16,14 @@ DEFAULT_METHOD_KEY = "generic_operating"
DEFAULT_METHOD_VERSION = "0.1.0" 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]: def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
result = dict(row) result = dict(row)
for key in ("id", "tenant_id", "initiative_id"): for key in ("id", "tenant_id", "initiative_id"):
@@ -217,12 +225,28 @@ def update_method_key(
method_key: str, method_key: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> dict[str, Any]: ) -> 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) method = get_method(method_key)
if not method: if not method:
raise ValueError(f"Unbekannte Methode: {method_key}") 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) existing = get_steering_context(tenant_id=tenant_id, initiative_id=initiative_id)
if not existing: if not existing:
raise ValueError("SteeringContext nicht gefunden") raise ValueError("SteeringContext nicht gefunden")
+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,
)
+144 -3
View File
@@ -176,20 +176,161 @@ def activate_work_cycle(
return result 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( def count_actions_in_work_cycle(
*, tenant_id: str, initiative_id: str, work_cycle_id: str *, tenant_id: str, initiative_id: str, work_cycle_id: str
) -> int: ) -> 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() conn = get_connection()
try: try:
with conn.cursor() as cur: with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute( cur.execute(
""" """
SELECT COUNT(*) FROM actions 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 WHERE tenant_id = %s AND initiative_id = %s AND work_cycle_id = %s
AND status NOT IN ('done', 'discarded') AND status NOT IN ('done', 'discarded')
ORDER BY sort_order ASC, title ASC
""", """,
(tenant_id, initiative_id, work_cycle_id), (tenant_id, initiative_id, work_cycle_id),
) )
return int(cur.fetchone()[0]) rows = [dict(row) for row in cur.fetchall()]
finally: finally:
conn.close() 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
+6
View File
@@ -22,6 +22,12 @@ def bootstrap_steering() -> None:
program_delivery.register() program_delivery.register()
continuous_product.register() continuous_product.register()
ap20_method_stubs.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() 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)
+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,
)
+11 -16
View File
@@ -1,4 +1,4 @@
"""Method graph profiles — AP1.4e.""" """Method graph profiles — AP1.4e / AP2.4 (via MethodDefinition)."""
from __future__ import annotations from __future__ import annotations
@@ -19,25 +19,20 @@ _STRICT = GraphMethodProfile(enforce_gate_blocking=True, emphasize_fulfillment=F
_FULFILLMENT = GraphMethodProfile(enforce_gate_blocking=False, emphasize_fulfillment=True) _FULFILLMENT = GraphMethodProfile(enforce_gate_blocking=False, emphasize_fulfillment=True)
_LIGHT = GraphMethodProfile(enforce_gate_blocking=False, emphasize_fulfillment=False) _LIGHT = GraphMethodProfile(enforce_gate_blocking=False, emphasize_fulfillment=False)
METHOD_GRAPH_PROFILES: dict[str, GraphMethodProfile] = { STRICT = _STRICT
"generic_operating": _LIGHT, FULFILLMENT = _FULFILLMENT
"queue_pull": _LIGHT, LIGHT = _LIGHT
"dispute_procedure": _LIGHT,
"continuous_product": _FULFILLMENT,
"maturity_progression": _FULFILLMENT,
"chapter_based_progression": _FULFILLMENT,
"product_milestone_driven": _STRICT,
"program_delivery": _STRICT,
"sequential_dependency": _STRICT,
"agile_iteration": _STRICT,
"recurring_control": _FULFILLMENT,
}
def get_graph_profile(method_key: str | None) -> GraphMethodProfile: def get_graph_profile(method_key: str | None) -> GraphMethodProfile:
if not method_key: if not method_key:
return METHOD_GRAPH_PROFILES[DEFAULT_METHOD_KEY] return LIGHT
return METHOD_GRAPH_PROFILES.get(method_key, _STRICT) from steering.methods.registry import get_method
method = get_method(method_key)
if method:
return method.graph_profile
return _STRICT
def enforce_gate_blocking_for_method(method_key: str | None) -> bool: def enforce_gate_blocking_for_method(method_key: str | None) -> bool:
+18
View File
@@ -0,0 +1,18 @@
"""Steering Kernel Spine — universal runtime entry for initiative steering."""
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding, SteeringEvaluation
__all__ = [
"HorizonMarker",
"LifecycleContext",
"SteeringBinding",
"SteeringEvaluation",
"evaluate_steering",
]
def evaluate_steering(*args, **kwargs):
"""Lazy import avoids circular dependency with extension registries."""
from steering.kernel.evaluate import evaluate_steering as _evaluate
return _evaluate(*args, **kwargs)
+43
View File
@@ -0,0 +1,43 @@
"""Attention evaluation (Q5) — method- and horizon-aware for one initiative."""
from __future__ import annotations
from typing import Any
from steering.kernel.models import HorizonMarker, SteeringBinding
from tenant_context import TenantContext
# Side-effect: register contributors
import steering.attention.contributors.core # noqa: F401
import steering.attention.contributors.gates # noqa: F401
import steering.attention.contributors.read_models # noqa: F401
import steering.attention.contributors.reviews # noqa: F401
def evaluate_attention(
ctx: TenantContext,
*,
initiative_id: str,
binding: SteeringBinding,
horizon: HorizonMarker,
next_work: list[dict[str, Any]],
read_models: dict[str, Any] | None = None,
proposals: dict[str, Any] | None = None,
eval_ctx=None,
limit: int = 20,
) -> list[dict[str, Any]]:
"""Kernel attention — contributors via registry (K-Ext-2)."""
from steering.attention.context import AttentionEvalContext
from steering.attention.contributors.registry import collect_attention_items
actx = AttentionEvalContext(
tenant_ctx=ctx,
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
next_work=next_work,
read_models=read_models or {},
proposals=proposals or {},
eval_ctx=eval_ctx,
)
return collect_attention_items(actx)[:limit]
+52
View File
@@ -0,0 +1,52 @@
"""Resolve primary method and composition modifier."""
from __future__ import annotations
from services import steering_context as sc_service
from services.work_cycle import get_active_work_cycle
from steering.kernel.models import SteeringBinding
from steering.methods.registry import get_method
from steering.strategies.next_action.default_strategy import default_strategy
from tenant_context import TenantContext
_AGILE_KEY = "agile_iteration"
def resolve_primary_method_key(ctx: TenantContext, initiative_id: str) -> str:
row = sc_service.get_steering_context(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
if row:
return row["method_key"]
return "generic_operating"
def _primary_composes_with_agile(primary_method_key: str) -> bool:
agile = get_method(_AGILE_KEY)
if not agile:
return False
return primary_method_key in agile.composes_with
def resolve_steering_binding(ctx: TenantContext, initiative_id: str) -> SteeringBinding:
primary_key = resolve_primary_method_key(ctx, initiative_id)
primary = get_method(primary_key)
primary_strategy = (
primary.next_action_strategy_key if primary else default_strategy.key
)
composition: str | None = None
strategy_key = primary_strategy
active_cycle = get_active_work_cycle(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
if active_cycle and _primary_composes_with_agile(primary_key):
composition = _AGILE_KEY
strategy_key = _AGILE_KEY
return SteeringBinding(
primary_method_key=primary_key,
composition_modifier=composition,
next_work_strategy_key=strategy_key,
)
+81
View File
@@ -0,0 +1,81 @@
"""Minimal TenantContext for service-layer steering calls."""
from __future__ import annotations
from typing import Optional
from db import get_connection
from psycopg2.extras import RealDictCursor
from rights_registry import load_grants_for_roles
from tenant_context import TenantContext
def resolve_minimal_tenant_context(
*,
tenant_id: str,
user_id: Optional[str] = None,
) -> TenantContext:
"""Build TenantContext for kernel calls from OM services (no HTTP session)."""
conn = get_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"SELECT id, slug, name FROM tenants WHERE id = %s",
(tenant_id,),
)
tenant = cur.fetchone()
if not tenant:
raise ValueError("Tenant nicht gefunden")
user_row = None
membership_role: str | None = None
actor_id: str | None = None
if user_id:
cur.execute(
"""
SELECT u.id, u.email, u.display_name, u.portal_role, tm.tenant_role
FROM users u
LEFT JOIN tenant_memberships tm
ON tm.user_id = u.id AND tm.tenant_id = %s AND tm.is_active = TRUE
WHERE u.id = %s
""",
(tenant_id, user_id),
)
user_row = cur.fetchone()
if user_row:
membership_role = user_row.get("tenant_role")
cur.execute(
"""
SELECT id FROM actors
WHERE tenant_id = %s AND user_id = %s AND actor_type = 'human'
LIMIT 1
""",
(tenant_id, user_id),
)
actor = cur.fetchone()
actor_id = str(actor["id"]) if actor else None
finally:
conn.close()
portal_role = user_row["portal_role"] if user_row else "user"
caps = frozenset(
load_grants_for_roles(
portal_role=portal_role,
tenant_role=membership_role,
)
)
return TenantContext(
user_id=str(user_row["id"]) if user_row else "",
email=user_row["email"] if user_row else "",
display_name=user_row["display_name"] if user_row else "",
portal_role=portal_role,
tenant_id=str(tenant["id"]),
tenant_slug=tenant["slug"],
tenant_name=tenant["name"],
tenant_role=membership_role,
actor_id=actor_id,
actor_type="human" if actor_id else None,
session_token="steering-service",
capabilities=caps,
)
+91
View File
@@ -0,0 +1,91 @@
"""Steering Kernel Spine — single entry point v0.4."""
from __future__ import annotations
from steering.kernel.attention import evaluate_attention
from steering.kernel.binding import resolve_steering_binding
from steering.eval_context import build_steering_eval_context
from steering.kernel.horizon import resolve_horizon
from steering.kernel.lifecycle import resolve_lifecycle_context
from steering.kernel.models import SteeringEvaluation
from steering.kernel.next_work import evaluate_next_work
from steering.agent_slots.registry import compute_agent_slots
from steering.proposals.registry import compute_proposals
from steering.read_models.registry import compute_read_models
from tenant_context import TenantContext
def evaluate_steering(
ctx: TenantContext,
*,
initiative_id: str,
next_work_limit: int = 10,
attention_limit: int = 20,
) -> SteeringEvaluation:
"""
Herzmaschine — ein Wahrheitsmodell pro Vorhaben.
Alle Initiative-Steuerung (Snapshot, Cockpit, API) muss hier durch.
"""
if next_work_limit < 1:
next_work_limit = 1
if attention_limit < 1:
attention_limit = 1
binding = resolve_steering_binding(ctx, initiative_id)
lifecycle = resolve_lifecycle_context(
ctx, initiative_id=initiative_id, binding=binding
)
horizon = resolve_horizon(
ctx,
initiative_id=initiative_id,
primary_method_key=binding.primary_method_key,
composition_modifier=binding.composition_modifier,
)
eval_ctx = build_steering_eval_context(
ctx,
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
lifecycle=lifecycle,
)
next_work = evaluate_next_work(
ctx,
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
limit=next_work_limit,
)
read_models = compute_read_models(eval_ctx)
proposals = compute_proposals(eval_ctx, read_models=read_models)
attention = evaluate_attention(
ctx,
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
next_work=next_work,
read_models=read_models,
proposals=proposals,
eval_ctx=eval_ctx,
limit=attention_limit,
)
agent_slots = compute_agent_slots(
eval_ctx, read_models=read_models, proposals=proposals
)
return SteeringEvaluation(
initiative_id=initiative_id,
binding=binding,
horizon=horizon,
lifecycle=lifecycle,
next_work=next_work,
attention=attention,
read_models=read_models,
proposals=proposals,
agent_slots=agent_slots,
)
+72
View File
@@ -0,0 +1,72 @@
"""Event ingress — dual trigger (Plan | Event) v0.2."""
from __future__ import annotations
from typing import Any
from steering.kernel.binding import resolve_primary_method_key
from steering.kernel.evaluate import evaluate_steering
from steering.lifecycle.event_transitions import EventKind
from steering.lifecycle.orchestrator import transition
from steering.lifecycle.slot_providers import (
register_default_slot_providers,
resolve_event_via_providers,
)
from tenant_context import TenantContext
register_default_slot_providers()
def apply_steering_event(
ctx: TenantContext,
*,
initiative_id: str,
event_kind: EventKind,
payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Event-Schub in den Kernel.
Plan-dominante Methoden: Event aktualisiert lifecycle_state entlang slot_map,
danach Re-Evaluate über evaluate_steering (Plan-Zug bleibt führend für Next).
"""
payload = payload or {}
primary_key = resolve_primary_method_key(ctx, initiative_id)
chain = resolve_event_via_providers(
primary_method_key=primary_key,
event_kind=event_kind,
payload=payload,
)
transitions: list[dict[str, Any]] = []
handled = bool(chain)
for slot_state in chain:
result = transition(
ctx,
initiative_id,
slot_state,
reason=f"steering_event:{event_kind}",
tenant_id=ctx.tenant_id,
user_id=ctx.user_id or None,
)
if not result.get("unchanged"):
transitions.append(result)
evaluation = evaluate_steering(ctx, initiative_id=initiative_id)
return {
"accepted": True,
"event_kind": event_kind,
"initiative_id": initiative_id,
"handled": handled,
"lifecycle_chain": list(chain),
"transitions": transitions,
"message": (
"Lifecycle aktualisiert — Re-Evaluate via Plan-Zug"
if handled
else "Event protokolliert — kein Lifecycle-Slot für diese Methode"
),
"payload_keys": sorted(payload.keys()),
"evaluation": evaluation.to_dict(),
}
+67
View File
@@ -0,0 +1,67 @@
"""Horizon resolution (Q1)."""
from __future__ import annotations
from steering.kernel.models import HorizonMarker
from steering.strategies.next_action.execution_ready import (
first_active_gate_id,
gate_horizon_scope_for_method,
)
from services.work_cycle import get_active_work_cycle
from tenant_context import TenantContext
def resolve_horizon(
ctx: TenantContext,
*,
initiative_id: str,
primary_method_key: str,
composition_modifier: str | None,
) -> HorizonMarker:
gate_id = gate_horizon_scope_for_method(
primary_method_key, ctx, initiative_id
)
gate_title: str | None = None
if gate_id:
gate_title = _load_gate_title(ctx, gate_id)
active_cycle = get_active_work_cycle(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
if composition_modifier and active_cycle:
return HorizonMarker(
kind="work_cycle",
gate_roadmap_item_id=gate_id,
gate_title=gate_title,
work_cycle_id=str(active_cycle["id"]),
work_cycle_title=active_cycle.get("title"),
)
if gate_id:
return HorizonMarker(
kind="gate",
gate_roadmap_item_id=gate_id,
gate_title=gate_title,
)
return HorizonMarker(kind="none")
def _load_gate_title(ctx: TenantContext, gate_id: str) -> str | None:
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 title FROM roadmap_items
WHERE id = %s AND tenant_id = %s
""",
(gate_id, ctx.tenant_id),
)
row = cur.fetchone()
return row["title"] if row else None
finally:
conn.close()
+65
View File
@@ -0,0 +1,65 @@
"""Lifecycle slot resolution — Kernel §4 (declarative, v0.1.1)."""
from __future__ import annotations
from typing import Any
from steering.kernel.models import LifecycleContext, SteeringBinding
from steering.lifecycle.slot_maps import (
active_slot_keys,
is_slot_operational,
slot_map_from_tuple,
)
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS, lifecycle_label
from steering.methods.registry import get_method
from services import steering_context as sc_service
from tenant_context import TenantContext
def _derive_slot_map_from_steps(steps: tuple[str, ...]) -> dict[str, str]:
active = set(steps)
return {
step: ("active" if step in active else "n/a") for step in STANDARD_LIFECYCLE_STEPS
}
def resolve_method_slot_map(method_key: str) -> dict[str, str]:
method = get_method(method_key)
if not method:
return _derive_slot_map_from_steps(STANDARD_LIFECYCLE_STEPS)
if method.slot_map:
return slot_map_from_tuple(method.slot_map)
return _derive_slot_map_from_steps(method.default_lifecycle_steps)
def resolve_lifecycle_context(
ctx: TenantContext,
*,
initiative_id: str,
binding: SteeringBinding,
) -> LifecycleContext:
slot_map = resolve_method_slot_map(binding.primary_method_key)
row = sc_service.get_steering_context(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
current_state = row["lifecycle_state"] if row else "intake"
if current_state not in STANDARD_LIFECYCLE_STEPS:
current_state = "intake"
active = active_slot_keys(slot_map) # type: ignore[arg-type]
operational = tuple(
step for step in STANDARD_LIFECYCLE_STEPS if is_slot_operational(slot_map.get(step, "n/a")) # type: ignore[arg-type]
)
return LifecycleContext(
current_state=current_state,
current_state_label=lifecycle_label(current_state),
slot_map=slot_map,
active_slots=active,
operational_slots=operational,
)
def lifecycle_to_dict(lifecycle: LifecycleContext) -> dict[str, Any]:
return lifecycle.to_dict()
+87
View File
@@ -0,0 +1,87 @@
"""Steering Kernel Spine — data models v0.1.1."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
@dataclass(frozen=True)
class HorizonMarker:
"""Aktiver Steuerungs-Horizont (Q1)."""
kind: Literal["gate", "work_cycle", "none"]
gate_roadmap_item_id: str | None = None
gate_title: str | None = None
work_cycle_id: str | None = None
work_cycle_title: str | None = None
def to_dict(self) -> dict[str, Any]:
return {
"kind": self.kind,
"gate_roadmap_item_id": self.gate_roadmap_item_id,
"gate_title": self.gate_title,
"work_cycle_id": self.work_cycle_id,
"work_cycle_title": self.work_cycle_title,
}
@dataclass(frozen=True)
class SteeringBinding:
"""Aufgelöste Methode: Primary + optional Composition."""
primary_method_key: str
composition_modifier: str | None
next_work_strategy_key: str
@dataclass(frozen=True)
class LifecycleContext:
"""Deklarativer Lifecycle-Vertrag + persistierter Pointer."""
current_state: str
current_state_label: str
slot_map: dict[str, str]
active_slots: tuple[str, ...]
operational_slots: tuple[str, ...]
def to_dict(self) -> dict[str, Any]:
return {
"current_state": self.current_state,
"current_state_label": self.current_state_label,
"slot_map": dict(self.slot_map),
"active_slots": list(self.active_slots),
"operational_slots": list(self.operational_slots),
}
@dataclass
class SteeringEvaluation:
"""Ergebnis von evaluate_steering — ein Wahrheitsmodell pro Vorhaben."""
initiative_id: str
binding: SteeringBinding
horizon: HorizonMarker
lifecycle: LifecycleContext
next_work: list[dict[str, Any]] = field(default_factory=list)
attention: list[dict[str, Any]] = field(default_factory=list)
read_models: dict[str, Any] = field(default_factory=dict)
proposals: dict[str, Any] = field(default_factory=dict)
agent_slots: list[dict[str, Any]] = field(default_factory=list)
data_source: str = "steering_kernel_v0.4"
def to_dict(self) -> dict[str, Any]:
return {
"initiative_id": self.initiative_id,
"primary_method_key": self.binding.primary_method_key,
"composition_modifier": self.binding.composition_modifier,
"next_work_strategy_key": self.binding.next_work_strategy_key,
"horizon": self.horizon.to_dict(),
"lifecycle": self.lifecycle.to_dict(),
"next_work": self.next_work,
"attention": self.attention,
"read_models": self.read_models,
"proposals": self.proposals,
"agent_slots": self.agent_slots,
"data_source": self.data_source,
}
+37
View File
@@ -0,0 +1,37 @@
"""Next work evaluation (Schlitz 5) — routes to registered strategies only."""
from __future__ import annotations
from typing import Any
from steering.kernel.models import HorizonMarker, SteeringBinding
from steering.strategies.next_action.default_strategy import default_strategy
from steering.strategies.next_action.registry import get_next_action_strategy
from tenant_context import TenantContext
def evaluate_next_work(
ctx: TenantContext,
*,
initiative_id: str,
binding: SteeringBinding,
horizon: HorizonMarker,
limit: int,
) -> list[dict[str, Any]]:
"""Invoke the bound next-work strategy (primary or composition)."""
if limit < 1:
limit = 1
strategy = get_next_action_strategy(binding.next_work_strategy_key) or default_strategy
candidates = strategy.evaluate(
ctx, initiative_id=initiative_id, limit=limit
)
for item in candidates:
item.setdefault("data_source", "steering_kernel")
if horizon.gate_roadmap_item_id:
item.setdefault("horizon_gate_id", horizon.gate_roadmap_item_id)
if horizon.work_cycle_id:
item.setdefault("horizon_work_cycle_id", horizon.work_cycle_id)
return candidates[:limit]
@@ -0,0 +1,66 @@
"""Lifecycle transition chains for kernel event ingress v0.2."""
from __future__ import annotations
from typing import Any, Literal
from steering.lifecycle.slot_maps import SlotStatus
EventKind = Literal[
"actor_result",
"gate_verified",
"gate_reopened",
"external_event",
"cadence_due",
"situational",
]
def _slot_accepts_event(status: SlotStatus, *, event_targets_slot: bool) -> bool:
if status == "active":
return True
if status == "optional" and event_targets_slot:
return True
return False
def resolve_lifecycle_chain(
*,
primary_method_key: str,
event_kind: EventKind,
payload: dict[str, Any] | None = None,
) -> tuple[str, ...]:
"""
Ordered lifecycle slots to visit for an event (method-aware via slot_map).
Returns slot keys; caller persists the last applicable state.
"""
from steering.kernel.lifecycle import resolve_method_slot_map
payload = payload or {}
slot_map = resolve_method_slot_map(primary_method_key)
if event_kind == "actor_result" and payload.get("to_status") == "done":
candidates = ("result_intake", "adaptation", "action_selection")
event_slot = "result_intake"
elif event_kind == "gate_verified":
candidates = ("validation", "adaptation", "action_selection")
event_slot = "validation"
elif event_kind == "gate_reopened":
candidates = ("adaptation", "planning", "action_selection")
event_slot = "adaptation"
elif event_kind == "situational" and payload.get("reason") == "blocker_resolved":
candidates = ("action_selection",)
event_slot = "action_selection"
else:
return ()
chain: list[str] = []
for step in candidates:
status = slot_map.get(step, "n/a")
if _slot_accepts_event(
status, # type: ignore[arg-type]
event_targets_slot=(step == event_slot or step in ("adaptation", "action_selection")),
):
chain.append(step)
return tuple(chain)
+93
View File
@@ -0,0 +1,93 @@
"""Method slot maps — Kernel §4 / Spec-D D5."""
from __future__ import annotations
from typing import Literal
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
SlotStatus = Literal["active", "skip", "n/a", "optional"]
VALID_SLOT_STATUSES = frozenset({"active", "skip", "n/a", "optional"})
# Spec-D sequential_dependency D5
SEQUENTIAL_DEPENDENCY_SLOTS: dict[str, SlotStatus] = {
"intake": "active",
"method_selection": "active",
"structure_setup": "active",
"planning": "active",
"action_selection": "active",
"assignment": "active",
"waiting": "active",
"result_intake": "active",
"validation": "active",
"review": "optional",
"adaptation": "active",
"closure": "active",
}
# Spec-D generic_operating D5 (method_bind → method_selection, next_work → action_selection)
GENERIC_OPERATING_SLOTS: dict[str, SlotStatus] = {
"intake": "active",
"method_selection": "active",
"structure_setup": "optional",
"planning": "n/a",
"action_selection": "active",
"assignment": "active",
"waiting": "optional",
"result_intake": "active",
"validation": "n/a",
"review": "n/a",
"adaptation": "optional",
"closure": "optional",
}
# Spec-D continuous_product D5 (method_bind → method_selection)
CONTINUOUS_PRODUCT_SLOTS: dict[str, SlotStatus] = {
"intake": "active",
"method_selection": "active",
"structure_setup": "active",
"planning": "active",
"action_selection": "active",
"assignment": "active",
"waiting": "active",
"result_intake": "active",
"validation": "optional",
"review": "optional",
"adaptation": "active",
"closure": "n/a",
}
def validate_slot_map(slot_map: dict[str, SlotStatus]) -> None:
for step, status in slot_map.items():
if step not in STANDARD_LIFECYCLE_STEPS:
raise ValueError(f"Unknown lifecycle slot: {step}")
if status not in VALID_SLOT_STATUSES:
raise ValueError(f"Invalid slot status for {step}: {status}")
missing = set(STANDARD_LIFECYCLE_STEPS) - set(slot_map.keys())
if missing:
raise ValueError(f"slot_map missing lifecycle steps: {sorted(missing)}")
def slot_map_to_tuple(slot_map: dict[str, SlotStatus]) -> tuple[tuple[str, SlotStatus], ...]:
validate_slot_map(slot_map)
return tuple((step, slot_map[step]) for step in STANDARD_LIFECYCLE_STEPS)
def slot_map_from_tuple(items: tuple[tuple[str, SlotStatus], ...]) -> dict[str, SlotStatus]:
if not items:
return {}
slot_map = dict(items)
validate_slot_map(slot_map)
return slot_map
def active_slot_keys(slot_map: dict[str, SlotStatus]) -> tuple[str, ...]:
return tuple(step for step in STANDARD_LIFECYCLE_STEPS if slot_map.get(step) == "active")
def is_slot_operational(status: SlotStatus) -> bool:
"""Slots that participate in runtime evaluation (v0.1.1)."""
return status in ("active", "optional")
@@ -0,0 +1,107 @@
"""Lifecycle slot providers — minimal registry v0.2."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Literal
from steering.lifecycle.event_transitions import EventKind
SlotKey = Literal[
"result_intake",
"validation",
"adaptation",
"action_selection",
"planning",
]
TransitionResolver = Callable[
[str, EventKind, dict[str, Any] | None],
tuple[str, ...],
]
_PROVIDERS: dict[SlotKey, TransitionResolver] = {}
@dataclass(frozen=True)
class SlotProviderRegistration:
slot_key: SlotKey
event_kinds: frozenset[EventKind]
def register_slot_provider(
slot_key: SlotKey,
*,
event_kinds: frozenset[EventKind],
resolver: TransitionResolver,
) -> None:
_PROVIDERS[slot_key] = resolver
_REGISTRATIONS[slot_key] = SlotProviderRegistration(
slot_key=slot_key, event_kinds=event_kinds
)
_REGISTRATIONS: dict[SlotKey, SlotProviderRegistration] = {}
def list_slot_provider_registrations() -> tuple[SlotProviderRegistration, ...]:
return tuple(_REGISTRATIONS.values())
def resolve_event_via_providers(
*,
primary_method_key: str,
event_kind: EventKind,
payload: dict[str, Any] | None = None,
) -> tuple[str, ...]:
"""First matching provider wins; fallback to default event_transitions."""
from steering.lifecycle.event_transitions import resolve_lifecycle_chain
payload = payload or {}
for slot_key, registration in _REGISTRATIONS.items():
if event_kind not in registration.event_kinds:
continue
resolver = _PROVIDERS.get(slot_key)
if resolver:
chain = resolver(primary_method_key, event_kind, payload)
if chain:
return chain
return resolve_lifecycle_chain(
primary_method_key=primary_method_key,
event_kind=event_kind,
payload=payload,
)
def register_default_slot_providers() -> None:
from steering.lifecycle.event_transitions import resolve_lifecycle_chain
if _PROVIDERS:
return
def _default_resolver(
primary_method_key: str,
event_kind: EventKind,
payload: dict[str, Any] | None,
) -> tuple[str, ...]:
return resolve_lifecycle_chain(
primary_method_key=primary_method_key,
event_kind=event_kind,
payload=payload,
)
register_slot_provider(
"result_intake",
event_kinds=frozenset({"actor_result"}),
resolver=_default_resolver,
)
register_slot_provider(
"validation",
event_kinds=frozenset({"gate_verified"}),
resolver=_default_resolver,
)
register_slot_provider(
"adaptation",
event_kinds=frozenset({"actor_result", "gate_verified", "gate_reopened"}),
resolver=_default_resolver,
)
@@ -1,7 +1,15 @@
"""Shared registration helper for AP2.0 method stubs.""" """Shared registration helper for AP2.0 method stubs — AP2.3e / AP2.4."""
from __future__ import annotations from __future__ import annotations
from typing import Literal
from steering.graph.profiles import (
FULFILLMENT,
GraphMethodProfile,
LIGHT,
STRICT,
)
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
from steering.methods.registry import MethodDefinition, get_method, register_method from steering.methods.registry import MethodDefinition, get_method, register_method
@@ -31,6 +39,49 @@ _LIGHT_STEPS = (
"closure", "closure",
) )
SLICES_OM_STANDARD = frozenset(
{
"backlog",
"actions",
"roadmap",
"projects",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
}
)
SLICES_PRODUCT = SLICES_OM_STANDARD | frozenset({"work_cycles"})
SLICES_QUEUE = frozenset({"backlog", "actions", "blockers", "steering_methods"})
SLICES_MATURITY = frozenset(
{
"actions",
"roadmap",
"blockers",
"evidence",
"decisions",
"reviews",
"recurring",
"steering_methods",
}
)
SLICES_RECURRING = frozenset(
{"actions", "roadmap", "recurring", "blockers", "steering_methods"}
)
SLICES_PROGRAM = SLICES_OM_STANDARD | frozenset({"work_cycles"})
SLICES_GENERIC = SLICES_OM_STANDARD
SLICES_AGILE = SLICES_PRODUCT
ELEM_NEXT = frozenset({"next_action_primary"})
def register_stub_method( def register_stub_method(
*, *,
@@ -39,6 +90,14 @@ def register_stub_method(
description: str, description: str,
next_action_strategy_key: str = "default", next_action_strategy_key: str = "default",
lifecycle_steps: tuple[str, ...] | None = None, lifecycle_steps: tuple[str, ...] | None = None,
data_slices: frozenset[str] | None = None,
compatible_archetype_keys: frozenset[str] | Literal["*"] = "*",
steering_elements: frozenset[str] | None = None,
ui_features: frozenset[str] | None = None,
graph_profile: GraphMethodProfile = LIGHT,
method_role: Literal["primary", "modifier"] = "primary",
composes_with: frozenset[str] | None = None,
slot_map: tuple[tuple[str, str], ...] | None = None,
) -> None: ) -> None:
if get_method(key): if get_method(key):
return return
@@ -50,6 +109,14 @@ def register_stub_method(
description=description, description=description,
default_lifecycle_steps=lifecycle_steps or STANDARD_LIFECYCLE_STEPS, default_lifecycle_steps=lifecycle_steps or STANDARD_LIFECYCLE_STEPS,
next_action_strategy_key=next_action_strategy_key, next_action_strategy_key=next_action_strategy_key,
data_slices=data_slices or SLICES_GENERIC,
compatible_archetype_keys=compatible_archetype_keys,
steering_elements=steering_elements or ELEM_NEXT,
ui_features=ui_features or frozenset(),
graph_profile=graph_profile,
method_role=method_role,
composes_with=composes_with or frozenset(),
slot_map=slot_map or (),
) )
) )
@@ -60,6 +127,12 @@ def register_product_like_method(
label: str, label: str,
description: str, description: str,
next_action_strategy_key: str, next_action_strategy_key: str,
data_slices: frozenset[str] | None = None,
compatible_archetype_keys: frozenset[str] | Literal["*"] | None = None,
steering_elements: frozenset[str] | None = None,
ui_features: frozenset[str] | None = None,
graph_profile: GraphMethodProfile = STRICT,
slot_map: tuple[tuple[str, str], ...] | None = None,
) -> None: ) -> None:
register_stub_method( register_stub_method(
key=key, key=key,
@@ -67,4 +140,13 @@ def register_product_like_method(
description=description, description=description,
next_action_strategy_key=next_action_strategy_key, next_action_strategy_key=next_action_strategy_key,
lifecycle_steps=_PRODUCT_LIKE_STEPS, lifecycle_steps=_PRODUCT_LIKE_STEPS,
data_slices=data_slices or SLICES_PRODUCT,
compatible_archetype_keys=compatible_archetype_keys
if compatible_archetype_keys is not None
else frozenset({"initiative.product"}),
steering_elements=steering_elements
or (ELEM_NEXT | frozenset({"gate_fulfillment", "work_cycle_scope"})),
ui_features=ui_features or frozenset(),
graph_profile=graph_profile,
slot_map=slot_map or (),
) )
@@ -1,8 +1,21 @@
"""AP2.0a — remaining method stubs.""" """AP2.0a — remaining method stubs — AP2.4 steering elements."""
from __future__ import annotations from __future__ import annotations
from steering.methods.registrations._helpers import register_stub_method from steering.graph.profiles import FULFILLMENT, LIGHT, STRICT
from steering.lifecycle.slot_maps import (
SEQUENTIAL_DEPENDENCY_SLOTS,
slot_map_to_tuple,
)
from steering.methods.registrations._helpers import (
ELEM_NEXT,
SLICES_AGILE,
SLICES_MATURITY,
SLICES_OM_STANDARD,
SLICES_QUEUE,
SLICES_RECURRING,
register_stub_method,
)
def register() -> None: def register() -> None:
@@ -11,40 +24,108 @@ def register() -> None:
label="Reifegrad-Entwicklung", label="Reifegrad-Entwicklung",
description="Stufen, Routinen, historische Entwicklung", description="Stufen, Routinen, historische Entwicklung",
next_action_strategy_key="maturity_progression", next_action_strategy_key="maturity_progression",
data_slices=SLICES_MATURITY,
compatible_archetype_keys=frozenset({"initiative.maturity_journey"}),
steering_elements=ELEM_NEXT
| frozenset({"maturity_stage", "recurring_rhythm"}),
graph_profile=FULFILLMENT,
) )
register_stub_method( register_stub_method(
key="sequential_dependency", key="sequential_dependency",
label="Sequenzielle Abhängigkeit", label="Sequenzielle Abhängigkeit",
description="Graph-Pfade, kritischer Pfad (read model)", description="Graph-Pfade, kritischer Pfad (read model)",
next_action_strategy_key="sequential_dependency", next_action_strategy_key="sequential_dependency",
data_slices=SLICES_OM_STANDARD,
compatible_archetype_keys=frozenset({"initiative.linear_project"}),
steering_elements=ELEM_NEXT
| frozenset({"critical_path", "gate_fulfillment"}),
ui_features=frozenset({"criticalPathControl"}),
graph_profile=STRICT,
slot_map=slot_map_to_tuple(SEQUENTIAL_DEPENDENCY_SLOTS),
) )
register_stub_method( register_stub_method(
key="recurring_control", key="recurring_control",
label="Rhythmus-Steuerung", label="Rhythmus-Steuerung",
description="Dauerprogramm, fällig/überfällig, Abweichungen", description="Dauerprogramm, fällig/überfällig, Abweichungen",
next_action_strategy_key="recurring_control", next_action_strategy_key="recurring_control",
data_slices=SLICES_RECURRING,
compatible_archetype_keys=frozenset({"initiative.recurring_program"}),
steering_elements=ELEM_NEXT | frozenset({"recurring_rhythm"}),
graph_profile=FULFILLMENT,
) )
register_stub_method( register_stub_method(
key="queue_pull", key="queue_pull",
label="Inbox / Queue", label="Inbox / Queue (Legacy)",
description="Pull oder Empfehlung aus Queue", description="Pull oder Empfehlung aus Queue — abgelöst durch checklist_flow",
next_action_strategy_key="queue_pull", next_action_strategy_key="queue_pull",
data_slices=SLICES_QUEUE,
compatible_archetype_keys=frozenset({"initiative.support_queue"}),
steering_elements=ELEM_NEXT | frozenset({"queue_inbox"}),
graph_profile=LIGHT,
) )
register_stub_method( register_stub_method(
key="agile_iteration", key="agile_iteration",
label="Iterations-Zeitbox", label="Iterations-Zeitbox",
description="Sprint/work_cycle Profil auf Product/Programm", description="Sprint/work_cycle Profil — komponiert mit Primary-Methoden",
next_action_strategy_key="agile_iteration", next_action_strategy_key="agile_iteration",
data_slices=SLICES_AGILE,
compatible_archetype_keys=frozenset(
{
"initiative.linear_project",
"initiative.product",
"initiative.recurring_program",
}
),
steering_elements=ELEM_NEXT
| frozenset({"work_cycle_scope", "backlog_epic_hierarchy"}),
ui_features=frozenset({"steeringSnapshotOnWorkSprint"}),
graph_profile=STRICT,
method_role="modifier",
composes_with=frozenset(
{
"continuous_product",
"sequential_dependency",
"recurring_control",
}
),
) )
register_stub_method( register_stub_method(
key="dispute_procedure", key="dispute_procedure",
label="Verfahren / Konflikt", label="Verfahren / Konflikt",
description="Reaktive Steuerung, Fristen, Entscheidungen", description="Reaktive Steuerung, Fristen, Entscheidungen",
next_action_strategy_key="default", next_action_strategy_key="default",
data_slices=frozenset(
{
"actions",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
}
),
compatible_archetype_keys=frozenset({"initiative.dispute_case"}),
steering_elements=ELEM_NEXT | frozenset({"dispute_timeline"}),
graph_profile=LIGHT,
) )
register_stub_method( register_stub_method(
key="chapter_based_progression", key="chapter_based_progression",
label="Kapitel-Entwicklung", label="Kapitel-Entwicklung",
description="Inhaltliche Progression, Reviews", description="Inhaltliche Progression, Reviews",
next_action_strategy_key="default", next_action_strategy_key="default",
data_slices=frozenset(
{
"actions",
"roadmap",
"blockers",
"evidence",
"decisions",
"reviews",
"steering_methods",
}
),
compatible_archetype_keys=frozenset({"initiative.content_project"}),
steering_elements=ELEM_NEXT
| frozenset({"chapter_progression", "gate_fulfillment"}),
graph_profile=FULFILLMENT,
) )
@@ -1,8 +1,13 @@
"""Built-in method: continuous_product — AP2.0a.""" """Built-in method: continuous_product — AP2.0a / AP2.4."""
from __future__ import annotations from __future__ import annotations
from steering.methods.registrations._helpers import register_product_like_method from steering.graph.profiles import FULFILLMENT
from steering.lifecycle.slot_maps import CONTINUOUS_PRODUCT_SLOTS, slot_map_to_tuple
from steering.methods.registrations._helpers import (
ELEM_NEXT,
register_product_like_method,
)
def register() -> None: def register() -> None:
@@ -11,4 +16,11 @@ def register() -> None:
label="Produkt (kontinuierlich)", label="Produkt (kontinuierlich)",
description="Kontinuierlicher Betrieb — Ist zuerst, Plan als Orientierung", description="Kontinuierlicher Betrieb — Ist zuerst, Plan als Orientierung",
next_action_strategy_key="continuous_product", next_action_strategy_key="continuous_product",
graph_profile=FULFILLMENT,
ui_features=frozenset(
{"continuousProductWorkMode", "steeringSnapshotOnWorkSprint"}
),
steering_elements=ELEM_NEXT
| frozenset({"gate_fulfillment", "work_cycle_scope"}),
slot_map=slot_map_to_tuple(CONTINUOUS_PRODUCT_SLOTS),
) )
@@ -1,8 +1,11 @@
"""Built-in method: generic_operating.""" """Built-in method: generic_operating — AP2.4."""
from __future__ import annotations from __future__ import annotations
from steering.graph.profiles import LIGHT
from steering.lifecycle.slot_maps import GENERIC_OPERATING_SLOTS, slot_map_to_tuple
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
from steering.methods.registrations._helpers import ELEM_NEXT, SLICES_GENERIC
from steering.methods.registry import MethodDefinition, get_method, register_method from steering.methods.registry import MethodDefinition, get_method, register_method
@@ -17,5 +20,10 @@ def register() -> None:
description="Standard-Lifecycle ohne methodenspezifische Spezialisierung", description="Standard-Lifecycle ohne methodenspezifische Spezialisierung",
default_lifecycle_steps=STANDARD_LIFECYCLE_STEPS, default_lifecycle_steps=STANDARD_LIFECYCLE_STEPS,
next_action_strategy_key="default", next_action_strategy_key="default",
data_slices=SLICES_GENERIC,
compatible_archetype_keys="*",
steering_elements=ELEM_NEXT,
graph_profile=LIGHT,
slot_map=slot_map_to_tuple(GENERIC_OPERATING_SLOTS),
) )
) )
@@ -1,8 +1,9 @@
"""Built-in method: product_milestone_driven — AP1.1.""" """Built-in method: product_milestone_driven — AP1.1 / AP2.4."""
from __future__ import annotations from __future__ import annotations
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS from steering.graph.profiles import STRICT
from steering.methods.registrations._helpers import ELEM_NEXT, SLICES_OM_STANDARD
from steering.methods.registry import MethodDefinition, get_method, register_method from steering.methods.registry import MethodDefinition, get_method, register_method
_PRODUCT_STEPS = ( _PRODUCT_STEPS = (
@@ -32,5 +33,14 @@ def register() -> None:
description="Meilenstein-orientierte Steuerung für Produkt- und Projektentwicklung", description="Meilenstein-orientierte Steuerung für Produkt- und Projektentwicklung",
default_lifecycle_steps=_PRODUCT_STEPS, default_lifecycle_steps=_PRODUCT_STEPS,
next_action_strategy_key="product_milestone_driven", next_action_strategy_key="product_milestone_driven",
data_slices=SLICES_OM_STANDARD,
compatible_archetype_keys=frozenset(
{
"initiative.product",
"initiative.generic",
}
),
steering_elements=ELEM_NEXT | frozenset({"gate_fulfillment"}),
graph_profile=STRICT,
) )
) )
@@ -1,8 +1,12 @@
"""Built-in method: program_delivery — AP2.0a.""" """Built-in method: program_delivery — AP2.0a / AP2.4."""
from __future__ import annotations from __future__ import annotations
from steering.methods.registrations._helpers import register_product_like_method from steering.methods.registrations._helpers import (
ELEM_NEXT,
SLICES_PROGRAM,
register_product_like_method,
)
def register() -> None: def register() -> None:
@@ -11,4 +15,8 @@ def register() -> None:
label="Programm (begrenzt)", label="Programm (begrenzt)",
description="Meilenstein- und gate-orientierte Steuerung mit Abschluss", description="Meilenstein- und gate-orientierte Steuerung mit Abschluss",
next_action_strategy_key="program_delivery", next_action_strategy_key="program_delivery",
data_slices=SLICES_PROGRAM,
compatible_archetype_keys=frozenset({"initiative.program"}),
steering_elements=ELEM_NEXT
| frozenset({"gate_fulfillment", "work_cycle_scope"}),
) )
+121 -1
View File
@@ -1,8 +1,12 @@
"""Method Registry — built-in steering methods.""" """Method Registry — built-in steering methods — AP2.3e / AP2.4."""
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Literal
from steering.elements.registry import validate_steering_element_keys
from steering.graph.profiles import GraphMethodProfile, LIGHT
_METHODS: dict[str, "MethodDefinition"] = {} _METHODS: dict[str, "MethodDefinition"] = {}
@@ -15,14 +19,97 @@ class MethodDefinition:
description: str description: str
default_lifecycle_steps: tuple[str, ...] default_lifecycle_steps: tuple[str, ...]
next_action_strategy_key: str = "default" next_action_strategy_key: str = "default"
data_slices: frozenset[str] = frozenset()
compatible_archetype_keys: frozenset[str] | Literal["*"] = "*"
steering_elements: frozenset[str] = frozenset()
ui_features: frozenset[str] = frozenset()
graph_profile: GraphMethodProfile = LIGHT
method_role: Literal["primary", "modifier"] = "primary"
composes_with: frozenset[str] = frozenset()
slot_map: tuple[tuple[str, str], ...] = ()
def ui_features_as_dict(features: frozenset[str]) -> dict[str, bool]:
return {key: True for key in sorted(features)}
def method_compatible_with_archetype(
method: MethodDefinition,
archetype_key: str,
*,
om_capabilities: frozenset[str] | None = None,
) -> bool:
compat = method.compatible_archetype_keys
if compat != "*" and archetype_key not in compat:
return False
if om_capabilities is not None and method.data_slices:
if not method.data_slices.issubset(om_capabilities):
return False
return True
def list_compatible_methods(
archetype_key: str,
*,
om_capabilities: frozenset[str] | None = None,
) -> tuple[MethodDefinition, ...]:
return tuple(
m
for m in _METHODS.values()
if m.method_role == "primary"
and method_compatible_with_archetype(
m, archetype_key, om_capabilities=om_capabilities
)
)
def register_method(defn: MethodDefinition) -> None: def register_method(defn: MethodDefinition) -> None:
if defn.key in _METHODS: if defn.key in _METHODS:
raise ValueError(f"Method already registered: {defn.key}") raise ValueError(f"Method already registered: {defn.key}")
if defn.steering_elements:
validate_steering_element_keys(defn.steering_elements)
if defn.method_role == "modifier" and not defn.composes_with:
raise ValueError(
f"Modifier method {defn.key} must declare composes_with primary keys"
)
if defn.slot_map:
from steering.lifecycle.slot_maps import slot_map_from_tuple
slot_map_from_tuple(defn.slot_map)
_METHODS[defn.key] = defn _METHODS[defn.key] = defn
def validate_method_registry() -> None:
"""Post-bootstrap: strategy keys exist; composes_with targets are primary methods."""
from steering.strategies.next_action.registry import get_next_action_strategy
for method in _METHODS.values():
strategy_key = method.next_action_strategy_key
if strategy_key != "default" and not get_next_action_strategy(strategy_key):
raise ValueError(
f"Method {method.key} references unknown next_action_strategy: {strategy_key}"
)
for primary_key in method.composes_with:
primary = get_method(primary_key)
if not primary:
raise ValueError(
f"Method {method.key} composes_with unknown method: {primary_key}"
)
if primary.method_role != "primary":
raise ValueError(
f"Method {method.key} composes_with non-primary method: {primary_key}"
)
def list_composable_modifiers(primary_method_key: str) -> tuple[MethodDefinition, ...]:
"""Modifier methods that may compose with the given primary method."""
return tuple(
m
for m in _METHODS.values()
if m.method_role == "modifier" and primary_method_key in m.composes_with
)
def get_method(key: str) -> MethodDefinition | None: def get_method(key: str) -> MethodDefinition | None:
return _METHODS.get(key) return _METHODS.get(key)
@@ -31,5 +118,38 @@ def list_methods() -> tuple[MethodDefinition, ...]:
return tuple(_METHODS.values()) return tuple(_METHODS.values())
def method_to_dict(
method: MethodDefinition,
*,
include_compatibility: bool = True,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"key": method.key,
"version": method.version,
"label": method.label,
"description": method.description,
"next_action_strategy_key": method.next_action_strategy_key,
"steering_elements": sorted(method.steering_elements),
"ui_features": ui_features_as_dict(method.ui_features),
"graph_profile": {
"enforce_gate_blocking": method.graph_profile.enforce_gate_blocking,
"emphasize_fulfillment": method.graph_profile.emphasize_fulfillment,
},
"method_role": method.method_role,
"composes_with": sorted(method.composes_with),
"data_slices": sorted(method.data_slices),
}
if method.slot_map:
payload["slot_map"] = {
step: status for step, status in method.slot_map
}
if include_compatibility:
compat = method.compatible_archetype_keys
payload["compatible_archetype_keys"] = (
"*" if compat == "*" else sorted(compat)
)
return payload
def clear_methods_for_tests() -> None: def clear_methods_for_tests() -> None:
_METHODS.clear() _METHODS.clear()
+172
View File
@@ -0,0 +1,172 @@
"""Portfolio-level steering aggregation — K-Ext-5."""
from __future__ import annotations
from typing import Any
from steering.kernel import evaluate_steering
from tenant_context import TenantContext
_SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
def _portfolio_rank_key(rank: int | None) -> int:
return rank if rank is not None else 999_999
def _load_active_initiatives(ctx: TenantContext, *, limit: int) -> list[dict[str, Any]]:
from data_layer.initiatives import get_active_initiatives
return get_active_initiatives(ctx, limit=limit)
def _enrich_item(
item: dict[str, Any],
*,
initiative_id: str,
initiative_title: str,
portfolio_rank: int | None,
) -> dict[str, Any]:
enriched = dict(item)
enriched.setdefault("initiative_id", initiative_id)
enriched["initiative_title"] = initiative_title
if portfolio_rank is not None:
enriched["portfolio_rank"] = portfolio_rank
enriched.setdefault("data_source", "steering_kernel")
return enriched
def _sort_attention(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
return sorted(
items,
key=lambda item: (
_SEVERITY_ORDER.get(item.get("severity", "info"), 99),
_portfolio_rank_key(item.get("portfolio_rank")),
item.get("initiative_title") or "",
item.get("title") or "",
),
)
def _sort_next_work(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
return sorted(
items,
key=lambda item: (
_portfolio_rank_key(item.get("portfolio_rank")),
item.get("rank") if item.get("rank") is not None else 999,
item.get("title") or "",
),
)
def aggregate_portfolio_steering(
ctx: TenantContext,
*,
max_initiatives: int = 50,
attention_per_initiative: int = 5,
next_work_per_initiative: int = 3,
total_attention: int = 30,
total_next_work: int = 15,
total_agent_slots: int = 20,
) -> dict[str, Any]:
"""
Aggregiert Kernel-Steuerung über aktive Initiativen (Portfolio-Rang).
"""
initiatives = _load_active_initiatives(ctx, limit=max_initiatives)
attention: list[dict[str, Any]] = []
next_work: list[dict[str, Any]] = []
agent_slots: list[dict[str, Any]] = []
proposals_summary: list[dict[str, Any]] = []
attention_by_initiative: dict[str, list[dict[str, Any]]] = {}
agent_slots_by_initiative: dict[str, list[dict[str, Any]]] = {}
for initiative in initiatives:
initiative_id = str(initiative["id"])
initiative_title = initiative.get("title") or "Vorhaben"
portfolio_rank = initiative.get("portfolio_rank")
evaluation = evaluate_steering(
ctx,
initiative_id=initiative_id,
next_work_limit=next_work_per_initiative,
attention_limit=attention_per_initiative,
)
initiative_attention: list[dict[str, Any]] = []
for item in evaluation.attention:
enriched = _enrich_item(
item,
initiative_id=initiative_id,
initiative_title=initiative_title,
portfolio_rank=portfolio_rank,
)
initiative_attention.append(enriched)
attention.append(enriched)
attention_by_initiative[initiative_id] = initiative_attention
for item in evaluation.next_work:
next_work.append(
_enrich_item(
item,
initiative_id=initiative_id,
initiative_title=initiative_title,
portfolio_rank=portfolio_rank,
)
)
initiative_slots: list[dict[str, Any]] = []
for slot in evaluation.agent_slots:
enriched = _enrich_item(
slot,
initiative_id=initiative_id,
initiative_title=initiative_title,
portfolio_rank=portfolio_rank,
)
initiative_slots.append(enriched)
agent_slots.append(enriched)
agent_slots_by_initiative[initiative_id] = initiative_slots
proposal_counts = {
key: len(value) if isinstance(value, list) else 0
for key, value in (evaluation.proposals or {}).items()
}
if any(proposal_counts.values()):
proposals_summary.append(
{
"initiative_id": initiative_id,
"initiative_title": initiative_title,
"portfolio_rank": portfolio_rank,
"counts": proposal_counts,
"total": sum(proposal_counts.values()),
}
)
attention = _sort_attention(attention)[:total_attention]
next_work = _sort_next_work(next_work)[:total_next_work]
agent_slots = sorted(
agent_slots,
key=lambda slot: (
{"high": 0, "normal": 1, "low": 2}.get(slot.get("priority", "normal"), 9),
_portfolio_rank_key(slot.get("portfolio_rank")),
),
)[:total_agent_slots]
proposals_summary.sort(
key=lambda row: (
-row.get("total", 0),
_portfolio_rank_key(row.get("portfolio_rank")),
)
)
return {
"data_source": "steering_kernel_portfolio_v0.1",
"initiative_count": len(initiatives),
"attention": attention,
"attention_by_initiative": attention_by_initiative,
"next_work": next_work,
"proposals_summary": proposals_summary,
"agent_slots": agent_slots,
"agent_slots_by_initiative": agent_slots_by_initiative,
}
+1
View File
@@ -0,0 +1 @@
"""Steering proposals — ranked suggestions without auto-mutation (P6+)."""
@@ -0,0 +1,127 @@
"""Gate next actions proposal — sequential_dependency / program_delivery."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
COMMITTABLE = frozenset({"new", "triaged", "accepted"})
_PRIORITY = {"critical": 0, "high": 1, "normal": 2, "low": 3}
def _active_gate_id(ctx: SteeringEvalContext) -> str | None:
if ctx.horizon.kind == "gate" and ctx.horizon.gate_roadmap_item_id:
return str(ctx.horizon.gate_roadmap_item_id)
debts = []
return None
def _sort_key(item: dict[str, Any]) -> tuple:
return (
_PRIORITY.get(item.get("priority") or "normal", 9),
item.get("sort_order") if item.get("sort_order") is not None else 9999,
(item.get("title") or "").lower(),
)
def propose_gate_next_actions(
ctx: SteeringEvalContext,
*,
read_models: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
read_models = read_models or {}
gate_id = _active_gate_id(ctx)
proposals: list[dict[str, Any]] = []
rank = 0
for debt in read_models.get("planning_debt") or []:
rank += 1
gid = str(debt.get("roadmap_item_id"))
proposals.append(
{
"proposal_key": "gate_next_actions",
"scope_type": "roadmap_item",
"scope_id": gid,
"rank": rank,
"reason_code": "planning_debt",
"summary": debt.get("message") or "Gate ohne Durchführungsplan",
"title": debt.get("title") or "Zielzustand",
"roadmap_item_id": gid,
"initiative_id": ctx.initiative_id,
"ranker_key": "heuristic_v0",
"confidence": "heuristic",
"factors": [{"code": "planning_debt", "weight": 100, "label": "Planning Debt"}],
"dependency_refs": [],
"dependency_blocked": False,
"data_source": "steering_kernel",
}
)
vocabulary = ctx.backlog_vocabulary
convertible = frozenset(vocabulary.get("convertible_kinds") or ["story", "bug", "issue"])
candidates = [
item
for item in ctx.backlog_items
if item.get("status") in COMMITTABLE
and item.get("item_kind") != "epic"
and (item.get("item_kind") or "story") in convertible
and (not gate_id or str(item.get("roadmap_item_id") or "") == gate_id)
]
for item in sorted(candidates, key=_sort_key)[:15]:
rank += 1
proposals.append(
{
"proposal_key": "gate_next_actions",
"scope_type": "backlog_item",
"scope_id": str(item["id"]),
"rank": rank,
"reason_code": "gate_backlog_ready",
"summary": "Eingang-Item am aktiven Gate committen",
"title": item.get("title") or "Backlog-Item",
"item_kind": item.get("item_kind") or "story",
"priority": item.get("priority") or "normal",
"roadmap_item_id": (
str(item["roadmap_item_id"]) if item.get("roadmap_item_id") else gate_id
),
"initiative_id": ctx.initiative_id,
"ranker_key": "heuristic_v0",
"confidence": "heuristic",
"factors": [
{
"code": "gate_alignment",
"weight": 50,
"label": "Gate-Zuordnung",
}
],
"dependency_refs": [],
"dependency_blocked": False,
"data_source": "steering_kernel",
}
)
return proposals
def gate_next_actions_attention_items(
*,
initiative_id: str,
proposals: list[dict[str, Any]],
) -> list[dict[str, Any]]:
backlog_ready = [p for p in proposals if p.get("scope_type") == "backlog_item"]
if not backlog_ready:
return []
return [
{
"kind": "gate_commit_suggested",
"severity": "info",
"title": "Gate-Planung",
"summary": f"{len(backlog_ready)} Item(s) für Gate-Commit vorgeschlagen",
"scope_type": "initiative",
"scope_id": initiative_id,
"initiative_id": initiative_id,
"reason_code": "gate_commit_suggested",
"data_source": "gate_next_actions",
}
]
@@ -0,0 +1,93 @@
"""Intake triage proposal — queue_inbox / continuous backlog (no sprint)."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
COMMITTABLE = frozenset({"new", "triaged", "accepted"})
_PRIORITY = {"critical": 0, "high": 1, "normal": 2, "low": 3}
_QUEUE_KIND_BIAS = {"bug": 0, "issue": 1, "incident": 1, "story": 2, "idea": 3}
def propose_intake_triage(
ctx: SteeringEvalContext,
*,
read_models: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
vocabulary = ctx.backlog_vocabulary
convertible = frozenset(vocabulary.get("convertible_kinds") or ["story", "bug", "issue"])
queue_mode = "queue_inbox" in ctx.steering_elements
candidates = [
item
for item in ctx.backlog_items
if item.get("status") in COMMITTABLE
and item.get("item_kind") != "epic"
and (item.get("item_kind") or "story") in convertible
]
if not candidates:
return []
def sort_key(item: dict[str, Any]) -> tuple:
kind = item.get("item_kind") or "story"
kind_bias = _QUEUE_KIND_BIAS.get(kind, 5) if queue_mode else 5
return (
_PRIORITY.get(item.get("priority") or "normal", 9),
kind_bias,
item.get("sort_order") if item.get("sort_order") is not None else 9999,
)
proposals: list[dict[str, Any]] = []
for rank, item in enumerate(sorted(candidates, key=sort_key)[:20], start=1):
kind = item.get("item_kind") or "story"
proposals.append(
{
"proposal_key": "intake_triage",
"scope_type": "backlog_item",
"scope_id": str(item["id"]),
"rank": rank,
"reason_code": "intake_triage_candidate",
"summary": "Triage-Kandidat (Heuristik — Ranker austauschbar)",
"title": item.get("title") or "Backlog-Item",
"item_kind": kind,
"priority": item.get("priority") or "normal",
"initiative_id": ctx.initiative_id,
"ranker_key": "heuristic_v0",
"confidence": "heuristic",
"factors": [
{
"code": "priority",
"weight": _PRIORITY.get(item.get("priority") or "normal", 9),
"label": "Priorität",
}
],
"dependency_refs": [],
"dependency_blocked": False,
"data_source": "steering_kernel",
}
)
return proposals
def intake_triage_attention_items(
*,
initiative_id: str,
proposals: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not proposals:
return []
return [
{
"kind": "intake_triage_suggested",
"severity": "info",
"title": "Eingang triagieren",
"summary": f"{len(proposals)} Item(s) — Kernel schlägt Triage-Reihenfolge vor",
"scope_type": "initiative",
"scope_id": initiative_id,
"initiative_id": initiative_id,
"reason_code": "intake_triage_suggested",
"data_source": "intake_triage",
}
]
+88
View File
@@ -0,0 +1,88 @@
"""Proposal provider registry — K-Ext-1 / P6."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Callable
from steering.eval_context import SteeringEvalContext
ProposalCompute = Callable[[SteeringEvalContext, dict[str, Any]], Any]
@dataclass(frozen=True)
class ProposalProvider:
key: str
requires_elements: frozenset[str]
requires_data_slices: frozenset[str]
compute: ProposalCompute
excludes_elements: frozenset[str] = field(default_factory=frozenset)
_PROVIDERS: list[ProposalProvider] = []
def register_proposal(provider: ProposalProvider) -> None:
_PROVIDERS.append(provider)
def compute_proposals(
ctx: SteeringEvalContext,
*,
read_models: dict[str, Any],
) -> dict[str, Any]:
elements = ctx.steering_elements
slices = frozenset(ctx.data_slices)
result: dict[str, Any] = {}
for provider in _PROVIDERS:
if provider.requires_elements and not provider.requires_elements <= elements:
continue
if provider.excludes_elements and provider.excludes_elements & elements:
continue
if provider.requires_data_slices and not provider.requires_data_slices <= slices:
continue
result[provider.key] = provider.compute(ctx, read_models)
return result
def _register_builtin_proposals() -> None:
from steering.proposals.gate_next_actions import propose_gate_next_actions
from steering.proposals.intake_triage import propose_intake_triage
from steering.proposals.sprint_commit import propose_sprint_commit
register_proposal(
ProposalProvider(
key="sprint_commit",
requires_elements=frozenset({"work_cycle_scope"}),
requires_data_slices=frozenset({"backlog", "work_cycles"}),
compute=lambda ctx, read_models: propose_sprint_commit(
ctx, read_models=read_models
),
)
)
register_proposal(
ProposalProvider(
key="gate_next_actions",
requires_elements=frozenset({"gate_fulfillment"}),
requires_data_slices=frozenset({"backlog", "roadmap", "actions"}),
compute=lambda ctx, read_models: propose_gate_next_actions(
ctx, read_models=read_models
),
)
)
register_proposal(
ProposalProvider(
key="intake_triage",
requires_elements=frozenset(),
requires_data_slices=frozenset({"backlog"}),
excludes_elements=frozenset({"work_cycle_scope"}),
compute=lambda ctx, read_models: propose_intake_triage(
ctx, read_models=read_models
),
)
)
_register_builtin_proposals()
+121
View File
@@ -0,0 +1,121 @@
"""Sprint commit proposals — ADP P6 / pluggable ranking."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
# Ranker registration side effects
import steering.proposals.sprint_commit_agent_v1 # noqa: F401
import steering.proposals.sprint_commit_heuristic_v0 # noqa: F401
from steering.proposals.sprint_commit_context import (
build_sprint_commit_candidates,
resolve_sprint_commit_ranker,
resolve_target_work_cycle,
)
def propose_sprint_commit(
ctx: SteeringEvalContext,
*,
read_models: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""Ranked backlog items for sprint commit — ranker is swappable, no auto-mutation."""
read_models = read_models or {}
target = resolve_target_work_cycle(ctx)
if not target:
return []
cycle_id = str(target["id"])
cycle_title = target.get("title") or "Sprint"
candidates = build_sprint_commit_candidates(ctx, target_work_cycle_id=cycle_id)
if not candidates:
return []
ranker = resolve_sprint_commit_ranker(ctx)
ranked = ranker.rank(
ctx,
candidates=candidates,
read_models=read_models,
target_work_cycle_id=cycle_id,
)
proposals: list[dict[str, Any]] = []
for row in ranked:
item = row.candidate.item
proposals.append(
{
"proposal_key": "sprint_commit",
"scope_type": "backlog_item",
"scope_id": str(item["id"]),
"rank": row.rank,
"score": row.score,
"reason_code": row.reason_code,
"summary": row.summary,
"title": item.get("title") or "Backlog-Item",
"item_kind": item.get("item_kind") or "story",
"priority": item.get("priority") or "normal",
"work_cycle_id": cycle_id,
"work_cycle_title": cycle_title,
"initiative_id": ctx.initiative_id,
"ranker_key": row.ranker_key,
"confidence": "agent" if row.ranker_key.startswith("agent") else "heuristic",
"factors": row.factors,
"dependency_refs": row.candidate.dependency_refs,
"dependency_blocked": row.candidate.dependency_blocked,
"data_source": "steering_kernel",
}
)
return proposals
def sprint_commit_attention_items(
*,
initiative_id: str,
proposals: list[dict[str, Any]],
actions: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Attention when sprint has room for proposed commits."""
from steering.proposals.sprint_commit_context import OPEN_ACTION
if not proposals:
return []
target_id = proposals[0].get("work_cycle_id")
if not target_id:
return []
sprint_actions = [
a
for a in actions
if a.get("work_cycle_id") and str(a["work_cycle_id"]) == str(target_id)
]
open_in_sprint = sum(1 for a in sprint_actions if a.get("status") in OPEN_ACTION)
ready = [p for p in proposals if not p.get("dependency_blocked")]
items: list[dict[str, Any]] = []
cycle_title = proposals[0].get("work_cycle_title") or "Sprint"
if open_in_sprint == 0 and ready:
ranker = proposals[0].get("ranker_key", "heuristic_v0")
items.append(
{
"kind": "sprint_commit_suggested",
"severity": "info",
"title": cycle_title,
"summary": (
f"{len(ready)} commit-bereite Item(s) — "
f"Vorschlag via Ranker {ranker}"
),
"scope_type": "work_cycle",
"scope_id": str(target_id),
"initiative_id": initiative_id,
"reason_code": "sprint_commit_suggested",
"data_source": "sprint_commit_proposal",
}
)
return items
@@ -0,0 +1,64 @@
"""Agent sprint ranker slot — placeholder for Principle Gate / Actor execution."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
from steering.proposals.sprint_commit_context import (
RankedSprintCommitCandidate,
SprintCommitCandidate,
register_sprint_commit_ranker,
)
from steering.proposals.sprint_commit_heuristic_v0 import HeuristicV0SprintCommitRanker
_FALLBACK = HeuristicV0SprintCommitRanker()
class AgentV1SprintCommitRanker:
"""
Agent-gestütztes Ranking — noch nicht aktiv (Principle Gate).
Kontext kommt aus Snapshot/Operating Context; Scoring über auditierten Actor,
nicht aus hardcodiertem Prompt. Bis Freigabe: Fallback auf heuristic_v0.
"""
key = "agent_v1"
def rank(
self,
ctx: SteeringEvalContext,
*,
candidates: list[SprintCommitCandidate],
read_models: dict[str, Any],
target_work_cycle_id: str,
) -> list[RankedSprintCommitCandidate]:
# TODO(P6+): Actor-Slot + Governance-Pack; KI wählt Subset + Begründung
ranked = _FALLBACK.rank(
ctx,
candidates=candidates,
read_models=read_models,
target_work_cycle_id=target_work_cycle_id,
)
return [
RankedSprintCommitCandidate(
candidate=row.candidate,
rank=row.rank,
score=row.score,
reason_code=row.reason_code,
summary=f"{row.summary} (Agent-Ranker: Fallback heuristic_v0)",
factors=row.factors
+ [
{
"code": "ranker_fallback",
"weight": 0,
"label": "agent_v1 noch nicht freigegeben",
}
],
ranker_key="agent_v1_fallback",
)
for row in ranked
]
register_sprint_commit_ranker(AgentV1SprintCommitRanker())
@@ -0,0 +1,173 @@
"""Sprint commit ranking — pluggable rankers (heuristic now, agent later)."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Protocol
from steering.eval_context import SteeringEvalContext
COMMITTABLE_STATUSES = frozenset({"new", "triaged", "accepted"})
PLANABLE_CYCLE_STATUSES = frozenset({"planned", "active"})
OPEN_ACTION = frozenset({"open", "ready", "in_progress", "blocked", "review_required"})
_DONE_ACTION = frozenset({"done", "discarded"})
@dataclass
class SprintCommitCandidate:
item: dict[str, Any]
dependency_refs: list[dict[str, Any]] = field(default_factory=list)
dependency_blocked: bool = False
dependency_reason: str | None = None
@dataclass
class RankedSprintCommitCandidate:
candidate: SprintCommitCandidate
rank: int
score: float
reason_code: str
summary: str
factors: list[dict[str, Any]]
ranker_key: str
class SprintCommitRanker(Protocol):
key: str
def rank(
self,
ctx: SteeringEvalContext,
*,
candidates: list[SprintCommitCandidate],
read_models: dict[str, Any],
target_work_cycle_id: str,
) -> list[RankedSprintCommitCandidate]:
...
_RANKERS: dict[str, SprintCommitRanker] = {}
def register_sprint_commit_ranker(ranker: SprintCommitRanker) -> None:
_RANKERS[ranker.key] = ranker
def resolve_sprint_commit_ranker(ctx: SteeringEvalContext) -> SprintCommitRanker:
"""
Ranker-Auswahl — nicht hardcodiert.
Zukünftig: Governance/Method-Metadata (`proposal_rankers.sprint_commit=agent_v1`)
oder Actor-Slot mit auditiertem Agent-Scoring. Default: heuristic_v0 (Fallback).
"""
configured = (
(ctx.operating_context.get("proposal_rankers") or {}).get("sprint_commit")
or (ctx.operating_context.get("method_capabilities") or {}).get(
"sprint_commit_ranker"
)
)
if configured and configured in _RANKERS:
return _RANKERS[configured]
return _RANKERS["heuristic_v0"]
def _action_by_id(actions: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
return {str(a["id"]): a for a in actions if a.get("id")}
def build_sprint_commit_candidates(
ctx: SteeringEvalContext,
*,
target_work_cycle_id: str,
) -> list[SprintCommitCandidate]:
"""Kandidaten + Abhängigkeitskontext — keine feste Bug/Story-Reihenfolge."""
vocabulary = ctx.backlog_vocabulary
convertible = frozenset(
vocabulary.get("convertible_kinds") or ["story", "bug", "issue"]
)
actions_by_id = _action_by_id(ctx.actions)
candidates: list[SprintCommitCandidate] = []
for item in ctx.backlog_items:
if item.get("status") not in COMMITTABLE_STATUSES:
continue
if item.get("item_kind") == "epic":
continue
if (item.get("item_kind") or "story") not in convertible:
continue
refs: list[dict[str, Any]] = []
blocked = False
block_reason: str | None = None
parent_action_id = item.get("parent_action_id")
if parent_action_id:
parent = actions_by_id.get(str(parent_action_id))
refs.append(
{
"ref_type": "parent_action",
"ref_id": str(parent_action_id),
"status": parent.get("status") if parent else "missing",
"title": parent.get("title") if parent else None,
}
)
if not parent:
blocked = True
block_reason = "missing_parent_action"
elif parent.get("status") not in _DONE_ACTION:
in_target_sprint = (
parent.get("work_cycle_id")
and str(parent["work_cycle_id"]) == str(target_work_cycle_id)
)
if not in_target_sprint:
blocked = True
block_reason = "waiting_on_feature_action"
parent_backlog_id = item.get("parent_backlog_id")
if parent_backlog_id:
refs.append(
{
"ref_type": "parent_epic",
"ref_id": str(parent_backlog_id),
}
)
candidates.append(
SprintCommitCandidate(
item=item,
dependency_refs=refs,
dependency_blocked=blocked,
dependency_reason=block_reason,
)
)
return candidates
def resolve_target_work_cycle(ctx: SteeringEvalContext) -> dict[str, Any] | None:
cycles = [
c for c in ctx.work_cycles if c.get("status") in PLANABLE_CYCLE_STATUSES
]
if not cycles:
return None
if ctx.horizon.work_cycle_id:
match = next(
(c for c in cycles if str(c["id"]) == str(ctx.horizon.work_cycle_id)),
None,
)
if match:
return match
planned = sorted(
[c for c in cycles if c.get("status") == "planned"],
key=lambda c: (c.get("sort_order", 0), str(c["id"])),
)
if planned:
return planned[0]
active = sorted(
[c for c in cycles if c.get("status") == "active"],
key=lambda c: (c.get("sort_order", 0), str(c["id"])),
)
return active[0] if active else None
@@ -0,0 +1,157 @@
"""Default sprint ranker — explicit fallback, not product policy."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
from steering.proposals.sprint_commit_context import (
RankedSprintCommitCandidate,
SprintCommitCandidate,
SprintCommitRanker,
register_sprint_commit_ranker,
)
_PRIORITY_SCORE = {"critical": 100, "high": 75, "normal": 50, "low": 25}
_KIND_BIAS = {"bug": 5, "issue": 3, "incident": 3, "story": 0, "idea": -5}
class HeuristicV0SprintCommitRanker:
"""
Fallback-Ranker bis Agent/Regelwerk aktiv ist.
Sortiert primär nach Priorität + Eingangsreihenfolge; item_kind ist nur leichte
Tendenz in `factors` — keine „Bugs immer zuerst“-Policy.
"""
key = "heuristic_v0"
def rank(
self,
ctx: SteeringEvalContext,
*,
candidates: list[SprintCommitCandidate],
read_models: dict[str, Any],
target_work_cycle_id: str,
) -> list[RankedSprintCommitCandidate]:
scored: list[tuple[float, SprintCommitCandidate, list[dict[str, Any]]]] = []
for candidate in candidates:
item = candidate.item
priority = item.get("priority") or "normal"
kind = item.get("item_kind") or "story"
priority_score = _PRIORITY_SCORE.get(priority, 50)
kind_bias = _KIND_BIAS.get(kind, 0)
factors: list[dict[str, Any]] = [
{
"code": "priority",
"weight": priority_score,
"label": f"Priorität {priority}",
},
{
"code": "intake_order",
"weight": -(item.get("sort_order") or 0),
"label": "Eingangsreihenfolge",
},
]
if kind_bias:
factors.append(
{
"code": "kind_bias",
"weight": kind_bias,
"label": f"Typ {kind} (leichte Tendenz, keine Policy)",
}
)
score = priority_score + kind_bias - (item.get("sort_order") or 0) * 0.01
if candidate.dependency_blocked:
score -= 1000
factors.append(
{
"code": "dependency_blocked",
"weight": -1000,
"label": candidate.dependency_reason or "Abhängigkeit offen",
}
)
epic_rollups = read_models.get("epic_rollup") or []
parent_epic = item.get("parent_backlog_id")
if parent_epic:
rollup = next(
(
r
for r in epic_rollups
if str(r.get("epic_backlog_id")) == str(parent_epic)
),
None,
)
if rollup and rollup.get("status") == "in_progress":
score += 2
factors.append(
{
"code": "epic_in_progress",
"weight": 2,
"label": "Epic mit laufender Arbeit",
}
)
scored.append((score, candidate, factors))
scored.sort(
key=lambda row: (
-row[0],
(row[1].item.get("title") or "").lower(),
)
)
ranked: list[RankedSprintCommitCandidate] = []
for index, (score, candidate, factors) in enumerate(scored[:20], start=1):
item = candidate.item
reason_code = _reason_code(item, candidate)
ranked.append(
RankedSprintCommitCandidate(
candidate=candidate,
rank=index,
score=score,
reason_code=reason_code,
summary=_summary_for(reason_code, candidate),
factors=factors,
ranker_key=self.key,
)
)
return ranked
def _reason_code(item: dict[str, Any], candidate: SprintCommitCandidate) -> str:
if candidate.dependency_blocked:
return candidate.dependency_reason or "dependency_blocked"
priority = item.get("priority") or "normal"
if priority == "critical":
return "priority_critical"
if priority == "high":
return "priority_high"
kind = item.get("item_kind") or "story"
if kind in ("bug", "issue", "incident"):
return "candidate_bug_or_issue"
return "candidate_ready"
def _summary_for(reason_code: str, candidate: SprintCommitCandidate) -> str:
if candidate.dependency_blocked:
if reason_code == "waiting_on_feature_action":
return "Wartet auf Feature-Arbeitspaket im Sprint oder erledigt"
if reason_code == "missing_parent_action":
return "Feature-Referenz fehlt — Abhängigkeit klären"
return "Abhängigkeit noch nicht erfüllt"
labels = {
"priority_critical": "Hohe Dringlichkeit (Priorität critical)",
"priority_high": "Erhöhte Priorität",
"candidate_bug_or_issue": "Kandidat (Heuristik — kein Bug-Zwang)",
"candidate_ready": "Bereit zum Commit (Heuristik)",
}
return labels.get(reason_code, "Sprint-Commit-Kandidat (Heuristik)")
register_sprint_commit_ranker(HeuristicV0SprintCommitRanker())
+1
View File
@@ -0,0 +1 @@
"""Steering read models — derived views, no OM mutation."""
+170
View File
@@ -0,0 +1,170 @@
"""Epic roll-up read model — ADP P4 / Backlog-Hierarchie.
Fortschritt eines Epics = Aggregation committeter/erledigter Stories im Subbaum.
Kein Gate-Status; Leading bleibt Action.
"""
from __future__ import annotations
from typing import Any, Literal
EpicRollupStatus = Literal["empty", "intake_only", "in_progress", "done"]
_DONE_ACTION = frozenset({"done"})
_ACTIVE_ACTION = frozenset({"open", "ready", "in_progress", "blocked", "review_required"})
_CHILD_EXCLUDE = frozenset({"rejected"})
def _action_status(actions_by_id: dict[str, dict[str, Any]], action_id: Any) -> str | None:
if not action_id:
return None
row = actions_by_id.get(str(action_id))
return row.get("status") if row else None
def compute_epic_rollup(
*,
backlog_items: list[dict[str, Any]],
actions: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Roll-up pro Epic-BacklogItem (item_kind=epic, nicht rejected)."""
actions_by_id = {str(a["id"]): a for a in actions if a.get("id")}
epics = [
b
for b in backlog_items
if b.get("item_kind") == "epic" and b.get("status") not in _CHILD_EXCLUDE
]
rollups: list[dict[str, Any]] = []
for epic in epics:
epic_id = str(epic["id"])
children = [
b
for b in backlog_items
if b.get("parent_backlog_id")
and str(b["parent_backlog_id"]) == epic_id
and b.get("item_kind") != "epic"
and b.get("status") not in _CHILD_EXCLUDE
]
child_total = len(children)
committed: list[dict[str, Any]] = []
uncommitted: list[dict[str, Any]] = []
for child in children:
if child.get("status") == "converted" or child.get("converted_action_id"):
committed.append(child)
else:
uncommitted.append(child)
actions_done = actions_in_progress = actions_open = 0
for child in committed:
status = _action_status(actions_by_id, child.get("converted_action_id"))
if status in _DONE_ACTION:
actions_done += 1
elif status in _ACTIVE_ACTION:
actions_in_progress += 1
actions_open += 1
elif status:
actions_open += 1
if child_total == 0:
rollup_status: EpicRollupStatus = "empty"
elif len(committed) == 0:
rollup_status = "intake_only"
elif actions_done == child_total:
rollup_status = "done"
else:
rollup_status = "in_progress"
completion_ratio = actions_done / child_total if child_total else None
commit_ratio = len(committed) / child_total if child_total else None
rollups.append(
{
"epic_backlog_id": epic_id,
"epic_title": epic.get("title") or "Epic",
"child_total": child_total,
"child_uncommitted": len(uncommitted),
"child_committed": len(committed),
"actions_done": actions_done,
"actions_in_progress": actions_in_progress,
"actions_open": actions_open,
"completion_ratio": completion_ratio,
"commit_ratio": commit_ratio,
"status": rollup_status,
"data_source": "epic_rollup_v0.1",
}
)
rollups.sort(key=lambda r: (r["status"] != "in_progress", r["epic_title"].lower()))
return rollups
def epic_rollup_attention_items(
*,
initiative_id: str,
rollups: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Attention aus Epic-Roll-up — Steuerung, nicht nur Anzeige."""
items: list[dict[str, Any]] = []
for rollup in rollups:
epic_id = rollup["epic_backlog_id"]
title = rollup["epic_title"]
child_total = rollup["child_total"]
if child_total == 0:
continue
if rollup["child_committed"] == 0:
items.append(
{
"kind": "epic_awaiting_commit",
"severity": "info",
"title": title,
"summary": (
f"Epic hat {rollup['child_uncommitted']} Item(s) im Eingang — "
"noch keine committete Arbeit"
),
"scope_type": "backlog",
"scope_id": epic_id,
"initiative_id": initiative_id,
"reason_code": "epic_awaiting_commit",
"data_source": "epic_rollup",
}
)
continue
if rollup["child_uncommitted"] > 0 and rollup["actions_in_progress"] > 0:
items.append(
{
"kind": "epic_uncommitted_during_execution",
"severity": "warning",
"title": title,
"summary": (
f"{rollup['child_uncommitted']} Item(s) noch im Eingang, "
f"während {rollup['actions_in_progress']} Arbeitspaket(e) laufen"
),
"scope_type": "backlog",
"scope_id": epic_id,
"initiative_id": initiative_id,
"reason_code": "epic_uncommitted_during_execution",
"data_source": "epic_rollup",
}
)
if rollup["status"] == "done":
items.append(
{
"kind": "epic_complete",
"severity": "info",
"title": title,
"summary": "Alle Stories im Epic erledigt",
"scope_type": "backlog",
"scope_id": epic_id,
"initiative_id": initiative_id,
"reason_code": "epic_complete",
"data_source": "epic_rollup",
}
)
return items
@@ -0,0 +1,27 @@
"""Execution graph read model — critical_path / gate_fulfillment."""
from __future__ import annotations
from typing import Any
from steering.eval_context import SteeringEvalContext
from steering.graph.execution_engine import compute_execution_graph_state
def compute_execution_graph_read_model(ctx: SteeringEvalContext) -> dict[str, Any]:
from services.execution_plan import list_dependencies_for_initiative
from steering.strategies.next_action.execution_ready import (
gate_horizon_scope_for_method,
)
gate_scope = gate_horizon_scope_for_method(
ctx.binding.primary_method_key, ctx.tenant_ctx, ctx.initiative_id
)
dependencies = list_dependencies_for_initiative(
tenant_id=ctx.tenant_ctx.tenant_id, initiative_id=ctx.initiative_id
)
return compute_execution_graph_state(
actions=ctx.actions,
dependencies=dependencies,
scope_roadmap_item_id=gate_scope,
)
Loaded 100 of 317 files, more files were not shown because too many files have changed in this diff. Show more