Update Planning Exercise Suggestion and Context Handling
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (pull_request) Successful in 37s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 13s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m15s

- Incremented version to 0.8.183, reflecting the implementation of Phase C1 enhancements.
- Added support for progression graph auto-matching and variant-aware successors in exercise suggestions.
- Updated request and response structures to include `anchor_exercise_variant_id`, `progression_graph_name`, and `suggested_variant_id`.
- Enhanced frontend components to integrate planning AI search capabilities, including a new modal for exercise creation and improved context display in the exercise list.
- Updated changelog to document these significant improvements in planning AI functionality.
This commit is contained in:
Lars committed 2026-05-23 10:42:17 +02:00
1 parent 50aff849d8
commit b2157d8a40
16 files changed
+985 -136

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
"""
Progressionsgraph-Auflösung für Planungs-KI (Phase C1).
Variantenbewusste Nachfolger-Kanten (Migration 034) und Auto-Match eines sichtbaren Graphen
anhand der Anker-Übung, wenn der Client keine graph_id sendet.
"""
from __future__ import annotations
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from tenant_context import TenantContext, library_content_visibility_sql
ProgressionSuccessorBundle = Tuple[Set[int], Dict[int, str], Dict[int, Optional[int]]]
def edge_matches_anchor_from(
edge: Mapping[str, Any],
from_variant_id: Optional[int],
) -> bool:
"""Kante gilt als Ausgang vom Anker: generische Kante oder passende Varianten-Kante."""
edge_var = edge.get("from_exercise_variant_id")
if edge_var is None:
return True
if from_variant_id is None:
return False
try:
return int(edge_var) == int(from_variant_id)
except (TypeError, ValueError):
return False
def filter_outgoing_progression_edges(
edges: Sequence[Mapping[str, Any]],
*,
from_variant_id: Optional[int],
) -> List[Mapping[str, Any]]:
return [e for e in edges if edge_matches_anchor_from(e, from_variant_id)]
def parse_successors_from_edges(
edges: Sequence[Mapping[str, Any]],
) -> ProgressionSuccessorBundle:
ids: Set[int] = set()
notes: Dict[int, str] = {}
variants: Dict[int, Optional[int]] = {}
for row in edges:
tid = int(row["to_exercise_id"])
ids.add(tid)
n = (row.get("notes") or "").strip()
if n:
notes[tid] = n
raw_v = row.get("to_exercise_variant_id")
variants[tid] = int(raw_v) if raw_v is not None else None
return ids, notes, variants
def rank_progression_graph_rows(rows: Sequence[Mapping[str, Any]]) -> Optional[Mapping[str, Any]]:
if not rows:
return None
def _key(row: Mapping[str, Any]) -> Tuple[int, int, int]:
var_match = int(row.get("variant_match_count") or 0)
out_count = int(row.get("outgoing_count") or 0)
gid = int(row.get("id") or 0)
return (var_match, out_count, gid)
return max(rows, key=_key)
def resolve_progression_graph_for_planning(
cur,
tenant: TenantContext,
*,
from_exercise_id: Optional[int],
from_variant_id: Optional[int],
explicit_graph_id: Optional[int],
) -> Tuple[Optional[int], Optional[str], bool]:
"""
Liefert (graph_id, graph_name, auto_resolved).
Bei explicit_graph_id: Sichtbarkeit prüfen, kein Auto-Match.
Sonst: sichtbarer Graph mit passenden Ausgangskanten vom Anker.
"""
profile_id = tenant.profile_id
role = tenant.global_role
vis_sql, vis_params = library_content_visibility_sql(
alias="g",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
if explicit_graph_id and int(explicit_graph_id) > 0:
gid = int(explicit_graph_id)
cur.execute(
f"""
SELECT g.id, g.name
FROM exercise_progression_graphs g
WHERE g.id = %s AND ({vis_sql})
""",
[gid, *vis_params],
)
row = cur.fetchone()
if not row:
return None, None, False
name = (row.get("name") or "").strip() or None
return gid, name, False
if not from_exercise_id or int(from_exercise_id) < 1:
return None, None, False
anchor_var = int(from_variant_id) if from_variant_id is not None else None
cur.execute(
f"""
SELECT g.id, g.name,
COUNT(*)::int AS outgoing_count,
COUNT(*) FILTER (
WHERE e.from_exercise_variant_id IS NOT NULL
AND (%s IS NOT NULL)
AND e.from_exercise_variant_id = %s
)::int AS variant_match_count
FROM exercise_progression_edges e
INNER JOIN exercise_progression_graphs g ON g.id = e.graph_id
WHERE e.from_exercise_id = %s
AND LOWER(TRIM(e.edge_type)) = 'next_exercise'
AND ({vis_sql})
AND (
e.from_exercise_variant_id IS NULL
OR (%s IS NULL)
OR e.from_exercise_variant_id = %s
)
GROUP BY g.id, g.name
""",
[anchor_var, anchor_var, int(from_exercise_id), *vis_params, anchor_var, anchor_var],
)
picked = rank_progression_graph_rows(cur.fetchall())
if not picked:
return None, None, False
gid = int(picked["id"])
name = (picked.get("name") or "").strip() or None
return gid, name, True
def load_progression_successors_for_anchor(
cur,
*,
graph_id: Optional[int],
from_exercise_id: Optional[int],
from_variant_id: Optional[int],
) -> ProgressionSuccessorBundle:
if not graph_id or not from_exercise_id:
return set(), {}, {}
cur.execute(
"""
SELECT to_exercise_id, to_exercise_variant_id, notes, from_exercise_variant_id
FROM exercise_progression_edges
WHERE graph_id = %s AND from_exercise_id = %s
AND LOWER(TRIM(edge_type)) = 'next_exercise'
""",
(int(graph_id), int(from_exercise_id)),
)
rows = [dict(r) for r in cur.fetchall()]
filtered = filter_outgoing_progression_edges(rows, from_variant_id=from_variant_id)
return parse_successors_from_edges(filtered)
def apply_progression_context_to_pack(
cur,
tenant: TenantContext,
pack: Dict[str, Any],
*,
explicit_graph_id: Optional[int],
anchor_variant_id: Optional[int],
) -> Dict[str, Any]:
"""Pack um aufgelösten Graph und Nachfolger anreichern."""
anchor_id = pack.get("anchor_exercise_id")
pack["anchor_exercise_variant_id"] = anchor_variant_id
graph_id, graph_name, auto_resolved = resolve_progression_graph_for_planning(
cur,
tenant,
from_exercise_id=anchor_id,
from_variant_id=anchor_variant_id,
explicit_graph_id=explicit_graph_id,
)
pack["progression_graph_id"] = graph_id
pack["progression_graph_name"] = graph_name
pack["progression_graph_auto_resolved"] = bool(auto_resolved)
succ_ids, notes, succ_variants = load_progression_successors_for_anchor(
cur,
graph_id=graph_id,
from_exercise_id=anchor_id,
from_variant_id=anchor_variant_id,
)
pack["progression_successor_ids"] = sorted(succ_ids)
pack["progression_edge_notes"] = notes
pack["progression_successor_variants"] = succ_variants
return pack
__all__ = [
"apply_progression_context_to_pack",
"edge_matches_anchor_from",
"filter_outgoing_progression_edges",
"load_progression_successors_for_anchor",
"parse_successors_from_edges",
"rank_progression_graph_rows",
"resolve_progression_graph_for_planning",
]
+4
View File
@@ -257,6 +257,10 @@ def rank_visible_library_hits(
"reasons": reasons,
}
)
succ_variants = pack.get("progression_successor_variants") or {}
suggested_vid = succ_variants.get(eid)
if suggested_vid:
hits[-1]["suggested_variant_id"] = int(suggested_vid)
hits.sort(key=lambda h: (-h["score"], h.get("title") or ""))
return hits, skills_by_ex
+66 -36
View File
@@ -6,7 +6,7 @@ Siehe .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md
from __future__ import annotations
import re
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from fastapi import HTTPException
from pydantic import BaseModel, Field
@@ -15,6 +15,7 @@ from tenant_context import TenantContext, library_content_visibility_sql
from planning_exercise_profiles import skill_profile_summary_from_exercise_ids
from planning_exercise_retrieval import run_multistage_planning_retrieval
from planning_exercise_llm_rank import try_llm_rerank_planning_hits
from planning_exercise_progression import apply_progression_context_to_pack
from planning_exercise_target_pipeline import (
build_planning_target_with_query_pipeline,
compose_retrieval_phase,
@@ -53,6 +54,7 @@ class PlanningExerciseSuggestRequest(BaseModel):
phase_order_index: Optional[int] = Field(default=None, ge=0)
parallel_stream_order_index: Optional[int] = Field(default=None, ge=0)
anchor_exercise_id: Optional[int] = Field(default=None, ge=1)
anchor_exercise_variant_id: Optional[int] = Field(default=None, ge=1)
progression_graph_id: Optional[int] = Field(default=None, ge=1)
query: Optional[str] = ""
intent_hint: Optional[str] = None
@@ -169,31 +171,62 @@ def _load_skill_ids_for_exercise(cur, exercise_id: Optional[int]) -> Set[int]:
return {int(r["skill_id"]) for r in cur.fetchall() if r.get("skill_id")}
def _load_progression_successors(
def _resolve_anchor_variant_id(
pack: Mapping[str, Any],
body: PlanningExerciseSuggestRequest,
sections: Optional[Sequence[Dict[str, Any]]] = None,
) -> Optional[int]:
raw = body.anchor_exercise_variant_id
if raw is not None:
try:
vid = int(raw)
except (TypeError, ValueError):
vid = 0
if vid > 0:
return vid
anchor_id = pack.get("anchor_exercise_id")
if not anchor_id or not sections:
return None
sec = _section_for_context(sections, pack.get("section_order_index"))
if not sec:
return None
target = int(anchor_id)
for it in sorted(sec.get("items") or [], key=lambda x: int(x.get("order_index") or 0), reverse=True):
if str(it.get("item_type") or "").strip().lower() == "note":
continue
try:
eid = int(it.get("exercise_id"))
except (TypeError, ValueError):
continue
if eid != target:
continue
raw_v = it.get("exercise_variant_id")
if raw_v is None:
return None
try:
vid = int(raw_v)
except (TypeError, ValueError):
return None
return vid if vid > 0 else None
return None
def _finalize_progression_context(
cur,
graph_id: Optional[int],
from_exercise_id: Optional[int],
) -> Tuple[Set[int], Dict[int, str]]:
if not graph_id or not from_exercise_id:
return set(), {}
cur.execute(
"""
SELECT to_exercise_id, notes
FROM exercise_progression_edges
WHERE graph_id = %s AND from_exercise_id = %s
AND LOWER(TRIM(edge_type)) = 'next_exercise'
""",
(int(graph_id), int(from_exercise_id)),
tenant: TenantContext,
pack: Dict[str, Any],
body: PlanningExerciseSuggestRequest,
*,
sections: Optional[Sequence[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
anchor_variant = _resolve_anchor_variant_id(pack, body, sections)
return apply_progression_context_to_pack(
cur,
tenant,
pack,
explicit_graph_id=body.progression_graph_id,
anchor_variant_id=anchor_variant,
)
ids: Set[int] = set()
notes: Dict[int, str] = {}
for row in cur.fetchall():
tid = int(row["to_exercise_id"])
ids.add(tid)
n = (row.get("notes") or "").strip()
if n:
notes[tid] = n
return ids, notes
def _load_group_recent_exercise_ids(
@@ -469,9 +502,6 @@ def build_planning_exercise_context_pack(
planned_ids = _collect_planned_exercise_ids(sections)
anchor_id = _resolve_anchor_from_plan(planned_ids, body.anchor_exercise_id)
anchor_skills = _load_skill_ids_for_exercise(cur, anchor_id)
progression_ids, progression_notes = _load_progression_successors(
cur, body.progression_graph_id, anchor_id
)
group_recent = _load_group_recent_exercise_ids(cur, unit.get("group_id"), int(body.unit_id))
titles = _load_exercise_titles(cur, [x for x in [anchor_id] if x])
@@ -493,9 +523,6 @@ def build_planning_exercise_context_pack(
"anchor_exercise_id": anchor_id,
"anchor_title": anchor_title,
"anchor_skill_ids": sorted(anchor_skills),
"progression_graph_id": body.progression_graph_id,
"progression_successor_ids": sorted(progression_ids),
"progression_edge_notes": progression_notes,
"group_recent_exercise_ids": sorted(group_recent),
}
return _attach_planning_context_details(cur, pack, sections=sections, body=body)
@@ -527,9 +554,6 @@ def build_client_planning_context_pack(
anchor_id = _resolve_anchor_from_plan(planned_ids, body.anchor_exercise_id)
anchor_skills = _load_skill_ids_for_exercise(cur, anchor_id)
progression_ids, progression_notes = _load_progression_successors(
cur, body.progression_graph_id, anchor_id
)
group_id = body.group_id
group_name = None
@@ -559,9 +583,6 @@ def build_client_planning_context_pack(
"anchor_exercise_id": anchor_id,
"anchor_title": anchor_title,
"anchor_skill_ids": sorted(anchor_skills),
"progression_graph_id": body.progression_graph_id,
"progression_successor_ids": sorted(progression_ids),
"progression_edge_notes": progression_notes,
"group_recent_exercise_ids": sorted(group_recent),
"context_mode": "client_free",
}
@@ -580,6 +601,12 @@ def suggest_planning_exercises(
pack = build_client_planning_context_pack(cur, tenant=tenant, body=body)
pack = _apply_client_planned_override(cur, pack, body)
pack = _attach_planning_context_details(cur, pack, body=body)
sections_for_variant = None
if body.unit_id and not (body.anchor_exercise_variant_id and int(body.anchor_exercise_variant_id) > 0):
sections_for_variant = _fetch_sections(cur, int(body.unit_id))
pack = _finalize_progression_context(
cur, tenant, pack, body, sections=sections_for_variant
)
query = _normalize_query(body.query)
heuristic_intent = resolve_planning_exercise_intent(query, body.intent_hint)
@@ -713,6 +740,9 @@ def suggest_planning_exercises(
"anchor_exercise_id": pack.get("anchor_exercise_id"),
"last_section_exercise_title": pack.get("last_section_exercise_title"),
"progression_graph_id": pack.get("progression_graph_id"),
"progression_graph_name": pack.get("progression_graph_name"),
"progression_graph_auto_resolved": pack.get("progression_graph_auto_resolved"),
"anchor_exercise_variant_id": pack.get("anchor_exercise_variant_id"),
"context_mode": pack.get("context_mode") or ("unit" if pack.get("unit_id") else "client_free"),
"unit_skill_profile": pack.get("unit_skill_profile_summary"),
"section_skill_profile": pack.get("section_skill_profile_summary"),
@@ -0,0 +1,56 @@
"""Tests Progressionsgraph-Auflösung für Planungs-KI (Phase C1)."""
from planning_exercise_progression import (
edge_matches_anchor_from,
filter_outgoing_progression_edges,
parse_successors_from_edges,
rank_progression_graph_rows,
)
def test_edge_matches_anchor_from_generic_edge():
assert edge_matches_anchor_from({"from_exercise_variant_id": None}, None)
assert edge_matches_anchor_from({"from_exercise_variant_id": None}, 5)
def test_edge_matches_anchor_from_variant_specific():
assert edge_matches_anchor_from({"from_exercise_variant_id": 3}, 3)
assert not edge_matches_anchor_from({"from_exercise_variant_id": 3}, None)
assert not edge_matches_anchor_from({"from_exercise_variant_id": 3}, 4)
def test_filter_outgoing_progression_edges():
edges = [
{"from_exercise_variant_id": None, "to_exercise_id": 10},
{"from_exercise_variant_id": 2, "to_exercise_id": 11},
]
filtered = filter_outgoing_progression_edges(edges, from_variant_id=2)
assert len(filtered) == 2
only_generic = filter_outgoing_progression_edges(edges, from_variant_id=None)
assert len(only_generic) == 1
assert only_generic[0]["to_exercise_id"] == 10
def test_parse_successors_from_edges():
ids, notes, variants = parse_successors_from_edges(
[
{
"to_exercise_id": 20,
"to_exercise_variant_id": 7,
"notes": " leicht ",
},
{"to_exercise_id": 21, "to_exercise_variant_id": None, "notes": ""},
]
)
assert ids == {20, 21}
assert notes[20] == "leicht"
assert variants[20] == 7
assert variants[21] is None
def test_rank_progression_graph_rows_prefers_variant_match():
rows = [
{"id": 1, "variant_match_count": 0, "outgoing_count": 5},
{"id": 2, "variant_match_count": 2, "outgoing_count": 1},
]
best = rank_progression_graph_rows(rows)
assert best["id"] == 2
+11 -2
View File
@@ -1,6 +1,6 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.182"
APP_VERSION = "0.8.183"
BUILD_DATE = "2026-05-23"
DB_SCHEMA_VERSION = "20260531074"
@@ -29,7 +29,7 @@ MODULE_VERSIONS = {
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
"methods": "0.1.0",
"exercises": "2.37.0", # Planungs-KI P1: Szenario-Pipeline + Query-Intent-Overlay
"planning_exercise_suggest": "0.10.0", # Phase B2: Rerank bei engem Top-Feld, auch nach Profil-LLM
"planning_exercise_suggest": "0.11.0", # Phase C1: Graph auto-match + variantenbewusste Nachfolger
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
"training_programs": "0.1.0",
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
@@ -44,6 +44,15 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
{
"version": "0.8.183",
"date": "2026-05-23",
"changes": [
"Planungs-KI Phase C1: Progressionsgraph auto-match vom Anker; variantenbewusste Nachfolger-Kanten (034).",
"Request/Response: anchor_exercise_variant_id, progression_graph_name, suggested_variant_id in Treffern.",
"Frontend Übungsliste: Planungs-KI-Suche im KI-Assistent-Modus; Neuanlage im Dialog statt „+ Neu“.",
],
},
{
"version": "0.8.182",
"date": "2026-05-23",