AP1.0: Steering Foundation — Lifecycle, Context, Signal Engine
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 1m19s
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 11s
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 1m19s
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 11s
Persistierter Standard Lifecycle pro Initiative, backend/steering/ Skeleton, Attention-Refactor und Hook-Dispatch als Basis für Method Registry. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
451d62ed46
commit
95feba6204
36 files changed
+2006
-724
No files matched your search
@@ -0,0 +1,15 @@
|
||||
"""Adaptive Steering Core — AP1.0 Foundation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.hooks.registry import register_builtin_hooks
|
||||
from steering.methods.registrations import generic_operating
|
||||
|
||||
|
||||
def bootstrap_steering() -> None:
|
||||
"""Register built-in hooks and methods (idempotent)."""
|
||||
register_builtin_hooks()
|
||||
generic_operating.register()
|
||||
|
||||
|
||||
bootstrap_steering()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""SteeringContext read helpers — AP1.0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from services import steering_context as sc_service
|
||||
from steering.lifecycle.states import lifecycle_label
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def get_steering_context_dto(
|
||||
ctx: TenantContext, *, initiative_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
row = sc_service.get_steering_context(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if not row:
|
||||
row = sc_service.ensure_steering_context(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
)
|
||||
return {
|
||||
**row,
|
||||
"lifecycle_label": lifecycle_label(row["lifecycle_state"]),
|
||||
}
|
||||
|
||||
|
||||
def get_or_create_for_initiative(
|
||||
ctx: TenantContext, *, initiative_id: str
|
||||
) -> dict[str, Any]:
|
||||
dto = get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
if not dto:
|
||||
raise ValueError("SteeringContext nicht verfügbar")
|
||||
return dto
|
||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
"""Hook dispatch — AP1.0 stub with audit trail."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from steering.hooks.registry import get_hook
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def dispatch_hook(
|
||||
slug: str,
|
||||
ctx: TenantContext | None,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
tenant_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Dispatch hook — AP1.0: audit only, no handlers yet."""
|
||||
hook = get_hook(slug)
|
||||
if not hook:
|
||||
return [{"kind": "hook_unknown", "slug": slug}]
|
||||
|
||||
tid = tenant_id or (ctx.tenant_id if ctx else None)
|
||||
if tid and user_id:
|
||||
from services.audit import log_audit
|
||||
|
||||
log_audit(
|
||||
f"steering.hook.{slug}",
|
||||
user_id=user_id,
|
||||
tenant_id=tid,
|
||||
details={"slug": slug, "payload": payload},
|
||||
)
|
||||
|
||||
return [{"kind": "hook_dispatched", "slug": slug, "lifecycle_step": hook.lifecycle_step}]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Hook Registry — stabile Einhängepunkte (AP1.0 definitions only)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
_HOOKS: dict[str, "HookDefinition"] = {}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HookDefinition:
|
||||
slug: str
|
||||
lifecycle_step: str
|
||||
description: str
|
||||
since_version: str = "0.11.0"
|
||||
|
||||
|
||||
def register_hook(defn: HookDefinition) -> None:
|
||||
if defn.slug in _HOOKS:
|
||||
raise ValueError(f"Hook already registered: {defn.slug}")
|
||||
_HOOKS[defn.slug] = defn
|
||||
|
||||
|
||||
def get_hook(slug: str) -> HookDefinition | None:
|
||||
return _HOOKS.get(slug)
|
||||
|
||||
|
||||
def list_hooks() -> tuple[HookDefinition, ...]:
|
||||
return tuple(_HOOKS.values())
|
||||
|
||||
|
||||
def clear_hooks_for_tests() -> None:
|
||||
_HOOKS.clear()
|
||||
|
||||
|
||||
def register_builtin_hooks() -> None:
|
||||
"""Slugs aus Target Architecture §7.3 — Handler folgen in AP1.3."""
|
||||
builtins = (
|
||||
("on_goal_captured", "intake", "Ziel erfasst"),
|
||||
("on_method_selected", "method_selection", "Methode gewählt"),
|
||||
("on_structure_required", "structure_setup", "Struktur erforderlich"),
|
||||
("on_backlog_required", "structure_setup", "Backlog erforderlich"),
|
||||
("on_next_action_requested", "action_selection", "Nächste Aktion angefragt"),
|
||||
("on_assignment_required", "assignment", "Zuweisung erforderlich"),
|
||||
("on_blocker_open", "waiting", "Blocker gemeldet"),
|
||||
("on_blocker_resolved", "action_selection", "Blocker geschlossen"),
|
||||
("on_wait_started", "waiting", "Warten begonnen"),
|
||||
("on_result_received", "result_intake", "Ergebnis eingegangen"),
|
||||
("on_evidence_required", "validation", "Nachweis erforderlich"),
|
||||
("on_review_due", "review", "Review fällig"),
|
||||
("on_review_completed", "review", "Review abgeschlossen"),
|
||||
("on_replan_required", "adaptation", "Anpassung nötig"),
|
||||
("on_closure_requested", "closure", "Abschluss angefragt"),
|
||||
)
|
||||
for slug, step, desc in builtins:
|
||||
if slug not in _HOOKS:
|
||||
register_hook(
|
||||
HookDefinition(
|
||||
slug=slug,
|
||||
lifecycle_step=step,
|
||||
description=desc,
|
||||
)
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,78 @@
|
||||
"""Lifecycle orchestrator — persistierter Standard Lifecycle (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from services import steering_context as sc_service
|
||||
from steering.lifecycle.states import validate_lifecycle_state
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def get_lifecycle_state(ctx: TenantContext, initiative_id: str) -> str:
|
||||
row = sc_service.get_steering_context(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
if row:
|
||||
return row["lifecycle_state"]
|
||||
created = sc_service.ensure_steering_context(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
initial_state="intake",
|
||||
)
|
||||
return created["lifecycle_state"]
|
||||
|
||||
|
||||
def transition(
|
||||
ctx: TenantContext | None,
|
||||
initiative_id: str,
|
||||
to_state: str,
|
||||
*,
|
||||
reason: str = "",
|
||||
tenant_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Lifecycle-Transition — AP1.0: freier Übergang (Guards in AP1.1)."""
|
||||
validate_lifecycle_state(to_state)
|
||||
tid = tenant_id or (ctx.tenant_id if ctx else None)
|
||||
if not tid:
|
||||
raise ValueError("tenant_id erforderlich")
|
||||
|
||||
existing = sc_service.get_steering_context(tenant_id=tid, initiative_id=initiative_id)
|
||||
if not existing:
|
||||
existing = sc_service.ensure_steering_context(
|
||||
tenant_id=tid,
|
||||
initiative_id=initiative_id,
|
||||
initial_state=to_state,
|
||||
)
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": None,
|
||||
"to_state": to_state,
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
from_state = existing["lifecycle_state"]
|
||||
if from_state == to_state:
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": from_state,
|
||||
"to_state": to_state,
|
||||
"reason": reason,
|
||||
"unchanged": True,
|
||||
}
|
||||
|
||||
updated = sc_service.update_lifecycle_state(
|
||||
tenant_id=tid,
|
||||
initiative_id=initiative_id,
|
||||
lifecycle_state=to_state,
|
||||
user_id=user_id,
|
||||
reason=reason,
|
||||
from_state=from_state,
|
||||
)
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
"from_state": from_state,
|
||||
"to_state": updated["lifecycle_state"],
|
||||
"reason": reason,
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Standard Lifecycle — gemeinsame Basis (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
STANDARD_LIFECYCLE_STEPS: tuple[str, ...] = (
|
||||
"intake",
|
||||
"method_selection",
|
||||
"structure_setup",
|
||||
"planning",
|
||||
"action_selection",
|
||||
"assignment",
|
||||
"waiting",
|
||||
"result_intake",
|
||||
"validation",
|
||||
"review",
|
||||
"adaptation",
|
||||
"closure",
|
||||
)
|
||||
|
||||
LIFECYCLE_LABELS: dict[str, str] = {
|
||||
"intake": "Aufnahme",
|
||||
"method_selection": "Methode wählen",
|
||||
"structure_setup": "Struktur aufbauen",
|
||||
"planning": "Planung",
|
||||
"action_selection": "Maßnahmen auswählen",
|
||||
"assignment": "Zuweisen",
|
||||
"waiting": "Warten",
|
||||
"result_intake": "Ergebnis aufnehmen",
|
||||
"validation": "Validierung",
|
||||
"review": "Review",
|
||||
"adaptation": "Anpassung",
|
||||
"closure": "Abschluss",
|
||||
}
|
||||
|
||||
|
||||
def lifecycle_label(state: str) -> str:
|
||||
return LIFECYCLE_LABELS.get(state, state)
|
||||
|
||||
|
||||
def validate_lifecycle_state(state: str) -> None:
|
||||
if state not in STANDARD_LIFECYCLE_STEPS:
|
||||
raise ValueError(f"Ungültiger Lifecycle-State: {state}")
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
||||
"""Built-in method: generic_operating — AP1.0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.lifecycle.states import STANDARD_LIFECYCLE_STEPS
|
||||
from steering.methods.registry import MethodDefinition, get_method, register_method
|
||||
|
||||
|
||||
def register() -> None:
|
||||
if get_method("generic_operating"):
|
||||
return
|
||||
register_method(
|
||||
MethodDefinition(
|
||||
key="generic_operating",
|
||||
version="0.1.0",
|
||||
description="Standard-Lifecycle ohne methodenspezifische Spezialisierung",
|
||||
default_lifecycle_steps=STANDARD_LIFECYCLE_STEPS,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Method Registry — built-in steering methods (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
_METHODS: dict[str, "MethodDefinition"] = {}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MethodDefinition:
|
||||
key: str
|
||||
version: str
|
||||
description: str
|
||||
default_lifecycle_steps: tuple[str, ...]
|
||||
|
||||
|
||||
def register_method(defn: MethodDefinition) -> None:
|
||||
if defn.key in _METHODS:
|
||||
raise ValueError(f"Method already registered: {defn.key}")
|
||||
_METHODS[defn.key] = defn
|
||||
|
||||
|
||||
def get_method(key: str) -> MethodDefinition | None:
|
||||
return _METHODS.get(key)
|
||||
|
||||
|
||||
def list_methods() -> tuple[MethodDefinition, ...]:
|
||||
return tuple(_METHODS.values())
|
||||
|
||||
|
||||
def clear_methods_for_tests() -> None:
|
||||
_METHODS.clear()
|
||||
Whitespace-only changes.
@@ -0,0 +1,706 @@
|
||||
"""Default Signal Rule Provider — regelbasiert, tenant-scoped (AP0.8a, AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from tenant_context import TenantContext
|
||||
|
||||
AttentionKind = Literal[
|
||||
"blocked_action",
|
||||
"open_blocker",
|
||||
"high_priority_action",
|
||||
"unassigned_action",
|
||||
"initiative_without_next_action",
|
||||
"stale_initiative",
|
||||
"milestone_at_risk",
|
||||
"overdue_action",
|
||||
"review_due",
|
||||
"recurring_due",
|
||||
"action_review_required",
|
||||
]
|
||||
|
||||
NextActionKind = Literal[
|
||||
"assign_action",
|
||||
"resolve_blocker",
|
||||
"create_action",
|
||||
"convert_backlog",
|
||||
"review_milestone",
|
||||
]
|
||||
|
||||
Severity = Literal["info", "warning", "critical"]
|
||||
|
||||
_SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
|
||||
|
||||
OPEN_BLOCKER_STATUSES = ("open", "in_progress")
|
||||
OPEN_ACTION_STATUSES = ("open", "ready", "in_progress", "blocked", "review_required")
|
||||
ACTIVE_INITIATIVE_STATUSES = ("active", "paused")
|
||||
|
||||
|
||||
def _serialize_attention(row: dict[str, Any]) -> dict[str, Any]:
|
||||
item = dict(row)
|
||||
for key in (
|
||||
"scope_id",
|
||||
"initiative_id",
|
||||
"action_id",
|
||||
"blocker_id",
|
||||
"milestone_id",
|
||||
"review_id",
|
||||
"recurring_element_id",
|
||||
):
|
||||
if item.get(key):
|
||||
item[key] = str(item[key])
|
||||
return item
|
||||
|
||||
|
||||
def _blocked_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'blocked_action' AS kind,
|
||||
'critical' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ist blockiert' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_blocked' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s AND a.status = 'blocked'
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _open_blockers(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'open_blocker' AS kind,
|
||||
'warning' AS severity,
|
||||
b.title AS title,
|
||||
'Offener Blocker im Vorhaben' AS summary,
|
||||
'blocker' AS scope_type,
|
||||
b.id AS scope_id,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
b.id AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'blockers' AS data_source
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
item = _serialize_attention(dict(row))
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def _high_priority_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
actor_filter = ""
|
||||
params: list[Any] = [ctx.tenant_id]
|
||||
if ctx.actor_id:
|
||||
actor_filter = """
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id
|
||||
AND aa.tenant_id = a.tenant_id
|
||||
AND aa.actor_id = %s
|
||||
)
|
||||
"""
|
||||
params.append(ctx.actor_id)
|
||||
else:
|
||||
return []
|
||||
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT
|
||||
'high_priority_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'High-Priority Maßnahme offen' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_high_priority_open' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.priority = 'high'
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
{actor_filter}
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
tuple(params),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _unassigned_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'unassigned_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ohne Zuweisung' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _initiatives_without_next_action(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'initiative_without_next_action' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Keine offene nächste Maßnahme' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = i.id
|
||||
AND a.tenant_id = i.tenant_id
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _stale_initiatives(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'stale_initiative' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Vorhaben seit über 14 Tagen unverändert' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_stale' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status = 'active'
|
||||
AND i.updated_at < NOW() - INTERVAL '14 days'
|
||||
ORDER BY i.updated_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _milestones_at_risk(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'milestone_at_risk' AS kind,
|
||||
'warning' AS severity,
|
||||
m.title AS title,
|
||||
'Meilenstein als gefährdet markiert' AS summary,
|
||||
'milestone' AS scope_type,
|
||||
m.id AS scope_id,
|
||||
m.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
m.id AS milestone_id,
|
||||
'milestone_at_risk' AS reason_code,
|
||||
'milestones' AS data_source
|
||||
FROM milestones m
|
||||
WHERE m.tenant_id = %s AND m.status = 'at_risk'
|
||||
ORDER BY m.updated_at DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _actions_review_required(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'action_review_required' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Ma├ƒnahme wartet auf Review ÔÇö kein geplantes Review verkn├╝pft' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'action_review_required_no_review' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status = 'review_required'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM reviews r
|
||||
WHERE r.tenant_id = a.tenant_id
|
||||
AND r.action_id = a.id
|
||||
AND r.status = 'planned'
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _overdue_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'overdue_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme überfällig' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'action_overdue' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.due_at IS NOT NULL
|
||||
AND a.due_at < NOW()
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
ORDER BY a.due_at ASC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _reviews_due(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'review_due' AS kind,
|
||||
'warning' AS severity,
|
||||
r.title AS title,
|
||||
'Review fällig' AS summary,
|
||||
'review' AS scope_type,
|
||||
r.id AS scope_id,
|
||||
r.initiative_id,
|
||||
r.action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
r.milestone_id,
|
||||
r.id AS review_id,
|
||||
NULL::uuid AS recurring_element_id,
|
||||
'review_due' AS reason_code,
|
||||
'reviews' AS data_source
|
||||
FROM reviews r
|
||||
WHERE r.tenant_id = %s
|
||||
AND r.status = 'planned'
|
||||
AND r.due_at IS NOT NULL
|
||||
AND r.due_at <= NOW()
|
||||
ORDER BY r.due_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
item = _serialize_attention(dict(row))
|
||||
for fk in ("action_id", "milestone_id"):
|
||||
if item.get(fk):
|
||||
item[fk] = str(item[fk])
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def _recurring_due(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'recurring_due' AS kind,
|
||||
'info' AS severity,
|
||||
re.title AS title,
|
||||
'Wiederkehrendes Element fällig' AS summary,
|
||||
'recurring_element' AS scope_type,
|
||||
re.id AS scope_id,
|
||||
re.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
NULL::uuid AS review_id,
|
||||
re.id AS recurring_element_id,
|
||||
'recurring_due' AS reason_code,
|
||||
'recurring_elements' AS data_source
|
||||
FROM recurring_elements re
|
||||
WHERE re.tenant_id = %s
|
||||
AND re.status = 'active'
|
||||
AND re.next_due_at IS NOT NULL
|
||||
AND re.next_due_at <= NOW()
|
||||
ORDER BY re.next_due_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def get_attention_items(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte Attention Items ÔÇö tenant-scoped, erkl├ñrbar."""
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
items: list[dict[str, Any]] = []
|
||||
items.extend(_blocked_actions(cur, ctx))
|
||||
items.extend(_open_blockers(cur, ctx))
|
||||
items.extend(_high_priority_actions(cur, ctx))
|
||||
items.extend(_unassigned_actions(cur, ctx))
|
||||
items.extend(_initiatives_without_next_action(cur, ctx))
|
||||
items.extend(_stale_initiatives(cur, ctx))
|
||||
items.extend(_milestones_at_risk(cur, ctx))
|
||||
items.extend(_overdue_actions(cur, ctx))
|
||||
items.extend(_actions_review_required(cur, ctx))
|
||||
items.extend(_reviews_due(cur, ctx))
|
||||
items.extend(_recurring_due(cur, ctx))
|
||||
|
||||
items.sort(key=lambda x: _SEVERITY_ORDER.get(x["severity"], 99))
|
||||
return items
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_next_action_candidates(
|
||||
ctx: TenantContext, *, limit: int = 10
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte NextActionCandidates ÔÇö limitiert, tenant-scoped."""
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if limit > 50:
|
||||
limit = 50
|
||||
|
||||
conn = get_connection()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'resolve_blocker' AS kind,
|
||||
b.title AS title,
|
||||
'Blocker klären oder Status aktualisieren' AS summary,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'Blocker bearbeiten' AS recommended_action
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'assign_action' AS kind,
|
||||
a.title AS title,
|
||||
'Actor zuweisen' AS summary,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'Maßnahme zuweisen' AS recommended_action
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'convert_backlog' AS kind,
|
||||
bi.title AS title,
|
||||
'Freigegebenes Backlog-Item in Maßnahme umwandeln' AS summary,
|
||||
bi.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
bi.id AS backlog_item_id,
|
||||
'backlog_accepted_not_converted' AS reason_code,
|
||||
'In Maßnahme umwandeln' AS recommended_action
|
||||
FROM backlog_items bi
|
||||
WHERE bi.tenant_id = %s
|
||||
AND bi.status = 'accepted'
|
||||
AND bi.converted_action_id IS NULL
|
||||
ORDER BY bi.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["backlog_item_id"] = str(item["backlog_item_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'create_action' AS kind,
|
||||
i.title AS title,
|
||||
'Nächste Maßnahme für Vorhaben anlegen' AS summary,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'Maßnahme anlegen' AS recommended_action
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = i.id
|
||||
AND a.tenant_id = i.tenant_id
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
candidates.append(item)
|
||||
|
||||
return candidates[:limit]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_next_action_candidates_for_initiative(
|
||||
ctx: TenantContext, *, initiative_id: str, limit: int = 5
|
||||
) -> list[dict[str, Any]]:
|
||||
"""NextActionCandidates f├╝r ein Vorhaben ÔÇö tenant-scoped."""
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if limit > 20:
|
||||
limit = 20
|
||||
|
||||
conn = get_connection()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'resolve_blocker' AS kind,
|
||||
b.title AS title,
|
||||
'Blocker klären oder Status aktualisieren' AS summary,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'Blocker bearbeiten' AS recommended_action
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.initiative_id = %s
|
||||
AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'assign_action' AS kind,
|
||||
a.title AS title,
|
||||
'Actor zuweisen' AS summary,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'Maßnahme zuweisen' AS recommended_action
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s AND a.initiative_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'convert_backlog' AS kind,
|
||||
bi.title AS title,
|
||||
'Freigegebenes Backlog-Item in Maßnahme umwandeln' AS summary,
|
||||
bi.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
bi.id AS backlog_item_id,
|
||||
'backlog_accepted_not_converted' AS reason_code,
|
||||
'In Maßnahme umwandeln' AS recommended_action
|
||||
FROM backlog_items bi
|
||||
WHERE bi.tenant_id = %s AND bi.initiative_id = %s
|
||||
AND bi.status = 'accepted'
|
||||
AND bi.converted_action_id IS NULL
|
||||
ORDER BY bi.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, initiative_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["backlog_item_id"] = str(item["backlog_item_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = %s AND a.tenant_id = %s
|
||||
AND a.status IN ('open', 'ready', 'in_progress', 'blocked', 'review_required')
|
||||
LIMIT 1
|
||||
""",
|
||||
(initiative_id, ctx.tenant_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT title FROM initiatives
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(initiative_id, ctx.tenant_id),
|
||||
)
|
||||
init_row = cur.fetchone()
|
||||
if init_row:
|
||||
candidates.append(
|
||||
{
|
||||
"kind": "create_action",
|
||||
"title": init_row["title"],
|
||||
"summary": "Nächste Maßnahme für Vorhaben anlegen",
|
||||
"initiative_id": initiative_id,
|
||||
"action_id": None,
|
||||
"backlog_item_id": None,
|
||||
"reason_code": "initiative_no_open_action",
|
||||
"recommended_action": "Maßnahme anlegen",
|
||||
}
|
||||
)
|
||||
|
||||
return candidates[:limit]
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Signal Engine — delegates to default rule provider (AP1.0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from steering.signals import default_rules
|
||||
from tenant_context import TenantContext
|
||||
|
||||
SignalKind = Literal["attention", "next_action"]
|
||||
|
||||
|
||||
def evaluate(
|
||||
ctx: TenantContext,
|
||||
kind: SignalKind = "attention",
|
||||
*,
|
||||
limit: int = 10,
|
||||
initiative_id: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if kind == "attention":
|
||||
return default_rules.get_attention_items(ctx)
|
||||
if initiative_id:
|
||||
return default_rules.get_next_action_candidates_for_initiative(
|
||||
ctx, initiative_id=initiative_id, limit=limit
|
||||
)
|
||||
return default_rules.get_next_action_candidates(ctx, limit=limit)
|
||||
Reference in new issue
Block a user