Compare commits

...
20 Commits
Author SHA1 Message Date
LarsandCursor a05bd34af3 feat(A1): Übungen als AP mit Wochentagsplan
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Successful in 5m3s
Test Suite / lint-backend (push) Successful in 3s
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
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 / pytest-backend (push) Successful in 4m57s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Successful in 4m52s
Test Suite / lint-backend (push) Successful in 3s
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
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 / pytest-backend (push) Successful in 4m52s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Failing after 5m1s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
Test Suite / compose-smoke (push) Has been skipped
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 / lint-backend (push) Waiting to run
Test Suite / compose-smoke (push) Waiting to run
Test Suite / k6 /api/health Baseline (push) Blocked by required conditions
Test Suite / playwright-smoke (push) Blocked by required conditions
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Has been cancelled
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 / pytest-backend (push) Failing after 4m44s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Test Suite / compose-smoke (push) Has been skipped
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 / pytest-backend (push) Failing after 5m3s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Test Suite / compose-smoke (push) Has been skipped
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 / pytest-backend (push) Successful in 4m43s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Failing after 4m46s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
Test Suite / compose-smoke (push) Has been skipped
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 / pytest-backend (push) Successful in 4m54s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Successful in 4m38s
Test Suite / lint-backend (push) Successful in 2s
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
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 / pytest-backend (push) Failing after 4m41s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Test Suite / compose-smoke (push) Has been skipped
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 / pytest-backend (push) Failing after 4m39s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 3s
Test Suite / compose-smoke (push) Has been skipped
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 / pytest-backend (push) Failing after 4m37s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 2s
Test Suite / compose-smoke (push) Has been skipped
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 / lint-backend (push) Waiting to run
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 / 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 / pytest-backend (push) Successful in 4m32s
Test Suite / lint-backend (push) Successful in 2s
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
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
101 changed files with 8810 additions and 601 deletions

No files matched your search

@@ -16,6 +16,7 @@ from steering.context import get_steering_context_dto
from steering.kernel import evaluate_steering 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")
@@ -383,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,
+1 -1
View File
@@ -124,7 +124,7 @@ INITIATIVE_UI_PROFILES: dict[str, dict[str, Any]] = {
"planDefaultRoute": "/plan/gates", "planDefaultRoute": "/plan/gates",
"workDefaultRoute": "/work/today", "workDefaultRoute": "/work/today",
"controlDefaultRoute": "/control/status", "controlDefaultRoute": "/control/status",
"planOutlineKeys": ["profile", "gates", "inbox", "work"], "planOutlineKeys": ["profile", "gates", "work"],
"workNavKeys": ["today", "mine", "sprint"], "workNavKeys": ["today", "mine", "sprint"],
"dataSlices": [ "dataSlices": [
"actions", "actions",
@@ -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 $$;
+43
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
@@ -155,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,
+2
View File
@@ -132,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]:
@@ -648,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,
+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)
+8 -3
View File
@@ -25,8 +25,9 @@ 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, parent_action_id, 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", "bug", "issue", "tech_debt"}) ACTION_KINDS = frozenset({"delivery", "planning", "review", "bug", "issue", "tech_debt"})
@@ -47,6 +48,7 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
"work_cycle_id", "work_cycle_id",
"parent_action_id", "parent_action_id",
"owner_actor_id", "owner_actor_id",
"schedule_id",
): ):
if result.get(key): if result.get(key):
result[key] = str(result[key]) result[key] = str(result[key])
@@ -337,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(
+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)
+160 -14
View File
@@ -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 = [
@@ -185,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] = []
@@ -194,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,
@@ -205,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"):
@@ -217,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(
@@ -309,6 +312,149 @@ def _apply_a2(
} }
def _retire_legacy_linear_stages_for_progression(
*,
tenant_id: str,
initiative_id: str,
keep_gate_ids: frozenset[str],
user_id: Optional[str] = None,
) -> None:
"""Starter-Kit-Stufen zurückstellen, wenn Join-Graph angelegt wird."""
from services.maturity_practice import list_practices_for_stage, update_recurring_element
from services.roadmap import list_roadmap_items_for_initiative, update_roadmap_item
for item in list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
):
if item.get("item_type") != "maturity_stage":
continue
if str(item["id"]) in keep_gate_ids:
continue
if item.get("status") not in ("active", "at_risk"):
continue
update_roadmap_item(
tenant_id=tenant_id,
item_id=item["id"],
status="planned",
user_id=user_id,
)
for practice in list_practices_for_stage(
tenant_id=tenant_id,
initiative_id=initiative_id,
stage_id=item["id"],
):
if practice.get("status") == "active":
update_recurring_element(
tenant_id=tenant_id,
recurring_id=practice["id"],
status="paused",
user_id=user_id,
)
def apply_a1_progression_demo(
*,
tenant_id: str,
initiative_id: str,
user_id: Optional[str] = None,
) -> dict[str, Any]:
"""PO-Kernbild: 2 parallele Gates → Join → Ausgänge (AP-A1-PM-6). Idempotent wenn Struktur existiert."""
from services.maturity_practice import seed_practices_for_stage
from services.roadmap import add_dependency, create_roadmap_item, list_roadmap_items_for_initiative
existing = list_roadmap_items_for_initiative(
tenant_id=tenant_id, initiative_id=initiative_id
)
if any(item.get("item_type") == "join_gate" for item in existing):
return {"applied": False, "reason": "progression_exists"}
d1 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Dehnung — Einstieg",
item_type="maturity_stage",
status="active",
sort_order=10,
user_id=user_id,
)
h1 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Hüftrotation — Einstieg",
item_type="maturity_stage",
status="active",
sort_order=20,
user_id=user_id,
)
join = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Mawashi Geri zur Hüfte",
item_type="join_gate",
status="planned",
sort_order=30,
user_id=user_id,
)
d2 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Dehnung — nach Join",
item_type="maturity_stage",
status="planned",
sort_order=40,
user_id=user_id,
)
h2 = create_roadmap_item(
tenant_id=tenant_id,
initiative_id=initiative_id,
title="Hüftrotation — nach Join",
item_type="maturity_stage",
status="planned",
sort_order=50,
user_id=user_id,
)
for from_id, to_id in (
(join["id"], d1["id"]),
(join["id"], h1["id"]),
(d2["id"], join["id"]),
(h2["id"], join["id"]),
):
try:
add_dependency(
tenant_id=tenant_id,
from_item_id=from_id,
to_item_id=to_id,
dependency_type="requires",
user_id=user_id,
)
except ValueError as exc:
if "existiert bereits" not in str(exc):
raise
seed_practices_for_stage(
tenant_id=tenant_id, initiative_id=initiative_id, stage=d1, user_id=user_id
)
seed_practices_for_stage(
tenant_id=tenant_id, initiative_id=initiative_id, stage=h1, user_id=user_id
)
_retire_legacy_linear_stages_for_progression(
tenant_id=tenant_id,
initiative_id=initiative_id,
keep_gate_ids=frozenset(
str(gate["id"]) for gate in (d1, h1, d2, h2)
),
user_id=user_id,
)
return {
"applied": True,
"join": join["title"],
"active_gates": [d1["title"], h1["title"]],
}
def _apply_b2b( def _apply_b2b(
*, *,
tenant_id: str, tenant_id: str,
+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:
+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,
}
+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:
+71 -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,
@@ -760,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
@@ -767,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),
) )
@@ -783,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,
+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
@@ -7,17 +7,13 @@ from typing import Any
from steering.signals import default_rules from steering.signals import default_rules
from steering.strategies.next_action.default_strategy import DefaultNextActionStrategy from steering.strategies.next_action.default_strategy import DefaultNextActionStrategy
from steering.strategies.next_action.execution_ready import ( from steering.strategies.next_action.execution_ready import (
first_active_gate_id,
list_execution_ready_candidates, list_execution_ready_candidates,
merge_candidates, merge_candidates,
) )
from steering.strategies.next_action.product_milestone_driven import ( from steering.strategies.next_action.product_milestone_driven import (
ProductMilestoneDrivenStrategy, ProductMilestoneDrivenStrategy,
) )
from steering.strategies.next_action.recurring_helpers import ( from steering.strategies.next_action.recurring_helpers import recurring_due_candidates
active_recurring_candidates,
recurring_due_candidates,
)
from steering.strategies.next_action.registry import ( from steering.strategies.next_action.registry import (
get_next_action_strategy, get_next_action_strategy,
register_next_action_strategy, register_next_action_strategy,
@@ -44,11 +40,14 @@ class MaturityProgressionStrategy:
return _default.evaluate(ctx, limit=limit) return _default.evaluate(ctx, limit=limit)
recurring = recurring_due_candidates(ctx, initiative_id, limit=limit) recurring = recurring_due_candidates(ctx, initiative_id, limit=limit)
if not recurring:
recurring = active_recurring_candidates(ctx, initiative_id, limit=1)
remaining = limit - len(recurring) remaining = limit - len(recurring)
gate_scope = first_active_gate_id(ctx, initiative_id) from services.progression_graph import list_active_work_gates
active_gates = list_active_work_gates(
tenant_id=ctx.tenant_id, initiative_id=initiative_id
)
gate_scope = active_gates[0]["id"] if len(active_gates) == 1 else None
ready: list[dict[str, Any]] = [] ready: list[dict[str, Any]] = []
if remaining > 0: if remaining > 0:
ready = list_execution_ready_candidates( ready = list_execution_ready_candidates(
@@ -8,6 +8,46 @@ from db import get_connection
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from tenant_context import TenantContext from tenant_context import TenantContext
_PRACTICE_DUE_SQL = """
SELECT
'recurring_due' AS kind,
re.title AS title,
COALESCE(NULLIF(re.description, ''), 'Heutige Übung') AS summary,
re.initiative_id,
re.id AS recurring_id,
NULL::uuid AS action_id,
NULL::uuid AS backlog_item_id,
'recurring_due' AS reason_code,
'Übung heute erledigen' AS recommended_action
FROM recurring_elements re
LEFT JOIN roadmap_items ri
ON ri.id = re.roadmap_item_id AND ri.tenant_id = re.tenant_id
WHERE re.tenant_id = %s AND re.initiative_id = %s
AND re.status = 'active'
AND (re.next_due_at IS NULL OR re.next_due_at <= NOW())
AND (re.roadmap_item_id IS NULL OR (ri.status = 'active' AND ri.item_type = 'maturity_stage'))
AND NOT EXISTS (
SELECT 1 FROM cadence_instances ci
WHERE ci.recurring_element_id = re.id
AND ci.tenant_id = re.tenant_id
AND ci.status = 'completed'
AND ci.completed_at >= CURRENT_DATE
)
ORDER BY re.next_due_at ASC NULLS FIRST, re.title
LIMIT %s
"""
def _serialize_recurring_rows(rows) -> list[dict[str, Any]]:
items: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item["initiative_id"] = str(item["initiative_id"])
if item.get("recurring_id"):
item["recurring_id"] = str(item["recurring_id"])
items.append(item)
return items
def recurring_due_candidates( def recurring_due_candidates(
ctx: TenantContext, initiative_id: str, *, limit: int ctx: TenantContext, initiative_id: str, *, limit: int
@@ -15,33 +55,8 @@ def recurring_due_candidates(
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(_PRACTICE_DUE_SQL, (ctx.tenant_id, initiative_id, limit))
""" return _serialize_recurring_rows(cur.fetchall())
SELECT
'recurring_due' AS kind,
re.title AS title,
'Wiederkehrendes Element fällig' AS summary,
re.initiative_id,
NULL::uuid AS action_id,
NULL::uuid AS backlog_item_id,
'recurring_due' AS reason_code,
'Rhythmus-Element bearbeiten' AS recommended_action
FROM recurring_elements re
WHERE re.tenant_id = %s AND re.initiative_id = %s
AND re.status = 'active'
AND re.next_due_at IS NOT NULL
AND re.next_due_at <= NOW()
ORDER BY re.next_due_at ASC
LIMIT %s
""",
(ctx.tenant_id, initiative_id, limit),
)
items: list[dict[str, Any]] = []
for row in cur.fetchall():
item = dict(row)
item["initiative_id"] = str(item["initiative_id"])
items.append(item)
return items
finally: finally:
conn.close() conn.close()
@@ -49,34 +64,5 @@ def recurring_due_candidates(
def active_recurring_candidates( def active_recurring_candidates(
ctx: TenantContext, initiative_id: str, *, limit: int = 1 ctx: TenantContext, initiative_id: str, *, limit: int = 1
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
"""Active recurring as 'heutige Übung' when nothing is due yet.""" """Due practices only — no fallback when already completed today."""
conn = get_connection() return recurring_due_candidates(ctx, initiative_id, limit=limit)
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"""
SELECT
'recurring_due' AS kind,
re.title AS title,
'Heutige Übung / Routine' AS summary,
re.initiative_id,
NULL::uuid AS action_id,
NULL::uuid AS backlog_item_id,
'recurring_active' AS reason_code,
'Routine ausführen' AS recommended_action
FROM recurring_elements re
WHERE re.tenant_id = %s AND re.initiative_id = %s
AND re.status = 'active'
ORDER BY re.next_due_at ASC NULLS LAST, re.title
LIMIT %s
""",
(ctx.tenant_id, initiative_id, limit),
)
items: list[dict[str, Any]] = []
for row in cur.fetchall():
item = dict(row)
item["initiative_id"] = str(item["initiative_id"])
items.append(item)
return items
finally:
conn.close()
+108
View File
@@ -0,0 +1,108 @@
"""AP A1.1 — CadenceInstance complete practice flow."""
from __future__ import annotations
from tests.factories import provision_user_in_tenant
from tests.test_initiatives_actions import _auth, _create_initiative, _login
def test_complete_daily_practice_advances_cadence(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Spagat Cadence",
archetype_key="initiative.maturity_journey",
)
initiative_id = created.json()["id"]
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
).json()
assert recurring
item = recurring[0]
assert item.get("open_cadence_instance")
assert item["open_cadence_instance"]["status"] == "open"
recurring_id = item["id"]
completed = client.post(
f"/api/recurring/{recurring_id}/complete",
json={"measurement_note": "45° Spagat gehalten"},
headers=_auth(token),
)
assert completed.status_code == 200
body = completed.json()
assert body["completed_instance"]["status"] == "completed"
assert body["completed_instance"]["measurement_note"] == "45° Spagat gehalten"
assert body["next_due_at"]
assert body["recurring"]["next_due_at"]
refreshed = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
).json()
assert refreshed[0]["today_completed"] is True
assert refreshed[0]["today_measurement_note"] == "45° Spagat gehalten"
def test_steering_next_action_includes_recurring_id(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Spagat Next",
archetype_key="initiative.maturity_journey",
)
initiative_id = created.json()["id"]
snap = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap.status_code == 200
next_actions = snap.json().get("next_actions") or []
recurring_items = [a for a in next_actions if a.get("kind") == "recurring_due"]
assert recurring_items
assert recurring_items[0].get("recurring_id")
def test_steering_next_action_excludes_completed_today(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Spagat Complete Today",
archetype_key="initiative.maturity_journey",
)
initiative_id = created.json()["id"]
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
).json()
recurring_id = recurring[0]["id"]
completed = client.post(
f"/api/recurring/{recurring_id}/complete",
json={"measurement_note": "done"},
headers=_auth(token),
)
assert completed.status_code == 200
snap = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap.status_code == 200
next_actions = snap.json().get("next_actions") or []
completed_again = [
a for a in next_actions if a.get("recurring_id") == recurring_id
]
assert not completed_again
+147
View File
@@ -0,0 +1,147 @@
"""Gate Activity Set API — A1 minimal usability."""
from __future__ import annotations
from tests.factories import provision_user_in_tenant
from tests.test_initiatives_actions import _auth, _create_initiative, _login
def test_gate_practice_create_and_list(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="A1 Gate Practices",
archetype_key="initiative.maturity_journey",
apply_starter_kit=False,
)
initiative_id = created.json()["id"]
gate = client.post(
f"/api/initiatives/{initiative_id}/roadmap/items",
json={
"title": "Dehnung — Einstieg",
"item_type": "maturity_stage",
"status": "active",
},
headers=_auth(token),
)
assert gate.status_code == 201
gate_id = gate.json()["id"]
empty = client.get(
f"/api/roadmap-items/{gate_id}/practices",
headers=_auth(token),
)
assert empty.status_code == 200
assert empty.json() == []
created_practice = client.post(
f"/api/roadmap-items/{gate_id}/practices",
json={
"title": "Vorbeuge halten",
"description": "3×30 Sek.",
},
headers=_auth(token),
)
assert created_practice.status_code == 201
body = created_practice.json()
assert body["roadmap_item_id"] == gate_id
assert body.get("action_id")
assert (body.get("schedule") or {}).get("schedule_kind") == "weekdays"
assert body["schedule"]["weekday_mask"] > 0
listed = client.get(
f"/api/roadmap-items/{gate_id}/practices",
headers=_auth(token),
)
assert listed.status_code == 200
assert len(listed.json()) == 1
assert listed.json()[0]["title"] == "Vorbeuge halten"
assert listed.json()[0].get("action_id")
def test_gate_practice_weekdays_creates_action_bridge(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="A1 Weekday Practices",
archetype_key="initiative.maturity_journey",
apply_starter_kit=False,
)
initiative_id = created.json()["id"]
gate = client.post(
f"/api/initiatives/{initiative_id}/roadmap/items",
json={
"title": "Dehnung — Einstieg",
"item_type": "maturity_stage",
"status": "active",
},
headers=_auth(token),
)
assert gate.status_code == 201
gate_id = gate.json()["id"]
created_practice = client.post(
f"/api/roadmap-items/{gate_id}/practices",
json={
"title": "Statisches Stretching",
"schedule": {
"schedule_kind": "weekdays",
"weekday_mask": 1 | 4 | 64,
},
},
headers=_auth(token),
)
assert created_practice.status_code == 201, created_practice.text
body = created_practice.json()
assert body["action_id"]
assert body.get("schedule", {}).get("schedule_kind") == "weekdays"
assert body["schedule"]["weekday_mask"] == 1 | 4 | 64
action = client.get(
f"/api/actions/{body['action_id']}",
headers=_auth(token),
)
assert action.status_code == 200
assert action.json()["roadmap_item_id"] == gate_id
assert action.json()["status"] == "open"
def test_join_gate_rejects_practices(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Join no practices",
archetype_key="initiative.maturity_journey",
apply_starter_kit=False,
)
initiative_id = created.json()["id"]
join = client.post(
f"/api/initiatives/{initiative_id}/roadmap/items",
json={
"title": "Konsolidierung",
"item_type": "join_gate",
"status": "planned",
},
headers=_auth(token),
)
assert join.status_code == 201
join_id = join.json()["id"]
rejected = client.post(
f"/api/roadmap-items/{join_id}/practices",
json={"title": "Nope", "interval_days": 1},
headers=_auth(token),
)
assert rejected.status_code == 400
+164
View File
@@ -0,0 +1,164 @@
"""AP-A1-PM — progression join graph tests."""
from __future__ import annotations
from services.progression_graph import compute_progression_lanes
from tests.factories import provision_user_in_tenant
from tests.test_initiatives_actions import _auth, _create_initiative, _login
def _item(item_id: str, item_type: str = "maturity_stage", **kwargs):
return {
"id": item_id,
"item_type": item_type,
"status": kwargs.get("status", "planned"),
"title": kwargs.get("title", item_id),
"sort_order": kwargs.get("sort_order", 0),
}
def _requires(from_id: str, to_id: str) -> dict:
return {
"from_item_id": from_id,
"to_item_id": to_id,
"dependency_type": "requires",
}
def test_progression_lanes_parallel_sources_and_post_join():
items = [
_item("d1", status="active", title="Dehnung — Einstieg"),
_item("h1", status="active", title="Hüftrotation — Einstieg"),
_item("join", item_type="join_gate", title="Join"),
_item("d2", title="Dehnung — nach Join"),
_item("h2", title="Hüftrotation — nach Join"),
]
deps = [
_requires("join", "d1"),
_requires("join", "h1"),
_requires("d2", "join"),
_requires("h2", "join"),
]
lanes = compute_progression_lanes(items=items, dependencies=deps)
assert lanes["d1"].startswith("source:")
assert lanes["h1"].startswith("source:")
assert lanes["h1"] != lanes["d1"]
assert lanes["d2"] == "post-join:d2"
assert lanes["h2"] == "post-join:h2"
assert lanes["d2"] != lanes["h2"]
def test_progression_lanes_sequential_chain_shares_lane():
items = [
_item("g1", status="active"),
_item("g2"),
_item("g3"),
]
deps = [_requires("g2", "g1"), _requires("g3", "g2")]
lanes = compute_progression_lanes(items=items, dependencies=deps)
assert lanes["g1"] == lanes["g2"] == lanes["g3"]
def test_progression_join_switches_and_activates_outputs(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Mawashi Progression",
archetype_key="initiative.maturity_journey",
)
initiative_id = created.json()["id"]
from services.archetype_starter_kit import apply_a1_progression_demo
demo = apply_a1_progression_demo(
tenant_id=user["tenant_id"],
initiative_id=initiative_id,
user_id=user["id"],
)
assert demo["applied"] is True
progression = client.get(
f"/api/initiatives/{initiative_id}/roadmap/progression-state",
headers=_auth(token),
)
assert progression.status_code == 200
body = progression.json()
assert len(body["active_work_gates"]) == 2
assert len(body["joins"]) == 1
assert body["joins"][0]["pending_inputs"]
items = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
).json()
by_title = {item["title"]: item for item in items}
d1 = by_title["Dehnung — Einstieg"]
h1 = by_title["Hüftrotation — Einstieg"]
join = by_title["Mawashi Geri zur Hüfte"]
for gate in (d1, h1):
client.post(
f"/api/initiatives/{initiative_id}/evidence",
json={
"title": f"Nachweis {gate['title']}",
"roadmap_item_id": gate["id"],
"status": "accepted",
},
headers=_auth(token),
)
verify = client.post(
f"/api/roadmap-items/{gate['id']}/verify-reached",
headers=_auth(token),
)
assert verify.status_code == 200
items_after = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
).json()
by_title_after = {item["title"]: item for item in items_after}
assert by_title_after[join["title"]]["status"] == "reached"
assert by_title_after["Dehnung — nach Join"]["status"] == "active"
assert by_title_after["Hüftrotation — nach Join"]["status"] == "active"
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
).json()
active_titles = {r["title"] for r in recurring if r["status"] == "active"}
assert "Enddehnung Mawashi-Vorbereitung" in active_titles
assert "Explosive Hüftrotation" in active_titles
def test_multi_active_work_gates_both_in_next_actions(client):
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
created = _create_initiative(
client,
token,
title="Multi Active",
archetype_key="initiative.maturity_journey",
)
initiative_id = created.json()["id"]
from services.archetype_starter_kit import apply_a1_progression_demo
apply_a1_progression_demo(
tenant_id=user["tenant_id"],
initiative_id=initiative_id,
user_id=user["id"],
)
snap = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap.status_code == 200
recurring_items = [
a for a in snap.json().get("next_actions") or [] if a.get("kind") == "recurring_due"
]
assert len(recurring_items) >= 2
+7
View File
@@ -86,6 +86,13 @@ def test_verify_reached_requires_evidence(client):
assert ok.json()["status"] == "reached" assert ok.json()["status"] == "reached"
assert ok.json()["verify_reason"] in ("criteria_ready", "evidence_accepted") assert ok.json()["verify_reason"] in ("criteria_ready", "evidence_accepted")
blocked_delete = client.delete(
f"/api/roadmap-items/{item['id']}",
headers=_auth(token),
)
assert blocked_delete.status_code == 400
assert "nicht gelöscht" in blocked_delete.json()["detail"].lower() or "terminal" in blocked_delete.json()["detail"].lower()
def test_milestone_compat_api_uses_roadmap(client): def test_milestone_compat_api_uses_roadmap(client):
user = provision_user_in_tenant(tenant_role="member") user = provision_user_in_tenant(tenant_role="member")
+136
View File
@@ -0,0 +1,136 @@
"""AP1.7b — Operational API Pflege-Parität (Backlog-Commit, Recurring, Sprint-Zuweisung)."""
from __future__ import annotations
from services import actors as actor_service
from services.actor_service_tokens import create_service_token
from tests.factories import provision_user_in_tenant
from tests.test_initiatives_actions import _auth, _create_initiative, _login
def _agent_token(admin, *, capabilities=None):
agent = actor_service.create_actor(
tenant_id=admin["tenant_id"],
actor_type="agent",
name="Ops Agent",
)
caps = capabilities or [
"kairo.action.read",
"kairo.action.manage",
"kairo.backlog.manage",
"kairo.recurring.manage",
"kairo.initiative.read",
]
created = create_service_token(
tenant_id=admin["tenant_id"],
actor_id=agent["id"],
label="AP17b",
created_by_user_id=admin["id"],
capabilities=caps,
)
return created["token"], agent["id"]
def test_operational_convert_backlog_to_sprint(client):
admin = provision_user_in_tenant(tenant_role="admin")
user_token = _login(client, admin)
actor_token, _ = _agent_token(admin)
created = _create_initiative(
client,
user_token,
title="Product Ops",
archetype_key="initiative.product",
)
initiative_id = created.json()["id"]
cycle = client.post(
f"/api/initiatives/{initiative_id}/work-cycles",
json={"title": "Sprint Ops", "status": "active"},
headers=_auth(user_token),
)
assert cycle.status_code == 201
cycle_id = cycle.json()["id"]
backlog = client.post(
f"/api/initiatives/{initiative_id}/backlog",
json={"title": "Via Agent", "status": "accepted"},
headers=_auth(user_token),
)
backlog_id = backlog.json()["id"]
converted = client.post(
f"/api/operational/backlog/{backlog_id}/convert-to-action",
json={"work_cycle_id": cycle_id, "assign_active_sprint": False},
headers={"X-Actor-Token": actor_token},
)
assert converted.status_code == 201
body = converted.json()
assert body["ok"] is True
assert body["data"]["action"]["work_cycle_id"] == cycle_id
def test_operational_patch_recurring_status(client):
admin = provision_user_in_tenant(tenant_role="admin")
user_token = _login(client, admin)
actor_token, _ = _agent_token(admin)
created = _create_initiative(
client,
user_token,
title="Spagat Ops",
archetype_key="initiative.maturity_journey",
apply_starter_kit=True,
)
initiative_id = created.json()["id"]
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(user_token),
).json()
assert recurring
recurring_id = recurring[0]["id"]
patched = client.patch(
f"/api/operational/recurring/{recurring_id}",
json={"status": "paused"},
headers={"X-Actor-Token": actor_token},
)
assert patched.status_code == 200
assert patched.json()["data"]["status"] == "paused"
def test_operational_assign_action_work_cycle(client):
admin = provision_user_in_tenant(tenant_role="admin")
user_token = _login(client, admin)
actor_token, _ = _agent_token(admin)
created = _create_initiative(
client,
user_token,
title="Sprint Assign",
archetype_key="initiative.product",
)
initiative_id = created.json()["id"]
cycle = client.post(
f"/api/initiatives/{initiative_id}/work-cycles",
json={"title": "Sprint B", "status": "planned"},
headers=_auth(user_token),
)
cycle_id = cycle.json()["id"]
action = client.post(
f"/api/initiatives/{initiative_id}/actions",
json={"title": "Loose AP", "status": "open"},
headers=_auth(user_token),
)
action_id = action.json()["id"]
assigned = client.patch(
f"/api/operational/actions/{action_id}/work-cycle",
json={"work_cycle_id": cycle_id},
headers={"X-Actor-Token": actor_token},
)
assert assigned.status_code == 200
assert assigned.json()["data"]["work_cycle_id"] == cycle_id
@@ -44,15 +44,21 @@ def test_maturity_stage_reached_rotates_recurring(client):
assert verify.status_code == 200 assert verify.status_code == 200
body = verify.json() body = verify.json()
assert body["status"] == "reached" assert body["status"] == "reached"
assert body.get("maturity_transition", {}).get("new_recurring_id") transition = body.get("maturity_transition") or {}
legacy = transition.get("legacy_linear") or {}
practice_ids = (legacy.get("practice_transition") or {}).get("practice_ids") or []
assert practice_ids or transition.get("successors_activated") or transition.get("joins_switched")
recurring = client.get( recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring", f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token), headers=_auth(token),
).json() ).json()
titles = {r["title"]: r["status"] for r in recurring} titles = {r["title"]: r["status"] for r in recurring}
assert titles.get("Tägliche Übung") == "paused" assert titles.get("Vorbeuge-Dehnung") == "paused"
assert any(t.startswith("Übung — Stufe 2") for t in titles) assert titles.get("Hüftöffner (Schmetterling)") == "paused"
assert any(
t.startswith("Seitlicher Spagat") and titles[t] == "active" for t in titles
)
items_after = client.get( items_after = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items", f"/api/initiatives/{initiative_id}/roadmap/items",
+4 -1
View File
@@ -51,7 +51,10 @@ def test_create_initiative_a1_applies_starter_kit(client):
headers=_auth(token), headers=_auth(token),
) )
assert recurring.status_code == 200 assert recurring.status_code == 200
assert any(r["title"] == "Tägliche Übung" for r in recurring.json()) stretch = next(r for r in recurring.json() if r["title"] == "Vorbeuge-Dehnung")
assert stretch.get("roadmap_item_id")
assert stretch.get("action_id")
assert (stretch.get("schedule") or {}).get("schedule_kind") == "weekdays"
def test_create_initiative_b2b_starter_kit(client): def test_create_initiative_b2b_starter_kit(client):
+191
View File
@@ -0,0 +1,191 @@
"""AP2.2c — A1 maturity journey End-to-End (Spagat Happy Path)."""
from __future__ import annotations
from tests.factories import provision_user_in_tenant
from tests.test_initiatives_actions import _auth, _create_initiative, _login
_STAGE1 = "Stufe 1 — Basis"
_STAGE1_EXERCISES = ("Vorbeuge-Dehnung", "Hüftöffner (Schmetterling)")
def _create_spagat(client, token):
created = _create_initiative(
client,
token,
title="Spagat können",
archetype_key="initiative.maturity_journey",
)
assert created.status_code == 201
body = created.json()
assert body["starter_kit"]["applied"] is True
return body["id"]
def test_a1_starter_kit_spagat_structure(client):
"""Starter-Kit: Stufen, Training-Project, Wochentags-Übung, Operating Context."""
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
initiative_id = _create_spagat(client, token)
ctx = client.get(
f"/api/initiatives/{initiative_id}/operating-context",
headers=_auth(token),
)
assert ctx.status_code == 200
body = ctx.json()
assert body["method_key"] == "maturity_progression"
assert "maturity_stage" in body["steering_elements"]
assert "recurring_rhythm" in body["steering_elements"]
assert body["ui_profile"]["controlDefaultRoute"] == "/control/status"
roadmap = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
)
assert roadmap.status_code == 200
stages = [i for i in roadmap.json() if i.get("item_type") == "maturity_stage"]
assert len(stages) == 3
assert sum(1 for s in stages if s["status"] == "active") == 1
assert any(s["title"] == _STAGE1 and s["status"] == "active" for s in stages)
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
)
assert recurring.status_code == 200
assert any(r["title"] == _STAGE1_EXERCISES[0] and r["status"] == "active" for r in recurring.json())
assert any(r["title"] == _STAGE1_EXERCISES[1] and r["status"] == "active" for r in recurring.json())
projects = client.get(
f"/api/initiatives/{initiative_id}/projects",
headers=_auth(token),
)
assert projects.status_code == 200
assert any(p["title"] == "Training" for p in projects.json())
snap = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap.status_code == 200
snap_body = snap.json()
assert snap_body["steering_kernel"]["primary_method_key"] == "maturity_progression"
assert snap_body.get("steering_guidance")
next_actions = snap_body.get("next_actions") or []
assert next_actions
top = next_actions[0]
assert top.get("kind") in ("recurring_due", "action", "review_milestone")
if top.get("kind") == "recurring_due":
assert top.get("reason_code") == "recurring_due"
def test_a1_stage_verify_rotates_recurring_and_next_action(client):
"""AP2.0e: Stufe 1 reached → alte Übung pausiert, Stufe 2 aktiv, neue Routine."""
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
initiative_id = _create_spagat(client, token)
items = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
).json()
stage1 = next(i for i in items if i["title"] == _STAGE1)
snap_before = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap_before.status_code == 200
client.post(
f"/api/initiatives/{initiative_id}/evidence",
json={
"title": "Stufe 1 geschafft",
"roadmap_item_id": stage1["id"],
"status": "accepted",
},
headers=_auth(token),
)
verify = client.post(
f"/api/roadmap-items/{stage1['id']}/verify-reached",
headers=_auth(token),
)
assert verify.status_code == 200
body = verify.json()
assert body["status"] == "reached"
transition = body.get("maturity_transition") or {}
legacy = transition.get("legacy_linear") or {}
practice_ids = (legacy.get("practice_transition") or {}).get("practice_ids") or []
assert (
practice_ids
or transition.get("successors_activated")
or transition.get("joins_switched")
)
recurring = client.get(
f"/api/initiatives/{initiative_id}/recurring",
headers=_auth(token),
).json()
titles = {r["title"]: r["status"] for r in recurring}
for title in _STAGE1_EXERCISES:
assert titles.get(title) == "paused"
assert any(
t.startswith("Seitlicher Spagat") and titles[t] == "active" for t in titles
)
items_after = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
).json()
stage2 = next(i for i in items_after if i["title"] == "Stufe 2 — Aufbau")
assert stage2["status"] == "active"
snap_after = client.get(
f"/api/initiatives/{initiative_id}/steering-snapshot",
headers=_auth(token),
)
assert snap_after.status_code == 200
next_after = snap_after.json().get("next_actions") or []
assert next_after
assert next_after[0].get("kind") == "recurring_due" or next_after[0].get("title") in (
"Seitlicher Spagat — links",
"Seitlicher Spagat — rechts",
"Aktive Vorbeuge",
)
def test_a1_journey_lists_stage_reached_event(client):
"""Journey enthält nach Verify mindestens ein Ereignis."""
user = provision_user_in_tenant(tenant_role="admin")
token = _login(client, user)
initiative_id = _create_spagat(client, token)
items = client.get(
f"/api/initiatives/{initiative_id}/roadmap/items",
headers=_auth(token),
).json()
stage1 = next(i for i in items if i["title"] == _STAGE1)
client.post(
f"/api/initiatives/{initiative_id}/evidence",
json={
"title": "Nachweis Stufe 1",
"roadmap_item_id": stage1["id"],
"status": "accepted",
},
headers=_auth(token),
)
client.post(
f"/api/roadmap-items/{stage1['id']}/verify-reached",
headers=_auth(token),
)
journey = client.get(
f"/api/initiatives/{initiative_id}/journey",
headers=_auth(token),
)
assert journey.status_code == 200
events = journey.json().get("events") or []
assert len(events) >= 1
@@ -82,6 +82,8 @@ def test_operating_context_maturity(client):
body = res.json() body = res.json()
assert body["method_key"] == "maturity_progression" assert body["method_key"] == "maturity_progression"
assert any(s["key"] == "journey" for s in body["ui_profile"]["processSteps"]) assert any(s["key"] == "journey" for s in body["ui_profile"]["processSteps"])
assert "inbox" not in (body["ui_profile"].get("planOutlineKeys") or [])
assert body["ui_profile"]["planOutlineKeys"] == ["profile", "gates", "work"]
def test_operating_context_program(client): def test_operating_context_program(client):
+85
View File
@@ -0,0 +1,85 @@
"""Unit tests for schedule due-date logic (no DB)."""
from __future__ import annotations
from datetime import date, datetime, timezone
from services.schedule import (
format_schedule_label,
initial_due_at,
is_due_on_date,
next_due_after_completion,
weekday_bit,
weekday_mask_for_date,
)
def test_interval_daily_label():
label = format_schedule_label({"schedule_kind": "interval", "interval_days": 1, "weekday_mask": 0})
assert label == "Täglich"
def test_interval_seven_is_not_weekly():
label = format_schedule_label({"schedule_kind": "interval", "interval_days": 7, "weekday_mask": 0})
assert label == "Alle 7 Tage"
def test_weekday_label_lists_days():
label = format_schedule_label(
{"schedule_kind": "weekdays", "weekday_mask": weekday_bit(0) | weekday_bit(2) | weekday_bit(6)}
)
assert label == "Mo, Mi, So"
assert "Wöchentlich" not in label
def test_weekday_mask_next_due_after_friday():
schedule = {
"schedule_kind": "weekdays",
"weekday_mask": weekday_bit(0) | weekday_bit(2) | weekday_bit(4),
"pause_until": None,
}
friday = datetime(2026, 8, 7, 12, 0, tzinfo=timezone.utc)
nxt = next_due_after_completion(schedule=schedule, completed_at=friday)
assert nxt.date() == date(2026, 8, 10)
def test_is_due_on_date_hides_future_weekday():
schedule = {
"schedule_kind": "weekdays",
"weekday_mask": weekday_bit(1),
"pause_until": None,
}
next_due = datetime(2026, 8, 18, tzinfo=timezone.utc)
assert is_due_on_date(schedule=schedule, next_due_at=next_due, on_date=date(2026, 8, 17)) is False
assert is_due_on_date(schedule=schedule, next_due_at=next_due, on_date=date(2026, 8, 18)) is True
def test_is_due_on_date_keeps_overdue_weekday():
schedule = {
"schedule_kind": "weekdays",
"weekday_mask": weekday_bit(0),
"pause_until": None,
}
missed_monday = datetime(2026, 8, 17, tzinfo=timezone.utc)
assert (
is_due_on_date(
schedule=schedule, next_due_at=missed_monday, on_date=date(2026, 8, 18)
)
is True
)
def test_weekday_mask_for_monday():
assert weekday_mask_for_date(date(2026, 8, 17)) == weekday_bit(0)
def test_pause_until_pushes_initial_due():
schedule = {
"schedule_kind": "interval",
"interval_days": 1,
"weekday_mask": 0,
"pause_until": "2026-08-10",
}
now = datetime(2026, 8, 4, 9, 0, tzinfo=timezone.utc)
due = initial_due_at(schedule=schedule, now=now)
assert due.date() == date(2026, 8, 11)
+18 -1
View File
@@ -51,8 +51,25 @@ docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py --
| `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`), verwaiste Test-Tenants; löscht zuerst Initiatives (AP0.5 FK) | | `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`), verwaiste Test-Tenants; löscht zuerst Initiatives (AP0.5 FK) |
| `seed_002_bootstrap_admin` | Python | Legt Systemadmin aus `KAIRO_BOOTSTRAP_*` an, wenn noch kein User existiert | | `seed_002_bootstrap_admin` | Python | Legt Systemadmin aus `KAIRO_BOOTSTRAP_*` an, wenn noch kein User existiert |
| `seed_003_ensure_dev_admin` | Python (dev) | Entfernt fremde Dev-User, stellt `lars@stommer.com` als Portal-Admin sicher (jeder Start) | | `seed_003_ensure_dev_admin` | Python (dev) | Entfernt fremde Dev-User, stellt `lars@stommer.com` als Portal-Admin sicher (jeder Start) |
| `seed_004_dogfooding_kairo_jinkendo` | Python (dev) | Deprecated — Dogfooding-Visualisierung, **nicht** Produkt; nur Nicht-Prod |
Dev-Seeds (`.dev.*`) werden in Nicht-Prod-Umgebungen **bei jedem Backend-Start** erneut ausgeführt. Dev-Seeds (`.dev.*` im Dateinamen) laufen **nicht in Production** (`ENVIRONMENT=production`) und werden in Dev **bei jedem Backend-Start** erneut ausgeführt.
### Prod-taugliche Seeds (laufen auch auf main)
| Seed | Verhalten Prod |
|------|----------------|
| `seed_002_bootstrap_admin` | Legt Admin **nur** an, wenn DB leer **und** `KAIRO_BOOTSTRAP_*` in `.env` gesetzt |
### Code-Registry (kein Data-Seed — identisch Dev/Prod)
Beim Backend-Start (`entrypoint.sh`, überspringbar via `SKIP_REGISTRY_SYNC=1`):
- `sync_rights_registry.py` — Capabilities
- `sync_prompt_feature_config.py` — Features/Prompts
- `sync_entity_field_registry.py` — Archetypen + Felddefinitionen aus `entity_archetypes/registry.py`
Zusätzlich im Code (Deploy-Artifact, keine DB-Seed-Datei): `method_profiles/registry.py`, `steering/methods/registrations/*`, Starter-Kits in `archetype_starter_kit.py`.
## Neuen Seed anlegen ## Neuen Seed anlegen
@@ -0,0 +1,70 @@
# ADP — A1 Progression: Graph-abgeleitete Lanes statt Strang=Project
**Status:** PO/Architektur-Korrektur (2026-07-28)
**Stand:** 2026-07-28
**Auslöser:** AP2.1 — Strang=Project und `strand_project_id` vermischen Dimension A (Zielzustands-Graph) mit Dimension B (Project-Struktur)
**Bezug:** `ADP_Execution_Plan_and_Work_Package_Dependencies_v0.1.md`, `SPEC_A1_Progression_Model_PO_Lock_v0.1.md`, `SPEC_D_maturity_progression_v0.1.md`
---
## Entscheidung
**A1 Multi-Gate-Progression braucht kein Project pro parallelem Pfad.**
| Thema | Lock |
|-------|------|
| **Ziel-Horizont (A)** | Gates + `requires`-Graph + Join — modelliert **Zielzustände**, nicht Pfade |
| **Ist / Übungen** | `RecurringElement.roadmap_item_id` → aktives Gate — **eine** Bindung |
| **Parallele aktive Gates** | Erlaubt; Horizon-Regel „max. 1 aktiv pro Lane“ aus **Graph-Topologie** ableiten |
| **Lane** | Interner, nicht persistierter Schlüssel (`compute_progression_lanes`) — kein Nutzerobjekt |
| **Project** | **Nicht** Träger paralleler Progression in A1; optional nur für echte Struktur-Hierarchie (ADP Dimension B) |
| **`strand_project_id`** | **Deprecated** für Steuerlogik; Spalte bleibt nullable (Migration 032), wird nicht mehr gelesen |
| **`recurring.project_id` für A1** | **Nicht** setzen / nicht auswerten für Ready-Menge |
---
## Begründung
1. **ADP-Leitentscheidung:** Gate-Designer = Zielzustände; Pfad-/Container-Semantik gehört nicht in dieselbe Pflichtmodellierung.
2. **Nutzerbild:** Mehrere aktive Gates, Routinen am Gate, Join wertet Kanten aus — kein Pfad-Navigator nötig.
3. **Archetyp-Isolation:** Project=Strang hätte andere Archetypen (A2, B1) semantisch verunreinigt.
4. **Kein Doppelmodell:** Kanten im Designer genügen; kein Strang-Dropdown, keine Stream-Projects für A1-Kernbild.
---
## Lane-Algorithmus (MVP)
Aus `requires`-Kanten zwischen Work-Gates und Joins:
- Sequenzielle Work-Gates teilen eine Lane (Vorgänger-Kette).
- Parallele Quellen (kein Work-Gate-Vorgänger) → getrennte Lanes.
- Erstes Gate nach Join (`requires` Join) → neue Lane (`post-join:{gate_id}`).
Horizon: Beim Aktivieren eines Gates werden andere `active`/`at_risk` Gates **derselben Lane** auf `planned` gesetzt.
---
## Implementierung
| Modul | Änderung |
|-------|----------|
| `backend/services/progression_graph.py` | `compute_progression_lanes`, `enforce_single_active_work_gate_per_lane` |
| `backend/services/maturity_practice.py` | Pause/Seed nur über `roadmap_item_id` + Lane |
| `backend/services/archetype_starter_kit.py` | Demo ohne Stream-Projects / `strand_project_id` |
| `frontend/.../WorkTodayPracticePanel.jsx` | Gruppierung nach Gate-Titel |
Steuerung bleibt in **`maturity_progression`** — nicht im generischen `roadmap_engine`.
---
## Spec-Nachzug
`SPEC_A1_Progression_Model_PO_Lock_v0.1.md` §1/§4: „Strang = Project“ → **ersetzt durch** „parallele Lanes = graph-abgeleitete Requires-Ketten“. Project-Spiegel `project.maturity_journey` optional für Struktur-IA, nicht für Horizon.
---
## Nicht in Scope
- Spalten-Drop in Migration ( später, wenn keine Legacy-Daten )
- Join If/Else (Stufe B)
- Blueprint / Starter-Kit als Produktweg
@@ -0,0 +1,77 @@
# ADP — Template / Blueprint Scope Lock v0.1
**Status:** Entwurf — gilt ab PO-Freigabe von `ADP_Vorhaben_Template_Blueprint_v0.1.md`
**Stand:** 2026-07-27
**Bezug:** `ADP_Vorhaben_Template_Blueprint_v0.1.md` §13, `ADP_AP1_0_Steering_Foundation_Scope_Lock_v0.1.md`, `Kairo_MVP_Definition_v0.3.md` §3
---
## Geltungsbereich
Dieses Scope Lock gilt für **alle Implementierungs-APs AP-BP-1 bis AP-BP-5**. AP-BP-6 (Designer) erfordert eigenes Scope-Lock-Update.
---
## Phase 1 (BP-1 … BP-4) — explizit **nicht** bauen
| # | Verboten | Begründung |
|---|----------|------------|
| SL-1 | **Blueprint-Designer** (visueller Editor, Drag-Drop) | BP-6; Over-Engineering |
| SL-2 | **YAML/JSON-Import** für Tenant-Blueprints | BP-6 |
| SL-3 | **Produktive KI/Prompt-Ausführung** aus Blueprint-Bindings | AP2.1 Freeze; SK-13 |
| SL-4 | **Agent-Ranker** (`agent_v1`) aktiviert durch Template | BP-5 nach AP2.1 Go |
| SL-5 | **MCP / Workflow-Fragmente** an Blueprint gebunden | Schicht 4 eingefroren |
| SL-6 | **Neue steering_elements** durch Blueprint-Aktivierung | Nur Method Registry |
| SL-7 | **method_key- oder archetype_key-Override** via Blueprint | Natur bleibt Archetyp |
| SL-8 | **Neue OM-Tabellen** pro Blueprint-Typ | Scope Lock OM |
| SL-9 | **Steuerungslogik** in Blueprint-Resolver, Routern, React-Pages | SK-01, SK-03 |
| SL-10 | **Archetyp-Ifs** (`blueprint_key === '…'`) in Pages | Composition + Context |
| SL-11 | **Auto-Upgrade** materialisierter Struktur bei Blueprint-Version | O-5 offen; v1 verboten |
| SL-12 | **Tenant-Custom-Field-Schema** im Blueprint erfinden | EFS-ADP Phase 2 |
| SL-13 | **User-Scope Blueprints** (`scope_type=user`) | BP-6 Kandidat |
| SL-14 | **Vollständiger Structure Builder** getriggert durch Blueprint | Deferred MVP |
| SL-15 | **Projekt-Blueprints** (`entity_type=project`) | AP1.10 Phase 2 |
| SL-16 | **Neue Composition-Provider-Kinds** ohne ADP UX Composition | Open/Closed FE |
| SL-17 | **Portfolio-weite** Blueprint-Copy (Cockpit) | Initiative-scoped only |
| SL-18 | **Hardcodierter Prompt-Text** in `bindings_json` | Prompt-Registry only |
---
## Phase 1 — **erlaubt** (nach ADP-Freigabe)
| # | Erlaubt | Phase |
|---|---------|-------|
| E-1 | Tabelle `blueprints` + System-Seed-Migration aus `method_profiles/registry.py` | BP-1 |
| E-2 | `GET /api/blueprints` list/get; Alias `method-profiles` | BP-1 |
| E-3 | Operating Context: `blueprint_key`, `blueprint_bindings` (read-only slice) | BP-1 |
| E-4 | Anlage-Dialog: Blueprint wählen | BP-2 |
| E-5 | `apply_starter_kit` liest `starter_kit` aus Blueprint | BP-2 |
| E-6 | EFS `field_defaults` bei Anlage | BP-2 |
| E-7 | Tenant-Fork System-Blueprint → `scope_type=tenant`, `status=draft` | BP-3 |
| E-8 | PATCH Tenant-Blueprint (Presets, Copy) mit Capability-Gate | BP-3 |
| E-9 | Merge Copy in `resolveSteeringComposition` + `PROPOSAL_UI_CONFIG` | BP-4 |
| E-10 | Backlog-Vocabulary-Override aus Blueprint | BP-4 |
| E-11 | `prompt_refs` **speichern** und in API exposieren (ohne Ausführung) | BP-4 |
---
## Abhängigkeiten — nicht vorher starten
| AP | Blocker |
|----|---------|
| BP-2 (Materialisierung) | AP2.2a Starter-Kit-Pipeline stabil |
| BP-4 (Composition) | UX Composition Kernel MVP (AP-UX-1) |
| BP-5 (Prompt/Agent) | **AP2.1 Go** + Principle Gate Prompts |
| BP-3 (Tenant-Fork) | Tenant-Invariants; Capability `kairo.blueprint.manage` definiert |
---
## Abnahme Scope Lock
- [ ] PO bestätigt: BP-1…4 ohne SL-1…18
- [ ] Kein Agent startet BP-5 ohne explizite AP2.1-Freigabe
- [ ] Truth Table aktualisieren bei BP-1 Lieferung
---
*Kurz-Scope-Lock — Detailkonzept in `ADP_Vorhaben_Template_Blueprint_v0.1.md`.*
@@ -71,8 +71,14 @@ Slots sind **stabil benannte Flächen** — unabhängig von React-Page-Struktur.
| `plan.inbox.proposals` | plan | inbox | Triage-Vorschläge | | `plan.inbox.proposals` | plan | inbox | Triage-Vorschläge |
| `plan.sprint.proposals` | plan | sprint | Sprint-Commit-Vorschläge | | `plan.sprint.proposals` | plan | sprint | Sprint-Commit-Vorschläge |
| `plan.gates.proposals` | plan | gates | Gate-Vorschläge | | `plan.gates.proposals` | plan | gates | Gate-Vorschläge |
| `work.today.primary` | work | today | Next Action (Steuerung) |
| `work.today.actions` | work | today | Arbeitspakete (Drill-down) |
| `work.sprint.primary` | work | sprint | Next Action im Sprint |
| `work.sprint.backlog` | work | sprint | Sprint-Backlog (Drill-down) |
**Erweiterung (post-MVP):** `control.plan-ist.read_models`, `plan.inbox.read_models`, Work-Modus-Slots. **Erweiterung (post-MVP):** `control.plan-ist.read_models`, `plan.inbox.read_models`.
**AP1.9d (2026-07-27):** Work-Modus-Slots `work.today.*`, `work.sprint.*` — Next Action als Hauptbild, Arbeitspaket-Listen als Drill-down. Layout-neutral für späteres UI-Redesign; Provider-Vertrag bleibt stabil.
--- ---
@@ -0,0 +1,108 @@
# ADP — Unified Schedule & Cadence Layer v0.1
**Status:** PO-Freigabe ausstehend (2026-08-04, Implementierung Slice 1 gestartet)
**Stand:** 2026-08-04
**Auslöser:** A1-Validation — RecurringElement als UI-Insel; Nutzer erwarten Rhythmus an AP/Task wie in Todo-Tools
**Bezug:** `Kairo_Steering_Method_Kernel_v0.1` Q2, `ADP_A1_Progression_Graph_Derived_Lanes_v0.1.md`, Spec-D `recurring_control`, Spec-D `maturity_progression`
---
## 1. Leitentscheidung
**Rhythmus/Wiederholung ist Kernfähigkeit**, nicht Archetyp-Insel.
| Kern | Host (Bindung) | Methode (Regeln) |
|------|----------------|------------------|
| **`Schedule`** — interval, Wochentage, Pause | `Action`, `RecurringElement` (Gate-Übung), später `Task` | `maturity_progression`, `sequential_dependency`, `recurring_control`, … |
| **`CadenceInstance`** — eine offene Fälligkeit, „heute erledigt“ | immer an `RecurringElement` (Bridge von `Action` optional) | Ready/Ranking in Method-Strategie |
**Nicht:** separates Planungs-UI pro Archetyp. **Eine** Schedule-Semantik, **ein** Editor-Widget, Host-spezifische Bindung.
---
## 2. Schedule-Modell
```text
schedules
schedule_kind 'interval' | 'weekdays'
interval_days int (nur interval; Default 1 = täglich nach Erledigen)
weekday_mask int (Mo=1, Di=2, Mi=4, Do=8, Fr=16, Sa=32, So=64)
pause_until date nullable — bis einschl. pausiert
```
| schedule_kind | Nutzer-Label | Semantik |
|---------------|--------------|----------|
| `interval` | „Alle N Tage“ | Nach Erledigen: nächste Fälligkeit = heute + N Kalendertage |
| `weekdays` | „Bestimmte Wochentage“ | Fällig an gewählten Tagen; nach Erledigen: nächster passender Tag |
**Anti-Duplikat (unverändert):** pro Recurring genau **eine** offene `CadenceInstance`.
---
## 3. Hosts
| Host | Spalte | Use Case |
|------|--------|----------|
| `recurring_elements` | `schedule_id`, `roadmap_item_id` | A1 Gate-Übung, A3 Ritual |
| `recurring_elements` | `action_id` (Bridge) | AP mit Wiederholung — ein Recurring spiegelt AP |
| `actions` | `schedule_id` | Steuerung / PMO-Review am AP |
**Action + Schedule:** beim Setzen wird `RecurringElement` mit `action_id` synchronisiert (Cadence-Pfad). AP-Status `done` schließt **nicht** die Serie — Cadence steuert Serie.
**Gate-Übung:** direkt `RecurringElement` + `schedule_id` + `roadmap_item_id`.
---
## 4. UI (Slice 1–2)
| Fläche | Widget |
|--------|--------|
| Gate-Detail | `ScheduleEditor` im Activity Set |
| AP-Detail | `ActionScheduleSection` — Toggle Wiederholung + gleicher Editor |
| Initiative (Slice 3) | „Rhythmen“ — Liste aller Schedules |
**Labels (Pflicht):** „Täglich“, „Alle 2 Tage“, „Wöchentlich“, Mo–So Checkboxen — **kein** nacktes „Rhythmus (Tage)“.
---
## 5. Methoden — unverändert getrennt
| Methode | Leading | Schedule-Host typisch |
|---------|---------|---------------------|
| `maturity_progression` | Cadence an **aktiven Gates** | Recurring + Gate |
| `recurring_control` | Cadence initiative-weit | Recurring |
| `sequential_dependency` | Action; optional Schedule am AP | Action + Bridge |
| `agile_iteration` | Cadence vor Sprint-Actions | komponiert |
Archetyp ändert **Auswertung**, nicht das Schedule-Schema.
---
## 6. Migration & Kompatibilität
- Migration `033`: Tabelle `schedules`; `schedule_id` auf `recurring_elements`, `actions`; `action_id` auf `recurring_elements`
- Bestehende `interval_days` auf Recurring → Backfill `schedules` (kind=interval)
- `interval_days` am Recurring **deprecated** (Lesefallback bis Entfernung)
---
## 7. Implementierungsfolge
```text
Slice 1 Schedule + Cadence-Logik (weekdays, pause) + Gate-UI ← dieser Commit
Slice 2 Action-Schedule + Bridge-Recurring
Slice 3 Initiative „Rhythmen“ / Wochenblick (read-only)
Slice 4 Task-Host optional
```
---
## 8. Nicht in Scope
- Cron/Uhrzeit (nur Datum)
- Alternanz A/B (Spec §4.3 — eigener Slice)
- RecurringElement-Tabelle entfernen ( erst nach Action-Host stabil)
---
*Bei Konflikt mit PO-Lock „Rhythmus am Recurring“: **Schedule ersetzt nicht Cadence**, vereinheitlicht nur Konfiguration.*
@@ -0,0 +1,616 @@
# ADP — Vorhaben-Template / Blueprint v0.1 (AP-BP-0)
**Status:** Konzeptionsentwurf — PO-Freigabe ausstehend
**Stand:** 2026-07-27
**Autor:** Architektur (AP-BP-0 Konzeptionsauftrag)
**Bezug:** `AP_BP_0_Template_Blueprint_Conception_Prompt_v0.1.md`, `Kairo_Vision_and_Product_Direction_v0.2.md`, `Kairo_Canonical_Operating_Model_v0.2.md`, `Kairo_MVP_Definition_v0.3.md`, `Kairo_Archetype_Decision_Lock_Interview_2026-07-25.md`, `ADP_Archetype_and_Method_Catalog_v0.2.md`, `Kairo_Steering_Method_Kernel_v0.1.md`, `ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `ADP_Steering_Kernel_Coding_Rules_v0.1.md`, `ADP_UX_Composition_Kernel_v0.1.md`, `ADP_AP1_10_Initiative_Archetypes_and_Entity_Field_System_v0.1.md`, `Kairo_Method_Design_Principles_v0.1.md`, `Kairo_MVP_Execution_Plan_v0.2.md`
**Ersetzt nicht:** Plugin-ADPs AP2.3/AP2.4, Steering Kernel Coding Rules, UX Composition Kernel
**Begleitdokument:** `ADP_Template_Blueprint_Scope_Lock_v0.1.md`
---
## 1. Problem & Nordstern
### 1.1 Ausgangslage
Kairo hat nach AP2.3/AP2.4 eine saubere Trennung **Archetyp (Schicht 2) ↔ Methode (Schicht 1)** und einen zentralen **Steering Kernel** (`evaluate_steering()`). Für konkrete Vorhabenarten — Karate Kumite, Kairo-Entwicklung, Buch schreiben — fehlt jedoch eine **implementierbare Schicht 3**, die:
- bei Anlage **sinnvolle Startstruktur** liefert (Starter-Kits AP2.2a),
- **domänenspezifische Felder, Labels und Copy** parametrisiert,
- **tenant-/nutzer-konfigurierbar** ist, ohne neue Archetypen zu erfinden,
- und **keine Steuerungslogik** dupliziert.
Heute existieren **dünne Code-Seeds** in `backend/method_profiles/registry.py` (`method_profile_key`) mit Metadaten und `seed_hints`, aber **ohne** profil-differenzierte Materialisierung in der UI, ohne Copy-Bindings und ohne tenant-scoped Persistenz.
### 1.2 Nordstern
> **Blueprint** = konkrete Vorlage **auf** einem Archetyp für einen **bestimmten Aufgabentyp**.
> Blueprint **parametrisiert und präsentiert** — es **ersetzt keine Methode** und **erfindet keine Steuerungslogik**.
Kairo bleibt **Program Director** (Vision v0.2, MVP v0.3 §1). Die Leitfrage bleibt:
> Welcher nächste Schritt bringt dieses Vorhaben **jetzt** am wirksamsten voran — und **warum**?
Blueprints helfen dem Nutzer, **schneller in methodengerechte Struktur** zu kommen und **passende Sprache** zu sehen — ohne Todo-Explosion (MVP v0.3 §7) und ohne versteckte Archetypen.
### 1.3 Warum nach MVP Stufe A — nicht davor blockierend
| Aspekt | Begründung |
|--------|------------|
| AP2.1 Validation | Stufe A muss Steuerung **ohne** Blueprint-Tiefe beweisen |
| AP2.2a Starter-Kits | Liefern **generische** Archetyp-Struktur — Blueprint **verfeinert** dieselbe Pipeline |
| Konzept jetzt | Migrationspfad von Code-Seeds → DB; Bindings-Matrix; Guardrails **vor** Implementierung |
| Implementierung BP-1+ | **Nach** ADP-Freigabe; parallel zu AP2.2c/e möglich — PO entscheidet Minimal-Slice |
---
## 2. Begriffe
| Begriff | Definition | Abgrenzung |
|---------|------------|------------|
| **Blueprint** (`blueprint_key`) | Versionierte, scope-gebundene Vorlage **auf** einem Archetyp. Bindet Felder, Presets, Copy, Composition-Config, Prompt-Refs — **nicht** Steuerungsalgorithmus. | ≠ Archetyp; ≠ Methode |
| **Vorhaben-Template** | Product-Sprache für Blueprint; synonym im PO-Kontext | Technischer Key: `blueprint_key` |
| **Archetyp** | Schicht 2: Natur, `om_capabilities`, Default-Methode (Empfehlung), EFS-Basis, `ui_profile` (Nav/Routen/Outline) | Ändert sich **nicht** durch Blueprint |
| **Methode** | Schicht 1: Steuerungsplugin im Kernel — `steering_elements`, Strategien, Proposals, Attention | Blueprint darf **keine** Methode ersetzen |
| **Ausprägung** (historisch) | Katalog v0.2 §2.0 Schicht-3-Label für `method_profile_key` | **Wird durch Blueprint ersetzt** (Rename + Superset, siehe §4.4) |
| **Method Profile** (Ist-Code) | Code-Seed in `method_profiles/registry.py` | **Legacy-Anker** → migriert zu System-Blueprint |
| **Preset** | Deklarativer Seed-Block innerhalb eines Blueprints (Starter-Kit-Definition, Recurring-Vorlage, Gate-Namen) | Wird bei Instanziierung **materialisiert** (OM-Objekte) |
| **Seed** | System-definierter Initialwert (Code oder DB), nicht tenant-editierbar im MVP | Blueprint **referenziert** Seeds; Tenant-Kopie darf Presets überschreiben (BP-3+) |
| **Structure Builder** (voll) | Hook-getriebene **Tiefenstruktur** via Method Registry (`on_structure_required`, Builder-Registry) | **Deferred** (MVP Execution Plan); Blueprint **liefert** leichte Presets, **triggert nicht** vollen Builder |
| **Starter-Kit** | AP2.2a: idempotente Materialisierung bei Anlage (`apply_starter_kit`) | Blueprint **liefert** Kit-Definition; Fallback = Archetyp-Default-Kit |
| **Instanziierung** | Vorhaben-Anlage: Blueprint wählen → Presets materialisieren, Referenzen setzen | `initiatives.blueprint_key` + `steering_context.lifecycle_metadata` |
| **Materialisiert** | Kopie in OM (RoadmapItems, Projects, BacklogItems, …) — danach **unabhängig** editierbar | |
| **Referenz** | Bleibt am Vorhaben: `blueprint_key`, `blueprint_version`, Prompt-Refs, Composition-Overrides | Änderung am Blueprint **propagiert nicht** rückwirkend auf materialisierte OM-Objekte (v1) |
### 2.1 Entscheidungs-Lock: Archetyp ≠ Template
PO 2026-07-25 (Decision-Lock §7): Template ändert die **Natur** eines Vorhabens nicht. Wesentliche Merkmale (Plan/Ist-Vertrag, Default-Methode-Empfehlung, OM-Capabilities) bleiben am Archetyp; Blueprint liefert **Konkretisierung** (Felder, Darstellung, Presets, Copy).
---
## 3. Schichtenmodell (erweitert)
### 3.1 Fünf Schichten + Blueprint-Position
```text
┌──────────────────────────────────────────────────────────────────────────┐
│ Schicht 4 — Integrationen & Agenten (eingefroren bis AP2.1 Go) │
│ MCP, Vibe-Coder, Gitea — Hook Slugs, Operational API │
├──────────────────────────────────────────────────────────────────────────┤
│ Schicht 3 — Blueprint (Vorhaben-Template / Ausprägung) │
│ blueprint_key, bindings_json — Felder, Presets, Copy, Composition, │
│ Prompt-Refs; Scope: system | tenant | user │
├──────────────────────────────────────────────────────────────────────────┤
│ Schicht 2 — Archetyp (entity_archetypes + EFS + ui_profile) │
│ Natur, om_capabilities, Default-Methode, Nav/Routen/Plan-Outline │
├──────────────────────────────────────────────────────────────────────────┤
│ Schicht 1 — Methode (Method Registry + Steering Kernel) │
│ steering_elements, data_slices, Strategien, Proposals, Attention │
├──────────────────────────────────────────────────────────────────────────┤
│ Schicht 0 — Framework (OM, TenantContext, Audit, Capabilities) │
└──────────────────────────────────────────────────────────────────────────┘
```
**Katalog v0.2 §2.0 Mapping:** Schicht 3 hieß „Ausprägung (Method Profile)“. Dieses ADP **benennt** sie verbindlich **Blueprint** und erweitert den Vertrag.
### 3.2 Auflösungskette zur Laufzeit
```text
Initiative (archetype_key, blueprint_key?)
│
▼
SteeringContext (method_key, lifecycle_metadata)
│
├──► Archetyp-Registry ──► ui_profile, om_capabilities, EFS-Basis
├──► Method Registry ──► steering_elements, data_slices, graph_profile
└──► Blueprint-Resolver ──► bindings (Copy, Presets-Metadaten, Composition-Overrides)
│
▼
GET /initiatives/:id/operating-context
(bestehend + blueprint-Binding-Slice)
│
▼
evaluate_steering() ──► Snapshot (read_models, proposals, agent_slots)
│
▼
resolveSteeringComposition() ──► UI-Slots + Provider (UX Composition Kernel)
```
**Regel:** Blueprint-Resolver läuft **neben** Operating Context — **nicht** im Kernel. Kernel liest höchstens **parametrisierte** Werte aus Operating Context (z. B. `proposal_rankers`, `agent_slot_config`) — nie Blueprint-Ifs.
### 3.3 Kompatibilitätsmatrix (Blueprint ↔ Archetyp ↔ Methode)
```text
compatible(blueprint, initiative) :=
blueprint.initiative_archetype_key = initiative.archetype_key
AND blueprint.method_key = steering_context.method_key
OR blueprint.method_key IS NULL -- „any compatible primary“
AND blueprint.method_key ∈ compatible_methods(archetype)
AND blueprint.scope erlaubt für Tenant/User
```
| Kardinalität | Regel |
|--------------|-------|
| Archetyp → Blueprint | **1:n** — mehrere Blueprints pro Archetyp (Kumite, Spagat, … auf A1) |
| Blueprint → Archetyp | **1:1** — kein Multi-Archetyp-Blueprint |
| Blueprint → Methode | **1:1** optional fix; `NULL` = Default-Methode des Archetyps |
| Vorhaben → Blueprint | **0:1** — optional; ohne Blueprint = Archetyp-Default-Starter |
| Modifier (`agile_iteration`) | Über Blueprint-Flag `composition_hints.agile_iteration` — **kein** eigener Blueprint-Typ |
---
## 4. Template-Metamodell
### 4.1 Entität `blueprint` (Ziel-Schema)
Persistenz Zielbild: Tabelle `blueprints` (tenant-scoped für Kopien; `tenant_id NULL` = System). Bis BP-1: Code-Seeds analog `method_profiles/registry.py`.
| Feld | Typ | Pflicht | Beschreibung |
|------|-----|---------|--------------|
| `blueprint_key` | string (stable slug) | ja | z. B. `maturity.karate_kumite` |
| `version` | semver / int | ja | Monotonic; Published-Version immutable |
| `label` | string | ja | UI-Anzeige (darf Archetyp-Label übersteuern) |
| `description` | text | nein | Kurzbeschreibung für Auswahl-Dialog |
| `initiative_archetype_key` | string | ja | Bindung Schicht 2 |
| `method_key` | string \| null | nein | Fixierte Primary-Methode; null = Archetyp-Default |
| `scope_type` | enum | ja | `system` \| `tenant` \| `user` |
| `scope_tenant_id` | uuid \| null | bedingt | Pflicht bei tenant/user |
| `scope_user_id` | uuid \| null | bedingt | Pflicht bei user |
| `parent_blueprint_key` | string \| null | nein | Vererbung (Tenant-Kopie von System-Blueprint) |
| `status` | enum | ja | `draft` \| `published` \| `deprecated` |
| `bindings_json` | jsonb | ja | Siehe §4.2 |
| `created_at`, `updated_at`, `published_at` | timestamp | ja | Audit |
| `is_system` | bool | ja | System-Blueprints nicht löschbar |
**Initiative-Referenz:**
| Feld auf `initiatives` / `steering_context` | Beschreibung |
|---------------------------------------------|--------------|
| `blueprint_key` | Gewählter Blueprint bei Anlage |
| `blueprint_version` | Eingefrorene Version bei Instanziierung |
| `method_profile_key` | **Deprecated-Alias** bis Migrationsende (BP-1) |
### 4.2 `bindings_json` — Top-Level-Struktur
Implementierbarer JSON-Vertrag (Auszug):
```json
{
"efs": {
"field_defaults": { "discipline": "Karate" },
"field_overrides": [],
"tenant_field_extensions_allowed": false
},
"starter_kit": {
"kit_key": "maturity.karate_kumite.v1",
"items": [
{ "kind": "project", "title": "Kumite", "sort_order": 1 },
{ "kind": "maturity_stage", "title": "Stufe 1 — Basis", "status": "active" }
]
},
"composition": {
"steering_element_copy": {
"gate_fulfillment": { "horizon_label": "Release-Horizont Kairo" }
},
"provider_overrides": [
{ "provider_key": "steering.critical_path", "order": 5, "props": {} }
],
"proposal_ui": {
"intake_triage": { "lead": "Product-Issues triagieren — nicht alles committen." }
}
},
"steering_presentation": {
"attention_labels": {},
"agent_slot_copy": {},
"backlog_vocabulary": { "backlog_item": "Issue" },
"journey_event_labels": {},
"graph_labels": {},
"plan_outline_hints": []
},
"prompt_refs": [
{
"prompt_key": "kairo.product.triage_hint",
"context_kind": "initiative_snapshot",
"placeholder_bindings": { "product_name": "efs.product_vision" }
}
],
"composition_hints": {
"agile_iteration": true,
"default_actor_setup": "po_plus_vibe_coder"
},
"ranker_params": {
"intake_triage": { "stale_days_weight": 1.2 }
},
"guidance": "Eingang triagieren, dann committete Actions — optional Sprint."
}
```
**Nicht in bindings_json:** `method_key`-Override auf inkompatiblen Archetyp, Lifecycle-States, neue `steering_elements`, Router-Logik, React-Komponenten-Keys ohne Provider-Registry.
### 4.3 Lifecycle (draft / published / deprecated)
| Status | Bedeutung |
|--------|-----------|
| `draft` | Editierbar; nicht in Anlage-Dialog für Endnutzer |
| `published` | Wählbar bei Anlage; Version frozen |
| `deprecated` | Nicht wählbar; bestehende Referenzen bleiben gültig |
**Versionierung:** Neues `published` = neue `version`; laufende Initiativen behalten `blueprint_version` bei Instanziierung. Kein Auto-Upgrade materialisierter Struktur (v1).
### 4.4 Method Profile → Blueprint (Rename + Superset)
**Empfehlung:**
| Aspekt | Entscheidung |
|--------|--------------|
| Konzept | **Superset** — Blueprint enthält alles, was `method_profile` heute kann, plus Bindings-Matrix |
| Technischer Key | **`blueprint_key`** — `method_profile_key` wird **Alias** in API/Snapshot bis BP-2 abgeschlossen |
| Modul | `backend/method_profiles/` → `backend/blueprints/` (BP-1); Re-Export für Kompatibilität |
| Decision-Lock D1 | `content.book_writing` bindet an **`initiative.linear_project`**, nicht `initiative.content_project` |
---
## 5. Bindings-Matrix
Legende:
| Spalte | Bedeutung |
|--------|-----------|
| **Template darf** | Blueprint darf Wert setzen/übersteuern (Präsentation, Defaults, Presets) |
| **Nur System** | Nur `scope_type=system` Blueprints; Tenant/User-Kopien eingeschränkt |
| **Kernel bleibt Owner** | Logik, Algorithmus, Aktivierung — nicht durch Template ersetzbar |
| **Phase** | Erste Implementierungsphase |
| Bindbares Artefakt | Template darf | Nur System | Kernel bleibt Owner | Phase |
|--------------------|---------------|------------|---------------------|-------|
| **EFS-Felddefinitionen** (Schema) | Nein — nur Archetyp-Registry + Tenant-EFS-Override (AP1.10 Phase 2) | Archetyp-Seeds | EFS-Validierungsservice | — |
| **EFS-Default-Werte** | Ja — `bindings.efs.field_defaults` | System-Blueprints | Validierung gegen `field_definitions` | BP-2 |
| **EFS-Label-Overrides** (Anzeige) | Ja — `field_overrides[].label` | — | Feldtyp/Required | BP-3 |
| **Tenant-nutzerdefinierte Felder** | Flag `tenant_field_extensions_allowed`; keine Schema-Erfindung im Template | Governance-Policy | Tenant-Invariants | BP-3+ |
| **Standardspalten** (`vision`, `goal`, …) | Default-Vorschläge bei Anlage | — | Initiative-Service | BP-2 |
| **Starter-Kit / Struktur-Presets** | Ja — vollständige `starter_kit.items[]` | System-Blueprints für Referenz-Portfolio | `apply_starter_kit` Idempotenz-Regeln | BP-2 |
| **Recurring-Presets** | Ja — als Starter-Items `kind: recurring` | — | Recurring-Service, AP2.0e Cadence-Logik | BP-2 |
| **steering_element UI-Copy** | Ja — Labels/Hints/Empfehlungstexte | — | **Aktivierung** via Methode `steering_elements` | BP-4 |
| **steering_element Sichtbarkeit** | Nein — nur über Methode + `data_slices` | — | `resolve_effective_steering_elements()` | — |
| **Composition-Provider** (Slot, order) | Ja — `order`, `props`, optionales Ausblenden via `enabled: false` | Neue Provider-Kinds | Provider-Registry + Match-Regeln | BP-4 |
| **Proposal-UI-Config** (`gate_next_actions`, `intake_triage`, `sprint_commit`) | Ja — `title`, `lead`, `acceptLabel` | — | Proposal-**Generierung** im Kernel | BP-4 |
| **Proposal-Ranker-Parameter** | Ja — `ranker_params.{proposal_key}` numerische Gewichte | Grenzen via Method Contract | Ranker-Implementierung, SK-05 | BP-5 |
| **Attention-Labels / Severity-Hints** | Ja — Präsentations-Copy für bekannte `attention_code` | — | Attention-**Auslösung** (Contributors) | BP-4 |
| **Agent-Slot-Copy** | Ja — Titel/Hinweis pro `slot_key` | — | Slot-**Existenz** + `agent_slot_config` | BP-5 |
| **Prompt-Referenzen** (key, context_kind, Platzhalter) | Ja — `prompt_refs[]` | Prompt-Inhalt in Prompt-Registry | Ausführung, Audit, Principle Gate | BP-5 |
| **Graph-/Gate-Labels** | Ja — Achsen-/Knoten-Labels, Gate-Titel-Vorschläge | — | Graph-Berechnung, Gate-Fulfillment | BP-4 |
| **Plan-Outline-Hints** | Ja — empfohlene Outline-Reihenfolge, Sektions-Titel | — | Archetyp `ui_profile.planOutline` Basis | BP-4 |
| **Backlog-Vocabulary-Profil** | Ja — Begriffe (`backlog_item` → „Issue“) | — | `resolve_backlog_vocabulary()` Logik | BP-4 |
| **Journey-Event-Typ-Labels** | Ja — Darstellungslabels für Event-Typen | — | Journey-Event-Erzeugung | BP-4 |
| **method_key** | Nein | — | SteeringContext + Kompatibilitätsprüfung | — |
| **archetype_key** | Nein | — | Initiative | — |
| **steering_elements (Aktivierung)** | Nein | — | Method Registry | — |
| **Next-Action-Algorithmus** | Nein | — | `evaluate_steering()` | — |
| **Lifecycle-Override** | Nein | — | Lifecycle-Orchestrator | — |
| **Neue OM-Tabellen / Entitätstypen** | Nein | — | Scope Lock | — |
| **Neue Provider-Kinds (UX)** | Nein | ADP UX Composition | Composition Kernel | — |
| **Archetyp-Ifs in Pages** | Verboten | — | `hasSteeringElement`, Operating Context | — |
---
## 6. Steuerungs-Grenze
### 6.1 Was bei Archetyp + Methode bleibt
| Verantwortung | Owner |
|---------------|-------|
| Natur, Plan/Ist-Vertrag | Archetyp |
| `steering_elements`, Proposals, Read Models, Attention | Methode + Kernel |
| Next Work, Ranking, `reason_code` | `evaluate_steering()` |
| Komposition `agile_iteration` | Method Registry (`composes_with`) |
| `data_slices` | Schnittmenge Archetyp ∩ Methode |
| Gate-Fulfillment, Planning Debt | Provider in `steering/proposals/`, `steering/read_models/` |
### 6.2 SK-Regeln (verbindlich)
| Regel | Konsequenz für Blueprint |
|-------|--------------------------|
| **SK-01** | Kein Blueprint-Zweig in `evaluate_steering()` |
| **SK-03** | Keine Steuerungsheuristik in Blueprint-Resolver |
| **SK-04** | UI bindet an Proposal-Keys — Blueprint ändert nur Copy/Parameter |
| **SK-05** | Ranker-Parameter nur Gewichte/Schwellen — keine „Bug-zuerst“-Policy im Template |
| **SK-10–12** | Frontend: Composition + `PROPOSAL_UI_CONFIG` Merge aus Operating Context |
| **SK-13–14** | Prompt-Inhalt nie im Blueprint-JSON — nur `prompt_key`-Referenz |
### 6.3 Anti-Patterns (explizit)
| Verboten | Konsequenz |
|----------|------------|
| Template als versteckter Archetyp | Neuer `archetype_key` nur via Archetyp-Registry + ADP |
| Todo-Wand durch Template-Listen | Presets ≠ 200 materialisierte Actions; Starter-Kit-Limits |
| Parallele Steuerung in Blueprint-Resolver | Ein Spine: Kernel |
| `if blueprint_key === '…'` in Pages | Nur Composition/Context |
| Template überschreibt `method_key` auf inkompatibel | Validierung bei Anlage |
---
## 7. EFS & nutzerdefinierte Felder
### 7.1 Feldquellen (Priorität)
```text
1. Archetyp field_definitions (system, EFS)
2. Tenant-Overrides auf field_definitions (AP1.10 Phase 2 — tenant-scoped)
3. Blueprint field_defaults + label overrides (Schicht 3)
4. Initiative field_values (Instanz)
```
### 7.2 Grenzen
| Thema | Regel |
|-------|-------|
| **Schema-Erfindung** | Blueprint darf **keine** neuen `field_key` ohne Archetyp/EFS-ADP einführen |
| **Tenant-Custom-Fields** | Eigene ADP-Erweiterung; Blueprint kann `tenant_field_extensions_allowed: true` setzen — **nicht** MVP BP-1/2 |
| **Validierung** | PATCH `/fields` validiert gegen effektive Definition — Blueprint-Defaults bei Anlage, danach normal |
| **Steering-Nutzung** | Dynamische Felder in Heuristiken nur mit ADP — Standardspalten + explizite Platzhalter-Bindings |
| **Search/Hot Path** | Nur `searchable=true` Felder; Blueprint-Defaults schreiben `field_values` |
### 7.3 Tenant-Invariants
- Alle Blueprint-Kopien: `tenant_id NOT NULL`
- User-Scope: zusätzlich `scope_user_id`; Capability `kairo.blueprint.manage_own`
- System-Blueprints: read-only für Tenants; Kopie erzeugt `scope_type=tenant`
---
## 8. UX / Composition
### 8.1 Template → UI-Slots
UX Composition Kernel (ADP UX v0.1) bleibt **Owner** der Slot-/Provider-Registry. Blueprint liefert **Overrides**:
```text
resolveSteeringComposition(
operatingContext, // enthält blueprint_bindings
steeringSnapshot,
...
)
→ merge PROPOSAL_UI_CONFIG with blueprint.composition.proposal_ui
→ merge steeringElementRegistry labels with blueprint.composition.steering_element_copy
→ apply provider_overrides (order, props, enabled)
```
### 8.2 Verboten
- Neue `kind`-Werte in `compositionProviders.js` ohne ADP
- Archetyp-Ifs zur Panel-Aktivierung
- Blueprint-spezifische React-Pages
### 8.3 Cockpit / Portfolio
Blueprint-Bindings gelten **initiative-scoped**. Portfolio-Aggregation (`GET /workspace/steering`) nutzt **keine** Blueprint-Copy — nur Kernel-Output.
---
## 9. Impulse, Proposals, Attention
| Aspekt | Blueprint | Kernel |
|--------|-----------|--------|
| Proposal **Existenz** | — | Provider + `steering_elements` |
| Proposal **summary** in DTO | — | Ranker/Provider |
| UI **title/lead/acceptLabel** | Ja | — |
| **reason_code** → Label-Mapping | Erweiterung `proposalReasonLabel`-Map | Codes stabil |
| Attention **Auslösung** | — | Contributors |
| Attention **Anzeige-Text** | Ja (`attention_labels`) | — |
| Programm-**Impulse** (B2a) | Copy für Impulse-Typen | Nested Context Kernel |
**Ranker-Parameterisierung:** Blueprint liefert `ranker_params` → Operating Context → Kernel liest bei Ranker-Aufruf. Keine neuen Ranker-Keys im Template ohne Registry-Eintrag.
---
## 10. KI / Prompts
### 10.1 Binding-Modell
```text
Blueprint.prompt_refs[]:
prompt_key → Eintrag in prompt_definitions (Foundation)
context_kind → initiative_snapshot | operating_context | agent_slot_payload
placeholder_bindings → { "product_name": "efs.product_vision" | "snapshot.method_key" }
```
### 10.2 Governance
| Regel | Detail |
|-------|--------|
| Freeze | **Keine produktive KI-Ausführung** bis AP2.1 Go — BP-5 Implementierung, nicht BP-1 |
| SK-13 | Kein Prompt-Text in Blueprint, UI, Router |
| Audit | Ausführung über bestehende `prompt_execution_logs` |
| Agent-Slots | SK-17: Slots deklarativ; Prompt-Ref optional an Slot |
---
## 11. Structure Builder — Abgrenzung
| Aspekt | Starter-Kit / Blueprint | Structure Builder (voll) |
|--------|-------------------------|---------------------------|
| **Wann** | Bei Initiative-Anlage | Hook `on_structure_required` / Lifecycle Schlitz 3 |
| **Tiefe** | 5–15 Seed-Objekte, Guidance | Tiefen-WBS, Feature-Landschaft, Graph-Generierung |
| **Owner** | Blueprint `starter_kit` + `apply_starter_kit` | Method Registry Builder |
| **MVP** | **Ja** (AP2.2a + BP-2) | **Deferred** |
| **Beziehung** | Blueprint **kann** `structure_builder_hint` setzen — triggert später optional Builder | Builder liest Hint, nicht Blueprint-If |
**Regel:** Blueprint **ersetzt** Structure Builder nicht. Bei BP-6+ Designer kann Tenant Presets erweitern — bleibt unter Builder-Hook-Governance.
---
## 12. Persistenz-Zielbild
### 12.1 Tabellen (Phase C Erweiterung Target Architecture §15)
```text
blueprints (
id, blueprint_key, version, label, description,
initiative_archetype_key, method_key,
scope_type, tenant_id, user_id,
parent_blueprint_key, status, bindings_json,
is_system, created_at, updated_at, published_at
)
initiatives.blueprint_key -- nullable
initiatives.blueprint_version -- nullable, gesetzt bei Anlage
steering_context.lifecycle_metadata.blueprint_key -- Spiegel / Legacy method_profile_key
```
**Indizes:** `(tenant_id, initiative_archetype_key, status)`, `(blueprint_key, version)` unique.
### 12.2 Code-Seeds → DB (BP-1)
1. Inhalt von `METHOD_PROFILES` nach `blueprints` migrieren (System, `published`)
2. `bindings_json` minimal: `guidance`, `starter_kit` aus erweiterten Seeds, `composition_hints`
3. API: `GET /api/blueprints?archetype_key=…` ersetzt erweitert `GET /steering/method-profiles`
4. Alias: `method_profile_key` ↔ `blueprint_key` (identische Werte in v1)
---
## 13. Migrationspfad — Phasenplan AP-BP-1…n
| Phase | Ziel | Deliverables | Abhängigkeit | Nicht in Phase |
|-------|------|--------------|--------------|----------------|
| **BP-0** | Konzeption | Dieses ADP + Scope Lock | — | Code |
| **BP-1** | Read-only System-Blueprints | DB-Tabelle + Seed-Migration; API list/get; Operating Context `blueprint_key`; Alias `method_profile_key` | ADP frei | Anlage-Materialisierung, Tenant-Kopien |
| **BP-2** | Anlage: Template wählen + materialisierte Presets | Anlage-Dialog Blueprint-Auswahl; `apply_starter_kit` aus Blueprint; EFS-Defaults; `blueprint_version` speichern | AP2.2a+, BP-1 | Copy-Bindings, Designer |
| **BP-3** | Tenant-Kopie + editierbare Felder/Presets | Fork System→Tenant; PATCH bindings (draft); Capability-Gate | Tenant-Invariants, BP-2 | Prompt-Ausführung |
| **BP-4** | Composition + Copy-Bindings | Merge in `resolveSteeringComposition`; Backlog-Vocabulary; Proposal/Attention-Copy | UX Kernel MVP, BP-1 | KI-Produktion |
| **BP-5** | Prompt/Agent-Bindings | `prompt_refs` Auflösung; Agent-Slot-Copy; `ranker_params` | **AP2.1 Go**, BP-4 | Designer |
| **BP-6** | Designer / Import | Visueller Blueprint-Editor; YAML-Import; Versionierung UI | BP-3, PO-Priorität | — |
### 13.1 Parallelität zu MVP Stufe A
```text
AP2.1 Validation (Stufe A Abschluss) ──┐
AP2.2c / AP1.9d ──┼── parallel möglich, nicht blockiert durch BP-0
BP-1 (Read-only Seeds) ──┘ nach ADP-Freigabe; PO entscheidet Minimal-Slice
BP-2+ sollte AP2.2a Starter-Kit-Pipeline nutzen — nicht ersetzen.
BP-5 explizit nach AP2.1 Go — KI/Prompt eingefroren.
```
### 13.2 Was **nicht** vor AP2.1 Go
- Produktive Prompt-Ausführung aus Blueprint
- Agent-Ranker (`agent_v1`) Parameter aus Template
- MCP/Workflow-Fragmente an Blueprint gebunden
---
## 14. Referenz-Blueprints (Beispiele — keine Vollimplementierung)
### 14.1 `product.kairo_dev`
| Attribut | Wert |
|----------|------|
| Archetyp | `initiative.product` |
| Methode | `continuous_product` |
| Komposition | `agile_iteration` via `composition_hints` |
| EFS-Defaults | `product_vision`, `primary_repo_or_system` (Platzhalter) |
| Starter-Kit | Gates „Orientierung“, „Nächster Release-Horizont“; Projects „Entwicklung“, „Betrieb“; Sample-Backlog „Idea“ |
| Composition | `gate_fulfillment`-Horizont-Copy; Sprint-Hinweis wenn `work_cycle_scope` aktiv |
| Proposals | `intake_triage.lead` product-spezifisch |
| Prompt-Ref (BP-5) | `kairo.product.triage_hint` |
| Backlog-Vocabulary | `backlog_item` → „Issue“ |
| **Nicht** | Eigene Next-Action-Strategie; kein erzwungenes `critical_path`; kein Archetyp-Wechsel |
**Differenzierung zu Generic Product:** Labels, Gate-Namen, Issue-Vokabular, PO+Vibe-Coder-Hint — **gleiche** `steering_elements` wie `continuous_product`.
### 14.2 `maturity.karate_kumite`
| Attribut | Wert |
|----------|------|
| Archetyp | `initiative.maturity_journey` |
| Methode | `maturity_progression` |
| EFS-Defaults | `discipline` = „Karate“ |
| Starter-Kit | 8 Projects (Fähigkeiten) × Stufen-Presets (5–7 `maturity_stage` pro Skill — **Struktur-Seed**, nicht 200 Tasks); Recurring „Training“ |
| Journey-Labels | Kumite-spezifische Event-Darstellung |
| Graph | `graph_prerequisites: true` — Labels only; Kanten manuell/separater Graph-Setup |
| **Nicht** | Stufenwechsel-Logik im Template — bleibt Kernel + AP2.0e; keine neuen OM-Typen |
**Differenzierung zu Generic A1:** Disziplin-Feld, 8-Skill-Raster, Kumite-Vokabular — **gleiche** Methode `maturity_progression`.
### 14.3 `content.book_writing`
| Attribut | Wert |
|----------|------|
| Archetyp | **`initiative.linear_project`** (Decision-Lock D1 — kein `content_project`) |
| Methode | `sequential_dependency` (+ optional `agile_iteration`) |
| EFS-Defaults | `word_goal`, `genre` |
| Starter-Kit | Kapitel als `milestone`/`chapter`-RoadmapItems; Review-Gate-Presets; Project „Manuskript“ |
| Composition | `gate_next_actions.lead` schreib-orientiert |
| Plan-Outline-Hints | Kapitel → Review → Revision |
| **Nicht** | Eigene Kapitel-Steuerungsmethode; `chapter_based_progression` nur wenn Methode explizit gewählt und kompatibel |
**Hinweis Migration:** Ist-Seed `content.book_writing` in `method_profiles/registry.py` referenziert noch `initiative.content_project` — bei BP-1 auf Decision-Lock korrigieren.
---
## 15. Abnahme & PO-Freigabe
### 15.1 Qualitätskriterien (AP-BP-0 Prompt)
- [x] Entwickler kann aus §4.2 + §5 ableiten, welche JSON-Felder ein Blueprint hat
- [x] Laufzeit-Auflösung neben Operating Context dokumentiert (§3.2)
- [x] Mindestens zwei Referenz-Blueprints differenzierbar ohne neues Steering (§14.1, §14.2)
- [x] Anti-Patterns MVP v0.3 §3 und SK-Regeln adressiert (§6.3)
- [x] Migrationspfad `method_profiles/registry.py` dokumentiert (§12.2, §4.4)
- [x] KI/Designer als Phasen, nicht MVP-Blocker (§13, BP-5/6)
- [x] Konflikte Katalog v0.2 / Decision-Lock markiert (§14.3, §16)
### 15.2 PO-Freigabe-Checkliste
- [ ] Blueprint vs. Method Profile Rename akzeptiert
- [ ] Bindings-Matrix Scope für BP-1…4 bestätigt
- [ ] Referenz-Blueprints (Kumite, Kairo Dev, Buch) als System-Seeds freigegeben
- [ ] Parallelität BP-1 vs. AP2.1 explizit entschieden
- [ ] Tenant-Custom-Fields-Grenze (BP-3 vs. EFS Phase 2) entschieden
---
## 16. Offene Entscheidungen (PO)
| # | Frage | Optionen | Empfehlung |
|---|-------|----------|------------|
| **O-1** | Minimal-Slice: BP-1 vor AP2.1? | A) BP-1 parallel B) BP-1 nach AP2.1 Go | A — read-only, risikoarm |
| **O-2** | API-Key: sofort `blueprint_key` oder Alias-Phase? | A) Dual-Key 6 Monate B) Hard cut | A — Dual-Key |
| **O-3** | User-Scope Blueprints (`scope_type=user`)? | A) BP-3 B) BP-6 C) Nie | B — erst mit Designer |
| **O-4** | Tenant darf System-Blueprint `bindings_json` überschreiben oder nur Fork? | A) Fork only B) Overlay | A — Fork only (Audit, Versionierung) |
| **O-5** | Materialisierte Presets bei Blueprint-Version-Upgrade? | A) Nie auto B) Opt-in Migration C) Nur Copy | A für v1 |
| **O-6** | `content.book_writing`: Methode `sequential_dependency` oder `chapter_based_progression`? | Decision-Lock: A2 + Profil | `sequential_dependency` Default; `chapter_based_progression` wenn PO als kompatible Methode freigibt |
| **O-7** | Blueprint-Auswahl Pflicht bei Anlage? | A) Optional B) Pflicht wenn >1 | A — Optional mit Empfehlung |
| **O-8** | Projekt-Blueprints (Phase 2 AP1.10)? | A) Initiative only v1 B) Project später | A — Initiative only v1 |
| **O-9** | Ranker-Parameter: Allowlist pro Proposal-Key? | A) Ja B) Freies JSON | A — Allowlist in Method Contract |
| **O-10** | Katalog v0.3: Schicht-3-Label „Blueprint“ statt „Ausprägung“? | A) Ja B) Beide | A |
---
## 17. Konfliktauflösung
| Konflikt | Auflösung |
|----------|-----------|
| Katalog v0.2 D1 `content_project` vs. Decision-Lock A2+Profil | **Decision-Lock führt** — Blueprint `content.book_writing` auf `linear_project` |
| Katalog v0.2 „Ausprägung“ vs. PO „Template“ | **Blueprint** = offizieller Name; Ausprägung historisch |
| `method_profile_key` in API/Snapshot | Alias bis BP-2 abgeschlossen |
| UX Composition: Provider-Props aus Blueprint vs. Registry | Registry definiert Kind; Blueprint nur `props`/`order`/`enabled` |
| AP2.4: `agile_iteration` über Profil | **`composition_hints.agile_iteration`** im Blueprint — kein separates Profil-Objekt |
---
## 18. Referenzen
| Artefakt | Pfad |
|----------|------|
| Konzeptions-Prompt | `docs/architecture/AP_BP_0_Template_Blueprint_Conception_Prompt_v0.1.md` |
| Scope Lock | `docs/architecture/ADP_Template_Blueprint_Scope_Lock_v0.1.md` |
| Method Profiles (Ist) | `backend/method_profiles/registry.py` |
| Starter-Kits | `backend/services/archetype_starter_kit.py` |
| Operating Context | `backend/services/operating_context.py` |
| UX Composition | `frontend/src/composition/` |
| Proposal UI Config | `frontend/src/utils/steeringProposals.js` |
---
*AP-BP-0 Ergebnis — kein Code. Implementierung erst nach PO-Freigabe dieses ADP.*
@@ -0,0 +1,227 @@
# AP-BP-0 — Konzeptions-Prompt: Vorhaben-Template / Blueprint-Architektur
**Status:** Arbeitsauftrag für Konzeptionsphase (kein Implementierungs-AP)
**Stand:** 2026-07-27
**Ziel-Deliverable:** `ADP_Vorhaben_Template_Blueprint_v0.1.md` (+ optional Scope-Lock-ADP)
**Nicht-Ziel:** Code, Migrationen, UI-Implementierung — erst nach PO-Freigabe des ADP
---
## Rolle des Agents
Du bist **Architekt:in für Jinkendo Kairo**. Deine Aufgabe ist eine **implementierbare, guardrail-konforme Konzeption** für die Schicht **Vorhaben-Template / Blueprint** — nicht ein generisches Template-Engine-Design und kein zweites Operating Model.
Kairo ist **Program Director**, kein To-do-Tool. Steuerung läuft zentral über `backend/steering/` (`evaluate_steering()`). Templates **parametrisieren und präsentieren**, sie **ersetzen keine Methode** und **erfinden keine neue Steuerungslogik**.
---
## PO-Vorgabe (verbindlich)
> Steuerung bleibt **Archetyp- und Steuerungstyp-spezifisch**.
> Templates liefern später einen **Blueprint für einen bestimmten Aufgabentyp**: individuelle Felder, Prompts für KI-Auswertungen, Empfehlungen/Impulse, grafische Darstellungen, nutzerdefinierte Felder, Presets — **tenant-/nutzer-konfigurierbar in weiten Teilen**.
**Archetyp ≠ Template** (Decision-Lock 2026-07-25): Template ändert die **Natur** eines Vorhabens nicht.
---
## Pflichtlektüre (in dieser Reihenfolge)
1. `docs/product/Kairo_Vision_and_Product_Direction_v0.2.md`
2. `docs/product/Kairo_Canonical_Operating_Model_v0.2.md`
3. `docs/product/Kairo_MVP_Definition_v0.3.md` — §2 Schichtenmodell, §7 Anti-Todo-Wand
4. `docs/architecture/ADP_Archetype_and_Method_Catalog_v0.2.md` — §2.0 Vier Schichten, §2.2 Ausprägung
5. `docs/product/Kairo_Archetype_Decision_Lock_Interview_2026-07-25.md` — §7 Archetyp ≠ Vorhaben-Template
6. `docs/architecture/Kairo_Steering_Method_Kernel_v0.1.md` — §10 Beziehung zu Archetypen und Templates
7. `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`
8. `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md` (SK-01…SK-19)
9. `docs/architecture/ADP_UX_Composition_Kernel_v0.1.md` — Frontend-Spiegel, UI-Slots
10. `docs/architecture/ADP_AP1_10_Initiative_Archetypes_and_Entity_Field_System_v0.1.md` — EFS
11. `docs/architecture/Kairo_Method_Design_Principles_v0.1.md` — §8 Structure Builder (Abgrenzung)
12. `docs/product/Kairo_MVP_Execution_Plan_v0.2.md` — Starter-Kits statt voller Structure Builder
**Ist-Code (Referenz, nicht blind kopieren):**
- `backend/method_profiles/registry.py` — heutige Code-Seeds (Schicht-3-Anker)
- `backend/services/archetype_starter_kit.py` — AP2.2a Starter-Kits
- `backend/services/operating_context.py` — Laufzeit-Auflösung
- `frontend/src/composition/` — UX Composition Kernel (Provider, Slots)
- `frontend/src/registry/steeringElementRegistry.js`
---
## Kontext: Was heute existiert (Baseline)
| Baustein | Stand | Rolle |
|----------|-------|-------|
| Archetyp-Registry + EFS | ✓ | Schicht 2 — Natur, Default-Methode, Felder |
| Method Registry + Kernel v0.4 | ✓ | Schicht 1 — Steuerung |
| `method_profile_key` (4 Code-Seeds) | ◐ | Schicht-3-Anker; API + Metadata; **kein** profil-differenziertes Starter-Kit in UI |
| Starter-Kits AP2.2a | ✓ | Leichte Startstruktur; Ersatz für MVP-Structure-Builder |
| UX Composition Kernel | ✓ MVP | UI-Slots/Provider aus `steering_elements` + Kernel-Proposals |
| Structure Builder (voll) | ✗ deferred | Zielbild in Method Design Principles |
| Tenant-Template-Designer | ✗ | Zielbild Target Architecture §15 |
| KI/Prompt produktiv | ✗ eingefroren | bis AP2.1 Go; Prompt-Registry existiert Foundation-seitig |
**Wichtig:** Das Konzept muss den **Migrationspfad** von Code-Seeds → tenant-scoped Blueprints beschreiben, ohne MVP Stufe A zu blockieren.
---
## Leitfragen der Konzeption
1. **Was ist ein Blueprint/Template formal?** (Entität, Version, Scope: system / tenant / user, Vererbung)
2. **Was darf ein Template binden?** (Felder, EFS-Overrides, Starter-Presets, UI-Copy, Composition-Provider-Config, Prompt-Ref-IDs, Impuls-Texte, Graph-Labels, …)
3. **Was darf ein Template explizit NICHT?** (Next-Action-Algorithmus, Lifecycle-Override, neue OM-Tabellen, Archetyp-Ifs in Pages, Router-Steuerung)
4. **Wie hängt Template an Archetyp + Methode?** (Kompatibilitätsmatrix; ein Template pro Aufgabentyp; mehrere Templates pro Archetyp?)
5. **Wie unterscheidet sich Template von Ausprägung (`method_profile_key`) und von Structure Builder?**
6. **Wie nutzt der UX Composition Kernel Template-Config?** (Provider-Props, Copy, Sichtbarkeit — nicht neue Provider-Kinds ohne ADP)
7. **Wie nutzt der Steering Kernel Template-Config?** (Proposal-Copy, Ranker-Parameter, Attention-Schwellen — über Registry, nicht Hardcode)
8. **Wie werden KI-Prompts gebunden?** (Platzhalter-Registry, Template → prompt_key + context_kind; Audit; kein Prompt im React)
9. **Nutzerdefinierte Felder:** EFS-Erweiterung tenant-scoped vs. Template-scoped — Grenzen, Validierung, Governance
10. **Instanziierung:** Bei Vorhaben-Anlage — Template wählen → was wird materialisiert vs. was bleibt Referenz?
11. **Konfiguration durch User:** Was ist MVP-nah (Kopie + Felder editieren) vs. post-MVP (Designer, Import)?
12. **Anti-Patterns:** Template als versteckter Archetyp; Todo-Wand durch Template-Listen; parallele Steuerung
---
## Gewünschte Deliverables
### 1. Hauptdokument: `ADP_Vorhaben_Template_Blueprint_v0.1.md`
Mindestens diese Abschnitte:
| § | Inhalt |
|---|--------|
| 1 Problem & Nordstern | Warum Blueprint nach MVP Stufe A; Bezug Program Director |
| 2 Begriffe | Blueprint, Template, Ausprägung, Preset, Seed, Structure Builder — **eindeutige Abgrenzung** |
| 3 Schichtenmodell (erweitert) | Schicht 0–4 + wo Blueprint sitzt; Diagramm |
| 4 Template-Metamodell | Felder, Relationen, Lifecycle (draft/published/deprecated) |
| 5 Bindings-Matrix | Zeilen = bindbare Artefakte; Spalten = erlaubt / parametrisierbar / verboten / Phase |
| 6 Steuerungs-Grenze | Was bleibt bei Archetyp+Methode; SK-Regeln; `evaluate_steering()` single spine |
| 7 EFS & nutzerdefinierte Felder | Feldquellen, Validierung, Tenant-Invariants |
| 8 UX / Composition | Template → UI-Slots, Provider-Props, Labels; kein Archetyp-If |
| 9 Impulse, Proposals, Attention | Template-Copy vs. Kernel-Logik; Ranker-Parameterisierung |
| 10 KI / Prompts | Binding-Modell; Governance; Freeze bis AP2.1 |
| 11 Structure Builder | Abgrenzung: wann Template seedet vs. Builder hook |
| 12 Persistenz-Zielbild | Code-Seeds → DB-Tabellen (Referenz Target Architecture §15) |
| 13 Migrationspfad | AP-BP-1…n Phasen; was **nicht** vor AP2.1 Go |
| 14 Referenz-Blueprints | Kumite, Kairo Dev, Buch — als **Beispiele**, nicht als Vollimplementierung |
| 15 Abnahme & PO-Freigabe | Checkliste |
| 16 Offene Entscheidungen | Explizit markieren, nicht wegdesignen |
### 2. Optional: `ADP_Template_Blueprint_Scope_Lock_v0.1.md`
Kurzes Scope-Lock-Dokument: Was in Phase 1 **nicht** gebaut wird.
### 3. Bindings-Matrix (Pflicht-Artefakt)
Tabelle mindestens für:
- EFS-Felddefinitionen & Default-Werte
- Starter-Kit / Struktur-Presets
- `steering_element` UI-Copy & Sichtbarkeit
- Composition-Provider (Slot, order, embedded props)
- Proposal-UI-Config (`gate_next_actions`, `intake_triage`, …)
- Attention-Labels / Severity-Hints
- Agent-Slot-Copy
- Prompt-Referenzen (key, context_kind, Platzhalter)
- Graph-/Gate-Labels, Plan-Outline-Hints
- Backlog-Vocabulary-Profil
- Journey-Event-Typ-Labels (Darstellung)
Pro Zeile: **Template darf** | **nur System** | **Kernel bleibt Owner**
### 4. Phasenplan AP-BP-1…n
| Phase | Ziel | Abhängigkeit |
|-------|------|--------------|
| BP-1 | Read-only System-Blueprints (Seed-Migration) | ADP frei |
| BP-2 | Anlage: Template wählen + materialisierte Presets | AP2.2a+ |
| BP-3 | Tenant-Kopie + editierbare Felder/Presets | Tenant-Invariants |
| BP-4 | Composition + Copy-Bindings | UX Kernel |
| BP-5 | Prompt/Agent-Bindings | AP2.1 Go |
| BP-6 | Designer / Import | optional spät |
---
## Harte Guardrails (nicht verhandelbar)
- Keine Steuerungslogik in Templates, Routern oder React-Pages
- Keine Archetyp-Ifs zur Aktivierung von Panels — nur `steering_elements`, Proposals, Capabilities, Template-Config
- Keine neuen OM-Tabellen pro Template-Typ ohne ADP + Scope Lock
- Keine hardcodierten Prompts in UI oder Backend-Routern
- User ≠ Actor; Tenant-scoped; Auth/Capability/Governance getrennt
- Template darf **nicht** `method_key` oder Archetyp-Natur überschreiben (nur kompatible Ausprägung innerhalb des Archetyps)
- MVP Stufe A (AP2.1) **nicht** als Blocker für Konzept — Implementierung BP-1+ **nach** AP2.1 unless explizit PO-Minimal-Slice
---
## Explizite Abgrenzungen (im Konzept klären)
| Konzept | Abgrenzung zu Blueprint |
|---------|-------------------------|
| **Archetyp** | Natur, OM-Capabilities, Default-Methode, Plan/Ist-Vertrag |
| **Methode** | Steuerungsplugin im Kernel |
| **Method Profile (heute)** | Dünner Seed-Anker — Blueprint **superset** oder **Rename**? Begründen. |
| **Starter-Kit** | Materialisierung bei Anlage — Blueprint **liefert** Kit-Definition? |
| **Structure Builder** | Hook-getriebene Tiefenstruktur — Blueprint **triggert** oder **ersetzt**? |
| **UX Composition Provider** | Renderer — Blueprint **konfiguriert**, erfindet keine neue Kind-Logik |
| **Referenz-Ausprägung (Kumite, Kairo Dev)** | Erste System-Blueprints |
---
## Qualitätskriterien für das Konzept
Das ADP ist **freigabefähig**, wenn:
- [ ] Ein Entwickler aus §4 + Bindings-Matrix ableiten kann, **welche JSON/YAML-Felder** ein Blueprint hat
- [ ] Klar ist, **wo** Template zur Laufzeit aufgelöst wird (neben Operating Context)
- [ ] Mindestens **zwei Referenz-Blueprints** (Kumite, Kairo Dev) durch das Modell **differenzierbar** beschrieben sind — ohne neues Steering-Verhalten
- [ ] Anti-Patterns aus MVP v0.3 §3 und Method Kernel SK-Regeln **explizit** adressiert sind
- [ ] Migrationspfad von `method_profiles/registry.py` dokumentiert ist
- [ ] Kein Scope Creep: KI-Produktion, MCP, Designer als **Phasen**, nicht MVP-Blocker
- [ ] Konflikte mit ADP Catalog v0.2 / UX Composition v0.1 **aufgelöst oder als Offen markiert**
---
## Arbeitsmodus
1. **Nur lesen** — kein Code, keine Migration, kein UI-Patch
2. **Zuerst** Begriffe + Bindings-Matrix + Steuerungs-Grenze — dann Persistenz
3. **Diagramme:** Schichtenmodell + Auflösungskette (Template + Operating Context → Snapshot → Composition)
4. **Offene PO-Fragen** gesammelt am Ende — nicht still entscheiden
5. Output-Sprache: **Deutsch**
6. Format: Markdown unter `docs/architecture/`
7. Bei Widerspruch gilt: Vision v0.2 → COM v0.2 → MVP v0.3 → dieses Prompt-Dokument
---
## Referenz-Beispiel (Zielbild, nicht implementieren)
**Blueprint `product.kairo_dev`** auf Archetyp `initiative.product` + Methode `continuous_product`:
- EFS: `product_vision`, `primary_repo_or_system` vorbelegt
- Starter: Orientierungs-Gates, Projects Entwicklung/Betrieb, Sample-Backlog „Idea“
- Composition: `gate_fulfillment`-Horizont-Copy, Sprint-Hinweis wenn `work_cycle_scope`
- Proposals: `intake_triage`-Lead-Text product-spezifisch
- Prompt-Ref (später): `kairo.product.triage_hint` — Platzhalter aus Snapshot
- **Nicht:** eigene Next-Action-Strategie, kein `critical_path`
**Blueprint `maturity.karate_kumite`** auf A1:
- EFS: `discipline` = Karate
- Starter: 8 Skills × Stufen-Presets (Struktur-Seed, nicht 200 Tasks)
- Recurring-Presets pro Stufe (Verweis AP2.0e)
- Journey-Labels kumite-spezifisch
- **Nicht:** Stufenwechsel-Logik im Template — bleibt Kernel/AP2.0e
---
## Was nach der Konzeption passiert (nicht Teil dieses Prompts)
- PO-Freigabe ADP
- Dann erst: MVP-Stufe-A-Abschluss (AP2.2c, AP1.9d, AP2.1) **parallel oder vor** BP-1 — PO entscheidet
- Implementierung AP-BP-1+ gemäß Phasenplan
---
*Dieses Dokument ist der **Prompt/Arbeitsauftrag** für AP-BP-0. Ergebnis = ADP v0.1, kein Code.*
+2 -2
View File
@@ -2,14 +2,14 @@
**Prozess:** `../M1_Hybrid_Path_and_Depth_D_v0.1.md` **Prozess:** `../M1_Hybrid_Path_and_Depth_D_v0.1.md`
**Methodenkern (Freeze):** [`../Kairo_Steering_Method_Kernel_v0.1.md`](../Kairo_Steering_Method_Kernel_v0.1.md) — Methodentypen: Kernel §6 **Methodenkern (Freeze):** [`../Kairo_Steering_Method_Kernel_v0.1.md`](../Kairo_Steering_Method_Kernel_v0.1.md) — Methodentypen: Kernel §6
**PO 2026-07-26:** Architektur beibehalten; Spec-D-Batch **vorläufig freigegeben** (Implementierungsausreichendheit noch offen) **PO 2026-07-28:** Spec-D `maturity_progression` — **Horizon/Progression PO-Lock** in [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md); Spec-D D3/D6/D8 angepasst.
| Methode | Typ | Datei | Status | | Methode | Typ | Datei | Status |
|---------|-----|-------|--------| |---------|-----|-------|--------|
| `sequential_dependency` | Primary (Ausführung) | SPEC_D_sequential_dependency_v0.1.md | vorläufig freigegeben| | `sequential_dependency` | Primary (Ausführung) | SPEC_D_sequential_dependency_v0.1.md | vorläufig freigegeben|
| `continuous_product` | Primary (Ausführung) | SPEC_D_continuous_product_v0.1.md | vorläufig freigegeben| | `continuous_product` | Primary (Ausführung) | SPEC_D_continuous_product_v0.1.md | vorläufig freigegeben|
| `recurring_control` | Primary (Ausführung) | SPEC_D_recurring_control_v0.1.md | vorläufig freigegeben| | `recurring_control` | Primary (Ausführung) | SPEC_D_recurring_control_v0.1.md | vorläufig freigegeben|
| `maturity_progression` | Primary (Ausführung) | SPEC_D_maturity_progression_v0.1.md | vorläufig freigegeben| | `maturity_progression` | Primary (Ausführung) | SPEC_D_maturity_progression_v0.1.md | PO-Lock Horizon (2026-07-28) |
| `checklist_flow` | Primary (Ausführung) | SPEC_D_checklist_flow_v0.1.md | vorläufig freigegeben| | `checklist_flow` | Primary (Ausführung) | SPEC_D_checklist_flow_v0.1.md | vorläufig freigegeben|
| `care_navigation` | Primary (Ausführung) | SPEC_D_care_navigation_v0.1.md | vorläufig freigegeben| | `care_navigation` | Primary (Ausführung) | SPEC_D_care_navigation_v0.1.md | vorläufig freigegeben|
| `dispute_procedure` | Primary (Ausführung) | SPEC_D_dispute_procedure_v0.1.md | vorläufig freigegeben| | `dispute_procedure` | Primary (Ausführung) | SPEC_D_dispute_procedure_v0.1.md | vorläufig freigegeben|
@@ -2,7 +2,7 @@
## Steuerungsmethode — Spec-Tiefe D v0.1 ## Steuerungsmethode — Spec-Tiefe D v0.1
**Status:** vorläufig freigegeben (PO 2026-07-26) — mit zugehöriger Archetyp-Vollspec; Implementierungsausreichendheit noch offen **Status:** vorläufig freigegeben (PO 2026-07-26) — mit zugehöriger Archetyp-Vollspec; Implementierungsausreichendheit noch offen
**Stand:** 2026-07-26 **Stand:** 2026-07-28 (PO-Lock Progressionsmodell — [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md))
**Default für:** A1 `initiative.maturity_journey` **Default für:** A1 `initiative.maturity_journey`
**Prozess:** `M1_Hybrid_Path_and_Depth_D_v0.1.md` **Prozess:** `M1_Hybrid_Path_and_Depth_D_v0.1.md`
**Quellen:** Decision-Lock A1, Archetyp-Vollspec A1, Kernel Freeze, AP2.0e **Quellen:** Decision-Lock A1, Archetyp-Vollspec A1, Kernel Freeze, AP2.0e
@@ -17,7 +17,7 @@
| `method_key` | `maturity_progression` | | `method_key` | `maturity_progression` |
| Rolle | primary (**Ausführung** — Kernel §6) | | Rolle | primary (**Ausführung** — Kernel §6) |
| Label (DE) | Reifegrad-Progression | | Label (DE) | Reifegrad-Progression |
| Zweck | Fähigkeit über Stufen steuern: Active Stage als Horizont; Next = fällige/alternierende Übung oder Stage-Action; bei Stage `reached` Activity Set wechseln. Weiches Vorhaben-Ende. | | Zweck | Fähigkeit über **parallele Strang-Pfade** (Gate-Graph) steuern; Next = fällige Übungen auf **aktiven Gates**; bei Gate `reached` strangspezifischer Activity-Set-Wechsel. Weiches Vorhaben-Ende. |
--- ---
@@ -34,20 +34,26 @@
## D3 Horizon ## D3 Horizon
**PO-Lock (2026-07-28):** [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md) §3 — ersetzt „eine aktive Stufe initiative-weit“ für Multi-Strang.
| Horizont | Bedeutung | | Horizont | Bedeutung |
|----------|-----------| |----------|-----------|
| **Aktive `maturity_stage`** | fokussierte Stufe; nur deren Stage Activity Set liefert Next | | **Aktive Gates (Menge)** | Alle `maturity_stage`/Gate-Knoten mit Status `active`, die graph-ready sind; **mehrere parallel** (je Strang max. ein aktives Gate auf dem Pfad) |
| Plan-Nebenblick | nächste Stufe / Graph-Voraussetzungen — nicht Leading für Next | | **Strang** | `Project` — paralleler Fähigkeits-Pfad; Übungen mit `project_id` |
| Ist | CadenceInstances + Stage-Actions der aktiven Stufe | | **Join-Gate** | wird `active`, wenn alle `requires`-Vorgänger `reached` |
| Plan-Nebenblick | blockierte / geplante Gates — nicht Leading für Next |
| Ist | CadenceInstances + Stage-Actions der **aktiven Gates** |
Keine Next-Kandidaten aus inaktiven Stufen. Keine Next-Kandidaten aus Gates, die nicht `active`/graph-ready sind.
**Lineares Demo-Kit (1 Strang, Stufe 1–3):** Teilmenge mit effektiv einem aktiven Gate — kein PO-Kernbild.
--- ---
## D4 Leading Work Item ## D4 Leading Work Item
**Primär:** `CadenceInstance` (Übung/Ritual am RecurringElement der aktiven Stufe). **Primär:** `CadenceInstance` (Übung am `RecurringElement` eines **aktiven Gates**, optional Strang via `project_id`).
**Sekundär:** `Action` (Stage-gebunden: Prüfung, Workshop, Nachweis). **Sekundär:** `Action` (Gate-gebunden: Prüfung, Workshop — selten bei A1).
**Hinweis-Objekt (kein Leading Work):** offenes Stufen-Kriterium / Verify-Fortschritt — erscheint in Next/Attention als Steuerhinweis. **Hinweis-Objekt (kein Leading Work):** offenes Stufen-Kriterium / Verify-Fortschritt — erscheint in Next/Attention als Steuerhinweis.
Pro Recurring: genau **eine** offene Instanz (kein Duplikat bei Verpassen). Pro Recurring: genau **eine** offene Instanz (kein Duplikat bei Verpassen).
@@ -77,12 +83,13 @@ Kernel-Schlitznamen: Abbildung auf §4 Kernel (Intake … Closure).
## D6 Next Action — konkrete Regeln ## D6 Next Action — konkrete Regeln
### Ready-Menge (aktive Stufe) ### Ready-Menge (aktive Gates)
Ein Work Item ist ready, wenn: Ein Work Item ist ready, wenn:
1. gebunden an die **aktive** `maturity_stage` und Aktivität **aktiv**, und 1. gebunden an ein **aktives**, graph-ready **Gate** und Aktivität **aktiv**, und
2. eines von: 2. (Multi-Strang) `project_id` passt zum Strang des Gates, und
3. eines von:
- **Cadence ohne Alternanz:** Instanz fällig oder überfällig (heute laut Cadence / overdue), oder - **Cadence ohne Alternanz:** Instanz fällig oder überfällig (heute laut Cadence / overdue), oder
- **Cadence in Alternanz-Gruppe:** Instanz ist das **aktuelle** Gruppenmitglied **und** fällig/überfällig (bzw. „dran“ laut Gruppenpolicy, wenn Cadence der Gruppe geteilt ist), oder - **Cadence in Alternanz-Gruppe:** Instanz ist das **aktuelle** Gruppenmitglied **und** fällig/überfällig (bzw. „dran“ laut Gruppenpolicy, wenn Cadence der Gruppe geteilt ist), oder
- **Stage-Action:** Status offen und Deps/Blocker erlauben Arbeit - **Stage-Action:** Status offen und Deps/Blocker erlauben Arbeit
@@ -141,7 +148,7 @@ Unabhängige Cadences am gleichen Stage → mehrere ready am selben Tag möglich
| practice done / Cadence erfüllt | Instanz schließen; nächste Instanz laut Cadence; bei Alternanz Rotation | | practice done / Cadence erfüllt | Instanz schließen; nächste Instanz laut Cadence; bei Alternanz Rotation |
| Stage-Action done | aus Ready; ggf. Kriterien-Fortschritt | | Stage-Action done | aus Ready; ggf. Kriterien-Fortschritt |
| Evidence / Kriterium erfüllt | Validation-Fortschritt | | Evidence / Kriterium erfüllt | Validation-Fortschritt |
| stage `reached` (Verify ok) | altes Activity Set deaktivieren; nächste Stufe aktiv; neues Set aktiv (AP2.0e erweitert) | | stage `reached` (Verify ok) | Activity Set **dieses Gates** deaktivieren; **pro Strang** nächstes Gate / neues Set (Join: strangspezifisch) |
| manuelle Adaptation (Set/Cadence/Alternanz) | Ready-Menge neu; auditiert | | manuelle Adaptation (Set/Cadence/Alternanz) | Ready-Menge neu; auditiert |
| Cadence-Zeitpunkt erreicht | Event-Schub → Ready neu bewerten | | Cadence-Zeitpunkt erreicht | Event-Schub → Ready neu bewerten |
@@ -175,7 +182,7 @@ Felder `alternation_group_id`, `alternation_order`: Archetyp-Vollspec A1 §10.
|-----|------| |-----|------|
| next_work_strategy | `maturity_progression` | | next_work_strategy | `maturity_progression` |
| attention_rules | Codes D7 | | attention_rules | Codes D7 |
| horizon_resolver | aktive `maturity_stage` | | horizon_resolver | Menge aktiver, graph-ready Gates (Multi-Strang) |
| dod_policy | Stage-Kriterien / Verify | | dod_policy | Stage-Kriterien / Verify |
| adaptation_hooks | `on_stage_reached` → Set-Wechsel; manuelle Set-Änderung | | adaptation_hooks | `on_stage_reached` → Set-Wechsel; manuelle Set-Änderung |
| steering_elements | `next_action_primary`, `maturity_stage`, `recurring_rhythm` | | steering_elements | `next_action_primary`, `maturity_stage`, `recurring_rhythm` |
@@ -191,6 +198,7 @@ Felder `alternation_group_id`, `alternation_order`: Archetyp-Vollspec A1 §10.
| Hybrid Dominanz | Cadence-Event + Stage-Plan — Kernel trägt Dual-Auslöser | | Hybrid Dominanz | Cadence-Event + Stage-Plan — Kernel trägt Dual-Auslöser |
| Leading polymorph | Cadence + Action — Kernel Q2 | | Leading polymorph | Cadence + Action — Kernel Q2 |
| Alternanz-State | Persistenz am Group-/Recurring-Kontext — Implementierungsdetail, fachlich hier verbindlich | | Alternanz-State | Persistenz am Group-/Recurring-Kontext — Implementierungsdetail, fachlich hier verbindlich |
| Multi-Fähigkeit | mehrere Projects ok; kein Abnahme-Zwang für Kern-Kit | | Multi-Fähigkeit | mehrere Projects / Stränge — **Kernbild A1** (PO-Lock); Gate-Graph verbindet Pfade |
| Single-active initiative-wide | **widerrufen** für Multi-Strang — nur Demo-Kit |
**PO-Empfehlung:** A1-Vollspec §4 OM + diese Spec-D = Steuervertrag; UI nur in Archetyp-Vollspec. **PO-Empfehlung:** A1-Vollspec §4 OM + diese Spec-D = Steuervertrag; UI nur in Archetyp-Vollspec.
@@ -57,7 +57,7 @@ Verhindert, dass Zielbild-Dokumente als Ist-Stand gelesen werden.
| Evidence | ✓ | `roadmap_item_id`, `action_id`; Gitea-Links in `description` (manuell) | | Evidence | ✓ | `roadmap_item_id`, `action_id`; Gitea-Links in `description` (manuell) |
| Decision | ✓ | | | Decision | ✓ | |
| Review | ✓ | `roadmap_item_id` | | Review | ✓ | `roadmap_item_id` |
| RecurringElement | ✓ | | | RecurringElement | ✓ | Cadence-Brücke für AP+Schedule; Default Wochentage (nicht Intervall +7) |
| Task (unter Action) | ◐ | AP1.5d: `parent_task_id`, Baum-API, Outline; Roll-up-UI ◐ | | Task (unter Action) | ◐ | AP1.5d: `parent_task_id`, Baum-API, Outline; Roll-up-UI ◐ |
| Roadmap | ◐ | 1 pro Initiative; Migration 010 | | Roadmap | ◐ | 1 pro Initiative; Migration 010 |
| RoadmapItem | ◐ | CRUD + Detail; Verify AP1.4b | | RoadmapItem | ◐ | CRUD + Detail; Verify AP1.4b |
@@ -156,7 +156,7 @@ Verhindert, dass Zielbild-Dokumente als Ist-Stand gelesen werden.
| Archetyp | Anlage+Kit | Struktur pflegen | Kontrolle | Op-API | Paket | | Archetyp | Anlage+Kit | Struktur pflegen | Kontrolle | Op-API | Paket |
|----------|------------|------------------|-----------|--------|-------| |----------|------------|------------------|-----------|--------|-------|
| A1 Reifegrad | ◐ AP2.2a | ◐ | ◐ | ◐ | AP2.2c + AP2.0e | | A1 Reifegrad | ✓ AP2.2a | ✓ | ✓ | ◐ | AP2.2c ✓ |
| A2 Linear | ✓ AP2.2a | ✓ | ✓ | ◐ | AP2.2b ✓ | | A2 Linear | ✓ AP2.2a | ✓ | ✓ | ◐ | AP2.2b ✓ |
| B2b Product | ◐ AP2.2a | ◐ | ◐ | ◐ | AP2.2d ✓ | | B2b Product | ◐ AP2.2a | ◐ | ◐ | ◐ | AP2.2d ✓ |
| B3 Sprint-Profil | ◐ | ◐ | ◐ | ◐ | AP2.2d ✓ | | B3 Sprint-Profil | ◐ | ◐ | ◐ | ◐ | AP2.2d ✓ |
@@ -176,7 +176,7 @@ Verhindert, dass Zielbild-Dokumente als Ist-Stand gelesen werden.
| maturity / sequential / queue / recurring Strategien | ✓ | AP2.0d; pytest + Deploy | | maturity / sequential / queue / recurring Strategien | ✓ | AP2.0d; pytest + Deploy |
| Referenz-Ausprägungen (Kumite, Buch, Kairo) | ◐ | Code-Registry; Nutzer wählt bei Anlage | | Referenz-Ausprägungen (Kumite, Buch, Kairo) | ◐ | Code-Registry; Nutzer wählt bei Anlage |
| Archetyp Starter-Kits | ◐ | AP2.2a | | Archetyp Starter-Kits | ◐ | AP2.2a |
| MVP-Abnahfe Stufe A validiert | ✗ | AP2.1 nach AP2.2b–e | | MVP-Abnahfe Stufe A validiert | ✗ | AP2.1: A1 PO No-Go; A2/B2b offen — Register §7 |
| Operational Actor API | ✓ | AP1.7: `/api/operational/` + Service Tokens | | Operational Actor API | ✓ | AP1.7: `/api/operational/` + Service Tokens |
| Actor Service Token | ✓ | AP1.7c; Tenant-scoped, capability-gebunden | | Actor Service Token | ✓ | AP1.7c; Tenant-scoped, capability-gebunden |
| MCP produktiv | ✗ | nach AP2.1 Go | | MCP produktiv | ✗ | nach AP2.1 Go |
@@ -220,6 +220,15 @@ Details: `Kairo_Status_Review_and_Next_Steps_v0.1.md` §2.1
| Roadmap-Phasen veraltet | Roadmap v0.2 §2 aktualisiert 2026-07-11 | | Roadmap-Phasen veraltet | Roadmap v0.2 §2 aktualisiert 2026-07-11 |
| Usability Recovery → InitiativeDetail | IA-first, Redirects AP1.9a | | Usability Recovery → InitiativeDetail | IA-first, Redirects AP1.9a |
| **F-A1-09** | Leitfrage (≤2 Min) | Prozess/Doku | — | offen | Report §3.3 |
---
## 7. Validation-Findings (AP2.1)
PO-Smoke-Ergebnisse und Architektur-Einordnung:
`docs/sprints/Sprint1_AP2_1_Validation_Findings_Register_v0.1.md`
--- ---
## Nächste erwartete Truth-Table-Änderungen ## Nächste erwartete Truth-Table-Änderungen
@@ -231,9 +240,11 @@ Details: `Kairo_Status_Review_and_Next_Steps_v0.1.md` §2.1
| ADP Backlog/Epic | P1–P8 ✓ · K-Ext-1/2/3/4/5 ✓ | | ADP Backlog/Epic | P1–P8 ✓ · K-Ext-1/2/3/4/5 ✓ |
| Steering Kernel Proposals | ✓ | sprint_commit · gate_next_actions · intake_triage (Kernel v0.4) | | Steering Kernel Proposals | ✓ | sprint_commit · gate_next_actions · intake_triage (Kernel v0.4) |
| AP2.2b | A2 Linear E2E ✓ (2026-07-27) | | AP2.2b | A2 Linear E2E ✓ (2026-07-27) |
| AP2.2c | A1 Reifegrad E2E ✓ (2026-07-27) |
| AP1.9d | Work-Composition + Drill-down ◐→✓ (2026-07-27) |
| AP2.2c–e | Referenz-Archetypen End-to-End ◐→✓ | | AP2.2c–e | Referenz-Archetypen End-to-End ◐→✓ |
| AP2.1 | MVP-Abnahfe ✗→✓ | | AP2.1 | MVP-Abnahfe ◐→✓ (Report v0.3 + Assignment 2026-07-28; PO-Smoke auf Dev) |
| AP1.7b | Op-API Parität | | AP1.7b | Op-API Parität ◐→✓ (2026-07-27) |
--- ---
+17 -9
View File
@@ -2,7 +2,7 @@
## MVP Execution Plan v0.2 ## MVP Execution Plan v0.2
**Status:** PO-Kurskorrektur — **führend für Implementierung ab 2026-07-12** **Status:** PO-Kurskorrektur — **führend für Implementierung ab 2026-07-12**
**Stand:** 2026-07-25 (AP2.3/AP2.4 Plugin-Architektur ✓) **Stand:** 2026-07-28 (Phase 5 AP2.1 — Validation-Artefakte bereit)
**Bezug:** `Kairo_MVP_Definition_v0.3.md` §5–9, `ADP_Archetype_and_Method_Catalog_v0.2.md` §3, `ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `Kairo_Corrected_MVP_Roadmap_v0.2.md` (AP-Historie) **Bezug:** `Kairo_MVP_Definition_v0.3.md` §5–9, `ADP_Archetype_and_Method_Catalog_v0.2.md` §3, `ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `Kairo_Corrected_MVP_Roadmap_v0.2.md` (AP-Historie)
**Spezifikationsphase (ab 2026-07-24/25):** **Spezifikationsphase (ab 2026-07-24/25):**
- Decision-Lock: `Kairo_Archetype_Decision_Lock_Interview_2026-07-25.md` - Decision-Lock: `Kairo_Archetype_Decision_Lock_Interview_2026-07-25.md`
@@ -78,13 +78,13 @@ Phase 0 DOC + Kurskorrektur (dieses Dokument) ✓
Phase 0b AP2.3/AP2.4 Plugin-Architektur (Archetyp ↔ Methode) ✓ Phase 0b AP2.3/AP2.4 Plugin-Architektur (Archetyp ↔ Methode) ✓
Phase 1 AP2.2a Archetyp-geführte Anlage + Starter-Kits ✓ Phase 1 AP2.2a Archetyp-geführte Anlage + Starter-Kits ✓
Phase 1b Specs Welle 1 finalisieren (A1,A2,B2a,B2b,B3) ◐ Phase 1b Specs Welle 1 finalisieren (A1,A2,B2a,B2b,B3) ◐
Phase 2 AP1.9d Methoden-Default-Ansichten (Anti-Todo-Wand) ◐ (Hints + Recurring) Phase 2 AP1.9d Methoden-Default-Ansichten (Anti-Todo-Wand) ◐→✓ (Work-Composition + Drill-down)
Phase 3 AP2.2b A2 Linear End-to-End ✓ Phase 3 AP2.2b A2 Linear End-to-End ✓
AP2.2c A1 Reifegrad + AP2.0e ◐ Code AP2.2c A1 Reifegrad + AP2.0e ✓
AP2.2d B2b Product + B3 Sprint ✓ AP2.2d B2b Product + B3 Sprint ✓
AP2.2e B2a Programm (optional vor AP2.1) AP2.2e B2a Programm (optional vor AP2.1)
Phase 4 AP1.7b Operational API — Pflege-Parität Phase 4 AP1.7b Operational API — Pflege-Parität ✓
Phase 5 AP2.1 Validation Report v0.3 (alle Stufe-A-Szenarien) Phase 5 AP2.1 Validation Report v0.3 (alle Stufe-A-Szenarien) ◐ PO
Phase 6 AP2.2f Stufe B: A3, B1, D1 Phase 6 AP2.2f Stufe B: A3, B1, D1
Phase 7 Schicht 4: Gitea-Webhook, MCP (nach AP2.1 Go) Phase 7 Schicht 4: Gitea-Webhook, MCP (nach AP2.1 Go)
``` ```
@@ -131,17 +131,25 @@ Auth: Actor Service Token (Tenant-scoped). Kein Gate-Verify, kein Lifecycle-Over
## 7. AP2.1 Validation (nach Stufe-A-Flows) ## 7. AP2.1 Validation (nach Stufe-A-Flows)
**Status:** Artefakte bereit (2026-07-28) — **PO-Smoke auf Dev ausstehend**
**Dev:** https://dev.kairo.jinkendo.de (`0.20.2-ap2.2d`, schema 025)
**Nicht:** ein Dogfooding-Vorhaben auf Pi. **Nicht:** ein Dogfooding-Vorhaben auf Pi.
**Sondern:** PO füllt Report mit **echten, in der UI angelegten** Referenz-Vorhaben: **Sondern:** PO füllt Report mit **echten, in der UI angelegten** Referenz-Vorhaben:
- A1 (Reifegrad) - A1 (Reifegrad)
- A2 (Linear) - A2 (Linear)
- B2b (+ optional B3 Zeitbox) - B2b (+ B3 Sprint minimal)
- D1 wenn Stufe B bis dahin fertig - D1 optional (Stufe B)
Vorlage: `docs/sprints/Sprint1_AP2_1_MVP_Validation_Report_v0.3.md` (neu bei AP2.1) | Artefakt | Pfad |
|----------|------|
| Auftrag (Ablauf, Go-Kriterien) | `docs/sprints/Sprint1_AP2_1_MVP_Validation_Assignment_v0.1.md` |
| Report (ausfüllen) | `docs/sprints/Sprint1_AP2_1_MVP_Validation_Report_v0.3.md` |
Go-Kriterium: MVP v0.3 §5 — pro Stufe-A-Archetyp Leitfrage ≤2 Min + Next Action begründet. Go-Kriterium: MVP v0.3 §5 — pro Stufe-A-Archetyp Leitfrage ≤2 Min + Next Action begründet; Portfolio Cockpit-Attention (Kriterium 7).
**Findings-Register (PO-Smoke + Architektur-Review):** `docs/sprints/Sprint1_AP2_1_Validation_Findings_Register_v0.1.md`
--- ---
+2 -2
View File
@@ -7,12 +7,12 @@
**UI-Navigation (Archetyp):** [`ARCHETYPE_UI_NAVIGATION_v0.1.md`](ARCHETYPE_UI_NAVIGATION_v0.1.md) **UI-Navigation (Archetyp):** [`ARCHETYPE_UI_NAVIGATION_v0.1.md`](ARCHETYPE_UI_NAVIGATION_v0.1.md)
**Backlog / Epic / Dual Commit:** [`../../architecture/ADP_Backlog_Hierarchy_and_Dual_Commit_Path_v0.1.md`](../../architecture/ADP_Backlog_Hierarchy_and_Dual_Commit_Path_v0.1.md) **Backlog / Epic / Dual Commit:** [`../../architecture/ADP_Backlog_Hierarchy_and_Dual_Commit_Path_v0.1.md`](../../architecture/ADP_Backlog_Hierarchy_and_Dual_Commit_Path_v0.1.md)
**PO 2026-07-26:** Specs **vorläufig freigegeben** — Implementierungsausreichendheit noch nicht abschließend bewertet. **PO 2026-07-28:** A1 **PO-Lock Progressionsmodell** — [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](SPEC_A1_Progression_Model_PO_Lock_v0.1.md) (Option C nach Validation No-Go).
| ID | Datei | Status | | ID | Datei | Status |
|----|-------|--------| |----|-------|--------|
| C1 | [SPEC_C1_dispute_case_v0.1.md](SPEC_C1_dispute_case_v0.1.md) | vorläufig freigegeben | | C1 | [SPEC_C1_dispute_case_v0.1.md](SPEC_C1_dispute_case_v0.1.md) | vorläufig freigegeben |
| A1 | [SPEC_A1_maturity_journey_v0.1.md](SPEC_A1_maturity_journey_v0.1.md) | vorläufig freigegeben | | A1 | [SPEC_A1_maturity_journey_v0.1.md](SPEC_A1_maturity_journey_v0.1.md) | PO-Lock Progression (2026-07-28) |
| A2 | [SPEC_A2_linear_project_v0.1.md](SPEC_A2_linear_project_v0.1.md) | vorläufig freigegeben | | A2 | [SPEC_A2_linear_project_v0.1.md](SPEC_A2_linear_project_v0.1.md) | vorläufig freigegeben |
| A3 | [SPEC_A3_recurring_program_v0.1.md](SPEC_A3_recurring_program_v0.1.md) | vorläufig freigegeben | | A3 | [SPEC_A3_recurring_program_v0.1.md](SPEC_A3_recurring_program_v0.1.md) | vorläufig freigegeben |
| B1 | [SPEC_B1_checklists_v0.1.md](SPEC_B1_checklists_v0.1.md) | vorläufig freigegeben | | B1 | [SPEC_B1_checklists_v0.1.md](SPEC_B1_checklists_v0.1.md) | vorläufig freigegeben |
@@ -0,0 +1,220 @@
# A1 — Progressionsmodell PO-Lock
## v0.1 (Option C, AP2.1)
**Status:** **PO-lock** (2026-07-28) — präzisiert Spec A1 §4 und Spec-D D3/D6 vor Implementierung
**Auslöser:** AP2.1 PO-Validation — flache Rhythmus-Liste deckt Nutzerbild nicht ab
**Bezug:** `SPEC_A1_maturity_journey_v0.1.md`, `SPEC_D_maturity_progression_v0.1.md`
---
## 1. PO-Kernentscheidung
A1 ist **kein lineares Stufenmodell mit losem „Wiederkehrend“**, sondern ein **Progressionsmodell über parallele Stränge (Pfade)** mit **Gate-Graph**, **Activity Sets pro Gate** und **wiederkehrenden Übungen als Ist-Tracking**.
| PO-These | Lock |
|----------|------|
| Primär ist **Üben / Wiederholung**, nicht committete Einmal-APs | ✓ Spec-D D4 unverändert |
| Komplexität liegt in **Planung + Durchführung paralleler Progressionen** | ✓ ab jetzt explizit |
| **Rhythmus** ist Eigenschaft der **Übung** (`RecurringElement`), kein losgelöstes Planungsobjekt | ✓ |
| **Strang** = `Project` (`container_kind=stream`); **Work-Gate** = `maturity_stage` mit Activity Set | ✓ |
| **Join** = Schaltknoten — kein Activity Set; konsolidierter Status; multi-in / multi-out | ✓ (§10) |
| **Kein Terminalgate-Typ** — letztes Gate vor Join ist normales Gate; Kante genügt | ✓ (§10) |
---
## 2. Referenzbeispiel (PO) — Mawashi Geri
**Vorhaben:** Fähigkeit „Mawashi Geri zum Kopf treffen“.
**Stränge (Projects):**
| Strang | Beispiel-Gates (Pfad) |
|--------|------------------------|
| Dehnung | D1 → D2 |
| Hüftrotation | H1 → H2 |
| Technik | T1 → T2 |
**Join (Schaltknoten):** „Mawashi Geri zur Hüfte“ — **keine Übungen**; Eingänge von D2, H2, T2; Ausgänge z. B. zu D3, G1 (Gleichgewicht). Konsolidierter Status **liegt am Join**, nicht an D2/H2/T2.
**Nach Schalten (MVP):** alle Ausgänge feuern → Nachfolge-Gates je Strang `active` → Activity Sets frei.
**Leitfrage:** *Welche Übungen sind heute auf aktiven Strang-Gates fällig — und welche Joins warten noch auf welche Eingänge?*
---
## 3. Horizon — Ersetzt „eine aktive Stufe initiative-weit“
### 3.1 Alt (v0.1, zu eng)
> Genau **eine** `maturity_stage` mit Status `active` pro Initiative.
Gilt **nicht mehr** für Multi-Strang-Progression (nur noch für lineares Demo-Kit „Spagat 1–2–3“).
### 3.2 Neu (PO-lock)
| Regel | Bedeutung |
|-------|-----------|
| **H1 — Parallele aktive Gates** | Initiative-weit **mehrere** Gates dürfen `active` sein — je Strang höchstens **ein** aktives Gate auf dem linearen Pfadfortschritt |
| **H2 — Strang** | `Project` mit Archetyp-Spiegel `project.maturity_journey`; optional `roadmap_item_id` am Gate für Zuordnung |
| **H3 — Join (Schaltknoten)** | Join **nie** in Today/Next; Status am Join = welche **Eingänge** noch nicht `reached`; Schaltbedingung = alle Eingänge erfüllt |
| **H4 — Ready / Next** | Ready-Menge = Activity Sets aller **aktiven Work-Gates** (`maturity_stage`); Joins ausgeschlossen |
| **H5 — Inaktive Pfade** | Gates `planned` / blockiert durch Graph → deren Übungen **nicht** in Next/Today |
**Horizon-Resolver (Ziel):** Menge `{ work_gate_id | status=active ∧ graph_ready ∧ hat Activity Set }` — Join-Knoten nie enthalten.
---
## 4. Activity Set — Bindung Übung ↔ Pfad
### 4.1 Was eine „Übung“ ist
| Begriff UI | OM-Entität | Pflicht-Bindung |
|------------|------------|-----------------|
| Übung / Ritual | `RecurringElement` | `roadmap_item_id` → Gate |
| Strang | `project_id` → Project (Strang) | **ja**, wenn ≥2 Stränge |
| Rhythmus | `interval_days`, Alternanz-Felder | am Recurring |
| Heute erledigt | `CadenceInstance` | pro Recurring |
**Anti-Pattern (PO):** flache Liste „Wiederkehrend“ ohne Gate- und Strang-Bezug.
### 4.2 Einmal-Aktivitäten
`Action` nur **sekundär** (Prüfung, Workshop, Nachweis) — an Gate + optional Strang. Nicht Träger täglicher Übung.
### 4.3 Messbarkeit
| Ebene | Mechanismus |
|-------|-------------|
| Ist (Tages-) | `CadenceInstance.measurement_note` |
| Plan (Gate) | `RoadmapItemCriterion` mit `criterion_kind: metric` |
| Verify | Evidence + Kriterien vor `reached` |
---
## 5. Verify, Schalten, Set-Wechsel
### 5.1 Work-Gate (mit Activity Set)
Bei `reached` eines Work-Gates **G**:
1. Activity Set von **G** deaktivieren.
2. Hat **G** einen **Join** als direkten Nachfolger (Kante G → Join): **kein** auto-next auf dem Strang — Beitrag zum Join ist erfüllt; Strang pausiert bis Join schaltet.
3. Hat **G** ein **Work-Nachfolge-Gate** auf demselben Strang: dieses → `active` (wenn unblocked).
4. Audit + Journey-Event.
### 5.2 Join (Schaltknoten, §10)
Bei **Schaltbedingung erfüllt** (alle Eingänge `reached`):
1. Join-Status → `reached` (automatisch oder explizites „Schalten“ — **kein** Verify über Übungs-Kriterien).
2. **MVP:** **alle** Ausgangs-Gates → `active` (sofern Work-Gates mit Activity Set).
3. Activity Sets der neu aktiven Gates freischalten.
4. Audit + Journey-Event („Join geschaltet: {Titel}“).
**Stufe B:** selektives Schalten von Ausgängen (If/Else) — §10.4.
**Nicht:** pauschal „nächste lineare Stufe 2“ initiative-weit (Demo-Kit-Ausnahme).
---
## 6. UI-Pflicht (Plan vor Today)
| Fläche | Inhalt (PO) |
|--------|-------------|
| **Plan → Struktur** | Stränge + Graph; Joins als **Knoten** (Eingänge/Ausgänge sichtbar) |
| **Plan → Gate-Detail** | Nur **Work-Gates**: Activity Set, Strang, Cadence, metric-Kriterien |
| **Plan → Join-Detail** | Titel, Eingänge, Ausgänge, Schaltstatus — **kein** Activity Set |
| **Ausführen → Today** | fällige Übungen nur von **aktiven Work-Gates** |
| **Kontrolle** | Join-Warteliste: *„{Join-Titel} wartet auf: Dehnung/D2, …“* |
| **Journey** | Set-Wechsel, Verify, Messwerte |
**Nicht** als Haupt-IA: generisches „Wiederkehrend“ ohne Plan-Kontext.
---
## 7. MVP-Stufe A — Abgrenzung nach PO-Lock
| Ebene | Inhalt | Stufe A |
|-------|--------|---------|
| **Demo Minimum** | Lineares Kit (Spagat 3 Stufen, 1 Strang) | Validation **technisch** — nicht PO-Kernbild |
| **PO-Kernbild** | ≥2 Stränge + Graph + Gate-Activity-Set + Today | **Voraussetzung** für A1 Go in MVP §4 |
| **Reich** | Alternanz, Templates (Kumite, Mawashi) | Stufe B / Template-APs |
**Konsequenz AP2.1:** A1 bleibt **No-Go** bis Progressions-IA (§6) mindestens für **2 Stränge + 1 Join** durchspielbar — nicht nur Cadence-Plumbing.
---
## 8. Implementierungsfolge (nach Lock, keine Spec-Neuerfindung)
```text
AP-A1-PM-1 Spec-D D3/D6/D8 + A1 §4 (dieses Lock) ✓
AP-A1-PM-2 Persistenz: recurring.project_id; strand_project_id am Gate; gate-activity-set API
AP-A1-PM-3 Horizon multi-active; Join-Resolver (§10); single-active revoke
AP-A1-PM-3b Join-Schalten: alle Ausgänge (MVP)
AP-A1-PM-4 UI: Plan Struktur + Work-Gate-Detail + Join-Knoten
AP-A1-PM-5 Today/Kontrolle: strang-gruppiert; Join-Warteliste
AP-A1-PM-6 Template: 2 Stränge → 1 Join → 2+ Ausgänge
```
Kein ADP für OM-Grundmodell — Erweiterung innerhalb RoadmapItem + Project + Recurring + CadenceInstance.
---
## 9. Offene Feinentscheide ( später )
| # | Thema | Default bis PO anders |
|---|--------|------------------------|
| 1 | Join als `item_type: join_gate` vs. `review_gate` + Flag | `join_gate` (neu, schlank) |
| 2 | Max. aktive Work-Gates pro Strang | 1 |
| 3 | Ranking zwischen Strängen | überfällig > heute > EFS später |
| 4 | Join-Schalten automatisch vs. Bestätigung | automatisch wenn alle Eingänge `reached` |
---
## 10. Join als Schaltknoten (PO-Lock 2026-07-28)
### 10.1 Warum kein Terminalgate
Der Nutzer modelliert **normale Gates** auf Strang-Pfaden und **verbindet** deren letztes relevantes Gate per Kante mit einem **Join**. Ein extra Typ „Terminalgate“ ist **nicht nötig** und würde Graph-Logik sichtbar machen, die die Engine ohnehin aus Kanten ableitet.
### 10.2 Join — Definition
| Eigenschaft | Lock |
|-------------|------|
| **Rolle** | Konsolidierungs- und Schaltpunkt; **trägt den sichtbaren Meilenstein-Status** (z. B. „Mawashi Geri zur Hüfte“) |
| **Activity Set** | **Keins** — keine `RecurringElement`, keine Tagesarbeit am Join |
| **Eingänge** | Work-Gates aus ≥1 Strang (`requires`: Join wartet auf Gate) |
| **Ausgänge** | Work-Gates auf Strang-Pfaden (`requires`: Nachfolger wartet auf Join) |
| **Schaltbedingung (MVP)** | Alle Eingänge `reached` |
| **Effekt (MVP)** | **Alle** Ausgänge schalten → Nachfolge-Gates `active` → deren Activity Sets frei |
| **Horizon / Today** | Join erscheint **nicht** — nur in Kontrolle / Plan-Graph |
### 10.3 Graph-Kanten (bestehende Engine)
Semantik unverändert (`roadmap_engine`):
```text
Eingang: join requires D2 (D2 muss reached sein, bevor Join schaltet)
Eingang: join requires H2
Ausgang: D3 requires join (D3 wird active, wenn Join reached)
Ausgang: G1 requires join
```
Der Join **entscheidet**, auf welche Stränge/Gates noch gewartet wird: UI listet offene Eingänge am Join-Titel — nicht als leere Strang-Strecke.
### 10.4 Stufe B — bedingte Ausgänge (If/Else)
| Stufe | Verhalten |
|-------|-----------|
| **A (MVP)** | Alle Ausgänge feuern gemeinsam |
| **B** | Pro Ausgang optional Bedingung (Kriterium, Metrik, manuelle Wahl); Engine schaltet nur erfüllte Ausgänge |
Technische Andockpunkte vorhanden: `optional_branch`, später Kriterium an Kante — **nicht** Stufe A.
### 10.5 Strang ohne Ausgang nach Join
Hat ein Strang **keinen** Ausgangs-Gate am Join, endet sein Beitrag dort — **ohne** Dummy-Gates. Strang-Project kann `completed` / ruhend; Today bleibt leer für diesen Strang bis ggf. ein späterer Join einen neuen Ausgang öffnet.
---
*Bei Widerspruch zu A1 v0.1 / Spec-D v0.1 ohne PO-Lock-Vermerk gilt **dieses Dokument** für Progressions- und Horizon-Fragen.*
@@ -2,8 +2,8 @@
## Archetyp-Vollspec (implementierbar) v0.1 ## Archetyp-Vollspec (implementierbar) v0.1
**Status:** vorläufig freigegeben (PO 2026-07-26) — Zielbild; Implementierungsausreichendheit noch nicht abschließend bewertet **Status:** vorläufig freigegeben (PO 2026-07-26) — Zielbild; Implementierungsausreichendheit noch nicht abschließend bewertet
**Stand:** 2026-07-26 **Stand:** 2026-07-28 (PO-Lock Progressionsmodell — siehe §14)
**MVP-Stufe:** A **MVP-Stufe:** A (PO-Kernbild: Multi-Strang — §14.4)
**Decision-Lock:** A1 Reifegrad **Decision-Lock:** A1 Reifegrad
**Default-Methode:** [`SPEC_D_maturity_progression_v0.1.md`](../../architecture/methods/SPEC_D_maturity_progression_v0.1.md) **Default-Methode:** [`SPEC_D_maturity_progression_v0.1.md`](../../architecture/methods/SPEC_D_maturity_progression_v0.1.md)
**Methodenkern:** `Kairo_Steering_Method_Kernel_v0.1.md` **Methodenkern:** `Kairo_Steering_Method_Kernel_v0.1.md`
@@ -52,7 +52,10 @@ Kontinuierliche Entwicklung einer Fähigkeit über **Phasen/Stufen**. Eine Phase
6. Innerhalb Mittelstufe Übung hinzufügen (Adaptation), auditiert. 6. Innerhalb Mittelstufe Übung hinzufügen (Adaptation), auditiert.
7. Optional zweites Fähigkeits-Project + Graph-Voraussetzung. 7. Optional zweites Fähigkeits-Project + Graph-Voraussetzung.
**Leitfrage:** Welche Stufe ist aktiv — und welche Übung/Aktivität ist **jetzt** dran (inkl. Alternanz/Zeitversatz)? **Leitfrage:** Welche **Strang-Gates** sind aktiv — und welche Übung ist **jetzt** auf welchem Pfad dran (inkl. Alternanz/Zeitversatz)?
**Referenzbeispiel (PO 2026-07-28) — parallele Progression „Mawashi Geri“:**
Mehrere Stränge (Projects: Dehnung, Hüftrotation, Technik), je Strang Gate-Kette im Graph, Join-Gate („sicher zur Hüfte“), Activity Set pro Gate, nach Join strangspezifischer Set-Wechsel. Vollständig: [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](SPEC_A1_Progression_Model_PO_Lock_v0.1.md) §2.
--- ---
@@ -67,25 +70,28 @@ evidence, decisions, reviews, steering_methods
## 4. Plan- / Ist-Vertrag ## 4. Plan- / Ist-Vertrag
### 4.1 Stufen / Phasen ### 4.1 Stufen / Phasen / Stränge
| Element | Rolle | | Element | Rolle |
|---------|--------| |---------|--------|
| `maturity_stage` (RoadmapItem) | Phase/Stufe; eine **aktive** Stufe (Horizon) | | `maturity_stage` (RoadmapItem) | Gate / Reifegrad-Checkpoint auf einem **Pfad** |
| Kriterien / Evidence | Verify vor `reached` | | **Strang** | `Project` (`project.maturity_journey`) — z. B. Dehnung, Technik, Hüftrotation |
| Graph | Voraussetzungen zwischen Stufen und/oder Fähigkeits-Projects | | Kriterien / Evidence | Verify vor `reached`; inkl. `metric` |
| Project `project.maturity_journey` | Fähigkeit/Spur; eine oder mehrere | | Graph | Parallele Pfade, `requires`-Kanten, **Join-Gates** zwischen Strängen |
| **Horizon (PO-lock)** | **Mehrere** aktive Gates initiative-weit; **pro Strang** höchstens ein aktives Gate auf dem Pfad — siehe [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](SPEC_A1_Progression_Model_PO_Lock_v0.1.md) §3 |
> **Hinweis:** Lineares Demo-Kit (Stufe 1–3, ein Strang) ist **Teilmenge**, nicht das PO-Kernbild.
### 4.2 Aktivitäts-Set einer Phase (verbindlich) ### 4.2 Aktivitäts-Set einer Phase (verbindlich)
| Aktivitätstyp | Persistenz | Rolle | | Aktivitätstyp | Persistenz | Rolle |
|---------------|------------|--------| |---------------|------------|--------|
| Übung / Ritual | `RecurringElement`, gebunden an `maturity_stage` | wiederkehrend | | Übung / Ritual | `RecurringElement`, gebunden an **Gate** (`roadmap_item_id`) **und Strang** (`project_id` bei Multi-Strang) | wiederkehrend |
| Einmal-/Sonderaktivität | `Action`, gebunden an Stufe | Prüfung, Workshop, Nachweis | | Einmal-/Sonderaktivität | `Action`, gebunden an Stufe | Prüfung, Workshop, Nachweis |
- Pro Stufe: **beliebig viele** Aktivitäten; **≥1 reicht**. - Pro **Gate**: beliebig viele Übungen; **≥1** pro aktivem Gate auf einem Strang.
- Pro Recurring: **eine** offene CadenceInstance (kein Duplikat bei Verpassen). - Pro Recurring: **eine** offene CadenceInstance (kein Duplikat bei Verpassen).
- Inaktive Stufen: kein Next, keine neuen Instanzen; Historie bleibt. - Inaktive / nicht-graph-ready Gates: kein Next, keine neuen Instanzen; Historie bleibt.
### 4.3 Zeitversatz und Alternanz (gleiche Phase) ### 4.3 Zeitversatz und Alternanz (gleiche Phase)
@@ -97,29 +103,30 @@ evidence, decisions, reviews, steering_methods
Alternanz-Regeln: Rotation nach Erfüllung; Overdue nur auf aktuelles Mitglied; Gruppe an Stufe gebunden. Alternanz-Regeln: Rotation nach Erfüllung; Overdue nur auf aktuelles Mitglied; Gruppe an Stufe gebunden.
### 4.4 Modifikation bei Stage `reached` ### 4.4 Modifikation bei Gate `reached`
1. Altes Activity Set deaktivieren. 1. Activity Set **dieses Gates** deaktivieren.
2. Nächste Stufe aktiv; neues Set aktiv. 2. **Pro Strang:** nächstes Gate auf dem Pfad `active` (Graph-regelkonform); bei **Join-Gates** nach Verify.
3. Neues Set darf Übungen/Cadences/Alternanz/Actions ersetzen/erweitern/reduzieren. 3. Neues Set **strangspezifisch** — Stränge dürfen divergieren (z. B. Technik ↓, Dehnung ↑).
4. Adaptation innerhalb Stufe (manuell) erlaubt und auditiert. 4. Adaptation innerhalb aktiven Gates (manuell) erlaubt und auditiert.
Erweitert AP2.0e auf ganze Activity Sets.
### 4.5 Datenfelder am Recurring (verbindlich) ### 4.5 Datenfelder am Recurring (verbindlich)
| Feld | Zweck | | Feld | Zweck |
|------|-------| |------|-------|
| Bindung an `maturity_stage` | Stage Activity Set | | `roadmap_item_id` | Gate / Activity Set |
| `project_id` | Strang (Pfad); Pflicht bei Multi-Strang |
| Cadence | Zeitversatz | | Cadence | Zeitversatz |
| `alternation_group_id` + `alternation_order` | Alternanz (leer = keine Gruppe) | | `alternation_group_id` + `alternation_order` | Alternanz (leer = keine Gruppe) |
| status aktiv/inaktiv | Set-Wechsel / Adaptation | | status aktiv/inaktiv | Set-Wechsel / Adaptation |
### 4.6 Anti-Patterns ### 4.6 Anti-Patterns
- Flache Liste „Wiederkehrend“ ohne Gate/Strang-Bezug
- Übungen aller Stufen als flache Action-Liste - Übungen aller Stufen als flache Action-Liste
- Verpasste Übung → Duplikat-Task - Verpasste Übung → Duplikat-Task
- Alternanz ohne Gruppen-Semantik - Alternanz ohne Gruppen-Semantik
- Ein uniformes Initiative-Set nach Join (statt strangspezifisch)
--- ---
@@ -130,7 +137,7 @@ Erweitert AP2.0e auf ganze Activity Sets.
| Aspekt | Kurz | | Aspekt | Kurz |
|--------|------| |--------|------|
| Dominanz | hybrid | | Dominanz | hybrid |
| Horizon | aktive `maturity_stage` | | Horizon | aktive Gates (multi-strang) — PO-Lock §14 |
| Leading | CadenceInstance; sekundär Stage-Action | | Leading | CadenceInstance; sekundär Stage-Action |
| Next / Ranking | Spec-D D6 | | Next / Ranking | Spec-D D6 |
| Attention / Events | Spec-D D7 / D8 | | Attention / Events | Spec-D D7 / D8 |
@@ -175,12 +182,12 @@ Cadence im Detail am RecurringElement.
| Fläche | Inhalt | | Fläche | Inhalt |
|--------|--------| |--------|--------|
| **Plan → Stufen** | Timeline/Liste; aktiv; Kriterien; Verify | | **Plan → Struktur** | Stränge (Projects) + Gate-Graph (parallel, Join) |
| **Plan → Stufe Detail** | Activity Set: Übungen (Cadence, Alternanz), Stage-Actions | | **Plan → Gate-Detail** | Activity Set: Übungen, Strang, Cadence, metric-Kriterien |
| **Plan → Struktur** | Fähigkeits-Projects + Graph | | **Plan → Stufen** | Graph-/Listen-Ansicht aktiver Gates |
| **Plan → Profil** | EFS Fokus/Frequenz/Disziplin | | **Plan → Profil** | EFS Fokus/Frequenz/Disziplin |
| **Ausführen / Today** | fällige Übungen + Alternanz-aktuell + Stage-Actions | | **Ausführen / Today** | fällige Übungen **gruppiert nach Strang/Gate** |
| **Kontrolle** | Stufe, Next + Begründung, Attention, Verify-Fortschritt | | **Kontrolle** | aktive Gates, Join-Status, Kriterien-Fortschritt |
| **Journey** | Stufenwechsel, Set-Modifikationen, erfüllte Übungen | | **Journey** | Stufenwechsel, Set-Modifikationen, erfüllte Übungen |
| **Process** | Stufen → Stufe/Übungen → Ausführen → Kontrolle | | **Process** | Stufen → Stufe/Übungen → Ausführen → Kontrolle |
| **Elements** | `next_action_primary`, `maturity_stage`, `recurring_rhythm` | | **Elements** | `next_action_primary`, `maturity_stage`, `recurring_rhythm` |
@@ -228,15 +235,19 @@ Cadence im Detail am RecurringElement.
## 11. Ist-Stand (Spec vs. Code) ## 11. Ist-Stand (Spec vs. Code)
**PO-Validation 2026-07-28:** Detaillierte Findings + Architektur-Urteil →
`docs/sprints/Sprint1_AP2_1_Validation_Findings_Register_v0.1.md` (F-A1-01…10)
**PO-Produkturteil A1 (2026-07-28):** **No-Go** — Cadence ohne Progressions-IA. **Option C (PO-Lock):** [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](SPEC_A1_Progression_Model_PO_Lock_v0.1.md) — Multi-Strang vor Re-Abnahme.
| Bereich | Spec | Code/Truth | Lücke | | Bereich | Spec | Code/Truth | Lücke |
|---------|------|------------|-------| |---------|------|------------|-------|
| Registry / Kit | A1 + Stufen | weitgehend AP2.0e/Kit | Multi-Übung/Alternanz | | Progressionsmodell | PO-Lock | Gate-Activity-Set: AP + Wochentags-Schedule (Recurring = Cadence-Brücke); Default-Kit weiter linear | Multi-Strang + Join-IA |
| Methode | `maturity_progression` | vorhanden | Ranking Alternanz Spec-D | | Horizon multi-active | PO-Lock §3 | single-active (widerrufen) | AP-A1-PM-3 |
| Stage Activity Set | verbindlich | Teilmenge | Stage-Bindung + UI Detail | | Stage Activity Set | Gate + Strang | Teilmenge | Gate-Detail UI + `project_id` |
| Alternanz-Felder | verbindlich | fehlt/teilweise | Persistenz + Strategy | | Registry / Kit | Demo Spagat | geliefert | reicht nicht für PO-Kernbild |
| EFS Pflicht | focus/frequency | Seeds prüfen | Seed-AP | | UI Plan Struktur/Gate | Pflicht | fehlt | AP-A1-PM-4 |
| steering_elements | D11 | teilweise | FE/BE Parität | | Alternanz / metric | verbindlich | fehlt/teilweise | AP-A1-PM-5+ |
| UI Stufe-Detail | Pflicht | lückenhaft | UI-AP |
--- ---
@@ -249,5 +260,25 @@ Fachmodell vollständig. Lücken (Alternanz, Multi-Übung-UI, EFS-Seeds) = Imple
## 13. Nachfolger ## 13. Nachfolger
- Alternanz-Persistenz + Strategy - Alternanz-Persistenz + Strategy
- UI Stufe-Detail / Activity Set - UI Plan → Struktur + Gate-Detail / Activity Set
- Template Kumite - Template Kumite / Mawashi (Multi-Strang)
---
## 14. PO-Lock Progressionsmodell (2026-07-28, Option C)
**Verbindlich** für Horizon, Stränge, Gate-Activity-Sets und MVP-Abgrenzung:
→ [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](SPEC_A1_Progression_Model_PO_Lock_v0.1.md)
Kurzfassung:
| Thema | Lock |
|-------|------|
| Strang | `Project` — parallele Fähigkeits-Pfade |
| Gate | `maturity_stage` im Graph; Join-Gates mit `requires` |
| Übung | `RecurringElement` = Übung; Rhythmus = Feld; **nicht** losgelöstes Objekt |
| Horizon | **Multi-active** Gates; pro Strang max. 1 aktives Gate auf Pfad |
| MVP A1 Go | ≥2 Stränge + Join + Gate-Activity-Set + Today — nicht nur lineares Spagat-Demo |
Implementierungsfolge: PO-Lock §8 (`AP-A1-PM-1` … `PM-6`).
@@ -0,0 +1,125 @@
# AP2.1 — MVP Validation (Stufe A)
## Auftrag v0.1
**Status:** freigegeben
**Stand:** 2026-07-28
**Bezug:** `Kairo_MVP_Definition_v0.3.md` §5–8, `Kairo_MVP_Execution_Plan_v0.2.md` §7
**Output:** ausgefüllter `Sprint1_AP2_1_MVP_Validation_Report_v0.3.md` + Go/No-Go
---
## 1. Ziel
Kairo ist **MVP-abnahmefähig (Stufe A)**, wenn ein PO **vier Referenz-Szenarien** in der **UI auf Dev** durchspielt und dokumentiert — **ohne** Dogfooding-Seed, **ohne** vorbefüllte Demo-Daten.
**Leitfrage (pro Vorhaben, ≤2 Minuten):**
> Welcher nächste Schritt bringt dieses Vorhaben **jetzt** am wirksamsten voran — und **warum**?
---
## 2. Abnahfe-Umfang (Stufe A)
| ID | Szenario | Archetyp | Methode | Pflicht |
|----|----------|----------|---------|---------|
| **A1** | Spagat können | `initiative.maturity_journey` | `maturity_progression` | ✓ |
| **A2** | Neue Küche | `initiative.linear_project` | `sequential_dependency` | ✓ |
| **B2b** | Product-Betrieb (z. B. Kairo selbst) | `initiative.product` | `continuous_product` | ✓ |
| **B3** | Sprint-Zeitbox auf B2b | Profil `agile_iteration` | `work_cycle` | ✓ minimal |
| D1 | Buch schreiben | Stufe B | — | optional (nicht MVP-Blocker) |
**B3** wird im **selben** Product-Vorhaben wie B2b geprüft (kein eigener Archetyp).
---
## 3. Umgebung
| | |
|---|---|
| **Dev-Instanz** | [https://dev.kairo.jinkendo.de](https://dev.kairo.jinkendo.de) |
| **Health** | `GET /api/health` |
| **Branch** | `develop` (nach letztem Deploy) |
| **CI-Referenz** | Gitea Actions `test.yml` — E2E-Tests als technische Vorprüfung |
**Regeln:**
- Vorhaben **neu in der UI anlegen** (Starter-Kit optional aktivieren)
- **Kein** `seed_004` / Dogfooding als Abnahme-Shortcut
- Screenshots oder Initiative-IDs im Report notieren
---
## 4. Ablauf pro Szenario (~20–30 Min)
1. **Anlegen** — Archetyp wählen, Starter-Kit, Scope setzen
2. **Struktur** — Stufen / Gates / Sprint anlegen (methodenabhängig)
3. **Ist committen** — mindestens 1–2 Arbeitspakete; bei B2b: Backlog → Sprint
4. **Kontrolle** — Lagebild: Methode, Next Action (1–3), Begründung, keine Todo-Wand
5. **Ausführen** — Default-Route (Heute / Sprint) zeigt Steuerung, nicht Gesamtliste
6. **Journey** — min. ein steuerungsrelevantes Event sichtbar
7. **Leitfrage** — PO beantwortet schriftlich in ≤2 Min (Stopuhr)
8. **Anti-Patterns** — explizit prüfen (§7 MVP v0.3)
Detaillierte Schritte: Abschnitt 6 in `Sprint1_AP2_1_MVP_Validation_Report_v0.3.md`.
---
## 5. Go-Kriterien (verbindlich)
### Pro Archetyp (A1, A2, B2b+B3)
| # | Kriterium (MVP v0.3 §5) | Go |
|---|------------------------|-----|
| 1 | Anlage + Default-Methode + Profil | ☐ |
| 2 | Passende Struktur modellierbar | ☐ |
| 3 | Ist committet (nicht alles gleichzeitig sichtbar) | ☐ |
| 4 | Kontrolle: Next Action **begründet** | ☐ |
| 5 | Journey nachvollziehbar (≥1 Event) | ☐ |
| 6 | Leitfrage ≤2 Min **ohne CRUD-Wand** | ☐ |
### Portfolio
| # | Kriterium | Go |
|---|-----------|-----|
| 7 | Cockpit: Attention pro Vorhaben, nicht Task-Details | ☐ |
### Gesamt-Go
- **Go Stufe A:** alle Pflicht-Szenarien (A1, A2, B2b+B3) + Kriterium 7 = ja
- **Bedingt:** ≤1 Szenario mit dokumentierter Lücke + Workaround + Fix-AP
- **No-Go:** Leitfrage nicht beantwortbar oder Todo-Explosion als Hauptbild
---
## 6. Technische Vorprüfung (Agent/CI — kein PO-Ersatz)
| Paket | Test-Datei | Szenario |
|-------|------------|----------|
| AP2.2a | `test_ap22a_starter_kit.py` | Kits A1, A2, B2b |
| AP2.2b | `test_ap22b_linear_e2e.py` | A2 Küche Happy Path |
| AP2.2c | `test_ap22c_maturity_e2e.py` | A1 Spagat + Stufenwechsel |
| AP2.2d | `test_ap22d_sprint_backlog.py` | B2b Backlog → Sprint |
Grüne CI-Tests sind **notwendig**, aber **nicht hinreichend** für AP2.1 Go.
---
## 7. Deliverables
| Artefakt | Pfad |
|----------|------|
| Report (ausfüllen) | `docs/sprints/Sprint1_AP2_1_MVP_Validation_Report_v0.3.md` |
| Truth Table | `AP2.1` Zeile nach Go aktualisieren |
| Execution Plan | Phase 5 als ✓ markieren |
---
## 8. Nach Go
- Merge `develop` → `main` (Prod-Deploy) erst nach **PO Go Stufe A**
- Template/Blueprint-Konzeption (AP-BP-0) parallel, nicht MVP-Blocker
- Stufe B (A3, B1, D1) erst nach AP2.1 Go planen
---
*Vorlage Report: `Sprint1_AP2_1_MVP_Validation_Report_v0.3.md`*
@@ -0,0 +1,334 @@
# AP2.1 — MVP Validation Report
## v0.3 (Stufe A)
**Status:** Entwurf — Re-Abnahme A1 Progression ausstehend (2026-08-02)
**Stand:** 2026-08-02 (§3.5 Progressions-Re-Abnahme ergänzt)
**Bezug:** `Kairo_MVP_Definition_v0.3.md` §5–8
**Assignment:** `Sprint1_AP2_1_MVP_Validation_Assignment_v0.1.md`
**Findings (Architektur-Review):** `Sprint1_AP2_1_Validation_Findings_Register_v0.1.md`
| Feld | Wert |
|------|------|
| **Kairo-Version / Deploy** | `0.20.2-ap2.2d` (schema 025) |
| **Dev-URL** | https://dev.kairo.jinkendo.de |
| **Branch / Commit** | `develop` @ `0baa595` |
| **Tester (PO)** | Lars |
| **Testdatum** | 2026-07-28 |
---
## 1. Executive Summary
| Entscheidung | ☐ Go Stufe A · ☐ Bedingt · ☑ No-Go (A1 bis Progressions-IA; Option C PO-Lock) |
|--------------|-------------------------------------|
**Kurzfazit (3–5 Sätze):**
Technisch: pytest grün, A1-Happy-Path (Anlage → Verify → Stufenwechsel) durchspielbar.
Produkt (PO): **A1 No-Go** — Cadence-Plumbing reicht nicht; Nutzerbild = **parallele Stränge + Gate-Graph + Activity Sets**, nicht flache „Wiederkehrend“-Liste. **PO-Entscheid Option C:** Spec schärfen → [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md). A2/B2b noch offen.
**Blocker (falls No-Go / Bedingt):**
- **A1:** Progressions-IA gemäß PO-Lock §6–8 (`AP-A1-PM-2` … `PM-6`) — Multi-Strang, Gate-Activity-Set, Plan-UI, Today gruppiert
- **Gesamt Stufe A:** MVP §4 verlangt A1 — Go erst nach PO-Kernbild (≥2 Stränge + Join) durchspielbar
---
## 2. Portfolio (Kriterium 7)
**Leitfrage Portfolio:** *Welches Vorhaben braucht jetzt welche Art von Attention?*
| Check | ja/nein | Notiz |
|-------|---------|-------|
| Cockpit zeigt Vorhaben mit Attention-Signal (nicht Task-Listen) | | |
| Unterschiedliche Vorhabenarten parallel erkennbar | | |
| Drill-down zu Details nur bewusst | | |
| Leitfrage Portfolio ≤2 Min | | |
---
## 3. Szenario A1 — Spagat können (Reifegrad)
**Initiative-ID / Titel:** Spagat können (PO-Smoke 2026-07-28)
**Archetyp:** `initiative.maturity_journey` · **Methode:** `maturity_progression`
**Zwischenurteil:** ☐ Go · ☐ Bedingt · ☑ **No-Go (Produkt)** — [Findings Register](Sprint1_AP2_1_Validation_Findings_Register_v0.1.md) F-A1-01…10
### 3.0 PO-Feedback (2026-07-28)
| Thema | Urteil |
|-------|--------|
| Anlage + Starter-Kit | ✓ technisch |
| Kontrolle (Stufe, Next Action) | ✗ kein Tages-/Gate-Fortschrittsbild |
| Ausführen (Anti-Todo-Wand) | ✗ Übung nicht ausführbar; AP-Verwirrung |
| Verify + Stufenwechsel | ✓ technisch; PO: kein Ersatz für laufendes Tracking |
| Journey / Rhythmen | ✗ unübersichtlich |
| Leitfrage ≤2 Min | **✗** — nicht sinnvoll beantwortbar |
**PO-Zitat (Kern):** *Für tagesbezogenes Tracking, Messmethoden und aktive Gate-Einschätzung unbrauchbar; Hürden größer als Nutzen.*
### 3.1 Smoke-Schritte (Dev)
| # | Schritt | Route | erledigt |
|---|---------|-------|----------|
| 1 | Vorhaben „Spagat können“ anlegen, Starter-Kit | Vorhaben → Neu | ☐ |
| 2 | Operating Context: `maturity_stage`, `recurring_rhythm` | API oder Kontrolle | ☐ |
| 3 | Kontrolle: Stufen-Panel + Rhythmen + Next Action | `/control/status` | ☐ |
| 4 | Ausführen: Next Action sichtbar, Liste eingeklappt | `/work/today` | ☐ |
| 5 | Evidence an Stufe 1, Verify → Stufe 2 aktiv | Plan → Stufen / Journey | ☐ |
| 6 | Recurring rotiert (alte Übung pausiert, neue aktiv) | Kontrolle / Rhythmen | ☐ |
| 7 | Journey zeigt Stufen-Event | `/control/journey` | ☐ |
**Technische Referenz:** `backend/tests/test_ap22c_maturity_e2e.py`
### 3.2 MVP-Nutzbarkeits-Bar (§5)
| # | Kriterium | ja/nein | Notiz |
|---|-----------|---------|-------|
| 1 | Anlage + Default-Methode | | |
| 2 | Stufen + Recurring strukturiert | | |
| 3 | Ist committet (Übung/Routine, nicht 200 Tasks) | | |
| 4 | Kontrolle: Next Action begründet (Rhythmus/Stufe) | | |
| 5 | Journey ≥1 Event | | |
| 6 | Leitfrage ≤2 Min ohne Listen-Wand | | |
### 3.3 Leitfrage-Antwort (PO, ≤2 Min)
**Nächster Schritt:** *Nicht sinnvoll bestimmbar* — kein klarer Tages-Handlungspfad (Übung erledigen + Fortschritt sehen).
**Warum:** Ausführen zeigt AP statt Übung; kein Tracking; Gate-Fortschritt nicht steuerbar; UI unübersichtlich.
**Stopuhr:** >2 Min / abgebrochen — **MVP §5.6 nicht erfüllt**
### 3.4 Anti-Patterns (§7)
| Verboten | aufgetreten? | Notiz |
|----------|--------------|-------|
| Flache Liste aller Übungs-Tasks als Hauptbild | ☐ ja ☐ nein | |
| Recurring im Action-Backlog statt Rhythmus-Ansicht | ☐ ja ☐ nein | |
**Lücken / UX-Schmerz:** PO No-Go — Register F-A1-02…10; Minimum Slice §6.1 vor Re-Test. Kein Architektur-Neudesign — fehlender A1-Kern (CadenceInstance, Today=Übung, Gate-Fortschritt, IA).
### 3.5 Re-Abnahme A1 — Progressionsmodell (PO-Lock, ohne Starter-Kit)
**Zweck:** PO-Kernbild prüfen gemäß [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md) §7 — **≥2 parallele Gates + 1 Join + Activity Sets + Today**, manuell modelliert (kein Spagat-Starter-Kit). Horizon/Lanes: [`ADP_A1_Progression_Graph_Derived_Lanes_v0.1.md`](../architecture/ADP_A1_Progression_Graph_Derived_Lanes_v0.1.md).
**Vorbedingungen**
| # | Check | erledigt |
|---|--------|----------|
| V1 | Deploy `develop` grün (pytest inkl. `test_a1_progression_join.py`) | ☐ |
| V2 | Health: `GET https://dev.kairo.jinkendo.de/api/health` | ☐ |
| V3 | PO-Entscheid: **kein Starter-Kit** — Anlage mit `"apply_starter_kit": false` (API) oder Spagat-Stufen nach Anlage löschen | ☐ |
**Referenz-Graph (MVP, 2 parallele Pfade — reicht für Go):**
```text
[Dehnung — Einstieg] ──requires──▶ [Join: Mawashi …] ◀──requires── [Hüftrotation — Einstieg]
│
┌───────────────────┴───────────────────┐
▼ ▼
[Dehnung — nach Join] [Hüftrotation — nach Join]
```
Alle Kanten: **Voraussetzung** (`requires`). Kein Parallelgruppe/Blockiert nötig. **Keine** Stream-Projects / `strand_project_id` nötig — parallele Pfade ergeben sich aus dem Graph.
---
**9 Smoke-Schritte**
| # | Schritt | Route / Aktion | Erwartung | ✓/✗ | Notiz |
|---|---------|----------------|-----------|-----|-------|
| **1** | Vorhaben anlegen | API `POST /api/initiatives` mit `archetype_key: initiative.maturity_journey`, **`apply_starter_kit: false`** | Archetyp A1, Methode `maturity_progression`, **keine** Spagat-Stufen | | |
| **2** | Operating Context | `GET …/initiatives/{id}/operating-context` oder Kontrolle | `maturity_stage`, `recurring_rhythm`; Default-Route Kontrolle | | |
| **3** | Gates + Join im Designer | Plan → Zielzustände → **Designer** | 5 Knoten: 4× `Reifegrad-Stufe` + 1× **Join/Schaltknoten**; D1+H1 **active**, Rest **planned** | | |
| **4** | Kanten ziehen | Designer, Kantentyp **Voraussetzung** | Join→D1, Join→H1, D2→Join, H2→Join (4 Kanten) | | |
| **5** | Activity Sets | Gate-Detail (Designer → Gate öffnen): **Übung anlegen** mit Rhythmus | Je aktivem Work-Gate ≥1 Übung; Join **ohne** Übungen | | |
| **6** | Today (Start) | `/work/today` (Initiative-Scope) | Übungen von **beiden** aktiven Gates; **keine** flache AP-Wand; Join **nicht** in Today | | |
| **7** | Verify Pfad 1 | Gate D1: Evidence + **Verify** | D1 `reached`; Join wartet auf H1; **kein** auto-next auf D2; Today nur noch H1-Übungen | | |
| **8** | Join schaltet | Gate H1: Evidence + **Verify** | Join `reached` (automatisch); D2 + H2 **active**; neue Übungen in Today | | |
| **9** | Leitfrage + Kontrolle | Kontrolle `/control/status` + Stopuhr | Join-Warteliste zeigte offene Eingänge (Schritt 7); Leitfrage in **≤2 Min** beantwortbar: *Welche Übung heute, welcher Join wartet?* | | |
**Technische Referenz (Automatisierung):** `backend/tests/test_a1_progression_join.py`
---
**Go-Kriterien A1 Progression (alle nötig für Go)**
| # | Kriterium | ja/nein | Notiz |
|---|-----------|---------|-------|
| G1 | Multi-Gate: 2 aktive Work-Gates parallel (Schritt 6) | | |
| G2 | Join: Warteliste/Kontrolle zeigt pending inputs (Schritt 7) | | |
| G3 | Join schaltet Ausgänge gemeinsam (Schritt 8) | | |
| G4 | Today = Übungen am Gate, nicht AP-Liste (Schritt 6, 9) | | |
| G5 | Leitfrage ≤2 Min (Schritt 9) | | |
| G6 | Kein Anti-Pattern: flache Rhythmus-Liste als Hauptbild | | |
**Zwischenurteil Re-Abnahme:** ☐ Go · ☐ Bedingt · ☐ No-Go
| Feld | Wert |
|------|------|
| **Initiative-ID / Titel** | |
| **Deploy / Commit** | `develop` @ |
| **Testdatum Re-Abnahme** | |
**Leitfrage-Antwort (PO, ≤2 Min):**
**Nächster Schritt:**
**Warum:**
**Stopuhr (Min):**
**Bei Go:** §3 Zwischenurteil auf Go setzen; Findings Register F-A1-02…10 einzeln abhaken; Truth Table MVP-Abnahfe A1 aktualisieren.
**Bei No-Go:** neue Finding-IDs im Register; keine Stufe-A-Sign-off.
---
## 4. Szenario A2 — Neue Küche (Linear)
**Initiative-ID / Titel:**
**Archetyp:** `initiative.linear_project` · **Methode:** `sequential_dependency`
### 4.1 Smoke-Schritte (Dev)
| # | Schritt | Route | erledigt |
|---|---------|-------|----------|
| 1 | Vorhaben „Neue Küche“ anlegen, Starter-Kit | Vorhaben → Neu | ☐ |
| 2 | Gate-Kette G1–G4, G1 aktiv | Plan → Zielzustände | ☐ |
| 3 | Projekte Hauptpfad + Begleitung vorhanden | Plan | ☐ |
| 4 | Kontrolle: Kritischer Pfad + Next Action | `/control/status` | ☐ |
| 5 | Ersten Schritt erledigen → nächster ready am Pfad | Ausführen / AP-Detail | ☐ |
| 6 | Gate-Verify / reached wo sinnvoll | Plan / Gates | ☐ |
| 7 | Ausführen: Steuerung, nicht alle Handwerker-Tasks | `/work/today` | ☐ |
**Technische Referenz:** `backend/tests/test_ap22b_linear_e2e.py`
### 4.2 MVP-Nutzbarkeits-Bar (§5)
| # | Kriterium | ja/nein | Notiz |
|---|-----------|---------|-------|
| 1 | Anlage + sequential_dependency | | |
| 2 | Gate-Kette + Abhängigkeiten | | |
| 3 | APs committet, nicht Backlog-Wand | | |
| 4 | Kontrolle: kritischer Pfad / ready Schritt begründet | | |
| 5 | Journey / Gate-Fortschritt sichtbar | | |
| 6 | Leitfrage ≤2 Min | | |
### 4.3 Leitfrage-Antwort (PO)
**Nächster Schritt:**
**Warum:**
**Stopuhr (Min):**
### 4.4 Anti-Patterns
| Verboten | aufgetreten? | Notiz |
|----------|--------------|-------|
| Alle Handwerker-Schritte als flache Todo-Liste | ☐ ja ☐ nein | |
| Gate nur Status-Dropdown ohne Steuerung | ☐ ja ☐ nein | |
**Lücken:**
---
## 5. Szenario B2b + B3 — Product + Sprint
**Initiative-ID / Titel:**
**Archetyp:** `initiative.product` · **Methode:** `continuous_product` (+ optional `agile_iteration`)
### 5.1 Smoke-Schritte B2b (Dev)
| # | Schritt | Route | erledigt |
|---|---------|-------|----------|
| 1 | Product-Vorhaben anlegen (Starter-Kit) | Vorhaben → Neu | ☐ |
| 2 | Eingang: Backlog-Item anlegen / triagieren | Plan → Eingang | ☐ |
| 3 | Gate/Meilenstein als Orientierung | Plan → Zielzustände | ☐ |
| 4 | Kontrolle: Next Action (Product-Horizont) | `/control/status` | ☐ |
| 5 | Prozessleiste: Eingang → Sprint planen → Ausführen | Scope-Navigation | ☐ |
### 5.2 Smoke-Schritte B3 (Sprint minimal)
| # | Schritt | Route | erledigt |
|---|---------|-------|----------|
| 6 | Sprint anlegen (geplant oder aktiv) | Plan → Sprint | ☐ |
| 7 | Backlog-Items in gewählten Sprint committen | Plan → Sprint (Checkbox / Vorschlag) | ☐ |
| 8 | Sprint-Backlog sichtbar getrennt vom Product Backlog | Plan → Sprint / Ausführen → Sprint | ☐ |
| 9 | Ausführen: Next Action im Sprint, Liste Drill-down | `/work/sprint` | ☐ |
| 10 | Optional: Sprint abschließen / Carryover | Sprint-Panel | ☐ |
**Technische Referenz:** `backend/tests/test_ap22d_sprint_backlog.py`, `test_ap22i_sprint_commit_proposal.py`
### 5.3 MVP-Nutzbarkeits-Bar (§5)
| # | Kriterium | ja/nein | Notiz |
|---|-----------|---------|-------|
| 1 | Anlage + continuous_product | | |
| 2 | Eingang + Gates + Sprint-Struktur | | |
| 3 | Product Backlog ≠ Sprint-Backlog ≠ committete APs | | |
| 4 | Kontrolle: Next Action Gate **oder** Sprint begründet | | |
| 5 | Journey / Sprint-Lifecycle Event | | |
| 6 | Leitfrage ≤2 Min | | |
### 5.4 Leitfrage-Antwort (PO)
**Nächster Schritt:**
**Warum:**
**Stopuhr (Min):**
### 5.5 Anti-Patterns
| Verboten | aufgetreten? | Notiz |
|----------|--------------|-------|
| Alle APs aller Gates gleichzeitig in Hauptliste | ☐ ja ☐ nein | |
| Sprint-Backlog = Product Backlog | ☐ ja ☐ nein | |
| Ausführen zeigt Gesamtliste statt Sprint-Default | ☐ ja ☐ nein | |
| Begriff „Zeitbox“ statt Sprint in UI | ☐ ja ☐ nein | |
**Lücken:**
---
## 6. Querschnitt — Composition & Product Language
| Check | ja/nein | Notiz |
|-------|---------|-------|
| MethodProcessBar zeigt Prozess (Product: Eingang→Sprint→Ausführen) | | |
| Work-Modus: Next Action vor voller AP-Liste | | |
| Begriffe konsistent (Sprint, Arbeitspaket, Eingang) | | |
| Keine Archetyp-Ifs spürbar (Steuerung methodengebunden) | | |
---
## 7. Op-API (AP1.7b — Stichprobe)
Optional: Agent/Service-Token gegen Dev.
| Endpoint | funktioniert | Notiz |
|----------|--------------|-------|
| `GET /api/operational/initiatives/{id}/context` | ☐ | |
| `GET /api/operational/next-action?initiative_id=` | ☐ | |
| `POST /api/operational/backlog/{id}/convert-to-action` | ☐ | |
---
## 8. Abgeleitete Prioritäten (nach Validation)
| Prio | Lücke | Fix-AP / Slice |
|------|-------|----------------|
| P0 | | |
| P1 | | |
| P2 | | |
---
## 9. Sign-off
| Rolle | Name | Datum | Go Stufe A |
|-------|------|-------|------------|
| Product Owner | | | ☐ ja ☐ nein ☐ bedingt |
**Bedingungen (falls bedingt):**
---
*Bei Go: Truth Table `AP2.1` → ✓, Execution Plan Phase 5 → ✓, dann Merge `develop` → `main` für Prod.*
@@ -0,0 +1,238 @@
# AP2.1 — Validation Findings Register
## v0.1 (PO-Smoke → Architektur-Review)
**Status:** aktiv — wird während AP2.1 ergänzt
**Stand:** 2026-07-28 (A1 Minimum Slice implementiert — PO Re-Abnahme ausstehend)
**Bezug:** `Sprint1_AP2_1_MVP_Validation_Report_v0.3.md`, `Kairo_MVP_Definition_v0.3.md` §5–8
**Dev:** https://dev.kairo.jinkendo.de · nach Deploy Migration **030** + A1-Slice
---
## 1. Zweck
Dieses Register hält **PO-Beobachtungen aus der MVP-Validation** fest und ordnet sie architektonisch ein:
| Kategorie | Bedeutung |
|-----------|-----------|
| **Bug** | Abweichung vom **aktuellen** Soll (Spec + gelieferte Architektur) — Fix ohne ADP |
| **Config-Drift** | Inkonsistenz innerhalb der Plugin-/Profile-Schicht (kein Modellbruch) |
| **Implementierungsschuld** | Architektur und Spec stimmen; Code liefert Teilmenge |
| **Aufgeschoben (Spec)** | Explizit in Archetyp-/Methoden-Spec oder ADP als „später“ / Stufe B+ |
| **Architektur-Lücke** | Zielmodell dokumentiert, tragfähige Basis fehlt oder widerspricht sich **über** Spec hinaus |
**Leitfrage des Reviews:** Brauchen wir ein **neues Architektur-Design**, oder ist die Plugin-/Kernel-Schicht korrekt und es fehlen **Slices**?
---
## 2. Architektur-Urteil (Stand nach A1-Smoke)
### 2.1 Kurzfazit (technisch)
**Kein generelles Architektur-Design-Problem.** Die vier Schichten (Methode → Archetyp → Profil → UI-Composition, AP2.3/AP2.4) tragen den A1-Happy-Path **technisch**.
### 2.1b PO-Produkturteil A1 (2026-07-28)
**No-Go für echten Einsatz** — unabhängig vom grünen E2E-Test.
> Leitfrage lässt sich nicht sinnvoll beantworten. Für tagesbezogenes Tracking (durchgeführt; optional Messwerte wie Anzahl, 45°-Spagat), aktive Einschätzung des Gate-Fortschritts und übersichtliche Steuerung ist der Vorhabentyp **unbrauchbar**. Hürden > Nutzen.
| Dimension | Technische Validation | PO-Produktnutzen |
|-----------|----------------------|------------------|
| Happy Path (Anlage → Verify) | ✓ | ◐ — nur Demo, kein Alltag |
| Leitfrage ≤2 Min (MVP §5.6) | — | **✗** |
| Tages-Tracking / Übung erledigen | ✗ | **Blocker** |
| Messgrößen / Metriken | ✗ | **Blocker** (PO) |
| Gate-Fortschritt sichtbar steuerbar | ◐ | **✗** |
| Übersichtlichkeit | ◐ | **✗** |
**Architektur-Einordnung:** PO-Anforderungen stehen **bereits in SPEC A1 / Spec-D** (CadenceInstance, Tages-Übung, Kriterien, Metriken). Es fehlt nicht ein neues Design — es fehlt der **Minimal-Slice für nutzbaren A1**, der fälschlich als „post-MVP“ behandelt wurde.
**Konsequenz AP2.1 / MVP Stufe A:** A1 erfüllt **nicht** die MVP-Nutzbarkeits-Bar §5 für PO-Abnahme. Gesamt-Go Stufe A **blockiert**, solange A1 Pflicht-Szenario bleibt (`Kairo_MVP_Definition_v0.3.md` §4).
Die Validation zeigt drei **Lückentypen**:
```text
(1) Config-Drift planOutlineKeys ≠ dataSlices → schneller Fix
(2) Spec-Deferred CadenceInstance, Alternanz, metric → geplant, Spec §11
(3) Polymorphie-Gap Kernel Q2 Work-Items: BE ja, FE nein → Implementierungsschuld
```
### 2.2 Referenz-Architektur (Prüfmaßstab)
| Dokument | Rolle |
|----------|--------|
| `ADP_Archetype_Method_Plugin_Architecture_v0.1.md` | Route Gating, Slices, kein Page-If |
| `SPEC_A1_maturity_journey_v0.1.md` §4, §8, §11 | A1-Fachmodell + Ist-Stand-Tabelle |
| `methods/SPEC_D_maturity_progression_v0.1.md` D4–D6 | Leading = CadenceInstance; Ranking |
| `ADP_Roadmap_Graph_and_Gate_Checklist_v0.1.md` | Kriterien, Evidence, `metric` später |
| `Kairo_Steering_Method_Kernel_v0.1.md` Q2 | Work-Item-Polymorphie |
| `Kairo_Steering_Method_Normalization_Program_v0.1.md` | CadenceInstance als Normalform |
### 2.3 Was **nicht** neu designt werden muss
- Archetyp ↔ Methode ↔ UI-Profil (Operating Context)
- Gate-Verify + Kriterien-Checkliste (AP1.4b)
- Stufenwechsel + Recurring-Rotation (AP2.0e)
- Composition-Slots (`maturity_stage`, `recurring_rhythm`, `work.today`)
---
## 3. Findings — Szenario A1 (Spagat / Reifegrad)
**PO-Validation:** 2026-07-28 · Vorhaben „Spagat können“ · `initiative.maturity_journey`
**Urteil A1:** **No-Go (Produkt)** · technischer Kernpfad ✓ · MVP §5 für PO **✗**
| ID | PO-Beobachtung | Kategorie | Architektur-Urteil | MVP Stufe A | Follow-up |
|----|----------------|-----------|-------------------|-------------|-----------|
| **F-A1-01** | Klick **Plan → Eingang** leitet auf **Zielzustände** um | **Config-Drift** | `planOutlineKeys` enthält `inbox`, `dataSlices` ohne `backlog` → Route Gating korrekt, Nav falsch. **Kein Modellproblem.** Spec A1 §8: Eingang „nicht dominant“. | Mitverantwortlich Unübersicht | **Fix:** `inbox` aus `planOutlineKeys` bei `initiative.maturity_journey` |
| **F-A1-02** | Keine Konfiguration **Wochentage / Rhythmus**; kein **Tages-Tracking** („heute erledigt“) | **Implementierungsschuld** (Spec-Pflicht) | Spec A1 §4.3–4.5 + Spec-D D4: `CadenceInstance`. Code: nur `RecurringElement` + Fälligkeit. **Kein Designbruch — fehlender Kern-Slice.** | **PO-Blocker** | **AP A1-Cadence-MVP:** Instanz + „heute erledigt“ |
| **F-A1-03** | **Ausführen:** AP statt Übung; Rhythmus-Link tot; AP nicht öffenbar | **Implementierungsschuld** | Kernel Q2: Leading = CadenceInstance; FE verlinkt nur Actions. | **PO-Blocker** | **AP A1-Work-UI** |
| **F-A1-04** | Kriterien auto-erfüllt via Evidence; keine laufende Gate-Einschätzung | **By Design** + **Lücke UX** | AP1.4b korrekt für Verify-Moment; PO braucht **Fortschrittsbild** während Stufe (Spec A1 §8 Kontrolle). | **PO-Blocker** (Einschätzung) | Fortschritts-Panel + manuelle/metric Kriterien |
| **F-A1-05** | Keine Messung (4×/Woche, 80 Punkte, 45° Spagat, …) | **Implementierungsschuld** (Spec vorbereitet) | `criterion_kind: metric` + Cadence-Erfüllung geplant; keine Engine. Schema reicht — **Feature fehlt, kein ADP neu.** | **PO-Blocker** | Messwert am Tagesabschluss + optional metric-Kriterium |
| **F-A1-06** | Keine **kontinuierliche** Fortschrittskontrolle in der Stufe | **Implementierungsschuld** | Plan/Ist-Trennung korrekt; Ist-Tracking für Übungen fehlt (CadenceInstance). | **PO-Blocker** | Teil A1-Cadence-MVP |
| **F-A1-07** | Nach Verify keine AP-Aktivierung; nur Recurring rotiert | **Implementierungsschuld** | Spec A1 §4.4 Activity Set — Scope AP2.0e minimal. | Sekundär vs. F-A1-02–06 | AP A1-Activity-Set |
| **F-A1-08** | Journey unklar; pausierte Übung verwirrend | **IA** | Technisch korrekt (AP2.0e); PO wahrgenommene Unübersicht. | Mitverantwortlich | IA A1 Today-first |
| **F-A1-09** | **Leitfrage** nicht beantwortbar — Hürden > Nutzen | **PO-Produkturteil** | MVP §5.6 nicht erfüllt. Symptom von F-A1-02…05, nicht Doku-Problem. | **No-Go** | siehe §8 Minimum-Slice |
| **F-A1-10** | **Extreme Unübersichtlichkeit** (Eingang-Redirect, AP vs. Übung, Journey vs. Rhythmen) | **IA + Implementierungsschuld** | Plugin-Architektur OK; **A1-Profil und Work-Default** spiegeln Nutzerbild Spec §8 nicht. Kein neues OM nötig — **falsche/fehlende UI-Hülle**. | **PO-Blocker** | A1-IA-Slice (Eingang weg, Today=Übung, klare Stufenleiste) |
---
## 4. Detail-Notizen (Architektur-Check)
### F-A1-01 — Eingang vs. Slices
```text
ui_profiles.py initiative.maturity_journey:
planOutlineKeys: [profile, gates, inbox, work] ← Nav zeigt Eingang
dataSlices: [actions, roadmap, recurring, …] ← kein "backlog"
viewRegistry.js /plan/inbox requiredSlices: ['backlog']
→ isRouteAllowedForMode = false → Redirect planDefaultRoute (/plan/gates)
```
**Urteil:** Plugin-Architektur funktioniert wie designed; **Profil-Seed ist inkonsistent**.
### F-A1-02 / F-A1-06 — CadenceInstance-Schicht
| Schicht | Spec | Code heute |
|---------|------|------------|
| RecurringElement | Container + Bindung Stufe | ✓ |
| Cadence / Wochentage / Alternanz | Spec A1 §4.3–4.5 | ✗ |
| CadenceInstance (eine offene Instanz) | Spec-D D4, Kernel Q2 | ✗ (nur `next_due_at` am Element) |
| Erfüllung → nächste Instanz | Spec A1 Happy Path §9.3 | ◐ (manuell / overdue-Logik minimal) |
**Urteil:** **Kein falsches Design** — Normalization-Programm beschreibt Ziel; MVP lieferte **Minimal-Rhythmus**. Spec A1 §11 listet das explizit als Lücke.
### F-A1-03 — Work-Item-Polymorphie (Kernel Q2)
| Work Item | Next Action BE | Next Action FE Link |
|-----------|----------------|---------------------|
| Action | ✓ | ✓ |
| Backlog | ✓ | ✓ |
| Recurring / Cadence | ✓ (`recurring_due`) | ✗ (nur Text `recommended_action`) |
**Urteil:** **Architektur-Lücke nur in der Präsentationsschicht** — Steering-Kernel und Strategies sind erweiterbar; FE muss polymorphe Ziele unterstützen (Link-Typ-Registry analog Backend `kind`).
### F-A1-04 / F-A1-05 — Kriterien & Metriken
- **Evidence → satisfied:** beabsichtigt (`roadmap_criteria.prepare_criteria_for_verify`).
- **Manuelle Kriterien:** bleiben offen bis manuell / waived — korrekt.
- **Metriken:** Schema vorbereitet, **keine** Regel-Engine — ADP „später“.
**Urteil:** Gate-Modell ist **generisch genug**; fehlende Metrik-Auswertung ist **Feature-Deferral**, kein Redesign.
### F-A1-07 — Activity Set bei Stufenwechsel
`maturity_stage_transition.on_maturity_stage_reached`:
- pausiert aktive Recurring ✓
- aktiviert nächste Stufe ✓
- legt neue Recurring-Übung an ✓
- **keine** Stage-Actions, **keine** Graph-Aktivierung weiterer Plan-APs
Spec A1 §4.4 verlangt volles Set — **Implementierungsschuld**, Scope AP2.0e war Minimal-Slice.
---
## 5. Abgleich mit SPEC_A1 §11 (Ist-Stand-Tabelle)
| Spec §11 Zeile | Validation bestätigt |
|----------------|-------------------|
| Multi-Übung / Alternanz fehlt | F-A1-02 ✓ |
| Stage Activity Set Teilmenge | F-A1-07 ✓ |
| UI Stufe-Detail lückenhaft | F-A1-02, F-A1-03 ✓ |
| steering_elements FE/BE Parität | F-A1-03 (recurring in Kontrolle ✓, Work ◐) |
**Keine neue Spec-Zeile nötig** — Register präzisiert PO-Sicht für AP2.1.
**Urteil:** **Kein falsches Design** — PO-Anforderung = Spec §4 / Spec-D. MVP lieferte **Infrastruktur ohne Ist-Schicht**. Für PO-Abnahme ist das **kein „später“**, sondern **fehlender A1-Kern**.
### F-A1-09 / F-A1-10 — PO-Leitfrage & Unübersichtlichkeit
**PO (2026-07-28, wörtlich zusammengefasst):**
- Leitfrage nicht sinnvoll beantwortbar
- Tages-Tracking + optional Messwerte (Anzahl, Grad, …) + aktive Gate-Einschätzung **erforderlich** für echten Einsatz
- Extreme Unübersichtlichkeit → **Hürden größer als Nutzen**
**Architektur:** Symptome von fehlendem CadenceInstance-Modell, Work-UI auf AP statt Übung, IA-Rauschen (Eingang, Journey). **Kein Widerspruch** zwischen Vision und Spec — **Widerspruch zwischen geliefertem MVP-Slice und PO-Mindestnutzen**.
---
## 6. Priorisierte Follow-ups (PO-gesteuert)
### 6.1 A1 Minimum Usability Slice (vor erneuter A1-Abnahme)
**Implementiert (2026-07-28, uncommitted):** Migration 030, `cadence_instance` + `POST /api/recurring/{id}/complete`, `WorkTodayPracticePanel`, Next-Action-Link `#today-practice`, Gate-Fortschritt in `MaturityStagePanel`, Eingang aus A1-Nav. **Offen:** PO Re-Abnahme; Metric-Kriterium manuell (Slice #5, optional vor Re-Test).
| # | Lieferung | Decke PO-Schmerz | Status |
|---|-----------|------------------|--------|
| 1 | **CadenceInstance + „Heute erledigt“** | Tages-Tracking | ✓ implementiert |
| 2 | **Ausführen/Today = Übung** | Nutzen Alltag | ✓ implementiert |
| 3 | **Kontrolle: Gate-Fortschritt** | Gate-Einschätzung | ✓ implementiert (Kriterien offen/erfüllt) |
| 4 | **IA A1** (Eingang weg) | Unübersichtlichkeit | ✓ implementiert |
| 5 | **Metric-Kriterium manuell** | Messgrößen | ◐ Messnotiz am Complete; Auto-Engine weiter offen |
Alternanz, volle Metric-Engine, Activity-Set-Automation → **nach** Slice 1–4.
### 6.2 Technische Quick-Wins (P0)
| Prio | ID | Slice |
|------|-----|-------|
| P0 | F-A1-01 | Eingang aus A1-Nav |
| P1 | F-A1-03 | Next Action → Recurring/Übung-Aktion |
---
## 7. Konsequenz für AP2.1 / MVP Stufe A
| Option | Bedeutung | PO 2026-07-28 |
|--------|-----------|---------------|
| **A — A1 nachziehen** | Minimum Slice liefern | ◐ Cadence done; Progressions-IA offen |
| **B — MVP-Definition anpassen** | A1 aus Stufe-A-Abnahfe | nicht gewählt |
| **C — Spec schärfen, dann implementieren** | PO-Lock vor Coding | **✓ gewählt** |
**PO-Lock (Option C):** [`docs/product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../product/archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md)
Kernentscheide:
- **Parallele Gates** + **Gate-Graph** + **Join-Gates** (Lanes graph-abgeleitet — ADP A1 Lanes v0.1)
- **Horizon:** mehrere aktive Gates (nicht eine Stufe initiative-weit)
- **Übung** = `RecurringElement` am Gate (`roadmap_item_id`); Rhythmus = Feld
- **A1 Go MVP:** ≥2 parallele Gates + 1 Join + Gate-Activity-Set + Today — nicht nur Spagat-Demo
**Validation A1:** Re-Abnahme gemäß [`Sprint1_AP2_1_MVP_Validation_Report_v0.3.md`](Sprint1_AP2_1_MVP_Validation_Report_v0.3.md) **§3.5** (Progressionsmodell, ohne Starter-Kit). A2/B2b-Smoke **parallel** möglich.
---
## 8. Nächste Register-Einträge
| Szenario | Status |
|----------|--------|
| A2 — Neue Küche (Linear) | ausstehend |
| B2b + B3 — Product + Sprint | ausstehend |
| Portfolio / Cockpit (Kriterium 7) | ausstehend |
---
*Aktualisieren bei jedem PO-Smoke-Schritt. Bei Kategorie „Architektur-Lücke“ → ADP prüfen, nicht sofort implementieren.*
@@ -0,0 +1,61 @@
# AP A1 — Minimum Usability Slice
## Auftrag v0.1
**Status:** freigegeben (PO folgt Option A, 2026-07-28) · **superseded by Option C PO-Lock** — siehe [`SPEC_A1_Progression_Model_PO_Lock_v0.1.md`](../archetypes/SPEC_A1_Progression_Model_PO_Lock_v0.1.md)
**Auslöser:** AP2.1 PO No-Go A1 — [`Sprint1_AP2_1_Validation_Findings_Register_v0.1.md`](Sprint1_AP2_1_Validation_Findings_Register_v0.1.md) §6.1
**Ziel:** A1 **real nutzbar** für Tages-Tracking + Gate-Einschätzung + klare Today-Ansicht — **ohne** Architektur-Neudesign.
---
## 1. Nicht-Ziele (dieser Slice)
- Alternanz-Gruppen, Wochentags-Editor vollständig
- Automatische Metric-Engine (4×/Woche auto-count)
- Volles Activity Set bei Stufenwechsel (Stage-APs auto-aktivieren)
- A3/Care CadenceInstance-Parität
---
## 2. Lieferumfang (Pflicht für Re-Abnahme A1)
| # | Lieferung | Findings | Akzeptanz |
|---|-----------|----------|-----------|
| 1 | **`cadence_instances`** + API `complete` | F-A1-02, F-A1-06 | Eine offene Instanz pro aktivem Recurring; „Heute erledigt“ → nächste Fälligkeit |
| 2 | **`WorkTodayPracticePanel`** | F-A1-03 | Ausführen/Today zeigt Übung zuerst; optional Messnotiz |
| 3 | **Next Action → Übung** | F-A1-03 | Klickbarer Pfad zu Today-Übung |
| 4 | **Gate-Fortschritt** am aktiven Stufe-Panel | F-A1-04 | Kriterien offen/erfüllt sichtbar + Link Gate-Detail |
| 5 | **IA A1** | F-A1-01, F-A1-10 | Eingang aus Nav; Plan-Outline nur profile + gates + work |
---
## 3. Architektur-Bezug (kein ADP nötig)
| Baustein | Dokument |
|----------|----------|
| CadenceInstance | `Kairo_Steering_Method_Normalization_Program_v0.1.md`, Spec-D `maturity_progression` D4 |
| Work-Item-Polymorphie FE | Kernel Q2 — Link-Typ `recurring_id` |
| Gate-Kriterien | AP1.4b — bestehend |
---
## 4. Pakete
```text
A1.1 Migration 030 + cadence_instance service + complete API + pytest
A1.2 WorkTodayPracticePanel + Composition + NextAction-Link
A1.3 MaturityStagePanel Gate-Fortschritt + ui_profile IA
A1.4 Re-Validation A1 (PO) → Report §3 Go/Bedingt
```
---
## 5. Re-Abnahme-Kriterien (PO)
1. PO kann **heute** Übung als erledigt markieren (+ optional Messnotiz).
2. **Leitfrage ≤2 Min:** „Welche Übung heute?“ — ohne AP-Detour.
3. **Kontrolle:** aktive Stufe + Kriterien-Fortschritt erkennbar.
4. Kein Eingang-Redirect / Nav-Rauschen.
---
*Nach Abschluss: Findings Register F-A1-* auf erledigt setzen; AP2.1 A1 erneut smoke-testen.*
+11
View File
@@ -27,6 +27,17 @@ export function unplanActionToBacklog(id, { carryover = false } = {}) {
return apiFetch(`/api/actions/${id}/unplan-to-backlog${query}`, { method: 'POST' }) return apiFetch(`/api/actions/${id}/unplan-to-backlog${query}`, { method: 'POST' })
} }
export function upsertActionSchedule(id, schedule) {
return apiFetch(`/api/actions/${id}/schedule`, {
method: 'PUT',
body: JSON.stringify(schedule),
})
}
export function clearActionSchedule(id) {
return apiFetch(`/api/actions/${id}/schedule`, { method: 'DELETE' })
}
export function listMyOpenActions() { export function listMyOpenActions() {
return apiFetch('/api/actions/me/open') return apiFetch('/api/actions/me/open')
} }
+7
View File
@@ -21,3 +21,10 @@ export function updateRecurring(recurringId, body) {
export function deleteRecurring(recurringId) { export function deleteRecurring(recurringId) {
return apiFetch(`/api/recurring/${recurringId}`, { method: 'DELETE' }) return apiFetch(`/api/recurring/${recurringId}`, { method: 'DELETE' })
} }
export function completeRecurringPractice(recurringId, body = {}) {
return apiFetch(`/api/recurring/${recurringId}/complete`, {
method: 'POST',
body: JSON.stringify(body),
})
}
+11
View File
@@ -70,6 +70,17 @@ export function listRoadmapItemCriteria(itemId) {
return apiFetch(`/api/roadmap-items/${itemId}/criteria`) return apiFetch(`/api/roadmap-items/${itemId}/criteria`)
} }
export function listGatePractices(gateId) {
return apiFetch(`/api/roadmap-items/${gateId}/practices`)
}
export function createGatePractice(gateId, body) {
return apiFetch(`/api/roadmap-items/${gateId}/practices`, {
method: 'POST',
body: JSON.stringify(body),
})
}
export function createRoadmapItemCriterion(itemId, body) { export function createRoadmapItemCriterion(itemId, body) {
return apiFetch(`/api/roadmap-items/${itemId}/criteria`, { return apiFetch(`/api/roadmap-items/${itemId}/criteria`, {
method: 'POST', method: 'POST',
@@ -0,0 +1,148 @@
import { useEffect, useState } from 'react'
import { clearActionSchedule, getAction, upsertActionSchedule } from '../api/actions.js'
import { ScheduleEditor } from './ScheduleEditor.jsx'
import {
buildSchedulePayload,
defaultScheduleValue,
formatScheduleLabel,
scheduleFromApi,
} from '../utils/scheduleUtils.js'
export function ActionScheduleSection({
action,
canManage = false,
onUpdated,
}) {
const [enabled, setEnabled] = useState(Boolean(action?.schedule))
const [schedule, setSchedule] = useState(defaultScheduleValue())
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
const [editing, setEditing] = useState(false)
const [loadedSchedule, setLoadedSchedule] = useState(null)
useEffect(() => {
let cancelled = false
getAction(action.id)
.then((full) => {
if (cancelled) return
setLoadedSchedule(full.schedule || null)
setEnabled(Boolean(full.schedule))
setSchedule(scheduleFromApi(full.schedule))
})
.catch(() => {})
return () => {
cancelled = true
}
}, [action.id, action.updated_at])
const displaySchedule = loadedSchedule ?? action?.schedule
async function run(fn) {
setBusy(true)
setError(null)
try {
await fn()
if (onUpdated) await onUpdated()
} catch (err) {
setError(err.message)
} finally {
setBusy(false)
}
}
async function handleEnable(checked) {
if (!checked) {
if (!displaySchedule) {
setEnabled(false)
return
}
if (!window.confirm('Wiederholung am Arbeitspaket entfernen?')) return
await run(() => clearActionSchedule(action.id))
setEnabled(false)
return
}
setEnabled(true)
setEditing(true)
}
async function handleSave() {
let payload
try {
payload = buildSchedulePayload(schedule)
} catch (err) {
setError(err.message)
return
}
await run(() => upsertActionSchedule(action.id, payload))
setEditing(false)
}
return (
<section className="card action-schedule-section">
<div className="section-header">
<div>
<h3>Wiederholung</h3>
<p className="section-lead muted">
Regelmäßige Ausführung dieses Arbeitspakets — gleicher Rhythmus wie bei Gate-Übungen.
</p>
</div>
{canManage && (
<label className="toggle-inline">
<input
type="checkbox"
checked={enabled}
disabled={busy}
onChange={(e) => handleEnable(e.target.checked)}
/>
Rhythmus aktiv
</label>
)}
</div>
{error && <p className="error">{error}</p>}
{!enabled && !displaySchedule && (
<p className="muted">Keine Wiederholung — eignet sich z. B. für monatliches Reporting.</p>
)}
{(enabled || displaySchedule) && !editing && (
<p className="action-schedule-section__summary">
<strong>{formatScheduleLabel(displaySchedule || schedule)}</strong>
{canManage && (
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => setEditing(true)}
>
Bearbeiten
</button>
)}
</p>
)}
{editing && canManage && (
<div className="action-schedule-section__edit">
<ScheduleEditor value={schedule} onChange={setSchedule} disabled={busy} />
<div className="action-controls">
<button type="button" className="btn btn-primary btn-sm" disabled={busy} onClick={handleSave}>
Speichern
</button>
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => {
setEditing(false)
setSchedule(scheduleFromApi(displaySchedule))
setEnabled(Boolean(displaySchedule))
}}
>
Abbrechen
</button>
</div>
</div>
)}
</section>
)
}
+46 -16
View File
@@ -42,6 +42,8 @@ export function BacklogSection({
busy, busy,
sectionTitle = 'Product Backlog', sectionTitle = 'Product Backlog',
sectionLead = 'Eingang vor dem Commit — triagieren, dann in den Sprint planen.', sectionLead = 'Eingang vor dem Commit — triagieren, dann in den Sprint planen.',
defaultSprintTargetId = null,
lockSprintTarget = false,
}) { }) {
const { operatingContext, steeringElements, steeringSnapshot } = useInitiativeOperations() const { operatingContext, steeringElements, steeringSnapshot } = useInitiativeOperations()
const [modalMode, setModalMode] = useState(null) const [modalMode, setModalMode] = useState(null)
@@ -74,6 +76,13 @@ export function BacklogSection({
if (!showSprintPlanning || !initiativeId) { if (!showSprintPlanning || !initiativeId) {
return return
} }
if (
defaultSprintTargetId
&& planableSprints.some((cycle) => cycle.id === defaultSprintTargetId)
) {
setSprintTargetId(defaultSprintTargetId)
return
}
const stored = sessionStorage.getItem(SPRINT_TARGET_STORAGE_PREFIX + initiativeId) const stored = sessionStorage.getItem(SPRINT_TARGET_STORAGE_PREFIX + initiativeId)
if (stored && planableSprints.some((cycle) => cycle.id === stored)) { if (stored && planableSprints.some((cycle) => cycle.id === stored)) {
setSprintTargetId(stored) setSprintTargetId(stored)
@@ -84,7 +93,13 @@ export function BacklogSection({
} }
const preferred = activeWorkCycle?.id || planableSprints[0]?.id || '' const preferred = activeWorkCycle?.id || planableSprints[0]?.id || ''
setSprintTargetId(preferred) setSprintTargetId(preferred)
}, [showSprintPlanning, initiativeId, planableSprints, activeWorkCycle?.id]) }, [
showSprintPlanning,
initiativeId,
planableSprints,
activeWorkCycle?.id,
defaultSprintTargetId,
])
useEffect(() => { useEffect(() => {
if (!initiativeId || !sprintTargetId) return if (!initiativeId || !sprintTargetId) return
@@ -292,21 +307,36 @@ export function BacklogSection({
{showSprintPlanning && canManage && ( {showSprintPlanning && canManage && (
<div className="backlog-sprint-planning card-list-item"> <div className="backlog-sprint-planning card-list-item">
<label className="backlog-sprint-planning__field"> {lockSprintTarget && selectedSprint ? (
<span className="muted">Ziel-Sprint</span> <p className="muted backlog-sprint-planning__locked">
<select Ziel-Sprint: <strong>{selectedSprint.title}</strong>
value={sprintTargetId} {selectedSprint.status === 'active'
onChange={(e) => setSprintTargetId(e.target.value)} ? ' (aktiv)'
disabled={busy} : selectedSprint.status === 'planned'
> ? ' (geplant)'
{planableSprints.map((cycle) => ( : ''}
<option key={cycle.id} value={cycle.id}> </p>
{cycle.title} ) : (
{cycle.status === 'active' ? ' (aktiv)' : cycle.status === 'planned' ? ' (geplant)' : ''} <label className="backlog-sprint-planning__field">
</option> <span className="muted">Ziel-Sprint</span>
))} <select
</select> value={sprintTargetId}
</label> onChange={(e) => setSprintTargetId(e.target.value)}
disabled={busy}
>
{planableSprints.map((cycle) => (
<option key={cycle.id} value={cycle.id}>
{cycle.title}
{cycle.status === 'active'
? ' (aktiv)'
: cycle.status === 'planned'
? ' (geplant)'
: ''}
</option>
))}
</select>
</label>
)}
{selectedCommittable.length > 0 && ( {selectedCommittable.length > 0 && (
<button <button
type="button" type="button"
+44 -18
View File
@@ -1,29 +1,55 @@
import { useState } from 'react' import { useState } from 'react'
/**
* Generischer Drill-down-Container — AP1.9d Anti-Todo-Wand.
* Bewusst layout-neutral für späteres UI-Redesign.
*/
export function CollapsibleSection({ export function CollapsibleSection({
title, title,
summary, lead,
defaultOpen = false, defaultCollapsed = true,
expandLabel = 'Alle anzeigen',
collapseLabel = 'Einklappen',
headerActions = null,
className = 'card',
children, children,
className = '',
}) { }) {
const [open, setOpen] = useState(defaultOpen) const [expanded, setExpanded] = useState(!defaultCollapsed)
return ( return (
<section className={`collapsible-section card ${className}`.trim()}> <section className={className}>
<button <div className="section-header">
type="button" <div>
className="collapsible-section-trigger" {title && <h2>{title}</h2>}
onClick={() => setOpen((v) => !v)} {lead && <p className="section-lead muted">{lead}</p>}
aria-expanded={open} </div>
> {headerActions}
<span className="collapsible-section-title">{title}</span> </div>
{summary && <span className="collapsible-section-summary muted">{summary}</span>}
<span className="collapsible-section-chevron" aria-hidden="true"> {expanded ? (
{open ? '▾' : '▸'} <>
</span> {children}
</button> <p className="collapsible-section__toggle">
{open && <div className="collapsible-section-body">{children}</div>} <button
type="button"
className="btn btn-ghost btn-sm"
onClick={() => setExpanded(false)}
>
{collapseLabel}
</button>
</p>
</>
) : (
<p className="collapsible-section__toggle">
<button
type="button"
className="btn btn-secondary btn-sm"
onClick={() => setExpanded(true)}
>
{expandLabel}
</button>
</p>
)}
</section> </section>
) )
} }
@@ -0,0 +1,292 @@
import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { createGatePractice, listGatePractices } from '../api/roadmap.js'
import { deleteRecurring, updateRecurring } from '../api/recurring.js'
import { RECURRING_STATUSES, RECURRING_STATUS_LABELS } from '../constants/status.js'
import { EmptyState } from './EmptyState.jsx'
import { ScheduleEditor, scheduleEditorFromPractice } from './ScheduleEditor.jsx'
import { StatusBadge } from './StatusBadge.jsx'
import { scopedPath } from '../utils/routes.js'
import {
buildSchedulePayload,
defaultScheduleValue,
formatScheduleLabel,
} from '../utils/scheduleUtils.js'
function formatDueAt(iso) {
if (!iso) return null
try {
return new Date(iso).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
} catch {
return iso
}
}
export function GateActivitySetSection({
gateId,
initiativeId,
gateStatus,
gateTitle,
canManage = false,
}) {
const [practices, setPractices] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [busy, setBusy] = useState(false)
const [showForm, setShowForm] = useState(false)
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [schedule, setSchedule] = useState(defaultScheduleValue())
const [editingRhythmId, setEditingRhythmId] = useState(null)
const [editSchedule, setEditSchedule] = useState(defaultScheduleValue())
const load = useCallback(async () => {
setLoading(true)
setError(null)
try {
const items = await listGatePractices(gateId)
setPractices(Array.isArray(items) ? items : [])
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}, [gateId])
useEffect(() => {
load()
}, [load])
async function runAction(fn) {
setBusy(true)
setError(null)
try {
await fn()
await load()
} catch (err) {
setError(err.message)
} finally {
setBusy(false)
}
}
async function handleCreate(e) {
e.preventDefault()
if (!title.trim()) return
let payload
try {
payload = buildSchedulePayload(schedule)
} catch (err) {
setError(err.message)
return
}
await runAction(async () => {
await createGatePractice(gateId, {
title: title.trim(),
description: description.trim(),
status: 'active',
schedule: payload,
})
setTitle('')
setDescription('')
setSchedule(defaultScheduleValue())
setShowForm(false)
})
}
async function saveRhythm(practice) {
let payload
try {
payload = buildSchedulePayload(editSchedule)
} catch (err) {
setError(err.message)
return
}
await runAction(async () => {
await updateRecurring(practice.id, { schedule: payload })
setEditingRhythmId(null)
})
}
const isActiveGate = gateStatus === 'active' || gateStatus === 'at_risk'
const routineLabel = gateTitle ? `Routine: ${gateTitle}` : 'Routine an diesem Gate'
return (
<section className="card gate-activity-set">
<div className="section-header">
<div>
<h3>{routineLabel}</h3>
<p className="section-lead muted">
Übungen sind Arbeitspakete mit Wochentagsplan an diesem Zielzustand.
Sie erscheinen in Today nur an den gewählten Tagen, solange das Gate{' '}
<strong>aktiv</strong> ist.
</p>
</div>
{canManage && (
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() => setShowForm((value) => !value)}
disabled={busy}
>
{showForm ? 'Abbrechen' : 'Übung anlegen'}
</button>
)}
</div>
{error && <p className="error">{error}</p>}
{!isActiveGate && (
<p className="muted gate-activity-set__hint">
Gate-Status ist <strong>{gateStatus}</strong> — Übungen werden in Today sichtbar, sobald
das Gate auf <strong>aktiv</strong> steht.
</p>
)}
{isActiveGate && practices.some((item) => item.status === 'active') && initiativeId && (
<p className="muted gate-activity-set__hint">
<Link to={scopedPath('/work/today', { initiativeId })} className="link-inline">
Ausführen → Today
</Link>{' '}
— fällige Übungen dieser Stufe abhaken.
</p>
)}
{showForm && canManage && (
<form className="inline-form-block gate-activity-set__form" onSubmit={handleCreate}>
<label>
Titel
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={255}
required
placeholder="z. B. Vorbeuge halten"
/>
</label>
<label>
Beschreibung (optional)
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={2}
placeholder="Hinweise zur Ausführung"
/>
</label>
<ScheduleEditor value={schedule} onChange={setSchedule} disabled={busy} />
<button type="submit" className="btn btn-primary" disabled={busy}>
Übung speichern
</button>
</form>
)}
{loading ? (
<p className="muted">Übungen werden geladen…</p>
) : practices.length === 0 ? (
<EmptyState message="Noch keine Übungen — mindestens ein Arbeitspaket mit Wochentagen anlegen." />
) : (
<ul className="item-list gate-activity-set__list">
{practices.map((practice) => (
<li key={practice.id} className="list-item card-list-item">
<div className="list-item-main">
<strong>{practice.title}</strong>
{practice.action_id && initiativeId && (
<p className="muted list-item-sub">
<Link
to={scopedPath(`/actions/${practice.action_id}`, { initiativeId })}
className="link-inline"
>
Arbeitspaket öffnen
</Link>
</p>
)}
{practice.description && (
<p className="muted list-item-sub">{practice.description}</p>
)}
<p className="muted list-item-sub">
{formatScheduleLabel(practice.schedule || practice)}
{practice.open_cadence_instance?.due_at
? ` · Fällig: ${formatDueAt(practice.open_cadence_instance.due_at)}`
: ''}
{practice.today_completed ? ' · heute erledigt' : ''}
</p>
{editingRhythmId === practice.id && (
<div className="gate-activity-set__rhythm-edit">
<ScheduleEditor
value={editSchedule}
onChange={setEditSchedule}
disabled={busy}
compact
/>
<div className="action-controls">
<button
type="button"
className="btn btn-primary btn-sm"
disabled={busy}
onClick={() => saveRhythm(practice)}
>
Rhythmus speichern
</button>
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => setEditingRhythmId(null)}
>
Abbrechen
</button>
</div>
</div>
)}
</div>
{canManage && (
<div className="list-item-meta action-controls">
<StatusBadge kind="recurring" status={practice.status} />
<select
className="inline-select"
value={practice.status}
disabled={busy}
onChange={(e) =>
runAction(() =>
updateRecurring(practice.id, { status: e.target.value }),
)
}
aria-label="Übungs-Status"
>
{RECURRING_STATUSES.map((status) => (
<option key={status} value={status}>
{RECURRING_STATUS_LABELS[status]}
</option>
))}
</select>
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => {
setEditingRhythmId(practice.id)
setEditSchedule(scheduleEditorFromPractice(practice))
}}
>
Rhythmus
</button>
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => {
if (!window.confirm(`„${practice.title}" löschen?`)) return
runAction(() => deleteRecurring(practice.id))
}}
>
Löschen
</button>
</div>
)}
</li>
))}
</ul>
)}
</section>
)
}
+147 -49
View File
@@ -1,10 +1,14 @@
import { useState } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { gatePath } from '../utils/routes.js' import { gatePath } from '../utils/routes.js'
import { import {
MILESTONE_STATUS_LABELS, MILESTONE_STATUS_LABELS,
ROADMAP_ITEM_TYPE_LABELS, ROADMAP_ITEM_TYPE_LABELS,
isJoinGateItem,
} from '../constants/status.js' } from '../constants/status.js'
import { StatusBadge } from './StatusBadge.jsx' import { StatusBadge } from './StatusBadge.jsx'
import { Modal } from './Modal.jsx'
import { RoadmapItemForm } from './RoadmapItemForm.jsx'
function formatDate(value) { function formatDate(value) {
if (!value) return null if (!value) return null
@@ -17,82 +21,176 @@ function formatDate(value) {
} }
} }
function graphNodeHint(item, graphItem, enforceBlocking) {
if (item.status === 'reached') {
return { label: 'Abgeschlossen', className: 'status-pill status-pill--done' }
}
if (enforceBlocking && graphItem?.blocked) {
return { label: 'Blockiert', className: 'status-pill status-pill--blocked' }
}
if (graphItem?.ready || item.status === 'active') {
return { label: 'Aktiv / bereit', className: 'status-pill status-pill--ready' }
}
return null
}
export function GateDesignerNodePanel({ export function GateDesignerNodePanel({
item, item,
graphState, graphState,
criteriaProgress, criteriaProgress,
canManage = false,
busy = false,
onClose, onClose,
onUpdate,
onDelete,
}) { }) {
const [showEdit, setShowEdit] = useState(false)
if (!item) return null if (!item) return null
const joinGate = isJoinGateItem(item)
const graphItem = graphState?.items?.[item.id] const graphItem = graphState?.items?.[item.id]
const enforceBlocking = graphState?.graph_profile?.enforce_gate_blocking !== false
const statusHint = graphNodeHint(item, graphItem, enforceBlocking)
const terminalStatus = ['reached', 'moved', 'discarded'].includes(item.status)
const canDelete = canManage && !terminalStatus && typeof onDelete === 'function'
const canEdit = canManage && !terminalStatus && typeof onUpdate === 'function'
const progress = criteriaProgress?.[item.id] const progress = criteriaProgress?.[item.id]
const closed = progress?.closed ?? 0 const closed = progress?.closed ?? 0
const total = progress?.total ?? 0 const total = progress?.total ?? 0
return ( async function handleEditSubmit(payload) {
<aside className="gate-designer-node-panel" aria-label="Gate-Informationen"> await onUpdate(item.id, payload)
<div className="gate-designer-node-panel__header"> setShowEdit(false)
<h3 className="gate-designer-node-panel__title">{item.title || 'Gate'}</h3> }
<button
type="button"
className="btn btn-secondary btn-sm"
aria-label="Panel schließen"
onClick={onClose}
>
×
</button>
</div>
<dl className="gate-designer-node-panel__meta"> async function handleDeleteClick() {
<div> const label = item.title || 'dieses Gate'
<dt>Typ</dt> const ok = window.confirm(
<dd>{ROADMAP_ITEM_TYPE_LABELS[item.item_type] || item.item_type || 'Gate'}</dd> `„${label}" wirklich löschen? Verknüpfte Kanten werden mit entfernt.`,
)
if (!ok) return
await onDelete(item.id)
onClose?.()
}
return (
<>
<aside className="gate-designer-node-panel" aria-label="Gate-Informationen">
<div className="gate-designer-node-panel__header">
<h3 className="gate-designer-node-panel__title">{item.title || 'Gate'}</h3>
<button
type="button"
className="btn btn-secondary btn-sm"
aria-label="Panel schließen"
onClick={onClose}
>
×
</button>
</div> </div>
<div>
<dt>Status</dt> {statusHint && (
<dd> <p className="gate-designer-node-panel__status-hint">
<StatusBadge status={item.status || 'planned'} /> <span className={statusHint.className}>{statusHint.label}</span>
</dd> </p>
</div>
{item.target_date && (
<div>
<dt>Zieltermin</dt>
<dd>{formatDate(item.target_date)}</dd>
</div>
)} )}
{total > 0 && (
<dl className="gate-designer-node-panel__meta">
<div> <div>
<dt>Kriterien</dt> <dt>Typ</dt>
<dd>{ROADMAP_ITEM_TYPE_LABELS[item.item_type] || item.item_type || 'Gate'}</dd>
</div>
<div>
<dt>Status</dt>
<dd> <dd>
{closed}/{total} erfüllt <StatusBadge status={item.status || 'planned'} />
</dd> </dd>
</div> </div>
{item.target_date && (
<div>
<dt>Zieltermin</dt>
<dd>{formatDate(item.target_date)}</dd>
</div>
)}
{total > 0 && (
<div>
<dt>Kriterien</dt>
<dd>
{closed}/{total} erfüllt
</dd>
</div>
)}
</dl>
{joinGate && (
<p className="gate-designer-node-panel__topology muted">
Schaltknoten — schaltet, wenn alle Eingänge (requires) erreicht sind. Keine Checkliste,
kein manuelles Verify.
</p>
)} )}
</dl>
{item.goal_description && ( {item.goal_description && (
<p className="gate-designer-node-panel__goal muted">{item.goal_description}</p> <p className="gate-designer-node-panel__goal muted">{item.goal_description}</p>
)} )}
{graphItem?.parallel_group_keys?.length > 0 && ( {graphItem?.parallel_group_keys?.length > 0 && (
<p className="gate-designer-node-panel__topology muted"> <p className="gate-designer-node-panel__topology muted">
Parallel: {graphItem.parallel_group_keys.join(', ')} Parallel: {graphItem.parallel_group_keys.join(', ')}
</p> </p>
)} )}
{graphItem?.optional_prerequisites?.length > 0 && ( {graphItem?.optional_prerequisites?.length > 0 && (
<p className="gate-designer-node-panel__topology muted"> <p className="gate-designer-node-panel__topology muted">
Optional: {graphItem.optional_prerequisites.length} Zweig(e) — blockieren nicht Optional: {graphItem.optional_prerequisites.length} Zweig(e) — blockieren nicht
</p> </p>
)} )}
<div className="gate-designer-node-panel__actions"> {terminalStatus && (
<Link to={gatePath(item.id)} className="btn btn-secondary btn-sm"> <p className="gate-designer-node-panel__topology muted">
Vollständig bearbeiten {item.status === 'reached'
</Link> ? 'Abgeschlossene Gates sind geschützt und können nicht gelöscht oder in den Typ geändert werden.'
</div> : `Terminaler Status (${MILESTONE_STATUS_LABELS[item.status] || item.status}) — Löschen gesperrt.`}
</aside> </p>
)}
<div className="gate-designer-node-panel__actions">
{canEdit && (
<button
type="button"
className="btn btn-secondary btn-sm"
disabled={busy}
onClick={() => setShowEdit(true)}
>
Typ & Metadaten
</button>
)}
{canDelete && (
<button
type="button"
className="btn btn-secondary btn-sm gate-designer-node-panel__delete"
disabled={busy}
onClick={handleDeleteClick}
>
Löschen
</button>
)}
<Link to={gatePath(item.id)} className="btn btn-secondary btn-sm">
Vollständig bearbeiten
</Link>
</div>
</aside>
<Modal open={showEdit} title="Gate bearbeiten" onClose={() => setShowEdit(false)}>
<RoadmapItemForm
mode="edit"
initial={item}
busy={busy}
submitLabel="Speichern"
onCancel={() => setShowEdit(false)}
onSubmit={handleEditSubmit}
/>
</Modal>
</>
) )
} }
+245 -15
View File
@@ -15,7 +15,14 @@ import {
loadManualGatePositions, loadManualGatePositions,
storeManualGatePositions, storeManualGatePositions,
} from '../plan/gateGraphDesigner.js' } from '../plan/gateGraphDesigner.js'
import { DESIGNER_EDGE_KINDS, DESIGNER_EDGE_LABELS, edgeKindNeedsGroupKey, resolveDependencyEndpoints } from '../plan/gateGraphTopology.js' import {
DESIGNER_EDGE_KINDS,
DESIGNER_EDGE_DESCRIPTIONS,
DESIGNER_EDGE_LABELS,
dependencyVisualEndpoints,
edgeKindNeedsGroupKey,
resolveDependencyEndpoints,
} from '../plan/gateGraphTopology.js'
import { LoadingState } from './LoadingState.jsx' import { LoadingState } from './LoadingState.jsx'
import { ErrorState } from './ErrorState.jsx' import { ErrorState } from './ErrorState.jsx'
import { EmptyState } from './EmptyState.jsx' import { EmptyState } from './EmptyState.jsx'
@@ -61,6 +68,8 @@ export function GateGraphDesigner({
canManage = false, canManage = false,
busy: busyProp = false, busy: busyProp = false,
onCreate, onCreate,
onUpdate,
onDelete,
onGraphChanged, onGraphChanged,
graphState, graphState,
}) { }) {
@@ -147,6 +156,21 @@ export function GateGraphDesigner({
[items, selectedNodeId], [items, selectedNodeId],
) )
const selectedDependency = useMemo(
() => dependencies.find((dep) => dep.id === selectedEdgeId) || null,
[dependencies, selectedEdgeId],
)
const itemTitleById = useMemo(() => {
const map = new Map()
for (const item of items) {
map.set(item.id, item.title || 'Gate')
}
return map
}, [items])
const enforceBlocking = graphState?.graph_profile?.enforce_gate_blocking !== false
async function notifyGraphChanged() { async function notifyGraphChanged() {
await reloadDependencies() await reloadDependencies()
onGraphChanged?.() onGraphChanged?.()
@@ -200,6 +224,74 @@ export function GateGraphDesigner({
} }
} }
async function handleChangeEdgeType(newType) {
if (!selectedDependency || !canManage) return
if (newType === selectedDependency.dependency_type) return
const effectiveGroupKey = (selectedDependency.group_key || groupKey || 'phase-1').trim()
if (edgeKindNeedsGroupKey(newType) && !effectiveGroupKey) {
setError('Parallelgruppe benötigt einen Schlüssel (group_key).')
return
}
setBusyLocal(true)
setError(null)
try {
const { sourceId, targetId } = dependencyVisualEndpoints(selectedDependency)
await deleteRoadmapDependency(selectedDependency.id)
const { from_item_id: fromItemId, to_item_id: toItemId } = resolveDependencyEndpoints(
newType,
sourceId,
targetId,
)
const body = {
to_item_id: toItemId,
dependency_type: newType,
}
if (edgeKindNeedsGroupKey(newType)) {
body.group_key = effectiveGroupKey
}
await addRoadmapItemDependency(fromItemId, body)
setEdgeType(newType)
if (edgeKindNeedsGroupKey(newType)) {
setGroupKey(effectiveGroupKey)
}
await notifyGraphChanged()
} catch (err) {
setError(err?.message || 'Kantentyp konnte nicht geändert werden.')
} finally {
setBusyLocal(false)
}
}
async function handleDeleteGate(itemId) {
if (!onDelete || !canManage) return
setBusyLocal(true)
setError(null)
try {
await onDelete(itemId)
setSelectedNodeId(null)
onGraphChanged?.()
} catch (err) {
setError(err?.message || 'Gate konnte nicht gelöscht werden.')
} finally {
setBusyLocal(false)
}
}
async function handleUpdateGate(itemId, payload) {
if (!onUpdate || !canManage) return
setBusyLocal(true)
setError(null)
try {
await onUpdate(itemId, payload)
onGraphChanged?.()
} catch (err) {
setError(err?.message || 'Gate konnte nicht gespeichert werden.')
throw err
} finally {
setBusyLocal(false)
}
}
function openCreateAt(point) { function openCreateAt(point) {
setCreatePosition({ setCreatePosition({
x: Math.max(0, point.x - GATE_NODE_WIDTH / 2), x: Math.max(0, point.x - GATE_NODE_WIDTH / 2),
@@ -514,11 +606,46 @@ export function GateGraphDesigner({
)} )}
</div> </div>
<div className="gate-graph-designer__legends">
<div className="gate-map-view__legend muted gate-graph-designer__legend">
<span className="gate-map-view__legend-item">
<span className="gate-map-view__legend-line gate-map-view__legend-line--requires" />
Voraussetzung
</span>
<span className="gate-map-view__legend-item">
<span className="gate-map-view__legend-line gate-map-view__legend-line--blocks" />
Blockiert
</span>
<span className="gate-map-view__legend-item">
<span className="gate-map-view__legend-line gate-map-view__legend-line--related" />
Bezug
</span>
<span className="gate-map-view__legend-item">
<span className="gate-map-view__legend-line gate-map-view__legend-line--parallel" />
Parallel
</span>
<span className="gate-map-view__legend-item">
<span className="gate-map-view__legend-line gate-map-view__legend-line--optional" />
Optional
</span>
</div>
<div className="gate-graph-designer__node-legend muted">
<span className="gate-graph-designer__node-legend-item gate-graph-designer__node-legend-item--reached">
Abgeschlossen
</span>
<span className="gate-graph-designer__node-legend-item gate-graph-designer__node-legend-item--ready">
Aktiv / bereit
</span>
<span className="gate-graph-designer__node-legend-item gate-graph-designer__node-legend-item--blocked">
Blockiert
</span>
</div>
</div>
{canManage && ( {canManage && (
<p className="gate-graph-designer__hint muted"> <p className="gate-graph-designer__hint muted">
Vom unteren Punkt ziehen: Voraussetzung/Block/Bezug/Parallel/Optional. Join-Gates Vom unteren Punkt ziehen: Kante anlegen. Klick auf Kante oder Gate öffnet Bearbeitung
verbinden mehrere Pflicht-Voraussetzungen (AND). Doppelklick auf leere Fläche legt ein rechts. Join-Gates sammeln Eingänge (AND). Doppelklick auf leere Fläche legt ein Gate an.
Gate an.
</p> </p>
)} )}
@@ -586,10 +713,8 @@ export function GateGraphDesigner({
} }
onClick={(event) => { onClick={(event) => {
event.stopPropagation() event.stopPropagation()
if (canManage) { setSelectedEdgeId(edge.id)
setSelectedEdgeId(edge.id) setSelectedNodeId(null)
setSelectedNodeId(null)
}
}} }}
/> />
))} ))}
@@ -607,11 +732,24 @@ export function GateGraphDesigner({
{layout.nodes.map((node) => { {layout.nodes.map((node) => {
const item = node.item const item = node.item
const isSelected = selectedNodeId === node.id const isSelected = selectedNodeId === node.id
const nodeGraph = graphState?.items?.[node.id]
const nodeClass = const nodeClass =
'gate-map-view__node gate-map-view__node--' + 'gate-map-view__node gate-map-view__node--' +
(item.status || 'planned') + (item.status || 'planned') +
(item.item_type === 'join_gate' ? ' gate-map-view__node--join_gate' : '') +
(enforceBlocking && nodeGraph?.blocked ? ' gate-map-view__node--blocked' : '') +
(nodeGraph?.ready ? ' gate-map-view__node--ready' : '') +
(item.status === 'reached' ? ' gate-map-view__node--reached' : '') +
(isSelected ? ' gate-graph-designer__node--selected' : '') + (isSelected ? ' gate-graph-designer__node--selected' : '') +
(draggingNodeId === node.id ? ' gate-graph-designer__node--dragging' : '') (draggingNodeId === node.id ? ' gate-graph-designer__node--dragging' : '')
const statusLabel =
item.status === 'reached'
? '✓'
: enforceBlocking && nodeGraph?.blocked
? '⏸'
: nodeGraph?.ready || item.status === 'active'
? '●'
: null
return ( return (
<g <g
key={node.id} key={node.id}
@@ -627,12 +765,27 @@ export function GateGraphDesigner({
rx="8" rx="8"
ry="8" ry="8"
/> />
{statusLabel && (
<text
className="gate-graph-designer__node-status-mark"
x={node.width - 14}
y="18"
aria-hidden="true"
>
{statusLabel}
</text>
)}
<text className="gate-map-view__node-title" x="12" y="28"> <text className="gate-map-view__node-title" x="12" y="28">
{truncateTitle(item.title)} {truncateTitle(item.title)}
</text> </text>
<text className="gate-map-view__node-meta" x="12" y="50"> <text className="gate-map-view__node-meta" x="12" y="50">
{ROADMAP_ITEM_TYPE_LABELS[item.item_type] || item.item_type || 'Gate'} {ROADMAP_ITEM_TYPE_LABELS[item.item_type] || item.item_type || 'Gate'}
</text> </text>
{item.status === 'reached' && (
<text className="gate-map-view__node-meta gate-graph-designer__node-reached-label" x="12" y="68">
Erreicht
</text>
)}
{canManage && ( {canManage && (
<circle <circle
className="gate-graph-designer__port" className="gate-graph-designer__port"
@@ -648,13 +801,90 @@ export function GateGraphDesigner({
</svg> </svg>
</div> </div>
{selectedItem && ( {(selectedItem || selectedDependency) && (
<GateDesignerNodePanel <div className="gate-graph-designer__side-panel">
item={selectedItem} {selectedDependency && (
graphState={graphState} <aside className="gate-designer-edge-panel" aria-label="Kanten-Bearbeitung">
criteriaProgress={criteriaProgress} <div className="gate-designer-node-panel__header">
onClose={() => setSelectedNodeId(null)} <h3 className="gate-designer-node-panel__title">Kante</h3>
/> <button
type="button"
className="btn btn-secondary btn-sm"
aria-label="Panel schließen"
onClick={() => setSelectedEdgeId(null)}
>
×
</button>
</div>
<p className="muted gate-designer-edge-panel__route">
{(() => {
const { sourceId, targetId } = dependencyVisualEndpoints(selectedDependency)
return `${itemTitleById.get(sourceId) || sourceId} → ${itemTitleById.get(targetId) || targetId}`
})()}
</p>
{canManage ? (
<>
<label className="gate-graph-designer__edge-type">
<span className="muted">Kantentyp</span>
<select
value={selectedDependency.dependency_type}
disabled={busy}
onChange={(e) => handleChangeEdgeType(e.target.value)}
>
{DESIGNER_EDGE_KINDS.map((value) => (
<option key={value} value={value}>
{DESIGNER_EDGE_LABELS[value]}
</option>
))}
</select>
</label>
{edgeKindNeedsGroupKey(selectedDependency.dependency_type) && (
<label className="gate-graph-designer__edge-type">
<span className="muted">Gruppenschlüssel</span>
<input
type="text"
value={selectedDependency.group_key || groupKey}
maxLength={128}
disabled={busy}
placeholder="z. B. phase-1"
onChange={(e) => setGroupKey(e.target.value)}
/>
</label>
)}
<p className="gate-designer-edge-panel__help muted">
{DESIGNER_EDGE_DESCRIPTIONS[selectedDependency.dependency_type]}
</p>
<button
type="button"
className="btn btn-secondary btn-sm gate-designer-node-panel__delete"
disabled={busy}
onClick={() => handleDeleteEdge(selectedDependency.id)}
>
Kante entfernen
</button>
</>
) : (
<p className="muted">
{DESIGNER_EDGE_LABELS[selectedDependency.dependency_type]} —{' '}
{DESIGNER_EDGE_DESCRIPTIONS[selectedDependency.dependency_type]}
</p>
)}
</aside>
)}
{selectedItem && !selectedDependency && (
<GateDesignerNodePanel
item={selectedItem}
graphState={graphState}
criteriaProgress={criteriaProgress}
canManage={canManage}
busy={busy}
onClose={() => setSelectedNodeId(null)}
onUpdate={handleUpdateGate}
onDelete={handleDeleteGate}
/>
)}
</div>
)} )}
</div> </div>
+1
View File
@@ -171,6 +171,7 @@ export function GateMapView({ initiativeId, items, graphState: graphStateProp, e
const nodeClass = const nodeClass =
'gate-map-view__node gate-map-view__node--' + 'gate-map-view__node gate-map-view__node--' +
(item.status || 'planned') + (item.status || 'planned') +
(item.item_type === 'join_gate' ? ' gate-map-view__node--join_gate' : '') +
(enforceBlocking && nodeGraph?.blocked ? ' gate-map-view__node--blocked' : '') + (enforceBlocking && nodeGraph?.blocked ? ' gate-map-view__node--blocked' : '') +
(nodeGraph?.ready ? ' gate-map-view__node--ready' : '') (nodeGraph?.ready ? ' gate-map-view__node--ready' : '')
return ( return (
@@ -10,6 +10,7 @@ export function GatesPlanPanel({
items, items,
canManage, canManage,
onCreate, onCreate,
onUpdate,
onReorder, onReorder,
onDelete, onDelete,
busy, busy,
@@ -129,6 +130,8 @@ export function GatesPlanPanel({
canManage={canManage} canManage={canManage}
busy={busy} busy={busy}
onCreate={canManage ? onCreate : undefined} onCreate={canManage ? onCreate : undefined}
onUpdate={canManage ? onUpdate : undefined}
onDelete={canManage ? onDelete : undefined}
onGraphChanged={refreshGraphState} onGraphChanged={refreshGraphState}
graphState={graphState} graphState={graphState}
/> />
@@ -1,5 +1,6 @@
import { ActionHubCard } from './ActionHubCard.jsx' import { ActionHubCard } from './ActionHubCard.jsx'
import { ActionForm } from './ActionForm.jsx' import { ActionForm } from './ActionForm.jsx'
import { CollapsibleSection } from './CollapsibleSection.jsx'
import { EmptyState } from './EmptyState.jsx' import { EmptyState } from './EmptyState.jsx'
export function InitiativeActionsHub({ export function InitiativeActionsHub({
@@ -34,35 +35,35 @@ export function InitiativeActionsHub({
sectionTitle = 'Arbeitspakete', sectionTitle = 'Arbeitspakete',
sectionLead = 'Committete operative Einheit — Aufgaben im Detail. Blocker, Nachweise und Reviews hängen am Arbeitspaket.', sectionLead = 'Committete operative Einheit — Aufgaben im Detail. Blocker, Nachweise und Reviews hängen am Arbeitspaket.',
allActions = [], allActions = [],
collapsible = false,
defaultCollapsed = true,
expandLabel = 'Alle anzeigen',
collapseLabel = 'Liste einklappen',
}) { }) {
return ( const headerActions = (
<section className="card initiative-actions-hub"> <div className="section-actions">
<div className="section-header"> <label className="checkbox-label inline-filter">
<div> <input
<h2>{sectionTitle}</h2> type="checkbox"
<p className="section-lead muted">{sectionLead}</p> checked={hideDone}
</div> onChange={(e) => onHideDoneChange(e.target.checked)}
<div className="section-actions"> />
<label className="checkbox-label inline-filter"> Erledigte ausblenden
<input </label>
type="checkbox" {canManage && (
checked={hideDone} <button
onChange={(e) => onHideDoneChange(e.target.checked)} type="button"
/> className="btn btn-primary btn-block-mobile"
Erledigte ausblenden onClick={onToggleForm}
</label> >
{canManage && ( {showForm ? 'Abbrechen' : 'Arbeitspaket'}
<button </button>
type="button" )}
className="btn btn-primary btn-block-mobile" </div>
onClick={onToggleForm} )
>
{showForm ? 'Abbrechen' : 'Arbeitspaket'}
</button>
)}
</div>
</div>
const body = (
<>
{showForm && canManage && ( {showForm && canManage && (
<div className="inline-form-block"> <div className="inline-form-block">
<ActionForm <ActionForm
@@ -118,6 +119,35 @@ export function InitiativeActionsHub({
/> />
))} ))}
</div> </div>
</>
)
if (collapsible) {
return (
<CollapsibleSection
className="card initiative-actions-hub"
title={sectionTitle}
lead={sectionLead}
defaultCollapsed={defaultCollapsed}
expandLabel={expandLabel}
collapseLabel={collapseLabel}
headerActions={headerActions}
>
{body}
</CollapsibleSection>
)
}
return (
<section className="card initiative-actions-hub">
<div className="section-header">
<div>
<h2>{sectionTitle}</h2>
<p className="section-lead muted">{sectionLead}</p>
</div>
{headerActions}
</div>
{body}
</section> </section>
) )
} }
@@ -0,0 +1,55 @@
import { useMemo } from 'react'
import { EmptyState } from './EmptyState.jsx'
/**
* A1 — Join-Schaltknoten: wartende Eingänge (kein Activity Set am Join).
*/
export function JoinWaitlistPanel({ progressionState = null }) {
const joins = useMemo(() => {
const list = progressionState?.joins || []
return list.filter(
(join) => join.status !== 'reached' && (join.pending_inputs?.length || 0) > 0,
)
}, [progressionState])
if (joins.length === 0) {
return (
<section className="card join-waitlist-panel">
<h2>Join-Fortschritt</h2>
<EmptyState message="Keine Joins warten auf Eingänge." />
</section>
)
}
return (
<section className="card join-waitlist-panel">
<div className="section-header">
<div>
<h2>Join-Fortschritt</h2>
<p className="section-lead muted">
Konsolidierte Meilensteine — welche Eingangs-Gates fehlen noch zum Schalten?
</p>
</div>
</div>
<ul className="item-list join-waitlist-panel__list">
{joins.map((join) => (
<li key={join.join_id} className="list-item card-list-item">
<div className="list-item-main">
<strong>{join.title}</strong>
<p className="muted list-item-sub">
Wartet auf:{' '}
{(join.pending_inputs || [])
.map((input) =>
input.strand_title
? `${input.strand_title} / ${input.title}`
: input.title,
)
.join(' · ')}
</p>
</div>
</li>
))}
</ul>
</section>
)
}
@@ -0,0 +1,122 @@
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { MILESTONE_STATUS_LABELS } from '../constants/status.js'
import { listInitiativeRoadmapCriteriaProgress } from '../api/roadmap.js'
import { gatePath, scopedPath } from '../utils/routes.js'
import { EmptyState } from './EmptyState.jsx'
export function MaturityStagePanel({
initiativeId,
roadmapItems = [],
embedded = true,
}) {
const [criteriaProgress, setCriteriaProgress] = useState({})
const stages = [...roadmapItems]
.filter((item) => item.item_type === 'maturity_stage')
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
const activeStages = stages.filter((s) => s.status === 'active')
const activeStage = activeStages[0]
useEffect(() => {
if (!initiativeId) return undefined
let cancelled = false
listInitiativeRoadmapCriteriaProgress(initiativeId)
.then((data) => {
if (!cancelled) setCriteriaProgress(data || {})
})
.catch(() => {
if (!cancelled) setCriteriaProgress({})
})
return () => {
cancelled = true
}
}, [initiativeId, roadmapItems.length])
const activeProgress = activeStage ? criteriaProgress[activeStage.id] : null
const body =
stages.length === 0 ? (
<EmptyState message="Noch keine Reifegrad-Stufen — unter Plan anlegen oder Starter-Kit nutzen." />
) : (
<>
{activeStages.length > 0 && (
<>
<p className="maturity-stage-active muted">
Aktive Gate(s):{' '}
{activeStages.map((stage, index) => (
<span key={stage.id}>
{index > 0 ? ' · ' : ''}
<Link to={gatePath(stage.id)} className="link-inline">
<strong>{stage.title}</strong>
</Link>
</span>
))}
</p>
{activeStage && activeProgress && (
<p className="maturity-stage-progress muted">
Gate-Fortschritt:{' '}
<strong>
{activeProgress.closed ?? 0} / {activeProgress.total ?? 0}
</strong>{' '}
Kriterien erfüllt
{(activeProgress.open ?? 0) > 0 && (
<span> · {activeProgress.open} offen</span>
)}
</p>
)}
</>
)}
<ol className="item-list maturity-stage-list">
{stages.map((stage, index) => (
<li
key={stage.id}
className={
'list-item card-list-item maturity-stage-item' +
(stage.status === 'active' ? ' maturity-stage-item--active' : '') +
(stage.status === 'reached' ? ' maturity-stage-item--reached' : '')
}
>
<span className="maturity-stage-item__index muted">{index + 1}</span>
<div className="list-item-main">
<Link to={gatePath(stage.id)} className="list-item-link">
<strong>{stage.title}</strong>
</Link>
<span className="muted list-item-sub">
{MILESTONE_STATUS_LABELS[stage.status] || stage.status}
</span>
</div>
</li>
))}
</ol>
<p className="muted maturity-stage-hint">
Kriterien und Verify am{' '}
<Link to={scopedPath('/plan/gates', { initiativeId })} className="link-inline">
Plan → Stufen
</Link>
; Übung unter{' '}
<Link to={scopedPath('/work/today', { initiativeId })} className="link-inline">
Ausführen → Heute
</Link>
.
</p>
</>
)
if (!embedded) return body
return (
<section className="card maturity-stage-panel">
<div className="section-header">
<div>
<h2>Reifegrad-Stufen</h2>
<p className="section-lead muted">
Aktive Stufe, Gate-Fortschritt und Orientierung — Steuerungshorizont (A1).
</p>
</div>
</div>
{body}
</section>
)
}
@@ -0,0 +1,110 @@
import { Link } from 'react-router-dom'
import { RECURRING_STATUS_LABELS } from '../constants/status.js'
import { EmptyState } from './EmptyState.jsx'
import { scopedPath } from '../utils/routes.js'
function formatDueAt(iso) {
if (!iso) return null
try {
return new Date(iso).toLocaleString('de-DE')
} catch {
return iso
}
}
function activeMaturityStages(roadmapItems = []) {
return [...roadmapItems]
.filter((item) => item.item_type === 'maturity_stage' && item.status === 'active')
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
}
function practicesForStage(recurringItems = [], stageId) {
if (!stageId) {
return (recurringItems || []).filter((item) => item.roadmap_item_id)
}
return (recurringItems || []).filter((item) => item.roadmap_item_id === stageId)
}
export function RecurringRhythmPanel({
initiativeId,
roadmapItems = [],
recurringItems = [],
canManage = false,
embedded = true,
}) {
const stages = activeMaturityStages(roadmapItems)
const stagePractices = stages.flatMap((stage) =>
practicesForStage(recurringItems, stage.id),
)
const active = stagePractices.filter((item) => item.status === 'active')
const paused = stagePractices.filter((item) => item.status === 'paused')
const body =
stages.length === 0 ? (
<EmptyState message="Keine aktiven Work-Gates — Plan → Struktur prüfen." />
) : stagePractices.length === 0 ? (
<EmptyState message="Keine Übungen auf aktiven Gates — Starter-Kit oder Join prüfen." />
) : (
<>
<p className="recurring-rhythm-summary muted">
{stages.length} aktive Gate(s) — {active.length} Übung(en) aktiv
{paused.length > 0 ? `, ${paused.length} pausiert` : ''}.
</p>
<ul className="item-list recurring-rhythm-list">
{[...active, ...paused].map((item) => (
<li
key={item.id}
className={
'list-item card-list-item recurring-rhythm-item' +
(item.status === 'active' ? ' recurring-rhythm-item--active' : '') +
(item.today_completed ? ' recurring-rhythm-item--done-today' : '')
}
>
<div className="list-item-main">
<strong>{item.title}</strong>
<span className="muted list-item-sub">
{RECURRING_STATUS_LABELS[item.status] || item.status}
{item.today_completed ? ' · heute erledigt' : ''}
{!item.today_completed && item.next_due_at
? ` · Fällig: ${formatDueAt(item.next_due_at)}`
: ''}
</span>
{item.today_measurement_note && (
<span className="muted list-item-sub">Messwert: {item.today_measurement_note}</span>
)}
</div>
</li>
))}
</ul>
<p className="muted recurring-rhythm-hint">
{canManage
? 'Übungen anlegen und Rhythmus pflegen am '
: 'Übungen am '}
<Link to={scopedPath('/plan/gates', { initiativeId })} className="link-inline">
Zielzustand (Gate-Detail)
</Link>
{' '}— Activity Set pro Gate. Heute erledigen unter{' '}
<Link to={scopedPath('/work/today', { initiativeId })} className="link-inline">
Ausführen → Today
</Link>
.
</p>
</>
)
if (!embedded) return body
return (
<section className="card recurring-rhythm-panel">
<div className="section-header">
<div>
<h2>Übungen der aktiven Gates</h2>
<p className="section-lead muted">
Activity Sets aller aktiven Work-Gates — Join-Knoten haben keine Übungen (A1).
</p>
</div>
</div>
{body}
</section>
)
}
@@ -44,6 +44,12 @@ export function RecurringSection({ items, canManage, onCreate, onUpdateStatus, o
)} )}
</div> </div>
<p className="muted form-hint">
Für Reifegrad-Vorhaben (A1): Übungen am{' '}
<strong>Zielzustand (Gate-Detail)</strong> anlegen — dort Activity Set mit Rhythmus.
Diese Liste ist für initiative-weite Elemente ohne Gate-Bezug.
</p>
{showForm && canManage && ( {showForm && canManage && (
<form className="inline-form-block" onSubmit={handleSubmit}> <form className="inline-form-block" onSubmit={handleSubmit}>
<label> <label>
+41 -11
View File
@@ -1,10 +1,11 @@
import { useState } from 'react'
import { import {
MILESTONE_STATUSES, MILESTONE_STATUSES,
MILESTONE_STATUS_LABELS, MILESTONE_STATUS_LABELS,
ROADMAP_ITEM_TYPES_FOR_DESIGNER,
ROADMAP_ITEM_TYPE_LABELS, ROADMAP_ITEM_TYPE_LABELS,
} from '../constants/status.js' } from '../constants/status.js'
const ITEM_TYPES = ['milestone', 'review_gate', 'maturity_stage']
const EDITABLE_STATUSES = MILESTONE_STATUSES.filter( const EDITABLE_STATUSES = MILESTONE_STATUSES.filter(
(s) => !['reached', 'moved', 'discarded'].includes(s), (s) => !['reached', 'moved', 'discarded'].includes(s),
) )
@@ -17,6 +18,9 @@ export function RoadmapItemForm({
submitLabel = 'Anlegen', submitLabel = 'Anlegen',
mode = 'create', mode = 'create',
}) { }) {
const [itemType, setItemType] = useState(initial.item_type || 'milestone')
const isJoinGate = itemType === 'join_gate'
async function handleSubmit(e) { async function handleSubmit(e) {
e.preventDefault() e.preventDefault()
const form = e.target const form = e.target
@@ -27,7 +31,7 @@ export function RoadmapItemForm({
item_type: form.item_type.value, item_type: form.item_type.value,
sequencing_mode: initial.sequencing_mode || 'sequential', sequencing_mode: initial.sequencing_mode || 'sequential',
} }
if (mode === 'create') { if (mode === 'create' && !isJoinGate) {
const initialCriterion = form.initial_criterion_title?.value?.trim() const initialCriterion = form.initial_criterion_title?.value?.trim()
if (initialCriterion) { if (initialCriterion) {
payload.initial_criterion_title = initialCriterion payload.initial_criterion_title = initialCriterion
@@ -40,19 +44,36 @@ export function RoadmapItemForm({
} }
const statusLocked = ['reached', 'moved', 'discarded'].includes(initial.status) const statusLocked = ['reached', 'moved', 'discarded'].includes(initial.status)
const showTypeField = mode === 'create' || (mode === 'edit' && !statusLocked)
return ( return (
<form className="form workspace-form roadmap-item-form" onSubmit={handleSubmit}> <form className="form workspace-form roadmap-item-form" onSubmit={handleSubmit}>
{mode === 'create' && ( {showTypeField && (
<label> <label>
Typ Typ
<select name="item_type" defaultValue={initial.item_type || 'milestone'}> <select
{ITEM_TYPES.map((t) => ( name="item_type"
value={itemType}
onChange={(e) => setItemType(e.target.value)}
disabled={statusLocked}
>
{ROADMAP_ITEM_TYPES_FOR_DESIGNER.map((t) => (
<option key={t} value={t}> <option key={t} value={t}>
{ROADMAP_ITEM_TYPE_LABELS[t] || t} {ROADMAP_ITEM_TYPE_LABELS[t] || t}
</option> </option>
))} ))}
</select> </select>
{isJoinGate && (
<span className="muted form-hint">
Schaltknoten: sammelt Eingänge (AND) und schaltet Ausgänge — keine Übungen, kein
manuelles Verify.
</span>
)}
{mode === 'edit' && !isJoinGate && initial.item_type === 'join_gate' && (
<span className="muted form-hint">
Beim Wechsel von Join zu Gate: Checkliste auf der Detailseite ergänzen.
</span>
)}
</label> </label>
)} )}
<label> <label>
@@ -62,7 +83,9 @@ export function RoadmapItemForm({
defaultValue={initial.title || ''} defaultValue={initial.title || ''}
maxLength={255} maxLength={255}
required required
placeholder="z. B. MVP nutzbar im Alltag" placeholder={
isJoinGate ? 'z. B. Integration abgeschlossen' : 'z. B. MVP nutzbar im Alltag'
}
disabled={statusLocked} disabled={statusLocked}
/> />
</label> </label>
@@ -72,14 +95,20 @@ export function RoadmapItemForm({
name="goal_description" name="goal_description"
rows={3} rows={3}
defaultValue={initial.goal_description || ''} defaultValue={initial.goal_description || ''}
placeholder="Kurzer Kontext — prüfbare Akzeptanz legst du als Kriterien an." placeholder={
isJoinGate
? 'Konsolidierter Meilenstein — welche Pfade laufen hier zusammen?'
: 'Kurzer Kontext — prüfbare Akzeptanz legst du als Kriterien an.'
}
disabled={statusLocked} disabled={statusLocked}
/> />
<span className="muted form-hint"> {!isJoinGate && (
Die Checkliste auf der Gate-Detailseite ist führend für Verify. <span className="muted form-hint">
</span> Die Checkliste auf der Gate-Detailseite ist führend für Verify.
</span>
)}
</label> </label>
{mode === 'create' && ( {mode === 'create' && !isJoinGate && (
<label> <label>
Erstes Kriterium (optional) Erstes Kriterium (optional)
<input <input
@@ -104,6 +133,7 @@ export function RoadmapItemForm({
<p className="muted form-hint"> <p className="muted form-hint">
Reihenfolge und Parallelität steuerst du über Kanten auf der Gate-Detailseite — nicht mehr Reihenfolge und Parallelität steuerst du über Kanten auf der Gate-Detailseite — nicht mehr
über ein Abfolge-Feld. über ein Abfolge-Feld.
{isJoinGate && ' Eingänge: Join → Work-Gate (requires). Ausgänge: Work-Gate → Join.'}
</p> </p>
{mode === 'edit' && ( {mode === 'edit' && (
<label> <label>
+144
View File
@@ -0,0 +1,144 @@
import { useMemo, useState } from 'react'
import {
INTERVAL_PRESETS,
WEEKDAY_OPTIONS,
defaultScheduleValue,
detectIntervalPreset,
scheduleFromApi,
toggleWeekdayMask,
weekdayBitForDate,
} from '../utils/scheduleUtils.js'
export function ScheduleEditor({
value,
onChange,
disabled = false,
compact = false,
}) {
const current = value || defaultScheduleValue()
const [preset, setPreset] = useState(() =>
current.schedule_kind === 'weekdays'
? 'weekdays'
: detectIntervalPreset(current.interval_days),
)
const showCustomInterval = preset === 'custom'
function setKind(kind) {
if (kind === 'weekdays') {
onChange({
...current,
schedule_kind: 'weekdays',
weekday_mask: current.weekday_mask || weekdayBitForDate(),
})
setPreset('weekdays')
return
}
const presetDef = INTERVAL_PRESETS.find((p) => p.id === kind) || INTERVAL_PRESETS[0]
onChange({
...current,
schedule_kind: 'interval',
interval_days: presetDef.intervalDays || current.interval_days || 1,
})
setPreset(kind)
}
const weekdaySummary = useMemo(() => {
const selected = WEEKDAY_OPTIONS.filter((d) => (current.weekday_mask || 0) & d.bit)
return selected.map((d) => d.label).join(', ')
}, [current.weekday_mask])
return (
<fieldset className={`schedule-editor${compact ? ' schedule-editor--compact' : ''}`} disabled={disabled}>
<legend className="schedule-editor__legend">Rhythmus</legend>
<div className="schedule-editor__modes" role="group" aria-label="Rhythmus-Art">
<button
type="button"
className={`btn btn-sm ${preset === 'weekdays' ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => setKind('weekdays')}
>
Wochentage
</button>
{INTERVAL_PRESETS.filter((p) => p.id !== 'custom').map((p) => (
<button
key={p.id}
type="button"
className={`btn btn-sm ${preset === p.id ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => setKind(p.id)}
>
{p.label}
</button>
))}
<button
type="button"
className={`btn btn-sm ${preset === 'custom' ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => setKind('custom')}
>
Individuell
</button>
</div>
{current.schedule_kind === 'interval' && showCustomInterval && (
<label className="schedule-editor__field">
Alle wie viele Tage?
<input
type="number"
min={1}
value={current.interval_days}
onChange={(e) =>
onChange({ ...current, interval_days: Number.parseInt(e.target.value, 10) || 1 })
}
/>
</label>
)}
{current.schedule_kind === 'weekdays' && (
<div className="schedule-editor__weekdays">
<p className="muted schedule-editor__hint">
Immer an diesen Tagen — nach Erledigen bleibt der Wochentag.
{weekdaySummary ? ` (${weekdaySummary})` : ''}
</p>
<div className="schedule-editor__weekday-row">
{WEEKDAY_OPTIONS.map((day) => {
const active = Boolean((current.weekday_mask || 0) & day.bit)
return (
<label key={day.bit} className={`schedule-weekday${active ? ' is-active' : ''}`}>
<input
type="checkbox"
checked={active}
onChange={() =>
onChange({
...current,
weekday_mask: toggleWeekdayMask(current.weekday_mask || 0, day.bit),
})
}
/>
{day.label}
</label>
)
})}
</div>
</div>
)}
<label className="schedule-editor__field">
Pause bis (optional)
<input
type="date"
value={current.pause_until || ''}
onChange={(e) => onChange({ ...current, pause_until: e.target.value })}
/>
</label>
</fieldset>
)
}
export function scheduleEditorFromPractice(practice) {
return scheduleFromApi(practice?.schedule || {
schedule_kind: 'interval',
interval_days: practice?.interval_days || 1,
weekday_mask: 0,
pause_until: null,
})
}
@@ -0,0 +1,179 @@
import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { completeRecurringPractice } from '../api/recurring.js'
import { EmptyState } from './EmptyState.jsx'
import { scopedPath } from '../utils/routes.js'
import { isPracticeDueToday } from '../utils/scheduleUtils.js'
function formatDue(iso) {
if (!iso) return null
try {
return new Date(iso).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
} catch {
return iso
}
}
function activeWorkGates(roadmapItems = []) {
return [...roadmapItems]
.filter((item) => item.item_type === 'maturity_stage' && item.status === 'active')
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
}
function exercisesForGate(recurringItems = [], gateId) {
return (recurringItems || []).filter(
(item) =>
item.status === 'active' &&
item.roadmap_item_id === gateId &&
isPracticeDueToday(item),
)
}
function ExerciseRow({ exercise, canManage, busy, onCompleted }) {
const [measurement, setMeasurement] = useState('')
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState(null)
const completedToday = Boolean(exercise.today_completed)
const savedNote = exercise.today_measurement_note
async function handleComplete(e) {
e.preventDefault()
if (!canManage || submitting || completedToday) return
setSubmitting(true)
setError(null)
try {
await completeRecurringPractice(exercise.id, {
measurement_note: measurement.trim() || undefined,
})
setMeasurement('')
await onCompleted?.()
} catch (err) {
setError(err.message)
} finally {
setSubmitting(false)
}
}
return (
<li className="list-item card-list-item work-today-practice__item">
<div className="list-item-main">
<strong>{exercise.title}</strong>
{exercise.description && (
<p className="muted list-item-sub">{exercise.description}</p>
)}
{completedToday ? (
<p className="work-today-practice__done muted">
Heute erledigt
{savedNote ? ` — ${savedNote}` : ''}
</p>
) : (
exercise.open_cadence_instance?.due_at && (
<p className="muted list-item-sub">
Fällig: {formatDue(exercise.open_cadence_instance.due_at)}
</p>
)
)}
</div>
{canManage && !completedToday && (
<form className="inline-form-block work-today-practice__form" onSubmit={handleComplete}>
<label>
Messwert / Notiz (optional)
<input
value={measurement}
onChange={(e) => setMeasurement(e.target.value)}
placeholder="z. B. 45°, 3×30 Sek."
maxLength={2000}
/>
</label>
{error && <p className="error">{error}</p>}
<button type="submit" className="btn btn-primary btn-sm" disabled={submitting || busy}>
{submitting ? 'Speichern …' : 'Heute erledigt'}
</button>
</form>
)}
</li>
)
}
/**
* A1 — Heutige Übungen aller aktiven Work-Gates, gruppiert nach Gate.
*/
export function WorkTodayPracticePanel({
initiativeId,
roadmapItems = [],
recurringItems = [],
canManage = false,
onCompleted,
busy = false,
}) {
const gates = useMemo(() => activeWorkGates(roadmapItems), [roadmapItems])
const grouped = useMemo(() => {
return gates.map((gate) => ({
gate,
exercises: exercisesForGate(recurringItems, gate.id),
}))
}, [gates, recurringItems])
const todayExercises = grouped.flatMap((group) => group.exercises)
const pending = todayExercises.filter((item) => !item.today_completed)
const allDone = todayExercises.length > 0 && pending.length === 0
return (
<section className="card work-today-practice" id="today-practice">
<div className="section-header">
<div>
<h2>Heutige Übungen</h2>
<p className="section-lead muted">
{gates.length > 0
? `${gates.length} aktive Gate(s) — nur heute fällige Übungen, optional Messwert.`
: 'Tages-Tracking für aktive Work-Gates.'}
</p>
</div>
</div>
{todayExercises.length === 0 ? (
<EmptyState message={
gates.length === 0
? 'Keine Übungen auf aktiven Gates — Starter-Kit oder Join-Fortschritt prüfen.'
: 'Heute keine fälligen Übungen.'
} />
) : (
<>
{allDone && (
<p className="work-today-practice__all-done muted">
Alle Übungen für heute erledigt — nächste Fälligkeit laut Rhythmus.
</p>
)}
{grouped.map(({ gate, exercises }) =>
exercises.length === 0 ? null : (
<div key={gate.id} className="work-today-practice__strand">
<h3 className="work-today-practice__strand-title">{gate.title}</h3>
<ul className="item-list work-today-practice__list">
{exercises.map((exercise) => (
<ExerciseRow
key={exercise.id}
exercise={exercise}
canManage={canManage}
busy={busy}
onCompleted={onCompleted}
/>
))}
</ul>
</div>
),
)}
</>
)}
<p className="muted work-today-practice__hint">
Übungen verwalten unter{' '}
<Link to={scopedPath('/control/journey', { initiativeId })} className="link-inline">
Kontrolle → Journey
</Link>
.
</p>
</section>
)
}
@@ -25,24 +25,36 @@ export function InitiativeCompositionSurface({
() => ({ () => ({
initiativeId: ops.initiativeId, initiativeId: ops.initiativeId,
actions: ops.actions, actions: ops.actions,
roadmapItems: ops.roadmapItems,
recurringItems: ops.recurringItems,
steeringSnapshotLoading: ops.steeringSnapshotLoading, steeringSnapshotLoading: ops.steeringSnapshotLoading,
steeringSnapshotError: ops.steeringSnapshotError, steeringSnapshotError: ops.steeringSnapshotError,
steeringMethods: ops.steeringMethods, steeringMethods: ops.steeringMethods,
handleMethodChange: ops.handleMethodChange, handleMethodChange: ops.handleMethodChange,
methodBusy: ops.methodBusy, methodBusy: ops.methodBusy,
formBusy: ops.formBusy, formBusy: ops.formBusy,
activeWorkCycle: ops.activeWorkCycle,
uiFeatures: ops.uiFeatures,
dataSlices: ops.dataSlices,
onAcceptBacklogProposal, onAcceptBacklogProposal,
refreshOm: ops.refreshOm,
}), }),
[ [
ops.initiativeId, ops.initiativeId,
ops.actions, ops.actions,
ops.roadmapItems,
ops.recurringItems,
ops.steeringSnapshotLoading, ops.steeringSnapshotLoading,
ops.steeringSnapshotError, ops.steeringSnapshotError,
ops.steeringMethods, ops.steeringMethods,
ops.handleMethodChange, ops.handleMethodChange,
ops.methodBusy, ops.methodBusy,
ops.formBusy, ops.formBusy,
ops.activeWorkCycle,
ops.uiFeatures,
ops.dataSlices,
onAcceptBacklogProposal, onAcceptBacklogProposal,
ops.refreshOm,
], ],
) )
@@ -0,0 +1,113 @@
import { useInitiativeOperations } from '../context/InitiativeOperationsContext.jsx'
import { InitiativeActionsHub } from '../components/InitiativeActionsHub.jsx'
import { EmptyState } from '../components/EmptyState.jsx'
import { PRODUCT_TERMS, actionCountLabel } from '../constants/productLanguage.js'
/**
* Composition-Provider: committete Arbeitspakete als Drill-down (nicht Hauptbild).
* @param {{ variant?: 'today' | 'sprint' | 'sprint-product', defaultCollapsed?: boolean }} props
*/
export function WorkActionsPanel({ variant = 'today', defaultCollapsed = true }) {
const ops = useInitiativeOperations()
const {
initiativeId,
actions,
visibleActions,
sprintActions,
activeWorkCycle,
uiFeatures,
dataSlices,
projects,
roadmapItems,
actionContextById,
hideDone,
setHideDone,
showActionForm,
setShowActionForm,
editingActionId,
setEditingActionId,
formBusy,
actors,
actorsLoading,
actorsError,
actorsUsedFallback,
reloadActors,
handleCreateAction,
handleUpdateAction,
handleQuickStatus,
handleCreateBlockerForAction,
handleMoveActionToSprint,
handleUnplanAction,
capabilities,
workCycles,
} = ops
const supportsWorkCycles = dataSlices.includes('work_cycles')
const isProductMode = uiFeatures.continuousProductWorkMode && supportsWorkCycles
let panelActions = visibleActions
let sectionTitle = PRODUCT_TERMS.actionPlural
let sectionLead =
'Committete operative Einheit — nur bei Bedarf die volle Liste öffnen.'
if (variant === 'sprint' && activeWorkCycle) {
panelActions = sprintActions
sectionTitle = PRODUCT_TERMS.sprintBacklog
sectionLead = `Arbeitspakete im ${PRODUCT_TERMS.workCycle} „${activeWorkCycle.title}“.`
} else if (variant === 'sprint-product' && isProductMode && !activeWorkCycle) {
panelActions = visibleActions
sectionTitle = `Committete ${PRODUCT_TERMS.actionPlural}`
sectionLead = `Ohne aktiven ${PRODUCT_TERMS.workCycle} — Product-Ist im Vorhaben.`
} else if (variant === 'sprint' && !activeWorkCycle && !isProductMode) {
return (
<EmptyState
message={`${PRODUCT_TERMS.sprintBacklog} ist für diesen Vorhabentyp nicht verfügbar.`}
/>
)
}
const openCount = panelActions.filter((a) => a.status !== 'done' && a.status !== 'discarded').length
const expandLabel =
openCount > 0
? `${actionCountLabel(openCount)} anzeigen`
: `Alle ${PRODUCT_TERMS.actionPlural} anzeigen`
return (
<InitiativeActionsHub
initiativeId={initiativeId}
actions={panelActions}
projects={projects}
roadmapItems={roadmapItems}
actionContextById={actionContextById}
hideDone={hideDone}
onHideDoneChange={setHideDone}
showForm={showActionForm}
onToggleForm={() => setShowActionForm((v) => !v)}
editingActionId={editingActionId}
onEditAction={setEditingActionId}
onCancelEdit={() => setEditingActionId(null)}
onCreateAction={handleCreateAction}
onUpdateAction={handleUpdateAction}
onQuickStatus={handleQuickStatus}
onCreateBlockerForAction={handleCreateBlockerForAction}
onMoveToSprint={handleMoveActionToSprint}
onUnplanToBacklog={handleUnplanAction}
canManage={capabilities.has('kairo.action.manage')}
canManageBlocker={capabilities.has('kairo.blocker.manage')}
formBusy={formBusy}
actors={actors}
actorsLoading={actorsLoading}
actorsError={actorsError}
actorsUsedFallback={actorsUsedFallback}
onReloadActors={reloadActors}
workCycles={workCycles}
activeWorkCycle={activeWorkCycle}
allActions={actions}
sectionTitle={sectionTitle}
sectionLead={sectionLead}
collapsible
defaultCollapsed={defaultCollapsed}
expandLabel={expandLabel}
/>
)
}
@@ -22,6 +22,7 @@ import { WIDGETS } from '../registry/widgetRegistry.js'
* @property {string} [proposalKey] * @property {string} [proposalKey]
* @property {string} [widgetKey] * @property {string} [widgetKey]
* @property {string} [predicateKey] * @property {string} [predicateKey]
* @property {string} [workActionsVariant]
*/ */
const WIDGET_PROVIDERS = WIDGETS.filter((w) => w.area === 'workspace').map((widget) => ({ const WIDGET_PROVIDERS = WIDGETS.filter((w) => w.area === 'workspace').map((widget) => ({
@@ -57,11 +58,51 @@ export const COMPOSITION_PROVIDERS = [
scopeTypes: ['initiative'], scopeTypes: ['initiative'],
order: 10, order: 10,
}, },
{
key: 'steering.join_waitlist',
kind: 'steering_element',
steeringElement: 'maturity_stage',
slotKeys: ['control.status.steering'],
componentKey: 'JoinWaitlistPanel',
requiresCapability: 'kairo.initiative.read',
scopeTypes: ['initiative'],
order: 14,
},
{
key: 'steering.maturity_stage',
kind: 'steering_element',
steeringElement: 'maturity_stage',
slotKeys: ['control.status.steering'],
componentKey: 'MaturityStagePanel',
requiresCapability: 'kairo.initiative.read',
scopeTypes: ['initiative'],
order: 15,
},
{
key: 'steering.recurring_rhythm',
kind: 'steering_element',
steeringElement: 'recurring_rhythm',
slotKeys: ['control.status.steering'],
componentKey: 'RecurringRhythmPanel',
requiresCapability: 'kairo.initiative.read',
scopeTypes: ['initiative'],
order: 16,
},
{
key: 'work.practice.today',
kind: 'steering_element',
steeringElement: 'recurring_rhythm',
slotKeys: ['work.today.primary'],
componentKey: 'WorkTodayPracticePanel',
requiresCapability: 'kairo.recurring.read',
scopeTypes: ['initiative'],
order: 5,
},
{ {
key: 'steering.next_action', key: 'steering.next_action',
kind: 'steering_element', kind: 'steering_element',
steeringElement: 'next_action_primary', steeringElement: 'next_action_primary',
slotKeys: ['control.status.steering'], slotKeys: ['control.status.steering', 'work.today.primary', 'work.sprint.primary'],
componentKey: 'NextActionWidget', componentKey: 'NextActionWidget',
requiresCapability: 'kairo.workspace.read', requiresCapability: 'kairo.workspace.read',
scopeTypes: ['initiative'], scopeTypes: ['initiative'],
@@ -117,6 +158,40 @@ export const COMPOSITION_PROVIDERS = [
scopeTypes: ['initiative'], scopeTypes: ['initiative'],
order: 0, order: 0,
}, },
// —— Work / Ausführen (AP1.9d — Drill-down, kein Todo-Wand-Hauptbild) ——
{
key: 'work.actions.today',
kind: 'core',
slotKeys: ['work.today.actions'],
componentKey: 'WorkActionsPanel',
workActionsVariant: 'today',
requiresCapability: 'kairo.action.read',
scopeTypes: ['initiative'],
order: 0,
},
{
key: 'work.actions.sprint',
kind: 'conditional',
predicateKey: 'hasActiveWorkCycle',
slotKeys: ['work.sprint.backlog'],
componentKey: 'WorkActionsPanel',
workActionsVariant: 'sprint',
requiresCapability: 'kairo.action.read',
scopeTypes: ['initiative'],
order: 0,
},
{
key: 'work.actions.sprint_product',
kind: 'conditional',
predicateKey: 'isProductWithoutActiveSprint',
slotKeys: ['work.sprint.backlog'],
componentKey: 'WorkActionsPanel',
workActionsVariant: 'sprint-product',
requiresCapability: 'kairo.action.read',
scopeTypes: ['initiative'],
order: 5,
},
] ]
/** /**
@@ -2,9 +2,14 @@ import { Link } from 'react-router-dom'
import { scopedPath } from '../utils/routes.js' import { scopedPath } from '../utils/routes.js'
import { SteeringSnapshotPanel } from '../components/SteeringSnapshotPanel.jsx' import { SteeringSnapshotPanel } from '../components/SteeringSnapshotPanel.jsx'
import { CriticalPathPanel } from '../components/CriticalPathPanel.jsx' import { CriticalPathPanel } from '../components/CriticalPathPanel.jsx'
import { JoinWaitlistPanel } from '../components/JoinWaitlistPanel.jsx'
import { MaturityStagePanel } from '../components/MaturityStagePanel.jsx'
import { RecurringRhythmPanel } from '../components/RecurringRhythmPanel.jsx'
import { AgentSlotsPanel } from '../components/AgentSlotsPanel.jsx' import { AgentSlotsPanel } from '../components/AgentSlotsPanel.jsx'
import { SteeringProposalsPanel } from '../components/SteeringProposalsPanel.jsx' import { SteeringProposalsPanel } from '../components/SteeringProposalsPanel.jsx'
import { NextActionWidget } from '../widgets/NextActionWidget.jsx' import { NextActionWidget } from '../widgets/NextActionWidget.jsx'
import { WorkTodayPracticePanel } from '../components/WorkTodayPracticePanel.jsx'
import { WorkActionsPanel } from './WorkActionsPanel.jsx'
/** Roadblocker-Strip — extrahiert aus InitiativeOverviewPage für Composition. */ /** Roadblocker-Strip — extrahiert aus InitiativeOverviewPage für Composition. */
export function RoadblockersStrip({ initiativeId, actionsBlocked = 0, blockersOpen = 0 }) { export function RoadblockersStrip({ initiativeId, actionsBlocked = 0, blockersOpen = 0 }) {
@@ -34,11 +39,16 @@ export function WidgetHost({ widget }) {
export const PROVIDER_COMPONENTS = { export const PROVIDER_COMPONENTS = {
SteeringSnapshotPanel, SteeringSnapshotPanel,
CriticalPathPanel, CriticalPathPanel,
MaturityStagePanel,
RecurringRhythmPanel,
NextActionWidget, NextActionWidget,
AgentSlotsPanel, AgentSlotsPanel,
SteeringProposalsPanel, SteeringProposalsPanel,
RoadblockersStrip, RoadblockersStrip,
WidgetHost, WidgetHost,
WorkActionsPanel,
WorkTodayPracticePanel,
JoinWaitlistPanel,
} }
/** /**
@@ -33,6 +33,25 @@ const CONDITIONAL_PREDICATES = {
const counts = ctx.steeringSnapshot?.counts || {} const counts = ctx.steeringSnapshot?.counts || {}
return (counts.actions_blocked || 0) > 0 || (counts.blockers_open || 0) > 0 return (counts.actions_blocked || 0) > 0 || (counts.blockers_open || 0) > 0
}, },
hasActiveWorkCycle(ctx) {
const cycle =
ctx.steeringSnapshot?.active_work_cycle
|| ctx.opsContext?.activeWorkCycle
|| null
return Boolean(cycle?.id)
},
isProductWithoutActiveSprint(ctx) {
if (CONDITIONAL_PREDICATES.hasActiveWorkCycle(ctx)) return false
const features =
ctx.operatingContext?.ui_features
|| ctx.opsContext?.uiFeatures
|| {}
const slices =
ctx.operatingContext?.data_slices
|| ctx.opsContext?.dataSlices
|| []
return Boolean(features.continuousProductWorkMode && slices.includes('work_cycles'))
},
} }
/** /**
@@ -77,7 +96,14 @@ function resolveAgentSlots(input) {
* @param {object | null | undefined} steeringSnapshot * @param {object | null | undefined} steeringSnapshot
*/ */
export function resolveNextActionUi(elements, steeringSnapshot) { export function resolveNextActionUi(elements, steeringSnapshot) {
const priority = ['critical_path', 'work_cycle_scope', 'gate_fulfillment', 'queue_inbox'] const priority = [
'critical_path',
'recurring_rhythm',
'work_cycle_scope',
'maturity_stage',
'gate_fulfillment',
'queue_inbox',
]
const hasActiveSprint = Boolean(steeringSnapshot?.active_work_cycle) const hasActiveSprint = Boolean(steeringSnapshot?.active_work_cycle)
for (const key of priority) { for (const key of priority) {
if (key === 'work_cycle_scope' && !hasActiveSprint) continue if (key === 'work_cycle_scope' && !hasActiveSprint) continue
@@ -165,6 +191,35 @@ export function buildProviderProps(provider, input) {
scopeRoadmapItemId: kernel?.horizon?.gate_roadmap_item_id ?? null, scopeRoadmapItemId: kernel?.horizon?.gate_roadmap_item_id ?? null,
} }
} }
case 'MaturityStagePanel':
return {
initiativeId: ops.initiativeId,
roadmapItems: ops.roadmapItems || [],
}
case 'RecurringRhythmPanel':
return {
initiativeId: ops.initiativeId,
roadmapItems: ops.roadmapItems || [],
recurringItems: ops.recurringItems || [],
canManage: capabilities.has('kairo.recurring.manage'),
}
case 'JoinWaitlistPanel':
return {
progressionState: input.steeringSnapshot?.progression_state ?? null,
}
case 'WorkTodayPracticePanel':
return {
initiativeId: ops.initiativeId,
roadmapItems: ops.roadmapItems || [],
recurringItems: ops.recurringItems || [],
canManage: capabilities.has('kairo.recurring.manage'),
busy: ops.formBusy,
onCompleted: async () => {
if (typeof ops.refreshOm === 'function') {
await ops.refreshOm(['recurring', 'steering_snapshot'])
}
},
}
case 'NextActionWidget': { case 'NextActionWidget': {
const nextActionUi = resolveNextActionUi(elements, input.steeringSnapshot) const nextActionUi = resolveNextActionUi(elements, input.steeringSnapshot)
return { return {
@@ -204,6 +259,11 @@ export function buildProviderProps(provider, input) {
const widget = getWidgetByKey(provider.widgetKey) const widget = getWidgetByKey(provider.widgetKey)
return { widget } return { widget }
} }
case 'WorkActionsPanel':
return {
variant: provider.workActionsVariant || 'today',
defaultCollapsed: true,
}
default: default:
return {} return {}
} }
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { COMPOSITION_PROVIDERS } from './compositionProviders.js' import { COMPOSITION_PROVIDERS } from './compositionProviders.js'
import { import {
resolveSteeringComposition, resolveSteeringComposition,
@@ -18,6 +18,8 @@ describe('uiSlotRegistry', () => {
it('defines MVP surfaces', () => { it('defines MVP surfaces', () => {
expect(COMPOSITION_SURFACES['control.status']).toBeTruthy() expect(COMPOSITION_SURFACES['control.status']).toBeTruthy()
expect(COMPOSITION_SURFACES['plan.inbox']).toBeTruthy() expect(COMPOSITION_SURFACES['plan.inbox']).toBeTruthy()
expect(COMPOSITION_SURFACES['work.today']).toBeTruthy()
expect(COMPOSITION_SURFACES['work.sprint']).toBeTruthy()
expect(COMPOSITION_SURFACES.cockpit).toBeTruthy() expect(COMPOSITION_SURFACES.cockpit).toBeTruthy()
}) })
@@ -215,7 +217,33 @@ describe('resolveSteeringComposition', () => {
expect(props.scopeRoadmapItemId).toBe('gate-1') expect(props.scopeRoadmapItemId).toBe('gate-1')
}) })
it('buildProviderProps gates milestone horizon in snapshot panel', () => { it('activates maturity panels for A1 on control.status', () => {
const result = resolveSteeringComposition({
surfaceKey: 'control.status',
scope: 'initiative',
capabilities: CAPS,
steeringElements: ['next_action_primary', 'maturity_stage', 'recurring_rhythm'],
steeringSnapshot: { counts: {}, next_actions: [] },
opsContext: { initiativeId: 'init-1', roadmapItems: [], recurringItems: [] },
})
const steering = result.slots['control.status.steering'] || []
expect(steering.some((p) => p.key === 'steering.maturity_stage')).toBe(true)
expect(steering.some((p) => p.key === 'steering.recurring_rhythm')).toBe(true)
expect(steering.some((p) => p.key === 'steering.critical_path')).toBe(false)
})
it('buildProviderProps uses recurring rhythm next-action copy', () => {
const provider = COMPOSITION_PROVIDERS.find((p) => p.key === 'steering.next_action')
const props = buildProviderProps(provider, {
steeringElements: ['next_action_primary', 'recurring_rhythm', 'maturity_stage'],
steeringSnapshot: { next_actions: [] },
opsContext: { initiativeId: 'x', steeringSnapshotLoading: false },
capabilities: CAPS,
})
expect(props.title).toContain('Rhythmus')
})
it('buildProviderProps toggles gate horizon on steering snapshot', () => {
const provider = COMPOSITION_PROVIDERS.find((p) => p.key === 'core.steering_snapshot') const provider = COMPOSITION_PROVIDERS.find((p) => p.key === 'core.steering_snapshot')
const withGate = buildProviderProps(provider, { const withGate = buildProviderProps(provider, {
steeringElements: ['gate_fulfillment', 'next_action_primary'], steeringElements: ['gate_fulfillment', 'next_action_primary'],
@@ -232,4 +260,88 @@ describe('resolveSteeringComposition', () => {
expect(withGate.showGateHorizon).toBe(true) expect(withGate.showGateHorizon).toBe(true)
expect(withoutGate.showGateHorizon).toBe(false) expect(withoutGate.showGateHorizon).toBe(false)
}) })
it('activates work.today next action and actions providers', () => {
const result = resolveSteeringComposition({
surfaceKey: 'work.today',
scope: 'initiative',
capabilities: new Set([...CAPS, 'kairo.recurring.read']),
steeringElements: ['next_action_primary', 'recurring_rhythm', 'critical_path'],
steeringSnapshot: { counts: {}, next_actions: [{ kind: 'action', title: 'X' }] },
opsContext: { initiativeId: 'init-1' },
})
expect(result.slots['work.today.primary']?.some((p) => p.key === 'steering.next_action')).toBe(
true,
)
expect(result.slots['work.today.primary']?.some((p) => p.key === 'work.practice.today')).toBe(
true,
)
expect(result.slots['work.today.actions']?.some((p) => p.key === 'work.actions.today')).toBe(
true,
)
})
it('buildProviderProps wires WorkTodayPracticePanel complete refresh', async () => {
const provider = COMPOSITION_PROVIDERS.find((p) => p.key === 'work.practice.today')
const refreshOm = vi.fn().mockResolvedValue(undefined)
const props = buildProviderProps(provider, {
opsContext: {
initiativeId: 'init-1',
roadmapItems: [{ id: 'stage-1', item_type: 'maturity_stage', status: 'active', title: 'Stufe 1' }],
recurringItems: [{ id: 'rec-1', status: 'active', title: 'Vorbeuge', roadmap_item_id: 'stage-1' }],
formBusy: false,
refreshOm,
},
capabilities: new Set([...CAPS, 'kairo.recurring.read', 'kairo.recurring.manage']),
})
expect(props.canManage).toBe(true)
await props.onCompleted()
expect(refreshOm).toHaveBeenCalledWith(['recurring', 'steering_snapshot'])
})
it('activates sprint backlog provider when active work cycle', () => {
const result = resolveSteeringComposition({
surfaceKey: 'work.sprint',
scope: 'initiative',
capabilities: CAPS,
steeringElements: ['next_action_primary', 'work_cycle_scope'],
steeringSnapshot: {
counts: {},
next_actions: [],
active_work_cycle: { id: 'wc-1', title: 'Sprint R1' },
},
opsContext: { initiativeId: 'init-1', activeWorkCycle: { id: 'wc-1' } },
})
expect(result.slots['work.sprint.backlog']?.some((p) => p.key === 'work.actions.sprint')).toBe(
true,
)
})
it('activates product backlog panel without active sprint', () => {
const result = resolveSteeringComposition({
surfaceKey: 'work.sprint',
scope: 'initiative',
capabilities: CAPS,
operatingContext: {
ui_features: { continuousProductWorkMode: true },
data_slices: ['work_cycles'],
},
steeringSnapshot: { counts: {}, next_actions: [] },
opsContext: {
initiativeId: 'init-1',
uiFeatures: { continuousProductWorkMode: true },
dataSlices: ['work_cycles'],
},
})
expect(
result.slots['work.sprint.backlog']?.some((p) => p.key === 'work.actions.sprint_product'),
).toBe(true)
})
it('buildProviderProps passes work actions variant', () => {
const provider = COMPOSITION_PROVIDERS.find((p) => p.key === 'work.actions.today')
const props = buildProviderProps(provider, { opsContext: {} })
expect(props.variant).toBe('today')
expect(props.defaultCollapsed).toBe(true)
})
}) })
@@ -26,6 +26,11 @@ export const UI_SLOTS = [
{ key: 'plan.inbox.proposals', mode: 'plan', routeKey: 'inbox', label: 'Triage-Vorschläge', order: 0 }, { key: 'plan.inbox.proposals', mode: 'plan', routeKey: 'inbox', label: 'Triage-Vorschläge', order: 0 },
{ key: 'plan.sprint.proposals', mode: 'plan', routeKey: 'sprint', label: 'Sprint-Vorschläge', order: 0 }, { key: 'plan.sprint.proposals', mode: 'plan', routeKey: 'sprint', label: 'Sprint-Vorschläge', order: 0 },
{ key: 'plan.gates.proposals', mode: 'plan', routeKey: 'gates', label: 'Gate-Vorschläge', order: 0 }, { key: 'plan.gates.proposals', mode: 'plan', routeKey: 'gates', label: 'Gate-Vorschläge', order: 0 },
{ key: 'work.today.primary', mode: 'work', routeKey: 'today', label: 'Nächster Schritt', order: 0 },
{ key: 'work.today.actions', mode: 'work', routeKey: 'today', label: 'Arbeitspakete', order: 10 },
{ key: 'work.sprint.primary', mode: 'work', routeKey: 'sprint', label: 'Nächster Schritt', order: 0 },
{ key: 'work.sprint.backlog', mode: 'work', routeKey: 'sprint', label: 'Sprint-Backlog', order: 10 },
] ]
/** /**
@@ -68,6 +73,16 @@ export const COMPOSITION_SURFACES = {
routeKey: 'gates', routeKey: 'gates',
slotKeys: ['plan.gates.proposals'], slotKeys: ['plan.gates.proposals'],
}, },
'work.today': {
mode: 'work',
routeKey: 'today',
slotKeys: ['work.today.primary', 'work.today.actions'],
},
'work.sprint': {
mode: 'work',
routeKey: 'sprint',
slotKeys: ['work.sprint.primary', 'work.sprint.backlog'],
},
} }
/** /**
+1 -1
View File
@@ -70,7 +70,7 @@ const ARCHETYPE_UI = {
planDefaultRoute: '/plan/gates', planDefaultRoute: '/plan/gates',
workDefaultRoute: '/work/today', workDefaultRoute: '/work/today',
controlDefaultRoute: '/control/status', controlDefaultRoute: '/control/status',
planOutlineKeys: ['profile', 'gates', 'inbox', 'work'], planOutlineKeys: ['profile', 'gates', 'work'],
workNavKeys: ['today', 'mine', 'sprint'], workNavKeys: ['today', 'mine', 'sprint'],
}, },
'initiative.program': { 'initiative.program': {
@@ -64,6 +64,17 @@ describe('methodUiDefaults', () => {
expect(resolvePlanOutlineNodes({}).length).toBe(6) expect(resolvePlanOutlineNodes({}).length).toBe(6)
}) })
it('maturity archetype omits inbox from plan outline', () => {
const ui = resolveMethodUiDefaults({ archetypeKey: 'initiative.maturity_journey' })
expect(ui.planDefaultRoute).toBe('/plan/gates')
expect(ui.planOutlineKeys).toEqual(['profile', 'gates', 'work'])
expect(resolvePlanOutlineNodes({ archetypeKey: 'initiative.maturity_journey' }).map((n) => n.key)).toEqual([
'profile',
'gates',
'work',
])
})
it('resolves active process step from pathname', () => { it('resolves active process step from pathname', () => {
const steps = resolveProcessSteps({ archetypeKey: 'initiative.product' }) const steps = resolveProcessSteps({ archetypeKey: 'initiative.product' })
expect(resolveActiveProcessStepKey('/plan/inbox', steps)).toBe('inbox') expect(resolveActiveProcessStepKey('/plan/inbox', steps)).toBe('inbox')
+24
View File
@@ -0,0 +1,24 @@
/**
* AP1.9d — zentrale UI-Begriffe (Product Language).
* Spätere UI-Neuimplementierung kann diese Konstanten ersetzen, ohne Pages zu patchen.
* @see docs/product/Kairo_MVP_Definition_v0.3.md §7
*/
export const PRODUCT_TERMS = {
action: 'Arbeitspaket',
actionPlural: 'Arbeitspakete',
actionPossessive: 'meine Arbeitspakete',
workCycle: 'Sprint',
workCyclePlural: 'Sprints',
productBacklog: 'Product Backlog',
sprintBacklog: 'Sprint-Backlog',
intake: 'Eingang',
}
/**
* @param {number} count
*/
export function actionCountLabel(count) {
if (count === 1) return `1 ${PRODUCT_TERMS.action}`
return `${count} ${PRODUCT_TERMS.actionPlural}`
}
+13
View File
@@ -92,6 +92,19 @@ export const ROADMAP_ITEM_TYPE_LABELS = {
milestone: 'Meilenstein / Gate', milestone: 'Meilenstein / Gate',
review_gate: 'Review-Gate', review_gate: 'Review-Gate',
maturity_stage: 'Reifegrad-Stufe', maturity_stage: 'Reifegrad-Stufe',
join_gate: 'Join / Schaltknoten',
}
/** Plan-Designer: anlegbare Gate-Typen (archetypübergreifend; später pro Archetyp konfigurierbar). */
export const ROADMAP_ITEM_TYPES_FOR_DESIGNER = [
'milestone',
'review_gate',
'maturity_stage',
'join_gate',
]
export function isJoinGateItem(item) {
return item?.item_type === 'join_gate'
} }
export const SEQUENCING_MODE_LABELS = { export const SEQUENCING_MODE_LABELS = {
+9
View File
@@ -12,6 +12,7 @@ import { updateAction, setActionAssignments } from '../api/actions.js'
import { createInitiativeBlocker } from '../api/blockers.js' import { createInitiativeBlocker } from '../api/blockers.js'
import { ActionHubCard } from '../components/ActionHubCard.jsx' import { ActionHubCard } from '../components/ActionHubCard.jsx'
import { ActionDependenciesSection } from '../components/ActionDependenciesSection.jsx' import { ActionDependenciesSection } from '../components/ActionDependenciesSection.jsx'
import { ActionScheduleSection } from '../components/ActionScheduleSection.jsx'
import { ActionForm } from '../components/ActionForm.jsx' import { ActionForm } from '../components/ActionForm.jsx'
import { TasksSection } from '../components/TasksSection.jsx' import { TasksSection } from '../components/TasksSection.jsx'
import { ErrorState } from '../components/ErrorState.jsx' import { ErrorState } from '../components/ErrorState.jsx'
@@ -39,6 +40,7 @@ function ActionDetailBody({
roadmapItems = [], roadmapItems = [],
allActions = [], allActions = [],
executionGraph = null, executionGraph = null,
onReload,
}) { }) {
if (editing) { if (editing) {
return ( return (
@@ -80,6 +82,11 @@ function ActionDetailBody({
onReloadActors={actorsState.reload} onReloadActors={actorsState.reload}
detailMode detailMode
/> />
<ActionScheduleSection
action={action}
canManage={capabilities.has('kairo.action.manage')}
onUpdated={onReload}
/>
<TasksSection <TasksSection
actionId={action.id} actionId={action.id}
canManage={capabilities.has('kairo.action.manage')} canManage={capabilities.has('kairo.action.manage')}
@@ -254,6 +261,7 @@ function ActionDetailStandalone() {
roadmapItems={roadmapItems} roadmapItems={roadmapItems}
allActions={allActions} allActions={allActions}
executionGraph={executionGraph} executionGraph={executionGraph}
onReload={load}
/> />
</section> </section>
</div> </div>
@@ -317,6 +325,7 @@ function ActionDetailNested() {
roadmapItems={ops.roadmapItems} roadmapItems={ops.roadmapItems}
allActions={ops.actions} allActions={ops.actions}
executionGraph={executionGraph} executionGraph={executionGraph}
onReload={ops.reload}
/> />
</section> </section>
) )
@@ -10,6 +10,7 @@ export function InitiativePlanPage() {
capabilities, capabilities,
formBusy, formBusy,
handleCreateRoadmapItem, handleCreateRoadmapItem,
handleUpdateRoadmapItem,
handleReorderRoadmapItems, handleReorderRoadmapItems,
handleDeleteRoadmapItem, handleDeleteRoadmapItem,
handleConvertBacklog, handleConvertBacklog,
@@ -45,6 +46,7 @@ export function InitiativePlanPage() {
items={roadmapItems} items={roadmapItems}
canManage={capabilities.has('kairo.milestone.manage')} canManage={capabilities.has('kairo.milestone.manage')}
onCreate={handleCreateRoadmapItem} onCreate={handleCreateRoadmapItem}
onUpdate={handleUpdateRoadmapItem}
onReorder={handleReorderRoadmapItems} onReorder={handleReorderRoadmapItems}
onDelete={handleDeleteRoadmapItem} onDelete={handleDeleteRoadmapItem}
busy={formBusy} busy={formBusy}
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom' import { Link, useNavigate, useParams } from 'react-router-dom'
import { createInitiativeEvidence } from '../../api/evidence.js' import { createInitiativeEvidence } from '../../api/evidence.js'
import { import {
getRoadmapItem, getRoadmapItem,
@@ -10,6 +10,7 @@ import {
listRoadmapItemDependencies, listRoadmapItemDependencies,
addRoadmapItemDependency, addRoadmapItemDependency,
deleteRoadmapDependency, deleteRoadmapDependency,
deleteRoadmapItem,
listInitiativeRoadmapItems, listInitiativeRoadmapItems,
} from '../../api/roadmap.js' } from '../../api/roadmap.js'
import { ErrorState } from '../../components/ErrorState.jsx' import { ErrorState } from '../../components/ErrorState.jsx'
@@ -18,11 +19,13 @@ import { StatusBadge } from '../../components/StatusBadge.jsx'
import { import {
MILESTONE_STATUS_LABELS, MILESTONE_STATUS_LABELS,
ROADMAP_ITEM_TYPE_LABELS, ROADMAP_ITEM_TYPE_LABELS,
isJoinGateItem,
} from '../../constants/status.js' } from '../../constants/status.js'
import { useCapabilities } from '../../hooks/useCapabilities.js' import { useCapabilities } from '../../hooks/useCapabilities.js'
import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx' import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx'
import { scopedPath } from '../../utils/routes.js' import { scopedPath } from '../../utils/routes.js'
import { listGateContributions } from '../../api/journey.js' import { listGateContributions } from '../../api/journey.js'
import { GateActivitySetSection } from '../../components/GateActivitySetSection.jsx'
import { GateContributionsSection } from '../../components/GateContributionsSection.jsx' import { GateContributionsSection } from '../../components/GateContributionsSection.jsx'
import { GateDependenciesSection } from '../../components/GateDependenciesSection.jsx' import { GateDependenciesSection } from '../../components/GateDependenciesSection.jsx'
import { GateCriteriaSection } from '../../components/GateCriteriaSection.jsx' import { GateCriteriaSection } from '../../components/GateCriteriaSection.jsx'
@@ -31,6 +34,7 @@ import { RoadmapItemForm } from '../../components/RoadmapItemForm.jsx'
export function RoadmapItemDetailPage({ overrideItemId }) { export function RoadmapItemDetailPage({ overrideItemId }) {
const { id: routeInitiativeId, itemId: routeItemId, gateId } = useParams() const { id: routeInitiativeId, itemId: routeItemId, gateId } = useParams()
const navigate = useNavigate()
const ops = useInitiativeOperations() const ops = useInitiativeOperations()
const initiativeId = routeInitiativeId || ops?.initiativeId const initiativeId = routeInitiativeId || ops?.initiativeId
const itemId = overrideItemId || routeItemId || gateId const itemId = overrideItemId || routeItemId || gateId
@@ -143,6 +147,8 @@ export function RoadmapItemDetailPage({ overrideItemId }) {
if (error && !item) return <ErrorState message={error} onRetry={load} /> if (error && !item) return <ErrorState message={error} onRetry={load} />
if (!item) return <ErrorState message="Plan-Element nicht gefunden." onRetry={load} /> if (!item) return <ErrorState message="Plan-Element nicht gefunden." onRetry={load} />
const joinGate = isJoinGateItem(item)
return ( return (
<section className="card roadmap-item-detail"> <section className="card roadmap-item-detail">
<p className="breadcrumb muted"> <p className="breadcrumb muted">
@@ -167,6 +173,20 @@ export function RoadmapItemDetailPage({ overrideItemId }) {
</div> </div>
<div className="section-header__actions"> <div className="section-header__actions">
<StatusBadge kind="milestone" status={item.status} /> <StatusBadge kind="milestone" status={item.status} />
{canManage && item.status === 'planned' && !joinGate && (
<button
type="button"
className="btn btn-primary btn-sm"
disabled={busy}
onClick={() =>
runAction(async () => {
await updateRoadmapItem(itemId, { status: 'active' })
})
}
>
Gate aktivieren
</button>
)}
{canManage && item.status !== 'reached' && ( {canManage && item.status !== 'reached' && (
<button <button
type="button" type="button"
@@ -177,6 +197,25 @@ export function RoadmapItemDetailPage({ overrideItemId }) {
Stammdaten Stammdaten
</button> </button>
)} )}
{canManage && !['reached', 'moved', 'discarded'].includes(item.status) && (
<button
type="button"
className="btn btn-secondary btn-sm gate-designer-node-panel__delete"
disabled={busy}
onClick={async () => {
const ok = window.confirm(
`„${item.title}" wirklich löschen? Verknüpfte Kanten werden mit entfernt.`,
)
if (!ok) return
await runAction(async () => {
await deleteRoadmapItem(itemId)
navigate(scopedPath('/plan/gates', { initiativeId }))
})
}}
>
Löschen
</button>
)}
</div> </div>
</div> </div>
@@ -197,19 +236,45 @@ export function RoadmapItemDetailPage({ overrideItemId }) {
onDelete={(dependencyId) => runAction(() => deleteRoadmapDependency(dependencyId))} onDelete={(dependencyId) => runAction(() => deleteRoadmapDependency(dependencyId))}
/> />
<GateCriteriaSection {!joinGate && (
itemId={itemId} <GateActivitySetSection
itemStatus={item.status} gateId={itemId}
criteria={criteria} initiativeId={initiativeId || item.initiative_id}
progress={progress} gateStatus={item.status}
canManage={canManage} gateTitle={item.title}
busy={busy} canManage={capabilities.has('kairo.recurring.manage')}
onChanged={reloadCriteria} />
onAction={runCriteriaAction} )}
/>
{joinGate ? (
<section className="card join-gate-detail">
<h3>Join / Schaltknoten</h3>
<p className="muted">
Kein Activity Set und kein manuelles Verify. Der Join schaltet automatisch auf{' '}
<strong>Erreicht</strong>, wenn alle eingehenden Voraussetzungen (Kanten{' '}
<em>requires</em> von diesem Join zu Work-Gates) erfüllt sind — danach werden
ausgehende Gates freigegeben.
</p>
<p className="muted">
Eingang: Join benötigt Gate · Ausgang: Gate benötigt Join (unter Abhängigkeiten
konfigurieren).
</p>
</section>
) : (
<GateCriteriaSection
itemId={itemId}
itemStatus={item.status}
criteria={criteria}
progress={progress}
canManage={canManage}
busy={busy}
onChanged={reloadCriteria}
onAction={runCriteriaAction}
/>
)}
<div className="gate-detail-actions"> <div className="gate-detail-actions">
{canManage && ['planned', 'active', 'at_risk'].includes(item.status) && ( {canManage && !joinGate && ['planned', 'active', 'at_risk'].includes(item.status) && (
<button <button
type="button" type="button"
className="btn btn-primary" className="btn btn-primary"
+67 -10
View File
@@ -2,11 +2,13 @@ import { useEffect, useMemo, useCallback } from 'react'
import { RequireInitiativeScope } from '../../components/RequireInitiativeScope.jsx' import { RequireInitiativeScope } from '../../components/RequireInitiativeScope.jsx'
import { ScopedInitiativeProvider } from '../../layout/ScopedInitiativeProvider.jsx' import { ScopedInitiativeProvider } from '../../layout/ScopedInitiativeProvider.jsx'
import { WorkCyclesPanel } from '../../components/WorkCyclesPanel.jsx' import { WorkCyclesPanel } from '../../components/WorkCyclesPanel.jsx'
import { BacklogSection } from '../../components/BacklogSection.jsx'
import { InitiativeCompositionSurface } from '../../composition/InitiativeCompositionSurface.jsx' import { InitiativeCompositionSurface } from '../../composition/InitiativeCompositionSurface.jsx'
import { InitiativeActionsHub } from '../../components/InitiativeActionsHub.jsx' import { InitiativeActionsHub } from '../../components/InitiativeActionsHub.jsx'
import { LoadingState } from '../../components/LoadingState.jsx' import { LoadingState } from '../../components/LoadingState.jsx'
import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx' import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx'
import { countActionsByWorkCycle } from '../../utils/workCycleActions.js' import { countActionsByWorkCycle } from '../../utils/workCycleActions.js'
import { PRODUCT_TERMS } from '../../constants/productLanguage.js'
function PlanSprintInner() { function PlanSprintInner() {
const ops = useInitiativeOperations() const ops = useInitiativeOperations()
@@ -19,8 +21,10 @@ function PlanSprintInner() {
selectedSprintActions, selectedSprintActions,
workCycles, workCycles,
actions, actions,
backlogItems,
projects, projects,
roadmapItems, roadmapItems,
featureParentActions,
capabilities, capabilities,
hideDone, hideDone,
setHideDone, setHideDone,
@@ -49,19 +53,50 @@ function PlanSprintInner() {
handleMoveActionToSprint, handleMoveActionToSprint,
handleUnplanAction, handleUnplanAction,
handleConvertBacklog, handleConvertBacklog,
handleBulkConvertBacklog,
handleCreateBacklog,
handleUpdateBacklog,
handleReorderBacklog,
handleDeleteBacklog,
reloadSlices, reloadSlices,
} = ops } = ops
useEffect(() => { useEffect(() => {
reloadSlices(['steering_snapshot']) reloadSlices(['steering_snapshot', 'backlog'])
}, [reloadSlices])
const reloadAfterSprintCommit = useCallback(async () => {
await reloadSlices(['steering_snapshot', 'actions', 'backlog'])
}, [reloadSlices]) }, [reloadSlices])
const onAcceptBacklogProposal = useCallback( const onAcceptBacklogProposal = useCallback(
async (itemId, options) => { async (itemId, options) => {
await handleConvertBacklog(itemId, options) await handleConvertBacklog(itemId, {
await reloadSlices(['steering_snapshot', 'actions', 'backlog']) work_cycle_id: options?.work_cycle_id || selectedWorkCycleId,
})
await reloadAfterSprintCommit()
}, },
[handleConvertBacklog, reloadSlices], [handleConvertBacklog, selectedWorkCycleId, reloadAfterSprintCommit],
)
const onConvertToSprint = useCallback(
async (itemId, options) => {
await handleConvertBacklog(itemId, {
work_cycle_id: options?.work_cycle_id || selectedWorkCycleId,
})
await reloadAfterSprintCommit()
},
[handleConvertBacklog, selectedWorkCycleId, reloadAfterSprintCommit],
)
const onBulkConvertToSprint = useCallback(
async (itemIds, options) => {
await handleBulkConvertBacklog(itemIds, {
work_cycle_id: options?.work_cycle_id || selectedWorkCycleId,
})
await reloadAfterSprintCommit()
},
[handleBulkConvertBacklog, selectedWorkCycleId, reloadAfterSprintCommit],
) )
const proposalFilterContext = useMemo( const proposalFilterContext = useMemo(
@@ -113,11 +148,33 @@ function PlanSprintInner() {
busy={formBusy} busy={formBusy}
/> />
{selectedWorkCycleId && ( {selectedWorkCycleId && (
<InitiativeCompositionSurface <>
surfaceKey="plan.sprint" <InitiativeCompositionSurface
filterContext={proposalFilterContext} surfaceKey="plan.sprint"
onAcceptBacklogProposal={onAcceptBacklogProposal} filterContext={proposalFilterContext}
/> onAcceptBacklogProposal={onAcceptBacklogProposal}
/>
<BacklogSection
items={backlogItems}
initiativeId={initiativeId}
roadmapItems={roadmapItems}
featureActions={featureParentActions}
workCycles={workCycles}
activeWorkCycle={activeWorkCycle}
canManage={capabilities.has('kairo.backlog.manage')}
onCreate={handleCreateBacklog}
onUpdate={handleUpdateBacklog}
onReorder={handleReorderBacklog}
onConvert={onConvertToSprint}
onBulkConvert={onBulkConvertToSprint}
onDelete={handleDeleteBacklog}
busy={formBusy}
defaultSprintTargetId={selectedWorkCycleId}
lockSprintTarget
sectionTitle={`Aus ${PRODUCT_TERMS.intake} in ${PRODUCT_TERMS.workCycle} planen`}
sectionLead={`Markiere commit-bereite Items und lege sie in „${selectedWorkCycle?.title || PRODUCT_TERMS.workCycle}" — oder nutze die Sprint-Vorschläge oben.`}
/>
</>
)} )}
{selectedWorkCycleId && selectedWorkCycle && ( {selectedWorkCycleId && selectedWorkCycle && (
<InitiativeActionsHub <InitiativeActionsHub
@@ -150,7 +207,7 @@ function PlanSprintInner() {
workCycles={workCycles} workCycles={workCycles}
activeWorkCycle={selectedWorkCycle} activeWorkCycle={selectedWorkCycle}
allActions={actions} allActions={actions}
sectionTitle={`Sprint-Backlog — ${selectedWorkCycle.title}`} sectionTitle={`${PRODUCT_TERMS.sprintBacklog} — ${selectedWorkCycle.title}`}
sectionLead={sprintLead} sectionLead={sprintLead}
/> />
)} )}
+41 -160
View File
@@ -1,51 +1,26 @@
import { useEffect, useMemo } from 'react' import { useEffect } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { RequireInitiativeScope } from '../../components/RequireInitiativeScope.jsx' import { RequireInitiativeScope } from '../../components/RequireInitiativeScope.jsx'
import { InitiativeActionsHub } from '../../components/InitiativeActionsHub.jsx' import { InitiativeCompositionSurface } from '../../composition/InitiativeCompositionSurface.jsx'
import { NextActionWidget } from '../../widgets/NextActionWidget.jsx'
import { LoadingState } from '../../components/LoadingState.jsx' import { LoadingState } from '../../components/LoadingState.jsx'
import { EmptyState } from '../../components/EmptyState.jsx' import { EmptyState } from '../../components/EmptyState.jsx'
import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx' import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx'
import { useProgramScope } from '../../context/ProgramScopeContext.jsx' import { useProgramScope } from '../../context/ProgramScopeContext.jsx'
import { scopedPath } from '../../utils/routes.js' import { scopedPath } from '../../utils/routes.js'
import { PRODUCT_TERMS } from '../../constants/productLanguage.js'
function WorkSprintInner() { function WorkSprintInner() {
const { initiativeId, hrefWithScope } = useProgramScope() const { initiativeId, hrefWithScope } = useProgramScope()
const ops = useInitiativeOperations() const ops = useInitiativeOperations()
const { const {
activeWorkCycle, activeWorkCycle,
sprintActions,
projects,
roadmapItems,
capabilities,
hideDone,
setHideDone,
loading, loading,
error, error,
formBusy,
showActionForm,
setShowActionForm,
editingActionId,
setEditingActionId,
actionContextById,
actors,
actorsLoading,
actorsError,
actorsUsedFallback,
reloadActors,
handleCreateAction,
handleUpdateAction,
handleQuickStatus,
handleCreateBlockerForAction,
handleMoveActionToSprint,
handleUnplanAction,
initiative,
operatingContext, operatingContext,
dataSlices, dataSlices,
uiFeatures, uiFeatures,
steeringSnapshot, steeringSnapshot,
steeringSnapshotLoading, steeringSnapshotLoading,
visibleActions,
reloadSlices, reloadSlices,
} = ops } = ops
@@ -65,157 +40,63 @@ function WorkSprintInner() {
reloadSlices, reloadSlices,
]) ])
const defaultWorkCycleId = activeWorkCycle?.id || ''
const createAction = useMemo(
() => async (payload) => {
await handleCreateAction({
...payload,
work_cycle_id: payload.work_cycle_id || defaultWorkCycleId || undefined,
})
},
[handleCreateAction, defaultWorkCycleId],
)
if (loading) { if (loading) {
return <LoadingState message="Lade Sprint-Backlog …" /> return <LoadingState message={`Lade ${PRODUCT_TERMS.sprintBacklog} …`} />
} }
const isProductArchetype = isContinuousProductMode if (!supportsWorkCycles) {
return (
<EmptyState
message={`${PRODUCT_TERMS.sprintBacklog} ist für diesen Vorhabentyp nicht verfügbar.`}
/>
)
}
return ( return (
<> <>
{error && <p className="error">{error}</p>} {error && <p className="error">{error}</p>}
{!activeWorkCycle && isProductArchetype && ( {!activeWorkCycle && isContinuousProductMode && (
<> <section className="card sprint-context-banner">
<section className="card sprint-context-banner"> <h2>Product-Ist (ohne aktiven {PRODUCT_TERMS.workCycle})</h2>
<h2>Product-Ist (ohne aktiven Sprint)</h2> <p className="section-lead muted">
<p className="section-lead muted"> Kein aktiver {PRODUCT_TERMS.workCycle} — Kairo steuert nach{' '}
Kein aktiver Sprint — Kairo steuert nach{' '} <strong>{operatingContext?.method_key || 'continuous_product'}</strong> (wirkungsvollster
<strong>{operatingContext?.method_key || 'continuous_product'}</strong> (wirkungsvollster Schritt). Sprint-Planung Schritt). {PRODUCT_TERMS.workCycle}-Planung unter{' '}
unter{' '} <Link to={hrefWithScope('/plan/sprint')} className="link-inline">
<Link to={hrefWithScope('/plan/sprint')} className="link-inline"> Plan → Sprint planen
Plan → Sprint </Link>
</Link> .
. </p>
</p> </section>
</section>
<NextActionWidget
scope="initiative"
initiativeId={initiativeId}
items={steeringSnapshot?.next_actions}
loading={steeringSnapshotLoading}
embedded
title="Nächster Schritt (Product)"
subtitle="Empfehlung ohne Sprint-Zeitbox — committete Arbeitspakete im Vorhaben."
/>
<InitiativeActionsHub
initiativeId={initiativeId}
actions={visibleActions}
projects={projects}
roadmapItems={roadmapItems}
actionContextById={actionContextById}
hideDone={hideDone}
onHideDoneChange={setHideDone}
showForm={showActionForm}
onToggleForm={() => setShowActionForm((v) => !v)}
editingActionId={editingActionId}
onEditAction={setEditingActionId}
onCancelEdit={() => setEditingActionId(null)}
onCreateAction={handleCreateAction}
onUpdateAction={handleUpdateAction}
onQuickStatus={handleQuickStatus}
onCreateBlockerForAction={handleCreateBlockerForAction}
onMoveToSprint={handleMoveActionToSprint}
onUnplanToBacklog={handleUnplanAction}
canManage={capabilities.has('kairo.action.manage')}
canManageBlocker={capabilities.has('kairo.blocker.manage')}
formBusy={formBusy}
actors={actors}
actorsLoading={actorsLoading}
actorsError={actorsError}
actorsUsedFallback={actorsUsedFallback}
onReloadActors={reloadActors}
workCycles={ops.workCycles}
activeWorkCycle={activeWorkCycle}
sectionTitle="Committete Arbeitspakete"
sectionLead="Ohne aktiven Sprint — alle offenen Arbeitspakete im Product-Vorhaben."
/>
</>
)} )}
{activeWorkCycle && ( {activeWorkCycle && (
<> <section className="card sprint-context-banner">
<section className="card sprint-context-banner"> <h2>{PRODUCT_TERMS.sprintBacklog}</h2>
<h2>Sprint-Backlog</h2> <p className="section-lead muted">
<p className="section-lead muted"> <strong>{activeWorkCycle.title}</strong>
<strong>{activeWorkCycle.title}</strong> {activeWorkCycle.goal_description && ` — ${activeWorkCycle.goal_description}`}
{activeWorkCycle.goal_description && ` — ${activeWorkCycle.goal_description}`} {' · '}
{' · '} {PRODUCT_TERMS.productBacklog} triagierst du unter{' '}
Product Backlog triagierst du unter{' '} <Link to={scopedPath('/plan/inbox', { initiativeId })} className="link-inline">
<Link to={scopedPath('/plan/inbox', { initiativeId })} className="link-inline"> Plan → {PRODUCT_TERMS.intake}
Plan → Eingang </Link>
</Link> .
. </p>
</p> </section>
</section>
<NextActionWidget
scope="initiative"
initiativeId={initiativeId}
items={steeringSnapshot?.next_actions}
loading={steeringSnapshotLoading}
embedded
title="Nächster Schritt im Sprint"
/>
<InitiativeActionsHub
initiativeId={initiativeId}
actions={sprintActions}
projects={projects}
roadmapItems={roadmapItems}
actionContextById={actionContextById}
hideDone={hideDone}
onHideDoneChange={setHideDone}
showForm={showActionForm}
onToggleForm={() => setShowActionForm((v) => !v)}
editingActionId={editingActionId}
onEditAction={setEditingActionId}
onCancelEdit={() => setEditingActionId(null)}
onCreateAction={createAction}
onUpdateAction={handleUpdateAction}
onQuickStatus={handleQuickStatus}
onCreateBlockerForAction={handleCreateBlockerForAction}
onMoveToSprint={handleMoveActionToSprint}
onUnplanToBacklog={handleUnplanAction}
canManage={capabilities.has('kairo.action.manage')}
canManageBlocker={capabilities.has('kairo.blocker.manage')}
formBusy={formBusy}
actors={actors}
actorsLoading={actorsLoading}
actorsError={actorsError}
actorsUsedFallback={actorsUsedFallback}
onReloadActors={reloadActors}
workCycles={ops.workCycles}
activeWorkCycle={activeWorkCycle}
allActions={ops.actions}
/>
</>
)} )}
{!activeWorkCycle && !supportsWorkCycles && ( <InitiativeCompositionSurface surfaceKey="work.sprint" />
<EmptyState message="Sprint-Ausführung ist für diesen Vorhabentyp nicht verfügbar." />
)}
</> </>
) )
} }
export function WorkSprintPage() { export function WorkSprintPage() {
return ( return (
<RequireInitiativeScope lead="Sprint-Backlog ist vorhabenspezifisch — wähle ein passendes Vorhaben im Scope."> <RequireInitiativeScope
lead={`${PRODUCT_TERMS.sprintBacklog} ist vorhabenspezifisch — wähle ein passendes Vorhaben im Scope.`}
>
<WorkSprintInner /> <WorkSprintInner />
</RequireInitiativeScope> </RequireInitiativeScope>
) )
+74 -4
View File
@@ -1,9 +1,79 @@
import { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { RequireInitiativeScope } from '../../components/RequireInitiativeScope.jsx'
import { LoadingState } from '../../components/LoadingState.jsx'
import { NextActionWidget } from '../../widgets/NextActionWidget.jsx'
import { WorkspaceTodayWidget } from '../../widgets/WorkspaceTodayWidget.jsx' import { WorkspaceTodayWidget } from '../../widgets/WorkspaceTodayWidget.jsx'
import { InitiativeCompositionSurface } from '../../composition/InitiativeCompositionSurface.jsx'
import { useProgramScope } from '../../context/ProgramScopeContext.jsx'
import { useInitiativeOperations } from '../../context/InitiativeOperationsContext.jsx'
import { PRODUCT_TERMS } from '../../constants/productLanguage.js'
export function WorkTodayPage() { function WorkTodayPortfolioView() {
return ( return (
<section className="card"> <>
<WorkspaceTodayWidget /> <NextActionWidget
</section> scope="portfolio"
embedded
title="Nächste sinnvolle Schritte"
subtitle="Portfolio-weit — wähle ein Vorhaben im Scope für methodengebundene Ausführung."
/>
<section className="card">
<WorkspaceTodayWidget limit={3} />
</section>
</>
) )
} }
function WorkTodayInitiativeInner() {
const { hrefWithScope } = useProgramScope()
const ops = useInitiativeOperations()
const { loading, error, reloadSlices, uiFeatures } = ops
useEffect(() => {
reloadSlices(['steering_snapshot'])
}, [reloadSlices])
if (loading) {
return <LoadingState message="Lade Ausführung …" />
}
const isProductWithSprint = uiFeatures.continuousProductWorkMode
return (
<>
{error && <p className="error">{error}</p>}
{isProductWithSprint && (
<section className="card work-context-banner">
<p className="section-lead muted">
Ausführen zeigt den <strong>nächsten Schritt</strong> — nicht die Gesamtliste.{' '}
{PRODUCT_TERMS.sprintBacklog} unter{' '}
<Link to={hrefWithScope('/work/sprint')} className="link-inline">
Ausführen → Sprint
</Link>
.
</p>
</section>
)}
<InitiativeCompositionSurface surfaceKey="work.today" />
</>
)
}
function WorkTodayInitiativeView() {
return (
<RequireInitiativeScope lead="Ausführung im Vorhaben-Kontext braucht ein gewähltes Vorhaben im Scope.">
<WorkTodayInitiativeInner />
</RequireInitiativeScope>
)
}
export function WorkTodayPage() {
const { initiativeId } = useProgramScope()
if (!initiativeId) {
return <WorkTodayPortfolioView />
}
return <WorkTodayInitiativeView />
}
+23
View File
@@ -23,6 +23,19 @@ export const DESIGNER_EDGE_LABELS = {
optional_branch: 'Optional', optional_branch: 'Optional',
} }
/** Kurz-Erklärung der Kantentypen (Semantik from → to in der DB). */
export const DESIGNER_EDGE_DESCRIPTIONS = {
requires:
'Ziel-Gate benötigt Quell-Gate als erreicht (Voraussetzung). Join: alle Eingänge müssen erreicht sein.',
blocks:
'Quell-Gate blockiert Ziel-Gate, solange es noch aktiv ist (planned/active/at_risk).',
related: 'Informativer Bezug — keine Blockade im Graph.',
parallel_group:
'Markiert parallele Gates in einer Gruppe (group_key) — blockiert nicht, dient der Struktur.',
optional_branch:
'Wie Voraussetzung, aber optional — blockiert das Ziel-Gate nicht, wenn offen.',
}
/** @deprecated use DESIGNER_EDGE_KINDS */ /** @deprecated use DESIGNER_EDGE_KINDS */
export const DEFERRED_TOPOLOGY_EDGE_KINDS = ['parallel_group', 'optional_branch'] export const DEFERRED_TOPOLOGY_EDGE_KINDS = ['parallel_group', 'optional_branch']
@@ -40,3 +53,13 @@ export function resolveDependencyEndpoints(edgeKind, sourceId, targetId) {
} }
return { from_item_id: sourceId, to_item_id: targetId } return { from_item_id: sourceId, to_item_id: targetId }
} }
/**
* Visuelle Drag-Richtung (Quelle → Ziel) aus gespeicherter Abhängigkeit.
*/
export function dependencyVisualEndpoints(dep) {
if (dep.dependency_type === 'requires') {
return { sourceId: dep.to_item_id, targetId: dep.from_item_id }
}
return { sourceId: dep.from_item_id, targetId: dep.to_item_id }
}
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import { import {
DEFERRED_TOPOLOGY_EDGE_KINDS, DEFERRED_TOPOLOGY_EDGE_KINDS,
DESIGNER_EDGE_KINDS, DESIGNER_EDGE_KINDS,
dependencyVisualEndpoints,
edgeKindNeedsGroupKey, edgeKindNeedsGroupKey,
resolveDependencyEndpoints, resolveDependencyEndpoints,
} from './gateGraphTopology.js' } from './gateGraphTopology.js'
@@ -31,4 +32,21 @@ describe('gateGraphTopology', () => {
to_item_id: 'b', to_item_id: 'b',
}) })
}) })
it('resolves visual endpoints from stored dependency', () => {
expect(
dependencyVisualEndpoints({
from_item_id: 'b',
to_item_id: 'a',
dependency_type: 'requires',
}),
).toEqual({ sourceId: 'a', targetId: 'b' })
expect(
dependencyVisualEndpoints({
from_item_id: 'a',
to_item_id: 'b',
dependency_type: 'blocks',
}),
).toEqual({ sourceId: 'a', targetId: 'b' })
})
}) })
@@ -14,6 +14,15 @@ export const STEERING_ELEMENT_UI = {
nextActionSubtitle: nextActionSubtitle:
'Empfehlung aus dem Sprint-Backlog — Continuous Next außerhalb des Sprints.', 'Empfehlung aus dem Sprint-Backlog — Continuous Next außerhalb des Sprints.',
}, },
recurring_rhythm: {
nextActionTitle: 'Heutige Übung / Rhythmus',
nextActionSubtitle:
'Reifegrad — aktive Routine steuert den nächsten Schritt, nicht die Gesamtliste.',
},
maturity_stage: {
nextActionTitle: 'Nächster Schritt in der Reifegrad-Entwicklung',
nextActionSubtitle: 'Aktive Stufe und fällige Übung bestimmen die Empfehlung.',
},
gate_fulfillment: { gate_fulfillment: {
nextActionTitle: 'Nächster sinnvoller Schritt', nextActionTitle: 'Nächster sinnvoller Schritt',
nextActionSubtitle: nextActionSubtitle:
@@ -30,7 +39,7 @@ export const STEERING_ELEMENT_UI = {
/** Labels für Steuerungselemente auf Plan-Profil (Anzeige, nicht Verhalten). */ /** Labels für Steuerungselemente auf Plan-Profil (Anzeige, nicht Verhalten). */
export const STEERING_ELEMENT_PLAN_LABELS = { export const STEERING_ELEMENT_PLAN_LABELS = {
work_cycle_scope: 'Sprint-Zeitbox', work_cycle_scope: 'Sprint',
backlog_epic_hierarchy: 'Epic-Hierarchie im Eingang', backlog_epic_hierarchy: 'Epic-Hierarchie im Eingang',
gate_fulfillment: 'Gate-Fortschritt', gate_fulfillment: 'Gate-Fortschritt',
queue_inbox: 'Queue-Eingang', queue_inbox: 'Queue-Eingang',
+208 -11
View File
@@ -1093,6 +1093,11 @@
padding: 0 1rem 1rem; padding: 0 1rem 1rem;
} }
.collapsible-section__toggle {
margin: 0.75rem 0 0;
padding: 0 1rem 1rem;
}
.initiative-advanced-stack { .initiative-advanced-stack {
display: grid; display: grid;
gap: 0.75rem; gap: 0.75rem;
@@ -2041,6 +2046,13 @@
opacity: 0.92; opacity: 0.92;
} }
.gate-map-view__node--join_gate .gate-map-view__node-box {
stroke: #5b6ee1;
stroke-width: 2;
stroke-dasharray: 6 4;
fill: #eef0ff;
}
.status-pill { .status-pill {
display: inline-block; display: inline-block;
padding: 0.15rem 0.5rem; padding: 0.15rem 0.5rem;
@@ -2145,14 +2157,38 @@
} }
.gate-graph-designer__main { .gate-graph-designer__main {
position: relative;
display: flex; display: flex;
gap: 0.75rem; gap: 0;
align-items: stretch; align-items: stretch;
min-height: 420px;
} }
.gate-graph-designer__main .gate-graph-designer__viewport { .gate-graph-designer__main .gate-graph-designer__viewport {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
width: 100%;
}
.gate-graph-designer__side-panel {
position: absolute;
top: 0.5rem;
right: 0.5rem;
bottom: 0.5rem;
z-index: 2;
display: flex;
flex-direction: column;
width: min(360px, calc(100% - 1rem));
max-width: 100%;
pointer-events: none;
}
.gate-graph-designer__side-panel > * {
pointer-events: auto;
flex: 1;
min-height: 0;
overflow-y: auto;
box-shadow: 0 4px 24px rgba(15, 23, 42, 0.12);
} }
.gate-graph-designer__empty-actions { .gate-graph-designer__empty-actions {
@@ -2181,17 +2217,117 @@
} }
.gate-designer-node-panel { .gate-designer-node-panel {
flex: 0 0 240px; flex: 0 0 auto;
max-width: 280px; width: 100%;
max-width: none;
padding: 0.75rem 1rem; padding: 0.75rem 1rem;
border: 1px solid var(--jk-border, #dde3ea); border: 1px solid var(--jk-border, #dde3ea);
border-radius: 8px; border-radius: 8px;
background: var(--jk-surface, #fff); background: var(--jk-surface, #fff);
align-self: flex-start; align-self: stretch;
max-height: 70vh; max-height: none;
overflow-y: auto; overflow-y: auto;
} }
.gate-designer-edge-panel {
padding: 0.75rem 1rem;
border: 1px solid var(--jk-border, #dde3ea);
border-radius: 8px;
background: var(--jk-surface, #fff);
}
.gate-designer-edge-panel__route {
margin: 0 0 0.75rem;
font-size: 0.875rem;
word-break: break-word;
}
.gate-designer-edge-panel__help {
margin: 0.5rem 0 0.75rem;
font-size: 0.8125rem;
line-height: 1.45;
}
.gate-designer-node-panel__status-hint {
margin: 0 0 0.75rem;
}
.gate-designer-node-panel__delete {
color: #b91c1c;
border-color: #fecaca;
}
.gate-designer-node-panel__actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.gate-graph-designer__legends {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1.5rem;
align-items: center;
margin-bottom: 0.5rem;
}
.gate-graph-designer__legend {
margin: 0;
}
.gate-graph-designer__node-legend {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 0.75rem;
font-size: 0.8125rem;
}
.gate-graph-designer__node-legend-item {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.gate-graph-designer__node-legend-item::before {
content: '';
width: 0.75rem;
height: 0.75rem;
border-radius: 3px;
border: 1.5px solid var(--jk-border-strong, #c5ced8);
}
.gate-graph-designer__node-legend-item--reached::before {
background: #f0fdf4;
border-color: #16a34a;
}
.gate-graph-designer__node-legend-item--ready::before {
background: #ecfdf5;
border-color: #059669;
}
.gate-graph-designer__node-legend-item--blocked::before {
background: #fef2f2;
border-color: #dc2626;
}
.gate-graph-designer__node-status-mark {
font-size: 11px;
font-weight: 700;
fill: var(--jk-text-secondary, #445);
pointer-events: none;
}
.gate-map-view__node--reached .gate-graph-designer__node-reached-label {
fill: #15803d;
font-weight: 600;
}
.status-pill--done {
background: #f0fdf4;
color: #15803d;
}
.gate-designer-node-panel__header { .gate-designer-node-panel__header {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
@@ -2238,12 +2374,6 @@
font-size: 0.8125rem; font-size: 0.8125rem;
} }
.gate-designer-node-panel__actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.gate-graph-designer__toolbar { .gate-graph-designer__toolbar {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -2347,3 +2477,70 @@
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
} }
.schedule-editor {
border: 1px solid var(--jk-border, #dde3ea);
border-radius: 8px;
padding: 0.75rem 1rem;
margin: 0.75rem 0;
}
.schedule-editor__legend {
font-size: 0.875rem;
font-weight: 600;
padding: 0 0.25rem;
}
.schedule-editor__modes {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-bottom: 0.75rem;
}
.schedule-editor__field {
display: block;
margin-top: 0.5rem;
font-size: 0.875rem;
}
.schedule-editor__weekday-row {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.schedule-weekday {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 6px;
border: 1px solid var(--jk-border, #dde3ea);
font-size: 0.8125rem;
cursor: pointer;
}
.schedule-weekday.is-active {
background: var(--jk-accent-soft, #e8f0fe);
border-color: var(--jk-accent, #2563eb);
}
.gate-activity-set__rhythm-edit,
.action-schedule-section__edit {
margin-top: 0.75rem;
}
.action-schedule-section__summary {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.toggle-inline {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.875rem;
}
+137
View File
@@ -0,0 +1,137 @@
export const WEEKDAY_OPTIONS = [
{ bit: 1, label: 'Mo', index: 0 },
{ bit: 2, label: 'Di', index: 1 },
{ bit: 4, label: 'Mi', index: 2 },
{ bit: 8, label: 'Do', index: 3 },
{ bit: 16, label: 'Fr', index: 4 },
{ bit: 32, label: 'Sa', index: 5 },
{ bit: 64, label: 'So', index: 6 },
]
export const INTERVAL_PRESETS = [
{ id: 'daily', label: 'Täglich', intervalDays: 1 },
{ id: 'every2', label: 'Alle 2 Tage', intervalDays: 2 },
{ id: 'custom', label: 'Individuell…', intervalDays: null },
]
/** Monday=0 … Sunday=6, matching backend weekday_bit. */
export function weekdayBitForDate(date = new Date()) {
const mondayFirst = (date.getDay() + 6) % 7
return 1 << mondayFirst
}
export function defaultScheduleValue(date = new Date()) {
return {
schedule_kind: 'weekdays',
interval_days: 1,
weekday_mask: weekdayBitForDate(date),
pause_until: '',
}
}
export function scheduleFromApi(schedule) {
if (!schedule) return defaultScheduleValue()
return {
schedule_kind: schedule.schedule_kind || 'interval',
interval_days: schedule.interval_days || 1,
weekday_mask: schedule.weekday_mask || 0,
pause_until: schedule.pause_until ? schedule.pause_until.slice(0, 10) : '',
}
}
export function formatScheduleLabel(schedule) {
if (!schedule) return 'Kein Rhythmus'
if (schedule.label) return schedule.label
if (schedule.schedule_kind === 'weekdays') {
const days = WEEKDAY_OPTIONS.filter((d) => (schedule.weekday_mask || 0) & d.bit).map(
(d) => d.label,
)
const base = days.length ? days.join(', ') : 'Wochentage'
return schedule.pause_until ? `${base} (Pause bis ${schedule.pause_until.slice(0, 10)})` : base
}
const days = schedule.interval_days || 1
let base = days === 1 ? 'Täglich' : `Alle ${days} Tage`
if (schedule.pause_until) {
base = `${base} (Pause bis ${schedule.pause_until.slice(0, 10)})`
}
return base
}
export function buildSchedulePayload(value) {
const kind = value.schedule_kind
const payload = {
schedule_kind: kind,
interval_days: kind === 'interval' ? Number(value.interval_days) || 1 : 1,
weekday_mask: kind === 'weekdays' ? Number(value.weekday_mask) || 0 : 0,
pause_until: value.pause_until ? value.pause_until : null,
}
if (kind === 'weekdays' && payload.weekday_mask <= 0) {
throw new Error('Mindestens ein Wochentag auswählen.')
}
if (kind === 'interval' && payload.interval_days < 1) {
throw new Error('Intervall muss mindestens 1 Tag sein.')
}
return payload
}
export function toggleWeekdayMask(mask, bit) {
return (mask & bit) ? mask & ~bit : mask | bit
}
export function detectIntervalPreset(intervalDays) {
const match = INTERVAL_PRESETS.find(
(p) => p.intervalDays === intervalDays && p.id !== 'custom',
)
return match ? match.id : 'custom'
}
function startOfLocalDay(date) {
const copy = new Date(date)
copy.setHours(0, 0, 0, 0)
return copy
}
function parseDueDate(value) {
if (!value) return null
const parsed = new Date(value)
return Number.isNaN(parsed.getTime()) ? null : parsed
}
/**
* Same-routine weekday stickiness: due today if next_due ≤ today
* (includes overdue). Future weekdays stay hidden.
*/
export function isDueOnDate({ schedule, nextDueAt, onDate = new Date() } = {}) {
const day = startOfLocalDay(onDate)
const pauseUntil = schedule?.pause_until
if (pauseUntil) {
const pause = startOfLocalDay(new Date(pauseUntil))
if (!Number.isNaN(pause.getTime()) && day.getTime() <= pause.getTime()) {
return false
}
}
const due = parseDueDate(nextDueAt)
if (due && startOfLocalDay(due).getTime() > day.getTime()) {
return false
}
if ((schedule?.schedule_kind || 'interval') === 'weekdays') {
const mask = Number(schedule?.weekday_mask) || 0
if (due) return true
return Boolean(mask & weekdayBitForDate(day))
}
return true
}
export function isPracticeDueToday(practice, now = new Date()) {
if (!practice || practice.status !== 'active') return false
if (practice.today_completed) return true
const nextDueAt = practice.next_due_at || practice.open_cadence_instance?.due_at
return isDueOnDate({
schedule: practice.schedule,
nextDueAt,
onDate: now,
})
}
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import {
defaultScheduleValue,
formatScheduleLabel,
isDueOnDate,
isPracticeDueToday,
weekdayBitForDate,
} from './scheduleUtils.js'
describe('scheduleUtils weekday foundation', () => {
it('defaults to weekdays on today', () => {
const monday = new Date('2026-08-17T12:00:00')
const value = defaultScheduleValue(monday)
expect(value.schedule_kind).toBe('weekdays')
expect(value.weekday_mask).toBe(weekdayBitForDate(monday))
})
it('does not call interval 7 weekly', () => {
expect(formatScheduleLabel({ schedule_kind: 'interval', interval_days: 7 })).toBe('Alle 7 Tage')
})
it('labels weekday masks as days, not weekly', () => {
expect(
formatScheduleLabel({ schedule_kind: 'weekdays', weekday_mask: 1 | 4 | 64 }),
).toBe('Mo, Mi, So')
})
it('hides future weekday occurrences', () => {
const monday = new Date('2026-08-17T12:00:00')
const tuesdayDue = '2026-08-18T12:00:00'
const due = isDueOnDate({
schedule: { schedule_kind: 'weekdays', weekday_mask: 1 | 4 | 64 },
nextDueAt: tuesdayDue,
onDate: monday,
})
expect(due).toBe(false)
})
it('shows overdue weekday series on a later day', () => {
const tuesday = new Date('2026-08-18T12:00:00')
const mondayDue = '2026-08-17T12:00:00'
expect(
isDueOnDate({
schedule: { schedule_kind: 'weekdays', weekday_mask: 1 },
nextDueAt: mondayDue,
onDate: tuesday,
}),
).toBe(true)
})
it('filters Today to due or completed practices', () => {
const monday = new Date('2026-08-17T12:00:00')
const due = {
status: 'active',
today_completed: false,
next_due_at: '2026-08-17T12:00:00',
schedule: { schedule_kind: 'weekdays', weekday_mask: 1 },
}
const later = {
status: 'active',
today_completed: false,
next_due_at: '2026-08-18T12:00:00',
schedule: { schedule_kind: 'weekdays', weekday_mask: 2 },
}
const done = {
status: 'active',
today_completed: true,
next_due_at: '2026-08-18T12:00:00',
schedule: { schedule_kind: 'weekdays', weekday_mask: 2 },
}
expect(isPracticeDueToday(due, monday)).toBe(true)
expect(isPracticeDueToday(later, monday)).toBe(false)
expect(isPracticeDueToday(done, monday)).toBe(true)
})
})
+10
View File
@@ -9,7 +9,11 @@ import { WidgetCard } from '../components/WidgetCard.jsx'
import { actionPath, scopedPath } from '../utils/routes.js' import { actionPath, scopedPath } from '../utils/routes.js'
import { formatPortfolioRank } from '../utils/portfolioRank.js' import { formatPortfolioRank } from '../utils/portfolioRank.js'
import { useProgramScope } from '../context/ProgramScopeContext.jsx'
function NextActionList({ items, initiativeId, showInitiativeLink = true }) { function NextActionList({ items, initiativeId, showInitiativeLink = true }) {
const { hrefWithScope } = useProgramScope()
if (items.length === 0) { if (items.length === 0) {
return ( return (
<EmptyState message="Keine Empfehlungen — entweder alles erledigt oder noch nichts zu steuern." /> <EmptyState message="Keine Empfehlungen — entweder alles erledigt oder noch nichts zu steuern." />
@@ -17,6 +21,12 @@ function NextActionList({ items, initiativeId, showInitiativeLink = true }) {
} }
function actionLinkForItem(item) { function actionLinkForItem(item) {
if (item.recurring_id && item.initiative_id) {
return {
to: `${hrefWithScope('/work/today', { initiativeId: item.initiative_id })}#today-practice`,
label: 'Übung ausführen',
}
}
if (item.action_id) { if (item.action_id) {
return { to: actionPath(item.action_id), label: 'Arbeitspaket' } return { to: actionPath(item.action_id), label: 'Arbeitspaket' }
} }
+10 -7
View File
@@ -8,6 +8,7 @@ import { ErrorState } from '../components/ErrorState.jsx'
import { LoadingState } from '../components/LoadingState.jsx' import { LoadingState } from '../components/LoadingState.jsx'
import { WidgetCard } from '../components/WidgetCard.jsx' import { WidgetCard } from '../components/WidgetCard.jsx'
import { actionPath, scopedPath } from '../utils/routes.js' import { actionPath, scopedPath } from '../utils/routes.js'
import { PRODUCT_TERMS } from '../constants/productLanguage.js'
function formatDue(iso) { function formatDue(iso) {
if (!iso) return null if (!iso) return null
@@ -23,7 +24,7 @@ function formatDue(iso) {
} }
} }
export function WorkspaceTodayWidget() { export function WorkspaceTodayWidget({ limit = 10 }) {
const [actions, setActions] = useState([]) const [actions, setActions] = useState([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState(null) const [error, setError] = useState(null)
@@ -32,32 +33,34 @@ export function WorkspaceTodayWidget() {
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const data = await listWorkspaceTodayActions(10) const data = await listWorkspaceTodayActions(limit)
setActions(Array.isArray(data) ? data : []) setActions(Array.isArray(data) ? data : [])
} catch (err) { } catch (err) {
setError(err.message) setError(err.message)
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, []) }, [limit])
useEffect(() => { useEffect(() => {
load() load()
}, [load]) }, [load])
const hasMoreHint = limit < 10
return ( return (
<WidgetCard <WidgetCard
title="Heute" title="Heute"
subtitle="Deine Maßnahmen — überfällig und dringend zuerst" subtitle={`Deine ${PRODUCT_TERMS.actionPlural} — überfällig und dringend zuerst (max. ${limit})`}
actions={ actions={
<button type="button" className="btn btn-ghost" onClick={load} disabled={loading}> <button type="button" className="btn btn-ghost" onClick={load} disabled={loading}>
Aktualisieren Aktualisieren
</button> </button>
} }
footer={ footer={
actions.length > 0 ? ( actions.length > 0 || hasMoreHint ? (
<Link to="/work/mine" className="link-inline"> <Link to="/work/mine" className="link-inline">
Alle meine Maßnahmen → Alle {PRODUCT_TERMS.actionPossessive} →
</Link> </Link>
) : null ) : null
} }
@@ -65,7 +68,7 @@ export function WorkspaceTodayWidget() {
{loading && <LoadingState />} {loading && <LoadingState />}
{!loading && error && <ErrorState message={error} onRetry={load} />} {!loading && error && <ErrorState message={error} onRetry={load} />}
{!loading && !error && actions.length === 0 && ( {!loading && !error && actions.length === 0 && (
<EmptyState message="Keine Maßnahmen für heute — prüfe „Nächste sinnvolle Schritte“ oben." /> <EmptyState message={`Keine ${PRODUCT_TERMS.actionPlural} für heute — wähle ein Vorhaben für die Steuerungsempfehlung.`} />
)} )}
{!loading && !error && actions.length > 0 && ( {!loading && !error && actions.length > 0 && (
<ul className="item-list"> <ul className="item-list">
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more