Compare commits
32
Commits
dc6f25b673
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a05bd34af3 | ||
|
|
ea0aa18b8d | ||
|
|
87ecee5301 | ||
|
|
17add13d9d | ||
|
|
88a03a65f2 | ||
|
|
cb165cd821 | ||
|
|
15f87eada2 | ||
|
|
b80f52cb50 | ||
|
|
3a0ef3a734 | ||
|
|
192a65a798 | ||
|
|
19e962d8ec | ||
|
|
b7d88ce24a | ||
|
|
0baa5952bc | ||
|
|
903304adf1 | ||
|
|
be0090d513 | ||
|
|
69c516dba4 | ||
|
|
252b3f05f2 | ||
|
|
89ae15ca4c | ||
|
|
84d912b8ba | ||
|
|
02b6469c2d | ||
|
|
43d33d0edb | ||
|
|
b6434bcc50 | ||
|
|
390161e224 | ||
|
|
a5154cbd3b | ||
|
|
b747200f3a | ||
|
|
1bbc5dbfce | ||
|
|
20636f88d2 | ||
|
|
c5e2c69b1e | ||
|
|
ef5ee0d19b | ||
|
|
a13913f1a0 | ||
|
|
a3b14d9c00 | ||
|
|
f33135b87f |
No files matched your search
@@ -6,7 +6,7 @@ alwaysApply: true
|
||||
|
||||
# Kairo Plugin-Architektur (AP2.3 / AP2.4)
|
||||
|
||||
Verbindliche ADPs: `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `docs/architecture/ADP_Steering_Kernel_Spine_v0.1.md`
|
||||
Verbindliche ADPs: `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md`, `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md`, `docs/architecture/ADP_Steering_Kernel_Spine_v0.1.md`, **`docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`**, **`.cursor/rules/kairo-steering-kernel.mdc`**
|
||||
|
||||
## Vier Schichten — Auflösung zur Laufzeit
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
description: Steering Kernel v0.4 — verbindliche Regeln für Read Models, Proposals, Attention, Agent-Slots, Ranker (alle Coding-Agenten)
|
||||
globs: backend/steering/**,backend/data_layer/initiative_snapshot.py,frontend/src/components/SteeringProposalsPanel.jsx,frontend/src/components/AgentSlotsPanel.jsx,frontend/src/utils/steeringProposals.js,frontend/src/utils/agentSlots.js,frontend/src/utils/sprintCommitProposal.js,frontend/src/pages/initiative/InitiativeInboxPage.jsx,frontend/src/pages/initiative/InitiativePlanPage.jsx,frontend/src/pages/initiative/InitiativeOverviewPage.jsx,frontend/src/pages/modes/PlanSprintPage.jsx
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Kairo Steering Kernel — Coding Rules (verbindlich)
|
||||
|
||||
**Primärdokument:** `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md`
|
||||
**Architektur:** `docs/architecture/ADP_Steering_Kernel_Extension_Model_v0.1.md`
|
||||
|
||||
## Herzmaschine
|
||||
|
||||
- Initiative-Steuerung **nur** via `evaluate_steering()` in `backend/steering/kernel/evaluate.py`
|
||||
- Snapshot spiegelt `evaluation.read_models` + `evaluation.proposals` + `evaluation.agent_slots` — **kein** Duplikat-Rechnen
|
||||
|
||||
## Neue Fähigkeit = Provider registrieren
|
||||
|
||||
| Was | Wo |
|
||||
|-----|-----|
|
||||
| Read Model | `steering/read_models/registry.py` |
|
||||
| Proposal | `steering/proposals/registry.py` |
|
||||
| Attention | `steering/attention/contributors/*.py` + Registry |
|
||||
| Agent-Slot | `steering/agent_slots/registry.py` |
|
||||
| Sprint-Ranker | `register_sprint_commit_ranker()` — weitere Ranker analog |
|
||||
|
||||
Aktivierung über `steering_elements` / `data_slices` im Methoden-Vertrag — **nicht** über Page-Ifs oder `method_key`-Branches im Kernel.
|
||||
|
||||
## Proposals
|
||||
|
||||
- **Kein Auto-Commit** — Accept in UI/API
|
||||
- **Keine feste Bug/Story-Policy** — `ranker_key` + `factors[]`; Heuristik = Fallback (`heuristic_v0`)
|
||||
- Abhängigkeiten: `dependency_refs`, `dependency_blocked`
|
||||
- KI: `agent_v1` Ranker + Actor-Slot — **keine** hardcodierten Prompts (Principle Gate)
|
||||
|
||||
## Agent-Slots
|
||||
|
||||
- Deklarative Fenster für Actors — **kein** Prompt, **keine** Auto-Ausführung
|
||||
- Config: `operatingContext.agent_slot_config` (`enabled_slots`, `guardrail_pack`, `stale_debt_days`)
|
||||
- UI: `AgentSlotsPanel` + Snapshot `steering_kernel.agent_slots`
|
||||
|
||||
## Portfolio (K-Ext-5)
|
||||
|
||||
- Aggregiert Kernel-Output über Initiativen: `GET /api/workspace/steering`
|
||||
- Modul: `steering/portfolio/aggregate.py` — **kein** Duplikat-Rechnen außerhalb Kernel
|
||||
- Legacy `/api/workspace/attention` bleibt (SQL-Regeln) bis vollständige Migration
|
||||
|
||||
## Frontend
|
||||
|
||||
- `SteeringProposalsPanel` + `PROPOSAL_UI_CONFIG` in `utils/steeringProposals.js`
|
||||
- Daten aus `steeringSnapshot.steering_kernel.proposals`
|
||||
- Keine neue Proposal-Page pro Methode
|
||||
|
||||
## Methoden-Parität (Ist)
|
||||
|
||||
| Provider | Element-Gate |
|
||||
|----------|--------------|
|
||||
| `sprint_commit` | `work_cycle_scope` |
|
||||
| `gate_next_actions` | `gate_fulfillment` |
|
||||
| `intake_triage` | `backlog` slice, **excludes** `work_cycle_scope` |
|
||||
| `epic_rollup` | `backlog_epic_hierarchy` |
|
||||
| `planning_debt` / `execution_graph` | `gate_fulfillment` / `critical_path` |
|
||||
| `tech_debt_summary` | `backlog` + `actions` slices |
|
||||
| `review.due` / `recurring.due` / `review.guardrail` | Agent-Slots (data_slices + elements) |
|
||||
|
||||
## Verboten
|
||||
|
||||
- Steuerungslogik außerhalb `backend/steering/`
|
||||
- Archetyp-Ifs für Steuerungs-UI
|
||||
- `evaluate_next_work` für Commit-Vorschläge (Plan ≠ Ist)
|
||||
- OM-Tabellen für Vorschläge
|
||||
|
||||
## Tests
|
||||
|
||||
- Unit-Test pro Provider/Ranker
|
||||
- Snapshot-Integration wenn DB-Test verfügbar
|
||||
- Truth Table aktualisieren
|
||||
@@ -50,6 +50,7 @@ Lies bei Projektstart in dieser Reihenfolge:
|
||||
8. `docs/architecture/Kairo_Tenant_Invariants_v0.1.md`
|
||||
9. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
10. `.cursor/rules/kairo-architecture.mdc`
|
||||
11. **`.cursor/rules/kairo-steering-kernel.mdc`** + `docs/architecture/ADP_Steering_Kernel_Coding_Rules_v0.1.md` (Steering Kernel v0.3 — Read Models, Proposals, Ranker)
|
||||
11. `docs/architecture/ADP_Archetype_Method_Plugin_Architecture_v0.1.md` (AP2.3 — **geliefert**)
|
||||
12. `docs/architecture/ADP_AP2_4_Steering_Elements_and_Method_Contract_v0.1.md` (AP2.4 — **geliefert**)
|
||||
13. `.cursor/rules/kairo-plugin-architecture.mdc`
|
||||
|
||||
@@ -16,6 +16,7 @@ from steering.context import get_steering_context_dto
|
||||
from steering.kernel import evaluate_steering
|
||||
from steering.signals.snapshot_signals import derive_initiative_signals
|
||||
from services.initiatives import get_initiative
|
||||
from services.progression_graph import compute_progression_state
|
||||
from tenant_context import TenantContext
|
||||
|
||||
OPEN_BLOCKER = ("open", "in_progress")
|
||||
@@ -125,7 +126,8 @@ def get_initiative_steering_snapshot(
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, title, status, priority, converted_action_id, created_at, updated_at
|
||||
SELECT id, title, status, priority, converted_action_id, item_kind,
|
||||
parent_backlog_id, created_at, updated_at
|
||||
FROM backlog_items
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY updated_at DESC
|
||||
@@ -296,6 +298,8 @@ def get_initiative_steering_snapshot(
|
||||
evaluation = evaluate_steering(ctx, initiative_id=initiative_id, next_work_limit=5)
|
||||
next_actions = evaluation.next_work
|
||||
kernel_attention = evaluation.attention
|
||||
epic_rollup = evaluation.read_models.get("epic_rollup") or []
|
||||
sprint_commit_proposals = evaluation.proposals.get("sprint_commit") or []
|
||||
|
||||
steering = get_steering_context_dto(ctx, initiative_id=initiative_id)
|
||||
metadata = steering.get("lifecycle_metadata") or {}
|
||||
@@ -350,11 +354,20 @@ def get_initiative_steering_snapshot(
|
||||
"primary_method_key": evaluation.binding.primary_method_key,
|
||||
"composition_modifier": evaluation.binding.composition_modifier,
|
||||
"data_source": evaluation.data_source,
|
||||
"read_models": evaluation.read_models,
|
||||
"proposals": evaluation.proposals,
|
||||
"agent_slots": evaluation.agent_slots,
|
||||
},
|
||||
"upcoming_milestones": upcoming_milestones,
|
||||
"upcoming_roadmap_items": upcoming_milestones,
|
||||
"next_actions": next_actions,
|
||||
"active_work_cycle": active_work_cycle,
|
||||
"epic_rollup": epic_rollup,
|
||||
"sprint_commit_proposals": sprint_commit_proposals,
|
||||
"gate_next_actions_proposals": evaluation.proposals.get("gate_next_actions") or [],
|
||||
"intake_triage_proposals": evaluation.proposals.get("intake_triage") or [],
|
||||
"agent_slots": evaluation.agent_slots,
|
||||
"tech_debt_summary": evaluation.read_models.get("tech_debt_summary") or {},
|
||||
"counts": {
|
||||
"actions_open": open_actions,
|
||||
"actions_blocked": blocked_actions,
|
||||
@@ -371,6 +384,9 @@ def get_initiative_steering_snapshot(
|
||||
"actions": actions,
|
||||
"roadmap_items": roadmap_items,
|
||||
"milestones": roadmap_items,
|
||||
"progression_state": compute_progression_state(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
),
|
||||
"initiative_level": {
|
||||
"blockers": unlinked_blockers,
|
||||
"evidence": unlinked_evidence,
|
||||
@@ -384,6 +400,8 @@ def get_initiative_steering_snapshot(
|
||||
"id": _sid(b["id"]),
|
||||
"title": b["title"],
|
||||
"status": b["status"],
|
||||
"item_kind": b.get("item_kind"),
|
||||
"parent_backlog_id": _sid(b.get("parent_backlog_id")),
|
||||
"converted_action_id": _sid(b.get("converted_action_id")),
|
||||
}
|
||||
for b in backlog
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Portfolio steering read model — K-Ext-5."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.portfolio.aggregate import aggregate_portfolio_steering
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def get_portfolio_steering(
|
||||
ctx: TenantContext,
|
||||
*,
|
||||
max_initiatives: int = 50,
|
||||
total_attention: int = 30,
|
||||
total_next_work: int = 15,
|
||||
) -> dict[str, Any]:
|
||||
return aggregate_portfolio_steering(
|
||||
ctx,
|
||||
max_initiatives=max_initiatives,
|
||||
total_attention=total_attention,
|
||||
total_next_work=total_next_work,
|
||||
)
|
||||
@@ -124,7 +124,7 @@ INITIATIVE_UI_PROFILES: dict[str, dict[str, Any]] = {
|
||||
"planDefaultRoute": "/plan/gates",
|
||||
"workDefaultRoute": "/work/today",
|
||||
"controlDefaultRoute": "/control/status",
|
||||
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
|
||||
"planOutlineKeys": ["profile", "gates", "work"],
|
||||
"workNavKeys": ["today", "mine", "sprint"],
|
||||
"dataSlices": [
|
||||
"actions",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- AP2.2f / ADP Backlog Epic-Hierarchie — parent_backlog_id + item_kind epic
|
||||
|
||||
ALTER TABLE backlog_items
|
||||
ADD COLUMN IF NOT EXISTS parent_backlog_id UUID NULL
|
||||
REFERENCES backlog_items (id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_backlog_parent_backlog
|
||||
ON backlog_items (tenant_id, initiative_id, parent_backlog_id)
|
||||
WHERE parent_backlog_id IS NOT NULL;
|
||||
|
||||
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
|
||||
ALTER TABLE backlog_items
|
||||
ADD CONSTRAINT backlog_items_item_kind_check
|
||||
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic'));
|
||||
@@ -0,0 +1,11 @@
|
||||
-- P7: Technische Schuld — item_kind / action_kind tech_debt
|
||||
|
||||
ALTER TABLE actions DROP CONSTRAINT IF EXISTS actions_action_kind_check;
|
||||
ALTER TABLE actions
|
||||
ADD CONSTRAINT actions_action_kind_check
|
||||
CHECK (action_kind IN ('delivery', 'planning', 'review', 'bug', 'issue', 'tech_debt'));
|
||||
|
||||
ALTER TABLE backlog_items DROP CONSTRAINT IF EXISTS backlog_items_item_kind_check;
|
||||
ALTER TABLE backlog_items
|
||||
ADD CONSTRAINT backlog_items_item_kind_check
|
||||
CHECK (item_kind IN ('story', 'bug', 'issue', 'epic', 'tech_debt'));
|
||||
@@ -0,0 +1,25 @@
|
||||
-- AP A1.1 — CadenceInstance (minimal): eine offene Instanz pro Recurring, Tages-Tracking
|
||||
|
||||
CREATE TABLE cadence_instances (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
recurring_element_id UUID NOT NULL REFERENCES recurring_elements(id) ON DELETE CASCADE,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||
CHECK (status IN ('open', 'completed')),
|
||||
due_at TIMESTAMPTZ NOT NULL,
|
||||
completed_at TIMESTAMPTZ NULL,
|
||||
measurement_note TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_cadence_instances_tenant_recurring
|
||||
ON cadence_instances(tenant_id, recurring_element_id);
|
||||
|
||||
CREATE INDEX idx_cadence_instances_open_due
|
||||
ON cadence_instances(tenant_id, due_at)
|
||||
WHERE status = 'open';
|
||||
|
||||
CREATE UNIQUE INDEX idx_cadence_instances_one_open_per_recurring
|
||||
ON cadence_instances(recurring_element_id)
|
||||
WHERE status = 'open';
|
||||
@@ -0,0 +1,9 @@
|
||||
-- AP A1.2 — RecurringElement an Reifegrad-Stufe binden (Activity Set)
|
||||
|
||||
ALTER TABLE recurring_elements
|
||||
ADD COLUMN roadmap_item_id UUID NULL
|
||||
REFERENCES roadmap_items(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX idx_recurring_elements_stage
|
||||
ON recurring_elements(tenant_id, roadmap_item_id)
|
||||
WHERE roadmap_item_id IS NOT NULL;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- AP-A1-PM-2: Progression graph — join_gate, strand binding, recurring strand
|
||||
|
||||
ALTER TABLE roadmap_items
|
||||
DROP CONSTRAINT IF EXISTS roadmap_items_item_type_check;
|
||||
|
||||
ALTER TABLE roadmap_items
|
||||
ADD CONSTRAINT roadmap_items_item_type_check
|
||||
CHECK (item_type IN (
|
||||
'milestone', 'review_gate', 'maturity_stage', 'work_cycle', 'join_gate'
|
||||
));
|
||||
|
||||
ALTER TABLE roadmap_items
|
||||
ADD COLUMN IF NOT EXISTS strand_project_id UUID NULL
|
||||
REFERENCES projects(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_roadmap_items_strand
|
||||
ON roadmap_items(tenant_id, strand_project_id)
|
||||
WHERE strand_project_id IS NOT NULL;
|
||||
|
||||
ALTER TABLE recurring_elements
|
||||
ADD COLUMN IF NOT EXISTS project_id UUID NULL
|
||||
REFERENCES projects(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_recurring_elements_project
|
||||
ON recurring_elements(tenant_id, project_id)
|
||||
WHERE project_id IS NOT NULL;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Unified Schedule & Cadence Layer (ADP v0.1)
|
||||
|
||||
CREATE TABLE schedules (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
schedule_kind VARCHAR(16) NOT NULL DEFAULT 'interval'
|
||||
CHECK (schedule_kind IN ('interval', 'weekdays')),
|
||||
interval_days INT NULL CHECK (interval_days IS NULL OR interval_days > 0),
|
||||
weekday_mask INT NOT NULL DEFAULT 0,
|
||||
pause_until DATE NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_schedules_tenant ON schedules(tenant_id);
|
||||
|
||||
ALTER TABLE recurring_elements
|
||||
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
|
||||
REFERENCES schedules(id) ON DELETE SET NULL;
|
||||
|
||||
ALTER TABLE recurring_elements
|
||||
ADD COLUMN IF NOT EXISTS action_id UUID NULL
|
||||
REFERENCES actions(id) ON DELETE CASCADE;
|
||||
|
||||
CREATE UNIQUE INDEX idx_recurring_elements_action
|
||||
ON recurring_elements(action_id)
|
||||
WHERE action_id IS NOT NULL;
|
||||
|
||||
ALTER TABLE actions
|
||||
ADD COLUMN IF NOT EXISTS schedule_id UUID NULL
|
||||
REFERENCES schedules(id) ON DELETE SET NULL;
|
||||
|
||||
-- Backfill: one schedule per recurring without schedule_id
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
sid UUID;
|
||||
idays INT;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
SELECT id, tenant_id, interval_days
|
||||
FROM recurring_elements
|
||||
WHERE schedule_id IS NULL
|
||||
LOOP
|
||||
idays := GREATEST(COALESCE(r.interval_days, 1), 1);
|
||||
INSERT INTO schedules (tenant_id, schedule_kind, interval_days, weekday_mask)
|
||||
VALUES (r.tenant_id, 'interval', idays, 0)
|
||||
RETURNING id INTO sid;
|
||||
UPDATE recurring_elements SET schedule_id = sid WHERE id = r.id;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -9,7 +9,9 @@ from capabilities import require_capability
|
||||
from data_layer import actions as dl_actions
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from schemas.schedule_payload import SchedulePayload
|
||||
from services import actions as action_service
|
||||
from services import scheduled_work as scheduled_work_service
|
||||
from services import tasks as task_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
@@ -155,6 +157,47 @@ def update_action(
|
||||
return item
|
||||
|
||||
|
||||
@router.put("/{action_id}/schedule")
|
||||
def upsert_action_schedule(
|
||||
action_id: str,
|
||||
body: SchedulePayload,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
return scheduled_work_service.upsert_action_schedule(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
user_id=ctx.user_id,
|
||||
schedule_kind=body.schedule_kind,
|
||||
interval_days=body.interval_days,
|
||||
weekday_mask=body.weekday_mask,
|
||||
pause_until=body.pause_until_date(),
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Arbeitspaket nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.delete("/{action_id}/schedule", status_code=200)
|
||||
def clear_action_schedule(
|
||||
action_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
return scheduled_work_service.clear_action_schedule(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Arbeitspaket nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.put("/{action_id}/assignments")
|
||||
def set_action_assignments(
|
||||
action_id: str,
|
||||
|
||||
@@ -20,8 +20,9 @@ class BacklogCreateRequest(BaseModel):
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
roadmap_item_id: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
item_kind: Literal["story", "bug", "issue"] = "story"
|
||||
item_kind: Literal["story", "bug", "issue", "epic", "tech_debt"] = "story"
|
||||
parent_action_id: Optional[str] = None
|
||||
parent_backlog_id: Optional[str] = None
|
||||
|
||||
|
||||
class BacklogUpdateRequest(BaseModel):
|
||||
@@ -32,9 +33,11 @@ class BacklogUpdateRequest(BaseModel):
|
||||
roadmap_item_id: Optional[str] = None
|
||||
clear_roadmap_item: bool = False
|
||||
sort_order: Optional[int] = None
|
||||
item_kind: Optional[Literal["story", "bug", "issue"]] = None
|
||||
item_kind: Optional[Literal["story", "bug", "issue", "epic", "tech_debt"]] = None
|
||||
parent_action_id: Optional[str] = None
|
||||
clear_parent_action: bool = False
|
||||
parent_backlog_id: Optional[str] = None
|
||||
clear_parent_backlog: bool = False
|
||||
|
||||
|
||||
class BacklogConvertRequest(BaseModel):
|
||||
@@ -77,6 +80,8 @@ def update_backlog_item(
|
||||
item_kind=body.item_kind,
|
||||
parent_action_id=body.parent_action_id,
|
||||
clear_parent_action=body.clear_parent_action,
|
||||
parent_backlog_id=body.parent_backlog_id,
|
||||
clear_parent_backlog=body.clear_parent_backlog,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -90,11 +95,15 @@ def delete_backlog_item(
|
||||
backlog_item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
if not backlog_service.delete_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
):
|
||||
try:
|
||||
deleted = backlog_service.delete_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
|
||||
|
||||
|
||||
@@ -89,8 +89,9 @@ class BacklogCreateRequest(BaseModel):
|
||||
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
roadmap_item_id: Optional[str] = None
|
||||
item_kind: Literal["story", "bug", "issue"] = "story"
|
||||
item_kind: Literal["story", "bug", "issue", "epic"] = "story"
|
||||
parent_action_id: Optional[str] = None
|
||||
parent_backlog_id: Optional[str] = None
|
||||
|
||||
|
||||
class MilestoneCreateRequest(BaseModel):
|
||||
@@ -131,6 +132,7 @@ class RecurringCreateRequest(BaseModel):
|
||||
status: Literal["active", "paused", "ended"] = "active"
|
||||
interval_days: Optional[int] = Field(default=None, gt=0)
|
||||
next_due_at: Optional[str] = None
|
||||
roadmap_item_id: Optional[str] = None
|
||||
|
||||
|
||||
def _parse_optional_datetime(value: Optional[str], field_name: str) -> Optional[datetime]:
|
||||
@@ -438,6 +440,7 @@ def create_initiative_backlog_item(
|
||||
roadmap_item_id=body.roadmap_item_id,
|
||||
item_kind=body.item_kind,
|
||||
parent_action_id=body.parent_action_id,
|
||||
parent_backlog_id=body.parent_backlog_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
@@ -646,6 +649,7 @@ def create_initiative_recurring(
|
||||
status=body.status,
|
||||
interval_days=body.interval_days,
|
||||
next_due_at=next_due_at,
|
||||
roadmap_item_id=body.roadmap_item_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -14,6 +14,7 @@ from services import backlog as backlog_service
|
||||
from services import blockers as blocker_service
|
||||
from services import decisions as decision_service
|
||||
from services import evidence as evidence_service
|
||||
from services import recurring as recurring_service
|
||||
from services.audit import log_audit
|
||||
from tenant_context import TenantContext
|
||||
|
||||
@@ -74,6 +75,21 @@ class BacklogProposalBody(BaseModel):
|
||||
roadmap_item_id: Optional[str] = None
|
||||
|
||||
|
||||
class BacklogConvertBody(BaseModel):
|
||||
work_cycle_id: Optional[str] = None
|
||||
assign_active_sprint: bool = True
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class RecurringStatusPatch(BaseModel):
|
||||
status: Literal["active", "paused", "ended"]
|
||||
|
||||
|
||||
class ActionWorkCyclePatch(BaseModel):
|
||||
work_cycle_id: Optional[str] = None
|
||||
clear_work_cycle: bool = False
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def operational_me(ctx: TenantContext = Depends(require_operational_capability("kairo.action.read"))):
|
||||
return _ok(
|
||||
@@ -309,3 +325,105 @@ def operational_backlog_proposal(
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
return _ok(ctx, item)
|
||||
|
||||
|
||||
@router.post("/backlog/{backlog_item_id}/convert-to-action", status_code=201)
|
||||
def operational_convert_backlog(
|
||||
backlog_item_id: str,
|
||||
body: BacklogConvertBody,
|
||||
ctx: TenantContext = Depends(require_operational_capability("kairo.backlog.manage")),
|
||||
):
|
||||
assigned = body.assigned_actor_ids
|
||||
if not assigned and ctx.actor_id:
|
||||
assigned = [ctx.actor_id]
|
||||
try:
|
||||
result = backlog_service.convert_backlog_to_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id or None,
|
||||
assigned_actor_ids=assigned,
|
||||
work_cycle_id=body.work_cycle_id,
|
||||
assign_active_sprint=body.assign_active_sprint,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Backlog-Item nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
log_audit(
|
||||
"operational.backlog.convert",
|
||||
user_id=ctx.user_id or None,
|
||||
tenant_id=ctx.tenant_id,
|
||||
details={
|
||||
"backlog_item_id": backlog_item_id,
|
||||
"action_id": result.get("action", {}).get("id"),
|
||||
"work_cycle_id": body.work_cycle_id,
|
||||
"actor_id": ctx.actor_id,
|
||||
},
|
||||
)
|
||||
return _ok(ctx, result)
|
||||
|
||||
|
||||
@router.patch("/recurring/{recurring_id}")
|
||||
def operational_patch_recurring(
|
||||
recurring_id: str,
|
||||
body: RecurringStatusPatch,
|
||||
ctx: TenantContext = Depends(require_operational_capability("kairo.recurring.manage")),
|
||||
):
|
||||
try:
|
||||
item = recurring_service.update_recurring_element(
|
||||
tenant_id=ctx.tenant_id,
|
||||
recurring_id=recurring_id,
|
||||
user_id=ctx.user_id or None,
|
||||
status=body.status,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Recurring-Element nicht gefunden")
|
||||
|
||||
log_audit(
|
||||
"operational.recurring.status",
|
||||
user_id=ctx.user_id or None,
|
||||
tenant_id=ctx.tenant_id,
|
||||
details={
|
||||
"recurring_id": recurring_id,
|
||||
"status": body.status,
|
||||
"actor_id": ctx.actor_id,
|
||||
},
|
||||
)
|
||||
return _ok(ctx, item)
|
||||
|
||||
|
||||
@router.patch("/actions/{action_id}/work-cycle")
|
||||
def operational_patch_action_work_cycle(
|
||||
action_id: str,
|
||||
body: ActionWorkCyclePatch,
|
||||
ctx: TenantContext = Depends(require_operational_capability("kairo.action.manage")),
|
||||
):
|
||||
try:
|
||||
item = action_service.update_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
action_id=action_id,
|
||||
user_id=ctx.user_id or None,
|
||||
work_cycle_id=body.work_cycle_id,
|
||||
clear_work_cycle=body.clear_work_cycle,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Arbeitspaket nicht gefunden")
|
||||
|
||||
log_audit(
|
||||
"operational.action.work_cycle",
|
||||
user_id=ctx.user_id or None,
|
||||
tenant_id=ctx.tenant_id,
|
||||
details={
|
||||
"action_id": action_id,
|
||||
"work_cycle_id": body.work_cycle_id,
|
||||
"clear_work_cycle": body.clear_work_cycle,
|
||||
"actor_id": ctx.actor_id,
|
||||
},
|
||||
)
|
||||
return _ok(ctx, item)
|
||||
@@ -8,6 +8,7 @@ from typing import Literal, Optional
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from schemas.schedule_payload import SchedulePayload
|
||||
from services import recurring as recurring_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
@@ -22,6 +23,13 @@ class RecurringUpdateRequest(BaseModel):
|
||||
clear_interval_days: bool = False
|
||||
next_due_at: Optional[str] = None
|
||||
clear_next_due_at: bool = False
|
||||
roadmap_item_id: Optional[str] = None
|
||||
clear_roadmap_item_id: bool = False
|
||||
schedule: Optional[SchedulePayload] = None
|
||||
|
||||
|
||||
class RecurringCompleteRequest(BaseModel):
|
||||
measurement_note: Optional[str] = Field(default=None, max_length=2000)
|
||||
|
||||
|
||||
def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
|
||||
@@ -53,6 +61,7 @@ def update_recurring_element(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
next_due_at = _parse_datetime(body.next_due_at) if body.next_due_at is not None else None
|
||||
sched = body.schedule
|
||||
try:
|
||||
item = recurring_service.update_recurring_element(
|
||||
tenant_id=ctx.tenant_id,
|
||||
@@ -61,10 +70,16 @@ def update_recurring_element(
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
interval_days=body.interval_days,
|
||||
interval_days=body.interval_days if sched is None else sched.interval_days,
|
||||
clear_interval_days=body.clear_interval_days,
|
||||
next_due_at=next_due_at,
|
||||
clear_next_due_at=body.clear_next_due_at,
|
||||
roadmap_item_id=body.roadmap_item_id,
|
||||
clear_roadmap_item_id=body.clear_roadmap_item_id,
|
||||
schedule_kind=sched.schedule_kind if sched else None,
|
||||
weekday_mask=sched.weekday_mask if sched else None,
|
||||
pause_until=sched.pause_until_date() if sched else None,
|
||||
clear_pause_until=sched is not None and sched.pause_until is None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -73,6 +88,29 @@ def update_recurring_element(
|
||||
return item
|
||||
|
||||
|
||||
@router.post("/{recurring_id}/complete")
|
||||
def complete_recurring_practice(
|
||||
recurring_id: str,
|
||||
body: RecurringCompleteRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
from services.cadence_instance import complete_open_instance
|
||||
|
||||
try:
|
||||
result = complete_open_instance(
|
||||
tenant_id=ctx.tenant_id,
|
||||
recurring_element_id=recurring_id,
|
||||
user_id=ctx.user_id or None,
|
||||
measurement_note=body.measurement_note or "",
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Recurring-Element nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/{recurring_id}", status_code=204)
|
||||
def delete_recurring_element(
|
||||
recurring_id: str,
|
||||
|
||||
+106
-5
@@ -8,6 +8,7 @@ from typing import Any, Literal, Optional
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from schemas.schedule_payload import SchedulePayload
|
||||
from services import roadmap as roadmap_service
|
||||
from services import roadmap_criteria as criteria_service
|
||||
from services import roadmap_plan_snapshot as snapshot_service
|
||||
@@ -18,7 +19,7 @@ router = APIRouter(tags=["roadmap"])
|
||||
|
||||
class RoadmapItemCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
item_type: Literal["milestone", "review_gate", "maturity_stage", "work_cycle"] = "milestone"
|
||||
item_type: Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"] = "milestone"
|
||||
goal_description: str = ""
|
||||
definition_of_done: list[Any] = Field(default_factory=list)
|
||||
status: Literal[
|
||||
@@ -27,12 +28,13 @@ class RoadmapItemCreateRequest(BaseModel):
|
||||
sequencing_mode: Literal["sequential", "parallel", "optional"] = "sequential"
|
||||
target_date: Optional[date] = None
|
||||
sort_order: int = 0
|
||||
strand_project_id: Optional[str] = None
|
||||
initial_criterion_title: Optional[str] = Field(default=None, max_length=500)
|
||||
|
||||
|
||||
class RoadmapItemUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
item_type: Optional[Literal["milestone", "review_gate", "maturity_stage", "work_cycle"]] = None
|
||||
item_type: Optional[Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]] = None
|
||||
goal_description: Optional[str] = None
|
||||
definition_of_done: Optional[list[Any]] = None
|
||||
status: Optional[
|
||||
@@ -42,6 +44,8 @@ class RoadmapItemUpdateRequest(BaseModel):
|
||||
target_date: Optional[date] = None
|
||||
clear_target_date: bool = False
|
||||
sort_order: Optional[int] = None
|
||||
strand_project_id: Optional[str] = None
|
||||
clear_strand_project: bool = False
|
||||
|
||||
|
||||
class DependencyCreateRequest(BaseModel):
|
||||
@@ -84,6 +88,14 @@ class ReopenRequest(BaseModel):
|
||||
reason: str = ""
|
||||
|
||||
|
||||
class GatePracticeCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["active", "paused", "ended"] = "active"
|
||||
interval_days: int = Field(default=1, gt=0)
|
||||
schedule: Optional[SchedulePayload] = None
|
||||
|
||||
|
||||
class PlanSnapshotCreateRequest(BaseModel):
|
||||
reason: str = Field(default="", max_length=2000)
|
||||
|
||||
@@ -166,6 +178,21 @@ def get_initiative_roadmap_graph_state(
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/roadmap/progression-state")
|
||||
def get_initiative_progression_state(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
from services.progression_graph import compute_progression_state
|
||||
|
||||
return compute_progression_state(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@initiative_router.get("/{initiative_id}/roadmap/plan-ist-view")
|
||||
def get_initiative_plan_ist_view(
|
||||
initiative_id: str,
|
||||
@@ -228,6 +255,7 @@ def create_initiative_roadmap_item(
|
||||
sequencing_mode=body.sequencing_mode,
|
||||
target_date=body.target_date,
|
||||
sort_order=body.sort_order,
|
||||
strand_project_id=body.strand_project_id,
|
||||
initial_criterion_title=body.initial_criterion_title,
|
||||
)
|
||||
except ValueError as exc:
|
||||
@@ -265,6 +293,8 @@ def update_roadmap_item(
|
||||
target_date=body.target_date,
|
||||
clear_target_date=body.clear_target_date,
|
||||
sort_order=body.sort_order,
|
||||
strand_project_id=body.strand_project_id,
|
||||
clear_strand_project=body.clear_strand_project,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -278,12 +308,83 @@ def delete_roadmap_item(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
if not roadmap_service.delete_roadmap_item(
|
||||
tenant_id=ctx.tenant_id, item_id=item_id, user_id=ctx.user_id
|
||||
):
|
||||
try:
|
||||
deleted = roadmap_service.delete_roadmap_item(
|
||||
tenant_id=ctx.tenant_id, item_id=item_id, user_id=ctx.user_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
|
||||
|
||||
|
||||
def _work_gate_or_400(*, tenant_id: str, item_id: str) -> dict[str, Any]:
|
||||
item = roadmap_service.get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="RoadmapItem nicht gefunden")
|
||||
if item.get("item_type") == "join_gate":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Join-Gates haben kein Activity Set (Übungen)",
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
@items_router.get("/{item_id}/practices")
|
||||
def list_gate_practices(
|
||||
item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.read")),
|
||||
):
|
||||
from services import recurring as recurring_service
|
||||
|
||||
item = _work_gate_or_400(tenant_id=ctx.tenant_id, item_id=item_id)
|
||||
try:
|
||||
return recurring_service.list_recurring_for_gate(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
gate_id=item_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@items_router.post("/{item_id}/practices", status_code=201)
|
||||
def create_gate_practice(
|
||||
item_id: str,
|
||||
body: GatePracticeCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
item = _work_gate_or_400(tenant_id=ctx.tenant_id, item_id=item_id)
|
||||
sched = body.schedule
|
||||
try:
|
||||
from services.scheduled_work import create_scheduled_action_at_gate
|
||||
|
||||
if sched:
|
||||
return create_scheduled_action_at_gate(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
gate_id=item_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
user_id=ctx.user_id,
|
||||
schedule_kind=sched.schedule_kind,
|
||||
interval_days=sched.interval_days,
|
||||
weekday_mask=sched.weekday_mask,
|
||||
pause_until=sched.pause_until_date(),
|
||||
)
|
||||
return create_scheduled_action_at_gate(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
gate_id=item_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
user_id=ctx.user_id,
|
||||
schedule_kind="weekdays",
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@items_router.post("/{item_id}/verify-reached")
|
||||
def verify_roadmap_item_reached(
|
||||
item_id: str,
|
||||
|
||||
@@ -9,6 +9,7 @@ from data_layer import actions as dl_actions
|
||||
from data_layer import actors as dl_actors
|
||||
from data_layer import attention as dl_attention
|
||||
from data_layer import initiatives as dl_initiatives
|
||||
from data_layer import portfolio_steering as dl_portfolio_steering
|
||||
from data_layer import workspace as dl_workspace
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -96,6 +97,19 @@ def workspace_next_actions(
|
||||
return dl_attention.get_next_action_candidates(ctx, limit=limit or 10)
|
||||
|
||||
|
||||
@router.get("/steering")
|
||||
def workspace_steering(
|
||||
limit: Optional[int] = Query(default=30, ge=1, le=100),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
|
||||
):
|
||||
"""Portfolio-Steuerung — Kernel-Aggregation über alle aktiven Initiativen (K-Ext-5)."""
|
||||
return dl_portfolio_steering.get_portfolio_steering(
|
||||
ctx,
|
||||
total_attention=limit or 30,
|
||||
total_next_work=min(limit or 30, 15),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/portfolio/reorder")
|
||||
def workspace_portfolio_reorder(
|
||||
body: PortfolioReorderRequest,
|
||||
|
||||
@@ -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)
|
||||
File renamed without changes.
@@ -25,11 +25,12 @@ OPEN_ACTION_STATUSES = frozenset(
|
||||
)
|
||||
|
||||
_ACTION_COLUMNS = """
|
||||
id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, title, description,
|
||||
status, priority, due_at, sort_order, action_kind, parent_action_id, created_at, updated_at
|
||||
id, tenant_id, initiative_id, project_id, roadmap_item_id, work_cycle_id, schedule_id,
|
||||
title, description, status, priority, due_at, sort_order, action_kind, parent_action_id,
|
||||
created_at, updated_at
|
||||
"""
|
||||
|
||||
ACTION_KINDS = frozenset({"delivery", "planning", "review", "bug", "issue"})
|
||||
ACTION_KINDS = frozenset({"delivery", "planning", "review", "bug", "issue", "tech_debt"})
|
||||
UNPLAN_ALLOWED_STATUSES = frozenset({"open", "ready"})
|
||||
CARRYOVER_UNPLAN_STATUSES = frozenset(
|
||||
{"open", "ready", "in_progress", "blocked", "review_required"}
|
||||
@@ -47,6 +48,7 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"work_cycle_id",
|
||||
"parent_action_id",
|
||||
"owner_actor_id",
|
||||
"schedule_id",
|
||||
):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
@@ -83,8 +85,8 @@ def _validate_parent_action_in_initiative(
|
||||
if not row:
|
||||
raise ValueError("Referenz-Arbeitspaket (Feature) nicht gefunden")
|
||||
action_kind = row["action_kind"] if isinstance(row, dict) else row[0]
|
||||
if action_kind in ("bug", "issue"):
|
||||
raise ValueError("Referenz muss ein Feature-Arbeitspaket sein, kein Bug/Issue")
|
||||
if action_kind in ("bug", "issue", "tech_debt"):
|
||||
raise ValueError("Referenz muss ein Feature-Arbeitspaket sein, kein Bug/Issue/Schuld")
|
||||
|
||||
|
||||
def _action_kind_to_item_kind(action_kind: str) -> str:
|
||||
@@ -92,6 +94,8 @@ def _action_kind_to_item_kind(action_kind: str) -> str:
|
||||
return "bug"
|
||||
if action_kind == "issue":
|
||||
return "issue"
|
||||
if action_kind == "tech_debt":
|
||||
return "tech_debt"
|
||||
return "story"
|
||||
|
||||
|
||||
@@ -335,7 +339,10 @@ def get_action(*, tenant_id: str, action_id: str) -> Optional[dict[str, Any]]:
|
||||
action = _serialize_row(dict(row))
|
||||
finally:
|
||||
conn.close()
|
||||
return _attach_assignments([action], tenant_id=tenant_id)[0]
|
||||
enriched = _attach_assignments([action], tenant_id=tenant_id)[0]
|
||||
from services.scheduled_work import attach_action_schedule_fields
|
||||
|
||||
return attach_action_schedule_fields(enriched, tenant_id=tenant_id)
|
||||
|
||||
|
||||
def update_action(
|
||||
|
||||
@@ -26,6 +26,8 @@ DEFAULT_AGENT_CAPABILITIES: tuple[str, ...] = (
|
||||
"kairo.backlog.manage",
|
||||
"kairo.decision.read",
|
||||
"kairo.decision.manage",
|
||||
"kairo.recurring.read",
|
||||
"kairo.recurring.manage",
|
||||
)
|
||||
|
||||
ALLOWED_TOKEN_CAPABILITIES = frozenset(DEFAULT_AGENT_CAPABILITIES)
|
||||
|
||||
@@ -65,7 +65,8 @@ def get_starter_preview(
|
||||
{"kind": "maturity_stage", "title": "Stufe 2 — Aufbau", "status": "planned"},
|
||||
{"kind": "maturity_stage", "title": "Stufe 3 — Ziel", "status": "planned"},
|
||||
{"kind": "project", "title": "Training"},
|
||||
{"kind": "recurring", "title": "Tägliche Übung"},
|
||||
{"kind": "recurring", "title": "Vorbeuge-Dehnung"},
|
||||
{"kind": "recurring", "title": "Hüftöffner (Schmetterling)"},
|
||||
]
|
||||
elif archetype_key == "initiative.linear_project":
|
||||
items = [
|
||||
@@ -185,7 +186,6 @@ def _apply_a1(
|
||||
user_id: Optional[str],
|
||||
) -> dict[str, list[str]]:
|
||||
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
|
||||
|
||||
roadmap_ids: list[str] = []
|
||||
@@ -194,6 +194,7 @@ def _apply_a1(
|
||||
("Stufe 2 — Aufbau", "planned"),
|
||||
("Stufe 3 — Ziel", "planned"),
|
||||
]
|
||||
stage_items: list[dict[str, Any]] = []
|
||||
for index, (title, status) in enumerate(stage_defs):
|
||||
item = create_roadmap_item(
|
||||
tenant_id=tenant_id,
|
||||
@@ -205,6 +206,7 @@ def _apply_a1(
|
||||
user_id=user_id,
|
||||
)
|
||||
roadmap_ids.append(item["id"])
|
||||
stage_items.append(item)
|
||||
|
||||
projects = list_projects_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not _find_by_title(projects, "Training"):
|
||||
@@ -217,19 +219,20 @@ def _apply_a1(
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
recurring = list_recurring_for_initiative(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
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,
|
||||
)
|
||||
from services.maturity_practice import seed_practices_for_stage
|
||||
|
||||
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(
|
||||
@@ -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(
|
||||
*,
|
||||
tenant_id: str,
|
||||
|
||||
@@ -23,7 +23,7 @@ def log_audit(
|
||||
INSERT INTO audit_log (action, user_id, tenant_id, details)
|
||||
VALUES (%s, %s, %s, %s::jsonb)
|
||||
""",
|
||||
(action, user_id, tenant_id, json.dumps(details or {})),
|
||||
(action, user_id or None, tenant_id, json.dumps(details or {})),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
|
||||
+153
-7
@@ -10,18 +10,20 @@ from db import get_connection
|
||||
from services.actions import create_action
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import PRIORITIES, get_initiative
|
||||
from services.operating_context import get_operating_context
|
||||
from services.plan_ist import validate_roadmap_item_in_initiative
|
||||
|
||||
BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"]
|
||||
BacklogItemKind = Literal["story", "bug", "issue"]
|
||||
BacklogItemKind = Literal["story", "bug", "issue", "epic", "tech_debt"]
|
||||
|
||||
BACKLOG_STATUSES = frozenset({"new", "triaged", "accepted", "rejected", "converted"})
|
||||
BACKLOG_ITEM_KINDS = frozenset({"story", "bug", "issue"})
|
||||
BACKLOG_ITEM_KINDS = frozenset({"story", "bug", "issue", "epic", "tech_debt"})
|
||||
CONVERTIBLE_ITEM_KINDS = frozenset({"story", "bug", "issue", "tech_debt"})
|
||||
|
||||
_BACKLOG_COLUMNS = """
|
||||
id, tenant_id, initiative_id, title, description, status,
|
||||
priority, roadmap_item_id, converted_action_id, sort_order, item_kind,
|
||||
parent_action_id, created_at, updated_at
|
||||
parent_action_id, parent_backlog_id, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
@@ -34,6 +36,7 @@ def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"converted_action_id",
|
||||
"roadmap_item_id",
|
||||
"parent_action_id",
|
||||
"parent_backlog_id",
|
||||
):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
@@ -59,11 +62,35 @@ def _validate_item_kind(item_kind: str) -> None:
|
||||
raise ValueError(f"Ungültiger Backlog-Typ: {item_kind}")
|
||||
|
||||
|
||||
def _backlog_vocabulary_for_initiative(*, tenant_id: str, initiative_id: str) -> dict[str, Any]:
|
||||
context = get_operating_context(tenant_id=tenant_id, initiative_id=initiative_id)
|
||||
if not context:
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
return context.get("backlog_vocabulary") or {}
|
||||
|
||||
|
||||
def _validate_item_kind_for_initiative(
|
||||
*, tenant_id: str, initiative_id: str, item_kind: str
|
||||
) -> dict[str, Any]:
|
||||
_validate_item_kind(item_kind)
|
||||
vocabulary = _backlog_vocabulary_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
allowed = vocabulary.get("kinds") or []
|
||||
if allowed and item_kind not in allowed:
|
||||
raise ValueError(
|
||||
f"Backlog-Typ '{item_kind}' ist für dieses Vorhaben nicht erlaubt"
|
||||
)
|
||||
return vocabulary
|
||||
|
||||
|
||||
def _item_kind_to_action_kind(item_kind: str) -> str:
|
||||
if item_kind == "bug":
|
||||
return "bug"
|
||||
if item_kind == "issue":
|
||||
return "issue"
|
||||
if item_kind == "tech_debt":
|
||||
return "tech_debt"
|
||||
return "delivery"
|
||||
|
||||
|
||||
@@ -92,6 +119,55 @@ def _validate_parent_action_in_initiative(
|
||||
raise ValueError("Referenz muss ein Feature-Arbeitspaket sein, kein Bug/Issue")
|
||||
|
||||
|
||||
def _validate_backlog_hierarchy(
|
||||
*,
|
||||
cur,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
item_kind: str,
|
||||
parent_backlog_id: Optional[str],
|
||||
parent_action_id: Optional[str],
|
||||
backlog_item_id: Optional[str] = None,
|
||||
epic_hierarchy: bool = True,
|
||||
) -> None:
|
||||
if item_kind == "epic" and not epic_hierarchy:
|
||||
raise ValueError("Epic ist für dieses Vorhaben nicht verfügbar")
|
||||
|
||||
if item_kind == "epic":
|
||||
if parent_backlog_id:
|
||||
raise ValueError("Epic kann keinem übergeordneten Backlog-Item zugeordnet werden")
|
||||
if parent_action_id:
|
||||
raise ValueError("Epic kann keinem Arbeitspaket zugeordnet werden")
|
||||
return
|
||||
|
||||
if not parent_backlog_id:
|
||||
return
|
||||
|
||||
if not epic_hierarchy:
|
||||
raise ValueError("Epic-Zuordnung ist für dieses Vorhaben nicht verfügbar")
|
||||
|
||||
if backlog_item_id and parent_backlog_id == backlog_item_id:
|
||||
raise ValueError("Item kann nicht sich selbst als Epic referenzieren")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, item_kind, initiative_id
|
||||
FROM backlog_items
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(parent_backlog_id, tenant_id),
|
||||
)
|
||||
parent = cur.fetchone()
|
||||
if not parent:
|
||||
raise ValueError("Epic-Referenz nicht gefunden")
|
||||
parent_initiative = parent["initiative_id"] if isinstance(parent, dict) else parent[2]
|
||||
parent_kind = parent["item_kind"] if isinstance(parent, dict) else parent[1]
|
||||
if str(parent_initiative) != initiative_id:
|
||||
raise ValueError("Epic gehört zu einem anderen Vorhaben")
|
||||
if parent_kind != "epic":
|
||||
raise ValueError("Übergeordnetes Item muss ein Epic sein")
|
||||
|
||||
|
||||
def create_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
@@ -104,6 +180,7 @@ def create_backlog_item(
|
||||
sort_order: Optional[int] = None,
|
||||
item_kind: BacklogItemKind = "story",
|
||||
parent_action_id: Optional[str] = None,
|
||||
parent_backlog_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
@@ -111,7 +188,10 @@ def create_backlog_item(
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
_validate_priority(priority)
|
||||
_validate_item_kind(item_kind)
|
||||
vocabulary = _validate_item_kind_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, item_kind=item_kind
|
||||
)
|
||||
epic_hierarchy = bool((vocabulary.get("capabilities") or {}).get("epic_hierarchy"))
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
@@ -130,6 +210,15 @@ def create_backlog_item(
|
||||
initiative_id=initiative_id,
|
||||
parent_action_id=parent_action_id,
|
||||
)
|
||||
_validate_backlog_hierarchy(
|
||||
cur=cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
item_kind=item_kind,
|
||||
parent_backlog_id=parent_backlog_id,
|
||||
parent_action_id=parent_action_id,
|
||||
epic_hierarchy=epic_hierarchy,
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(sort_order), -10) + 10 AS next_order
|
||||
@@ -143,9 +232,9 @@ def create_backlog_item(
|
||||
f"""
|
||||
INSERT INTO backlog_items (
|
||||
tenant_id, initiative_id, title, description, status, priority,
|
||||
roadmap_item_id, sort_order, item_kind, parent_action_id
|
||||
roadmap_item_id, sort_order, item_kind, parent_action_id, parent_backlog_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_BACKLOG_COLUMNS}
|
||||
""",
|
||||
(
|
||||
@@ -159,6 +248,7 @@ def create_backlog_item(
|
||||
sort_order if sort_order is not None else next_order,
|
||||
item_kind,
|
||||
parent_action_id,
|
||||
parent_backlog_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
@@ -229,6 +319,8 @@ def update_backlog_item(
|
||||
item_kind: Optional[BacklogItemKind] = None,
|
||||
parent_action_id: Optional[str] = None,
|
||||
clear_parent_action: bool = False,
|
||||
parent_backlog_id: Optional[str] = None,
|
||||
clear_parent_backlog: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
|
||||
if not existing:
|
||||
@@ -280,21 +372,60 @@ def update_backlog_item(
|
||||
_validate_item_kind(item_kind)
|
||||
updates.append("item_kind = %s")
|
||||
params.append(item_kind)
|
||||
|
||||
effective_kind = item_kind if item_kind is not None else existing.get("item_kind") or "story"
|
||||
vocabulary = _validate_item_kind_for_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
item_kind=effective_kind,
|
||||
)
|
||||
epic_hierarchy = bool((vocabulary.get("capabilities") or {}).get("epic_hierarchy"))
|
||||
|
||||
if clear_parent_action:
|
||||
updates.append("parent_action_id = NULL")
|
||||
elif parent_action_id is not None:
|
||||
updates.append("parent_action_id = %s")
|
||||
params.append(parent_action_id)
|
||||
if clear_parent_backlog:
|
||||
updates.append("parent_backlog_id = NULL")
|
||||
elif parent_backlog_id is not None:
|
||||
updates.append("parent_backlog_id = %s")
|
||||
params.append(parent_backlog_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
effective_parent_backlog = (
|
||||
None
|
||||
if clear_parent_backlog
|
||||
else parent_backlog_id
|
||||
if parent_backlog_id is not None
|
||||
else existing.get("parent_backlog_id")
|
||||
)
|
||||
effective_parent_action = (
|
||||
None
|
||||
if clear_parent_action
|
||||
else parent_action_id
|
||||
if parent_action_id is not None
|
||||
else existing.get("parent_action_id")
|
||||
)
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([backlog_item_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
_validate_backlog_hierarchy(
|
||||
cur=cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
item_kind=effective_kind,
|
||||
parent_backlog_id=effective_parent_backlog,
|
||||
parent_action_id=effective_parent_action,
|
||||
backlog_item_id=backlog_item_id,
|
||||
epic_hierarchy=epic_hierarchy,
|
||||
)
|
||||
if parent_action_id is not None and not clear_parent_action:
|
||||
_validate_parent_action_in_initiative(
|
||||
cur=cur,
|
||||
@@ -348,6 +479,18 @@ def delete_backlog_item(
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM backlog_items
|
||||
WHERE parent_backlog_id = %s AND tenant_id = %s AND status != 'converted'
|
||||
LIMIT 1
|
||||
""",
|
||||
(backlog_item_id, tenant_id),
|
||||
)
|
||||
if cur.fetchone():
|
||||
raise ValueError(
|
||||
"Epic mit untergeordneten Items kann nicht gelöscht werden"
|
||||
)
|
||||
cur.execute(
|
||||
"DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(backlog_item_id, tenant_id),
|
||||
@@ -384,6 +527,10 @@ def convert_backlog_to_action(
|
||||
if existing["status"] not in ("accepted", "triaged", "new"):
|
||||
raise ValueError("Backlog-Item kann in diesem Status nicht konvertiert werden")
|
||||
|
||||
item_kind = existing.get("item_kind") or "story"
|
||||
if item_kind not in CONVERTIBLE_ITEM_KINDS:
|
||||
raise ValueError("Epic kann nicht direkt in ein Arbeitspaket umgewandelt werden")
|
||||
|
||||
resolved_cycle_id = work_cycle_id
|
||||
if not resolved_cycle_id and assign_active_sprint:
|
||||
from services.work_cycle import get_active_work_cycle
|
||||
@@ -394,7 +541,6 @@ def convert_backlog_to_action(
|
||||
if active:
|
||||
resolved_cycle_id = active["id"]
|
||||
|
||||
item_kind = existing.get("item_kind") or "story"
|
||||
action = create_action(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
|
||||
@@ -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
|
||||
@@ -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],
|
||||
}
|
||||
@@ -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 datetime import datetime, timezone
|
||||
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(
|
||||
*,
|
||||
@@ -20,68 +12,33 @@ def on_maturity_stage_reached(
|
||||
reached_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""Pause old routines, activate next stage, seed new routine for next stage."""
|
||||
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
|
||||
from services.progression_graph import on_work_gate_reached
|
||||
|
||||
stages = [
|
||||
s
|
||||
for s in list_roadmap_items_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_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,
|
||||
return on_work_gate_reached(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
reached_item_id=reached_item_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
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] = []
|
||||
for recurring in list_recurring_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
):
|
||||
if recurring.get("status") == "active":
|
||||
update_recurring_element(
|
||||
tenant_id=tenant_id,
|
||||
recurring_id=recurring["id"],
|
||||
status="paused",
|
||||
user_id=user_id,
|
||||
)
|
||||
paused.append(recurring["title"])
|
||||
def on_maturity_stage_reopened(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
stage_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Re-enable exercise set for reopened stage; pause others on same strand."""
|
||||
from services.maturity_practice import activate_stage_practice_set
|
||||
from services.roadmap import get_roadmap_item
|
||||
|
||||
created_recurring = None
|
||||
if next_stage:
|
||||
update_roadmap_item(
|
||||
tenant_id=tenant_id,
|
||||
item_id=next_stage["id"],
|
||||
status="active",
|
||||
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,
|
||||
}
|
||||
stage = get_roadmap_item(tenant_id=tenant_id, item_id=stage_id)
|
||||
if not stage:
|
||||
return {"stage_id": stage_id, "active_practices": []}
|
||||
return activate_stage_practice_set(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
stage=stage,
|
||||
user_id=user_id,
|
||||
)
|
||||
@@ -15,6 +15,8 @@ from entity_archetypes.registry import (
|
||||
from services.initiatives import get_initiative
|
||||
from services.steering_context import ensure_steering_context, get_steering_context
|
||||
from steering.graph.profiles import LIGHT, graph_profile_as_dict
|
||||
from steering.backlog_vocabulary import resolve_backlog_vocabulary
|
||||
from steering.effective_contract import resolve_effective_steering_elements
|
||||
from steering.methods.registry import (
|
||||
get_method,
|
||||
list_compatible_methods,
|
||||
@@ -143,6 +145,19 @@ def _compatible_methods_payload(
|
||||
]
|
||||
|
||||
|
||||
def _resolve_agent_slot_config(metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Governance-Konfiguration für Agent-Slots — keine Prompts."""
|
||||
defaults: dict[str, Any] = {
|
||||
"enabled_slots": ["review.due", "recurring.due", "review.guardrail"],
|
||||
"guardrail_pack": "default_v0",
|
||||
"stale_debt_days": 30,
|
||||
}
|
||||
custom = metadata.get("agent_slots") or metadata.get("agent_slot_config") or {}
|
||||
if isinstance(custom, dict):
|
||||
return {**defaults, **custom}
|
||||
return defaults
|
||||
|
||||
|
||||
def get_operating_context(
|
||||
*, tenant_id: str, initiative_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
@@ -169,6 +184,26 @@ def get_operating_context(
|
||||
method_key=method_key,
|
||||
)
|
||||
method_contract = _resolve_method_contract(method_key)
|
||||
active_composition_modifier = (
|
||||
"agile_iteration"
|
||||
if _resolve_active_agile_composition(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
primary_method_key=method_key,
|
||||
)
|
||||
else None
|
||||
)
|
||||
effective_steering_elements = resolve_effective_steering_elements(
|
||||
method_key,
|
||||
data_slices=data_slices,
|
||||
active_composition_modifier=active_composition_modifier,
|
||||
)
|
||||
backlog_vocabulary = resolve_backlog_vocabulary(
|
||||
data_slices=data_slices,
|
||||
method_key=method_key,
|
||||
steering_elements=effective_steering_elements,
|
||||
)
|
||||
agent_slot_config = _resolve_agent_slot_config(metadata)
|
||||
|
||||
return {
|
||||
"initiative_id": initiative_id,
|
||||
@@ -179,7 +214,8 @@ def get_operating_context(
|
||||
"om_capabilities": sorted(om_capabilities),
|
||||
"data_slices": data_slices,
|
||||
"method_capabilities": _method_capabilities(method_key),
|
||||
"steering_elements": method_contract["steering_elements"],
|
||||
"steering_elements": sorted(effective_steering_elements),
|
||||
"primary_steering_elements": method_contract["steering_elements"],
|
||||
"ui_features": method_contract["ui_features"],
|
||||
"graph_profile": method_contract["graph_profile"],
|
||||
"compatible_methods": _compatible_methods_payload(
|
||||
@@ -191,15 +227,9 @@ def get_operating_context(
|
||||
method_to_dict(m, include_compatibility=False)
|
||||
for m in list_composable_modifiers(method_key)
|
||||
],
|
||||
"active_composition_modifier": (
|
||||
"agile_iteration"
|
||||
if _resolve_active_agile_composition(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
primary_method_key=method_key,
|
||||
)
|
||||
else None
|
||||
),
|
||||
"active_composition_modifier": active_composition_modifier,
|
||||
"backlog_vocabulary": backlog_vocabulary,
|
||||
"agent_slot_config": agent_slot_config,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
@@ -16,14 +16,14 @@ RecurringStatus = Literal["active", "paused", "ended"]
|
||||
RECURRING_STATUSES = frozenset({"active", "paused", "ended"})
|
||||
|
||||
_RECURRING_COLUMNS = """
|
||||
id, tenant_id, initiative_id, title, description, status,
|
||||
interval_days, next_due_at, created_at, updated_at
|
||||
id, tenant_id, initiative_id, roadmap_item_id, project_id, action_id, schedule_id,
|
||||
title, description, status, interval_days, next_due_at, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id"):
|
||||
for key in ("id", "tenant_id", "initiative_id", "roadmap_item_id", "project_id", "action_id", "schedule_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("created_at", "updated_at", "next_due_at"):
|
||||
@@ -46,6 +46,12 @@ def create_recurring_element(
|
||||
status: RecurringStatus = "active",
|
||||
interval_days: Optional[int] = None,
|
||||
next_due_at: Optional[datetime] = None,
|
||||
roadmap_item_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
schedule_id: Optional[str] = None,
|
||||
schedule_kind: str = "interval",
|
||||
weekday_mask: int = 0,
|
||||
pause_until=None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
@@ -57,21 +63,48 @@ def create_recurring_element(
|
||||
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
||||
raise ValueError("Initiative nicht gefunden")
|
||||
|
||||
from services.schedule import create_schedule, initial_due_at
|
||||
|
||||
schedule = None
|
||||
if schedule_id:
|
||||
from services.schedule import get_schedule
|
||||
|
||||
schedule = get_schedule(tenant_id=tenant_id, schedule_id=schedule_id)
|
||||
if not schedule:
|
||||
raise ValueError("Schedule nicht gefunden")
|
||||
else:
|
||||
days = interval_days if interval_days is not None else 1
|
||||
schedule = create_schedule(
|
||||
tenant_id=tenant_id,
|
||||
schedule_kind=schedule_kind, # type: ignore[arg-type]
|
||||
interval_days=days,
|
||||
weekday_mask=weekday_mask,
|
||||
pause_until=pause_until,
|
||||
)
|
||||
schedule_id = schedule["id"]
|
||||
interval_days = schedule.get("interval_days") or days
|
||||
|
||||
if next_due_at is None:
|
||||
next_due_at = initial_due_at(schedule=schedule)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO recurring_elements (
|
||||
tenant_id, initiative_id, title, description, status,
|
||||
interval_days, next_due_at
|
||||
tenant_id, initiative_id, roadmap_item_id, project_id, schedule_id,
|
||||
title, description, status, interval_days, next_due_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING {_RECURRING_COLUMNS}
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
roadmap_item_id,
|
||||
project_id,
|
||||
schedule_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
@@ -90,6 +123,16 @@ def create_recurring_element(
|
||||
tenant_id=tenant_id,
|
||||
details={"recurring_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
|
||||
from services.cadence_instance import ensure_open_instance
|
||||
|
||||
open_inst = ensure_open_instance(
|
||||
tenant_id=tenant_id,
|
||||
recurring_element_id=row["id"],
|
||||
due_at=next_due_at,
|
||||
)
|
||||
row["open_cadence_instance"] = open_inst
|
||||
row["schedule"] = schedule
|
||||
return row
|
||||
|
||||
|
||||
@@ -111,10 +154,25 @@ def list_recurring_for_initiative(
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
rows = [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
from services.cadence_instance import attach_open_instances_to_recurring_list
|
||||
from services.schedule import attach_schedules_to_items
|
||||
|
||||
rows = attach_schedules_to_items(rows, tenant_id=tenant_id)
|
||||
return attach_open_instances_to_recurring_list(rows, tenant_id=tenant_id)
|
||||
|
||||
|
||||
def list_recurring_for_gate(
|
||||
*, tenant_id: str, initiative_id: str, gate_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
items = list_recurring_for_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
return [item for item in items if str(item.get("roadmap_item_id") or "") == str(gate_id)]
|
||||
|
||||
|
||||
def get_recurring_element(
|
||||
*, tenant_id: str, recurring_id: str
|
||||
@@ -131,10 +189,17 @@ def get_recurring_element(
|
||||
(recurring_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
from services.schedule import attach_schedules_to_items
|
||||
|
||||
enriched = attach_schedules_to_items([result], tenant_id=tenant_id)
|
||||
return enriched[0] if enriched else result
|
||||
|
||||
|
||||
def update_recurring_element(
|
||||
*,
|
||||
@@ -148,6 +213,14 @@ def update_recurring_element(
|
||||
clear_interval_days: bool = False,
|
||||
next_due_at: Optional[datetime] = None,
|
||||
clear_next_due_at: bool = False,
|
||||
roadmap_item_id: Optional[str] = None,
|
||||
clear_roadmap_item_id: bool = False,
|
||||
project_id: Optional[str] = None,
|
||||
clear_project_id: bool = False,
|
||||
schedule_kind: Optional[str] = None,
|
||||
weekday_mask: Optional[int] = None,
|
||||
pause_until=None,
|
||||
clear_pause_until: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
|
||||
if not existing:
|
||||
@@ -182,8 +255,50 @@ def update_recurring_element(
|
||||
elif next_due_at is not None:
|
||||
updates.append("next_due_at = %s")
|
||||
params.append(next_due_at)
|
||||
if clear_roadmap_item_id:
|
||||
updates.append("roadmap_item_id = NULL")
|
||||
elif roadmap_item_id is not None:
|
||||
updates.append("roadmap_item_id = %s")
|
||||
params.append(roadmap_item_id)
|
||||
if clear_project_id:
|
||||
updates.append("project_id = NULL")
|
||||
elif project_id is not None:
|
||||
updates.append("project_id = %s")
|
||||
params.append(project_id)
|
||||
|
||||
if not updates:
|
||||
if not updates and schedule_kind is None and weekday_mask is None and not clear_pause_until and pause_until is None:
|
||||
return existing
|
||||
|
||||
schedule_updated = False
|
||||
if existing.get("schedule_id") and (
|
||||
schedule_kind is not None
|
||||
or weekday_mask is not None
|
||||
or pause_until is not None
|
||||
or clear_pause_until
|
||||
or interval_days is not None
|
||||
):
|
||||
from services.schedule import initial_due_at, update_schedule
|
||||
|
||||
sched = update_schedule(
|
||||
tenant_id=tenant_id,
|
||||
schedule_id=str(existing["schedule_id"]),
|
||||
schedule_kind=schedule_kind, # type: ignore[arg-type]
|
||||
interval_days=interval_days,
|
||||
weekday_mask=weekday_mask,
|
||||
pause_until=pause_until,
|
||||
clear_pause_until=clear_pause_until,
|
||||
)
|
||||
if sched:
|
||||
schedule_updated = True
|
||||
if interval_days is not None and sched.get("interval_days"):
|
||||
updates.append("interval_days = %s")
|
||||
params.append(sched["interval_days"])
|
||||
if next_due_at is None:
|
||||
next_due_at = initial_due_at(schedule=sched)
|
||||
updates.append("next_due_at = %s")
|
||||
params.append(next_due_at)
|
||||
|
||||
if not updates and not schedule_updated:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
@@ -226,7 +341,7 @@ def update_recurring_element(
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
return get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id) or result
|
||||
|
||||
|
||||
def delete_recurring_element(
|
||||
@@ -235,6 +350,17 @@ def delete_recurring_element(
|
||||
recurring_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
existing = get_recurring_element(tenant_id=tenant_id, recurring_id=recurring_id)
|
||||
if not existing:
|
||||
return False
|
||||
action_id = existing.get("action_id")
|
||||
if action_id:
|
||||
from services.actions import delete_action
|
||||
|
||||
return delete_action(
|
||||
tenant_id=tenant_id, action_id=action_id, user_id=user_id
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
|
||||
+71
-12
@@ -13,14 +13,14 @@ from services.audit import log_audit
|
||||
from services.initiatives import get_initiative
|
||||
from services.roadmap_criteria import create_default_criterion, prepare_criteria_for_verify
|
||||
|
||||
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage", "work_cycle"]
|
||||
RoadmapItemType = Literal["milestone", "review_gate", "maturity_stage", "work_cycle", "join_gate"]
|
||||
RoadmapItemStatus = Literal[
|
||||
"planned", "active", "at_risk", "reached", "moved", "discarded"
|
||||
]
|
||||
SequencingMode = Literal["sequential", "parallel", "optional"]
|
||||
DependencyType = Literal["requires", "blocks", "related", "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(
|
||||
{"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]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "roadmap_id", "initiative_id", "from_item_id", "to_item_id"):
|
||||
for key in ("id", "tenant_id", "roadmap_id", "initiative_id", "from_item_id", "to_item_id", "strand_project_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("target_date"):
|
||||
@@ -185,6 +185,7 @@ def list_roadmap_items_for_initiative(
|
||||
ri.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
|
||||
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
|
||||
ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order,
|
||||
ri.strand_project_id,
|
||||
ri.created_at, ri.updated_at
|
||||
FROM roadmap_items ri
|
||||
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
|
||||
@@ -208,6 +209,7 @@ def get_roadmap_item(*, tenant_id: str, item_id: str) -> Optional[dict[str, Any]
|
||||
ri.id, ri.tenant_id, ri.roadmap_id, r.initiative_id,
|
||||
ri.item_type, ri.title, ri.goal_description, ri.definition_of_done,
|
||||
ri.status, ri.sequencing_mode, ri.target_date, ri.sort_order,
|
||||
ri.strand_project_id,
|
||||
ri.created_at, ri.updated_at
|
||||
FROM roadmap_items ri
|
||||
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
|
||||
@@ -233,6 +235,7 @@ def create_roadmap_item(
|
||||
sequencing_mode: SequencingMode = "sequential",
|
||||
target_date: Optional[date] = None,
|
||||
sort_order: int = 0,
|
||||
strand_project_id: Optional[str] = None,
|
||||
initial_criterion_title: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -255,12 +258,13 @@ def create_roadmap_item(
|
||||
"""
|
||||
INSERT INTO roadmap_items (
|
||||
tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date, sort_order
|
||||
definition_of_done, status, sequencing_mode, target_date, sort_order,
|
||||
strand_project_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
sort_order, strand_project_id, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
@@ -273,11 +277,12 @@ def create_roadmap_item(
|
||||
sequencing_mode,
|
||||
target_date,
|
||||
sort_order,
|
||||
strand_project_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
row["initiative_id"] = initiative_id
|
||||
if item_type != "work_cycle":
|
||||
if item_type not in ("work_cycle", "join_gate"):
|
||||
create_default_criterion(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
@@ -324,6 +329,8 @@ def update_roadmap_item(
|
||||
target_date: Optional[date] = None,
|
||||
clear_target_date: bool = False,
|
||||
sort_order: Optional[int] = None,
|
||||
strand_project_id: Optional[str] = None,
|
||||
clear_strand_project: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not existing:
|
||||
@@ -373,6 +380,11 @@ def update_roadmap_item(
|
||||
if sort_order is not None:
|
||||
updates.append("sort_order = %s")
|
||||
params.append(sort_order)
|
||||
if clear_strand_project:
|
||||
updates.append("strand_project_id = NULL")
|
||||
elif strand_project_id is not None:
|
||||
updates.append("strand_project_id = %s")
|
||||
params.append(strand_project_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
@@ -383,6 +395,20 @@ def update_roadmap_item(
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
if (
|
||||
status == "active"
|
||||
and existing.get("item_type") == "maturity_stage"
|
||||
):
|
||||
from services.progression_graph import (
|
||||
enforce_single_active_work_gate_per_lane,
|
||||
)
|
||||
|
||||
enforce_single_active_work_gate_per_lane(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=str(existing["initiative_id"]),
|
||||
keep_active_id=item_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE roadmap_items
|
||||
@@ -390,7 +416,7 @@ def update_roadmap_item(
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
sort_order, strand_project_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
@@ -432,6 +458,14 @@ def update_roadmap_item(
|
||||
def delete_roadmap_item(
|
||||
*, tenant_id: str, item_id: str, user_id: Optional[str] = None
|
||||
) -> bool:
|
||||
existing = get_roadmap_item(tenant_id=tenant_id, item_id=item_id)
|
||||
if not existing:
|
||||
return False
|
||||
if existing.get("status") in TERMINAL_STATUSES:
|
||||
raise ValueError(
|
||||
"Erreichte oder terminal abgeschlossene Gates können nicht gelöscht werden"
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
@@ -643,6 +677,10 @@ def verify_reached(
|
||||
raise ValueError("RoadmapItem nicht gefunden")
|
||||
if item["status"] in TERMINAL_STATUSES:
|
||||
raise ValueError(f"RoadmapItem bereits terminal: {item['status']}")
|
||||
if item.get("item_type") == "join_gate":
|
||||
raise ValueError(
|
||||
"Join-Knoten schaltet automatisch, wenn alle Eingänge erreicht sind — kein manuelles Verify"
|
||||
)
|
||||
|
||||
initiative_id = item["initiative_id"]
|
||||
conn = get_connection()
|
||||
@@ -685,7 +723,7 @@ def verify_reached(
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
sort_order, strand_project_id, created_at, updated_at
|
||||
""",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
@@ -709,9 +747,9 @@ def verify_reached(
|
||||
details={"roadmap_item_id": item_id, "verify_reason": verify_reason},
|
||||
)
|
||||
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,
|
||||
initiative_id=initiative_id,
|
||||
reached_item_id=item_id,
|
||||
@@ -760,6 +798,17 @@ def reopen_roadmap_item(
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
if item.get("item_type") == "maturity_stage":
|
||||
from services.progression_graph import (
|
||||
enforce_single_active_work_gate_per_lane,
|
||||
)
|
||||
|
||||
enforce_single_active_work_gate_per_lane(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
keep_active_id=item_id,
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE roadmap_items
|
||||
@@ -767,7 +816,7 @@ def reopen_roadmap_item(
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, roadmap_id, item_type, title, goal_description,
|
||||
definition_of_done, status, sequencing_mode, target_date,
|
||||
sort_order, created_at, updated_at
|
||||
sort_order, strand_project_id, created_at, updated_at
|
||||
""",
|
||||
(item_id, tenant_id),
|
||||
)
|
||||
@@ -783,6 +832,16 @@ def reopen_roadmap_item(
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if row.get("item_type") == "maturity_stage":
|
||||
from services.maturity_stage_transition import on_maturity_stage_reopened
|
||||
|
||||
row["maturity_practice"] = on_maturity_stage_reopened(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
stage_id=item_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
log_audit(
|
||||
"roadmap_item.reopened",
|
||||
user_id=user_id,
|
||||
|
||||
@@ -73,6 +73,15 @@ def _reopen_item_if_reached(
|
||||
) -> None:
|
||||
if item["status"] != "reached":
|
||||
return
|
||||
if item.get("item_type") == "maturity_stage":
|
||||
from services.progression_graph import enforce_single_active_work_gate_per_lane
|
||||
|
||||
enforce_single_active_work_gate_per_lane(
|
||||
cur,
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=str(item["initiative_id"]),
|
||||
keep_active_id=item["id"],
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE roadmap_items
|
||||
|
||||
@@ -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}
|
||||
),
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent slot providers — K-Ext-4 / P8."""
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Agent slots for architecture guardrail reviews at active gates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
|
||||
def resolve_guardrail_review_slots(
|
||||
ctx: SteeringEvalContext,
|
||||
read_models: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Emit guardrail slot when active gate has planning debt or open review actions."""
|
||||
horizon = ctx.horizon
|
||||
if horizon.kind != "gate" or not horizon.gate_roadmap_item_id:
|
||||
return []
|
||||
|
||||
gate_id = str(horizon.gate_roadmap_item_id)
|
||||
guardrail_pack = ctx.agent_slot_config.get("guardrail_pack") or "default_v0"
|
||||
|
||||
has_planned_guardrail = any(
|
||||
review.get("status") == "planned"
|
||||
and str(review.get("milestone_id") or "") == gate_id
|
||||
for review in ctx.reviews
|
||||
)
|
||||
if has_planned_guardrail:
|
||||
return []
|
||||
|
||||
planning_debt = read_models.get("planning_debt") or []
|
||||
gate_debt = any(str(d.get("roadmap_item_id") or "") == gate_id for d in planning_debt)
|
||||
open_review_actions = any(
|
||||
action.get("action_kind") == "review"
|
||||
and str(action.get("roadmap_item_id") or "") == gate_id
|
||||
and action.get("status") in ("open", "ready", "in_progress", "review_required")
|
||||
for action in ctx.actions
|
||||
)
|
||||
if not gate_debt and not open_review_actions:
|
||||
return []
|
||||
|
||||
return [
|
||||
{
|
||||
"slot_key": "review.guardrail",
|
||||
"scope_type": "roadmap_item",
|
||||
"scope_id": gate_id,
|
||||
"title": horizon.gate_title or "Guardrail-Review",
|
||||
"summary": "Architektur-Guardrail für aktives Gate prüfen",
|
||||
"actor_role_hint": "architecture_reviewer",
|
||||
"payload_keys": ["checklist_id", "guardrail_pack"],
|
||||
"guardrail_pack": guardrail_pack,
|
||||
"priority": "normal",
|
||||
"roadmap_item_id": gate_id,
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Agent slots for due recurring elements."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
|
||||
def _parse_due(value: Any) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
text = str(value).replace("Z", "+00:00")
|
||||
parsed = datetime.fromisoformat(text)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def resolve_recurring_due_slots(ctx: SteeringEvalContext) -> list[dict[str, Any]]:
|
||||
now = datetime.now(timezone.utc)
|
||||
slots: list[dict[str, Any]] = []
|
||||
|
||||
for element in ctx.recurring_elements:
|
||||
if element.get("status") != "active":
|
||||
continue
|
||||
due = _parse_due(element.get("next_due_at"))
|
||||
if due is None or due > now:
|
||||
continue
|
||||
slots.append(
|
||||
{
|
||||
"slot_key": "recurring.due",
|
||||
"scope_type": "recurring_element",
|
||||
"scope_id": str(element["id"]),
|
||||
"title": element.get("title") or "Rhythmus",
|
||||
"summary": "Wiederkehrendes Element ist fällig",
|
||||
"actor_role_hint": "operator",
|
||||
"payload_keys": ["recurring_id", "interval_days"],
|
||||
"priority": "normal",
|
||||
"recurring_element_id": str(element["id"]),
|
||||
}
|
||||
)
|
||||
|
||||
return slots
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Agent slot provider registry — K-Ext-4."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
AgentSlotResolve = Callable[[SteeringEvalContext, dict[str, Any], dict[str, Any]], list[dict]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentSlotProvider:
|
||||
slot_key: str
|
||||
requires_elements: frozenset[str]
|
||||
requires_data_slices: frozenset[str]
|
||||
resolve: AgentSlotResolve
|
||||
requires_any_element: frozenset[str] = field(default_factory=frozenset)
|
||||
excludes_elements: frozenset[str] = field(default_factory=frozenset)
|
||||
|
||||
|
||||
_PROVIDERS: list[AgentSlotProvider] = []
|
||||
|
||||
|
||||
def register_agent_slot(provider: AgentSlotProvider) -> None:
|
||||
_PROVIDERS.append(provider)
|
||||
|
||||
|
||||
def _slot_enabled(ctx: SteeringEvalContext, slot_key: str) -> bool:
|
||||
config = ctx.agent_slot_config
|
||||
enabled = config.get("enabled_slots")
|
||||
if enabled is None:
|
||||
return True
|
||||
return slot_key in enabled
|
||||
|
||||
|
||||
def compute_agent_slots(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
read_models: dict[str, Any],
|
||||
proposals: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
elements = ctx.steering_elements
|
||||
slices = frozenset(ctx.data_slices)
|
||||
slots: list[dict[str, Any]] = []
|
||||
|
||||
for provider in _PROVIDERS:
|
||||
if not _slot_enabled(ctx, provider.slot_key):
|
||||
continue
|
||||
if provider.requires_elements and not provider.requires_elements <= elements:
|
||||
continue
|
||||
if provider.excludes_elements and provider.excludes_elements & elements:
|
||||
continue
|
||||
if provider.requires_any_element and not (
|
||||
provider.requires_any_element & elements
|
||||
):
|
||||
continue
|
||||
if provider.requires_data_slices and not provider.requires_data_slices <= slices:
|
||||
continue
|
||||
slots.extend(provider.resolve(ctx, read_models, proposals))
|
||||
|
||||
for slot in slots:
|
||||
slot.setdefault("data_source", "steering_kernel")
|
||||
slot.setdefault("initiative_id", ctx.initiative_id)
|
||||
slot.setdefault("context_refs", ["steering_snapshot", "operating_context"])
|
||||
|
||||
slots.sort(
|
||||
key=lambda s: {"high": 0, "normal": 1, "low": 2}.get(s.get("priority", "normal"), 9)
|
||||
)
|
||||
return slots
|
||||
|
||||
|
||||
def _register_builtin_agent_slots() -> None:
|
||||
from steering.agent_slots.guardrail_review import resolve_guardrail_review_slots
|
||||
from steering.agent_slots.recurring_due import resolve_recurring_due_slots
|
||||
from steering.agent_slots.review_due import resolve_review_due_slots
|
||||
|
||||
register_agent_slot(
|
||||
AgentSlotProvider(
|
||||
slot_key="review.due",
|
||||
requires_elements=frozenset(),
|
||||
requires_data_slices=frozenset({"reviews"}),
|
||||
resolve=lambda ctx, read_models, proposals: resolve_review_due_slots(ctx),
|
||||
)
|
||||
)
|
||||
register_agent_slot(
|
||||
AgentSlotProvider(
|
||||
slot_key="recurring.due",
|
||||
requires_elements=frozenset({"recurring_rhythm"}),
|
||||
requires_data_slices=frozenset({"recurring"}),
|
||||
resolve=lambda ctx, read_models, proposals: resolve_recurring_due_slots(ctx),
|
||||
)
|
||||
)
|
||||
register_agent_slot(
|
||||
AgentSlotProvider(
|
||||
slot_key="review.guardrail",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
requires_data_slices=frozenset({"reviews", "roadmap"}),
|
||||
resolve=lambda ctx, read_models, proposals: resolve_guardrail_review_slots(
|
||||
ctx, read_models
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
_register_builtin_agent_slots()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Agent slots for due planned reviews."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
|
||||
def _parse_due(value: Any) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
text = str(value).replace("Z", "+00:00")
|
||||
parsed = datetime.fromisoformat(text)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def resolve_review_due_slots(ctx: SteeringEvalContext) -> list[dict[str, Any]]:
|
||||
now = datetime.now(timezone.utc)
|
||||
slots: list[dict[str, Any]] = []
|
||||
|
||||
for review in ctx.reviews:
|
||||
if review.get("status") != "planned":
|
||||
continue
|
||||
due = _parse_due(review.get("due_at"))
|
||||
if due is None or due > now:
|
||||
continue
|
||||
slots.append(
|
||||
{
|
||||
"slot_key": "review.due",
|
||||
"scope_type": "review",
|
||||
"scope_id": str(review["id"]),
|
||||
"title": review.get("title") or "Review",
|
||||
"summary": "Geplantes Review ist fällig",
|
||||
"actor_role_hint": "reviewer",
|
||||
"payload_keys": ["review_id", "checklist_id"],
|
||||
"priority": "high" if due < now else "normal",
|
||||
"review_id": str(review["id"]),
|
||||
"action_id": (
|
||||
str(review["action_id"]) if review.get("action_id") else None
|
||||
),
|
||||
"milestone_id": (
|
||||
str(review["milestone_id"]) if review.get("milestone_id") else None
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
return slots
|
||||
@@ -0,0 +1 @@
|
||||
"""Attention contributors — K-Ext-2."""
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Attention evaluation context — shared caches for contributors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.kernel.models import HorizonMarker, SteeringBinding
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionEvalContext:
|
||||
tenant_ctx: TenantContext
|
||||
initiative_id: str
|
||||
binding: SteeringBinding
|
||||
horizon: HorizonMarker
|
||||
next_work: list[dict[str, Any]]
|
||||
read_models: dict[str, Any]
|
||||
proposals: dict[str, Any]
|
||||
eval_ctx: SteeringEvalContext | None = None
|
||||
|
||||
_actions: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_blockers: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_roadmap_items: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_dependencies: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_graph_state: dict[str, Any] | None = field(default=None, repr=False)
|
||||
_gate_scope: str | None = field(default=None, repr=False)
|
||||
|
||||
@property
|
||||
def steering_elements(self) -> frozenset[str]:
|
||||
if self.eval_ctx:
|
||||
return self.eval_ctx.steering_elements
|
||||
return frozenset()
|
||||
|
||||
@property
|
||||
def actions(self) -> list[dict[str, Any]]:
|
||||
if self._actions is None:
|
||||
if self.eval_ctx:
|
||||
self._actions = self.eval_ctx.actions
|
||||
else:
|
||||
from services import actions as action_service
|
||||
|
||||
self._actions = action_service.list_actions_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._actions
|
||||
|
||||
@property
|
||||
def blockers(self) -> list[dict[str, Any]]:
|
||||
if self._blockers is None:
|
||||
from services import blockers as blocker_service
|
||||
|
||||
self._blockers = blocker_service.list_blockers_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
|
||||
)
|
||||
return self._blockers
|
||||
|
||||
@property
|
||||
def roadmap_items(self) -> list[dict[str, Any]]:
|
||||
if self._roadmap_items is None:
|
||||
from services import roadmap as roadmap_service
|
||||
|
||||
self._roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
|
||||
)
|
||||
return self._roadmap_items
|
||||
|
||||
@property
|
||||
def gate_scope(self) -> str | None:
|
||||
if self._gate_scope is None:
|
||||
from steering.strategies.next_action.execution_ready import (
|
||||
gate_horizon_scope_for_method,
|
||||
)
|
||||
|
||||
self._gate_scope = gate_horizon_scope_for_method(
|
||||
self.binding.primary_method_key,
|
||||
self.tenant_ctx,
|
||||
self.initiative_id,
|
||||
)
|
||||
return self._gate_scope
|
||||
|
||||
@property
|
||||
def dependencies(self) -> list[dict[str, Any]]:
|
||||
if self._dependencies is None:
|
||||
from services.execution_plan import list_dependencies_for_initiative
|
||||
|
||||
self._dependencies = list_dependencies_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id, initiative_id=self.initiative_id
|
||||
)
|
||||
return self._dependencies
|
||||
|
||||
@property
|
||||
def graph_state(self) -> dict[str, Any]:
|
||||
if self._graph_state is None:
|
||||
cached = self.read_models.get("execution_graph")
|
||||
if cached is not None:
|
||||
self._graph_state = cached
|
||||
else:
|
||||
from steering.graph.execution_engine import compute_execution_graph_state
|
||||
|
||||
self._graph_state = compute_execution_graph_state(
|
||||
actions=self.actions,
|
||||
dependencies=self.dependencies,
|
||||
scope_roadmap_item_id=self.gate_scope,
|
||||
)
|
||||
return self._graph_state
|
||||
@@ -0,0 +1 @@
|
||||
"""Attention contributors package."""
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Core attention contributors — blockers, blocked actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
from steering.attention.contributors.registry import (
|
||||
AttentionContributor,
|
||||
register_attention_contributor,
|
||||
)
|
||||
|
||||
|
||||
def _open_blockers(ctx: AttentionEvalContext) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
for blocker in ctx.blockers:
|
||||
if blocker.get("status") not in ("open", "in_progress"):
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "open_blocker",
|
||||
"severity": "warning",
|
||||
"title": blocker.get("title") or "Blocker",
|
||||
"summary": "Offener Blocker im Vorhaben",
|
||||
"scope_type": "blocker",
|
||||
"scope_id": str(blocker["id"]),
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"action_id": (
|
||||
str(blocker["action_id"]) if blocker.get("action_id") else None
|
||||
),
|
||||
"blocker_id": str(blocker["id"]),
|
||||
"reason_code": "path_blocked",
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _blocked_actions(ctx: AttentionEvalContext) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
for action in ctx.actions:
|
||||
if action.get("status") != "blocked":
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "blocked_action",
|
||||
"severity": "critical",
|
||||
"title": action.get("title") or "Arbeitspaket",
|
||||
"summary": "Maßnahme ist blockiert",
|
||||
"scope_type": "action",
|
||||
"scope_id": str(action["id"]),
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"action_id": str(action["id"]),
|
||||
"reason_code": "path_blocked",
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
register_attention_contributor(
|
||||
AttentionContributor(key="open_blockers", contribute=_open_blockers)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(key="blocked_actions", contribute=_blocked_actions)
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Gate / execution graph attention — planning_debt, execution_waiting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
from steering.attention.contributors.registry import (
|
||||
AttentionContributor,
|
||||
register_attention_contributor,
|
||||
)
|
||||
from steering.graph.execution_engine import (
|
||||
execution_waiting_to_attention_items,
|
||||
planning_debt_to_attention_items,
|
||||
)
|
||||
|
||||
_GATE_METHODS = frozenset(
|
||||
{"sequential_dependency", "program_delivery", "maturity_progression"}
|
||||
)
|
||||
|
||||
|
||||
def _planning_debt(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if ctx.binding.primary_method_key not in _GATE_METHODS:
|
||||
return []
|
||||
debts = ctx.read_models.get("planning_debt")
|
||||
if debts is None:
|
||||
from steering.graph.execution_engine import compute_planning_debt
|
||||
|
||||
gate_scope = ctx.gate_scope
|
||||
scoped_roadmap = ctx.roadmap_items
|
||||
scoped_actions = ctx.actions
|
||||
if gate_scope:
|
||||
scoped_roadmap = [
|
||||
ri for ri in ctx.roadmap_items if str(ri.get("id")) == str(gate_scope)
|
||||
]
|
||||
scoped_actions = [
|
||||
a
|
||||
for a in ctx.actions
|
||||
if a.get("roadmap_item_id")
|
||||
and str(a["roadmap_item_id"]) == str(gate_scope)
|
||||
]
|
||||
debts = compute_planning_debt(
|
||||
actions=scoped_actions, roadmap_items=scoped_roadmap
|
||||
)
|
||||
return planning_debt_to_attention_items(
|
||||
initiative_id=ctx.initiative_id, debts=debts or []
|
||||
)
|
||||
|
||||
|
||||
def _execution_waiting(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if "critical_path" not in ctx.steering_elements and "gate_fulfillment" not in ctx.steering_elements:
|
||||
return []
|
||||
return execution_waiting_to_attention_items(
|
||||
initiative_id=ctx.initiative_id,
|
||||
actions=ctx.actions,
|
||||
graph_state=ctx.graph_state,
|
||||
)
|
||||
|
||||
|
||||
def _horizon_no_ready_work(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if ctx.next_work:
|
||||
return []
|
||||
if ctx.binding.primary_method_key not in _GATE_METHODS:
|
||||
return []
|
||||
if ctx.horizon.kind != "gate":
|
||||
return []
|
||||
|
||||
debts = ctx.read_models.get("planning_debt") or []
|
||||
has_planning = len(debts) > 0
|
||||
has_waiting = bool(ctx.graph_state.get("blocked_actions"))
|
||||
if not has_planning and not has_waiting and not ctx.graph_state.get("ready_actions"):
|
||||
return [
|
||||
{
|
||||
"kind": "initiative_without_next_action",
|
||||
"severity": "info",
|
||||
"title": ctx.horizon.gate_title or "Aktiver Horizont",
|
||||
"summary": "Keine ausführungsbereite Arbeit im aktiven Horizont",
|
||||
"scope_type": "milestone",
|
||||
"scope_id": ctx.horizon.gate_roadmap_item_id,
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"reason_code": "horizon_no_ready_work",
|
||||
}
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="planning_debt",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
contribute=_planning_debt,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="execution_waiting",
|
||||
requires_any_element=frozenset({"critical_path", "gate_fulfillment"}),
|
||||
contribute=_execution_waiting,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="horizon_no_ready_work",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
contribute=_horizon_no_ready_work,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Read-model / proposal derived attention."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
from steering.attention.contributors.registry import (
|
||||
AttentionContributor,
|
||||
register_attention_contributor,
|
||||
)
|
||||
from steering.proposals.gate_next_actions import gate_next_actions_attention_items
|
||||
from steering.proposals.intake_triage import intake_triage_attention_items
|
||||
from steering.proposals.sprint_commit import sprint_commit_attention_items
|
||||
from steering.read_models.epic_rollup import epic_rollup_attention_items
|
||||
|
||||
|
||||
def _epic_rollup(ctx: AttentionEvalContext) -> list[dict]:
|
||||
rollups = ctx.read_models.get("epic_rollup")
|
||||
if not rollups:
|
||||
return []
|
||||
return epic_rollup_attention_items(
|
||||
initiative_id=ctx.initiative_id, rollups=rollups
|
||||
)
|
||||
|
||||
|
||||
def _sprint_commit(ctx: AttentionEvalContext) -> list[dict]:
|
||||
proposals = ctx.proposals.get("sprint_commit")
|
||||
if not proposals:
|
||||
return []
|
||||
return sprint_commit_attention_items(
|
||||
initiative_id=ctx.initiative_id,
|
||||
proposals=proposals,
|
||||
actions=ctx.actions,
|
||||
)
|
||||
|
||||
|
||||
def _gate_next_actions(ctx: AttentionEvalContext) -> list[dict]:
|
||||
proposals = ctx.proposals.get("gate_next_actions")
|
||||
if not proposals:
|
||||
return []
|
||||
return gate_next_actions_attention_items(
|
||||
initiative_id=ctx.initiative_id, proposals=proposals
|
||||
)
|
||||
|
||||
|
||||
def _intake_triage(ctx: AttentionEvalContext) -> list[dict]:
|
||||
proposals = ctx.proposals.get("intake_triage")
|
||||
if not proposals:
|
||||
return []
|
||||
return intake_triage_attention_items(
|
||||
initiative_id=ctx.initiative_id, proposals=proposals
|
||||
)
|
||||
|
||||
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="epic_rollup",
|
||||
requires_elements=frozenset({"backlog_epic_hierarchy"}),
|
||||
contribute=_epic_rollup,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="sprint_commit",
|
||||
requires_elements=frozenset({"work_cycle_scope"}),
|
||||
contribute=_sprint_commit,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="gate_next_actions",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
contribute=_gate_next_actions,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="intake_triage",
|
||||
contribute=_intake_triage,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Attention contributor registry — K-Ext-2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
|
||||
AttentionContribute = Callable[[AttentionEvalContext], list[dict]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttentionContributor:
|
||||
key: str
|
||||
requires_elements: frozenset[str] = field(default_factory=frozenset)
|
||||
requires_any_element: frozenset[str] = field(default_factory=frozenset)
|
||||
requires_primary_methods: frozenset[str] = field(default_factory=frozenset)
|
||||
contribute: AttentionContribute = lambda _ctx: []
|
||||
|
||||
|
||||
_CONTRIBUTORS: list[AttentionContributor] = []
|
||||
|
||||
|
||||
def register_attention_contributor(contributor: AttentionContributor) -> None:
|
||||
_CONTRIBUTORS.append(contributor)
|
||||
|
||||
|
||||
def collect_attention_items(ctx: AttentionEvalContext) -> list[dict]:
|
||||
elements = ctx.steering_elements
|
||||
primary = ctx.binding.primary_method_key
|
||||
items: list[dict] = []
|
||||
|
||||
for contributor in _CONTRIBUTORS:
|
||||
if (
|
||||
contributor.requires_elements
|
||||
and not contributor.requires_elements <= elements
|
||||
):
|
||||
continue
|
||||
if contributor.requires_any_element and not (
|
||||
contributor.requires_any_element & elements
|
||||
):
|
||||
continue
|
||||
if (
|
||||
contributor.requires_primary_methods
|
||||
and primary not in contributor.requires_primary_methods
|
||||
):
|
||||
continue
|
||||
items.extend(contributor.contribute(ctx))
|
||||
|
||||
for item in items:
|
||||
item.setdefault("data_source", "steering_kernel")
|
||||
|
||||
items.sort(
|
||||
key=lambda x: {"critical": 0, "warning": 1, "info": 2}.get(
|
||||
x.get("severity", "info"), 9
|
||||
)
|
||||
)
|
||||
return items
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Attention contributors for reviews, recurring, tech debt."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
from steering.attention.contributors.registry import (
|
||||
AttentionContributor,
|
||||
register_attention_contributor,
|
||||
)
|
||||
|
||||
|
||||
def _parse_due(value) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
text = str(value).replace("Z", "+00:00")
|
||||
parsed = datetime.fromisoformat(text)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _reviews_due(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if not ctx.eval_ctx or "reviews" not in ctx.eval_ctx.data_slices:
|
||||
return []
|
||||
now = datetime.now(timezone.utc)
|
||||
items: list[dict] = []
|
||||
for review in ctx.eval_ctx.reviews:
|
||||
if review.get("status") != "planned":
|
||||
continue
|
||||
due = _parse_due(review.get("due_at"))
|
||||
if due is None or due > now:
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "review_due",
|
||||
"severity": "warning",
|
||||
"title": review.get("title") or "Review",
|
||||
"summary": "Review fällig",
|
||||
"scope_type": "review",
|
||||
"scope_id": str(review["id"]),
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"review_id": str(review["id"]),
|
||||
"reason_code": "review_due",
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _recurring_due(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if not ctx.eval_ctx or "recurring" not in ctx.eval_ctx.data_slices:
|
||||
return []
|
||||
now = datetime.now(timezone.utc)
|
||||
items: list[dict] = []
|
||||
for element in ctx.eval_ctx.recurring_elements:
|
||||
if element.get("status") != "active":
|
||||
continue
|
||||
due = _parse_due(element.get("next_due_at"))
|
||||
if due is None or due > now:
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "recurring_due",
|
||||
"severity": "info",
|
||||
"title": element.get("title") or "Rhythmus",
|
||||
"summary": "Wiederkehrendes Element fällig",
|
||||
"scope_type": "recurring_element",
|
||||
"scope_id": str(element["id"]),
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"recurring_element_id": str(element["id"]),
|
||||
"reason_code": "recurring_due",
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _action_review_required(ctx: AttentionEvalContext) -> list[dict]:
|
||||
if not ctx.eval_ctx or "reviews" not in ctx.eval_ctx.data_slices:
|
||||
return []
|
||||
planned_by_action = {
|
||||
str(review["action_id"])
|
||||
for review in ctx.eval_ctx.reviews
|
||||
if review.get("status") == "planned" and review.get("action_id")
|
||||
}
|
||||
items: list[dict] = []
|
||||
for action in ctx.actions:
|
||||
if action.get("status") != "review_required":
|
||||
continue
|
||||
action_id = str(action["id"])
|
||||
if action_id in planned_by_action:
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "action_review_required",
|
||||
"severity": "warning",
|
||||
"title": action.get("title") or "Arbeitspaket",
|
||||
"summary": "Maßnahme wartet auf Review — kein geplantes Review verknüpft",
|
||||
"scope_type": "action",
|
||||
"scope_id": action_id,
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"action_id": action_id,
|
||||
"reason_code": "action_review_required_no_review",
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _architecture_debt_stale(ctx: AttentionEvalContext) -> list[dict]:
|
||||
summary = ctx.read_models.get("tech_debt_summary") or {}
|
||||
if not summary.get("enabled") or not summary.get("stale_count"):
|
||||
return []
|
||||
return [
|
||||
{
|
||||
"kind": "architecture_debt_stale",
|
||||
"severity": "warning",
|
||||
"title": "Technische Schuld",
|
||||
"summary": (
|
||||
f"{summary['stale_count']} offene Schuld-Einträge älter als "
|
||||
f"{summary.get('stale_days', 30)} Tage ohne Fortschritt"
|
||||
),
|
||||
"scope_type": "initiative",
|
||||
"scope_id": ctx.initiative_id,
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"reason_code": "architecture_debt_stale",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
register_attention_contributor(
|
||||
AttentionContributor(key="review_due", contribute=_reviews_due)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(
|
||||
key="recurring_due",
|
||||
requires_elements=frozenset({"recurring_rhythm"}),
|
||||
contribute=_recurring_due,
|
||||
)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(key="action_review_required", contribute=_action_review_required)
|
||||
)
|
||||
register_attention_contributor(
|
||||
AttentionContributor(key="architecture_debt_stale", contribute=_architecture_debt_stale)
|
||||
)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Profilgebundenes Backlog-Vokabular — ADP P3 / AP2.4 Methoden-Vertrag."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
_EMPTY: dict[str, Any] = {
|
||||
"profile_key": "none",
|
||||
"kinds": [],
|
||||
"labels": {},
|
||||
"default_kind": "story",
|
||||
"epic_hierarchy": False,
|
||||
"convertible_kinds": [],
|
||||
"capabilities": {
|
||||
"sprint_commit": False,
|
||||
"epic_hierarchy": False,
|
||||
},
|
||||
}
|
||||
|
||||
_AGILE_INTAKE: dict[str, Any] = {
|
||||
"profile_key": "agile_intake",
|
||||
"kinds": ["epic", "story", "bug", "issue", "tech_debt"],
|
||||
"labels": {
|
||||
"epic": "Epic",
|
||||
"story": "Story",
|
||||
"bug": "Bug",
|
||||
"issue": "Issue",
|
||||
"tech_debt": "Technische Schuld",
|
||||
},
|
||||
"default_kind": "story",
|
||||
"epic_hierarchy": True,
|
||||
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
|
||||
}
|
||||
|
||||
_CONTINUOUS_INTAKE: dict[str, Any] = {
|
||||
"profile_key": "continuous_intake",
|
||||
"kinds": ["story", "bug", "issue", "tech_debt"],
|
||||
"labels": {
|
||||
"story": "Idee",
|
||||
"bug": "Bug",
|
||||
"issue": "Störung",
|
||||
"tech_debt": "Technische Schuld",
|
||||
},
|
||||
"default_kind": "story",
|
||||
"epic_hierarchy": False,
|
||||
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
|
||||
}
|
||||
|
||||
_STANDARD_INTAKE: dict[str, Any] = {
|
||||
"profile_key": "standard_intake",
|
||||
"kinds": ["story", "bug", "issue", "tech_debt"],
|
||||
"labels": {
|
||||
"story": "Story",
|
||||
"bug": "Bug",
|
||||
"issue": "Issue",
|
||||
"tech_debt": "Technische Schuld",
|
||||
},
|
||||
"default_kind": "story",
|
||||
"epic_hierarchy": False,
|
||||
"convertible_kinds": ["story", "bug", "issue", "tech_debt"],
|
||||
}
|
||||
|
||||
|
||||
def _with_capabilities(
|
||||
vocabulary: dict[str, Any],
|
||||
*,
|
||||
steering_elements: frozenset[str],
|
||||
) -> dict[str, Any]:
|
||||
result = dict(vocabulary)
|
||||
sprint_commit = "work_cycle_scope" in steering_elements
|
||||
epic_hierarchy = "backlog_epic_hierarchy" in steering_elements
|
||||
result["epic_hierarchy"] = epic_hierarchy
|
||||
result["capabilities"] = {
|
||||
"sprint_commit": sprint_commit,
|
||||
"epic_hierarchy": epic_hierarchy,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def resolve_backlog_vocabulary(
|
||||
*,
|
||||
data_slices: list[str],
|
||||
method_key: str,
|
||||
steering_elements: frozenset[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Backlog-Typen/Labels aus effektivem Methoden-Vertrag — nicht aus Page-Ifs."""
|
||||
if "backlog" not in data_slices:
|
||||
return dict(_EMPTY)
|
||||
|
||||
if "backlog_epic_hierarchy" in steering_elements:
|
||||
return _with_capabilities(dict(_AGILE_INTAKE), steering_elements=steering_elements)
|
||||
|
||||
if method_key == "continuous_product":
|
||||
return _with_capabilities(
|
||||
dict(_CONTINUOUS_INTAKE), steering_elements=steering_elements
|
||||
)
|
||||
|
||||
return _with_capabilities(dict(_STANDARD_INTAKE), steering_elements=steering_elements)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Effective method contract — primary + composition modifier (AP2.4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.methods.registry import get_method
|
||||
|
||||
PLAN_PHASE_MODIFIER_KEY = "agile_iteration"
|
||||
|
||||
|
||||
def resolve_effective_steering_elements(
|
||||
primary_method_key: str,
|
||||
*,
|
||||
data_slices: list[str],
|
||||
active_composition_modifier: str | None,
|
||||
) -> frozenset[str]:
|
||||
"""
|
||||
Primärmethode + aktiver Modifier; Plan-Phase: agile_iteration wenn work_cycles
|
||||
Slice aktiv und Methode komponierbar (Epic-Planung vor aktivem Sprint).
|
||||
"""
|
||||
primary = get_method(primary_method_key)
|
||||
elements: set[str] = set(primary.steering_elements if primary else [])
|
||||
|
||||
modifier_keys: list[str] = []
|
||||
if active_composition_modifier:
|
||||
modifier_keys.append(active_composition_modifier)
|
||||
elif "work_cycles" in data_slices:
|
||||
agile = get_method(PLAN_PHASE_MODIFIER_KEY)
|
||||
if agile and primary_method_key in agile.composes_with:
|
||||
modifier_keys.append(PLAN_PHASE_MODIFIER_KEY)
|
||||
|
||||
for modifier_key in modifier_keys:
|
||||
modifier = get_method(modifier_key)
|
||||
if modifier:
|
||||
elements.update(modifier.steering_elements)
|
||||
|
||||
return frozenset(elements)
|
||||
@@ -41,6 +41,12 @@ STEERING_ELEMENTS: dict[str, SteeringElementDefinition] = {
|
||||
description="Aktive work_cycle und Sprint-Backlog",
|
||||
modes=("work", "plan"),
|
||||
),
|
||||
"backlog_epic_hierarchy": SteeringElementDefinition(
|
||||
key="backlog_epic_hierarchy",
|
||||
label="Epic-Hierarchie",
|
||||
description="Epic-Container und Story-Baum im Plan-Eingang (Agile-Modifier)",
|
||||
modes=("plan",),
|
||||
),
|
||||
"recurring_rhythm": SteeringElementDefinition(
|
||||
key="recurring_rhythm",
|
||||
label="Rhythmen",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Shared evaluation context for steering read models and proposals (K-Ext-1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
@dataclass
|
||||
class SteeringEvalContext:
|
||||
"""Tenant-scoped context — lazy OM loads for extension providers."""
|
||||
|
||||
tenant_ctx: TenantContext
|
||||
initiative_id: str
|
||||
binding: SteeringBinding
|
||||
horizon: HorizonMarker
|
||||
lifecycle: LifecycleContext
|
||||
operating_context: dict[str, Any]
|
||||
|
||||
_actions: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_backlog_items: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_work_cycles: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_reviews: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
_recurring_elements: list[dict[str, Any]] | None = field(default=None, repr=False)
|
||||
|
||||
@property
|
||||
def steering_elements(self) -> frozenset[str]:
|
||||
return frozenset(self.operating_context.get("steering_elements") or [])
|
||||
|
||||
@property
|
||||
def data_slices(self) -> list[str]:
|
||||
return list(self.operating_context.get("data_slices") or [])
|
||||
|
||||
@property
|
||||
def backlog_vocabulary(self) -> dict[str, Any]:
|
||||
return dict(self.operating_context.get("backlog_vocabulary") or {})
|
||||
|
||||
@property
|
||||
def agent_slot_config(self) -> dict[str, Any]:
|
||||
return dict(self.operating_context.get("agent_slot_config") or {})
|
||||
|
||||
@property
|
||||
def actions(self) -> list[dict[str, Any]]:
|
||||
if self._actions is None:
|
||||
from services import actions as action_service
|
||||
|
||||
self._actions = action_service.list_actions_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._actions
|
||||
|
||||
@property
|
||||
def backlog_items(self) -> list[dict[str, Any]]:
|
||||
if self._backlog_items is None:
|
||||
from services import backlog as backlog_service
|
||||
|
||||
self._backlog_items = backlog_service.list_backlog_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._backlog_items
|
||||
|
||||
@property
|
||||
def work_cycles(self) -> list[dict[str, Any]]:
|
||||
if self._work_cycles is None:
|
||||
from services.work_cycle import list_work_cycles_for_initiative
|
||||
|
||||
self._work_cycles = list_work_cycles_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._work_cycles
|
||||
|
||||
@property
|
||||
def reviews(self) -> list[dict[str, Any]]:
|
||||
if self._reviews is None:
|
||||
from services.reviews import list_reviews_for_initiative
|
||||
|
||||
self._reviews = list_reviews_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._reviews
|
||||
|
||||
@property
|
||||
def recurring_elements(self) -> list[dict[str, Any]]:
|
||||
if self._recurring_elements is None:
|
||||
from services.recurring import list_recurring_for_initiative
|
||||
|
||||
self._recurring_elements = list_recurring_for_initiative(
|
||||
tenant_id=self.tenant_ctx.tenant_id,
|
||||
initiative_id=self.initiative_id,
|
||||
)
|
||||
return self._recurring_elements
|
||||
|
||||
|
||||
def build_steering_eval_context(
|
||||
tenant_ctx: TenantContext,
|
||||
*,
|
||||
initiative_id: str,
|
||||
binding: SteeringBinding,
|
||||
horizon: HorizonMarker,
|
||||
lifecycle: LifecycleContext,
|
||||
) -> SteeringEvalContext:
|
||||
from services.operating_context import get_operating_context
|
||||
|
||||
operating = (
|
||||
get_operating_context(
|
||||
tenant_id=tenant_ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
or {}
|
||||
)
|
||||
return SteeringEvalContext(
|
||||
tenant_ctx=tenant_ctx,
|
||||
initiative_id=initiative_id,
|
||||
binding=binding,
|
||||
horizon=horizon,
|
||||
lifecycle=lifecycle,
|
||||
operating_context=operating,
|
||||
)
|
||||
@@ -1,6 +1,5 @@
|
||||
"""Steering Kernel Spine — universal runtime entry for initiative steering."""
|
||||
|
||||
from steering.kernel.evaluate import evaluate_steering
|
||||
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding, SteeringEvaluation
|
||||
|
||||
__all__ = [
|
||||
@@ -10,3 +9,10 @@ __all__ = [
|
||||
"SteeringEvaluation",
|
||||
"evaluate_steering",
|
||||
]
|
||||
|
||||
|
||||
def evaluate_steering(*args, **kwargs):
|
||||
"""Lazy import avoids circular dependency with extension registries."""
|
||||
from steering.kernel.evaluate import evaluate_steering as _evaluate
|
||||
|
||||
return _evaluate(*args, **kwargs)
|
||||
@@ -5,16 +5,13 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from steering.kernel.models import HorizonMarker, SteeringBinding
|
||||
from steering.strategies.next_action.execution_ready import gate_horizon_scope_for_method
|
||||
from tenant_context import TenantContext
|
||||
|
||||
_GATE_METHODS = frozenset(
|
||||
{
|
||||
"sequential_dependency",
|
||||
"program_delivery",
|
||||
"maturity_progression",
|
||||
}
|
||||
)
|
||||
# Side-effect: register contributors
|
||||
import steering.attention.contributors.core # noqa: F401
|
||||
import steering.attention.contributors.gates # noqa: F401
|
||||
import steering.attention.contributors.read_models # noqa: F401
|
||||
import steering.attention.contributors.reviews # noqa: F401
|
||||
|
||||
|
||||
def evaluate_attention(
|
||||
@@ -24,139 +21,23 @@ def evaluate_attention(
|
||||
binding: SteeringBinding,
|
||||
horizon: HorizonMarker,
|
||||
next_work: list[dict[str, Any]],
|
||||
read_models: dict[str, Any] | None = None,
|
||||
proposals: dict[str, Any] | None = None,
|
||||
eval_ctx=None,
|
||||
limit: int = 20,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Kernel attention for a single initiative — no fake next when planning debt."""
|
||||
from services import actions as action_service
|
||||
from services import blockers as blocker_service
|
||||
from services import roadmap as roadmap_service
|
||||
from services.execution_plan import list_dependencies_for_initiative
|
||||
from steering.graph.execution_engine import (
|
||||
compute_execution_graph_state,
|
||||
compute_planning_debt,
|
||||
execution_waiting_to_attention_items,
|
||||
planning_debt_to_attention_items,
|
||||
"""Kernel attention — contributors via registry (K-Ext-2)."""
|
||||
from steering.attention.context import AttentionEvalContext
|
||||
from steering.attention.contributors.registry import collect_attention_items
|
||||
|
||||
actx = AttentionEvalContext(
|
||||
tenant_ctx=ctx,
|
||||
initiative_id=initiative_id,
|
||||
binding=binding,
|
||||
horizon=horizon,
|
||||
next_work=next_work,
|
||||
read_models=read_models or {},
|
||||
proposals=proposals or {},
|
||||
eval_ctx=eval_ctx,
|
||||
)
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
blockers = blocker_service.list_blockers_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
for blocker in blockers:
|
||||
if blocker.get("status") not in ("open", "in_progress"):
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "open_blocker",
|
||||
"severity": "warning",
|
||||
"title": blocker.get("title") or "Blocker",
|
||||
"summary": "Offener Blocker im Vorhaben",
|
||||
"scope_type": "blocker",
|
||||
"scope_id": str(blocker["id"]),
|
||||
"initiative_id": initiative_id,
|
||||
"action_id": (
|
||||
str(blocker["action_id"]) if blocker.get("action_id") else None
|
||||
),
|
||||
"blocker_id": str(blocker["id"]),
|
||||
"reason_code": "path_blocked",
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
actions = action_service.list_actions_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
for action in actions:
|
||||
if action.get("status") != "blocked":
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"kind": "blocked_action",
|
||||
"severity": "critical",
|
||||
"title": action.get("title") or "Arbeitspaket",
|
||||
"summary": "Maßnahme ist blockiert",
|
||||
"scope_type": "action",
|
||||
"scope_id": str(action["id"]),
|
||||
"initiative_id": initiative_id,
|
||||
"action_id": str(action["id"]),
|
||||
"reason_code": "path_blocked",
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
gate_scope = gate_horizon_scope_for_method(
|
||||
binding.primary_method_key, ctx, initiative_id
|
||||
)
|
||||
roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
|
||||
scoped_roadmap = roadmap_items
|
||||
scoped_actions = actions
|
||||
if gate_scope:
|
||||
scope = str(gate_scope)
|
||||
scoped_roadmap = [ri for ri in roadmap_items if str(ri.get("id")) == scope]
|
||||
scoped_actions = [
|
||||
a
|
||||
for a in actions
|
||||
if a.get("roadmap_item_id") and str(a["roadmap_item_id"]) == scope
|
||||
]
|
||||
|
||||
if binding.primary_method_key in _GATE_METHODS:
|
||||
debts = compute_planning_debt(
|
||||
actions=scoped_actions, roadmap_items=scoped_roadmap
|
||||
)
|
||||
items.extend(
|
||||
planning_debt_to_attention_items(
|
||||
initiative_id=initiative_id, debts=debts
|
||||
)
|
||||
)
|
||||
|
||||
dependencies = list_dependencies_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
graph_state = compute_execution_graph_state(
|
||||
actions=actions,
|
||||
dependencies=dependencies,
|
||||
scope_roadmap_item_id=gate_scope,
|
||||
)
|
||||
items.extend(
|
||||
execution_waiting_to_attention_items(
|
||||
initiative_id=initiative_id,
|
||||
actions=actions,
|
||||
graph_state=graph_state,
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
not next_work
|
||||
and binding.primary_method_key in _GATE_METHODS
|
||||
and horizon.kind == "gate"
|
||||
):
|
||||
has_planning = any(i.get("reason_code") == "planning_debt" for i in items)
|
||||
has_waiting = any(i.get("reason_code") == "execution_waiting" for i in items)
|
||||
if not has_planning and not has_waiting and not graph_state.get("ready_actions"):
|
||||
items.append(
|
||||
{
|
||||
"kind": "initiative_without_next_action",
|
||||
"severity": "info",
|
||||
"title": horizon.gate_title or "Aktiver Horizont",
|
||||
"summary": "Keine ausführungsbereite Arbeit im aktiven Horizont",
|
||||
"scope_type": "milestone",
|
||||
"scope_id": horizon.gate_roadmap_item_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "horizon_no_ready_work",
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
for item in items:
|
||||
item.setdefault("data_source", "steering_kernel")
|
||||
|
||||
items.sort(
|
||||
key=lambda x: {"critical": 0, "warning": 1, "info": 2}.get(
|
||||
x.get("severity", "info"), 9
|
||||
)
|
||||
)
|
||||
return items[:limit]
|
||||
return collect_attention_items(actx)[:limit]
|
||||
@@ -1,13 +1,17 @@
|
||||
"""Steering Kernel Spine — single entry point v0.1."""
|
||||
"""Steering Kernel Spine — single entry point v0.4."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.kernel.attention import evaluate_attention
|
||||
from steering.kernel.binding import resolve_steering_binding
|
||||
from steering.eval_context import build_steering_eval_context
|
||||
from steering.kernel.horizon import resolve_horizon
|
||||
from steering.kernel.lifecycle import resolve_lifecycle_context
|
||||
from steering.kernel.models import SteeringEvaluation
|
||||
from steering.kernel.next_work import evaluate_next_work
|
||||
from steering.agent_slots.registry import compute_agent_slots
|
||||
from steering.proposals.registry import compute_proposals
|
||||
from steering.read_models.registry import compute_read_models
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
@@ -39,6 +43,14 @@ def evaluate_steering(
|
||||
composition_modifier=binding.composition_modifier,
|
||||
)
|
||||
|
||||
eval_ctx = build_steering_eval_context(
|
||||
ctx,
|
||||
initiative_id=initiative_id,
|
||||
binding=binding,
|
||||
horizon=horizon,
|
||||
lifecycle=lifecycle,
|
||||
)
|
||||
|
||||
next_work = evaluate_next_work(
|
||||
ctx,
|
||||
initiative_id=initiative_id,
|
||||
@@ -47,15 +59,25 @@ def evaluate_steering(
|
||||
limit=next_work_limit,
|
||||
)
|
||||
|
||||
read_models = compute_read_models(eval_ctx)
|
||||
proposals = compute_proposals(eval_ctx, read_models=read_models)
|
||||
|
||||
attention = evaluate_attention(
|
||||
ctx,
|
||||
initiative_id=initiative_id,
|
||||
binding=binding,
|
||||
horizon=horizon,
|
||||
next_work=next_work,
|
||||
read_models=read_models,
|
||||
proposals=proposals,
|
||||
eval_ctx=eval_ctx,
|
||||
limit=attention_limit,
|
||||
)
|
||||
|
||||
agent_slots = compute_agent_slots(
|
||||
eval_ctx, read_models=read_models, proposals=proposals
|
||||
)
|
||||
|
||||
return SteeringEvaluation(
|
||||
initiative_id=initiative_id,
|
||||
binding=binding,
|
||||
@@ -63,4 +85,7 @@ def evaluate_steering(
|
||||
lifecycle=lifecycle,
|
||||
next_work=next_work,
|
||||
attention=attention,
|
||||
read_models=read_models,
|
||||
proposals=proposals,
|
||||
agent_slots=agent_slots,
|
||||
)
|
||||
@@ -65,7 +65,10 @@ class SteeringEvaluation:
|
||||
lifecycle: LifecycleContext
|
||||
next_work: list[dict[str, Any]] = field(default_factory=list)
|
||||
attention: list[dict[str, Any]] = field(default_factory=list)
|
||||
data_source: str = "steering_kernel_v0.2"
|
||||
read_models: dict[str, Any] = field(default_factory=dict)
|
||||
proposals: dict[str, Any] = field(default_factory=dict)
|
||||
agent_slots: list[dict[str, Any]] = field(default_factory=list)
|
||||
data_source: str = "steering_kernel_v0.4"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
@@ -77,5 +80,8 @@ class SteeringEvaluation:
|
||||
"lifecycle": self.lifecycle.to_dict(),
|
||||
"next_work": self.next_work,
|
||||
"attention": self.attention,
|
||||
"read_models": self.read_models,
|
||||
"proposals": self.proposals,
|
||||
"agent_slots": self.agent_slots,
|
||||
"data_source": self.data_source,
|
||||
}
|
||||
@@ -76,7 +76,8 @@ def register() -> None:
|
||||
"initiative.recurring_program",
|
||||
}
|
||||
),
|
||||
steering_elements=ELEM_NEXT | frozenset({"work_cycle_scope"}),
|
||||
steering_elements=ELEM_NEXT
|
||||
| frozenset({"work_cycle_scope", "backlog_epic_hierarchy"}),
|
||||
ui_features=frozenset({"steeringSnapshotOnWorkSprint"}),
|
||||
graph_profile=STRICT,
|
||||
method_role="modifier",
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Portfolio-level steering aggregation — K-Ext-5."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.kernel import evaluate_steering
|
||||
from tenant_context import TenantContext
|
||||
|
||||
_SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
|
||||
|
||||
|
||||
def _portfolio_rank_key(rank: int | None) -> int:
|
||||
return rank if rank is not None else 999_999
|
||||
|
||||
|
||||
def _load_active_initiatives(ctx: TenantContext, *, limit: int) -> list[dict[str, Any]]:
|
||||
from data_layer.initiatives import get_active_initiatives
|
||||
|
||||
return get_active_initiatives(ctx, limit=limit)
|
||||
|
||||
|
||||
def _enrich_item(
|
||||
item: dict[str, Any],
|
||||
*,
|
||||
initiative_id: str,
|
||||
initiative_title: str,
|
||||
portfolio_rank: int | None,
|
||||
) -> dict[str, Any]:
|
||||
enriched = dict(item)
|
||||
enriched.setdefault("initiative_id", initiative_id)
|
||||
enriched["initiative_title"] = initiative_title
|
||||
if portfolio_rank is not None:
|
||||
enriched["portfolio_rank"] = portfolio_rank
|
||||
enriched.setdefault("data_source", "steering_kernel")
|
||||
return enriched
|
||||
|
||||
|
||||
def _sort_attention(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return sorted(
|
||||
items,
|
||||
key=lambda item: (
|
||||
_SEVERITY_ORDER.get(item.get("severity", "info"), 99),
|
||||
_portfolio_rank_key(item.get("portfolio_rank")),
|
||||
item.get("initiative_title") or "",
|
||||
item.get("title") or "",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _sort_next_work(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return sorted(
|
||||
items,
|
||||
key=lambda item: (
|
||||
_portfolio_rank_key(item.get("portfolio_rank")),
|
||||
item.get("rank") if item.get("rank") is not None else 999,
|
||||
item.get("title") or "",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def aggregate_portfolio_steering(
|
||||
ctx: TenantContext,
|
||||
*,
|
||||
max_initiatives: int = 50,
|
||||
attention_per_initiative: int = 5,
|
||||
next_work_per_initiative: int = 3,
|
||||
total_attention: int = 30,
|
||||
total_next_work: int = 15,
|
||||
total_agent_slots: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Aggregiert Kernel-Steuerung über aktive Initiativen (Portfolio-Rang).
|
||||
"""
|
||||
initiatives = _load_active_initiatives(ctx, limit=max_initiatives)
|
||||
|
||||
attention: list[dict[str, Any]] = []
|
||||
next_work: list[dict[str, Any]] = []
|
||||
agent_slots: list[dict[str, Any]] = []
|
||||
proposals_summary: list[dict[str, Any]] = []
|
||||
attention_by_initiative: dict[str, list[dict[str, Any]]] = {}
|
||||
agent_slots_by_initiative: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
for initiative in initiatives:
|
||||
initiative_id = str(initiative["id"])
|
||||
initiative_title = initiative.get("title") or "Vorhaben"
|
||||
portfolio_rank = initiative.get("portfolio_rank")
|
||||
|
||||
evaluation = evaluate_steering(
|
||||
ctx,
|
||||
initiative_id=initiative_id,
|
||||
next_work_limit=next_work_per_initiative,
|
||||
attention_limit=attention_per_initiative,
|
||||
)
|
||||
|
||||
initiative_attention: list[dict[str, Any]] = []
|
||||
for item in evaluation.attention:
|
||||
enriched = _enrich_item(
|
||||
item,
|
||||
initiative_id=initiative_id,
|
||||
initiative_title=initiative_title,
|
||||
portfolio_rank=portfolio_rank,
|
||||
)
|
||||
initiative_attention.append(enriched)
|
||||
attention.append(enriched)
|
||||
|
||||
attention_by_initiative[initiative_id] = initiative_attention
|
||||
|
||||
for item in evaluation.next_work:
|
||||
next_work.append(
|
||||
_enrich_item(
|
||||
item,
|
||||
initiative_id=initiative_id,
|
||||
initiative_title=initiative_title,
|
||||
portfolio_rank=portfolio_rank,
|
||||
)
|
||||
)
|
||||
|
||||
initiative_slots: list[dict[str, Any]] = []
|
||||
for slot in evaluation.agent_slots:
|
||||
enriched = _enrich_item(
|
||||
slot,
|
||||
initiative_id=initiative_id,
|
||||
initiative_title=initiative_title,
|
||||
portfolio_rank=portfolio_rank,
|
||||
)
|
||||
initiative_slots.append(enriched)
|
||||
agent_slots.append(enriched)
|
||||
agent_slots_by_initiative[initiative_id] = initiative_slots
|
||||
|
||||
proposal_counts = {
|
||||
key: len(value) if isinstance(value, list) else 0
|
||||
for key, value in (evaluation.proposals or {}).items()
|
||||
}
|
||||
if any(proposal_counts.values()):
|
||||
proposals_summary.append(
|
||||
{
|
||||
"initiative_id": initiative_id,
|
||||
"initiative_title": initiative_title,
|
||||
"portfolio_rank": portfolio_rank,
|
||||
"counts": proposal_counts,
|
||||
"total": sum(proposal_counts.values()),
|
||||
}
|
||||
)
|
||||
|
||||
attention = _sort_attention(attention)[:total_attention]
|
||||
next_work = _sort_next_work(next_work)[:total_next_work]
|
||||
agent_slots = sorted(
|
||||
agent_slots,
|
||||
key=lambda slot: (
|
||||
{"high": 0, "normal": 1, "low": 2}.get(slot.get("priority", "normal"), 9),
|
||||
_portfolio_rank_key(slot.get("portfolio_rank")),
|
||||
),
|
||||
)[:total_agent_slots]
|
||||
|
||||
proposals_summary.sort(
|
||||
key=lambda row: (
|
||||
-row.get("total", 0),
|
||||
_portfolio_rank_key(row.get("portfolio_rank")),
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
"data_source": "steering_kernel_portfolio_v0.1",
|
||||
"initiative_count": len(initiatives),
|
||||
"attention": attention,
|
||||
"attention_by_initiative": attention_by_initiative,
|
||||
"next_work": next_work,
|
||||
"proposals_summary": proposals_summary,
|
||||
"agent_slots": agent_slots,
|
||||
"agent_slots_by_initiative": agent_slots_by_initiative,
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Steering proposals — ranked suggestions without auto-mutation (P6+)."""
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Gate next actions proposal — sequential_dependency / program_delivery."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
COMMITTABLE = frozenset({"new", "triaged", "accepted"})
|
||||
_PRIORITY = {"critical": 0, "high": 1, "normal": 2, "low": 3}
|
||||
|
||||
|
||||
def _active_gate_id(ctx: SteeringEvalContext) -> str | None:
|
||||
if ctx.horizon.kind == "gate" and ctx.horizon.gate_roadmap_item_id:
|
||||
return str(ctx.horizon.gate_roadmap_item_id)
|
||||
debts = []
|
||||
return None
|
||||
|
||||
|
||||
def _sort_key(item: dict[str, Any]) -> tuple:
|
||||
return (
|
||||
_PRIORITY.get(item.get("priority") or "normal", 9),
|
||||
item.get("sort_order") if item.get("sort_order") is not None else 9999,
|
||||
(item.get("title") or "").lower(),
|
||||
)
|
||||
|
||||
|
||||
def propose_gate_next_actions(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
read_models: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
read_models = read_models or {}
|
||||
gate_id = _active_gate_id(ctx)
|
||||
proposals: list[dict[str, Any]] = []
|
||||
rank = 0
|
||||
|
||||
for debt in read_models.get("planning_debt") or []:
|
||||
rank += 1
|
||||
gid = str(debt.get("roadmap_item_id"))
|
||||
proposals.append(
|
||||
{
|
||||
"proposal_key": "gate_next_actions",
|
||||
"scope_type": "roadmap_item",
|
||||
"scope_id": gid,
|
||||
"rank": rank,
|
||||
"reason_code": "planning_debt",
|
||||
"summary": debt.get("message") or "Gate ohne Durchführungsplan",
|
||||
"title": debt.get("title") or "Zielzustand",
|
||||
"roadmap_item_id": gid,
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"ranker_key": "heuristic_v0",
|
||||
"confidence": "heuristic",
|
||||
"factors": [{"code": "planning_debt", "weight": 100, "label": "Planning Debt"}],
|
||||
"dependency_refs": [],
|
||||
"dependency_blocked": False,
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
vocabulary = ctx.backlog_vocabulary
|
||||
convertible = frozenset(vocabulary.get("convertible_kinds") or ["story", "bug", "issue"])
|
||||
candidates = [
|
||||
item
|
||||
for item in ctx.backlog_items
|
||||
if item.get("status") in COMMITTABLE
|
||||
and item.get("item_kind") != "epic"
|
||||
and (item.get("item_kind") or "story") in convertible
|
||||
and (not gate_id or str(item.get("roadmap_item_id") or "") == gate_id)
|
||||
]
|
||||
|
||||
for item in sorted(candidates, key=_sort_key)[:15]:
|
||||
rank += 1
|
||||
proposals.append(
|
||||
{
|
||||
"proposal_key": "gate_next_actions",
|
||||
"scope_type": "backlog_item",
|
||||
"scope_id": str(item["id"]),
|
||||
"rank": rank,
|
||||
"reason_code": "gate_backlog_ready",
|
||||
"summary": "Eingang-Item am aktiven Gate committen",
|
||||
"title": item.get("title") or "Backlog-Item",
|
||||
"item_kind": item.get("item_kind") or "story",
|
||||
"priority": item.get("priority") or "normal",
|
||||
"roadmap_item_id": (
|
||||
str(item["roadmap_item_id"]) if item.get("roadmap_item_id") else gate_id
|
||||
),
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"ranker_key": "heuristic_v0",
|
||||
"confidence": "heuristic",
|
||||
"factors": [
|
||||
{
|
||||
"code": "gate_alignment",
|
||||
"weight": 50,
|
||||
"label": "Gate-Zuordnung",
|
||||
}
|
||||
],
|
||||
"dependency_refs": [],
|
||||
"dependency_blocked": False,
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
return proposals
|
||||
|
||||
|
||||
def gate_next_actions_attention_items(
|
||||
*,
|
||||
initiative_id: str,
|
||||
proposals: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
backlog_ready = [p for p in proposals if p.get("scope_type") == "backlog_item"]
|
||||
if not backlog_ready:
|
||||
return []
|
||||
return [
|
||||
{
|
||||
"kind": "gate_commit_suggested",
|
||||
"severity": "info",
|
||||
"title": "Gate-Planung",
|
||||
"summary": f"{len(backlog_ready)} Item(s) für Gate-Commit vorgeschlagen",
|
||||
"scope_type": "initiative",
|
||||
"scope_id": initiative_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "gate_commit_suggested",
|
||||
"data_source": "gate_next_actions",
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Intake triage proposal — queue_inbox / continuous backlog (no sprint)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
COMMITTABLE = frozenset({"new", "triaged", "accepted"})
|
||||
_PRIORITY = {"critical": 0, "high": 1, "normal": 2, "low": 3}
|
||||
_QUEUE_KIND_BIAS = {"bug": 0, "issue": 1, "incident": 1, "story": 2, "idea": 3}
|
||||
|
||||
|
||||
def propose_intake_triage(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
read_models: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
vocabulary = ctx.backlog_vocabulary
|
||||
convertible = frozenset(vocabulary.get("convertible_kinds") or ["story", "bug", "issue"])
|
||||
queue_mode = "queue_inbox" in ctx.steering_elements
|
||||
|
||||
candidates = [
|
||||
item
|
||||
for item in ctx.backlog_items
|
||||
if item.get("status") in COMMITTABLE
|
||||
and item.get("item_kind") != "epic"
|
||||
and (item.get("item_kind") or "story") in convertible
|
||||
]
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
def sort_key(item: dict[str, Any]) -> tuple:
|
||||
kind = item.get("item_kind") or "story"
|
||||
kind_bias = _QUEUE_KIND_BIAS.get(kind, 5) if queue_mode else 5
|
||||
return (
|
||||
_PRIORITY.get(item.get("priority") or "normal", 9),
|
||||
kind_bias,
|
||||
item.get("sort_order") if item.get("sort_order") is not None else 9999,
|
||||
)
|
||||
|
||||
proposals: list[dict[str, Any]] = []
|
||||
for rank, item in enumerate(sorted(candidates, key=sort_key)[:20], start=1):
|
||||
kind = item.get("item_kind") or "story"
|
||||
proposals.append(
|
||||
{
|
||||
"proposal_key": "intake_triage",
|
||||
"scope_type": "backlog_item",
|
||||
"scope_id": str(item["id"]),
|
||||
"rank": rank,
|
||||
"reason_code": "intake_triage_candidate",
|
||||
"summary": "Triage-Kandidat (Heuristik — Ranker austauschbar)",
|
||||
"title": item.get("title") or "Backlog-Item",
|
||||
"item_kind": kind,
|
||||
"priority": item.get("priority") or "normal",
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"ranker_key": "heuristic_v0",
|
||||
"confidence": "heuristic",
|
||||
"factors": [
|
||||
{
|
||||
"code": "priority",
|
||||
"weight": _PRIORITY.get(item.get("priority") or "normal", 9),
|
||||
"label": "Priorität",
|
||||
}
|
||||
],
|
||||
"dependency_refs": [],
|
||||
"dependency_blocked": False,
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
return proposals
|
||||
|
||||
|
||||
def intake_triage_attention_items(
|
||||
*,
|
||||
initiative_id: str,
|
||||
proposals: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
if not proposals:
|
||||
return []
|
||||
return [
|
||||
{
|
||||
"kind": "intake_triage_suggested",
|
||||
"severity": "info",
|
||||
"title": "Eingang triagieren",
|
||||
"summary": f"{len(proposals)} Item(s) — Kernel schlägt Triage-Reihenfolge vor",
|
||||
"scope_type": "initiative",
|
||||
"scope_id": initiative_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "intake_triage_suggested",
|
||||
"data_source": "intake_triage",
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Proposal provider registry — K-Ext-1 / P6."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
ProposalCompute = Callable[[SteeringEvalContext, dict[str, Any]], Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProposalProvider:
|
||||
key: str
|
||||
requires_elements: frozenset[str]
|
||||
requires_data_slices: frozenset[str]
|
||||
compute: ProposalCompute
|
||||
excludes_elements: frozenset[str] = field(default_factory=frozenset)
|
||||
|
||||
|
||||
_PROVIDERS: list[ProposalProvider] = []
|
||||
|
||||
|
||||
def register_proposal(provider: ProposalProvider) -> None:
|
||||
_PROVIDERS.append(provider)
|
||||
|
||||
|
||||
def compute_proposals(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
read_models: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
elements = ctx.steering_elements
|
||||
slices = frozenset(ctx.data_slices)
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
for provider in _PROVIDERS:
|
||||
if provider.requires_elements and not provider.requires_elements <= elements:
|
||||
continue
|
||||
if provider.excludes_elements and provider.excludes_elements & elements:
|
||||
continue
|
||||
if provider.requires_data_slices and not provider.requires_data_slices <= slices:
|
||||
continue
|
||||
result[provider.key] = provider.compute(ctx, read_models)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _register_builtin_proposals() -> None:
|
||||
from steering.proposals.gate_next_actions import propose_gate_next_actions
|
||||
from steering.proposals.intake_triage import propose_intake_triage
|
||||
from steering.proposals.sprint_commit import propose_sprint_commit
|
||||
|
||||
register_proposal(
|
||||
ProposalProvider(
|
||||
key="sprint_commit",
|
||||
requires_elements=frozenset({"work_cycle_scope"}),
|
||||
requires_data_slices=frozenset({"backlog", "work_cycles"}),
|
||||
compute=lambda ctx, read_models: propose_sprint_commit(
|
||||
ctx, read_models=read_models
|
||||
),
|
||||
)
|
||||
)
|
||||
register_proposal(
|
||||
ProposalProvider(
|
||||
key="gate_next_actions",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
requires_data_slices=frozenset({"backlog", "roadmap", "actions"}),
|
||||
compute=lambda ctx, read_models: propose_gate_next_actions(
|
||||
ctx, read_models=read_models
|
||||
),
|
||||
)
|
||||
)
|
||||
register_proposal(
|
||||
ProposalProvider(
|
||||
key="intake_triage",
|
||||
requires_elements=frozenset(),
|
||||
requires_data_slices=frozenset({"backlog"}),
|
||||
excludes_elements=frozenset({"work_cycle_scope"}),
|
||||
compute=lambda ctx, read_models: propose_intake_triage(
|
||||
ctx, read_models=read_models
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
_register_builtin_proposals()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Sprint commit proposals — ADP P6 / pluggable ranking."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
# Ranker registration side effects
|
||||
import steering.proposals.sprint_commit_agent_v1 # noqa: F401
|
||||
import steering.proposals.sprint_commit_heuristic_v0 # noqa: F401
|
||||
from steering.proposals.sprint_commit_context import (
|
||||
build_sprint_commit_candidates,
|
||||
resolve_sprint_commit_ranker,
|
||||
resolve_target_work_cycle,
|
||||
)
|
||||
|
||||
|
||||
def propose_sprint_commit(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
read_models: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Ranked backlog items for sprint commit — ranker is swappable, no auto-mutation."""
|
||||
read_models = read_models or {}
|
||||
target = resolve_target_work_cycle(ctx)
|
||||
if not target:
|
||||
return []
|
||||
|
||||
cycle_id = str(target["id"])
|
||||
cycle_title = target.get("title") or "Sprint"
|
||||
|
||||
candidates = build_sprint_commit_candidates(ctx, target_work_cycle_id=cycle_id)
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
ranker = resolve_sprint_commit_ranker(ctx)
|
||||
ranked = ranker.rank(
|
||||
ctx,
|
||||
candidates=candidates,
|
||||
read_models=read_models,
|
||||
target_work_cycle_id=cycle_id,
|
||||
)
|
||||
|
||||
proposals: list[dict[str, Any]] = []
|
||||
for row in ranked:
|
||||
item = row.candidate.item
|
||||
proposals.append(
|
||||
{
|
||||
"proposal_key": "sprint_commit",
|
||||
"scope_type": "backlog_item",
|
||||
"scope_id": str(item["id"]),
|
||||
"rank": row.rank,
|
||||
"score": row.score,
|
||||
"reason_code": row.reason_code,
|
||||
"summary": row.summary,
|
||||
"title": item.get("title") or "Backlog-Item",
|
||||
"item_kind": item.get("item_kind") or "story",
|
||||
"priority": item.get("priority") or "normal",
|
||||
"work_cycle_id": cycle_id,
|
||||
"work_cycle_title": cycle_title,
|
||||
"initiative_id": ctx.initiative_id,
|
||||
"ranker_key": row.ranker_key,
|
||||
"confidence": "agent" if row.ranker_key.startswith("agent") else "heuristic",
|
||||
"factors": row.factors,
|
||||
"dependency_refs": row.candidate.dependency_refs,
|
||||
"dependency_blocked": row.candidate.dependency_blocked,
|
||||
"data_source": "steering_kernel",
|
||||
}
|
||||
)
|
||||
|
||||
return proposals
|
||||
|
||||
|
||||
def sprint_commit_attention_items(
|
||||
*,
|
||||
initiative_id: str,
|
||||
proposals: list[dict[str, Any]],
|
||||
actions: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Attention when sprint has room for proposed commits."""
|
||||
from steering.proposals.sprint_commit_context import OPEN_ACTION
|
||||
|
||||
if not proposals:
|
||||
return []
|
||||
|
||||
target_id = proposals[0].get("work_cycle_id")
|
||||
if not target_id:
|
||||
return []
|
||||
|
||||
sprint_actions = [
|
||||
a
|
||||
for a in actions
|
||||
if a.get("work_cycle_id") and str(a["work_cycle_id"]) == str(target_id)
|
||||
]
|
||||
open_in_sprint = sum(1 for a in sprint_actions if a.get("status") in OPEN_ACTION)
|
||||
|
||||
ready = [p for p in proposals if not p.get("dependency_blocked")]
|
||||
items: list[dict[str, Any]] = []
|
||||
cycle_title = proposals[0].get("work_cycle_title") or "Sprint"
|
||||
|
||||
if open_in_sprint == 0 and ready:
|
||||
ranker = proposals[0].get("ranker_key", "heuristic_v0")
|
||||
items.append(
|
||||
{
|
||||
"kind": "sprint_commit_suggested",
|
||||
"severity": "info",
|
||||
"title": cycle_title,
|
||||
"summary": (
|
||||
f"{len(ready)} commit-bereite Item(s) — "
|
||||
f"Vorschlag via Ranker {ranker}"
|
||||
),
|
||||
"scope_type": "work_cycle",
|
||||
"scope_id": str(target_id),
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "sprint_commit_suggested",
|
||||
"data_source": "sprint_commit_proposal",
|
||||
}
|
||||
)
|
||||
|
||||
return items
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Agent sprint ranker slot — placeholder for Principle Gate / Actor execution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.proposals.sprint_commit_context import (
|
||||
RankedSprintCommitCandidate,
|
||||
SprintCommitCandidate,
|
||||
register_sprint_commit_ranker,
|
||||
)
|
||||
from steering.proposals.sprint_commit_heuristic_v0 import HeuristicV0SprintCommitRanker
|
||||
|
||||
_FALLBACK = HeuristicV0SprintCommitRanker()
|
||||
|
||||
|
||||
class AgentV1SprintCommitRanker:
|
||||
"""
|
||||
Agent-gestütztes Ranking — noch nicht aktiv (Principle Gate).
|
||||
|
||||
Kontext kommt aus Snapshot/Operating Context; Scoring über auditierten Actor,
|
||||
nicht aus hardcodiertem Prompt. Bis Freigabe: Fallback auf heuristic_v0.
|
||||
"""
|
||||
|
||||
key = "agent_v1"
|
||||
|
||||
def rank(
|
||||
self,
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
candidates: list[SprintCommitCandidate],
|
||||
read_models: dict[str, Any],
|
||||
target_work_cycle_id: str,
|
||||
) -> list[RankedSprintCommitCandidate]:
|
||||
# TODO(P6+): Actor-Slot + Governance-Pack; KI wählt Subset + Begründung
|
||||
ranked = _FALLBACK.rank(
|
||||
ctx,
|
||||
candidates=candidates,
|
||||
read_models=read_models,
|
||||
target_work_cycle_id=target_work_cycle_id,
|
||||
)
|
||||
return [
|
||||
RankedSprintCommitCandidate(
|
||||
candidate=row.candidate,
|
||||
rank=row.rank,
|
||||
score=row.score,
|
||||
reason_code=row.reason_code,
|
||||
summary=f"{row.summary} (Agent-Ranker: Fallback heuristic_v0)",
|
||||
factors=row.factors
|
||||
+ [
|
||||
{
|
||||
"code": "ranker_fallback",
|
||||
"weight": 0,
|
||||
"label": "agent_v1 noch nicht freigegeben",
|
||||
}
|
||||
],
|
||||
ranker_key="agent_v1_fallback",
|
||||
)
|
||||
for row in ranked
|
||||
]
|
||||
|
||||
|
||||
register_sprint_commit_ranker(AgentV1SprintCommitRanker())
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Sprint commit ranking — pluggable rankers (heuristic now, agent later)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
COMMITTABLE_STATUSES = frozenset({"new", "triaged", "accepted"})
|
||||
PLANABLE_CYCLE_STATUSES = frozenset({"planned", "active"})
|
||||
OPEN_ACTION = frozenset({"open", "ready", "in_progress", "blocked", "review_required"})
|
||||
_DONE_ACTION = frozenset({"done", "discarded"})
|
||||
|
||||
|
||||
@dataclass
|
||||
class SprintCommitCandidate:
|
||||
item: dict[str, Any]
|
||||
dependency_refs: list[dict[str, Any]] = field(default_factory=list)
|
||||
dependency_blocked: bool = False
|
||||
dependency_reason: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class RankedSprintCommitCandidate:
|
||||
candidate: SprintCommitCandidate
|
||||
rank: int
|
||||
score: float
|
||||
reason_code: str
|
||||
summary: str
|
||||
factors: list[dict[str, Any]]
|
||||
ranker_key: str
|
||||
|
||||
|
||||
class SprintCommitRanker(Protocol):
|
||||
key: str
|
||||
|
||||
def rank(
|
||||
self,
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
candidates: list[SprintCommitCandidate],
|
||||
read_models: dict[str, Any],
|
||||
target_work_cycle_id: str,
|
||||
) -> list[RankedSprintCommitCandidate]:
|
||||
...
|
||||
|
||||
|
||||
_RANKERS: dict[str, SprintCommitRanker] = {}
|
||||
|
||||
|
||||
def register_sprint_commit_ranker(ranker: SprintCommitRanker) -> None:
|
||||
_RANKERS[ranker.key] = ranker
|
||||
|
||||
|
||||
def resolve_sprint_commit_ranker(ctx: SteeringEvalContext) -> SprintCommitRanker:
|
||||
"""
|
||||
Ranker-Auswahl — nicht hardcodiert.
|
||||
|
||||
Zukünftig: Governance/Method-Metadata (`proposal_rankers.sprint_commit=agent_v1`)
|
||||
oder Actor-Slot mit auditiertem Agent-Scoring. Default: heuristic_v0 (Fallback).
|
||||
"""
|
||||
configured = (
|
||||
(ctx.operating_context.get("proposal_rankers") or {}).get("sprint_commit")
|
||||
or (ctx.operating_context.get("method_capabilities") or {}).get(
|
||||
"sprint_commit_ranker"
|
||||
)
|
||||
)
|
||||
if configured and configured in _RANKERS:
|
||||
return _RANKERS[configured]
|
||||
return _RANKERS["heuristic_v0"]
|
||||
|
||||
|
||||
def _action_by_id(actions: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
return {str(a["id"]): a for a in actions if a.get("id")}
|
||||
|
||||
|
||||
def build_sprint_commit_candidates(
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
target_work_cycle_id: str,
|
||||
) -> list[SprintCommitCandidate]:
|
||||
"""Kandidaten + Abhängigkeitskontext — keine feste Bug/Story-Reihenfolge."""
|
||||
vocabulary = ctx.backlog_vocabulary
|
||||
convertible = frozenset(
|
||||
vocabulary.get("convertible_kinds") or ["story", "bug", "issue"]
|
||||
)
|
||||
actions_by_id = _action_by_id(ctx.actions)
|
||||
|
||||
candidates: list[SprintCommitCandidate] = []
|
||||
for item in ctx.backlog_items:
|
||||
if item.get("status") not in COMMITTABLE_STATUSES:
|
||||
continue
|
||||
if item.get("item_kind") == "epic":
|
||||
continue
|
||||
if (item.get("item_kind") or "story") not in convertible:
|
||||
continue
|
||||
|
||||
refs: list[dict[str, Any]] = []
|
||||
blocked = False
|
||||
block_reason: str | None = None
|
||||
|
||||
parent_action_id = item.get("parent_action_id")
|
||||
if parent_action_id:
|
||||
parent = actions_by_id.get(str(parent_action_id))
|
||||
refs.append(
|
||||
{
|
||||
"ref_type": "parent_action",
|
||||
"ref_id": str(parent_action_id),
|
||||
"status": parent.get("status") if parent else "missing",
|
||||
"title": parent.get("title") if parent else None,
|
||||
}
|
||||
)
|
||||
if not parent:
|
||||
blocked = True
|
||||
block_reason = "missing_parent_action"
|
||||
elif parent.get("status") not in _DONE_ACTION:
|
||||
in_target_sprint = (
|
||||
parent.get("work_cycle_id")
|
||||
and str(parent["work_cycle_id"]) == str(target_work_cycle_id)
|
||||
)
|
||||
if not in_target_sprint:
|
||||
blocked = True
|
||||
block_reason = "waiting_on_feature_action"
|
||||
|
||||
parent_backlog_id = item.get("parent_backlog_id")
|
||||
if parent_backlog_id:
|
||||
refs.append(
|
||||
{
|
||||
"ref_type": "parent_epic",
|
||||
"ref_id": str(parent_backlog_id),
|
||||
}
|
||||
)
|
||||
|
||||
candidates.append(
|
||||
SprintCommitCandidate(
|
||||
item=item,
|
||||
dependency_refs=refs,
|
||||
dependency_blocked=blocked,
|
||||
dependency_reason=block_reason,
|
||||
)
|
||||
)
|
||||
|
||||
return candidates
|
||||
|
||||
|
||||
def resolve_target_work_cycle(ctx: SteeringEvalContext) -> dict[str, Any] | None:
|
||||
cycles = [
|
||||
c for c in ctx.work_cycles if c.get("status") in PLANABLE_CYCLE_STATUSES
|
||||
]
|
||||
if not cycles:
|
||||
return None
|
||||
|
||||
if ctx.horizon.work_cycle_id:
|
||||
match = next(
|
||||
(c for c in cycles if str(c["id"]) == str(ctx.horizon.work_cycle_id)),
|
||||
None,
|
||||
)
|
||||
if match:
|
||||
return match
|
||||
|
||||
planned = sorted(
|
||||
[c for c in cycles if c.get("status") == "planned"],
|
||||
key=lambda c: (c.get("sort_order", 0), str(c["id"])),
|
||||
)
|
||||
if planned:
|
||||
return planned[0]
|
||||
|
||||
active = sorted(
|
||||
[c for c in cycles if c.get("status") == "active"],
|
||||
key=lambda c: (c.get("sort_order", 0), str(c["id"])),
|
||||
)
|
||||
return active[0] if active else None
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Default sprint ranker — explicit fallback, not product policy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.proposals.sprint_commit_context import (
|
||||
RankedSprintCommitCandidate,
|
||||
SprintCommitCandidate,
|
||||
SprintCommitRanker,
|
||||
register_sprint_commit_ranker,
|
||||
)
|
||||
|
||||
_PRIORITY_SCORE = {"critical": 100, "high": 75, "normal": 50, "low": 25}
|
||||
_KIND_BIAS = {"bug": 5, "issue": 3, "incident": 3, "story": 0, "idea": -5}
|
||||
|
||||
|
||||
class HeuristicV0SprintCommitRanker:
|
||||
"""
|
||||
Fallback-Ranker bis Agent/Regelwerk aktiv ist.
|
||||
|
||||
Sortiert primär nach Priorität + Eingangsreihenfolge; item_kind ist nur leichte
|
||||
Tendenz in `factors` — keine „Bugs immer zuerst“-Policy.
|
||||
"""
|
||||
|
||||
key = "heuristic_v0"
|
||||
|
||||
def rank(
|
||||
self,
|
||||
ctx: SteeringEvalContext,
|
||||
*,
|
||||
candidates: list[SprintCommitCandidate],
|
||||
read_models: dict[str, Any],
|
||||
target_work_cycle_id: str,
|
||||
) -> list[RankedSprintCommitCandidate]:
|
||||
scored: list[tuple[float, SprintCommitCandidate, list[dict[str, Any]]]] = []
|
||||
|
||||
for candidate in candidates:
|
||||
item = candidate.item
|
||||
priority = item.get("priority") or "normal"
|
||||
kind = item.get("item_kind") or "story"
|
||||
priority_score = _PRIORITY_SCORE.get(priority, 50)
|
||||
kind_bias = _KIND_BIAS.get(kind, 0)
|
||||
|
||||
factors: list[dict[str, Any]] = [
|
||||
{
|
||||
"code": "priority",
|
||||
"weight": priority_score,
|
||||
"label": f"Priorität {priority}",
|
||||
},
|
||||
{
|
||||
"code": "intake_order",
|
||||
"weight": -(item.get("sort_order") or 0),
|
||||
"label": "Eingangsreihenfolge",
|
||||
},
|
||||
]
|
||||
if kind_bias:
|
||||
factors.append(
|
||||
{
|
||||
"code": "kind_bias",
|
||||
"weight": kind_bias,
|
||||
"label": f"Typ {kind} (leichte Tendenz, keine Policy)",
|
||||
}
|
||||
)
|
||||
|
||||
score = priority_score + kind_bias - (item.get("sort_order") or 0) * 0.01
|
||||
|
||||
if candidate.dependency_blocked:
|
||||
score -= 1000
|
||||
factors.append(
|
||||
{
|
||||
"code": "dependency_blocked",
|
||||
"weight": -1000,
|
||||
"label": candidate.dependency_reason or "Abhängigkeit offen",
|
||||
}
|
||||
)
|
||||
|
||||
epic_rollups = read_models.get("epic_rollup") or []
|
||||
parent_epic = item.get("parent_backlog_id")
|
||||
if parent_epic:
|
||||
rollup = next(
|
||||
(
|
||||
r
|
||||
for r in epic_rollups
|
||||
if str(r.get("epic_backlog_id")) == str(parent_epic)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if rollup and rollup.get("status") == "in_progress":
|
||||
score += 2
|
||||
factors.append(
|
||||
{
|
||||
"code": "epic_in_progress",
|
||||
"weight": 2,
|
||||
"label": "Epic mit laufender Arbeit",
|
||||
}
|
||||
)
|
||||
|
||||
scored.append((score, candidate, factors))
|
||||
|
||||
scored.sort(
|
||||
key=lambda row: (
|
||||
-row[0],
|
||||
(row[1].item.get("title") or "").lower(),
|
||||
)
|
||||
)
|
||||
|
||||
ranked: list[RankedSprintCommitCandidate] = []
|
||||
for index, (score, candidate, factors) in enumerate(scored[:20], start=1):
|
||||
item = candidate.item
|
||||
reason_code = _reason_code(item, candidate)
|
||||
ranked.append(
|
||||
RankedSprintCommitCandidate(
|
||||
candidate=candidate,
|
||||
rank=index,
|
||||
score=score,
|
||||
reason_code=reason_code,
|
||||
summary=_summary_for(reason_code, candidate),
|
||||
factors=factors,
|
||||
ranker_key=self.key,
|
||||
)
|
||||
)
|
||||
return ranked
|
||||
|
||||
|
||||
def _reason_code(item: dict[str, Any], candidate: SprintCommitCandidate) -> str:
|
||||
if candidate.dependency_blocked:
|
||||
return candidate.dependency_reason or "dependency_blocked"
|
||||
priority = item.get("priority") or "normal"
|
||||
if priority == "critical":
|
||||
return "priority_critical"
|
||||
if priority == "high":
|
||||
return "priority_high"
|
||||
kind = item.get("item_kind") or "story"
|
||||
if kind in ("bug", "issue", "incident"):
|
||||
return "candidate_bug_or_issue"
|
||||
return "candidate_ready"
|
||||
|
||||
|
||||
def _summary_for(reason_code: str, candidate: SprintCommitCandidate) -> str:
|
||||
if candidate.dependency_blocked:
|
||||
if reason_code == "waiting_on_feature_action":
|
||||
return "Wartet auf Feature-Arbeitspaket im Sprint oder erledigt"
|
||||
if reason_code == "missing_parent_action":
|
||||
return "Feature-Referenz fehlt — Abhängigkeit klären"
|
||||
return "Abhängigkeit noch nicht erfüllt"
|
||||
labels = {
|
||||
"priority_critical": "Hohe Dringlichkeit (Priorität critical)",
|
||||
"priority_high": "Erhöhte Priorität",
|
||||
"candidate_bug_or_issue": "Kandidat (Heuristik — kein Bug-Zwang)",
|
||||
"candidate_ready": "Bereit zum Commit (Heuristik)",
|
||||
}
|
||||
return labels.get(reason_code, "Sprint-Commit-Kandidat (Heuristik)")
|
||||
|
||||
|
||||
register_sprint_commit_ranker(HeuristicV0SprintCommitRanker())
|
||||
@@ -0,0 +1 @@
|
||||
"""Steering read models — derived views, no OM mutation."""
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Epic roll-up read model — ADP P4 / Backlog-Hierarchie.
|
||||
|
||||
Fortschritt eines Epics = Aggregation committeter/erledigter Stories im Subbaum.
|
||||
Kein Gate-Status; Leading bleibt Action.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
EpicRollupStatus = Literal["empty", "intake_only", "in_progress", "done"]
|
||||
|
||||
_DONE_ACTION = frozenset({"done"})
|
||||
_ACTIVE_ACTION = frozenset({"open", "ready", "in_progress", "blocked", "review_required"})
|
||||
_CHILD_EXCLUDE = frozenset({"rejected"})
|
||||
|
||||
|
||||
def _action_status(actions_by_id: dict[str, dict[str, Any]], action_id: Any) -> str | None:
|
||||
if not action_id:
|
||||
return None
|
||||
row = actions_by_id.get(str(action_id))
|
||||
return row.get("status") if row else None
|
||||
|
||||
|
||||
def compute_epic_rollup(
|
||||
*,
|
||||
backlog_items: list[dict[str, Any]],
|
||||
actions: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Roll-up pro Epic-BacklogItem (item_kind=epic, nicht rejected)."""
|
||||
actions_by_id = {str(a["id"]): a for a in actions if a.get("id")}
|
||||
epics = [
|
||||
b
|
||||
for b in backlog_items
|
||||
if b.get("item_kind") == "epic" and b.get("status") not in _CHILD_EXCLUDE
|
||||
]
|
||||
|
||||
rollups: list[dict[str, Any]] = []
|
||||
for epic in epics:
|
||||
epic_id = str(epic["id"])
|
||||
children = [
|
||||
b
|
||||
for b in backlog_items
|
||||
if b.get("parent_backlog_id")
|
||||
and str(b["parent_backlog_id"]) == epic_id
|
||||
and b.get("item_kind") != "epic"
|
||||
and b.get("status") not in _CHILD_EXCLUDE
|
||||
]
|
||||
|
||||
child_total = len(children)
|
||||
committed: list[dict[str, Any]] = []
|
||||
uncommitted: list[dict[str, Any]] = []
|
||||
for child in children:
|
||||
if child.get("status") == "converted" or child.get("converted_action_id"):
|
||||
committed.append(child)
|
||||
else:
|
||||
uncommitted.append(child)
|
||||
|
||||
actions_done = actions_in_progress = actions_open = 0
|
||||
for child in committed:
|
||||
status = _action_status(actions_by_id, child.get("converted_action_id"))
|
||||
if status in _DONE_ACTION:
|
||||
actions_done += 1
|
||||
elif status in _ACTIVE_ACTION:
|
||||
actions_in_progress += 1
|
||||
actions_open += 1
|
||||
elif status:
|
||||
actions_open += 1
|
||||
|
||||
if child_total == 0:
|
||||
rollup_status: EpicRollupStatus = "empty"
|
||||
elif len(committed) == 0:
|
||||
rollup_status = "intake_only"
|
||||
elif actions_done == child_total:
|
||||
rollup_status = "done"
|
||||
else:
|
||||
rollup_status = "in_progress"
|
||||
|
||||
completion_ratio = actions_done / child_total if child_total else None
|
||||
commit_ratio = len(committed) / child_total if child_total else None
|
||||
|
||||
rollups.append(
|
||||
{
|
||||
"epic_backlog_id": epic_id,
|
||||
"epic_title": epic.get("title") or "Epic",
|
||||
"child_total": child_total,
|
||||
"child_uncommitted": len(uncommitted),
|
||||
"child_committed": len(committed),
|
||||
"actions_done": actions_done,
|
||||
"actions_in_progress": actions_in_progress,
|
||||
"actions_open": actions_open,
|
||||
"completion_ratio": completion_ratio,
|
||||
"commit_ratio": commit_ratio,
|
||||
"status": rollup_status,
|
||||
"data_source": "epic_rollup_v0.1",
|
||||
}
|
||||
)
|
||||
|
||||
rollups.sort(key=lambda r: (r["status"] != "in_progress", r["epic_title"].lower()))
|
||||
return rollups
|
||||
|
||||
|
||||
def epic_rollup_attention_items(
|
||||
*,
|
||||
initiative_id: str,
|
||||
rollups: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Attention aus Epic-Roll-up — Steuerung, nicht nur Anzeige."""
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
for rollup in rollups:
|
||||
epic_id = rollup["epic_backlog_id"]
|
||||
title = rollup["epic_title"]
|
||||
child_total = rollup["child_total"]
|
||||
if child_total == 0:
|
||||
continue
|
||||
|
||||
if rollup["child_committed"] == 0:
|
||||
items.append(
|
||||
{
|
||||
"kind": "epic_awaiting_commit",
|
||||
"severity": "info",
|
||||
"title": title,
|
||||
"summary": (
|
||||
f"Epic hat {rollup['child_uncommitted']} Item(s) im Eingang — "
|
||||
"noch keine committete Arbeit"
|
||||
),
|
||||
"scope_type": "backlog",
|
||||
"scope_id": epic_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "epic_awaiting_commit",
|
||||
"data_source": "epic_rollup",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
if rollup["child_uncommitted"] > 0 and rollup["actions_in_progress"] > 0:
|
||||
items.append(
|
||||
{
|
||||
"kind": "epic_uncommitted_during_execution",
|
||||
"severity": "warning",
|
||||
"title": title,
|
||||
"summary": (
|
||||
f"{rollup['child_uncommitted']} Item(s) noch im Eingang, "
|
||||
f"während {rollup['actions_in_progress']} Arbeitspaket(e) laufen"
|
||||
),
|
||||
"scope_type": "backlog",
|
||||
"scope_id": epic_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "epic_uncommitted_during_execution",
|
||||
"data_source": "epic_rollup",
|
||||
}
|
||||
)
|
||||
|
||||
if rollup["status"] == "done":
|
||||
items.append(
|
||||
{
|
||||
"kind": "epic_complete",
|
||||
"severity": "info",
|
||||
"title": title,
|
||||
"summary": "Alle Stories im Epic erledigt",
|
||||
"scope_type": "backlog",
|
||||
"scope_id": epic_id,
|
||||
"initiative_id": initiative_id,
|
||||
"reason_code": "epic_complete",
|
||||
"data_source": "epic_rollup",
|
||||
}
|
||||
)
|
||||
|
||||
return items
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Execution graph read model — critical_path / gate_fulfillment."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.graph.execution_engine import compute_execution_graph_state
|
||||
|
||||
|
||||
def compute_execution_graph_read_model(ctx: SteeringEvalContext) -> dict[str, Any]:
|
||||
from services.execution_plan import list_dependencies_for_initiative
|
||||
from steering.strategies.next_action.execution_ready import (
|
||||
gate_horizon_scope_for_method,
|
||||
)
|
||||
|
||||
gate_scope = gate_horizon_scope_for_method(
|
||||
ctx.binding.primary_method_key, ctx.tenant_ctx, ctx.initiative_id
|
||||
)
|
||||
dependencies = list_dependencies_for_initiative(
|
||||
tenant_id=ctx.tenant_ctx.tenant_id, initiative_id=ctx.initiative_id
|
||||
)
|
||||
return compute_execution_graph_state(
|
||||
actions=ctx.actions,
|
||||
dependencies=dependencies,
|
||||
scope_roadmap_item_id=gate_scope,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Planning debt read model — gate_fulfillment."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.graph.execution_engine import compute_planning_debt
|
||||
|
||||
|
||||
def compute_planning_debt_read_model(ctx: SteeringEvalContext) -> list[dict[str, Any]]:
|
||||
from services import roadmap as roadmap_service
|
||||
from steering.strategies.next_action.execution_ready import (
|
||||
gate_horizon_scope_for_method,
|
||||
)
|
||||
|
||||
gate_scope = gate_horizon_scope_for_method(
|
||||
ctx.binding.primary_method_key, ctx.tenant_ctx, ctx.initiative_id
|
||||
)
|
||||
roadmap_items = roadmap_service.list_roadmap_items_for_initiative(
|
||||
tenant_id=ctx.tenant_ctx.tenant_id, initiative_id=ctx.initiative_id
|
||||
)
|
||||
actions = ctx.actions
|
||||
|
||||
scoped_roadmap = roadmap_items
|
||||
scoped_actions = actions
|
||||
if gate_scope:
|
||||
scope = str(gate_scope)
|
||||
scoped_roadmap = [ri for ri in roadmap_items if str(ri.get("id")) == scope]
|
||||
scoped_actions = [
|
||||
a
|
||||
for a in actions
|
||||
if a.get("roadmap_item_id") and str(a["roadmap_item_id"]) == scope
|
||||
]
|
||||
|
||||
return compute_planning_debt(actions=scoped_actions, roadmap_items=scoped_roadmap)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Read model provider registry — K-Ext-1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
ReadModelCompute = Callable[[SteeringEvalContext], Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReadModelProvider:
|
||||
key: str
|
||||
requires_elements: frozenset[str]
|
||||
requires_data_slices: frozenset[str]
|
||||
compute: ReadModelCompute
|
||||
requires_any_element: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
_PROVIDERS: list[ReadModelProvider] = []
|
||||
|
||||
|
||||
def register_read_model(provider: ReadModelProvider) -> None:
|
||||
_PROVIDERS.append(provider)
|
||||
|
||||
|
||||
def compute_read_models(ctx: SteeringEvalContext) -> dict[str, Any]:
|
||||
"""Run all matching read model providers for the initiative context."""
|
||||
elements = ctx.steering_elements
|
||||
slices = frozenset(ctx.data_slices)
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
for provider in _PROVIDERS:
|
||||
if provider.requires_elements and not provider.requires_elements <= elements:
|
||||
continue
|
||||
if provider.requires_any_element and not (
|
||||
provider.requires_any_element & elements
|
||||
):
|
||||
continue
|
||||
if provider.requires_data_slices and not provider.requires_data_slices <= slices:
|
||||
continue
|
||||
result[provider.key] = provider.compute(ctx)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _register_builtin_read_models() -> None:
|
||||
from steering.read_models.epic_rollup import compute_epic_rollup
|
||||
from steering.read_models.execution_graph import compute_execution_graph_read_model
|
||||
from steering.read_models.planning_debt import compute_planning_debt_read_model
|
||||
from steering.read_models.tech_debt import compute_tech_debt_summary
|
||||
|
||||
register_read_model(
|
||||
ReadModelProvider(
|
||||
key="epic_rollup",
|
||||
requires_elements=frozenset({"backlog_epic_hierarchy"}),
|
||||
requires_data_slices=frozenset({"backlog"}),
|
||||
compute=lambda ctx: compute_epic_rollup(
|
||||
backlog_items=ctx.backlog_items,
|
||||
actions=ctx.actions,
|
||||
),
|
||||
)
|
||||
)
|
||||
register_read_model(
|
||||
ReadModelProvider(
|
||||
key="planning_debt",
|
||||
requires_elements=frozenset({"gate_fulfillment"}),
|
||||
requires_data_slices=frozenset({"roadmap", "actions"}),
|
||||
compute=compute_planning_debt_read_model,
|
||||
)
|
||||
)
|
||||
register_read_model(
|
||||
ReadModelProvider(
|
||||
key="execution_graph",
|
||||
requires_elements=frozenset(),
|
||||
requires_any_element=frozenset({"critical_path", "gate_fulfillment"}),
|
||||
requires_data_slices=frozenset({"actions"}),
|
||||
compute=compute_execution_graph_read_model,
|
||||
)
|
||||
)
|
||||
register_read_model(
|
||||
ReadModelProvider(
|
||||
key="tech_debt_summary",
|
||||
requires_elements=frozenset(),
|
||||
requires_data_slices=frozenset({"backlog", "actions"}),
|
||||
compute=compute_tech_debt_summary,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
_register_builtin_read_models()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Tech debt summary read model — P7."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
|
||||
_OPEN_BACKLOG = frozenset({"new", "triaged", "accepted"})
|
||||
_OPEN_ACTION = frozenset({"open", "ready", "in_progress", "blocked", "review_required"})
|
||||
|
||||
|
||||
def _parse_ts(value: Any) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
text = str(value).replace("Z", "+00:00")
|
||||
parsed = datetime.fromisoformat(text)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def compute_tech_debt_summary(ctx: SteeringEvalContext) -> dict[str, Any]:
|
||||
vocabulary = ctx.backlog_vocabulary
|
||||
if "tech_debt" not in (vocabulary.get("kinds") or []):
|
||||
return {
|
||||
"enabled": False,
|
||||
"backlog_items": [],
|
||||
"actions": [],
|
||||
"total_open": 0,
|
||||
"stale_count": 0,
|
||||
}
|
||||
|
||||
stale_days = int(ctx.agent_slot_config.get("stale_debt_days") or 30)
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=stale_days)
|
||||
|
||||
backlog_items: list[dict[str, Any]] = []
|
||||
for item in ctx.backlog_items:
|
||||
if item.get("item_kind") != "tech_debt":
|
||||
continue
|
||||
if item.get("status") not in _OPEN_BACKLOG:
|
||||
continue
|
||||
created = _parse_ts(item.get("created_at"))
|
||||
stale = created is not None and created < cutoff
|
||||
backlog_items.append(
|
||||
{
|
||||
"id": str(item["id"]),
|
||||
"title": item.get("title") or "Technische Schuld",
|
||||
"status": item.get("status"),
|
||||
"stale": stale,
|
||||
"created_at": item.get("created_at"),
|
||||
}
|
||||
)
|
||||
|
||||
actions: list[dict[str, Any]] = []
|
||||
for action in ctx.actions:
|
||||
if action.get("action_kind") != "tech_debt":
|
||||
continue
|
||||
if action.get("status") not in _OPEN_ACTION:
|
||||
continue
|
||||
created = _parse_ts(action.get("created_at"))
|
||||
stale = created is not None and created < cutoff
|
||||
actions.append(
|
||||
{
|
||||
"id": str(action["id"]),
|
||||
"title": action.get("title") or "Technische Schuld",
|
||||
"status": action.get("status"),
|
||||
"stale": stale,
|
||||
"created_at": action.get("created_at"),
|
||||
}
|
||||
)
|
||||
|
||||
stale_count = sum(1 for row in backlog_items if row["stale"]) + sum(
|
||||
1 for row in actions if row["stale"]
|
||||
)
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"backlog_items": backlog_items,
|
||||
"actions": actions,
|
||||
"total_open": len(backlog_items) + len(actions),
|
||||
"stale_count": stale_count,
|
||||
"stale_days": stale_days,
|
||||
}
|
||||
@@ -7,17 +7,13 @@ from typing import Any
|
||||
from steering.signals import default_rules
|
||||
from steering.strategies.next_action.default_strategy import DefaultNextActionStrategy
|
||||
from steering.strategies.next_action.execution_ready import (
|
||||
first_active_gate_id,
|
||||
list_execution_ready_candidates,
|
||||
merge_candidates,
|
||||
)
|
||||
from steering.strategies.next_action.product_milestone_driven import (
|
||||
ProductMilestoneDrivenStrategy,
|
||||
)
|
||||
from steering.strategies.next_action.recurring_helpers import (
|
||||
active_recurring_candidates,
|
||||
recurring_due_candidates,
|
||||
)
|
||||
from steering.strategies.next_action.recurring_helpers import recurring_due_candidates
|
||||
from steering.strategies.next_action.registry import (
|
||||
get_next_action_strategy,
|
||||
register_next_action_strategy,
|
||||
@@ -44,11 +40,14 @@ class MaturityProgressionStrategy:
|
||||
return _default.evaluate(ctx, 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)
|
||||
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]] = []
|
||||
if remaining > 0:
|
||||
ready = list_execution_ready_candidates(
|
||||
|
||||
@@ -8,6 +8,46 @@ from db import get_connection
|
||||
from psycopg2.extras import RealDictCursor
|
||||
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(
|
||||
ctx: TenantContext, initiative_id: str, *, limit: int
|
||||
@@ -15,33 +55,8 @@ def recurring_due_candidates(
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
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
|
||||
cur.execute(_PRACTICE_DUE_SQL, (ctx.tenant_id, initiative_id, limit))
|
||||
return _serialize_recurring_rows(cur.fetchall())
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -49,34 +64,5 @@ def recurring_due_candidates(
|
||||
def active_recurring_candidates(
|
||||
ctx: TenantContext, initiative_id: str, *, limit: int = 1
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Active recurring as 'heutige Übung' when nothing is due yet."""
|
||||
conn = get_connection()
|
||||
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()
|
||||
"""Due practices only — no fallback when already completed today."""
|
||||
return recurring_due_candidates(ctx, initiative_id, limit=limit)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Unit tests for agent slot providers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from steering.agent_slots.guardrail_review import resolve_guardrail_review_slots
|
||||
from steering.agent_slots.recurring_due import resolve_recurring_due_slots
|
||||
from steering.agent_slots.review_due import resolve_review_due_slots
|
||||
from steering.agent_slots.registry import compute_agent_slots
|
||||
from steering.kernel.models import HorizonMarker
|
||||
|
||||
|
||||
def _ctx(**kwargs):
|
||||
defaults = {
|
||||
"initiative_id": "init-1",
|
||||
"horizon": HorizonMarker(kind="none"),
|
||||
"operating_context": {
|
||||
"data_slices": ["reviews", "recurring", "roadmap"],
|
||||
"steering_elements": ["gate_fulfillment", "recurring_rhythm"],
|
||||
"agent_slot_config": {},
|
||||
},
|
||||
"_reviews": [],
|
||||
"_recurring_elements": [],
|
||||
"_actions": [],
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
|
||||
class FakeCtx:
|
||||
initiative_id = defaults["initiative_id"]
|
||||
horizon = defaults["horizon"]
|
||||
operating_context = defaults["operating_context"]
|
||||
|
||||
@property
|
||||
def steering_elements(self):
|
||||
return frozenset(self.operating_context.get("steering_elements") or [])
|
||||
|
||||
@property
|
||||
def data_slices(self):
|
||||
return list(self.operating_context.get("data_slices") or [])
|
||||
|
||||
@property
|
||||
def agent_slot_config(self):
|
||||
return dict(self.operating_context.get("agent_slot_config") or {})
|
||||
|
||||
@property
|
||||
def reviews(self):
|
||||
return defaults["_reviews"]
|
||||
|
||||
@property
|
||||
def recurring_elements(self):
|
||||
return defaults["_recurring_elements"]
|
||||
|
||||
@property
|
||||
def actions(self):
|
||||
return defaults["_actions"]
|
||||
|
||||
return FakeCtx()
|
||||
|
||||
|
||||
def test_review_due_slot_for_overdue_planned_review():
|
||||
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||
ctx = _ctx(
|
||||
_reviews=[
|
||||
{
|
||||
"id": "rev-1",
|
||||
"title": "Architektur-Review",
|
||||
"status": "planned",
|
||||
"due_at": past,
|
||||
}
|
||||
]
|
||||
)
|
||||
slots = resolve_review_due_slots(ctx)
|
||||
assert len(slots) == 1
|
||||
assert slots[0]["slot_key"] == "review.due"
|
||||
assert slots[0]["scope_id"] == "rev-1"
|
||||
assert slots[0]["actor_role_hint"] == "reviewer"
|
||||
|
||||
|
||||
def test_recurring_due_slot():
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
ctx = _ctx(
|
||||
_recurring_elements=[
|
||||
{
|
||||
"id": "rec-1",
|
||||
"title": "Sprint-Retro",
|
||||
"status": "active",
|
||||
"next_due_at": past,
|
||||
}
|
||||
]
|
||||
)
|
||||
slots = resolve_recurring_due_slots(ctx)
|
||||
assert len(slots) == 1
|
||||
assert slots[0]["slot_key"] == "recurring.due"
|
||||
|
||||
|
||||
def test_guardrail_slot_when_gate_has_planning_debt():
|
||||
ctx = _ctx(
|
||||
horizon=HorizonMarker(
|
||||
kind="gate",
|
||||
gate_roadmap_item_id="gate-1",
|
||||
gate_title="G3 Architektur",
|
||||
),
|
||||
_reviews=[],
|
||||
)
|
||||
read_models = {
|
||||
"planning_debt": [{"roadmap_item_id": "gate-1", "title": "G3"}],
|
||||
}
|
||||
slots = resolve_guardrail_review_slots(ctx, read_models)
|
||||
assert len(slots) == 1
|
||||
assert slots[0]["slot_key"] == "review.guardrail"
|
||||
assert slots[0]["guardrail_pack"] == "default_v0"
|
||||
|
||||
|
||||
def test_compute_agent_slots_respects_enabled_slots_filter():
|
||||
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||
ctx = _ctx(
|
||||
operating_context={
|
||||
"data_slices": ["reviews", "recurring", "roadmap"],
|
||||
"steering_elements": ["gate_fulfillment", "recurring_rhythm"],
|
||||
"agent_slot_config": {"enabled_slots": ["review.due"]},
|
||||
},
|
||||
_reviews=[
|
||||
{"id": "rev-1", "title": "Review", "status": "planned", "due_at": past}
|
||||
],
|
||||
_recurring_elements=[
|
||||
{
|
||||
"id": "rec-1",
|
||||
"title": "Retro",
|
||||
"status": "active",
|
||||
"next_due_at": past,
|
||||
}
|
||||
],
|
||||
)
|
||||
slots = compute_agent_slots(ctx, read_models={}, proposals={})
|
||||
assert len(slots) == 1
|
||||
assert slots[0]["slot_key"] == "review.due"
|
||||
@@ -86,6 +86,13 @@ def test_verify_reached_requires_evidence(client):
|
||||
assert ok.json()["status"] == "reached"
|
||||
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):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
|
||||
@@ -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
|
||||
body = verify.json()
|
||||
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(
|
||||
f"/api/initiatives/{initiative_id}/recurring",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
titles = {r["title"]: r["status"] for r in recurring}
|
||||
assert titles.get("Tägliche Übung") == "paused"
|
||||
assert any(t.startswith("Übung — Stufe 2") for t in titles)
|
||||
assert titles.get("Vorbeuge-Dehnung") == "paused"
|
||||
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(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/items",
|
||||
|
||||
@@ -51,7 +51,10 @@ def test_create_initiative_a1_applies_starter_kit(client):
|
||||
headers=_auth(token),
|
||||
)
|
||||
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):
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""AP2.2b — A2 linear project End-to-End (Neue Küche Happy Path)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
_STARTER_ACTION = "Erster Schritt — Planung konkretisieren"
|
||||
_GATE_TITLES = (
|
||||
"G1 — Planung",
|
||||
"G2 — Vorbereitung",
|
||||
"G3 — Umsetzung",
|
||||
"G4 — Abschluss",
|
||||
)
|
||||
|
||||
|
||||
def _gate_by_title(items: list[dict], prefix: str) -> dict:
|
||||
return next(i for i in items if i.get("title", "").startswith(prefix))
|
||||
|
||||
|
||||
def _create_kitchen(client, token):
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Neue Küche",
|
||||
archetype_key="initiative.linear_project",
|
||||
)
|
||||
assert created.status_code == 201
|
||||
body = created.json()
|
||||
assert body["starter_kit"]["applied"] is True
|
||||
assert body["archetype_key"] == "initiative.linear_project"
|
||||
return body["id"]
|
||||
|
||||
|
||||
def test_a2_starter_kit_kitchen_structure(client):
|
||||
"""Starter-Kit: Gates in Kette, Projects, Guidance, Operating Context."""
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_kitchen(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"] == "sequential_dependency"
|
||||
assert "critical_path" in body["steering_elements"]
|
||||
assert "gate_fulfillment" in body["steering_elements"]
|
||||
assert body["ui_profile"]["planDefaultRoute"] == "/plan/gates"
|
||||
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
|
||||
items = roadmap.json()
|
||||
assert len(items) == 4
|
||||
assert {i["title"] for i in items} == set(_GATE_TITLES)
|
||||
assert sum(1 for i in items if i["status"] == "active") == 1
|
||||
assert _gate_by_title(items, "G1")["status"] == "active"
|
||||
|
||||
deps = client.get(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/dependencies",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert deps.status_code == 200
|
||||
gate_ids = {i["title"]: i["id"] for i in items}
|
||||
dep_pairs = {(d["from_item_id"], d["to_item_id"]) for d in deps.json()}
|
||||
assert (gate_ids["G2 — Vorbereitung"], gate_ids["G1 — Planung"]) in dep_pairs
|
||||
assert (gate_ids["G3 — Umsetzung"], gate_ids["G2 — Vorbereitung"]) in dep_pairs
|
||||
assert (gate_ids["G4 — Abschluss"], gate_ids["G3 — Umsetzung"]) in dep_pairs
|
||||
|
||||
projects = client.get(
|
||||
f"/api/initiatives/{initiative_id}/projects",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert projects.status_code == 200
|
||||
assert {"Hauptpfad", "Begleitung"} <= {p["title"] for p in projects.json()}
|
||||
|
||||
actions = client.get(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert actions.status_code == 200
|
||||
assert any(a["title"] == _STARTER_ACTION for a in actions.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_guidance"]
|
||||
assert snap_body["steering_kernel"]["primary_method_key"] == "sequential_dependency"
|
||||
assert snap_body["steering_kernel"]["horizon"]["kind"] == "gate"
|
||||
next_actions = snap_body.get("next_actions") or []
|
||||
assert next_actions
|
||||
starter = next(a for a in actions.json() if a["title"] == _STARTER_ACTION)
|
||||
assert next_actions[0]["action_id"] == starter["id"]
|
||||
assert next_actions[0]["reason_code"] in (
|
||||
"execution_ready",
|
||||
"execution_critical_path",
|
||||
)
|
||||
|
||||
|
||||
def test_a2_kitchen_critical_path_complete_advances_next(client):
|
||||
"""Montage-Kette am aktiven Gate: kritischer Pfad, Next mit Begründung, Fortschritt."""
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_kitchen(client, token)
|
||||
|
||||
actions = client.get(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
headers=_auth(token),
|
||||
)
|
||||
starter = next(a for a in actions.json() if a["title"] == _STARTER_ACTION)
|
||||
deleted = client.delete(
|
||||
f"/api/actions/{starter['id']}",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert deleted.status_code == 204
|
||||
|
||||
roadmap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/roadmap/items",
|
||||
headers=_auth(token),
|
||||
)
|
||||
g1_id = _gate_by_title(roadmap.json(), "G1")["id"]
|
||||
|
||||
titles = ["Geräte geliefert", "Einbau Montage", "Endabnahme Küche"]
|
||||
action_ids: list[str] = []
|
||||
for index, title in enumerate(titles):
|
||||
res = client.post(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
json={
|
||||
"title": title,
|
||||
"status": "open",
|
||||
"roadmap_item_id": g1_id,
|
||||
"sort_order": index,
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 201
|
||||
action_ids.append(res.json()["id"])
|
||||
|
||||
for pred, succ in zip(action_ids[:-1], action_ids[1:]):
|
||||
dep = client.post(
|
||||
f"/api/initiatives/{initiative_id}/execution/dependencies",
|
||||
json={
|
||||
"predecessor_action_id": pred,
|
||||
"successor_action_id": succ,
|
||||
"dependency_kind": "requires",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert dep.status_code == 201
|
||||
|
||||
graph = client.get(
|
||||
f"/api/initiatives/{initiative_id}/execution/graph-state",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert graph.status_code == 200
|
||||
graph_body = graph.json()
|
||||
assert graph_body["critical_path"] == action_ids
|
||||
assert action_ids[0] in graph_body["ready_actions"]
|
||||
assert action_ids[1] in graph_body["blocked_actions"]
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
snap_body = snap.json()
|
||||
kernel = snap_body["steering_kernel"]
|
||||
exec_graph = kernel["read_models"].get("execution_graph") or {}
|
||||
assert exec_graph.get("critical_path") == action_ids
|
||||
|
||||
next_actions = snap_body.get("next_actions") or []
|
||||
assert next_actions
|
||||
top = next_actions[0]
|
||||
assert top["action_id"] == action_ids[0]
|
||||
assert top["reason_code"] in ("execution_ready", "execution_critical_path")
|
||||
|
||||
done = client.patch(
|
||||
f"/api/actions/{action_ids[0]}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert done.status_code == 200
|
||||
|
||||
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]["action_id"] == action_ids[1]
|
||||
assert next_after[0]["reason_code"] in (
|
||||
"execution_ready",
|
||||
"execution_critical_path",
|
||||
)
|
||||
|
||||
|
||||
def test_a2_kitchen_planning_debt_surfaces_gate_proposals(client):
|
||||
"""Aktives Gate ohne Actions → Planning Debt + gate_next_actions Proposal."""
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_kitchen(client, token)
|
||||
|
||||
actions = client.get(
|
||||
f"/api/initiatives/{initiative_id}/actions",
|
||||
headers=_auth(token),
|
||||
)
|
||||
starter = next(a for a in actions.json() if a["title"] == _STARTER_ACTION)
|
||||
deleted = client.delete(
|
||||
f"/api/actions/{starter['id']}",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert deleted.status_code == 204
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
snap_body = snap.json()
|
||||
planning_debt = snap_body["steering_kernel"]["read_models"].get("planning_debt") or []
|
||||
assert planning_debt
|
||||
assert any(d.get("kind") == "missing_execution_plan" for d in planning_debt)
|
||||
|
||||
gate_proposals = snap_body.get("gate_next_actions_proposals") or []
|
||||
assert gate_proposals
|
||||
assert any(p.get("reason_code") == "planning_debt" for p in gate_proposals)
|
||||
|
||||
attention_codes = {a.get("code") for a in snap_body.get("attention_items") or []}
|
||||
assert "planning_debt" in attention_codes
|
||||
@@ -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
|
||||
@@ -0,0 +1,161 @@
|
||||
"""AP2.2f — Backlog Epic-Hierarchie (parent_backlog_id + item_kind epic)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def _create_product_initiative(client, token, title="Epic Product"):
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title=title,
|
||||
archetype_key="initiative.product",
|
||||
)
|
||||
assert created.status_code == 201
|
||||
return created.json()["id"]
|
||||
|
||||
|
||||
def test_create_epic_and_story_under_epic(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token)
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Checkout Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert epic.status_code == 201
|
||||
epic_id = epic.json()["id"]
|
||||
assert epic.json()["item_kind"] == "epic"
|
||||
assert epic.json().get("parent_backlog_id") is None
|
||||
|
||||
story = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Login Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert story.status_code == 201
|
||||
assert story.json()["parent_backlog_id"] == epic_id
|
||||
|
||||
listed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
by_id = {item["id"]: item for item in listed.json()}
|
||||
assert by_id[story.json()["id"]]["parent_backlog_id"] == epic_id
|
||||
|
||||
|
||||
def test_epic_cannot_convert_to_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token, title="Epic Convert Block")
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Big Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_id = epic.json()["id"]
|
||||
|
||||
converted = client.post(
|
||||
f"/api/backlog/{epic_id}/convert-to-action",
|
||||
json={},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert converted.status_code == 400
|
||||
assert "Epic" in converted.json()["detail"]
|
||||
|
||||
|
||||
def test_story_under_epic_converts_to_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token, title="Story Convert")
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_id = epic.json()["id"]
|
||||
|
||||
story = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
story_id = story.json()["id"]
|
||||
|
||||
converted = client.post(
|
||||
f"/api/backlog/{story_id}/convert-to-action",
|
||||
json={},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert converted.status_code == 201
|
||||
assert converted.json()["action"]["title"] == "Story"
|
||||
|
||||
|
||||
def test_cannot_delete_epic_with_children(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token, title="Epic Delete Guard")
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_id = epic.json()["id"]
|
||||
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Child Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "new",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
deleted = client.delete(f"/api/backlog/{epic_id}", headers=_auth(token))
|
||||
assert deleted.status_code == 400
|
||||
assert "untergeordneten" in deleted.json()["detail"]
|
||||
|
||||
|
||||
def test_epic_cannot_have_parent_backlog(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token, title="Epic Parent Guard")
|
||||
|
||||
epic_a = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Epic A", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_a_id = epic_a.json()["id"]
|
||||
|
||||
epic_b = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Epic B",
|
||||
"item_kind": "epic",
|
||||
"parent_backlog_id": epic_a_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert epic_b.status_code == 400
|
||||
@@ -0,0 +1,78 @@
|
||||
"""AP2.2g — Profilgebundenes Backlog-Vokabular (ADP P3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def test_operating_context_product_has_agile_backlog_vocabulary(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Product Vocab",
|
||||
archetype_key="initiative.product",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
res = client.get(
|
||||
f"/api/initiatives/{initiative_id}/operating-context",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
vocab = res.json()["backlog_vocabulary"]
|
||||
assert vocab["profile_key"] == "agile_intake"
|
||||
assert "epic" in vocab["kinds"]
|
||||
assert vocab["labels"]["story"] == "Story"
|
||||
assert vocab["capabilities"]["epic_hierarchy"] is True
|
||||
assert vocab["capabilities"]["sprint_commit"] is True
|
||||
assert "backlog_epic_hierarchy" in res.json()["steering_elements"]
|
||||
|
||||
|
||||
def test_operating_context_linear_has_standard_backlog_vocabulary(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Linear Vocab",
|
||||
archetype_key="initiative.linear_project",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
res = client.get(
|
||||
f"/api/initiatives/{initiative_id}/operating-context",
|
||||
headers=_auth(token),
|
||||
)
|
||||
vocab = res.json()["backlog_vocabulary"]
|
||||
assert vocab["profile_key"] == "standard_intake"
|
||||
assert vocab["kinds"] == ["story", "bug", "issue", "tech_debt"]
|
||||
assert vocab["labels"]["tech_debt"] == "Technische Schuld"
|
||||
assert "epic" not in vocab["kinds"]
|
||||
assert vocab["capabilities"]["epic_hierarchy"] is False
|
||||
assert "backlog_epic_hierarchy" not in res.json()["steering_elements"]
|
||||
|
||||
|
||||
def test_linear_initiative_rejects_epic_backlog_item(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Linear Epic Block",
|
||||
archetype_key="initiative.linear_project",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Not allowed", "item_kind": "epic", "status": "new"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert epic.status_code == 400
|
||||
assert "nicht erlaubt" in epic.json()["detail"]
|
||||
@@ -0,0 +1,141 @@
|
||||
"""AP2.2h — Epic Roll-up Read Model (ADP P4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def _create_product_initiative(client, token, title="Epic Rollup"):
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title=title,
|
||||
archetype_key="initiative.product",
|
||||
)
|
||||
assert created.status_code == 201
|
||||
return created.json()["id"]
|
||||
|
||||
|
||||
def test_steering_snapshot_includes_epic_rollup(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token)
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Checkout Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_id = epic.json()["id"]
|
||||
|
||||
story_a = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Login Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
story_a_id = story_a.json()["id"]
|
||||
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Payment Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
converted = client.post(
|
||||
f"/api/backlog/{story_a_id}/convert-to-action",
|
||||
json={},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert converted.status_code == 201
|
||||
action_id = converted.json()["action"]["id"]
|
||||
|
||||
done = client.patch(
|
||||
f"/api/actions/{action_id}",
|
||||
json={"status": "done"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert done.status_code == 200
|
||||
|
||||
snapshot = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snapshot.status_code == 200
|
||||
body = snapshot.json()
|
||||
assert "epic_rollup" in body
|
||||
assert len(body["epic_rollup"]) == 1
|
||||
|
||||
rollup = body["epic_rollup"][0]
|
||||
assert rollup["epic_backlog_id"] == epic_id
|
||||
assert rollup["child_total"] == 2
|
||||
assert rollup["child_uncommitted"] == 1
|
||||
assert rollup["child_committed"] == 1
|
||||
assert rollup["actions_done"] == 1
|
||||
assert rollup["status"] == "in_progress"
|
||||
assert rollup["completion_ratio"] == 0.5
|
||||
|
||||
|
||||
def test_steering_snapshot_epic_attention_awaiting_commit(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_product_initiative(client, token, title="Epic Attention")
|
||||
|
||||
epic = client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Epic", "item_kind": "epic", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
epic_id = epic.json()["id"]
|
||||
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={
|
||||
"title": "Story",
|
||||
"item_kind": "story",
|
||||
"parent_backlog_id": epic_id,
|
||||
"status": "accepted",
|
||||
},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
snapshot = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snapshot.status_code == 200
|
||||
attention_codes = [
|
||||
item.get("code") or item.get("reason_code")
|
||||
for item in snapshot.json().get("attention_items", [])
|
||||
]
|
||||
assert "epic_awaiting_commit" in attention_codes
|
||||
|
||||
|
||||
def test_linear_initiative_has_no_epic_rollup(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Linear Rollup",
|
||||
archetype_key="initiative.linear_project",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
snapshot = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snapshot.status_code == 200
|
||||
assert snapshot.json().get("epic_rollup") == []
|
||||
@@ -0,0 +1,75 @@
|
||||
"""AP2.2i — Sprint commit proposals via Kernel v0.3 (P6)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def test_steering_snapshot_includes_sprint_commit_proposals(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Sprint Proposal",
|
||||
archetype_key="initiative.product",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/work-cycles",
|
||||
json={"title": "Sprint R2", "status": "planned"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Fix login", "item_kind": "bug", "status": "accepted", "priority": "high"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json={"title": "Checkout story", "item_kind": "story", "status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
snapshot = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snapshot.status_code == 200
|
||||
body = snapshot.json()
|
||||
assert body["steering_kernel"]["data_source"] == "steering_kernel_v0.4"
|
||||
proposals = body.get("sprint_commit_proposals") or []
|
||||
assert len(proposals) >= 2
|
||||
assert proposals[0]["proposal_key"] == "sprint_commit"
|
||||
assert proposals[0].get("ranker_key") == "heuristic_v0"
|
||||
assert "factors" in proposals[0]
|
||||
|
||||
attention_codes = [
|
||||
item.get("code") or item.get("reason_code")
|
||||
for item in body.get("attention_items", [])
|
||||
]
|
||||
assert "sprint_commit_suggested" in attention_codes
|
||||
|
||||
|
||||
def test_linear_initiative_has_no_sprint_proposals(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Linear Proposals",
|
||||
archetype_key="initiative.linear_project",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
snapshot = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snapshot.status_code == 200
|
||||
assert snapshot.json().get("sprint_commit_proposals") == []
|
||||
@@ -30,6 +30,7 @@ def test_operating_context_product(client):
|
||||
assert body["initiative_id"] == initiative_id
|
||||
assert body["archetype_key"] == "initiative.product"
|
||||
assert body["method_key"] == "continuous_product"
|
||||
assert "backlog_epic_hierarchy" in body["steering_elements"]
|
||||
assert body["ui_profile"]["planDefaultRoute"] == "/plan/inbox"
|
||||
assert body["ui_profile"]["workDefaultRoute"] == "/work/sprint"
|
||||
assert "work_cycles" in body["data_slices"]
|
||||
@@ -81,6 +82,8 @@ def test_operating_context_maturity(client):
|
||||
body = res.json()
|
||||
assert body["method_key"] == "maturity_progression"
|
||||
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):
|
||||
|
||||
@@ -49,6 +49,7 @@ def test_agile_iteration_composes_with_matrix():
|
||||
}
|
||||
)
|
||||
assert "program_delivery" not in method.composes_with
|
||||
assert "backlog_epic_hierarchy" in method.steering_elements
|
||||
|
||||
|
||||
def test_list_composable_modifiers_for_linear():
|
||||
|
||||
@@ -42,7 +42,7 @@ def test_evaluate_steering_returns_horizon_and_next(client):
|
||||
|
||||
ctx = tenant_context_from_user(user)
|
||||
evaluation = evaluate_steering(ctx, initiative_id=initiative_id)
|
||||
assert evaluation.data_source == "steering_kernel_v0.2"
|
||||
assert evaluation.data_source == "steering_kernel_v0.4"
|
||||
assert evaluation.lifecycle.slot_map.get("action_selection") == "active"
|
||||
assert evaluation.lifecycle.slot_map.get("validation") == "active"
|
||||
assert evaluation.lifecycle.slot_map.get("review") == "optional"
|
||||
@@ -77,7 +77,7 @@ def test_snapshot_routes_through_kernel_not_side_path(client):
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.json()["steering_kernel"]["data_source"] == "steering_kernel_v0.2"
|
||||
assert snap.json()["steering_kernel"]["data_source"] == "steering_kernel_v0.4"
|
||||
assert "lifecycle" in snap.json()["steering_kernel"]
|
||||
assert snap.json()["steering_kernel"]["lifecycle"]["slot_map"]["closure"] == "active"
|
||||
|
||||
@@ -103,4 +103,4 @@ def test_apply_steering_event_stub(client):
|
||||
)
|
||||
assert result["accepted"] is True
|
||||
assert result["handled"] is True
|
||||
assert result["evaluation"]["data_source"] == "steering_kernel_v0.2"
|
||||
assert result["evaluation"]["data_source"] == "steering_kernel_v0.4"
|
||||
@@ -106,7 +106,7 @@ def test_continuous_product_routes_through_spine(client):
|
||||
body = snap.json()
|
||||
kernel = body["steering_kernel"]
|
||||
assert kernel["primary_method_key"] == "continuous_product"
|
||||
assert kernel["data_source"] == "steering_kernel_v0.2"
|
||||
assert kernel["data_source"] == "steering_kernel_v0.4"
|
||||
assert kernel["lifecycle"]["slot_map"]["closure"] == "n/a"
|
||||
assert kernel["lifecycle"]["slot_map"]["planning"] == "active"
|
||||
assert body.get("next_actions") is not None
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Unit tests for backlog vocabulary resolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.backlog_vocabulary import resolve_backlog_vocabulary
|
||||
|
||||
|
||||
def test_resolve_agile_from_steering_element():
|
||||
vocab = resolve_backlog_vocabulary(
|
||||
data_slices=["backlog", "actions", "work_cycles"],
|
||||
method_key="continuous_product",
|
||||
steering_elements=frozenset(
|
||||
{"work_cycle_scope", "backlog_epic_hierarchy", "next_action_primary"}
|
||||
),
|
||||
)
|
||||
assert vocab["profile_key"] == "agile_intake"
|
||||
assert vocab["capabilities"]["epic_hierarchy"] is True
|
||||
assert vocab["capabilities"]["sprint_commit"] is True
|
||||
assert "epic" in vocab["kinds"]
|
||||
|
||||
|
||||
def test_resolve_continuous_without_epic_element():
|
||||
vocab = resolve_backlog_vocabulary(
|
||||
data_slices=["backlog", "actions"],
|
||||
method_key="continuous_product",
|
||||
steering_elements=frozenset({"next_action_primary"}),
|
||||
)
|
||||
assert vocab["profile_key"] == "continuous_intake"
|
||||
assert vocab["labels"]["story"] == "Idee"
|
||||
assert vocab["capabilities"]["epic_hierarchy"] is False
|
||||
|
||||
|
||||
def test_resolve_standard_for_generic_backlog():
|
||||
vocab = resolve_backlog_vocabulary(
|
||||
data_slices=["backlog", "actions"],
|
||||
method_key="sequential_dependency",
|
||||
steering_elements=frozenset({"critical_path", "next_action_primary"}),
|
||||
)
|
||||
assert vocab["profile_key"] == "standard_intake"
|
||||
assert vocab["labels"]["story"] == "Story"
|
||||
assert "tech_debt" in vocab["kinds"]
|
||||
|
||||
|
||||
def test_resolve_empty_without_backlog_slice():
|
||||
vocab = resolve_backlog_vocabulary(
|
||||
data_slices=["actions", "roadmap"],
|
||||
method_key="maturity_progression",
|
||||
steering_elements=frozenset({"next_action_primary"}),
|
||||
)
|
||||
assert vocab["kinds"] == []
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Unit tests for effective method contract resolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.effective_contract import resolve_effective_steering_elements
|
||||
|
||||
|
||||
def test_product_plan_phase_includes_agile_backlog_elements():
|
||||
elements = resolve_effective_steering_elements(
|
||||
"continuous_product",
|
||||
data_slices=["backlog", "actions", "work_cycles"],
|
||||
active_composition_modifier=None,
|
||||
)
|
||||
assert "work_cycle_scope" in elements
|
||||
assert "backlog_epic_hierarchy" in elements
|
||||
|
||||
|
||||
def test_linear_without_work_cycles_excludes_agile_backlog():
|
||||
elements = resolve_effective_steering_elements(
|
||||
"sequential_dependency",
|
||||
data_slices=["backlog", "actions", "roadmap"],
|
||||
active_composition_modifier=None,
|
||||
)
|
||||
assert "critical_path" in elements
|
||||
assert "backlog_epic_hierarchy" not in elements
|
||||
|
||||
|
||||
def test_active_modifier_merges_agile_elements():
|
||||
elements = resolve_effective_steering_elements(
|
||||
"sequential_dependency",
|
||||
data_slices=["backlog", "actions"],
|
||||
active_composition_modifier="agile_iteration",
|
||||
)
|
||||
assert "backlog_epic_hierarchy" in elements
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Unit tests — Epic roll-up read model (P4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.read_models.epic_rollup import (
|
||||
compute_epic_rollup,
|
||||
epic_rollup_attention_items,
|
||||
)
|
||||
|
||||
|
||||
def _item(
|
||||
*,
|
||||
id: str,
|
||||
title: str,
|
||||
item_kind: str = "story",
|
||||
status: str = "accepted",
|
||||
parent_backlog_id: str | None = None,
|
||||
converted_action_id: str | None = None,
|
||||
) -> dict:
|
||||
return {
|
||||
"id": id,
|
||||
"title": title,
|
||||
"item_kind": item_kind,
|
||||
"status": status,
|
||||
"parent_backlog_id": parent_backlog_id,
|
||||
"converted_action_id": converted_action_id,
|
||||
}
|
||||
|
||||
|
||||
def test_epic_rollup_empty_epic():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[_item(id="e1", title="Epic", item_kind="epic")],
|
||||
actions=[],
|
||||
)
|
||||
assert len(rollups) == 1
|
||||
assert rollups[0]["status"] == "empty"
|
||||
assert rollups[0]["child_total"] == 0
|
||||
|
||||
|
||||
def test_epic_rollup_intake_only():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[
|
||||
_item(id="e1", title="Checkout", item_kind="epic"),
|
||||
_item(id="s1", title="Login", parent_backlog_id="e1"),
|
||||
_item(id="s2", title="Pay", parent_backlog_id="e1"),
|
||||
],
|
||||
actions=[],
|
||||
)
|
||||
assert rollups[0]["status"] == "intake_only"
|
||||
assert rollups[0]["child_total"] == 2
|
||||
assert rollups[0]["child_uncommitted"] == 2
|
||||
assert rollups[0]["completion_ratio"] == 0.0
|
||||
|
||||
|
||||
def test_epic_rollup_partial_and_done():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[
|
||||
_item(id="e1", title="Epic", item_kind="epic"),
|
||||
_item(
|
||||
id="s1",
|
||||
title="Done story",
|
||||
parent_backlog_id="e1",
|
||||
status="converted",
|
||||
converted_action_id="a1",
|
||||
),
|
||||
_item(id="s2", title="Open story", parent_backlog_id="e1"),
|
||||
],
|
||||
actions=[
|
||||
{"id": "a1", "status": "done"},
|
||||
{"id": "a2", "status": "in_progress"},
|
||||
],
|
||||
)
|
||||
assert rollups[0]["status"] == "in_progress"
|
||||
assert rollups[0]["actions_done"] == 1
|
||||
assert rollups[0]["child_uncommitted"] == 1
|
||||
assert rollups[0]["completion_ratio"] == 0.5
|
||||
|
||||
|
||||
def test_epic_rollup_all_done():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[
|
||||
_item(id="e1", title="Epic", item_kind="epic"),
|
||||
_item(
|
||||
id="s1",
|
||||
title="A",
|
||||
parent_backlog_id="e1",
|
||||
status="converted",
|
||||
converted_action_id="a1",
|
||||
),
|
||||
],
|
||||
actions=[{"id": "a1", "status": "done"}],
|
||||
)
|
||||
assert rollups[0]["status"] == "done"
|
||||
assert rollups[0]["completion_ratio"] == 1.0
|
||||
|
||||
|
||||
def test_epic_rollup_attention_awaiting_commit():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[
|
||||
_item(id="e1", title="Epic", item_kind="epic"),
|
||||
_item(id="s1", title="Story", parent_backlog_id="e1"),
|
||||
],
|
||||
actions=[],
|
||||
)
|
||||
items = epic_rollup_attention_items(initiative_id="init-1", rollups=rollups)
|
||||
assert any(i["reason_code"] == "epic_awaiting_commit" for i in items)
|
||||
|
||||
|
||||
def test_epic_rollup_attention_split_focus():
|
||||
rollups = compute_epic_rollup(
|
||||
backlog_items=[
|
||||
_item(id="e1", title="Epic", item_kind="epic"),
|
||||
_item(
|
||||
id="s1",
|
||||
title="Running",
|
||||
parent_backlog_id="e1",
|
||||
status="converted",
|
||||
converted_action_id="a1",
|
||||
),
|
||||
_item(id="s2", title="Waiting", parent_backlog_id="e1"),
|
||||
],
|
||||
actions=[{"id": "a1", "status": "in_progress"}],
|
||||
)
|
||||
items = epic_rollup_attention_items(initiative_id="init-1", rollups=rollups)
|
||||
assert any(i["reason_code"] == "epic_uncommitted_during_execution" for i in items)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Unit tests — gate_next_actions proposal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding
|
||||
from steering.proposals.gate_next_actions import propose_gate_next_actions
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def _ctx(*, backlog_items, read_models=None, gate_id="gate-1"):
|
||||
binding = SteeringBinding(
|
||||
primary_method_key="sequential_dependency",
|
||||
composition_modifier=None,
|
||||
next_work_strategy_key="sequential_dependency",
|
||||
)
|
||||
lifecycle = LifecycleContext(
|
||||
current_state="execution",
|
||||
current_state_label="Ausführung",
|
||||
slot_map={},
|
||||
active_slots=(),
|
||||
operational_slots=(),
|
||||
)
|
||||
horizon = HorizonMarker(
|
||||
kind="gate",
|
||||
gate_roadmap_item_id=gate_id,
|
||||
gate_title="Gate A",
|
||||
)
|
||||
eval_ctx = SteeringEvalContext(
|
||||
tenant_ctx=TenantContext(
|
||||
user_id="u1",
|
||||
email="t@example.com",
|
||||
display_name="Test",
|
||||
portal_role="user",
|
||||
tenant_id="t1",
|
||||
tenant_slug="t",
|
||||
tenant_name="T",
|
||||
tenant_role="admin",
|
||||
actor_id=None,
|
||||
actor_type=None,
|
||||
session_token="test",
|
||||
capabilities=frozenset(),
|
||||
),
|
||||
initiative_id="init-1",
|
||||
binding=binding,
|
||||
horizon=horizon,
|
||||
lifecycle=lifecycle,
|
||||
operating_context={
|
||||
"steering_elements": ["gate_fulfillment", "critical_path"],
|
||||
"data_slices": ["backlog", "roadmap", "actions"],
|
||||
"backlog_vocabulary": {"convertible_kinds": ["story", "bug", "issue"]},
|
||||
},
|
||||
)
|
||||
eval_ctx._backlog_items = backlog_items
|
||||
eval_ctx._actions = []
|
||||
eval_ctx._work_cycles = []
|
||||
return eval_ctx, read_models or {}
|
||||
|
||||
|
||||
def test_gate_proposal_includes_planning_debt():
|
||||
eval_ctx, read_models = _ctx(
|
||||
backlog_items=[],
|
||||
read_models={
|
||||
"planning_debt": [
|
||||
{
|
||||
"roadmap_item_id": "gate-1",
|
||||
"title": "Gate A",
|
||||
"message": "Kein Plan",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
result = propose_gate_next_actions(eval_ctx, read_models=read_models)
|
||||
assert result[0]["scope_type"] == "roadmap_item"
|
||||
assert result[0]["reason_code"] == "planning_debt"
|
||||
|
||||
|
||||
def test_gate_proposal_backlog_at_gate():
|
||||
eval_ctx, read_models = _ctx(
|
||||
backlog_items=[
|
||||
{
|
||||
"id": "b1",
|
||||
"title": "Story",
|
||||
"item_kind": "story",
|
||||
"status": "accepted",
|
||||
"roadmap_item_id": "gate-1",
|
||||
"priority": "normal",
|
||||
"sort_order": 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
result = propose_gate_next_actions(eval_ctx, read_models=read_models)
|
||||
assert any(p["scope_type"] == "backlog_item" for p in result)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Unit tests — intake_triage proposal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.eval_context import SteeringEvalContext
|
||||
from steering.kernel.models import HorizonMarker, LifecycleContext, SteeringBinding
|
||||
from steering.proposals.intake_triage import propose_intake_triage
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def test_intake_triage_proposes_backlog_items():
|
||||
binding = SteeringBinding(
|
||||
primary_method_key="sequential_dependency",
|
||||
composition_modifier=None,
|
||||
next_work_strategy_key="sequential_dependency",
|
||||
)
|
||||
eval_ctx = SteeringEvalContext(
|
||||
tenant_ctx=TenantContext(
|
||||
user_id="u1",
|
||||
email="t@example.com",
|
||||
display_name="Test",
|
||||
portal_role="user",
|
||||
tenant_id="t1",
|
||||
tenant_slug="t",
|
||||
tenant_name="T",
|
||||
tenant_role="admin",
|
||||
actor_id=None,
|
||||
actor_type=None,
|
||||
session_token="test",
|
||||
capabilities=frozenset(),
|
||||
),
|
||||
initiative_id="init-1",
|
||||
binding=binding,
|
||||
horizon=HorizonMarker(kind="none"),
|
||||
lifecycle=LifecycleContext(
|
||||
current_state="execution",
|
||||
current_state_label="Ausführung",
|
||||
slot_map={},
|
||||
active_slots=(),
|
||||
operational_slots=(),
|
||||
),
|
||||
operating_context={
|
||||
"steering_elements": ["gate_fulfillment"],
|
||||
"data_slices": ["backlog"],
|
||||
"backlog_vocabulary": {"convertible_kinds": ["story", "bug", "issue"]},
|
||||
},
|
||||
)
|
||||
eval_ctx._backlog_items = [
|
||||
{"id": "b1", "title": "Item", "item_kind": "story", "status": "new", "priority": "normal", "sort_order": 0},
|
||||
]
|
||||
eval_ctx._actions = []
|
||||
eval_ctx._work_cycles = []
|
||||
|
||||
result = propose_intake_triage(eval_ctx, read_models={})
|
||||
assert len(result) == 1
|
||||
assert result[0]["proposal_key"] == "intake_triage"
|
||||
assert result[0]["ranker_key"] == "heuristic_v0"
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Integration tests for portfolio steering API — K-Ext-5."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def test_workspace_steering_aggregates_kernel(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
created = _create_initiative(client, token, title="Portfolio Kernel")
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
res = client.get("/api/workspace/steering", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["data_source"] == "steering_kernel_portfolio_v0.1"
|
||||
assert body["initiative_count"] >= 1
|
||||
assert isinstance(body["attention"], list)
|
||||
assert isinstance(body["next_work"], list)
|
||||
assert isinstance(body["proposals_summary"], list)
|
||||
assert isinstance(body["agent_slots"], list)
|
||||
assert initiative_id in body["attention_by_initiative"]
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Unit tests for portfolio steering aggregation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from steering.portfolio.aggregate import _sort_attention, _sort_next_work
|
||||
|
||||
|
||||
def test_sort_attention_by_severity_then_portfolio_rank():
|
||||
items = [
|
||||
{"severity": "info", "portfolio_rank": 0, "title": "B"},
|
||||
{"severity": "critical", "portfolio_rank": 2, "title": "A"},
|
||||
{"severity": "warning", "portfolio_rank": 1, "title": "C"},
|
||||
]
|
||||
sorted_items = _sort_attention(items)
|
||||
assert sorted_items[0]["severity"] == "critical"
|
||||
assert sorted_items[1]["severity"] == "warning"
|
||||
assert sorted_items[2]["severity"] == "info"
|
||||
|
||||
|
||||
def test_sort_next_work_by_portfolio_rank():
|
||||
items = [
|
||||
{"portfolio_rank": 2, "title": "Late"},
|
||||
{"portfolio_rank": 0, "title": "First"},
|
||||
{"portfolio_rank": None, "title": "Unranked"},
|
||||
]
|
||||
sorted_items = _sort_next_work(items)
|
||||
assert sorted_items[0]["title"] == "First"
|
||||
assert sorted_items[1]["title"] == "Late"
|
||||
assert sorted_items[2]["title"] == "Unranked"
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user