AP1.16a-b: Execution-Graph für Arbeitspaket-Abhängigkeiten.
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 2m20s
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 14s
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 2m20s
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 14s
Migration 023, Engine, API und ADP für Durchführungsplan getrennt vom Gate-Graph; Docs und Sprint-Assignment synchronisiert. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a1b353fcee
commit
1166a0c7f1
16 files changed
+1421
-43
No files matched your search
@@ -65,6 +65,7 @@ from routers import ( # noqa: E402
|
||||
decisions,
|
||||
entity_archetypes,
|
||||
evidence,
|
||||
execution_plan,
|
||||
features,
|
||||
initiatives,
|
||||
journey,
|
||||
@@ -100,6 +101,7 @@ app.include_router(roadmap.initiative_router)
|
||||
app.include_router(roadmap.items_router)
|
||||
app.include_router(roadmap.deps_router)
|
||||
app.include_router(roadmap.criteria_router)
|
||||
app.include_router(execution_plan.initiative_router)
|
||||
app.include_router(evidence.router)
|
||||
app.include_router(decisions.router)
|
||||
app.include_router(reviews.router)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
-- AP1.16a: Durchführungsplan — Action-Reihenfolge, kind, Abhängigkeiten
|
||||
|
||||
ALTER TABLE actions
|
||||
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE actions
|
||||
ADD COLUMN IF NOT EXISTS action_kind VARCHAR(32) NOT NULL DEFAULT 'delivery'
|
||||
CHECK (action_kind IN ('delivery', 'planning', 'review'));
|
||||
|
||||
CREATE INDEX idx_actions_initiative_sort
|
||||
ON actions(tenant_id, initiative_id, sort_order);
|
||||
|
||||
CREATE TABLE action_dependencies (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||
predecessor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||
successor_action_id UUID NOT NULL REFERENCES actions(id) ON DELETE CASCADE,
|
||||
dependency_kind VARCHAR(32) NOT NULL DEFAULT 'requires'
|
||||
CHECK (dependency_kind IN ('requires', 'blocks', 'relates')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (tenant_id, predecessor_action_id, successor_action_id, dependency_kind)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_action_deps_predecessor
|
||||
ON action_dependencies(tenant_id, predecessor_action_id);
|
||||
|
||||
CREATE INDEX idx_action_deps_successor
|
||||
ON action_dependencies(tenant_id, successor_action_id);
|
||||
|
||||
CREATE INDEX idx_action_deps_initiative
|
||||
ON action_dependencies(tenant_id, initiative_id);
|
||||
@@ -29,6 +29,8 @@ class ActionUpdateRequest(BaseModel):
|
||||
clear_project: bool = False
|
||||
roadmap_item_id: Optional[str] = None
|
||||
clear_roadmap_item: bool = False
|
||||
sort_order: Optional[int] = None
|
||||
action_kind: Optional[Literal["delivery", "planning", "review"]] = None
|
||||
|
||||
|
||||
class TaskCreateRequest(BaseModel):
|
||||
@@ -135,6 +137,8 @@ def update_action(
|
||||
clear_project=body.clear_project,
|
||||
roadmap_item_id=body.roadmap_item_id,
|
||||
clear_roadmap_item=body.clear_roadmap_item,
|
||||
sort_order=body.sort_order,
|
||||
action_kind=body.action_kind,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Execution plan API — AP1.16b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from services import actions as action_service
|
||||
from services import execution_plan as execution_plan_service
|
||||
from steering.graph.execution_engine import load_initiative_execution_graph_state
|
||||
from tenant_context import TenantContext
|
||||
|
||||
initiative_router = APIRouter(prefix="/api/initiatives", tags=["execution-plan"])
|
||||
|
||||
|
||||
class ActionDependencyCreateRequest(BaseModel):
|
||||
predecessor_action_id: str
|
||||
successor_action_id: str
|
||||
dependency_kind: Literal["requires", "blocks", "relates"] = "requires"
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/execution/graph-state")
|
||||
def get_initiative_execution_graph_state(
|
||||
initiative_id: str,
|
||||
scope_roadmap_item_id: Optional[str] = Query(default=None),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
|
||||
):
|
||||
try:
|
||||
state = load_initiative_execution_graph_state(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
scope_roadmap_item_id=scope_roadmap_item_id,
|
||||
)
|
||||
if scope_roadmap_item_id is None:
|
||||
from services import actions as action_service
|
||||
from services import roadmap as roadmap_service
|
||||
|
||||
all_actions = action_service.list_actions_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
from steering.graph.execution_engine import compute_planning_debt
|
||||
|
||||
state["planning_debt"] = compute_planning_debt(
|
||||
actions=all_actions,
|
||||
roadmap_items=roadmap_items,
|
||||
)
|
||||
return state
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/execution/dependencies")
|
||||
def list_initiative_action_dependencies(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.read")),
|
||||
):
|
||||
try:
|
||||
return execution_plan_service.list_dependencies_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.post("/{initiative_id}/execution/dependencies", status_code=201)
|
||||
def create_initiative_action_dependency(
|
||||
initiative_id: str,
|
||||
body: ActionDependencyCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
predecessor = action_service.get_action(
|
||||
tenant_id=ctx.tenant_id, action_id=body.predecessor_action_id
|
||||
)
|
||||
successor = action_service.get_action(
|
||||
tenant_id=ctx.tenant_id, action_id=body.successor_action_id
|
||||
)
|
||||
if not predecessor or not successor:
|
||||
raise ValueError("Action nicht gefunden")
|
||||
if (
|
||||
predecessor["initiative_id"] != initiative_id
|
||||
or successor["initiative_id"] != initiative_id
|
||||
):
|
||||
raise ValueError("Actions gehören nicht zum angegebenen Vorhaben")
|
||||
|
||||
return execution_plan_service.add_dependency(
|
||||
tenant_id=ctx.tenant_id,
|
||||
predecessor_action_id=body.predecessor_action_id,
|
||||
successor_action_id=body.successor_action_id,
|
||||
dependency_kind=body.dependency_kind,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.delete(
|
||||
"/{initiative_id}/execution/dependencies/{dependency_id}",
|
||||
status_code=204,
|
||||
)
|
||||
def delete_initiative_action_dependency(
|
||||
initiative_id: str,
|
||||
dependency_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
del initiative_id # scope validated via tenant + dependency row
|
||||
try:
|
||||
execution_plan_service.delete_dependency(
|
||||
tenant_id=ctx.tenant_id,
|
||||
dependency_id=dependency_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -67,6 +67,8 @@ class ActionCreateRequest(BaseModel):
|
||||
project_id: Optional[str] = None
|
||||
roadmap_item_id: Optional[str] = None
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
sort_order: int = 0
|
||||
action_kind: Literal["delivery", "planning", "review"] = "delivery"
|
||||
|
||||
|
||||
class BlockerCreateRequest(BaseModel):
|
||||
@@ -331,6 +333,8 @@ def create_initiative_action(
|
||||
project_id=body.project_id,
|
||||
roadmap_item_id=body.roadmap_item_id,
|
||||
assigned_actor_ids=body.assigned_actor_ids,
|
||||
sort_order=body.sort_order,
|
||||
action_kind=body.action_kind,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -25,9 +25,11 @@ OPEN_ACTION_STATUSES = frozenset(
|
||||
|
||||
_ACTION_COLUMNS = """
|
||||
id, tenant_id, initiative_id, project_id, roadmap_item_id, title, description,
|
||||
status, priority, due_at, created_at, updated_at
|
||||
status, priority, due_at, sort_order, action_kind, created_at, updated_at
|
||||
"""
|
||||
|
||||
ACTION_KINDS = frozenset({"delivery", "planning", "review"})
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
@@ -43,6 +45,11 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return result
|
||||
|
||||
|
||||
def _validate_action_kind(action_kind: str) -> None:
|
||||
if action_kind not in ACTION_KINDS:
|
||||
raise ValueError(f"Ungültiger action_kind: {action_kind}")
|
||||
|
||||
|
||||
def _validate_action_status(status: str) -> None:
|
||||
if status not in ACTION_STATUSES:
|
||||
raise ValueError(f"Ungültiger Action-Status: {status}")
|
||||
@@ -138,6 +145,8 @@ def create_action(
|
||||
project_id: Optional[str] = None,
|
||||
roadmap_item_id: Optional[str] = None,
|
||||
assigned_actor_ids: Optional[list[str]] = None,
|
||||
sort_order: int = 0,
|
||||
action_kind: str = "delivery",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
@@ -145,6 +154,7 @@ def create_action(
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_action_status(status)
|
||||
_validate_priority(priority)
|
||||
_validate_action_kind(action_kind)
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
_validate_project_in_initiative(
|
||||
@@ -169,9 +179,9 @@ def create_action(
|
||||
f"""
|
||||
INSERT INTO actions (
|
||||
tenant_id, initiative_id, project_id, roadmap_item_id, title, description,
|
||||
status, priority, due_at
|
||||
status, priority, due_at, sort_order, action_kind
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_ACTION_COLUMNS}
|
||||
""",
|
||||
(
|
||||
@@ -184,6 +194,8 @@ def create_action(
|
||||
status,
|
||||
priority,
|
||||
due_at,
|
||||
sort_order,
|
||||
action_kind,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
@@ -228,7 +240,7 @@ def list_actions_for_initiative(
|
||||
SELECT {_ACTION_COLUMNS}
|
||||
FROM actions
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC, title
|
||||
ORDER BY sort_order ASC, title ASC, created_at DESC
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
@@ -274,6 +286,8 @@ def update_action(
|
||||
clear_project: bool = False,
|
||||
roadmap_item_id: Optional[str] = None,
|
||||
clear_roadmap_item: bool = False,
|
||||
sort_order: Optional[int] = None,
|
||||
action_kind: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_action(tenant_id=tenant_id, action_id=action_id)
|
||||
if not existing:
|
||||
@@ -331,6 +345,13 @@ def update_action(
|
||||
conn.close()
|
||||
updates.append("roadmap_item_id = %s")
|
||||
params.append(roadmap_item_id)
|
||||
if sort_order is not None:
|
||||
updates.append("sort_order = %s")
|
||||
params.append(sort_order)
|
||||
if action_kind is not None:
|
||||
_validate_action_kind(action_kind)
|
||||
updates.append("action_kind = %s")
|
||||
params.append(action_kind)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Execution plan — Action dependencies CRUD (AP1.16a/b)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
from services.actions import get_action
|
||||
|
||||
DependencyKind = Literal["requires", "blocks", "relates"]
|
||||
|
||||
DEPENDENCY_KINDS = frozenset({"requires", "blocks", "relates"})
|
||||
|
||||
|
||||
def _validate_dependency_kind(kind: str) -> None:
|
||||
if kind not in DEPENDENCY_KINDS:
|
||||
raise ValueError(f"Ungültiger dependency_kind: {kind}")
|
||||
|
||||
|
||||
def _serialize_dependency(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in (
|
||||
"id",
|
||||
"tenant_id",
|
||||
"initiative_id",
|
||||
"predecessor_action_id",
|
||||
"successor_action_id",
|
||||
):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("created_at"):
|
||||
result["created_at"] = result["created_at"].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def _would_create_cycle(
|
||||
*,
|
||||
dependencies: list[dict[str, Any]],
|
||||
predecessor_id: str,
|
||||
successor_id: str,
|
||||
) -> bool:
|
||||
"""Prüft Zyklus wenn successor transitiv predecessor requires."""
|
||||
graph: dict[str, list[str]] = {}
|
||||
for dep in dependencies:
|
||||
if dep.get("dependency_kind", "requires") != "requires":
|
||||
continue
|
||||
pred = str(dep["predecessor_action_id"])
|
||||
succ = str(dep["successor_action_id"])
|
||||
graph.setdefault(succ, []).append(pred)
|
||||
|
||||
graph.setdefault(successor_id, []).append(predecessor_id)
|
||||
|
||||
visiting: set[str] = set()
|
||||
visited: set[str] = set()
|
||||
|
||||
def dfs(node: str) -> bool:
|
||||
if node in visiting:
|
||||
return True
|
||||
if node in visited:
|
||||
return False
|
||||
visiting.add(node)
|
||||
for upstream in graph.get(node, []):
|
||||
if dfs(upstream):
|
||||
return True
|
||||
visiting.remove(node)
|
||||
visited.add(node)
|
||||
return False
|
||||
|
||||
return dfs(successor_id)
|
||||
|
||||
|
||||
def list_dependencies_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id,
|
||||
predecessor_action_id, successor_action_id,
|
||||
dependency_kind, created_at
|
||||
FROM action_dependencies
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY created_at
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_dependency(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def add_dependency(
|
||||
*,
|
||||
tenant_id: str,
|
||||
predecessor_action_id: str,
|
||||
successor_action_id: str,
|
||||
dependency_kind: DependencyKind = "requires",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
_validate_dependency_kind(dependency_kind)
|
||||
if predecessor_action_id == successor_action_id:
|
||||
raise ValueError("Abhängigkeit auf sich selbst nicht erlaubt")
|
||||
|
||||
predecessor = get_action(tenant_id=tenant_id, action_id=predecessor_action_id)
|
||||
successor = get_action(tenant_id=tenant_id, action_id=successor_action_id)
|
||||
if not predecessor or not successor:
|
||||
raise ValueError("Action nicht gefunden")
|
||||
if predecessor["initiative_id"] != successor["initiative_id"]:
|
||||
raise ValueError("Abhängigkeiten nur innerhalb eines Vorhabens")
|
||||
|
||||
initiative_id = predecessor["initiative_id"]
|
||||
existing = list_dependencies_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if _would_create_cycle(
|
||||
dependencies=existing,
|
||||
predecessor_id=predecessor_action_id,
|
||||
successor_id=successor_action_id,
|
||||
):
|
||||
raise ValueError("Abhängigkeit würde Zyklus erzeugen")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM action_dependencies
|
||||
WHERE tenant_id = %s
|
||||
AND predecessor_action_id = %s
|
||||
AND successor_action_id = %s
|
||||
AND dependency_kind = %s
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
predecessor_action_id,
|
||||
successor_action_id,
|
||||
dependency_kind,
|
||||
),
|
||||
)
|
||||
if cur.fetchone():
|
||||
raise ValueError("Abhängigkeit existiert bereits")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO action_dependencies (
|
||||
tenant_id, initiative_id,
|
||||
predecessor_action_id, successor_action_id,
|
||||
dependency_kind
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id,
|
||||
predecessor_action_id, successor_action_id,
|
||||
dependency_kind, created_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
predecessor_action_id,
|
||||
successor_action_id,
|
||||
dependency_kind,
|
||||
),
|
||||
)
|
||||
row = _serialize_dependency(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"action.dependency_added",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"predecessor_action_id": predecessor_action_id,
|
||||
"successor_action_id": successor_action_id,
|
||||
"dependency_kind": dependency_kind,
|
||||
},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def delete_dependency(
|
||||
*, tenant_id: str, dependency_id: str, user_id: Optional[str] = None
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, predecessor_action_id, successor_action_id, dependency_kind
|
||||
FROM action_dependencies
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(dependency_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError("Abhängigkeit nicht gefunden")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM action_dependencies
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(dependency_id, tenant_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"action.dependency_removed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"dependency_id": dependency_id,
|
||||
"predecessor_action_id": str(row["predecessor_action_id"]),
|
||||
"successor_action_id": str(row["successor_action_id"]),
|
||||
},
|
||||
)
|
||||
return True
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Execution plan read models — AP1.16b (Action dependency graph)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
DONE_STATUSES = frozenset({"done"})
|
||||
OPEN_STATUSES = frozenset(
|
||||
{"open", "ready", "in_progress", "blocked", "review_required"}
|
||||
)
|
||||
TERMINAL_SKIP = frozenset({"done", "discarded"})
|
||||
|
||||
|
||||
def _is_predecessor_satisfied(status: str) -> bool:
|
||||
return status in DONE_STATUSES
|
||||
|
||||
|
||||
def _sort_actions(actions: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return sorted(
|
||||
actions,
|
||||
key=lambda action: (
|
||||
action.get("sort_order", 0),
|
||||
action.get("title") or "",
|
||||
str(action.get("id", "")),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _sequential_order_blocked_by(
|
||||
action: dict[str, Any],
|
||||
sorted_actions: list[dict[str, Any]],
|
||||
) -> list[str]:
|
||||
"""Fallback ohne Kanten: sequenzielle Actions nach sort_order."""
|
||||
blocked_by: list[str] = []
|
||||
action_id = str(action["id"])
|
||||
for prev in sorted_actions:
|
||||
if str(prev["id"]) == action_id:
|
||||
break
|
||||
if not _is_predecessor_satisfied(prev.get("status", "open")):
|
||||
blocked_by.append(str(prev["id"]))
|
||||
return blocked_by
|
||||
|
||||
|
||||
def _compute_critical_path(
|
||||
*,
|
||||
action_by_id: dict[str, dict[str, Any]],
|
||||
requires_predecessors: dict[str, list[str]],
|
||||
) -> list[str]:
|
||||
"""Längste Kette über requires-Kanten (Memoization)."""
|
||||
memo: dict[str, list[str]] = {}
|
||||
|
||||
def chain_for(action_id: str) -> list[str]:
|
||||
if action_id in memo:
|
||||
return memo[action_id]
|
||||
preds = requires_predecessors.get(action_id, [])
|
||||
if not preds:
|
||||
memo[action_id] = [action_id]
|
||||
return memo[action_id]
|
||||
best: list[str] = []
|
||||
for pred_id in preds:
|
||||
if pred_id not in action_by_id:
|
||||
continue
|
||||
upstream = chain_for(pred_id)
|
||||
if len(upstream) > len(best):
|
||||
best = upstream
|
||||
memo[action_id] = best + [action_id]
|
||||
return memo[action_id]
|
||||
|
||||
longest: list[str] = []
|
||||
for action_id in action_by_id:
|
||||
candidate = chain_for(action_id)
|
||||
if len(candidate) > len(longest):
|
||||
longest = candidate
|
||||
return longest
|
||||
|
||||
|
||||
def compute_planning_debt(
|
||||
*,
|
||||
actions: list[dict[str, Any]],
|
||||
roadmap_items: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Aktive Gates ohne verknüpfte Actions → Planning Debt (AP1.16d light)."""
|
||||
active_gates = [
|
||||
item
|
||||
for item in roadmap_items
|
||||
if item.get("status") == "active"
|
||||
]
|
||||
if not active_gates:
|
||||
return []
|
||||
|
||||
actions_by_gate: dict[str, int] = {}
|
||||
for action in actions:
|
||||
gate_id = action.get("roadmap_item_id")
|
||||
if not gate_id:
|
||||
continue
|
||||
gid = str(gate_id)
|
||||
actions_by_gate[gid] = actions_by_gate.get(gid, 0) + 1
|
||||
|
||||
debts: list[dict[str, Any]] = []
|
||||
for gate in active_gates:
|
||||
gid = str(gate["id"])
|
||||
if actions_by_gate.get(gid, 0) == 0:
|
||||
debts.append(
|
||||
{
|
||||
"kind": "missing_execution_plan",
|
||||
"roadmap_item_id": gid,
|
||||
"title": gate.get("title"),
|
||||
"message": "Aktiver Zielzustand ohne Durchführungsplan",
|
||||
}
|
||||
)
|
||||
return debts
|
||||
|
||||
|
||||
def compute_execution_graph_state(
|
||||
*,
|
||||
actions: list[dict[str, Any]],
|
||||
dependencies: list[dict[str, Any]],
|
||||
scope_roadmap_item_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Read Model pro Initiative (optional Gate-Scope).
|
||||
|
||||
DB-Kante: predecessor → successor
|
||||
- requires: successor blocked bis predecessor done
|
||||
- blocks: successor blocked solange predecessor offen
|
||||
- relates: keine Blockade
|
||||
"""
|
||||
if scope_roadmap_item_id:
|
||||
scope = str(scope_roadmap_item_id)
|
||||
actions = [
|
||||
a
|
||||
for a in actions
|
||||
if a.get("roadmap_item_id") and str(a["roadmap_item_id"]) == scope
|
||||
]
|
||||
action_ids = {str(a["id"]) for a in actions}
|
||||
dependencies = [
|
||||
dep
|
||||
for dep in dependencies
|
||||
if str(dep["predecessor_action_id"]) in action_ids
|
||||
and str(dep["successor_action_id"]) in action_ids
|
||||
]
|
||||
|
||||
sorted_actions = _sort_actions(actions)
|
||||
action_by_id = {str(action["id"]): action for action in actions}
|
||||
has_any_deps = len(dependencies) > 0
|
||||
|
||||
blocked_by_map: dict[str, list[str]] = {
|
||||
action_id: [] for action_id in action_by_id
|
||||
}
|
||||
requires_predecessors: dict[str, list[str]] = {
|
||||
action_id: [] for action_id in action_by_id
|
||||
}
|
||||
|
||||
for dep in dependencies:
|
||||
kind = dep.get("dependency_kind") or "requires"
|
||||
pred_id = str(dep["predecessor_action_id"])
|
||||
succ_id = str(dep["successor_action_id"])
|
||||
if pred_id not in action_by_id or succ_id not in action_by_id:
|
||||
continue
|
||||
|
||||
if kind == "requires":
|
||||
requires_predecessors.setdefault(succ_id, []).append(pred_id)
|
||||
predecessor = action_by_id[pred_id]
|
||||
if not _is_predecessor_satisfied(predecessor.get("status", "open")):
|
||||
if pred_id not in blocked_by_map[succ_id]:
|
||||
blocked_by_map[succ_id].append(pred_id)
|
||||
elif kind == "blocks":
|
||||
blocker = action_by_id[pred_id]
|
||||
if blocker.get("status", "open") in OPEN_STATUSES:
|
||||
if pred_id not in blocked_by_map[succ_id]:
|
||||
blocked_by_map[succ_id].append(pred_id)
|
||||
# relates: no block
|
||||
|
||||
if not has_any_deps:
|
||||
for action in sorted_actions:
|
||||
action_id = str(action["id"])
|
||||
for prereq_id in _sequential_order_blocked_by(action, sorted_actions):
|
||||
if prereq_id not in blocked_by_map[action_id]:
|
||||
blocked_by_map[action_id].append(prereq_id)
|
||||
if prereq_id not in requires_predecessors.get(action_id, []):
|
||||
requires_predecessors.setdefault(action_id, []).append(prereq_id)
|
||||
|
||||
action_states: dict[str, dict[str, Any]] = {}
|
||||
blocked_actions: list[str] = []
|
||||
ready_actions: list[str] = []
|
||||
|
||||
for action_id, action in action_by_id.items():
|
||||
status = action.get("status", "open")
|
||||
blocked_by = blocked_by_map.get(action_id, [])
|
||||
blocked = len(blocked_by) > 0 and status not in TERMINAL_SKIP
|
||||
ready = status in OPEN_STATUSES and not blocked
|
||||
|
||||
action_states[action_id] = {
|
||||
"status": status,
|
||||
"action_kind": action.get("action_kind", "delivery"),
|
||||
"sort_order": action.get("sort_order", 0),
|
||||
"roadmap_item_id": (
|
||||
str(action["roadmap_item_id"]) if action.get("roadmap_item_id") else None
|
||||
),
|
||||
"blocked": blocked,
|
||||
"ready": ready,
|
||||
"blocked_by": blocked_by,
|
||||
}
|
||||
if blocked:
|
||||
blocked_actions.append(action_id)
|
||||
if ready:
|
||||
ready_actions.append(action_id)
|
||||
|
||||
critical_path = _compute_critical_path(
|
||||
action_by_id=action_by_id,
|
||||
requires_predecessors=requires_predecessors,
|
||||
)
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"items": action_states,
|
||||
"blocked_actions": blocked_actions,
|
||||
"ready_actions": ready_actions,
|
||||
"critical_path": critical_path,
|
||||
"scope_roadmap_item_id": scope_roadmap_item_id,
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def load_initiative_execution_graph_state(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
scope_roadmap_item_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Lädt Actions, Kanten und optional Planning Debt."""
|
||||
from services import actions as action_service
|
||||
from services import execution_plan as execution_plan_service
|
||||
|
||||
actions = action_service.list_actions_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
dependencies = execution_plan_service.list_dependencies_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
|
||||
return compute_execution_graph_state(
|
||||
actions=actions,
|
||||
dependencies=dependencies,
|
||||
scope_roadmap_item_id=scope_roadmap_item_id,
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Unit tests for execution graph engine (AP1.16b)."""
|
||||
|
||||
from steering.graph.execution_engine import (
|
||||
compute_execution_graph_state,
|
||||
compute_planning_debt,
|
||||
)
|
||||
|
||||
|
||||
def _action(action_id: str, status: str = "open", **kwargs):
|
||||
return {
|
||||
"id": action_id,
|
||||
"status": status,
|
||||
"sort_order": kwargs.get("sort_order", 0),
|
||||
"title": kwargs.get("title", action_id),
|
||||
"action_kind": kwargs.get("action_kind", "delivery"),
|
||||
"roadmap_item_id": kwargs.get("roadmap_item_id"),
|
||||
}
|
||||
|
||||
|
||||
def test_requires_blocks_until_predecessor_done():
|
||||
actions = [_action("b", "open"), _action("a", "open")]
|
||||
deps = [
|
||||
{
|
||||
"predecessor_action_id": "b",
|
||||
"successor_action_id": "a",
|
||||
"dependency_kind": "requires",
|
||||
}
|
||||
]
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=deps)
|
||||
assert state["items"]["a"]["blocked"] is True
|
||||
assert state["items"]["a"]["blocked_by"] == ["b"]
|
||||
assert "a" in state["blocked_actions"]
|
||||
assert "a" not in state["ready_actions"]
|
||||
|
||||
actions[0]["status"] = "done"
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=deps)
|
||||
assert state["items"]["a"]["ready"] is True
|
||||
assert "a" in state["ready_actions"]
|
||||
|
||||
|
||||
def test_sequential_fallback_without_edges():
|
||||
actions = [
|
||||
_action("first", "open", sort_order=0),
|
||||
_action("second", "open", sort_order=1),
|
||||
]
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=[])
|
||||
assert state["items"]["first"]["ready"] is True
|
||||
assert state["items"]["second"]["blocked"] is True
|
||||
assert state["items"]["second"]["blocked_by"] == ["first"]
|
||||
|
||||
actions[0]["status"] = "done"
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=[])
|
||||
assert state["items"]["second"]["ready"] is True
|
||||
|
||||
|
||||
def test_blocks_edge():
|
||||
actions = [_action("blocker", "in_progress"), _action("blocked", "open")]
|
||||
deps = [
|
||||
{
|
||||
"predecessor_action_id": "blocker",
|
||||
"successor_action_id": "blocked",
|
||||
"dependency_kind": "blocks",
|
||||
}
|
||||
]
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=deps)
|
||||
assert state["items"]["blocked"]["blocked"] is True
|
||||
|
||||
actions[0]["status"] = "done"
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=deps)
|
||||
assert state["items"]["blocked"]["ready"] is True
|
||||
|
||||
|
||||
def test_critical_path():
|
||||
actions = [
|
||||
_action("a", "done", sort_order=0),
|
||||
_action("b", "open", sort_order=1),
|
||||
_action("c", "open", sort_order=2),
|
||||
]
|
||||
deps = [
|
||||
{
|
||||
"predecessor_action_id": "a",
|
||||
"successor_action_id": "b",
|
||||
"dependency_kind": "requires",
|
||||
},
|
||||
{
|
||||
"predecessor_action_id": "b",
|
||||
"successor_action_id": "c",
|
||||
"dependency_kind": "requires",
|
||||
},
|
||||
]
|
||||
state = compute_execution_graph_state(actions=actions, dependencies=deps)
|
||||
assert state["critical_path"] == ["a", "b", "c"]
|
||||
|
||||
|
||||
def test_planning_debt_active_gate_without_actions():
|
||||
actions = [_action("x", roadmap_item_id="gate-2")]
|
||||
roadmap_items = [
|
||||
{"id": "gate-1", "status": "active", "title": "G5"},
|
||||
{"id": "gate-2", "status": "active", "title": "G6"},
|
||||
]
|
||||
debts = compute_planning_debt(actions=actions, roadmap_items=roadmap_items)
|
||||
assert len(debts) == 1
|
||||
assert debts[0]["roadmap_item_id"] == "gate-1"
|
||||
|
||||
|
||||
def test_scope_filters_to_gate():
|
||||
actions = [
|
||||
_action("a", roadmap_item_id="g1", sort_order=0),
|
||||
_action("b", roadmap_item_id="g2", sort_order=0),
|
||||
]
|
||||
state = compute_execution_graph_state(
|
||||
actions=actions,
|
||||
dependencies=[],
|
||||
scope_roadmap_item_id="g1",
|
||||
)
|
||||
assert set(state["items"].keys()) == {"a"}
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "0.18.0-ap2.0"
|
||||
DB_SCHEMA_VERSION = "019"
|
||||
DB_SCHEMA_VERSION = "023"
|
||||
APP_NAME = "jinkendo-kairo"
|
||||
Reference in new issue
Block a user