46 Commits
Author SHA1 Message Date
Lars de86ec0131 Merge pull request 'Migration nach llmnode' (#60) from develop into main
Deploy Production llm-node / deploy (push) Successful in 1m22s
Deploy Production / deploy (push) Successful in 1m4s
Reviewed-on: #60
2026-10-29 15:53:41 +01:00
LarsandClaude Opus 5.5 36d51d4c33 Deploy production to llm-node alongside the Pi.
Deploy Development / deploy (push) Successful in 55s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m46s
Test Suite / pytest-backend (push) Successful in 51s
A separate workflow on the linux_host runner deploys main to llm-node with its own checkout, /etc/shinkan/prod.env and a compose override that mounts the NAS media without creating host paths. Media retention stays off there until it is explicitly enabled, because both installations share the media pool. The deploy only passes when /api/health/ready reports a ready database and complete schema. The Pi workflow keeps its name and label and now aborts on any other host.

Also documents both deployments and the recovery contract with the backup orchestrator.

version: 0.8.246 (backend)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:47:38 +01:00
LarsandCursor ad7c7ad4e5 Keep the dev deploy and the test suite as separate workflows.
Deploy Development / deploy (push) Successful in 59s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 43s
Test Suite / playwright-tests (push) Failing after 7m54s
Test Suite / pytest-backend (push) Successful in 49s
Tests no longer run as jobs inside the development deploy. A push to develop starts the test suite on its own and aims it at the dev stack.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 13:54:42 +01:00
LarsandCursor 5fc839afbc Run develop tests after the dev deploy, never against production by default.
Deploy Dev Stack / deploy (push) Successful in 55s
Deploy Dev Stack / pytest-backend (push) Successful in 50s
Deploy Dev Stack / build-frontend (push) Successful in 17s
Deploy Dev Stack / k6 /health Baseline (push) Successful in 32s
Deploy Dev Stack / lint-backend (push) Successful in 0s
Deploy Dev Stack / playwright-tests (push) Failing after 7m48s
workflow_run uses the workflow file on main and fell through to the prod directory when the triggering name was missing. Dev checks now follow Deploy Dev Stack and target the dev stack explicitly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 13:34:33 +01:00
LarsandCursor d4a193607f Run the dev test suite once, after the deploy.
Deploy Development / deploy (push) Successful in 54s
The compose check looked for docker-compose.yml inside the backend image, where that file is not copied. A push no longer starts a second suite in parallel with the deploy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 11:36:56 +01:00
LarsandCursor 95d365d9fa Schedule media retention at 03:00 Europe/Berlin.
Deploy Development / deploy (push) Successful in 1m1s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 19s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m57s
Test Suite / pytest-backend (push) Failing after 49s
The folded python -c command crashed the cron container before any run. Content-report rate limiting now applies only after the good-faith declaration.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 11:14:37 +01:00
Lars 4e5a7b466f Merge pull request 'Security Update 1' (#59) from develop into main
Deploy Production / deploy (push) Successful in 55s
Reviewed-on: #59
2026-10-13 17:38:10 +02:00
LarsandCursor f10c28e5cd Close medium exposure on reports, registration, uploads, and exercise HTML.
Deploy Development / deploy (push) Successful in 59s
Test Suite / build-frontend (push) Successful in 17s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 7m48s
Test Suite / pytest-backend (push) Failing after 47s
Test Suite / lint-backend (push) Successful in 0s
A superadmin can also turn off another account''s two-factor when the authenticator is lost.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 16:47:57 +02:00
LarsandCursor 5ea225ec6b Show a scannable QR code when setting up two-factor authentication.
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 46s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 5m8s
Test Suite / lint-backend (push) Successful in 1s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 08:15:51 +02:00
LarsandCursor 2e22a7c8e0 Keep recovery codes on screen and make two-factor optional.
Deploy Development / deploy (push) Successful in 51s
Test Suite / pytest-backend (push) Successful in 46s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 4m10s
Test Suite / lint-backend (push) Successful in 0s
Admins can replace missed codes or turn two-factor off without a forced enrollment on every login.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 08:03:05 +02:00
LarsandCursor 32b28a93f3 Harden login, sessions, and media access before the dev deploy.
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 5m43s
Test Suite / lint-backend (push) Successful in 0s
Limit brute-force attempts, require admin TOTP, and keep session tokens out of media URLs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 07:45:53 +02:00
LarsandCursor 6c7c24e887 Add Jinkendo family design principles and entitlement model docs.
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m35s
Test Suite / lint-backend (push) Successful in 1s
Document cross-app architecture patterns, Mitai alignment, and family entitlement standards. Documentation only; no runtime changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 09:12:48 +02:00
Lars 3181cc126d Enhance Planning AI Context with Catalog Exercise Hints
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / lint-backend (push) Successful in 0s
- Introduced support for catalog exercise hints in various functions, including `_build_stage_ai_context`, `try_suggest_ai_stage_step`, and `build_gap_fill_goal_text`, improving the contextual information available for AI suggestions.
- Added a new function `catalog_exercise_hints_block` to consolidate hints retrieval from the catalog context.
- Updated the `PlanningIntentContext` to include catalog exercise hints, ensuring they are part of the API output.
- Implemented tests to verify the inclusion of catalog exercise hints in goal text generation and rematch logic.
- Incremented version numbers and updated changelog to reflect these enhancements.
2026-06-19 12:35:30 +02:00
Lars b719f85c4e Merge pull request 'Progression und additional specific text placeholders' (#58) from develop into main
Deploy Production / deploy (push) Successful in 47s
Reviewed-on: #58
2026-06-18 11:28:45 +02:00
Lars 35fe31774b Update Catalog Prompt Slots Migration and Documentation
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 1s
- Modified migration 092 to clarify the purpose of the catalog prompt slots and removed unnecessary seed data, emphasizing that primary focus data is tenant-specific.
- Updated migration 094 to eliminate the full seed process, reflecting the decision to manage catalog prompt slots content through the admin UI or fallback mechanisms.
- Revised documentation to indicate the absence of migration seeds and the reliance on runtime fallbacks for catalog prompt slots, ensuring clarity for future development.
2026-06-18 11:22:33 +02:00
Lars 90e8f51566 Update Catalog Prompt Slots Router and Access Layer Exemptions
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- Added documentation to the `catalog_prompt_slots.py` file to clarify its role as a global admin catalog requiring authentication and admin role, without tenant context.
- Updated the `check_access_layer_hints.py` script to include `catalog_prompt_slots.py` in the list of exempt routers, ensuring proper access control for admin functionalities.
2026-06-15 15:27:03 +02:00
Lars 7e5ef4561a Refactor Catalog Prompt Slot Management and Enhance Fallback Logic
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function `_resolve_entry_slot_values` to streamline the merging of stored slot values with fallbacks, improving code clarity and maintainability.
- Updated `get_catalog_entry_slots` and `resolve_catalog_prompt_variables` functions to utilize the new fallback logic, enhancing the handling of catalog entries.
- Enhanced the `CatalogPromptSlotsEditor` component to display fallback information for slots, improving user experience in managing catalog prompts.
- Incremented version numbers and updated changelog to reflect the new features and improvements.
2026-06-15 15:18:00 +02:00
Lars 53f2b027cc Enhance Planning Catalog Context and Prompt Slot Management
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new catalog context handling in planning prompt functions, allowing for improved integration of planning variables.
- Added optional catalog context parameters in various functions to streamline the merging of planning prompt variables.
- Updated frontend components to include CatalogPromptSlotsEditor for managing prompt slots across different catalog types.
- Enhanced API utilities to support fetching and updating catalog prompt slots, improving backend functionality for catalog management.
- Incremented version numbers and updated changelog to reflect the new features and improvements.
2026-06-15 12:13:15 +02:00
Lars 9cee862c32 Implement Planning Prompt Enhancements and LLM Usage Tracking
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 49s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m26s
Test Suite / lint-backend (push) Successful in 0s
- Added new fields for goal query, user notes, max steps, and search query in the AiPromptPreviewBody to support planning prompts.
- Integrated planning prompt handling in the preview_ai_prompt function, allowing for distinct processing of planning and exercise prompts.
- Introduced LLM usage tracking in openrouter_chat_completion and planning_exercise_suggest functions to monitor AI call metrics.
- Updated frontend components to accommodate new input fields for planning prompts, enhancing user experience and functionality.
2026-06-15 07:50:49 +02:00
Lars 0b203489f7 Implement Graph Visibility Promotion Logic and Update UI Components
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / lint-backend (push) Successful in 0s
- Added a new function `_graph_promotion_transition` to determine the necessary exercise visibility changes during graph promotions.
- Updated the `list_visibility_promotion_candidates` endpoint to utilize the new promotion logic, ensuring accurate exercise visibility handling.
- Enhanced the frontend components to prompt users for exercise visibility adjustments based on graph visibility changes, improving user experience.
- Introduced tests for the new promotion logic to ensure correctness and reliability in visibility transitions.
2026-06-14 07:30:26 +02:00
Lars 1c67a50ce4 Enhance Exercise Progression Graph Panel with Governance Club Management
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / lint-backend (push) Successful in 0s
- Introduced functionality to manage governance clubs for superadmins, allowing for better club selection and organization within the Exercise Progression Graph Panel.
- Implemented state management for clubs, including sorting and filtering options, to improve user experience and accessibility.
- Enhanced the useEffect hook to fetch governance clubs dynamically, ensuring up-to-date club information is available for selection.
- Updated the club selection dropdown to categorize clubs into "My Clubs" and "Other Clubs," improving clarity and usability for users.
2026-06-14 07:19:35 +02:00
Lars 87d9fa9b65 Enhance Exercise Progression Graph Panel with Club Management Features
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- Added functionality to select and manage clubs within the Exercise Progression Graph Panel, allowing users to assign clubs to exercises.
- Introduced state management for club selection and manual entry, improving user experience for platform admins.
- Updated visibility handling to ensure proper governance and club association during exercise promotion.
- Enhanced error handling to provide clearer feedback when no club is selected, ensuring users are guided to make necessary selections.
2026-06-14 07:10:11 +02:00
Lars 4b9374765b Enhance Progression Graph Management with F15 Features and Evaluation Improvements
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / lint-backend (push) Successful in 0s
- Updated `PROJECT_STATUS.md` to reflect the implementation of F15 features, including the unified slot review and handling of `findings_stale`.
- Enhanced `PROGRESSION_GRAPH_SLOT_EDITOR_SPEC.md` with detailed descriptions of new functionalities related to the match dialog and path quality assessments.
- Introduced new functions in `exercise_progression_graphs.py` to validate exercise visibility against progression graph settings, ensuring proper governance.
- Improved frontend components to support new governance parameters (visibility and club_id) in exercise creation workflows.
- Updated documentation in `HANDOVER.md` and `PLANNING_KI_ROADMAP.md` to outline the latest developments and validation results for the F15 features.
- Enhanced utility functions for exercise creation to incorporate governance settings, improving the overall user experience in the path builder and editor.
2026-06-14 06:44:12 +02:00
Lars b629f192ac Refactor ProgressionSlotCard Key Prop for Improved Stability
Deploy Development / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m39s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
- Updated the key prop in the ProgressionSlotCard component to use a simpler index-based key, enhancing the stability of component rendering during updates.
- This change aims to prevent potential issues with component re-renders and improve overall performance in the ProgressionGraphEditor.
2026-06-13 17:33:36 +02:00
Lars 313d613b7c Enhance Path Quality Assessment and Slot Management Features
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- Added new functions for computing assignment quality scores and counting step assignment statistics, improving the evaluation of steps in path quality assessments.
- Updated existing methods to incorporate the new scoring logic, enhancing the robustness of path evaluations.
- Introduced UI components in the frontend to display detailed quality assessment results, including handling of split dimensions in path evaluations.
- Enhanced tests to cover new functionalities and ensure accuracy in quality scoring and slot management processes.
2026-06-13 17:13:35 +02:00
Lars ea7de64061 Merge pull request 'progression V2' (#57) from develop into main
Deploy Production / deploy (push) Successful in 47s
Reviewed-on: #57
2026-06-13 16:34:09 +02:00
Lars 7265cd5a01 Add findings_stale field to GraphPlanningRoadmapArtifact and update ProgressionGraphEditor for state management
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m34s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `findings_stale` field in `GraphPlanningRoadmapArtifact` to track the freshness of findings.
- Updated `ProgressionGraphEditor` to manage `findingsStale` state across various functions, ensuring accurate representation of evaluation status.
- Modified related utility functions and tests to accommodate the new state, enhancing overall functionality and user feedback in the progression graph management process.
2026-06-13 16:29:17 +02:00
Lars 5e5f4ca8d4 Enhance Progression Findings and Graph Editor with Evaluation Staleness Handling
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Failing after 2s
Test Suite / playwright-tests (push) Successful in 1m19s
Test Suite / lint-backend (push) Successful in 0s
- Added `evaluationStale` state to `ProgressionGraphEditor` and `ProgressionFindingsPanel` to track the freshness of evaluations.
- Updated UI to display a warning when evaluations are stale, prompting users to re-evaluate the graph.
- Modified loading and evaluation functions to manage the `evaluationStale` state effectively, ensuring accurate user feedback during the evaluation process.
- Improved user notifications regarding the need for re-evaluation after changes to the graph.
2026-06-13 16:23:04 +02:00
Lars f0e581a9f5 Implement Off-Topic Slot Gap Specification and Unified Slot Review Enhancements
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m34s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `_build_off_topic_slot_gap_spec` to generate specifications for off-topic slots, improving the handling of filled but thematically inappropriate slots.
- Added `_build_unified_slot_review_entry` to streamline the review process for slots, incorporating various parameters for better evaluation and suggestions.
- Enhanced existing logic in slot management to improve the robustness of path evaluations and user feedback.
- Added tests for the new off-topic slot gap specification to ensure functionality and correctness.
2026-06-13 12:43:59 +02:00
Lars cd457e3ea0 Enhance Slot Evaluation and Scoring Mechanisms
Deploy Development / deploy (push) Successful in 46s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m26s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new functions `_off_topic_semantic_scores_by_slot` and `_score_exercise_stage_fit_for_spec` to improve the evaluation of off-topic steps and exercise stage fit, enhancing the quality assessment process.
- Updated `_run_unified_slot_improvement_review` to incorporate off-topic scores and exercise stage fit scoring, refining the decision-making process for slot suggestions.
- Enhanced existing logic to streamline the handling of slot scores and improve the overall robustness of slot management in path evaluations.
2026-06-13 12:33:16 +02:00
Lars e9bf5bd1a5 Enhance Path Evaluation and Slot Management Features
Deploy Development / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `_parse_slot_refs_from_text` to extract and convert slot references from text, improving the handling of user input in path evaluations.
- Updated `_problematic_slots_from_path_qa` to utilize the new parsing function, enhancing the identification of problematic slots based on various hints and issues.
- Enhanced `ProgressionGraphEditor` and `ProgressionOptimizeCompareModal` to better display identified problem slots and their associated reasons, improving user feedback during evaluations.
- Added tests for new parsing functionality and its integration with existing slot management processes, ensuring robustness in slot reference handling.
2026-06-13 12:17:58 +02:00
Lars 3468b2066e Enhance Path QA and Progression Review Logic
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m27s
Test Suite / lint-backend (push) Successful in 1s
- Introduced `_resolve_hint_major_index` to accurately map hints to major step indices, improving the handling of optimization hints in path evaluations.
- Added `_problematic_slots_from_path_qa` to identify and categorize problematic slots based on baseline QA, enhancing the quality assessment process.
- Updated `_slot_suggestion_accepted` to incorporate new parameters for slot problems and stage specifications, refining the decision-making process for slot suggestions.
- Enhanced `ProgressionGraphEditor` to improve user notifications regarding identified issues and suggestions, ensuring clearer communication of path evaluation results.
- Modified `buildProgressionComparePayload` and `buildUnifiedSlotReviewComparePayload` to support baseline evaluations, streamlining the comparison process for proposed paths.
2026-06-13 10:39:52 +02:00
Lars a1e4ad66df Implement Quick Evaluation and Quality Scoring for Path QA
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / lint-backend (push) Successful in 0s
- Added `_quick_evaluate_steps_qa` function to streamline path quality assessment without recursive API calls, enhancing performance for slot comparisons.
- Introduced `compute_deterministic_path_quality_score` to provide a heuristic quality score based on gaps and off-topic steps, improving evaluation accuracy.
- Updated `_run_unified_slot_improvement_review` to utilize the new quick evaluation method, optimizing the review process and integrating quality scoring.
- Enhanced `build_path_qa_summary` to include quality score calculations, ensuring comprehensive feedback on path evaluations.
- Refactored related functions for improved clarity and efficiency in handling path quality assessments.
2026-06-13 10:27:07 +02:00
Lars 85fccdd093 Enhance Progression Path Comparison and Slot Evaluation Features
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new fields in `ProgressionPathSuggestRequest` for baseline evaluation and incremental scoring, improving the assessment of proposed paths.
- Implemented `_apply_slot_diff_to_steps` and `_score_incremental_slot_diffs` functions to manage slot differences and evaluate their impact on quality scores.
- Updated `ProgressionGraphEditor` to streamline the match comparison flow, integrating new evaluation parameters and improving user notifications.
- Enhanced `ProgressionOptimizeCompareModal` to better display proposed path suggestions, including pro/con evaluations and quality delta metrics.
- Refactored utility functions for clearer handling of slot differences and improved overall data management in the progression graph editor.
2026-06-13 10:11:10 +02:00
Lars 19bbcdaf50 Refactor Progression Comparison Logic and Enhance UI Components
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m19s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new utility functions for comparing slot differences, including `compareDiffKind`, `annotateCompareDiffKinds`, and various filtering functions to streamline the comparison process.
- Updated `ProgressionGraphEditor` to utilize the new comparison logic, improving the handling of slot differences and user notifications.
- Enhanced `ProgressionOptimizeCompareModal` to better manage proposed path suggestions, including clearer messaging and improved selection handling for optional replacements.
- Adjusted frontend components to reflect changes in comparison logic, ensuring a more intuitive user experience in managing progression paths.
2026-06-13 09:02:15 +02:00
Lars cec96ae473 Implement Progression Comparison Logic and Refactor Fetching Methods
Deploy Development / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `buildProgressionComparePayload` to create a structured comparison response from baseline and proposed evaluation results, enhancing clarity in slot differences.
- Refactored `fetchMatchCompare` to `fetchFullMatch` for improved clarity and functionality in fetching progression paths.
- Updated `runMatchCompareFlow` to streamline the evaluation process, integrating baseline and match results for a comprehensive comparison.
- Enhanced utility functions for managing slot differences and gap fill offers, improving overall data handling in the progression graph editor.
- Adjusted frontend components to reflect these changes, ensuring a more intuitive user experience in managing progression paths.
2026-06-13 08:46:10 +02:00
Lars 53f1c7161f Refactor AI Gap Fill and Progression Path Evaluation Logic
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
- Removed the `try_suggest_ai_stage_step` function from `_enrich_roadmap_unfilled_gap_offers`, simplifying the gap fill offer generation process.
- Updated `_run_evaluate_only_path_qa` and `suggest_progression_path` to disable AI calls and proposals, enhancing control over evaluation parameters.
- Adjusted `ProgressionGraphEditor` to reflect changes in API requests, ensuring consistent handling of evaluation data.
- Added a new test to validate the behavior of proposed QA when no slot differences are present, improving test coverage for comparison logic.
2026-06-13 08:43:02 +02:00
Lars 89c6780294 Enhance AI Gap Fill Logic and Progression Path Handling
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 1s
- Integrated `try_suggest_ai_stage_step` to suggest AI-generated gap fill steps based on user input, improving the automation of the planning process.
- Updated `_enrich_roadmap_unfilled_gap_offers` to conditionally include AI gap fill proposals, enhancing the offer generation logic.
- Implemented `_merge_gap_fill_offers_from_steps` to consolidate gap fill offers from various steps, ensuring a comprehensive list of available offers.
- Modified `ProgressionGraphEditor` to utilize the new merging logic for gap fill offers, improving the user experience in managing offers.
- Enhanced utility functions to streamline the collection and filtering of gap fill offers from API responses.
- Bumped version to reflect the new features and improvements.
2026-06-13 08:36:53 +02:00
Lars 3f130aa8ad Refactor Progression Path Evaluation and Comparison Logic
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / lint-backend (push) Successful in 1s
- Updated `suggest_progression_path` to utilize `evaluate_steps` for improved validation, ensuring at least one evaluation step is provided.
- Modified frontend components to enhance user experience in the comparison process, including clearer messaging and improved dialog handling.
- Adjusted `ProgressionGraphEditor` to streamline the comparison flow and integrate new evaluation parameters.
- Enhanced `ProgressionOptimizeCompareModal` to reflect changes in comparison logic, allowing for better user interaction with proposed path suggestions.
- Bumped version to reflect the new features and improvements.
2026-06-13 08:17:59 +02:00
Lars 69ce3f6975 Enhance Rematch Suggestion Logic and Progression Path Evaluation
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `_baseline_slot_accepts_rematch_suggestion` to filter out filled or invalid slots from rematch suggestions, improving the accuracy of rematch logic.
- Updated `_build_rematch_suggestion_diffs` to skip non-eligible baseline slots, streamlining the rematch suggestion process.
- Added `_evaluate_steps_for_compare_qa` to evaluate steps against the current state, enhancing the quality assessment during progression path suggestions.
- Modified `_build_progression_compare_response` to ensure proper handling of slot differences and quality scores, improving response clarity.
- Updated frontend components to reflect changes in rematch handling and evaluation logic.
- Bumped version to reflect the new features and improvements.
2026-06-13 08:02:44 +02:00
Lars dccb065181 Enhance Slot Difference Annotation and Rematch Suggestion Logic
Deploy Development / deploy (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `_annotate_slot_diffs` to mark trivial ID swaps in slot differences, improving clarity in comparison results.
- Added `_actionable_slot_diffs` to filter out non-actionable differences, streamlining the evaluation process.
- Implemented `_build_rematch_suggestion_diffs` to generate suggestions based on rematch logs, enhancing the path optimization workflow.
- Updated `_build_progression_compare_response` to incorporate actionable slot differences and rematch suggestions, improving the response structure.
- Enhanced frontend components to display rematch suggestions and handle trivial differences more effectively.
- Bumped version to reflect the new features and improvements.
2026-06-13 07:55:47 +02:00
Lars e828a5da32 Enhance Progression Path Evaluation and Comparison Logic
Deploy Development / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m23s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `_steps_to_evaluate_payloads` to convert path steps into evaluation payloads for improved quality assessments.
- Updated `_build_progression_compare_response` to include a new `proposed_eval` parameter, allowing for fair quality assessment comparisons.
- Enhanced `ProgressionGraphEditor` to utilize the new pipeline quality assessment data.
- Modified `ProgressionOptimizeCompareModal` to display detailed comparison results, including handling of trivial slot differences and optimization hints.
- Bumped version to reflect the new features and improvements.
2026-06-13 07:44:01 +02:00
Lars 5bca5ef9eb Enhance Progression Path Evaluation and Optimization Features
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / lint-backend (push) Successful in 0s
- Updated `suggest_progression_path` to include additional evaluation parameters, allowing for more comprehensive path assessments.
- Introduced `PathQaPipelineDetails` component to display detailed quality assessment metrics, including rematch and refine logs, in the frontend.
- Enhanced `ProgressionGraphEditor` to manage proposed path evaluations and integrate quality assessment results into the draft workflow.
- Improved `ProgressionOptimizeCompareModal` to present optimization hints and quality tier information for proposed paths.
- Bumped version to reflect the new features and improvements.
2026-06-12 13:33:36 +02:00
Lars 5ed06002d9 Implement Comparison Logic for Progression Path Suggestions
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / lint-backend (push) Successful in 0s
- Added `compare_with_assignments` flag to `ProgressionPathSuggestRequest` to enable comparison of proposed paths with existing slot assignments.
- Introduced `_assignment_preservation_active` function to determine if existing assignments should be preserved during path suggestions.
- Enhanced `suggest_progression_path` to handle comparison logic, including validation for minimum slot assignments required for comparison.
- Implemented `_build_progression_compare_response` to structure the response for comparison results, including slot differences and quality scores.
- Updated frontend components to support new comparison features, including handling of slot assignments and optimization comparisons.
- Bumped version to reflect the new features and improvements.
2026-06-12 13:22:04 +02:00
Lars b8f65e04c5 Enhance Rematch Logic and Slot Filtering in Planning Path
Deploy Development / deploy (push) Successful in 41s
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 (push) Successful in 45s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `filter_rematch_slot_indices` to exclude preserved slots from rematching, improving the accuracy of slot assignments.
- Added `_slot_priority_for_rematch` to prioritize existing slot assignments during rematching, enhancing the robustness of the rematch process.
- Updated `_run_roadmap_rematch_loop` to utilize the new filtering and prioritization logic, ensuring better handling of rematch scenarios.
- Enhanced tests in `test_planning_path_rematch.py` to validate the new filtering behavior and ensure correct exercise restoration when not rejected.
- Bumped version to reflect the new features and improvements.
2026-06-12 12:33:00 +02:00
Lars f3710ac0a1 Enhance Planning Catalog Context Integration in Progression Path
Deploy Development / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
- Updated `PROJECT_STATUS.md` to reflect the addition of the Planning AI Progression Graph and its context in the roadmap.
- Enhanced `DOMAIN_MODEL.md` with details on the new `planning_catalog_context` features, allowing trainers to manage curriculum stages and context.
- Added tests in `test_planning_catalog_context.py` to validate the separation of LLM highlights from fix hints during QA processes.
- Updated `HANDOVER.md` and `PLANNING_KI_ROADMAP.md` to reflect the latest app version and improvements in the planning context.
- Enhanced frontend components to support the new planning catalog context, including updates to `ExerciseProgressionPathBuilder` and `ProgressionGraphEditor`.
- Bumped version to 0.8.233 to reflect the new features and improvements.
2026-06-12 12:25:52 +02:00
132 changed files with 13637 additions and 760 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent). **Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**. **Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**. **Planungs-KI Progressionsgraph** (Roadmap-first, Auto-Optimierung, Katalog-Kontext **0.8.233**, **F15** Match-Dialog + getrennte Pfad-QS lokal): Ist-Doku **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`**, Handover **`docs/HANDOVER.md`** §2.8.
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md) **Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
+2
View File
@@ -465,6 +465,8 @@ skill_level_definitions (
**Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4. **Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4.
**KI-Planung (Workbench, Stand 0.8.233):** Am Graph können Trainer neben Kanten ein **`planning_roadmap`**-Artefakt (Curriculum-Stufen) und **`planning_catalog_context`** (Primärfokus, Stilrichtung, Trainingsstil, Zielgruppe aus den Katalog-Dimensionen §1) pflegen. Die Roadmap-first-Pipeline matcht Übungen pro Stufe; Didaktik und Reihenfolge kommen aus Roadmap + QS, nicht aus Technik-Hardcoding. **Geplant (H1):** Katalog-Dimensionen zusätzlich als **Prompt-Snippets** in LLM-Aufrufen (Priorität Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung) — **`docs/architecture/PLANNING_CATALOG_PROMPT_SNIPPETS.md`**. Technische Details: **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`**. Für **Trainingsplanung** (Einheit, Abschnitt, Rahmen-Slot) gelten dieselben Katalog- und Retrieval-Bausteine mit anderen Scopes — Phase G, siehe Roadmap **`PLANNING_KI_ROADMAP.md`**.
### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009) ### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009)
**Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**). **Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**).
@@ -0,0 +1,9 @@
# Designprinzipien — verschoben
Die **Jinkendo-Produktfamilie Designprinzipien** (Index + Shinkan-Serie) liegen nicht mehr hier.
**Neuer Standort (Shinkan-Serie):** [docs/jinkendo-family/design-principles/DESIGN_PRINCIPLES_INDEX.md](../../../docs/jinkendo-family/design-principles/DESIGN_PRINCIPLES_INDEX.md)
**Mitai-Serie:** [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md)
**Abgleich:** [docs/jinkendo-family/DESIGN_PRINCIPLES_ALIGNMENT.md](../../../docs/jinkendo-family/DESIGN_PRINCIPLES_ALIGNMENT.md)
@@ -0,0 +1,86 @@
# Produktions-Deployments (Raspberry Pi + llm-node)
Stand: 2026-10-29
Zwei unabhängige Prod-Deployments laufen parallel. Beide starten bei jedem Push auf `main`, jeweils als eigener Workflow-Lauf auf eigenem Runner. Ein Fehler im einen blockiert das andere nicht.
Backup, Recovery und Erstbefüllung der llm-node-DB: `RECOVERY_CONTRACT.md`.
| | Raspberry Pi (alt) | llm-node (neu) |
|---|---|---|
| Workflow | `.gitea/workflows/deploy-prod.yml` | `.gitea/workflows/deploy-prod-llm-node.yml` |
| Workflow-Name | `Deploy Production` | `Deploy Production llm-node` |
| Host | 192.168.2.49, `raspberrypi5`, aarch64 | 192.168.2.144, `llm-node`, x86_64 |
| Runner | `Raspi5-Paperless`, Label `ubuntu-latest` (Host-Modus) | `llm-node-runner`, Label `linux_host` (Host-Modus) |
| Deploy-Verzeichnis | `/home/lars/docker/shinkan` | `/home/llmadmin/docker/shinkan-prod` |
| Compose | `docker-compose.yml`, Projekt `shinkan` (Verzeichnisname) | `docker-compose.yml` + `docker-compose.llm-node.yml`, Projekt `shinkan-prod` |
| Konfiguration | `/home/lars/docker/shinkan/.env` | `/etc/shinkan/prod.env` (Workflow-Variable `ENV_FILE`) |
| Datenbank | Volume `shinkan_shinkan-db-data` auf dem Pi | Volume `shinkan-prod_shinkan-db-data` auf llm-node |
| Medien (Host) | `SHINKAN_MEDIA_HOST` laut Pi-`.env` | `/srv/shinkan/prod/media` (NFSv4 von `192.168.2.63:/volume1/shinkan-media/prod`) |
| Medien (Container) | `/app/media` | `/app/media` |
| Medienbereinigung | `retention-cron` läuft immer mit | aus; nur mit `MEDIA_RETENTION: enabled` |
| Ports | 3003, 127.0.0.1:8003, 127.0.0.1:5434 | 3003, 127.0.0.1:8003, 127.0.0.1:5434 |
| Manuell auslösen | nur per Push auf `main` | Push auf `main` oder Gitea „Run workflow“ (`workflow_dispatch`) |
Die Runner-Labels sind am 2026-10-29 aus den `.runner`-Dateien beider Hosts abgelesen worden (act_runner v0.2.11). Jeder Workflow prüft im ersten Schritt Hostname und Architektur und bricht auf einem fremden Runner ab. Wer Labels an einem Runner ändert, muss beide Workflows mitprüfen; `ubuntu-latest` darf nicht auf llm-node, `linux_host` nicht auf dem Pi registriert werden.
Das llm-node-Deployment braucht vom Pi nichts: Code kommt aus dem Gitea auf llm-node selbst, DB und Konfiguration liegen lokal, Medien direkt auf dem NAS.
## Server-Voraussetzungen auf llm-node
Außerhalb des Repos eingerichtet und nicht Teil des Workflows:
- `/etc/shinkan/prod.env`, lesbar für `llmadmin` (Runner-User), Pflicht: `DB_PASSWORD`. `SHINKAN_MEDIA_HOST` und `MEDIA_ROOT` sind optional; wenn gesetzt, müssen sie `/srv/shinkan/prod/media` bzw. `/app/media` sein. `COMPOSE_PROFILES` darf dort nicht stehen.
- NFS-Mount `/srv/shinkan/prod/media`, dauerhaft und beim Boot abgesichert. Erreichbarkeit und Monitoring des NAS liegen beim Server, nicht im Deployment.
- `/home/llmadmin/docker/shinkan-prod`; das Git-Checkout legt der Workflow beim ersten Lauf selbst an.
## docker-compose.llm-node.yml
Override nur für llm-node; Pi und Dev nutzen ihn nicht. Alle Compose-Aufrufe im Workflow (build, up, rm, ps, logs) laufen als
```bash
docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.yml --env-file /etc/shinkan/prod.env ...
```
- Ersetzt den Medien-Mount von `backend` und `retention-cron` durch einen Bind-Mount `/srv/shinkan/prod/media` → `/app/media` mit `create_host_path: false`. Ist der Mount nicht da, startet der Container nicht, statt Medien auf die lokale Platte zu schreiben.
- Hängt `retention-cron` an das Profil `media-retention`. Ohne Profil wird der Dienst weder gebaut noch gestartet.
## Ablauf je Lauf (llm-node)
1. Runner-Guard (`llm-node`/`x86_64`)
2. `ENV_FILE` prüfen: lesbar, `DB_PASSWORD` gesetzt, kein `COMPOSE_PROFILES`, Medienwerte passend. Es werden keine Werte ausgegeben.
3. `git fetch origin main` + `git reset --hard origin/main` im Deploy-Verzeichnis
4. `build --no-cache` und `up -d --remove-orphans`. Bei `MEDIA_RETENTION: disabled` wird ein noch vorhandener `retention-cron` entfernt.
5. Healthchecks mit Wiederholung (bis ca. 3 min je Prüfung):
- `127.0.0.1:8003/api/version`
- `127.0.0.1:8003/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true` (HTTP 200 allein reicht nicht)
- `127.0.0.1:3003/api/version` und `127.0.0.1:3003/api/health/ready` (gleiche Bedingung, über Frontend-Nginx)
- `127.0.0.1:3003/`
Bei Fehler: `compose ps` und Backend-Logs, Lauf rot.
## Medienbereinigung auf llm-node aktivieren
Pi und llm-node nutzen denselben Medienbestand, aber getrennte Datenbanken. Eine Bereinigung auf einer Seite kann Dateien löschen, die die andere Datenbank noch referenziert. Deshalb ist `retention-cron` auf llm-node aus.
Aktivieren erst, wenn nur noch eine Datenbank den Bestand führt (Pi-Bereinigung abgeschaltet bzw. Cutover erfolgt):
1. In `deploy-prod-llm-node.yml` `MEDIA_RETENTION: disabled` auf `enabled` setzen.
2. Über `develop` → `main` ausrollen. Der Lauf baut und startet `retention-cron` mit Profil `media-retention`.
Die Bereinigungslogik selbst (`backend/scripts/media_retention_scheduler.py`, täglich 03:00 Europe/Berlin, kein Löschen beim Start) ist dieselbe wie auf dem Pi.
## Altes Deployment (Pi) abschalten
Nur den Workflow abschalten, nicht den Pi-Runner: der Runner bedient auch `Deploy Development` und `Test Suite`.
Eine der beiden Varianten:
- **Gitea-UI (ohne Commit):** Repository → Actions → `Deploy Production` → „Disable workflow“. Rückgängig über „Enable workflow“.
- **Im Repo:** `.gitea/workflows/deploy-prod.yml` löschen oder den Trigger auf `on: workflow_dispatch` reduzieren und über `develop` → `main` ausrollen.
Folgen:
- `deploy-prod-llm-node.yml` ist davon unberührt.
- `test.yml` startet seine Prod-Prüfungen per `workflow_run` nach `Deploy Production`. Diese Prüfungen laufen gegen das Pi-Verzeichnis und entfallen mit dem Abschalten. Sie sind nicht auf llm-node umgestellt.
- Die Pi-Container laufen weiter, einschließlich der Pi-Medienbereinigung, bis sie dort mit `docker compose down` gestoppt werden.
+200
View File
@@ -0,0 +1,200 @@
# Shinkan Backup & Recovery – Schnittstelle zum Backup-Orchestrator
Stand: 2026-10-29 · Status: **Entwurf zur Abstimmung, nichts umgesetzt**
Dieses Dokument legt fest, wie der Backup-Orchestrator (`pi-backup-orchestrator`, eigenes Projekt) und Shinkan bei Backup, Wiederherstellung und Restore-Test zusammenarbeiten. Es richtet sich an den Orchestrator-Agenten und an die Umsetzung der Shinkan-Skripte.
Grundsatz: **Der Orchestrator weiß, wann und wohin gesichert wird. Shinkan weiß, wie die eigene Datenbank sicher eingespielt und geprüft wird.** Der Orchestrator ruft Shinkan-Skripte auf und wertet Exit-Code und JSON aus. Shinkan-Interna (Migrationen, Sessions, Medienpfade, Healthchecks) stehen nicht im Orchestrator.
Verwandt: `PROD_DEPLOYMENTS.md` (Deployments Pi + llm-node), `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Medien-Lifecycle).
---
## 1. Ist-Stand (geprüft am 2026-10-29, nur lesend)
| Punkt | Stand |
|---|---|
| Orchestrator | `pi-backup-orchestrator` v0.3 auf dem Pi, Timer `backup-orchestrator-daily` täglich 05:30, Job `shinkan-prod-db` (Phase 10, kritisch), danach `nas-data` (Phase 20) |
| Dump | `pg_dump` im Container `shinkan-db-prod`, **Plain SQL**, PostgreSQL 16.12, ca. 1,2 MB, 94 Tabellen |
| Ablage | `/media/lars/paperless/db-backup/shinkan-prod.sql` auf der **lokalen NVMe** des Pi, fester Dateiname (bis 2026-10-28 mit Zeitstempel); auf das NAS über `nas-data` |
| Migrationen | Tabelle `schema_migrations(id, migration, executed_at)`; `migration` = Dateiname ohne `.sql`, z. B. `096_login_lockout_and_totp`. Maßgeblich ist `backend/run_migrations.py` (läuft beim Backend-Start). Die Variante in `db_init.py` (Spalte `filename`) wird beim Start nicht genutzt. |
| Medien | Gemeinsamer Bestand auf dem NAS (`192.168.2.63:/volume1/shinkan-media/prod`), im Container `/app/media`. `media_assets.storage_key` relativ (`library/…`) mit `sha256` und `byte_size`; ältere `exercise_media.file_path` als `/media/<storage_key>` |
| Ziel-Prod | llm-node, Compose-Projekt `shinkan-prod`, `docker-compose.yml` + `docker-compose.llm-node.yml`, Konfiguration `/etc/shinkan/prod.env`, Container `shinkan-db-prod` (Postgres nur `127.0.0.1:5434`) |
## 2. Begriffe
- **Backup-Satz:** Dump + Prüfsumme + Backup-Manifest + Medien-Manifest, alle mit demselben Zeitstempel. Nur ein vollständiger Satz gilt als Backup.
- **Ziel (target):** benannte, fest im Skript hinterlegte Umgebung. Kein freies Zusammenbauen von Pfaden über Parameter.
| target | Host | Zweck | Schreibt in DB |
|---|---|---|---|
| `pi-prod` | raspberrypi5 | Manifest zum bestehenden Pi-Dump | nein (nur lesend) |
| `llm-prod` | llm-node | Manifest, Recovery, Erstbefüllung | ja, nur `restore` |
| `llm-restoretest` | llm-node | Restore-Test, wird danach entfernt | ja, nur eigene Wegwerf-DB |
Jedes Skript prüft wie die Workflows Hostname und Architektur und bricht auf einem fremden Host ab. Restore auf `pi-prod` gibt es nicht.
## 3. Schnittstelle
Alle Skripte liegen im Shinkan-Repo unter `scripts/ops/` und laufen auf dem Host der Zielumgebung, aus dem jeweiligen Deploy-Checkout. Die Code-Version, gegen die geprüft wird, ist damit immer die dort deployte.
Gemeinsam für alle Befehle:
- Ergebnis als JSON in die Datei `--result <pfad>` (Orchestrator legt den Pfad fest, z. B. im Run-Log-Verzeichnis). Auf stdout nur menschenlesbares Log.
- Keine Secrets, keine Dump-Inhalte, keine personenbezogenen Daten in Log oder JSON. Tabellennamen, Zeilenzahlen, Dateipfade im Medienbestand und Versionsangaben sind erlaubt.
- Exit-Codes:
| Code | Bedeutung |
|---|---|
| 0 | erfolgreich |
| 1 | Fehler während der Ausführung (Details im JSON) |
| 2 | Aufruf oder Vorbedingung falsch (falscher Host, fehlende Datei, fehlende Bestätigung) |
| 3 | Dump passt nicht zum Code (enthält Migrationen, die der Code nicht kennt) |
| 4 | Prüfsumme stimmt nicht |
| 5 | Wiederherstellung durchgeführt, Prüfung danach fehlgeschlagen (Rollback ausgeführt bzw. im JSON beschrieben) |
### 3.1 `shinkan-backup-manifest`
Aufruf direkt nach dem Dump, im selben Orchestrator-Job.
```
shinkan-backup-manifest --target pi-prod|llm-prod --dump <datei> --out-dir <verzeichnis> --result <json>
```
Schreibt neben den Dump:
- `<dump>.sha256`
- `<dump>.manifest.json`:
- `created_at`, `host`, `target`
- `app_version` (aus `/api/version`), `git_commit` (Deploy-Checkout)
- `migrations`: Liste aus `schema_migrations.migration`, `last_migration`
- `dump_format` (`plain` | `custom`), `dump_bytes`, `dump_sha256`
- `row_counts` je Tabelle, nur informativ (eigener Lesezugriff, nicht derselbe Snapshot wie der Dump)
- `media_manifest` (Dateiname + sha256)
- `<dump>.media.jsonl`, eine Zeile je Datei im Medienbestand: `path` (relativ zu `/app/media`), `size`, `mtime`. `sha256` nur für neue oder geänderte Dateien (Cache über `path`+`size`+`mtime`), damit der Lauf bei wachsendem Bestand kurz bleibt.
Der Manifest-Job liest nur; ein Fehler darin macht den Backup-Satz unvollständig, aber nicht den Dump ungültig. Empfehlung: Job unkritisch, Kuma-Meldung eigener Monitor.
### 3.2 `shinkan-restore`
```
shinkan-restore --target llm-prod|llm-restoretest --dump <datei> --result <json>
[--confirm <db>@<host>] [--allow-overwrite] [--sessions clear|keep]
```
- `--confirm shinkan@llm-node` ist bei `llm-prod` Pflicht.
- `--allow-overwrite` ist Pflicht, wenn die Ziel-DB echte Daten hat (mindestens ein Eintrag in `profiles`). Eine frisch migrierte DB ohne Profile gilt als leer.
- `--sessions`: Default `clear`. `keep` nur bei Recovery desselben Systems nach einem Crash, wenn angemeldete Nutzer angemeldet bleiben sollen.
Ablauf (verbindlich):
1. **Vorbedingungen:** Host-Guard, Dump lesbar, `<dump>.sha256` vorhanden und passend (sonst Exit 4), Zielkonfiguration vorhanden.
2. **In eine Staging-DB einspielen,** nicht direkt in die Live-DB: `shinkan_restore_<zeitstempel>` im laufenden Postgres-Container anlegen und den Dump in **einer Transaktion** einspielen, bei Fehler Abbruch ohne Teilstand.
- Plain SQL: `psql -v ON_ERROR_STOP=1 --single-transaction`
- Custom-Format (`PGDMP`-Kopf): `pg_restore --single-transaction --exit-on-error --no-owner --no-acl`
3. **Migrationsabgleich in der Staging-DB:** Jeder Eintrag in `schema_migrations.migration` muss als `backend/migrations/<eintrag>.sql` im deployten Code existieren. Sonst ist der Dump neuer als der Code → Staging-DB löschen, Exit 3. Fehlende Einträge (Dump älter als Code) sind normal; sie werden beim Backend-Start nachgezogen.
4. **Plausibilität in der Staging-DB:** Pflichttabellen wie im Ready-Check vorhanden; `profiles`, `skills` nicht leer. Abweichung der Zeilenzahlen zum Manifest nur als Hinweis im JSON.
5. **Sessions:** bei `clear` `TRUNCATE sessions` in der Staging-DB.
6. **Umschalten:**
- Backend, Frontend und `retention-cron` stoppen (Compose `stop`, Postgres läuft weiter).
- Live-DB umbenennen: `shinkan` → `shinkan_before_<zeitstempel>`.
- Staging-DB umbenennen: `shinkan_restore_<zeitstempel>` → `shinkan`.
- Backend und Frontend starten; `retention-cron` nur, wenn es im Deployment aktiviert ist (llm-node: `MEDIA_RETENTION`).
7. **Prüfen:** dieselben Healthchecks wie im Deploy-Workflow, insbesondere `/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true`.
8. **Bei Fehler in 6–7:** Dienste stoppen, Umbenennung rückgängig machen (`shinkan_before_<zeitstempel>` → `shinkan`), Dienste starten, erneut prüfen. Exit 5 mit beiden Ergebnissen im JSON.
9. **Aufräumen:** `shinkan_before_<zeitstempel>` bleibt stehen, bis jemand sie ausdrücklich löscht (eigener Befehl `--drop-previous <name>` oder manuell). Kein automatisches Löschen.
Ergebnis-JSON u. a.: `dump_sha256`, `dump_last_migration`, `code_last_migration`, `migrations_applied_on_start`, `sessions`, `previous_db`, `health`, `duration_seconds`.
### 3.3 `shinkan-restore-test`
```
shinkan-restore-test --dump <datei> --result <json> [--playwright] [--keep]
```
Baut eine Wegwerf-Umgebung auf llm-node, spielt den Dump mit `shinkan-restore --target llm-restoretest` ein, prüft und räumt auf.
- **Eigenes Compose-Projekt** `shinkan-restoretest` mit **eigener Compose-Datei ohne `container_name`**. Die Basisdatei setzt feste Namen (`shinkan-db-prod` …) und kollidiert sonst mit Prod auf demselben Host.
- **Ports:** Frontend und Backend nur auf `127.0.0.1`, Postgres ohne veröffentlichten Port. Konkrete Ports vor Umsetzung auf llm-node prüfen.
- **Medien nur lesend:** `/srv/shinkan/prod/media:/app/media:ro`. Der Medienbestand ist gemeinsam; ein Test darf dort nichts schreiben oder löschen.
- **Aus:** `retention-cron`, SMTP (Variablen leer), `AUTO_ADMIN_FIRST_USER`, `ADMIN_BOOTSTRAP_EMAILS`, OpenRouter.
- **Prüfungen:** Ready-Check, Plausibilität wie 3.2, Medien-Abgleich (3.4) gegen den aktuellen Bestand.
- **`--playwright`:** lesende Smoke-Tests gegen `PLAYWRIGHT_BASE_URL` der Testumgebung. Tests, die hochladen oder Medien ändern, müssen ausgeschlossen werden (schreibgeschützter Mount). Testzugang über einen eigens im Test angelegten Nutzer, nicht über echte Nutzerkonten.
- **Ende:** `docker compose -p shinkan-restoretest down -v`, außer bei `--keep` (zur Fehlersuche).
Empfohlener Takt: wöchentlich mit dem jüngsten Backup-Satz, zusätzlich nach Änderungen an Dump-Format oder Migrationsrunner.
### 3.4 `shinkan-media-diff`
```
shinkan-media-diff --target llm-prod|llm-restoretest --result <json> [--manifest <dump>.media.jsonl]
```
Vergleicht die Medienverweise der (wiederhergestellten) DB mit dem aktuellen Medienbestand. Löscht und ändert nichts.
Kategorien im Ergebnis:
| Kategorie | Bedeutung | Folge |
|---|---|---|
| `missing` | in `media_assets` / `exercise_media` referenziert, Datei fehlt | reparieren oder Eintrag bereinigen |
| `mismatch` | Datei vorhanden, `byte_size` oder `sha256` passt nicht | prüfen |
| `added_after_backup` | Datei vorhanden, nicht referenziert, nicht im Medien-Manifest des Backups | Upload nach dem Backup; DB-Eintrag ging mit dem Restore verloren → Kandidat für Nachpflege |
| `orphan` | Datei vorhanden, nicht referenziert, bereits im Manifest | Kandidat zum Aufräumen |
Solange Pi und llm-node denselben Bestand mit getrennten Datenbanken nutzen, gehören `orphan` und `added_after_backup` teilweise zur anderen Installation. **Keine automatische Bereinigung** auf Basis dieses Berichts.
Der Bericht enthält immer das Versions-Tripel: App-Version und Commit des Ziels, letzte Migration der DB, Medien-Manifest des Backups.
## 4. Zuständigkeiten
| Aufgabe | Orchestrator | Shinkan |
|---|---|---|
| Zeitplan (täglich, später 2-stündlich) | ✓ | |
| Dump erzeugen (`pg_dump` im Container) | ✓ | |
| Manifest erzeugen | ruft auf | `shinkan-backup-manifest` |
| Ablage, Generationen, Kopie auf NAS | ✓ | |
| Meldungen (Kuma, Webhooks) | ✓ | liefert Exit-Code + JSON |
| Restore-Test planen | ✓ | `shinkan-restore-test` |
| Recovery auslösen | manuell über Orchestrator-CLI | `shinkan-restore` |
| Medienabgleich | ruft nach Restore auf | `shinkan-media-diff` |
| Installation auf llm-node | ✓ | |
## 5. Anforderungen an den Orchestrator
1. **Generationen auf dem NAS.** Mit festem Dateinamen gibt es lokal nur einen Stand. Auf dem NAS müssen mehrere Backup-Sätze erhalten bleiben. Vorschlag: 2-stündliche Sätze 2 Tage, tägliche 30 Tage, monatliche 12 Monate. Ein Satz wird erst überschrieben bzw. rotiert, wenn der neue vollständig ist (Dump + `.sha256` + Manifest).
2. **Atomar schreiben:** Dump erst in eine temporäre Datei, nach Erfolg umbenennen. Ein abgebrochener Dump darf den letzten guten nicht ersetzen.
3. **Dump-Format:** Plain SQL funktioniert. Empfohlen für die Zukunft: `pg_dump -Fc` (kleiner, Inhaltsverzeichnis mit `pg_restore --list`, gezielte Teil-Restores). `shinkan-restore` erkennt beide Formate.
4. **llm-node:** Eigene Orchestrator-Instanz auf llm-node für `shinkan-prod` (`docker exec shinkan-db-prod pg_dump …`). Postgres ist dort nur lokal erreichbar; Fern-Dumps vom Pi sind nicht vorgesehen.
5. **Bis zum Cutover** laufen beide Sicherungen: Pi für das alte Prod, llm-node für das neue. Ablage getrennt (`shinkan-prod-pi/`, `shinkan-prod-llm/`), damit Sätze nicht verwechselt werden.
6. **Takt für externe Kunden:** Vollständige Dumps alle 2 Stunden sind bei der aktuellen Größe unproblematisch und jeder Satz ist eigenständig einspielbar. Ein „Diff zum ersten Dump des Tages“ ist mit `pg_dump` nicht möglich; ein Textvergleich von SQL-Dumps ist kein verlässliches Backup. Für Datenverlust im Minutenbereich ist der Weg WAL-Archivierung mit Basis-Backup (z. B. pgBackRest oder WAL-G, Point-in-Time-Recovery). Das ändert die Postgres-Konfiguration und ist ein eigenes Vorhaben.
## 6. Erstbefüllung llm-node (einmalig)
Nutzt bewusst denselben Weg wie die Recovery; die Erstbefüllung ist damit der erste echte Recovery-Test.
1. Deploy-Workflow `Deploy Production llm-node` ist mindestens einmal erfolgreich gelaufen (DB frisch migriert, keine Profile).
2. Jüngsten Pi-Backup-Satz (`shinkan-prod.sql` + `.sha256` + Manifest) nach llm-node kopieren, Ablage `/var/lib/shinkan/restore/` (Verzeichnis 700, Dateien 600, Eigentümer `llmadmin`).
3. Optional vorher `shinkan-restore-test` mit diesem Satz.
4. `shinkan-restore --target llm-prod --dump … --confirm shinkan@llm-node --sessions clear` (ohne `--allow-overwrite`, da die DB als leer gilt).
5. `shinkan-media-diff --target llm-prod` und Bericht ansehen.
6. Fachliche Stichprobe (Login, Übungen, Medien).
Vor Schritt 4 klären: SMTP in `/etc/shinkan/prod.env` für die Testphase aus oder bewusst an (echte Nutzerdaten → echte Mails möglich).
Für den Cutover wird Schritt 2–6 mit Schreibstopp auf dem Pi wiederholt (Pi-Backend stoppen, Dump, Restore mit `--allow-overwrite`).
## 7. Sicherheit und Datenschutz
- Dumps enthalten E-Mail-Adressen, Passwort-Hashes und TOTP-Geheimnisse. Ablage nur mit Rechten 600/640, Transport nur im LAN per SSH, nie ins Repo, nie in Webhooks, Logs oder Kuma-Nachrichten.
- Skripte geben keine Umgebungsvariablen aus und lesen Zugangsdaten nur aus der Zielkonfiguration bzw. dem Container.
- Auf dem Pi-Prod nur lesende Zugriffe (Manifest). Kein Restore auf dem Pi.
- Restore-Test nie mit beschreibbarem Medien-Mount, nie mit aktivem SMTP.
## 8. Offene Entscheidungen
1. Dump-Format künftig `-Fc` oder weiter Plain SQL?
2. Aufbewahrung der Generationen (Vorschlag in 5.1) und ob das NAS zusätzlich Snapshots führt.
3. Ports und Takt des Restore-Tests; welche Playwright-Tests als lesender Smoke-Satz gelten.
4. Default `--sessions` bei Crash-Recovery (`clear` sicherer, `keep` bequemer).
5. Zeitpunkt für WAL-Archivierung/PITR (spätestens mit dem ersten externen Kunden mit Zusage zur Verfügbarkeit).
6. Wiederherstellung einzelner Vereine bei mehreren Kunden: mit beiden Verfahren nicht direkt möglich; bei Bedarf eigenes Export/Import-Konzept je Mandant.
@@ -7,6 +7,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht | | profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht |
| profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin | | profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin |
| profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft | | profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft |
| profiles | `POST /api/profiles/{id}/totp-reset` | Plattform | `get_tenant_context` | nur `superadmin`, nicht das eigene Konto | Schaltet TOTP ab, löscht Wiederherstellungscodes, beendet Sitzungen |
| clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth | | clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth |
| club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | | | club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | |
| club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | | | club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | |
@@ -1,6 +1,6 @@
# Progressionsgraph — Slot-Editor (Phase B) # Progressionsgraph — Slot-Editor (Phase B + F15)
**Stand:** 2026-06-10 · **Status:** In Umsetzung **Stand:** 2026-05-22 · **Status:** Umgesetzt (F14 + F15 lokal nach 0.8.233)
## Ziel ## Ziel
@@ -35,35 +35,52 @@ Leere Slots in der Roadmap sind erlaubt; Kanten nur zwischen aufeinanderfolgende
slots: Slot[], // index = major_step_index slots: Slot[], // index = major_step_index
pathSkillExpectations?, pathSkillExpectations?,
lastFindings?, // path_qa-Snapshot lastFindings?, // path_qa-Snapshot
findingsStale?: boolean, // Bewertung veraltet (↔ Artefakt findings_stale)
dirty: boolean, dirty: boolean,
} }
``` ```
**Hydration:** `planning_roadmap` + Kanten → Slots; `slot_contents[]` für Entwürfe; Primärkette aus `next_exercise`. **Hydration:** `planning_roadmap` + Kanten → Slots; `slot_contents[]` für Entwürfe; Primärkette aus `next_exercise`.
**Speichern:** Batch-Delete bestehender Pfad-/Schwester-Kanten → `edges/sequence` (Primärkette) → einzelne `sibling`-Kanten → `PUT`/`sequence` mit Artefakt inkl. `slot_contents`, optional `last_findings`. **Speichern:** Batch-Delete bestehender Pfad-/Schwester-Kanten → `edges/sequence` (Primärkette) → einzelne `sibling`-Kanten → `PUT`/`sequence` mit Artefakt inkl. `slot_contents`, `last_findings`, **`findings_stale`**.
## Findings-Panel ## Findings-Panel
Nutzt `path_qa` (`overall_ok`, `quality_score`, `issues`, `recommendations`, `gap_fill_offers`, …). Nutzt `path_qa`:
| Feld | Bedeutung |
|------|-----------|
| `quality_score` | Gesamt = **min(`roadmap_qa`, `assignment_qa`)** |
| `roadmap_qa` | Stufen/Roadmap (LLM `topic_coverage`, …) |
| `assignment_qa` | Slot-Befüllung (`empty_slot_count`, …) |
| `overall_ok`, `issues`, `recommendations`, `gap_fill_offers`, … | wie bisher |
**API:** `POST /api/planning/progression-path-suggest` mit `evaluate_only: true` und `evaluate_steps[]` — QA ohne Re-Match. **API:** `POST /api/planning/progression-path-suggest` mit `evaluate_only: true` und `evaluate_steps[]` — QA ohne Re-Match.
Persistenz: `planning_roadmap.last_findings`. **Bewertung veraltet:** Jede Graph-Änderung setzt `findingsStale: true` → Banner im Panel. Nach „Graph bewerten“ → `false`. Persistenz: `planning_roadmap.findings_stale`.
## Match-Flow („Übungen matchen“)
1. **Schritt 1:** `evaluate_only` + volle Pfad-QS (wie „Graph bewerten“)
2. **Schritt 2:** `unified_slot_review: true` → **`ProgressionOptimizeCompareModal`**
3. Pro Slot: aktuell vs. beste Bibliothek vs. optional KI-Vorschlag
4. **Vorauswahl:** Bibliothek nur wenn Stufen-Fit ≥ 50 % und besser als Baseline; sonst KI (bei leerem/schwachem Slot)
5. **Übernahme:** nur gewählte Slots speichern — **keine** automatische Nach-Bewertung
## Artefakt-Erweiterung (`GraphPlanningRoadmapArtifact`) ## Artefakt-Erweiterung (`GraphPlanningRoadmapArtifact`)
Zusätzlich optional: Optional:
- `slot_contents[]` — `{ major_step_index, primary, siblings[] }` - `slot_contents[]` — `{ major_step_index, primary, siblings[] }`
- `last_findings` — letzter `path_qa`-Snapshot - `last_findings` — letzter `path_qa`-Snapshot
- **`findings_stale`** — bool, Bewertung bezieht sich nicht mehr auf aktuellen Graph-Stand
## UI (konsolidiert) ## UI (konsolidiert)
- **Eine Oberfläche:** `ExerciseProgressionGraphPanel` embeddet `ProgressionGraphEditor` (Slots + Findings) - **Eine Oberfläche:** `ExerciseProgressionGraphPanel` embeddet `ProgressionGraphEditor` (Slots + Findings)
- Kein separater Slot-Editor, kein 4-Schritt-KI-Wizard, kein `ProgressionChainEditor` im Panel - Kein separater Slot-Editor, kein 4-Schritt-KI-Wizard, kein `ProgressionChainEditor` im Panel
- Route `/progression-graphs/:id` → Redirect nach `/exercises` (Deep-Link wählt Graph) - Route `/progression-graphs/:id` → Redirect nach `/exercises` (Deep-Link wählt Graph)
- **Phase C:** Übersicht mit Kacheln (Name, Start, Ziel) - **Slot-Keys:** stabil `slot-{index}` (nicht Lernziel-Text) — sonst Fokusverlust beim Tippen
## Ersetzt (Legacy, nicht mehr im Panel) ## Ersetzt (Legacy, nicht mehr im Panel)
@@ -71,11 +88,14 @@ Zusätzlich optional:
## Implementierungsreihenfolge ## Implementierungsreihenfolge
| ID | Inhalt | | ID | Inhalt | Status |
|----|--------| |----|--------|--------|
| B.0 | Draft + Laden/Speichern Slots ↔ Kanten | | B.0 | Draft + Laden/Speichern Slots ↔ Kanten | ✅ |
| B.1 | Slot-Karten, Bibliothek + Entwurf | | B.1 | Slot-Karten, Bibliothek + Entwurf | ✅ |
| B.2 | Findings-Panel + `evaluate_only` | | B.2 | Findings-Panel + `evaluate_only` | ✅ |
| B.3 | Entwürfe im Artefakt + „Übung anlegen“ | | B.3 | Entwürfe im Artefakt + „Übung anlegen“ | ✅ |
| B.4 | Route + Panel vereinfachen | | B.4 | Route + Panel vereinfachen | ✅ |
| B.5 | `last_findings` + Phase-C-Vorbereitung | | B.5 | `last_findings` + Phase-C-Vorbereitung | ✅ |
| F15 | Unified Slot-Review, getrennte QS, `findings_stale` | ✅ |
**Ist-Doku:** `docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md` §8.1 · `docs/HANDOVER.md` §2.8 F15
+6 -1
View File
@@ -53,7 +53,12 @@ SMTP_FROM=noreply@jinkendo.de
SMTP_SSL= SMTP_SSL=
SMTP_STARTTLS= SMTP_STARTTLS=
AUTO_ADMIN_FIRST_USER=true # Produktion: false. true nur für eine bewusst leere Erstinstallation.
AUTO_ADMIN_FIRST_USER=false
# true erzwingt TOTP für Plattform-Admins beim Login. Standard ist freiwillig.
REQUIRE_ADMIN_TOTP=false
# Optional. Sonst wird das Medien-Token aus DB_PASSWORD abgeleitet.
# MEDIA_TOKEN_SECRET=
ADMIN_BOOTSTRAP_EMAILS= ADMIN_BOOTSTRAP_EMAILS=
APP_URL=https://shinkan.jinkendo.de APP_URL=https://shinkan.jinkendo.de
+166
View File
@@ -0,0 +1,166 @@
name: Deploy Production llm-node
# Zweites, unabhängiges Prod-Deployment auf llm-node (192.168.2.144, AMD64).
# Läuft parallel zu "Deploy Production" (Raspberry Pi). Den Namen nicht auf
# "Deploy Production" ändern: test.yml hört per workflow_run exakt auf diesen Namen.
# Runner: llm-node-runner mit einzigem Label linux_host (Host-Modus).
# Der Pi-Runner (Raspi5-Paperless) hat nur ubuntu-latest und nimmt diesen Job nie an.
# Compose: docker-compose.yml + docker-compose.llm-node.yml, Konfiguration aus ENV_FILE.
# Doku: .claude/docs/technical/PROD_DEPLOYMENTS.md
on:
push:
branches: [main]
workflow_dispatch:
jobs:
deploy:
runs-on: linux_host
env:
APP_DIR: /home/llmadmin/docker/shinkan-prod
ENV_FILE: /etc/shinkan/prod.env
COMPOSE_PROJECT: shinkan-prod
REPO_URL: http://192.168.2.144:3000/Lars/shinkan-jinkendo.git
MEDIA_HOST: /srv/shinkan/prod/media
# Medienbereinigung (retention-cron): disabled | enabled.
# Pi und llm-node teilen den Medienbestand bei getrennten Datenbanken.
# Nur nach Abschalten der Pi-Bereinigung bzw. dem Cutover auf enabled setzen.
MEDIA_RETENTION: disabled
steps:
- name: Runner prüfen (nur llm-node)
shell: bash
run: |
set -euo pipefail
if [ "$(hostname)" != "llm-node" ] || [ "$(uname -m)" != "x86_64" ]; then
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet llm-node/x86_64. Abbruch."
exit 1
fi
echo "✓ Runner $(hostname)/$(uname -m)"
- name: Konfiguration prüfen
shell: bash
run: |
set -euo pipefail
if [ ! -r "$ENV_FILE" ]; then
echo "✗ $ENV_FILE fehlt oder ist nicht lesbar."
exit 1
fi
env_value() {
grep -E "^$1=" "$ENV_FILE" | tail -1 | cut -d= -f2- | tr -d "\"'" || true
}
if [ -z "$(env_value DB_PASSWORD)" ]; then
echo "✗ DB_PASSWORD ist in $ENV_FILE nicht gesetzt."
exit 1
fi
# Profile steuert allein MEDIA_RETENTION in diesem Workflow.
if grep -Eq "^COMPOSE_PROFILES=" "$ENV_FILE"; then
echo "✗ COMPOSE_PROFILES in $ENV_FILE entfernen; die Bereinigung schaltet MEDIA_RETENTION im Workflow."
exit 1
fi
# Override mountet fest $MEDIA_HOST -> /app/media; abweichende Werte ergäben einen zweiten Mount.
media_host="$(env_value SHINKAN_MEDIA_HOST)"
media_root="$(env_value MEDIA_ROOT)"
if [ -n "$media_host" ] && [ "$media_host" != "$MEDIA_HOST" ]; then
echo "✗ SHINKAN_MEDIA_HOST=$media_host, erwartet $MEDIA_HOST."
exit 1
fi
if [ -n "$media_root" ] && [ "$media_root" != "/app/media" ]; then
echo "✗ MEDIA_ROOT=$media_root, erwartet /app/media."
exit 1
fi
case "$MEDIA_RETENTION" in
disabled|enabled) ;;
*) echo "✗ MEDIA_RETENTION=$MEDIA_RETENTION, erlaubt: disabled | enabled."; exit 1 ;;
esac
echo "✓ $ENV_FILE geprüft, Medien $MEDIA_HOST -> /app/media, Bereinigung $MEDIA_RETENTION"
- name: Code aktualisieren
shell: bash
run: |
set -euo pipefail
cd "$APP_DIR"
if [ ! -d .git ]; then
git init -q
git remote add origin "$REPO_URL"
fi
git fetch origin main
git reset --hard origin/main
git log -1 --oneline
- name: Build und Start
shell: bash
run: |
set -euo pipefail
echo "=== Deploying Shinkan to PRODUCTION (llm-node) ==="
cd "$APP_DIR"
dc() {
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
--env-file "$ENV_FILE" "$@"
}
if [ "$MEDIA_RETENTION" = enabled ]; then
dc --profile media-retention build --no-cache
dc --profile media-retention up -d --remove-orphans
else
dc build --no-cache
dc up -d --remove-orphans
# Ein früher gestarteter retention-cron läuft sonst weiter.
dc --profile media-retention rm -s -f retention-cron
fi
- name: Healthchecks
shell: bash
run: |
set -euo pipefail
cd "$APP_DIR"
dc() {
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
--env-file "$ENV_FILE" "$@"
}
wait_for() {
local url="$1" label="$2" i
for i in $(seq 1 60); do
if curl -sf -o /dev/null "$url"; then
echo "✓ $label healthy ($url)"
return 0
fi
sleep 3
done
echo "✗ $label nicht erreichbar ($url)"
return 1
}
# HTTP 200 reicht nicht: status=ready, database=true und schema_complete=true.
wait_ready() {
local url="$1" label="$2" i body=""
for i in $(seq 1 60); do
body="$(curl -sf "$url" || true)"
if [ -n "$body" ] && printf '%s' "$body" \
| jq -e '.status == "ready" and .database == true and .schema_complete == true' >/dev/null 2>&1; then
echo "✓ $label ready ($url)"
return 0
fi
sleep 3
done
echo "✗ $label nicht ready ($url):"
printf '%s' "$body" | jq -c '{status, database, schema_complete}' 2>/dev/null || echo " keine gültige Antwort"
return 1
}
ok=1
wait_for http://127.0.0.1:8003/api/version "PROD API (direkt)" || ok=0
if [ "$ok" = 1 ]; then
wait_ready http://127.0.0.1:8003/api/health/ready "PROD API (direkt)" || ok=0
fi
if [ "$ok" = 1 ]; then
wait_for http://127.0.0.1:3003/api/version "PROD API über Frontend-Nginx" || ok=0
fi
if [ "$ok" = 1 ]; then
wait_ready http://127.0.0.1:3003/api/health/ready "PROD API über Frontend-Nginx" || ok=0
fi
if [ "$ok" = 1 ]; then
wait_for http://127.0.0.1:3003/ "PROD Frontend" || ok=0
fi
if [ "$ok" != 1 ]; then
dc ps || true
dc logs backend --tail 120 || true
exit 1
fi
echo "=== Shinkan PROD Deploy (llm-node) complete ==="
+15
View File
@@ -1,5 +1,11 @@
name: Deploy Production name: Deploy Production
# Prod-Deployment auf dem Raspberry Pi. Parallel dazu: deploy-prod-llm-node.yml.
# Namen nicht ändern: test.yml hört per workflow_run exakt auf "Deploy Production".
# Runner: Raspi5-Paperless mit einzigem Label ubuntu-latest (Host-Modus); der
# llm-node-Runner trägt dieses Label nicht. Der Guard bricht auf jedem anderen Host ab.
# Abschalten: .claude/docs/technical/PROD_DEPLOYMENTS.md
on: on:
push: push:
branches: [main] branches: [main]
@@ -8,6 +14,15 @@ jobs:
deploy: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Runner prüfen (nur Raspberry Pi)
run: |
set -e
if [ "$(hostname)" != "raspberrypi5" ] || [ "$(uname -m)" != "aarch64" ]; then
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet raspberrypi5/aarch64. Abbruch."
exit 1
fi
echo "✓ Runner $(hostname)/$(uname -m)"
- name: Deploy to Production - name: Deploy to Production
run: | run: |
set -e set -e
+46 -17
View File
@@ -1,15 +1,16 @@
name: Test Suite name: Test Suite
# develop: push/PR → Tests gegen Dev (parallel oder vor Deploy Development). # Eigener Workflow, getrennt von Deploy Development.
# main: kein push/PR-Trigger — vermeidet doppelten Dev-Lauf beim Merge develop→main; # push/PR auf develop: diese Datei, Ziel ist das Testsystem.
# Prod-Tests nur via workflow_run nach erfolgreichem Deploy Production. # workflow_run nur nach Deploy Production. Nicht nach dem Dev-Deploy:
# der Listener auf main nutzt bei fehlendem Namen sonst das Prod-Verzeichnis.
on: on:
push: push:
branches: [develop] branches: [develop]
pull_request: pull_request:
branches: [develop] branches: [develop]
workflow_run: workflow_run:
workflows: ["Deploy Development", "Deploy Production"] workflows: ["Deploy Production"]
types: [completed] types: [completed]
jobs: jobs:
@@ -25,18 +26,24 @@ jobs:
REF_NAME="${{ github.ref_name }}" REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}" BASE_REF="${{ github.base_ref }}"
RUN_WORKFLOW="${{ github.event.workflow_run.name }}" RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
APP_DIR="/home/lars/docker/shinkan" HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
COMPOSE_FILE="docker-compose.yml"
if [ "$EVENT_NAME" = "workflow_run" ]; then if [ "$EVENT_NAME" = "workflow_run" ]; then
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
COMPOSE_FILE="docker-compose.dev-env.yml" echo "Produktion wird nicht angefasst."
exit 1
fi fi
APP_DIR="/home/lars/docker/shinkan"
COMPOSE_FILE="docker-compose.yml"
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" APP_DIR="/home/lars/docker/shinkan-dev"
COMPOSE_FILE="docker-compose.dev-env.yml" COMPOSE_FILE="docker-compose.dev-env.yml"
else
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
exit 1
fi fi
echo "CI-Ziel: $APP_DIR ($COMPOSE_FILE)"
cd "$APP_DIR" cd "$APP_DIR"
echo "Warte auf stabilen backend-Container …" echo "Warte auf stabilen backend-Container …"
@@ -70,16 +77,24 @@ jobs:
run: | run: |
EVENT_NAME="${{ github.event_name }}" EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}" REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}"
RUN_WORKFLOW="${{ github.event.workflow_run.name }}" RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
APP_DIR="/home/lars/docker/shinkan" HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
if [ "$EVENT_NAME" = "workflow_run" ]; then if [ "$EVENT_NAME" = "workflow_run" ]; then
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
echo "Produktion wird nicht angefasst."
exit 1
fi fi
elif [ "$REF_NAME" = "develop" ]; then APP_DIR="/home/lars/docker/shinkan"
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" APP_DIR="/home/lars/docker/shinkan-dev"
else
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
exit 1
fi fi
echo "CI-Ziel: $APP_DIR"
python3 -m py_compile "$APP_DIR/backend/main.py" python3 -m py_compile "$APP_DIR/backend/main.py"
echo "✓ Backend syntax OK" echo "✓ Backend syntax OK"
@@ -92,16 +107,24 @@ jobs:
run: | run: |
EVENT_NAME="${{ github.event_name }}" EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}" REF_NAME="${{ github.ref_name }}"
BASE_REF="${{ github.base_ref }}"
RUN_WORKFLOW="${{ github.event.workflow_run.name }}" RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
APP_DIR="/home/lars/docker/shinkan" HEAD_BRANCH="${{ github.event.workflow_run.head_branch }}"
if [ "$EVENT_NAME" = "workflow_run" ]; then if [ "$EVENT_NAME" = "workflow_run" ]; then
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then if [ "$RUN_WORKFLOW" != "Deploy Production" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" echo "workflow_run ist nicht Deploy Production (name=$RUN_WORKFLOW head=$HEAD_BRANCH ref=$REF_NAME)."
echo "Produktion wird nicht angefasst."
exit 1
fi fi
elif [ "$REF_NAME" = "develop" ]; then APP_DIR="/home/lars/docker/shinkan"
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev" APP_DIR="/home/lars/docker/shinkan-dev"
else
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
exit 1
fi fi
echo "CI-Ziel: $APP_DIR"
cd "$APP_DIR/frontend" cd "$APP_DIR/frontend"
npm install npm install
@@ -129,6 +152,9 @@ jobs:
echo "mode=prod" >> $GITHUB_OUTPUT echo "mode=prod" >> $GITHUB_OUTPUT
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
echo "→ k6 gegen Prod-Basis." echo "→ k6 gegen Prod-Basis."
elif [ "$EVENT" = "workflow_run" ]; then
echo "workflow_run ist nicht Deploy Production (name=$WF_NAME). Abbruch."
exit 1
else else
echo "mode=dev" >> $GITHUB_OUTPUT echo "mode=dev" >> $GITHUB_OUTPUT
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
@@ -219,6 +245,9 @@ jobs:
echo "mode=prod" >> $GITHUB_OUTPUT echo "mode=prod" >> $GITHUB_OUTPUT
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD." echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
elif [ "$EVENT" = "workflow_run" ]; then
echo "workflow_run ist nicht Deploy Production (name=$WF_NAME). Abbruch."
exit 1
else else
echo "mode=dev" >> $GITHUB_OUTPUT echo "mode=dev" >> $GITHUB_OUTPUT
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
+7 -1
View File
@@ -139,8 +139,14 @@ Git Workflow:
develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098) develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098)
main → Auto-Deploy → shinkan.jinkendo.de (shinkan/, Port 3003/8003) main → Auto-Deploy → shinkan.jinkendo.de (shinkan/, Port 3003/8003)
main → Auto-Deploy → llm-node (192.168.2.144, /home/llmadmin/docker/shinkan-prod)
parallel, eigener Workflow deploy-prod-llm-node.yml
Compose-Override docker-compose.llm-node.yml, Config /etc/shinkan/prod.env
Details + Abschalten des Pi-Prod: .claude/docs/technical/PROD_DEPLOYMENTS.md
Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo
Runner: Raspberry Pi (/home/lars/gitea-runner/) Runner: Raspberry Pi (/home/lars/gitea-runner/, Label ubuntu-latest)
llm-node (act_runner.service, Label linux_host)
Manuell: Manuell:
cd /home/lars/docker/shinkan[-dev] cd /home/lars/docker/shinkan[-dev]
+2
View File
@@ -33,6 +33,8 @@ AUTH_INFRA_PREFIXES = (
"/api/auth/status", "/api/auth/status",
"/api/auth/pin", "/api/auth/pin",
"/api/auth/resend-verification", "/api/auth/resend-verification",
"/api/auth/totp",
"/api/auth/media-grant",
"/api/profiles/me", "/api/profiles/me",
"/api/me/entitlements", "/api/me/entitlements",
) )
+317
View File
@@ -0,0 +1,317 @@
"""
Admin-Vorschau: Platzhalter für Planungs-Prompts (Progressionsgraph, Pfad-QS, Suggest).
Nutzt repräsentative Beispieldaten + echte Katalog-Auszüge aus der DB.
"""
from __future__ import annotations
import json
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Field
from planning_exercise_semantics import brief_to_summary_dict, build_semantic_brief
from planning_intent_context import build_planning_intent_context
from planning_prompt_variables import merge_planning_prompt_variables
PLANNING_PROMPT_SLUGS = frozenset(
{
"planning_progression_start_target",
"planning_progression_goal_analysis",
"planning_progression_roadmap",
"planning_progression_stage_spec",
"planning_exercise_query_semantics",
"planning_exercise_path_qa",
"planning_exercise_search_intent",
"planning_exercise_search_rank",
"planning_exercise_expectation_profile",
}
)
class PlanningPromptPreviewInput(BaseModel):
goal_query: str = Field(
default="Mae Geri vom Grundschritt bis zur kontrollierten Kumite-Nähe",
max_length=2000,
)
user_notes: str = Field(default="Fokus Breitensport, ohne Wettkampfdruck.", max_length=2000)
max_steps: int = Field(default=5, ge=2, le=10)
search_query: Optional[str] = Field(default=None, max_length=2000)
planning_catalog_context: Optional[Dict[str, Any]] = Field(default=None)
def is_planning_prompt_slug(slug: str) -> bool:
return (slug or "").strip().lower() in PLANNING_PROMPT_SLUGS
def _compact_json(obj: Any) -> str:
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
def _sample_goal_analysis() -> Dict[str, Any]:
return {
"primary_topic": "Mae Geri",
"start_assumption": "Grundstellung und einfache Frontkick-Bewegung bekannt",
"target_state": "Kontrollierter Mae Geri in Kumite-Nähe mit Hüftöffnung",
"success_criteria": [
"Hüfte öffnet vor dem Kick",
"Ballen trifft Zielzone",
"Rückzug ohne Balanceverlust",
],
"constraints": {
"partner_required": False,
"excluded_themes": ["reine Kraft ohne Technikbezug"],
"trainer_notes": "Breitensport, kein Wettkampf",
},
}
def _sample_major_steps(max_steps: int) -> List[Dict[str, Any]]:
phases = ["einstieg", "grundlage", "vertiefung", "anwendung", "perfektion"]
titles = [
"Grundstellung und Mae Geri Einstieg",
"Hüftöffnung und Ballen-Fokus",
"Koordination und Rückzug",
"Anwendung in Partnerübung",
"Qualität unter leichtem Druck",
]
out: List[Dict[str, Any]] = []
for i in range(max_steps):
out.append(
{
"index": i,
"phase": phases[min(i, len(phases) - 1)],
"title": titles[min(i, len(titles) - 1)],
"learning_goal": titles[min(i, len(titles) - 1)],
}
)
return out
def _sample_path_steps() -> List[Dict[str, Any]]:
return [
{
"index": 1,
"exercise_id": 101,
"title": "Mae Geri — Stand und Hüftöffnung",
"goal": "Frontkick mit geöffneter Hüfte aus Grundstellung",
"is_bridge": False,
"is_ai_proposal": False,
"reasons": ["Stufen-Gate: Grundlagen"],
},
{
"index": 2,
"exercise_id": 102,
"title": "Mae Geri — Ballen und Rückzug",
"goal": "Präziser Ballentreffer mit kontrolliertem Rückzug",
"is_bridge": False,
"is_ai_proposal": False,
"reasons": ["Nachfolger im Graph"],
},
]
def _sample_planning_context() -> Dict[str, Any]:
return {
"scope": "progression_path",
"goal_query": "Mae Geri vom Grundschritt bis zur Kumite-Nähe",
"stage_index": 1,
"learning_goal": "Hüftöffnung und Ballen-Fokus",
}
def _sample_target_profile() -> Dict[str, Any]:
return {
"primary_focus": "Kihon",
"training_type": "Breitensport",
"skill_expectations": ["Geri Waza", "Koordination"],
}
def _sample_candidates() -> List[Dict[str, Any]]:
return [
{
"exercise_id": 101,
"title": "Mae Geri — Stand und Hüftöffnung",
"summary": "Frontkick mit Hüftöffnung",
"skill_names": ["Geri Waza"],
"score_hint": 0.82,
},
{
"exercise_id": 102,
"title": "Mae Geri — Ballen und Rückzug",
"summary": "Ballentreffer mit Rückzug",
"skill_names": ["Geri Waza", "Koordination"],
"score_hint": 0.76,
},
]
def _load_catalog_variables(cur) -> Dict[str, str]:
from planning_exercise_intent import (
_load_compact_catalog,
_load_skills_catalog_compact,
)
return {
"skills_catalog_json": _compact_json(_load_skills_catalog_compact(cur)),
"focus_areas_catalog_json": _compact_json(_load_compact_catalog(cur, "focus_areas", "id")),
"training_types_catalog_json": _compact_json(_load_compact_catalog(cur, "training_types", "id")),
"style_directions_catalog_json": _compact_json(_load_compact_catalog(cur, "style_directions", "id")),
"target_groups_catalog_json": _compact_json(_load_compact_catalog(cur, "target_groups", "id")),
}
def _preview_catalog_context(body: PlanningPromptPreviewInput):
from planning_catalog_context import catalog_context_from_mapping
raw = body.planning_catalog_context
if raw:
return catalog_context_from_mapping(raw)
return None
def _merge_catalog_preview(cur, slug: str, base: Dict[str, str], body: PlanningPromptPreviewInput) -> Dict[str, str]:
return merge_planning_prompt_variables(
cur,
base,
catalog=_preview_catalog_context(body),
slug=slug,
)
def resolve_planning_prompt_preview_variables(
cur,
slug: str,
body: PlanningPromptPreviewInput,
) -> Dict[str, str]:
"""Mustache-Variablen für Planungs-Prompt-Vorschau im Admin."""
s = (slug or "").strip().lower()
if s not in PLANNING_PROMPT_SLUGS:
raise ValueError(f"Kein Planungs-Prompt-Slug: {slug!r}")
goal_query = (body.goal_query or "").strip() or "Mae Geri Progression"
search_query = (body.search_query or "").strip() or goal_query
max_steps = int(body.max_steps)
brief = build_semantic_brief(goal_query)
brief_json = _compact_json(brief_to_summary_dict(brief))
goal_analysis = _sample_goal_analysis()
major_steps = _sample_major_steps(max_steps)
intent_ctx = build_planning_intent_context(
goal_query=goal_query,
goal_analysis=goal_analysis,
semantic_brief=brief,
extra_context=(body.user_notes or "").strip() or None,
)
intent_ctx_json = _compact_json(intent_ctx.to_api_dict())
ctx = _sample_planning_context()
target = _sample_target_profile()
catalogs = _load_catalog_variables(cur)
if s == "planning_progression_start_target":
return _merge_catalog_preview(
cur,
s,
{
"goal_query": goal_query,
"semantic_brief_json": brief_json,
"user_notes": (body.user_notes or "").strip(),
},
body,
)
if s == "planning_progression_goal_analysis":
return _merge_catalog_preview(
cur,
s,
{
"goal_query": goal_query,
"semantic_brief_json": brief_json,
},
body,
)
if s == "planning_progression_roadmap":
return _merge_catalog_preview(
cur,
s,
{
"goal_query": goal_query,
"goal_analysis_json": _compact_json(goal_analysis),
"semantic_brief_json": brief_json,
"max_steps": str(max_steps),
},
body,
)
if s == "planning_progression_stage_spec":
return _merge_catalog_preview(
cur,
s,
{
"goal_query": goal_query,
"goal_analysis_json": _compact_json(goal_analysis),
"major_steps_json": _compact_json(major_steps),
"intent_context_json": intent_ctx_json,
"semantic_brief_json": brief_json,
},
body,
)
if s == "planning_exercise_query_semantics":
return {
"search_query": search_query,
"semantic_brief_json": brief_json,
}
if s == "planning_exercise_path_qa":
return _merge_catalog_preview(
cur,
s,
{
"goal_query": goal_query,
"semantic_brief_json": brief_json,
"steps_json": _compact_json(_sample_path_steps()),
"gaps_json": _compact_json([]),
"bridge_inserts_json": _compact_json([]),
},
body,
)
if s == "planning_exercise_search_intent":
return {
"search_query": search_query,
"heuristic_intent": "progression_next",
"scenario_hint": "preset_next",
"planning_context_json": _compact_json(ctx),
"target_profile_json": _compact_json(target),
**catalogs,
}
if s == "planning_exercise_search_rank":
return {
"search_query": search_query,
"intent": "progression_next",
"planning_context_json": _compact_json(ctx),
"target_profile_json": _compact_json(target),
"candidates_json": _compact_json(_sample_candidates()),
"result_limit": "5",
}
if s == "planning_exercise_expectation_profile":
return {
"heuristic_intent": "suggest_next",
"planning_context_json": _compact_json(ctx),
"target_profile_json": _compact_json(target),
**{k: v for k, v in catalogs.items() if k != "style_directions_catalog_json"},
}
raise ValueError(f"Planungs-Prompt-Slug nicht implementiert: {slug!r}")
__all__ = [
"PLANNING_PROMPT_SLUGS",
"PlanningPromptPreviewInput",
"is_planning_prompt_slug",
"resolve_planning_prompt_preview_variables",
]
+70 -4
View File
@@ -12,6 +12,11 @@ from fastapi import Header, Query, HTTPException
import bcrypt import bcrypt
from db import get_db, get_cursor from db import get_db, get_cursor
from media_grant import profile_id_from_media_grant
# Fester bcrypt-Hash, damit ein unbekannter Login dieselbe Rechenzeit hat wie ein Treffer.
_LOGIN_TIMING_HASH = "$2b$12$GYdnAmeiqaZg/.5J9E4f4.xhz70piViqXIpqKCY/FY609qj65sc9i"
MAX_SESSION_DAYS = 30
def hash_pin(pin: str) -> str: def hash_pin(pin: str) -> str:
@@ -33,6 +38,34 @@ def verify_pin(pin: str, stored_hash: str) -> bool:
return stored_hash == hashlib.sha256(pin.encode()).hexdigest() return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
def verify_pin_for_login(pin: str, stored_hash: Optional[str]) -> bool:
"""Immer ein bcrypt-Vergleich, auch wenn das Konto fehlt (kein Zeit-Orakel)."""
if stored_hash and str(stored_hash).startswith("$2"):
return verify_pin(pin, stored_hash)
verify_pin(pin or "x", _LOGIN_TIMING_HASH)
if not stored_hash:
return False
return verify_pin(pin, stored_hash)
def session_lifetime_days(profile: Optional[dict]) -> int:
raw = profile.get("session_days") if profile else None
try:
days = int(raw) if raw is not None else MAX_SESSION_DAYS
except (TypeError, ValueError):
days = MAX_SESSION_DAYS
if days < 1:
days = 1
if days > MAX_SESSION_DAYS:
days = MAX_SESSION_DAYS
return days
def revoke_profile_sessions(cur, profile_id: int) -> None:
"""Alle Sitzungen eines Profils entfernen, inklusive Reset- und 2FA-Zwischentokens."""
cur.execute("DELETE FROM sessions WHERE profile_id = %s", (profile_id,))
def make_token() -> str: def make_token() -> str:
"""Generate a secure random token for sessions.""" """Generate a secure random token for sessions."""
return secrets.token_urlsafe(32) return secrets.token_urlsafe(32)
@@ -51,12 +84,39 @@ def get_session(token: str):
cur.execute( cur.execute(
"SELECT s.*, p.role, p.name " "SELECT s.*, p.role, p.name "
"FROM sessions s JOIN profiles p ON s.profile_id=p.id " "FROM sessions s JOIN profiles p ON s.profile_id=p.id "
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP", "WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
"AND COALESCE(s.purpose, 'full') = 'full'",
(token,) (token,)
) )
return cur.fetchone() return cur.fetchone()
def get_limited_session(token: str, purpose: str):
"""Sitzung mit festem Zweck (totp_enroll, totp_challenge). Kein Fach-API-Zugriff."""
if not token or purpose not in ("totp_enroll", "totp_challenge"):
return None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT s.*, p.role, p.name, p.email "
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
"AND s.purpose = %s",
(token, purpose),
)
return cur.fetchone()
def _profile_session_from_id(profile_id: int) -> Optional[dict]:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id AS profile_id, role, name FROM profiles WHERE id = %s",
(profile_id,),
)
return cur.fetchone()
def require_auth(x_auth_token: Optional[str] = Header(default=None)): def require_auth(x_auth_token: Optional[str] = Header(default=None)):
""" """
FastAPI dependency - requires valid authentication. FastAPI dependency - requires valid authentication.
@@ -80,8 +140,8 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
""" """
FastAPI dependency - auth via header OR query parameter. FastAPI dependency - auth via header OR query parameter.
Used for endpoints accessed by <img> tags and SSE connections that can't send headers. Dateiabruf für <img>/<video>: Header-Sitzung oder kurzlebiges Medien-Token (?ssetoken).
Query parameter is 'ssetoken' to avoid conflicts with endpoint 'token' parameters. Ein Sitzungstoken in der Query-Zeichenfolge wird nicht akzeptiert.
Usage: Usage:
@app.get("/api/photos/{id}") @app.get("/api/photos/{id}")
@@ -93,7 +153,13 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
Raises: Raises:
HTTPException 401 if not authenticated HTTPException 401 if not authenticated
""" """
session = get_session(x_auth_token or ssetoken) session = get_session(x_auth_token) if x_auth_token else None
if session:
return session
profile_id = profile_id_from_media_grant(ssetoken)
if profile_id is None:
raise HTTPException(401, "Nicht eingeloggt")
session = _profile_session_from_id(profile_id)
if not session: if not session:
raise HTTPException(401, "Nicht eingeloggt") raise HTTPException(401, "Nicht eingeloggt")
return session return session
+432
View File
@@ -0,0 +1,432 @@
"""
Katalog-Prompt-Slots — Slot-Typ-Vokabular + Werte pro Stammdaten-Zeile (H2).
Prompts in ai_prompts referenzieren Platzhalter wie {{focus_area_hints_on_progression}}.
Inhalte liegen in catalog_prompt_slots (Admin-editierbar), nicht im Code pro Eintrag.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from planning_catalog_context import (
ProgressionPlanningCatalogContext,
PlanningCatalogContextItem,
catalog_context_has_items,
)
from catalog_slot_fallbacks import merge_stored_slots_with_fallbacks
# ---------------------------------------------------------------------------
# Dimensionen (Prioritätsreihenfolge)
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class CatalogKindConfig:
kind: str
table: str
context_attr: str
label_de: str
CATALOG_KINDS: Tuple[CatalogKindConfig, ...] = (
CatalogKindConfig("focus_area", "focus_areas", "focus_areas", "Primärfokus"),
CatalogKindConfig("training_type", "training_types", "training_types", "Trainingsstil"),
CatalogKindConfig("target_group", "target_groups", "target_groups", "Zielgruppe"),
CatalogKindConfig("style_direction", "style_directions", "style_directions", "Stilrichtung"),
)
_KIND_BY_NAME = {c.kind: c for c in CATALOG_KINDS}
# ---------------------------------------------------------------------------
# Slot-Typen (Vokabular — erweiterbar via catalog_prompt_slot_types)
# ---------------------------------------------------------------------------
SLOT_KEYS: Tuple[str, ...] = (
"description",
"hints_on_progression",
"hints_on_exercise",
"hints_on_path_qa",
"anti_patterns",
"rematch_guard",
)
LLM_SLOT_KEYS: Tuple[str, ...] = tuple(k for k in SLOT_KEYS if k != "rematch_guard")
GUIDANCE_BLOCK_SLOTS: Tuple[str, ...] = (
"description",
"hints_on_progression",
"hints_on_path_qa",
"anti_patterns",
)
GUIDANCE_PROFILE_BY_SLUG: Dict[str, Tuple[str, ...]] = {
"planning_exercise_path_qa": ("description", "hints_on_path_qa", "anti_patterns"),
"planning_progression_roadmap": ("description", "hints_on_progression", "anti_patterns"),
"planning_progression_stage_spec": ("hints_on_progression", "anti_patterns", "description"),
"planning_progression_goal_analysis": ("description", "hints_on_progression"),
"planning_progression_start_target": ("description",),
}
def placeholder_key(catalog_kind: str, slot_key: str) -> str:
return f"{catalog_kind}_{slot_key}"
def all_placeholder_keys() -> List[str]:
keys: List[str] = []
for cfg in CATALOG_KINDS:
for slot in SLOT_KEYS:
keys.append(placeholder_key(cfg.kind, slot))
keys.extend(["catalog_guidance_block", "catalog_context_json", "has_catalog_guidance"])
return keys
def empty_catalog_variables() -> Dict[str, str]:
out = {k: "" for k in all_placeholder_keys()}
return out
# ---------------------------------------------------------------------------
# Katalog-Kontext → aktiver Eintrag
# ---------------------------------------------------------------------------
def pick_active_catalog_item(
items: Sequence[PlanningCatalogContextItem],
) -> Optional[PlanningCatalogContextItem]:
if not items:
return None
primaries = [i for i in items if i.is_primary]
if primaries:
return primaries[0]
if len(items) == 1:
return items[0]
return max(items, key=lambda i: (float(i.weight), -int(i.id)))
def _load_catalog_row(cur, table: str, item_id: int) -> Optional[Dict[str, Any]]:
cur.execute(
f"""
SELECT id, name, description
FROM {table}
WHERE id = %s
""",
(int(item_id),),
)
row = cur.fetchone()
if not row:
return None
return {
"id": int(row["id"]),
"name": str(row.get("name") or "").strip(),
"description": str(row.get("description") or "").strip(),
}
def _load_slots_for_entry(cur, catalog_kind: str, catalog_id: int) -> Dict[str, str]:
cur.execute(
"""
SELECT slot_key, content
FROM catalog_prompt_slots
WHERE catalog_kind = %s AND catalog_id = %s
""",
(catalog_kind, int(catalog_id)),
)
out: Dict[str, str] = {}
for row in cur.fetchall():
key = str(row.get("slot_key") or "").strip()
if key:
out[key] = str(row.get("content") or "").strip()
return out
def _slot_types_table_ready(cur) -> bool:
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.catalog_prompt_slot_types",))
row = cur.fetchone()
if not row:
return False
val = row.get("t") if isinstance(row, dict) else row[0]
return val is not None and str(val).strip() != ""
def list_slot_type_definitions(cur) -> List[Dict[str, Any]]:
if not _slot_types_table_ready(cur):
return _fallback_slot_type_rows()
cur.execute(
"""
SELECT slot_key, display_name, description, applicable_kinds, sort_order, for_llm, for_code
FROM catalog_prompt_slot_types
ORDER BY sort_order ASC NULLS LAST, slot_key ASC
"""
)
rows = []
for row in cur.fetchall():
d = dict(row)
kinds = d.get("applicable_kinds")
if isinstance(kinds, str):
kinds = [k.strip() for k in kinds.strip("{}").split(",") if k.strip()]
d["applicable_kinds"] = list(kinds or [])
rows.append(d)
return rows
def _fallback_slot_type_rows() -> List[Dict[str, Any]]:
labels = {
"description": "Allgemeine Beschreibung",
"hints_on_progression": "Hinweise Progressionsgraph",
"hints_on_exercise": "Hinweise Übungsanlage",
"hints_on_path_qa": "Hinweise Pfad-QS",
"anti_patterns": "Anti-Patterns (Fehlbewertung vermeiden)",
"rematch_guard": "Rematch-Guard (Code)",
}
kinds = [c.kind for c in CATALOG_KINDS]
rows = []
for i, key in enumerate(SLOT_KEYS):
rows.append(
{
"slot_key": key,
"display_name": labels.get(key, key),
"description": "",
"applicable_kinds": kinds,
"sort_order": (i + 1) * 10,
"for_llm": key != "rematch_guard",
"for_code": key == "rematch_guard",
}
)
return rows
def _resolve_entry_slot_values(
stored: Mapping[str, str],
row: Mapping[str, Any],
catalog_kind: str,
) -> Dict[str, str]:
"""DB → Namens-Fallback → Stammdaten-Beschreibung (nur description)."""
return merge_stored_slots_with_fallbacks(
stored,
catalog_kind=catalog_kind,
name=str(row.get("name") or ""),
stammdaten_description=str(row.get("description") or ""),
)
def get_catalog_entry_slots(cur, catalog_kind: str, catalog_id: int) -> Dict[str, Any]:
cfg = _KIND_BY_NAME.get((catalog_kind or "").strip())
if not cfg:
raise ValueError(f"Unbekannter catalog_kind: {catalog_kind!r}")
row = _load_catalog_row(cur, cfg.table, catalog_id)
if not row:
raise LookupError("Katalog-Eintrag nicht gefunden")
stored = _load_slots_for_entry(cur, cfg.kind, catalog_id)
merged = _resolve_entry_slot_values(stored, row, cfg.kind)
return {
"catalog_kind": cfg.kind,
"catalog_id": int(catalog_id),
"name": row["name"],
"slots": merged,
"stored_slots": {k: stored.get(k, "") for k in SLOT_KEYS},
}
def upsert_catalog_entry_slots(
cur,
catalog_kind: str,
catalog_id: int,
slots: Mapping[str, Any],
) -> Dict[str, Any]:
cfg = _KIND_BY_NAME.get((catalog_kind or "").strip())
if not cfg:
raise ValueError(f"Unbekannter catalog_kind: {catalog_kind!r}")
row = _load_catalog_row(cur, cfg.table, catalog_id)
if not row:
raise LookupError("Katalog-Eintrag nicht gefunden")
for slot_key, raw in (slots or {}).items():
sk = str(slot_key or "").strip()
if sk not in SLOT_KEYS:
continue
content = str(raw or "").strip()
if not content:
cur.execute(
"""
DELETE FROM catalog_prompt_slots
WHERE catalog_kind = %s AND catalog_id = %s AND slot_key = %s
""",
(cfg.kind, int(catalog_id), sk),
)
continue
cur.execute(
"""
INSERT INTO catalog_prompt_slots (catalog_kind, catalog_id, slot_key, content, updated_at)
VALUES (%s, %s, %s, %s, NOW())
ON CONFLICT (catalog_kind, catalog_id, slot_key)
DO UPDATE SET content = EXCLUDED.content, updated_at = NOW()
""",
(cfg.kind, int(catalog_id), sk, content),
)
return get_catalog_entry_slots(cur, cfg.kind, catalog_id)
def _render_dimension_section(
label_de: str,
name: str,
slot_values: Mapping[str, str],
*,
slot_keys: Sequence[str],
) -> Optional[str]:
parts: List[str] = [f"### {label_de} — {name}"]
labels = {
"description": "Beschreibung",
"hints_on_progression": "Progressions-Hinweise",
"hints_on_path_qa": "QS-Hinweise",
"hints_on_exercise": "Übungsanlage",
"anti_patterns": "Vermeiden",
}
added = False
for sk in slot_keys:
text = str(slot_values.get(sk) or "").strip()
if not text:
continue
added = True
if sk == "description":
parts.append(text)
else:
parts.append(f"{labels.get(sk, sk)}: {text}")
if not added:
return None
return "\n".join(parts)
def _compose_guidance_block(
sections: List[str],
) -> str:
if not sections:
return ""
return "## Katalog-Kontext (Didaktik & Bewertung)\n\n" + "\n\n".join(sections)
def resolve_catalog_prompt_variables(
cur,
catalog: Optional[ProgressionPlanningCatalogContext],
*,
slug: Optional[str] = None,
) -> Dict[str, Any]:
"""
Liefert Mustache-Strings + Metadaten.
Returns dict mit allen {{kind_slot}} Keys, catalog_guidance_block, catalog_context_json,
has_catalog_guidance (bool), active_slots (list).
"""
variables = empty_catalog_variables()
meta: Dict[str, Any] = {
"active_slots": [],
"audit": {},
}
if cur is None or not catalog_context_has_items(catalog):
variables["catalog_context_json"] = ""
return {**variables, **meta}
profile = GUIDANCE_PROFILE_BY_SLUG.get((slug or "").strip().lower(), GUIDANCE_BLOCK_SLOTS)
sections: List[str] = []
audit: Dict[str, Any] = {}
has_any = False
active_slots: List[str] = []
for cfg in CATALOG_KINDS:
items = getattr(catalog, cfg.context_attr, None) or []
active = pick_active_catalog_item(items)
if not active:
continue
row = _load_catalog_row(cur, cfg.table, active.id)
if not row:
continue
stored = _load_slots_for_entry(cur, cfg.kind, row["id"]) if _slot_types_table_ready(cur) else {}
slot_values = _resolve_entry_slot_values(stored, row, cfg.kind)
for sk in SLOT_KEYS:
pk = placeholder_key(cfg.kind, sk)
text = slot_values.get(sk, "")
variables[pk] = text
if text.strip() and sk in LLM_SLOT_KEYS:
has_any = True
active_slots.append(pk)
audit[cfg.context_attr] = {
"catalog_kind": cfg.kind,
"id": row["id"],
"name": row["name"],
"is_primary": bool(active.is_primary),
"weight": float(active.weight),
"filled_slots": [k for k in LLM_SLOT_KEYS if slot_values.get(k, "").strip()],
"stored_slots": [k for k in SLOT_KEYS if (stored.get(k) or "").strip()],
}
section = _render_dimension_section(cfg.label_de, row["name"], slot_values, slot_keys=profile)
if section:
sections.append(section)
variables["catalog_guidance_block"] = _compose_guidance_block(sections)
ctx_json = json.dumps(audit, ensure_ascii=False, separators=(",", ":"))
variables["catalog_context_json"] = f"Katalog-Audit: {ctx_json}" if audit else ""
variables["has_catalog_guidance"] = "true" if has_any else ""
return {
**variables,
"active_slots": active_slots,
"audit": audit,
}
def get_rematch_guard_for_catalog(
cur,
catalog: Optional[ProgressionPlanningCatalogContext],
) -> Optional[str]:
"""Erste passende rematch_guard entlang der Dimensions-Priorität."""
if cur is None or not catalog_context_has_items(catalog):
return None
for cfg in CATALOG_KINDS:
items = getattr(catalog, cfg.context_attr, None) or []
active = pick_active_catalog_item(items)
if not active:
continue
stored = _load_slots_for_entry(cur, cfg.kind, active.id)
row = _load_catalog_row(cur, cfg.table, active.id)
if not row:
continue
slot_values = _resolve_entry_slot_values(stored, row, cfg.kind)
guard = (slot_values.get("rematch_guard") or "").strip()
if guard:
return guard
return None
# Abwärtskompatibilität H1-API
def build_catalog_guidance_for_prompt(
cur,
catalog: Optional[ProgressionPlanningCatalogContext],
*,
slug: Optional[str] = None,
) -> Dict[str, Any]:
resolved = resolve_catalog_prompt_variables(cur, catalog, slug=slug)
return {
"catalog_guidance_block": resolved.get("catalog_guidance_block", ""),
"catalog_context_json": resolved.get("catalog_context_json", ""),
"has_catalog_guidance": resolved.get("has_catalog_guidance") == "true",
"snippet_keys": list(resolved.get("active_slots") or []),
"variables": {k: str(resolved.get(k) or "") for k in all_placeholder_keys()},
}
__all__ = [
"CATALOG_KINDS",
"GUIDANCE_PROFILE_BY_SLUG",
"SLOT_KEYS",
"build_catalog_guidance_for_prompt",
"empty_catalog_variables",
"get_catalog_entry_slots",
"get_rematch_guard_for_catalog",
"list_slot_type_definitions",
"pick_active_catalog_item",
"placeholder_key",
"all_placeholder_keys",
"resolve_catalog_prompt_variables",
"upsert_catalog_entry_slots",
]
+284
View File
@@ -0,0 +1,284 @@
"""
Namensbasierte Fallback-Slots — bis Admin/DB befüllt sind (H1-Registry-Inhalt).
DB-Werte in catalog_prompt_slots haben immer Vorrang. Fallbacks füllen nur leere Slot-Keys.
"""
from __future__ import annotations
import re
import unicodedata
from typing import Dict, Mapping, Optional, Sequence, Tuple
_UMLAUT_MAP = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss", "Ä": "ae", "Ö": "oe", "Ü": "ue"})
SlotPack = Dict[str, str]
# (catalog_kind, name_pattern_lower) — erste passende Regel gewinnt; * = Default pro Kind
_FALLBACK_RULES: Tuple[Tuple[str, str, SlotPack], ...] = (
# --- focus_area ---
(
"focus_area",
"gewaltschutz",
{
"description": (
"Planung zielt auf Prävention, Deeskalation, Grenzen und sichere Übungsformen — "
"nicht auf Wettkampf-Perfektion oder Technik-Show."
),
"hints_on_progression": (
"Phasen: Wahrnehmung → Grenzen → Deeskalation → sichere Übungsformen; "
"keine Kumite-Perfektionsstufen erzwingen."
),
"hints_on_exercise": (
"Übungen mit Rollen, Kommunikation, Ausweichen; keine rein technischen Kick-Fokus-Inseln ohne Bezug."
),
"hints_on_path_qa": (
"Gute Pfade bauen Sicherheit, Kommunikation und Alternativen auf; "
"„Lücken“ sind fehlende Deeskalations- oder Rollenspiel-Stufen, nicht fehlende Kick-Varianten."
),
"anti_patterns": "Nicht nach Kumite-Tiefe, Explosivität oder Wettkampf-Belastung bewerten.",
},
),
(
"focus_area",
"selbstverteidigung",
{
"description": (
"Praktische Selbstverteidigung: realistische Szenarien, Sicherheit und "
"anwendungsnahe Progression — nicht Show-Technik oder Wettkampf-Kata."
),
"hints_on_progression": (
"Von Wahrnehmung und Distanz zu einfachen Abwehrmustern und kontrollierter Anwendung."
),
"hints_on_exercise": "Partnerübungen mit klaren Sicherheitsregeln; Szenario-Bezug wichtiger als Stil-Show.",
"hints_on_path_qa": (
"Lücken bei Szenario- oder Sicherheitsstufen sind relevant; "
"fehlende Kick-Varianten oder Wettkampftiefe sind kein Mangel."
),
"anti_patterns": "Keine Wettkampf- oder Kata-Perfektion als QS-Maßstab.",
},
),
(
"focus_area",
"fitness",
{
"description": (
"Fitness- und Konditionsorientierung mit sicherer Belastungssteuerung; "
"Technikbezug nur wo fachlich sinnvoll."
),
"hints_on_progression": "Progression von niedriger zu moderater Belastung; klare Pausen und Technikhygiene.",
"hints_on_path_qa": (
"Keine Wettkampf-Spezialisierung als Pflicht-Kriterium; "
"Belastungssteigerung ohne Technikbezug abwerten."
),
"anti_patterns": "Keine Kumite-Perfektion oder Wettkampf-Kombinationen als QS-Maßstab verlangen.",
},
),
(
"focus_area",
"karate",
{
"description": (
"Technik-Curriculum im Karate-Kontext: aufeinander aufbauende Kihon-Progression "
"mit klaren Qualitätsankern (Stand, Hüfte, Kime)."
),
"hints_on_progression": (
"Typische Phasen: Einstieg → Grundlagen → Koordination/Kraft → Anwendung → optional Vertiefung; "
"Grundlagen vor Perfektion."
),
"hints_on_exercise": (
"Kihon und Partnerübungen mit Technikbezug; reine Kraft-/Ausdauer-Inseln nur mit klarer Begründung."
),
"hints_on_path_qa": (
"Kohärente Progression Grundlagen → Anwendung → Vertiefung; "
"Übergänge ohne Sprünge; themenfremde Kraft-/Ausdauer-Inseln abwerten."
),
"anti_patterns": "Keine pauschale Perfektions-Stufe verlangen, wenn Kontext Breitensport ist.",
},
),
(
"focus_area",
"*",
{
"description": "Technik- oder Themen-Curriculum mit didaktisch aufeinander aufbauenden Stufen.",
"hints_on_progression": "Grundlagen vor Anwendung; moderate Sprünge zwischen Stufen vermeiden.",
"hints_on_path_qa": (
"Kohärente Progression zum Anfrage-Thema; "
"Lücken sind fehlende Zwischenstufen im Lernpfad, nicht fehlende Nebenthemen."
),
"hints_on_exercise": "Übungen mit klarem Bezug zum Pfad-Thema und zur Stufe.",
},
),
# --- training_type ---
(
"training_type",
"breitensport",
{
"description": (
"Partizipation, Verständlichkeit, Freude am Bewegen; weniger maximale Spezialisierung."
),
"hints_on_progression": "Moderater Schwierigkeitsanstieg; Perfektionsphasen optional.",
"hints_on_path_qa": (
"Hohe OK-Rate bei moderatem Schwierigkeitsanstieg; "
"„Perfektion“-Stufen nur optional, nicht als Pflicht-Lücke."
),
"rematch_guard": "Keine leeren Slots erzwingen, nur um eine Leistungs-Perfektionsstufe zu füllen.",
},
),
(
"training_type",
"leistungssport",
{
"description": "Leistungsorientiertes Training mit höherer Anspruchskurve und Spezialisierung.",
"hints_on_progression": "Belastungs- und Kombinationsprogressionen sind erwünscht.",
"hints_on_path_qa": (
"Höhere Anspruchskurven sind passend; Lücken in Spezialisierung können echte Hinweise sein."
),
},
),
(
"training_type",
"wettkampf",
{
"description": (
"Wettkampforientiertes Training mit höherer Anspruchskurve und belastungsnahen Phasen."
),
"hints_on_progression": "Anwendungs- und Druckphasen zeitig einplanen.",
"hints_on_path_qa": (
"Spezialisierung, Kombination und Belastung unter Druck sind relevant; "
"Lücken in Anwendungs- oder Perfektionsphasen können echte Hinweise sein."
),
},
),
(
"training_type",
"*",
{
"hints_on_path_qa": "Didaktische Kohärenz wichtiger als maximale Spezialisierung — Kontext beachten.",
},
),
# --- target_group ---
(
"target_group",
"kinder",
{
"description": (
"Kinder: kurze Einheiten, spielerische Einstiege, Sicherheit und altersgerechte Komplexität."
),
"hints_on_progression": "Spielerische Einstiege; kurze Abschnitte; Sicherheit vor Perfektion.",
"hints_on_path_qa": (
"Didaktik ohne Überforderung; klare Regeln und Sicherheit vor Perfektion; "
"Lücken bei Spiel-/Rollenelementen wichtiger als Wettkampftiefe."
),
"anti_patterns": "Keine Erwachsenen-Wettkampf-Perfektion als QS-Maßstab.",
},
),
(
"target_group",
"leistungssportler",
{
"description": "Leistungsgruppe: höhere Anspruchskurven und Spezialisierung sind fachlich passend.",
"hints_on_progression": "Anspruchskurve und Spezialisierung dürfen steiler sein.",
"hints_on_path_qa": (
"Höhere Anspruchskurven, Belastungs- und Kombinationsprogressionen sind relevant; "
"Lücken in Spezialisierung können echte Hinweise sein."
),
},
),
(
"target_group",
"breitensportler",
{
"description": "Breitensport: Partizipation und Verständlichkeit vor maximaler Spezialisierung.",
"hints_on_path_qa": (
"Moderate Progression; Perfektions-Lücken sind selten echte Mängel."
),
"anti_patterns": "Keine Leistungssport-Perfektion als Pflicht-Kriterium.",
},
),
(
"target_group",
"*",
{
"hints_on_path_qa": "Zielgruppe im Tempo und in der Komplexität berücksichtigen.",
},
),
# --- style_direction ---
(
"style_direction",
"shotokan",
{
"description": (
"Shotokan-Linie: klare Kihon-Struktur, Hüft- und Standarbeit als wiederkehrende Qualitätsanker."
),
"hints_on_progression": "Nuancen in Stellung und Hüfttechnik; kein neuer Planungstyp.",
"hints_on_path_qa": "Konsistenz von Stand, Hüfte und Kime entlang des Pfads bewerten.",
},
),
(
"style_direction",
"*",
{
"hints_on_progression": (
"Stil-spezifische Nuancen (Stand, Hüfte, Rhythmus) einbeziehen — ohne Stilwechsel zu erzwingen."
),
},
),
)
def normalize_catalog_name_key(name: str) -> str:
s = unicodedata.normalize("NFKD", (name or "").translate(_UMLAUT_MAP))
s = s.encode("ascii", "ignore").decode("ascii").lower()
s = re.sub(r"[^a-z0-9]+", "_", s).strip("_")
return s or "unknown"
def get_fallback_slots_for_entry(catalog_kind: str, name: str) -> SlotPack:
kind = (catalog_kind or "").strip().lower()
norm = normalize_catalog_name_key(name)
default: SlotPack = {}
for rule_kind, pattern, pack in _FALLBACK_RULES:
if rule_kind != kind:
continue
if pattern == "*":
default = dict(pack)
continue
if pattern in norm or norm.startswith(pattern) or pattern in (name or "").lower():
return dict(pack)
return default
def merge_stored_slots_with_fallbacks(
stored: Mapping[str, str],
*,
catalog_kind: str,
name: str,
stammdaten_description: str = "",
) -> Dict[str, str]:
"""DB + Stammdaten-Beschreibung + Namens-Fallback."""
fallbacks = get_fallback_slots_for_entry(catalog_kind, name)
out: Dict[str, str] = {}
for key in (
"description",
"hints_on_progression",
"hints_on_exercise",
"hints_on_path_qa",
"anti_patterns",
"rematch_guard",
):
if key == "description":
out[key] = (
(stored.get(key) or "").strip()
or (fallbacks.get(key) or "").strip()
or (stammdaten_description or "").strip()
)
else:
out[key] = (stored.get(key) or "").strip() or (fallbacks.get(key) or "").strip()
return out
__all__ = [
"get_fallback_slots_for_entry",
"merge_stored_slots_with_fallbacks",
"normalize_catalog_name_key",
]
+122 -1
View File
@@ -8,7 +8,9 @@
from __future__ import annotations from __future__ import annotations
import re import re
from html.parser import HTMLParser
from typing import FrozenSet, Optional, Set from typing import FrozenSet, Optional, Set
from html import escape as html_escape
from fastapi import HTTPException from fastapi import HTTPException
@@ -40,7 +42,126 @@ def normalize_inline_exercise_media_markup(html: Optional[str]) -> Optional[str]
f'class="shinkan-inline-media"></span>' f'class="shinkan-inline-media"></span>'
) )
return _BRACE_PATTERN.sub(_repl, html) return sanitize_exercise_rich_html(_BRACE_PATTERN.sub(_repl, html))
_ALLOWED_RICH_TAGS = frozenset(
{"p", "div", "br", "ul", "ol", "li", "h3", "b", "strong", "i", "em", "u", "span", "a"}
)
_DROP_WITH_CHILDREN = frozenset(
{"script", "iframe", "object", "embed", "style", "link", "meta", "svg", "math"}
)
_VOID_TAGS = frozenset({"br"})
_MEDIA_SIZES = frozenset({"small", "medium", "full"})
_CAPTION_MAX = 120
def _clean_caption(raw: str) -> str:
text = re.sub(r"[\u0000-\u001f\u007f]", " ", raw or "")
text = re.sub(r"[\"'`<>]", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return text[:_CAPTION_MAX]
def _safe_rich_attrs(tag: str, attrs: list[tuple[str, Optional[str]]]) -> list[tuple[str, str]]:
values = {}
for name, value in attrs:
if not name:
continue
values[name.lower()] = "" if value is None else str(value)
if tag == "a":
href = values.get("href", "").strip()
if href.lower().startswith(("http://", "https://")) and not re.search(r"[\u0000-\u001f\u007f]", href):
return [("href", href)]
return []
if tag != "span":
return []
media_id = values.get("data-shinkan-exercise-media", "").strip()
if not re.fullmatch(r"\d+", media_id):
return []
out = [("data-shinkan-exercise-media", media_id)]
size = values.get("data-shinkan-exercise-media-size", "").strip().lower()
if size in _MEDIA_SIZES:
out.append(("data-shinkan-exercise-media-size", size))
caption = _clean_caption(values.get("data-shinkan-exercise-media-caption", ""))
if caption:
out.append(("data-shinkan-exercise-media-caption", caption))
classes = [c for c in values.get("class", "").split() if c == "shinkan-inline-media"]
if classes:
out.append(("class", "shinkan-inline-media"))
return out
class _RichHtmlSanitizer(HTMLParser):
"""Baut erlaubtes Übungs-HTML neu auf. Unbekannte Tags fallen weg, ihr Text bleibt."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self._drop_depth = 0
self._stack: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
self._start(tag.lower(), attrs, void=False)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
self._start(tag.lower(), attrs, void=True)
def _start(self, tag: str, attrs: list[tuple[str, Optional[str]]], *, void: bool) -> None:
if self._drop_depth:
if not void and tag not in _VOID_TAGS:
self._drop_depth += 1
return
if tag in _DROP_WITH_CHILDREN:
if not void:
self._drop_depth = 1
return
if tag not in _ALLOWED_RICH_TAGS:
return
safe = _safe_rich_attrs(tag, attrs)
rendered = tag
if safe:
rendered += "".join(f' {name}="{html_escape(value, quote=True)}"' for name, value in safe)
if void or tag in _VOID_TAGS:
self.parts.append(f"<{rendered}>")
return
self._stack.append(tag)
self.parts.append(f"<{rendered}>")
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if self._drop_depth:
if tag in _DROP_WITH_CHILDREN or self._drop_depth > 1:
self._drop_depth = max(0, self._drop_depth - 1)
return
if self._stack and self._stack[-1] == tag:
self._stack.pop()
self.parts.append(f"</{tag}>")
def handle_data(self, data: str) -> None:
if self._drop_depth or not data:
return
self.parts.append(html_escape(data))
def handle_entityref(self, name: str) -> None:
self.handle_data(f"&{name};")
def handle_charref(self, name: str) -> None:
self.handle_data(f"&#{name};")
def sanitize_exercise_rich_html(html: Optional[str]) -> Optional[str]:
"""Allowlist für gespeichertes Übungs-HTML. Skripte, Handler und fremde Attribute fallen weg."""
if html is None:
return None
if not isinstance(html, str):
html = str(html)
if not html.strip():
return html
parser = _RichHtmlSanitizer()
parser.feed(html)
parser.close()
return "".join(parser.parts)
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]: def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
+3 -2
View File
@@ -243,7 +243,7 @@ def read_root():
return out return out
# Register routers # Register routers
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin
app.include_router(auth.router) app.include_router(auth.router)
app.include_router(profiles.router) app.include_router(profiles.router)
@@ -269,6 +269,7 @@ app.include_router(dashboard.router)
app.include_router(training_modules.router) app.include_router(training_modules.router)
app.include_router(training_framework_programs.router) app.include_router(training_framework_programs.router)
app.include_router(catalogs.router) app.include_router(catalogs.router)
app.include_router(catalog_prompt_slots.router)
app.include_router(maturity_models.router) app.include_router(maturity_models.router)
app.include_router(matrix_stack_bundle.router) app.include_router(matrix_stack_bundle.router)
app.include_router(matrix_editor.router) app.include_router(matrix_editor.router)
@@ -281,7 +282,7 @@ app.include_router(ai_skill_retrieval_admin.router)
app.include_router(exercise_enrichment_admin.router) app.include_router(exercise_enrichment_admin.router)
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad # Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>). # GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken).
# Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/ # Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")) _media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
Path(_media_dir).mkdir(parents=True, exist_ok=True) Path(_media_dir).mkdir(parents=True, exist_ok=True)
+49
View File
@@ -0,0 +1,49 @@
"""Kurzlebige Medien-Tokens. Kein Sitzungstoken — nur für Dateiabruf per Query."""
from __future__ import annotations
import hashlib
import hmac
import os
import time
from typing import Optional
MEDIA_GRANT_TTL_SECONDS = 600
_PREFIX = "mg1"
def _key() -> bytes:
dedicated = (os.getenv("MEDIA_TOKEN_SECRET") or "").strip()
if dedicated:
return hashlib.sha256(dedicated.encode("utf-8")).digest()
material = (os.getenv("DB_PASSWORD") or "shinkan-dev-media").encode("utf-8")
return hashlib.sha256(b"shinkan-media-grant-v1|" + material).digest()
def issue_media_grant(profile_id: int, *, ttl_seconds: int = MEDIA_GRANT_TTL_SECONDS) -> tuple[str, int]:
exp = int(time.time()) + int(ttl_seconds)
payload = f"{int(profile_id)}.{exp}"
sig = hmac.new(_key(), payload.encode("ascii"), hashlib.sha256).hexdigest()
return f"{_PREFIX}.{payload}.{sig}", exp
def profile_id_from_media_grant(token: Optional[str], *, now: Optional[int] = None) -> Optional[int]:
if not token or not token.startswith(f"{_PREFIX}."):
return None
parts = token.split(".")
if len(parts) != 4:
return None
_, pid_s, exp_s, sig = parts
if not pid_s.isdigit() or not exp_s.isdigit():
return None
payload = f"{pid_s}.{exp_s}"
expected = hmac.new(_key(), payload.encode("ascii"), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig):
return None
exp = int(exp_s)
moment = int(time.time() if now is None else now)
if exp < moment:
return None
pid = int(pid_s)
if pid < 1:
return None
return pid
@@ -0,0 +1,172 @@
-- Migration 091: Planungs-KI H1 — Katalog-Guidance-Platzhalter in Progressions-Prompts
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
Ziel-Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
Schritte (JSON): {{steps_json}}
Erkannte Lücken: {{gaps_json}}
Eingefügte Brücken: {{bridge_inserts_json}}
{{catalog_guidance_block}}
{{catalog_context_json}}
Wichtig: Wenn Katalog-Kontext gesetzt ist, haben dessen QS-Kriterien Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
Prüfe:
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
5. Fehlen wichtige Zwischenschritte (Kraft, Geschwindigkeit, Anwendung, Perfektion)?
6. Gibt es Schritte ohne Bezug zum Hauptthema (z. B. reine Kraftübungen bei einer Technik)?
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes (beste didaktische Reihenfolge).
Nur Indizes aus dem steps_json verwenden — Länge muss exakt der Schrittzahl entsprechen.
Wenn wichtige Zwischenschritte fehlen oder Schritte themenfremd sind: suggested_new_exercises mit konkreten Übungs-Ideen (Titel + Kurzskizze), jeweils mit insert_after_step_index (0-basiert: nach welchem Schritt einfügen).
Antworte NUR mit JSON:
{
"overall_ok": true,
"quality_score": 0.85,
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
"ordered_step_indices": [0, 1, 2, 3],
"issues": ["…"],
"sequence_notes": ["…"],
"recommendations": ["…"],
"suggested_new_exercises": [
{
"title_hint": "Mae Geri Kraftentwicklung am Sandsack",
"sketch": "Gezielte Kraft- und Schnelligkeitsentwicklung für Mae Geri …",
"phase": "vertiefung",
"insert_after_step_index": 2,
"rationale": "Schließt Lücke zwischen Grundlagen und Gleichgewichtstritt"
}
]
}$t$,
default_template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
Ziel-Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
Schritte (JSON): {{steps_json}}
Erkannte Lücken: {{gaps_json}}
Eingefügte Brücken: {{bridge_inserts_json}}
{{catalog_guidance_block}}
{{catalog_context_json}}
Wichtig: Wenn Katalog-Kontext gesetzt ist, haben dessen QS-Kriterien Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
Prüfe:
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
5. Fehlen wichtige Zwischenschritte (Kraft, Geschwindigkeit, Anwendung, Perfektion)?
6. Gibt es Schritte ohne Bezug zum Hauptthema (z. B. reine Kraftübungen bei einer Technik)?
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes (beste didaktische Reihenfolge).
Nur Indizes aus dem steps_json verwenden — Länge muss exakt der Schrittzahl entsprechen.
Wenn wichtige Zwischenschritte fehlen oder Schritte themenfremd sind: suggested_new_exercises mit konkreten Übungs-Ideen (Titel + Kurzskizze), jeweils mit insert_after_step_index (0-basiert: nach welchem Schritt einfügen).
Antworte NUR mit JSON:
{
"overall_ok": true,
"quality_score": 0.85,
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
"ordered_step_indices": [0, 1, 2, 3],
"issues": ["…"],
"sequence_notes": ["…"],
"recommendations": ["…"],
"suggested_new_exercises": [
{
"title_hint": "Mae Geri Kraftentwicklung am Sandsack",
"sketch": "Gezielte Kraft- und Schnelligkeitsentwicklung für Mae Geri …",
"phase": "vertiefung",
"insert_after_step_index": 2,
"rationale": "Schließt Lücke zwischen Grundlagen und Gleichgewichtstritt"
}
]
}$t$
WHERE slug = 'planning_exercise_path_qa';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und analysierst eine Anfrage für einen Progressionsgraphen.
Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
{{catalog_guidance_block}}
Wichtig: Keine Gruppenanalyse — nur didaktischer Pfad für die Technik/das Thema.
Antworte NUR mit JSON:
{
"primary_topic": "Mae Geri",
"start_assumption": "Welche Voraussetzungen werden für den Einstieg angenommen",
"target_state": "Konkreter Zielzustand der Progression",
"success_criteria": ["messbare Kriterien"],
"constraints": { "partner_required": false }
}$t$,
default_template = template
WHERE slug = 'planning_progression_goal_analysis';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und erstellst eine didaktische Roadmap für einen Progressionsgraphen.
Anfrage: {{goal_query}}
Zielanalyse: {{goal_analysis_json}}
Semantic Brief: {{semantic_brief_json}}
Anzahl Major Steps (N): {{max_steps}}
{{catalog_guidance_block}}
{{catalog_context_json}}
Erzeuge zuerst 8–12 micro_objectives (phase, title, weight, depends_on), dann konsolidiere auf genau N major_steps.
Phasen: einstieg, grundlage, vertiefung, anwendung, perfektion — in sinnvoller Reihenfolge (Grundlagen vor Perfektion).
Beachte Katalog-Roadmap-Hinweise, falls gesetzt.
Antworte NUR mit JSON:
{
"micro_objectives": [
{ "id": "m1", "phase": "grundlage", "title": "…", "weight": 0.9, "depends_on": [] }
],
"major_steps": [
{ "index": 0, "phase": "grundlage", "learning_goal": "…", "consolidates": ["m1","m2"], "rationale": "…" }
],
"consolidation_notes": ["…"]
}$t$,
default_template = template
WHERE slug = 'planning_progression_roadmap';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
Anfrage: {{goal_query}}
Zielanalyse: {{goal_analysis_json}}
Major Steps: {{major_steps_json}}
{{catalog_guidance_block}}
{{catalog_context_json}}
Für jeden Major Step: messbares Lernziel, load_profile (z. B. koordination, präzision, kraft), exercise_type (kihon_einzel, partner_drill, kombination, kraft_auxiliary), success_criteria, anti_patterns (z. B. reine Kraft ohne Technikbezug).
Beachte Katalog-QS-Kriterien und Anti-Patterns, falls gesetzt.
Antworte NUR mit JSON:
{
"stage_specs": [
{
"major_step_index": 0,
"learning_goal": "…",
"load_profile": ["koordination", "gleichgewicht"],
"exercise_type": "kihon_einzel",
"success_criteria": ["…"],
"anti_patterns": ["…"]
}
]
}$t$,
default_template = template
WHERE slug = 'planning_progression_stage_spec';
@@ -0,0 +1,86 @@
-- Migration 092: Katalog-Prompt-Slots (H2) — Slot-Typ-Vokabular + leere Wertetabelle
-- Keine Inhalts-Seeds: Stammdaten (Primärfokus etc.) sind mandantenspezifisch.
-- Slot-Inhalte: Admin-UI oder catalog_slot_fallbacks.py (Namens-Match zur Laufzeit).
CREATE TABLE IF NOT EXISTS catalog_prompt_slot_types (
slot_key VARCHAR(64) PRIMARY KEY,
display_name VARCHAR(200) NOT NULL,
description TEXT,
applicable_kinds TEXT[] NOT NULL DEFAULT '{}',
sort_order INT DEFAULT 99,
for_llm BOOLEAN NOT NULL DEFAULT true,
for_code BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS catalog_prompt_slots (
id SERIAL PRIMARY KEY,
catalog_kind VARCHAR(32) NOT NULL,
catalog_id INT NOT NULL,
slot_key VARCHAR(64) NOT NULL REFERENCES catalog_prompt_slot_types(slot_key) ON DELETE CASCADE,
content TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE (catalog_kind, catalog_id, slot_key)
);
CREATE INDEX IF NOT EXISTS idx_catalog_prompt_slots_kind_id
ON catalog_prompt_slots (catalog_kind, catalog_id);
INSERT INTO catalog_prompt_slot_types (slot_key, display_name, description, applicable_kinds, sort_order, for_llm, for_code)
VALUES
(
'description',
'Allgemeine Beschreibung',
'Fachliche Einordnung des Katalog-Eintrags für Planungs-KI.',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
10,
true,
false
),
(
'hints_on_progression',
'Hinweise Progressionsgraph',
'Didaktik für Roadmap, Major Steps und Stufenspezifikation.',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
20,
true,
false
),
(
'hints_on_exercise',
'Hinweise Übungsanlage',
'Kontext für Gap-Fill, Übungs-KI und Schnellanlage.',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
30,
true,
false
),
(
'hints_on_path_qa',
'Hinweise Pfad-QS',
'Bewertungsmaßstäbe für Pfad-Qualitätssicherung.',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
40,
true,
false
),
(
'anti_patterns',
'Anti-Patterns',
'Explizite Fehlbewertungen vermeiden.',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
50,
true,
false
),
(
'rematch_guard',
'Rematch-Guard',
'Wann kein Auto-Rematch sinnvoll ist (primär Code-Logik).',
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
60,
false,
true
)
ON CONFLICT (slot_key) DO NOTHING;
@@ -0,0 +1,199 @@
-- Migration 093: Planungs-KI — granulare Katalog-Slot-Platzhalter in Prompt-Templates
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
Ziel-Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
Schritte (JSON): {{steps_json}}
Erkannte Lücken: {{gaps_json}}
Eingefügte Brücken: {{bridge_inserts_json}}
Katalog-Kontext für Bewertung (Trainer-Auswahl — leere Zeilen ignorieren):
Primärfokus:
{{focus_area_description}}
QS: {{focus_area_hints_on_path_qa}}
Vermeiden: {{focus_area_anti_patterns}}
Trainingsstil:
{{training_type_description}}
QS: {{training_type_hints_on_path_qa}}
Zielgruppe:
{{target_group_description}}
QS: {{target_group_hints_on_path_qa}}
Stilrichtung:
{{style_direction_description}}
QS: {{style_direction_hints_on_path_qa}}
{{catalog_context_json}}
Wichtig: Wenn Katalog-Slots gesetzt sind, haben diese Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
Prüfe:
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
5. Fehlen wichtige Zwischenschritte — gemäß Katalog-QS-Hinweisen, nicht pauschal „Perfektion“?
6. Gibt es Schritte ohne Bezug zum Hauptthema?
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes.
Wenn wichtige Zwischenschritte fehlen: suggested_new_exercises mit Titel + Kurzskizze und insert_after_step_index.
Antworte NUR mit JSON:
{
"overall_ok": true,
"quality_score": 0.85,
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
"ordered_step_indices": [0, 1, 2, 3],
"issues": ["…"],
"sequence_notes": ["…"],
"recommendations": ["…"],
"suggested_new_exercises": []
}$t$,
default_template = template
WHERE slug = 'planning_exercise_path_qa';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und analysierst eine Anfrage für einen Progressionsgraphen.
Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
Katalog-Kontext (Primärfokus / Trainingsstil / Zielgruppe / Stil — leere Zeilen ignorieren):
Primärfokus: {{focus_area_description}}
Progression: {{focus_area_hints_on_progression}}
Trainingsstil: {{training_type_description}}
Progression: {{training_type_hints_on_progression}}
Zielgruppe: {{target_group_description}}
Stilrichtung: {{style_direction_description}}
Wichtig: Keine Gruppenanalyse — nur didaktischer Pfad. Katalog-Hinweise beachten.
Antworte NUR mit JSON:
{
"primary_topic": "Mae Geri",
"start_assumption": "Welche Voraussetzungen werden für den Einstieg angenommen",
"target_state": "Konkreter Zielzustand der Progression",
"success_criteria": ["messbare Kriterien"],
"constraints": { "partner_required": false }
}$t$,
default_template = template
WHERE slug = 'planning_progression_goal_analysis';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und erstellst eine didaktische Roadmap für einen Progressionsgraphen.
Anfrage: {{goal_query}}
Zielanalyse: {{goal_analysis_json}}
Semantic Brief: {{semantic_brief_json}}
Anzahl Major Steps (N): {{max_steps}}
Katalog-Kontext für Stufenlogik:
Primärfokus:
{{focus_area_description}}
Roadmap: {{focus_area_hints_on_progression}}
Vermeiden: {{focus_area_anti_patterns}}
Trainingsstil:
{{training_type_description}}
Roadmap: {{training_type_hints_on_progression}}
Zielgruppe:
{{target_group_description}}
Roadmap: {{target_group_hints_on_progression}}
Stilrichtung:
{{style_direction_description}}
Roadmap: {{style_direction_hints_on_progression}}
{{catalog_context_json}}
Erzeuge zuerst 8–12 micro_objectives, dann konsolidiere auf genau N major_steps.
Phasen: einstieg, grundlage, vertiefung, anwendung, perfektion — Katalog-Roadmap-Hinweise beachten.
Antworte NUR mit JSON:
{
"micro_objectives": [
{ "id": "m1", "phase": "grundlage", "title": "…", "weight": 0.9, "depends_on": [] }
],
"major_steps": [
{ "index": 0, "phase": "grundlage", "learning_goal": "…", "consolidates": ["m1","m2"], "rationale": "…" }
],
"consolidation_notes": ["…"]
}$t$,
default_template = template
WHERE slug = 'planning_progression_roadmap';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
Anfrage: {{goal_query}}
Zielanalyse: {{goal_analysis_json}}
Major Steps: {{major_steps_json}}
Intent-Kontext: {{intent_context_json}}
Semantic Brief: {{semantic_brief_json}}
Katalog-Kontext je Stufe:
Primärfokus — Progression: {{focus_area_hints_on_progression}}
Primärfokus — Vermeiden: {{focus_area_anti_patterns}}
Trainingsstil — Progression: {{training_type_hints_on_progression}}
Trainingsstil — Vermeiden: {{training_type_anti_patterns}}
Zielgruppe — Progression: {{target_group_hints_on_progression}}
Zielgruppe — Vermeiden: {{target_group_anti_patterns}}
Stilrichtung — Progression: {{style_direction_hints_on_progression}}
{{catalog_context_json}}
Für jeden Major Step: messbares Lernziel, load_profile, exercise_type, success_criteria, anti_patterns — Katalog-Slots beachten.
Antworte NUR mit JSON:
{
"stage_specs": [
{
"major_step_index": 0,
"learning_goal": "…",
"load_profile": ["koordination", "gleichgewicht"],
"exercise_type": "kihon_einzel",
"success_criteria": ["…"],
"anti_patterns": ["…"]
}
]
}$t$,
default_template = template
WHERE slug = 'planning_progression_stage_spec';
UPDATE ai_prompts
SET template = $t$Du bist Assistent für Kampfsport-Trainer und extrahierst Start, Ziel und Ergänzungen für einen Progressionsgraphen.
Anfrage: {{goal_query}}
Semantic Brief: {{semantic_brief_json}}
Trainer-Notizen: {{user_notes}}
Katalog-Einordnung:
Primärfokus: {{focus_area_description}}
Trainingsstil: {{training_type_description}}
Zielgruppe: {{target_group_description}}
Antworte NUR mit JSON:
{
"primary_topic": "…",
"start_situation": "…",
"target_state": "…",
"roadmap_notes": "…",
"extraction_notes": "…"
}$t$,
default_template = template
WHERE slug = 'planning_progression_start_target';
@@ -0,0 +1,11 @@
-- Migration 094: bewusst ohne Daten-Seed (ersetzt frühere Voll-Befüllung)
--
-- Katalog-Stammdaten (Primärfokus, Trainingsstile, …) sind pro Umgebung unterschiedlich.
-- Migrationen dürfen keine Dev-Standardtexte an Prod-Kataloge hängen.
--
-- Slot-Inhalte stattdessen:
-- • Admin-UI (catalog_prompt_slots pro Eintrag)
-- • Laufzeit-Fallback catalog_slot_fallbacks.py (Namens-Match, kein DB-Schreiben)
-- • optional: backend/scripts/seed_catalog_prompt_slots_dev.py (nur lokale Dev-DB)
SELECT 1;
@@ -0,0 +1,7 @@
-- Migration 095: Entfernt per 092/094 (alte Version) eingespielte Standard-Slot-Texte
--
-- Betrifft Dev-Umgebungen, die die frühen Seed-Migrationen bereits erhalten haben.
-- Prod mit eigener Katalogstruktur: Tabelle bleibt leer bis Admin-Inhalte gepflegt werden.
-- Manuell in der Admin-UI gesetzte Texte nach 095 bitte erneut prüfen (waren ggf. identisch mit Seeds).
DELETE FROM catalog_prompt_slots;
@@ -0,0 +1,29 @@
-- Login-Sperre, Sitzungszweck (Vollzugriff / 2FA-Einrichtung / 2FA-Challenge), TOTP.
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS failed_login_count INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS locked_until TIMESTAMP,
ADD COLUMN IF NOT EXISTS totp_secret TEXT,
ADD COLUMN IF NOT EXISTS totp_pending_secret TEXT,
ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE sessions
ADD COLUMN IF NOT EXISTS purpose VARCHAR(32) NOT NULL DEFAULT 'full',
ADD COLUMN IF NOT EXISTS failed_attempts INTEGER NOT NULL DEFAULT 0;
UPDATE sessions
SET purpose = 'password_reset'
WHERE token LIKE 'reset_%' AND purpose = 'full';
CREATE INDEX IF NOT EXISTS idx_sessions_profile_purpose ON sessions (profile_id, purpose);
CREATE TABLE IF NOT EXISTS profile_recovery_codes (
id SERIAL PRIMARY KEY,
profile_id INTEGER NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
code_hash VARCHAR(64) NOT NULL,
used_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_profile_recovery_codes_profile
ON profile_recovery_codes (profile_id);
+25 -3
View File
@@ -13,16 +13,38 @@ from datetime import date, time, datetime
class LoginRequest(BaseModel): class LoginRequest(BaseModel):
email: EmailStr email: EmailStr
password: str password: str = Field(min_length=1, max_length=128)
class LoginTotpRequest(BaseModel):
challenge_token: str = Field(min_length=8, max_length=200)
code: str = Field(min_length=6, max_length=32)
class ChangePasswordRequest(BaseModel):
current_password: str = Field(min_length=1, max_length=128)
new_password: str = Field(min_length=8, max_length=128)
class TotpCodeRequest(BaseModel):
code: str = Field(min_length=6, max_length=12)
class TotpDisableRequest(BaseModel):
current_password: str = Field(min_length=1, max_length=128)
code: str = Field(min_length=6, max_length=32)
class RegisterRequest(BaseModel): class RegisterRequest(BaseModel):
email: EmailStr email: EmailStr
password: str password: str = Field(min_length=1, max_length=128)
name: Optional[str] = None name: Optional[str] = None
requested_club_id: Optional[int] = Field(default=None, ge=1) requested_club_id: Optional[int] = Field(default=None, ge=1)
class PasswordResetRequest(BaseModel): class PasswordResetRequest(BaseModel):
email: str email: EmailStr
class ResendVerificationRequest(BaseModel):
email: EmailStr
class PasswordResetConfirm(BaseModel): class PasswordResetConfirm(BaseModel):
token: str token: str
+7
View File
@@ -196,6 +196,13 @@ def openrouter_chat_completion(
cc, cc,
) )
try:
from planning_llm_usage import record_planning_llm_call
record_planning_llm_call(1)
except Exception:
pass
return joined return joined
+3 -2
View File
@@ -33,8 +33,8 @@ def insert_password_reset_session(cur: Any, profile_id: int, *, hours_valid: int
expires = datetime.now() + timedelta(hours=hours_valid) expires = datetime.now() + timedelta(hours=hours_valid)
cur.execute( cur.execute(
""" """
INSERT INTO sessions (token, profile_id, expires_at, created_at) INSERT INTO sessions (token, profile_id, expires_at, created_at, purpose)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP) VALUES (%s, %s, %s, CURRENT_TIMESTAMP, 'password_reset')
""", """,
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()), (f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
) )
@@ -53,6 +53,7 @@ Neues Passwort setzen:
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden. Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
Der Link meldet dich nicht an und schaltet die Zwei-Faktor-Anmeldung nicht ab.
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert. Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
@@ -0,0 +1,16 @@
"""
Katalog-Prompt-Snippets — Abwärtskompatibilität (H1-Importpfade).
Implementierung: catalog_prompt_slots.py (H2).
"""
from catalog_prompt_slots import (
build_catalog_guidance_for_prompt,
get_rematch_guard_for_catalog,
pick_active_catalog_item,
)
__all__ = [
"build_catalog_guidance_for_prompt",
"get_rematch_guard_for_catalog",
"pick_active_catalog_item",
]
+30
View File
@@ -19,6 +19,8 @@ from planning_exercise_form_context import (
prior_path_steps_before_major, prior_path_steps_before_major,
) )
from planning_exercise_semantics import PlanningSemanticBrief, brief_to_summary_dict from planning_exercise_semantics import PlanningSemanticBrief, brief_to_summary_dict
from planning_catalog_context import ProgressionPlanningCatalogContext
from planning_prompt_variables import catalog_exercise_hints_block
_logger = logging.getLogger("shinkan.planning_exercise_path_ai_fill") _logger = logging.getLogger("shinkan.planning_exercise_path_ai_fill")
@@ -54,6 +56,7 @@ def _build_stage_ai_context(
step_after: Optional[Mapping[str, Any]] = None, step_after: Optional[Mapping[str, Any]] = None,
prior_steps: Optional[Sequence[Mapping[str, Any]]] = None, prior_steps: Optional[Sequence[Mapping[str, Any]]] = None,
start_situation: Optional[str] = None, start_situation: Optional[str] = None,
catalog_exercise_hints: Optional[str] = None,
) -> ExerciseFormAiPromptContext: ) -> ExerciseFormAiPromptContext:
"""KI-Kontext für unbesetzte Roadmap-Stufe (keine Brücke zwischen falschen Array-Indizes).""" """KI-Kontext für unbesetzte Roadmap-Stufe (keine Brücke zwischen falschen Array-Indizes)."""
gap = dict(spec.get("gap") or {}) gap = dict(spec.get("gap") or {})
@@ -97,6 +100,9 @@ def _build_stage_ai_context(
sketch = (spec.get("sketch") or "").strip() sketch = (spec.get("sketch") or "").strip()
if sketch and sketch != learning_goal: if sketch and sketch != learning_goal:
goal_parts.extend(["", f"Kontext: {sketch}"]) goal_parts.extend(["", f"Kontext: {sketch}"])
hints = (catalog_exercise_hints or "").strip()
if hints:
goal_parts.extend(["", "Katalog-Hinweise Übungsanlage:", hints])
goal = "\n".join(goal_parts) goal = "\n".join(goal_parts)
focus_hint = topic if brief.topic_type == "technique" else None focus_hint = topic if brief.topic_type == "technique" else None
@@ -118,6 +124,7 @@ def try_suggest_ai_stage_step(
brief: PlanningSemanticBrief, brief: PlanningSemanticBrief,
spec: Mapping[str, Any], spec: Mapping[str, Any],
steps: Sequence[Mapping[str, Any]], steps: Sequence[Mapping[str, Any]],
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Optional[Dict[str, Any]]: ) -> Optional[Dict[str, Any]]:
"""KI-Vorschlag für leere Roadmap-Stufe.""" """KI-Vorschlag für leere Roadmap-Stufe."""
major_idx = spec.get("roadmap_major_step_index") major_idx = spec.get("roadmap_major_step_index")
@@ -136,6 +143,8 @@ def try_suggest_ai_stage_step(
if not gap.get("learning_goal"): if not gap.get("learning_goal"):
gap["learning_goal"] = spec.get("title_hint") or spec.get("sketch") gap["learning_goal"] = spec.get("title_hint") or spec.get("sketch")
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
ctx = _build_stage_ai_context( ctx = _build_stage_ai_context(
goal_query=goal_query, goal_query=goal_query,
brief=brief, brief=brief,
@@ -143,6 +152,7 @@ def try_suggest_ai_stage_step(
step_before=step_before, step_before=step_before,
step_after=step_after, step_after=step_after,
prior_steps=prior_steps, prior_steps=prior_steps,
catalog_exercise_hints=exercise_hints or None,
) )
try: try:
ai_payload = run_exercise_form_ai_suggestion(cur, ctx=ctx) ai_payload = run_exercise_form_ai_suggestion(cur, ctx=ctx)
@@ -189,6 +199,7 @@ def _build_gap_ai_context(
gap: Mapping[str, Any], gap: Mapping[str, Any],
title_hint: Optional[str] = None, title_hint: Optional[str] = None,
sketch_hint: Optional[str] = None, sketch_hint: Optional[str] = None,
catalog_exercise_hints: Optional[str] = None,
) -> ExerciseFormAiPromptContext: ) -> ExerciseFormAiPromptContext:
topic = (brief.primary_topic or "Technik").strip() topic = (brief.primary_topic or "Technik").strip()
phase = gap.get("expected_phase") or "vertiefung" phase = gap.get("expected_phase") or "vertiefung"
@@ -206,6 +217,9 @@ def _build_gap_ai_context(
] ]
if sketch: if sketch:
goal_parts.extend(["", f"Hinweis: {sketch}"]) goal_parts.extend(["", f"Hinweis: {sketch}"])
hints = (catalog_exercise_hints or "").strip()
if hints:
goal_parts.extend(["", "Katalog-Hinweise Übungsanlage:", hints])
goal = "\n".join(goal_parts) goal = "\n".join(goal_parts)
focus_hint = topic if brief.topic_type == "technique" else None focus_hint = topic if brief.topic_type == "technique" else None
@@ -271,8 +285,10 @@ def try_suggest_ai_bridge_step(
gap: Mapping[str, Any], gap: Mapping[str, Any],
title_hint: Optional[str] = None, title_hint: Optional[str] = None,
sketch_hint: Optional[str] = None, sketch_hint: Optional[str] = None,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Optional[Dict[str, Any]]: ) -> Optional[Dict[str, Any]]:
"""Ruft exercise AI suggest auf — kein Speichern in DB.""" """Ruft exercise AI suggest auf — kein Speichern in DB."""
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
ctx = _build_gap_ai_context( ctx = _build_gap_ai_context(
goal_query=goal_query, goal_query=goal_query,
brief=brief, brief=brief,
@@ -281,6 +297,7 @@ def try_suggest_ai_bridge_step(
gap=gap, gap=gap,
title_hint=title_hint, title_hint=title_hint,
sketch_hint=sketch_hint, sketch_hint=sketch_hint,
catalog_exercise_hints=exercise_hints or None,
) )
g_plain = strip_html_to_plain(ctx.goal) g_plain = strip_html_to_plain(ctx.goal)
if not g_plain.strip() and not (ctx.title or "").strip(): if not g_plain.strip() and not (ctx.title or "").strip():
@@ -478,6 +495,7 @@ def build_gap_fill_goal_text(
step_a: Optional[Mapping[str, Any]] = None, step_a: Optional[Mapping[str, Any]] = None,
step_b: Optional[Mapping[str, Any]] = None, step_b: Optional[Mapping[str, Any]] = None,
roadmap_snapshot: Optional[Mapping[str, Any]] = None, roadmap_snapshot: Optional[Mapping[str, Any]] = None,
catalog_exercise_hints: Optional[str] = None,
) -> str: ) -> str:
"""Ausführlicher Zieltext für KI-Neuanlage aus Pfad-, Roadmap- und Stufen-Kontext.""" """Ausführlicher Zieltext für KI-Neuanlage aus Pfad-, Roadmap- und Stufen-Kontext."""
topic = (brief.primary_topic or "Technik").strip() topic = (brief.primary_topic or "Technik").strip()
@@ -555,6 +573,9 @@ def build_gap_fill_goal_text(
parts.append(f"Qualitätsprüfung: {spec['rationale']}") parts.append(f"Qualitätsprüfung: {spec['rationale']}")
if spec.get("sketch"): if spec.get("sketch"):
parts.append(f"Skizze: {spec['sketch']}") parts.append(f"Skizze: {spec['sketch']}")
hints = (catalog_exercise_hints or "").strip()
if hints:
parts.append(f"Katalog-Hinweise Übungsanlage:\n{hints}")
parts.append( parts.append(
"Die Übung muss die Stufe didaktisch erfüllen: klare Voraussetzungen, messbares Stufenziel, " "Die Übung muss die Stufe didaktisch erfüllen: klare Voraussetzungen, messbares Stufenziel, "
"Bezug zum Gesamtpfad — keine generische Kraftübung ohne Technikbezug. " "Bezug zum Gesamtpfad — keine generische Kraftübung ohne Technikbezug. "
@@ -571,6 +592,7 @@ def build_gap_fill_offer(
brief: Optional[PlanningSemanticBrief] = None, brief: Optional[PlanningSemanticBrief] = None,
proposal: Optional[Mapping[str, Any]] = None, proposal: Optional[Mapping[str, Any]] = None,
roadmap_snapshot: Optional[Mapping[str, Any]] = None, roadmap_snapshot: Optional[Mapping[str, Any]] = None,
catalog_exercise_hints: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
source = spec.get("source") source = spec.get("source")
idx = int(spec.get("insert_after_index") or 0) idx = int(spec.get("insert_after_index") or 0)
@@ -603,6 +625,7 @@ def build_gap_fill_offer(
step_a=step_a, step_a=step_a,
step_b=step_b, step_b=step_b,
roadmap_snapshot=enriched_snapshot or None, roadmap_snapshot=enriched_snapshot or None,
catalog_exercise_hints=catalog_exercise_hints,
) )
ctx_preview = enriched_snapshot or None ctx_preview = enriched_snapshot or None
offer: Dict[str, Any] = { offer: Dict[str, Any] = {
@@ -642,6 +665,7 @@ def apply_gap_fill_after_qa(
max_ai_proposals: int = 3, max_ai_proposals: int = 3,
auto_insert_proposals: bool = False, auto_insert_proposals: bool = False,
roadmap_snapshot: Optional[Mapping[str, Any]] = None, roadmap_snapshot: Optional[Mapping[str, Any]] = None,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
""" """
Erzeugt gap_fill_offers für die UI; optional KI-Vorschläge einfügen. Erzeugt gap_fill_offers für die UI; optional KI-Vorschläge einfügen.
@@ -653,6 +677,7 @@ def apply_gap_fill_after_qa(
out = list(steps) out = list(steps)
proposals: List[Dict[str, Any]] = [] proposals: List[Dict[str, Any]] = []
offers: List[Dict[str, Any]] = [] offers: List[Dict[str, Any]] = []
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
for spec in specs: for spec in specs:
source = spec.get("source") source = spec.get("source")
@@ -666,6 +691,7 @@ def apply_gap_fill_after_qa(
brief=brief, brief=brief,
spec=spec, spec=spec,
steps=out, steps=out,
catalog=catalog,
) )
offer = build_gap_fill_offer( offer = build_gap_fill_offer(
spec=spec, spec=spec,
@@ -674,6 +700,7 @@ def apply_gap_fill_after_qa(
brief=brief, brief=brief,
proposal=proposal, proposal=proposal,
roadmap_snapshot=roadmap_snapshot, roadmap_snapshot=roadmap_snapshot,
catalog_exercise_hints=exercise_hints or None,
) )
offers.append(offer) offers.append(offer)
if proposal and auto_insert_proposals: if proposal and auto_insert_proposals:
@@ -700,6 +727,7 @@ def apply_gap_fill_after_qa(
brief=brief, brief=brief,
proposal=None, proposal=None,
roadmap_snapshot=roadmap_snapshot, roadmap_snapshot=roadmap_snapshot,
catalog_exercise_hints=exercise_hints or None,
) )
offers.append(offer) offers.append(offer)
continue continue
@@ -719,6 +747,7 @@ def apply_gap_fill_after_qa(
gap=gap, gap=gap,
title_hint=str(spec.get("title_hint") or ""), title_hint=str(spec.get("title_hint") or ""),
sketch_hint=str(spec.get("sketch") or ""), sketch_hint=str(spec.get("sketch") or ""),
catalog=catalog,
) )
offer = build_gap_fill_offer( offer = build_gap_fill_offer(
@@ -728,6 +757,7 @@ def apply_gap_fill_after_qa(
brief=brief, brief=brief,
proposal=proposal, proposal=proposal,
roadmap_snapshot=roadmap_snapshot, roadmap_snapshot=roadmap_snapshot,
catalog_exercise_hints=exercise_hints or None,
) )
offers.append(offer) offers.append(offer)
File diff suppressed because it is too large. Load diff
+218 -19
View File
@@ -9,6 +9,8 @@ import re
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
from planning_catalog_context import ProgressionPlanningCatalogContext
from planning_prompt_variables import merge_planning_prompt_variables
from exercise_ai import strip_html_to_plain from exercise_ai import strip_html_to_plain
from openrouter_chat import ( from openrouter_chat import (
effective_openrouter_model_for_prompt_row, effective_openrouter_model_for_prompt_row,
@@ -320,6 +322,7 @@ def try_llm_qa_progression_path(
steps: Sequence[Mapping[str, Any]], steps: Sequence[Mapping[str, Any]],
gaps: Sequence[Mapping[str, Any]], gaps: Sequence[Mapping[str, Any]],
bridge_inserts: Sequence[Mapping[str, Any]], bridge_inserts: Sequence[Mapping[str, Any]],
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[Optional[Dict[str, Any]], bool]: ) -> Tuple[Optional[Dict[str, Any]], bool]:
api_key, _ = normalize_openrouter_env() api_key, _ = normalize_openrouter_env()
if not api_key or len(steps) < 2: if not api_key or len(steps) < 2:
@@ -354,13 +357,18 @@ def try_llm_qa_progression_path(
} }
) )
variables = { variables = merge_planning_prompt_variables(
cur,
{
"goal_query": goal_query or "", "goal_query": goal_query or "",
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False), "semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
"steps_json": json.dumps(step_payload, ensure_ascii=False), "steps_json": json.dumps(step_payload, ensure_ascii=False),
"gaps_json": json.dumps(list(gaps), ensure_ascii=False), "gaps_json": json.dumps(list(gaps), ensure_ascii=False),
"bridge_inserts_json": json.dumps(list(bridge_inserts), ensure_ascii=False), "bridge_inserts_json": json.dumps(list(bridge_inserts), ensure_ascii=False),
} },
catalog=catalog,
slug="planning_exercise_path_qa",
)
try: try:
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_path_qa", variables) prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_path_qa", variables)
@@ -688,6 +696,160 @@ def find_step_pair_index(
return None return None
def count_step_assignment_stats(steps: Optional[Sequence[Mapping[str, Any]]]) -> Dict[str, int]:
stats = {"total": 0, "empty": 0, "library_filled": 0, "ai_proposal": 0}
for raw in steps or []:
if not isinstance(raw, dict):
continue
stats["total"] += 1
if raw.get("exercise_id") is not None and not raw.get("is_ai_proposal"):
stats["library_filled"] += 1
elif raw.get("is_ai_proposal"):
stats["ai_proposal"] += 1
else:
stats["empty"] += 1
return stats
def compute_assignment_quality_score(
*,
steps: Optional[Sequence[Mapping[str, Any]]] = None,
off_topic_steps: Optional[Sequence[Mapping[str, Any]]] = None,
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
) -> float:
"""QS der Übungsbesetzung — leere Slots stark abwerten."""
stats = count_step_assignment_stats(steps)
total = stats["total"]
if total <= 0:
return 0.45
empty = stats["empty"]
library = stats["library_filled"]
ai = stats["ai_proposal"]
fill_credit = (library + 0.55 * ai) / total
score = 0.1 + 0.84 * fill_credit
if empty > 0:
score -= 0.22 * (empty / total)
score -= 0.08 * len(off_topic_steps or [])
score -= 0.03 * len(gaps or [])
return max(0.08, min(0.98, round(score, 4)))
def compute_roadmap_quality_score(
*,
llm_qa: Optional[Mapping[str, Any]] = None,
llm_applied: bool = False,
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
multistage_qa: Optional[Mapping[str, Any]] = None,
) -> float:
"""QS der Roadmap-/Stufenlogik — unabhängig von Slot-Befüllung."""
if llm_applied and llm_qa and llm_qa.get("quality_score") is not None:
try:
return max(0.08, min(0.98, round(float(llm_qa["quality_score"]), 4)))
except (TypeError, ValueError):
pass
score = 0.9
score -= 0.05 * len(gaps or [])
hint_count = int((multistage_qa or {}).get("optimization_hint_count") or 0)
score -= min(0.12, 0.015 * hint_count)
return max(0.35, min(0.98, round(score, 4)))
def build_assignment_qa_snapshot(
*,
steps: Optional[Sequence[Mapping[str, Any]]] = None,
off_topic_steps: Optional[Sequence[Mapping[str, Any]]] = None,
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
) -> Dict[str, Any]:
off_topic = list(off_topic_steps or [])
stats = count_step_assignment_stats(steps)
score = compute_assignment_quality_score(
steps=steps,
off_topic_steps=off_topic,
gaps=gaps,
)
issues: List[str] = []
if stats["empty"] > 0:
issues.append(
f"{stats['empty']} von {stats['total']} Slot(s) ohne Übung — bitte Bibliothek oder KI-Vorschlag zuweisen",
)
if stats["ai_proposal"] > 0 and stats["library_filled"] == 0 and stats["empty"] > 0:
issues.append(
f"{stats['ai_proposal']} KI-Entwurf(e), aber noch {stats['empty']} leere Slot(s)",
)
for item in off_topic[:5]:
title = (item.get("title") or "Schritt").strip()
issues.append(f"„{title}“ passt nicht zum Stufen-Ziel")
overall_ok = stats["empty"] == 0 and len(off_topic) == 0
return {
"overall_ok": overall_ok,
"quality_score": score,
"slot_count": stats["total"],
"empty_slot_count": stats["empty"],
"library_filled_count": stats["library_filled"],
"ai_proposal_count": stats["ai_proposal"],
"issues": issues,
}
def build_roadmap_qa_snapshot(
*,
llm_qa: Optional[Mapping[str, Any]] = None,
llm_applied: bool = False,
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
multistage_qa: Optional[Mapping[str, Any]] = None,
roadmap_qa_mode: Optional[str] = None,
) -> Dict[str, Any]:
score = compute_roadmap_quality_score(
llm_qa=llm_qa,
llm_applied=llm_applied,
gaps=gaps,
multistage_qa=multistage_qa,
)
issues: List[str] = []
if not llm_applied:
for gap in gaps or []:
issues.append(
f"Übergang „{gap.get('from_title')}“ → „{gap.get('to_title')}“ schwach (Score {gap.get('gap_score')})",
)
if llm_applied and llm_qa:
issues.extend(str(x).strip() for x in (llm_qa.get("issues") or []) if str(x).strip())
overall_ok = bool(llm_qa.get("overall_ok", True)) if llm_applied and llm_qa else len(gaps or []) == 0
snapshot: Dict[str, Any] = {
"overall_ok": overall_ok,
"quality_score": score,
"issues": issues[:8],
"llm_applied": bool(llm_applied),
"roadmap_qa_mode": roadmap_qa_mode,
}
if llm_applied and llm_qa:
snapshot["topic_coverage"] = llm_qa.get("topic_coverage")
snapshot["recommendations"] = list(llm_qa.get("recommendations") or [])
snapshot["sequence_notes"] = list(llm_qa.get("sequence_notes") or [])
return snapshot
def merge_path_quality_scores(
roadmap_qa: Mapping[str, Any],
assignment_qa: Mapping[str, Any],
) -> float:
"""Gesamt-QS: schwächere Dimension begrenzt — leere Slots senken den Pfad deutlich."""
try:
roadmap_score = float(roadmap_qa.get("quality_score"))
except (TypeError, ValueError):
roadmap_score = None
try:
assignment_score = float(assignment_qa.get("quality_score"))
except (TypeError, ValueError):
assignment_score = None
if roadmap_score is not None and assignment_score is not None:
return round(min(roadmap_score, assignment_score), 4)
if assignment_score is not None:
return assignment_score
if roadmap_score is not None:
return roadmap_score
return 0.5
def build_path_qa_summary( def build_path_qa_summary(
*, *,
gaps: Sequence[Mapping[str, Any]], gaps: Sequence[Mapping[str, Any]],
@@ -702,6 +864,7 @@ def build_path_qa_summary(
reorder_notes: Optional[Sequence[str]] = None, reorder_notes: Optional[Sequence[str]] = None,
roadmap_qa_mode: Optional[str] = None, roadmap_qa_mode: Optional[str] = None,
multistage_qa: Optional[Mapping[str, Any]] = None, multistage_qa: Optional[Mapping[str, Any]] = None,
steps: Optional[Sequence[Mapping[str, Any]]] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
offers = list(gap_fill_offers or []) offers = list(gap_fill_offers or [])
off_topic = list(off_topic_steps or []) off_topic = list(off_topic_steps or [])
@@ -726,34 +889,70 @@ def build_path_qa_summary(
summary["qa_tiers"] = list(multistage_qa.get("qa_tiers") or []) summary["qa_tiers"] = list(multistage_qa.get("qa_tiers") or [])
summary["optimization_hints"] = list(multistage_qa.get("optimization_hints") or []) summary["optimization_hints"] = list(multistage_qa.get("optimization_hints") or [])
summary["optimization_hint_count"] = int(multistage_qa.get("optimization_hint_count") or 0) summary["optimization_hint_count"] = int(multistage_qa.get("optimization_hint_count") or 0)
assignment_qa = build_assignment_qa_snapshot(
steps=steps,
off_topic_steps=off_topic,
gaps=gaps,
)
roadmap_qa = build_roadmap_qa_snapshot(
llm_qa=llm_qa,
llm_applied=llm_applied,
gaps=gaps,
multistage_qa=multistage_qa,
roadmap_qa_mode=roadmap_qa_mode,
)
summary["assignment_qa"] = assignment_qa
summary["roadmap_qa"] = roadmap_qa
summary["quality_score"] = merge_path_quality_scores(roadmap_qa, assignment_qa)
summary["overall_ok"] = bool(
assignment_qa.get("overall_ok")
and roadmap_qa.get("overall_ok", True),
)
summary["topic_coverage"] = roadmap_qa.get("topic_coverage")
summary["recommendations"] = list(roadmap_qa.get("recommendations") or [])
summary["sequence_notes"] = list(roadmap_qa.get("sequence_notes") or [])
summary["issues"] = list(assignment_qa.get("issues") or []) + list(roadmap_qa.get("issues") or [])[:6]
if llm_qa: if llm_qa:
summary["overall_ok"] = bool(llm_qa.get("overall_ok", True))
summary["quality_score"] = llm_qa.get("quality_score")
summary["issues"] = list(llm_qa.get("issues") or [])
summary["sequence_notes"] = list(llm_qa.get("sequence_notes") or [])
summary["topic_coverage"] = llm_qa.get("topic_coverage")
summary["recommendations"] = list(llm_qa.get("recommendations") or [])
summary["suggested_new_exercises"] = list(llm_qa.get("suggested_new_exercises") or []) summary["suggested_new_exercises"] = list(llm_qa.get("suggested_new_exercises") or [])
else:
summary["overall_ok"] = len(gaps) == 0 and len(off_topic) == 0
summary["issues"] = [
f"Lücke zwischen „{g.get('from_title')}“ und „{g.get('to_title')}“ (Score {g.get('gap_score')})"
for g in gaps
] if gaps else []
if off_topic:
summary["issues"] = list(summary["issues"]) + [
f"Schritt „{o.get('title')}“ passt nicht zum Pfad-Thema"
for o in off_topic
]
return summary return summary
def compute_deterministic_path_quality_score(
*,
gaps: Sequence[Mapping[str, Any]],
off_topic_steps: Sequence[Mapping[str, Any]],
steps: Optional[Sequence[Mapping[str, Any]]] = None,
multistage_qa: Optional[Mapping[str, Any]] = None,
) -> float:
"""Heuristische Pfad-QS ohne LLM — Roadmap + Besetzung kombiniert."""
roadmap_qa = build_roadmap_qa_snapshot(
llm_qa=None,
llm_applied=False,
gaps=gaps,
multistage_qa=multistage_qa,
)
assignment_qa = build_assignment_qa_snapshot(
steps=steps,
off_topic_steps=off_topic_steps,
gaps=gaps,
)
return merge_path_quality_scores(roadmap_qa, assignment_qa)
__all__ = [ __all__ = [
"apply_llm_path_reorder", "apply_llm_path_reorder",
"build_assignment_qa_snapshot",
"build_path_qa_summary", "build_path_qa_summary",
"build_roadmap_qa_snapshot",
"compute_assignment_quality_score",
"compute_deterministic_path_quality_score",
"compute_roadmap_quality_score",
"count_step_assignment_stats",
"detect_off_topic_steps", "detect_off_topic_steps",
"detect_path_gaps", "detect_path_gaps",
"is_roadmap_planned_neighbor_pair", "is_roadmap_planned_neighbor_pair",
"merge_path_quality_scores",
"strip_off_topic_steps_from_path", "strip_off_topic_steps_from_path",
"find_step_pair_index", "find_step_pair_index",
"insert_bridge_exercises", "insert_bridge_exercises",
+15 -1
View File
@@ -49,9 +49,10 @@ class PlanningIntentContext:
context_notes: str = "" context_notes: str = ""
topic_type: str = "general" topic_type: str = "general"
technique_sibling_excludes: List[str] = field(default_factory=list) technique_sibling_excludes: List[str] = field(default_factory=list)
catalog_exercise_hints: Optional[str] = None
def to_api_dict(self) -> Dict[str, Any]: def to_api_dict(self) -> Dict[str, Any]:
return { out = {
"source_query": self.source_query, "source_query": self.source_query,
"primary_topic": self.primary_topic, "primary_topic": self.primary_topic,
"topic_type": self.topic_type, "topic_type": self.topic_type,
@@ -61,6 +62,10 @@ class PlanningIntentContext:
"technique_sibling_excludes": self.technique_sibling_excludes[:16], "technique_sibling_excludes": self.technique_sibling_excludes[:16],
"context_notes": self.context_notes[:1200] or None, "context_notes": self.context_notes[:1200] or None,
} }
hints = (self.catalog_exercise_hints or "").strip()
if hints:
out["catalog_exercise_hints"] = hints[:2000]
return out
def build_planning_intent_context( def build_planning_intent_context(
@@ -70,6 +75,8 @@ def build_planning_intent_context(
goal_analysis: Optional[Mapping[str, Any]] = None, goal_analysis: Optional[Mapping[str, Any]] = None,
extra_context: Optional[str] = None, extra_context: Optional[str] = None,
primary_topic: Optional[str] = None, primary_topic: Optional[str] = None,
cur=None,
catalog=None,
) -> PlanningIntentContext: ) -> PlanningIntentContext:
"""Intent aus Anfrage, Zielanalyse und optionalem Kontext — ohne Sonderregeln pro Thema.""" """Intent aus Anfrage, Zielanalyse und optionalem Kontext — ohne Sonderregeln pro Thema."""
ga = dict(goal_analysis or {}) ga = dict(goal_analysis or {})
@@ -124,6 +131,12 @@ def build_planning_intent_context(
if line not in path_success: if line not in path_success:
path_success.insert(0, line) path_success.insert(0, line)
catalog_hints = ""
if cur is not None and catalog is not None:
from planning_prompt_variables import catalog_exercise_hints_block
catalog_hints = catalog_exercise_hints_block(cur, catalog)
return PlanningIntentContext( return PlanningIntentContext(
source_query=(goal_query or "").strip(), source_query=(goal_query or "").strip(),
primary_topic=topic, primary_topic=topic,
@@ -133,6 +146,7 @@ def build_planning_intent_context(
explicit_exclusions=explicit, explicit_exclusions=explicit,
technique_sibling_excludes=siblings[:16], technique_sibling_excludes=siblings[:16],
context_notes=combined_notes[:1200], context_notes=combined_notes[:1200],
catalog_exercise_hints=catalog_hints or None,
) )
+62
View File
@@ -0,0 +1,62 @@
"""
Zähler für produktive OpenRouter-Aufrufe innerhalb einer Planungs-API-Anfrage.
Wird per ContextVar gesetzt (Router: ``planning_llm_call_meter``); ``openrouter_chat_completion``
erhöht den Zähler nach erfolgreicher Antwort — nur wenn ein Meter aktiv ist.
"""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Iterator, Optional
_llm_call_counter: ContextVar[Optional["PlanningLlmCallCounter"]] = ContextVar(
"planning_llm_call_counter",
default=None,
)
class PlanningLlmCallCounter:
"""Anzahl erfolgreicher OpenRouter-Chat-Completions in einem Request-Kontext."""
__slots__ = ("count",)
def __init__(self) -> None:
self.count = 0
def record(self, amount: int = 1) -> None:
try:
n = int(amount)
except (TypeError, ValueError):
n = 1
if n > 0:
self.count += n
def current_planning_llm_call_counter() -> Optional[PlanningLlmCallCounter]:
return _llm_call_counter.get()
def record_planning_llm_call(amount: int = 1) -> None:
counter = _llm_call_counter.get()
if counter is not None:
counter.record(amount)
@contextmanager
def planning_llm_call_meter() -> Iterator[PlanningLlmCallCounter]:
"""Aktiviert LLM-Zählung für den umschlossenen Block (inkl. verschachtelter Aufrufe)."""
counter = PlanningLlmCallCounter()
token = _llm_call_counter.set(counter)
try:
yield counter
finally:
_llm_call_counter.reset(token)
__all__ = [
"PlanningLlmCallCounter",
"current_planning_llm_call_counter",
"planning_llm_call_meter",
"record_planning_llm_call",
]
+124 -6
View File
@@ -7,6 +7,42 @@ from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from planning_progression_roadmap import ProgressionRoadmapContext, StageSpecArtifact from planning_progression_roadmap import ProgressionRoadmapContext, StageSpecArtifact
_UNFILLED_REMATCH_REASON = "Keine passende Übung für Roadmap-Stufe"
def _slot_priority_for_rematch(
body,
*,
major_idx: int,
old: Optional[Mapping[str, Any]],
rejected_by_major: Optional[Mapping[int, Set[int]]],
) -> Optional[int]:
"""Bestehende Slot-Zuordnung beim Rematch bevorzugen — außer explizit abgelehnt."""
priority_id: Optional[int] = None
if body is not None:
for raw in getattr(body, "slot_assignments", None) or []:
midx = getattr(raw, "roadmap_major_step_index", None)
if midx is None or int(midx) != int(major_idx):
continue
eid = getattr(raw, "exercise_id", None)
if eid is not None:
try:
priority_id = int(eid)
except (TypeError, ValueError):
priority_id = None
break
if priority_id is None and old and old.get("exercise_id") is not None:
try:
priority_id = int(old["exercise_id"])
except (TypeError, ValueError):
priority_id = None
if priority_id is None or priority_id < 1:
return None
rejected = rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
if priority_id in rejected:
return None
return priority_id
def collect_rematch_slot_indices( def collect_rematch_slot_indices(
*, *,
@@ -69,7 +105,7 @@ def collect_rematch_slot_indices(
if isinstance(item, (list, tuple)) and len(item) >= 2: if isinstance(item, (list, tuple)) and len(item) >= 2:
idx, spec = item[0], item[1] idx, spec = item[0], item[1]
midx = getattr(spec, "major_step_index", idx) midx = getattr(spec, "major_step_index", idx)
_register(int(midx), "Keine passende Übung für Roadmap-Stufe") _register(int(midx), _UNFILLED_REMATCH_REASON)
elif isinstance(item, dict): elif isinstance(item, dict):
midx = _resolve_major(item) midx = _resolve_major(item)
if midx is not None: if midx is not None:
@@ -80,6 +116,62 @@ def collect_rematch_slot_indices(
return indices, reasons return indices, reasons
def apply_rematch_catalog_guard(
slot_indices: Set[int],
rematch_reasons: Mapping[int, str],
*,
rematch_guard: Optional[str],
) -> Set[int]:
"""
Bei gesetztem rematch_guard (Katalog-Slot): kein Auto-Rematch nur wegen leerer Roadmap-Stufe.
Off-Topic, explizite QS-Hinweise und Stufen-Verfeinerung bleiben aktiv.
"""
if not (rematch_guard or "").strip():
return set(slot_indices)
return {
idx
for idx in slot_indices
if str(rematch_reasons.get(idx) or "").strip() != _UNFILLED_REMATCH_REASON
}
def filter_rematch_slot_indices(
steps: Sequence[Mapping[str, Any]],
slot_indices: Set[int],
*,
stripped_off_topic: Sequence[Mapping[str, Any]],
off_topic_steps: Sequence[Mapping[str, Any]],
) -> Set[int]:
"""Trainer-Zuordnungen (slot_best_match) nicht rematchen, außer Slot ist explizit beanstandet."""
flagged: Set[int] = set()
for item in list(stripped_off_topic or []) + list(off_topic_steps or []):
if not isinstance(item, dict):
continue
midx = item.get("roadmap_major_step_index")
if midx is not None:
try:
flagged.add(int(midx))
except (TypeError, ValueError):
pass
preserved: Set[int] = set()
for raw in steps or []:
if not isinstance(raw, dict):
continue
midx = raw.get("roadmap_major_step_index")
if midx is None:
continue
try:
major_idx = int(midx)
except (TypeError, ValueError):
continue
if raw.get("roadmap_match_source") == "slot_best_match" or raw.get("slot_status") == "preserved":
if major_idx not in flagged:
preserved.add(major_idx)
return {idx for idx in slot_indices if idx not in preserved}
def _context_before_major( def _context_before_major(
steps_by_major: Mapping[int, Mapping[str, Any]], steps_by_major: Mapping[int, Mapping[str, Any]],
target_major: int, target_major: int,
@@ -178,6 +270,12 @@ def rematch_roadmap_slots(
anchor_id=anchor_id, anchor_id=anchor_id,
anchor_variant_id=anchor_variant_id, anchor_variant_id=anchor_variant_id,
used=used, used=used,
slot_priority_exercise_id=_slot_priority_for_rematch(
body,
major_idx=major_idx,
old=old,
rejected_by_major=rejected_by_major,
),
) )
reason = str(rematch_reasons.get(int(major_idx)) or "rematch_slot") reason = str(rematch_reasons.get(int(major_idx)) or "rematch_slot")
@@ -186,12 +284,10 @@ def rematch_roadmap_slots(
new_eid = int(new_step.get("exercise_id") or 0) new_eid = int(new_step.get("exercise_id") or 0)
except (TypeError, ValueError): except (TypeError, ValueError):
new_eid = 0 new_eid = 0
hist = ( rejected = (
slot_assignment_history.get(int(major_idx), set()) rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
if slot_assignment_history
else set()
) )
if new_eid > 0 and new_eid in hist: if new_eid > 0 and new_eid in rejected:
new_step = None new_step = None
if new_step: if new_step:
steps_by_major[int(major_idx)] = new_step steps_by_major[int(major_idx)] = new_step
@@ -207,6 +303,26 @@ def rematch_roadmap_slots(
} }
) )
else: else:
if old and old.get("exercise_id") is not None:
try:
old_eid = int(old["exercise_id"])
except (TypeError, ValueError):
old_eid = 0
rejected = (
rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
)
if old_eid > 0 and old_eid not in rejected:
steps_by_major[int(major_idx)] = dict(old)
rematch_log.append(
{
"roadmap_major_step_index": int(major_idx),
"action": "restored",
"reason": reason,
"restored_exercise_id": old_eid,
"restored_title": old.get("title"),
}
)
continue
goal = (stage_spec.learning_goal or "").strip() goal = (stage_spec.learning_goal or "").strip()
major = None major = None
if roadmap_ctx.roadmap: if roadmap_ctx.roadmap:
@@ -277,7 +393,9 @@ def prune_stripped_after_rematch(
__all__ = [ __all__ = [
"apply_rematch_catalog_guard",
"collect_rematch_slot_indices", "collect_rematch_slot_indices",
"filter_rematch_slot_indices",
"prune_stripped_after_rematch", "prune_stripped_after_rematch",
"rematch_roadmap_slots", "rematch_roadmap_slots",
] ]
+32 -2
View File
@@ -18,6 +18,8 @@ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from pydantic import BaseModel, Field, ValidationError from pydantic import BaseModel, Field, ValidationError
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
from planning_catalog_context import ProgressionPlanningCatalogContext
from planning_prompt_variables import merge_planning_prompt_variables
from openrouter_chat import ( from openrouter_chat import (
effective_openrouter_model_for_prompt_row, effective_openrouter_model_for_prompt_row,
normalize_openrouter_env, normalize_openrouter_env,
@@ -190,12 +192,20 @@ def _run_prompt_json(
cur, cur,
slug: str, slug: str,
variables: Dict[str, str], variables: Dict[str, str],
*,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Optional[Dict[str, Any]]: ) -> Optional[Dict[str, Any]]:
api_key, _ = normalize_openrouter_env() api_key, _ = normalize_openrouter_env()
if not api_key or cur is None: if not api_key or cur is None:
return None return None
merged = merge_planning_prompt_variables(
cur,
variables,
catalog=catalog,
slug=slug,
)
try: try:
prow, rendered = load_and_render_ai_prompt(cur, slug, variables) prow, rendered = load_and_render_ai_prompt(cur, slug, merged)
model = effective_openrouter_model_for_prompt_row(prow) model = effective_openrouter_model_for_prompt_row(prow)
raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text) raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text)
return _extract_json_object(raw) return _extract_json_object(raw)
@@ -212,6 +222,7 @@ def try_llm_start_target_extract(
goal_query: str, goal_query: str,
brief: PlanningSemanticBrief, brief: PlanningSemanticBrief,
user_notes: str = "", user_notes: str = "",
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[Optional[StartTargetExtractArtifact], bool]: ) -> Tuple[Optional[StartTargetExtractArtifact], bool]:
obj = _run_prompt_json( obj = _run_prompt_json(
cur, cur,
@@ -221,6 +232,7 @@ def try_llm_start_target_extract(
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False), "semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
"user_notes": (user_notes or "").strip(), "user_notes": (user_notes or "").strip(),
}, },
catalog=catalog,
) )
if not obj: if not obj:
return None, False return None, False
@@ -236,6 +248,7 @@ def try_llm_goal_analysis(
*, *,
goal_query: str, goal_query: str,
brief: PlanningSemanticBrief, brief: PlanningSemanticBrief,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[Optional[GoalAnalysisArtifact], bool]: ) -> Tuple[Optional[GoalAnalysisArtifact], bool]:
obj = _run_prompt_json( obj = _run_prompt_json(
cur, cur,
@@ -244,6 +257,7 @@ def try_llm_goal_analysis(
"goal_query": goal_query or "", "goal_query": goal_query or "",
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False), "semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
}, },
catalog=catalog,
) )
if not obj: if not obj:
return None, False return None, False
@@ -261,6 +275,7 @@ def try_llm_roadmap(
brief: PlanningSemanticBrief, brief: PlanningSemanticBrief,
goal_analysis: GoalAnalysisArtifact, goal_analysis: GoalAnalysisArtifact,
max_steps: int, max_steps: int,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[Optional[RoadmapArtifact], bool]: ) -> Tuple[Optional[RoadmapArtifact], bool]:
obj = _run_prompt_json( obj = _run_prompt_json(
cur, cur,
@@ -271,6 +286,7 @@ def try_llm_roadmap(
"goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False), "goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False),
"max_steps": str(int(max_steps)), "max_steps": str(int(max_steps)),
}, },
catalog=catalog,
) )
if not obj: if not obj:
return None, False return None, False
@@ -304,6 +320,7 @@ def try_llm_stage_specs(
major_steps: Sequence[MajorStep], major_steps: Sequence[MajorStep],
intent_context: Optional[Mapping[str, Any]] = None, intent_context: Optional[Mapping[str, Any]] = None,
semantic_brief: Optional[PlanningSemanticBrief] = None, semantic_brief: Optional[PlanningSemanticBrief] = None,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[Optional[List[StageSpecArtifact]], bool]: ) -> Tuple[Optional[List[StageSpecArtifact]], bool]:
obj = _run_prompt_json( obj = _run_prompt_json(
cur, cur,
@@ -318,6 +335,7 @@ def try_llm_stage_specs(
ensure_ascii=False, ensure_ascii=False,
), ),
}, },
catalog=catalog,
) )
if not obj: if not obj:
return None, False return None, False
@@ -380,6 +398,7 @@ def resolve_roadmap_structured_input(
brief: PlanningSemanticBrief, brief: PlanningSemanticBrief,
cur=None, cur=None,
include_llm: bool = False, include_llm: bool = False,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> Tuple[RoadmapStructuredInput, StartTargetResolveMeta, Optional[StartTargetExtractArtifact]]: ) -> Tuple[RoadmapStructuredInput, StartTargetResolveMeta, Optional[StartTargetExtractArtifact]]:
"""Priorität je Feld: Trainer-Eingabe > LLM-Extraktion > Regex (von … bis …).""" """Priorität je Feld: Trainer-Eingabe > LLM-Extraktion > Regex (von … bis …)."""
user = structured or RoadmapStructuredInput() user = structured or RoadmapStructuredInput()
@@ -395,6 +414,7 @@ def resolve_roadmap_structured_input(
goal_query=goal_query, goal_query=goal_query,
brief=brief, brief=brief,
user_notes=user_notes, user_notes=user_notes,
catalog=catalog,
) )
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query) parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
@@ -1068,6 +1088,7 @@ def run_start_target_resolve_only(
cur=None, cur=None,
include_llm_start_target: bool = True, include_llm_start_target: bool = True,
structured: Optional[RoadmapStructuredInput] = None, structured: Optional[RoadmapStructuredInput] = None,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> ProgressionRoadmapContext: ) -> ProgressionRoadmapContext:
"""Nur Start/Ziel/Ergänzungen auflösen — ohne Roadmap-Stufen (Review vor Major Steps).""" """Nur Start/Ziel/Ergänzungen auflösen — ohne Roadmap-Stufen (Review vor Major Steps)."""
brief = semantic_brief or build_semantic_brief(goal_query) brief = semantic_brief or build_semantic_brief(goal_query)
@@ -1077,6 +1098,7 @@ def run_start_target_resolve_only(
brief=brief, brief=brief,
cur=cur, cur=cur,
include_llm=include_llm_start_target, include_llm=include_llm_start_target,
catalog=catalog,
) )
topic_override = None topic_override = None
if llm_extract and (llm_extract.primary_topic or "").strip(): if llm_extract and (llm_extract.primary_topic or "").strip():
@@ -1112,6 +1134,7 @@ def run_progression_roadmap_pipeline(
include_llm_roadmap: bool = False, include_llm_roadmap: bool = False,
include_llm_start_target: bool = False, include_llm_start_target: bool = False,
structured: Optional[RoadmapStructuredInput] = None, structured: Optional[RoadmapStructuredInput] = None,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
) -> ProgressionRoadmapContext: ) -> ProgressionRoadmapContext:
"""Workflow-lite: Phase A → B → C. LLM über ai_prompts-Slugs; deterministischer Fallback.""" """Workflow-lite: Phase A → B → C. LLM über ai_prompts-Slugs; deterministischer Fallback."""
brief = semantic_brief or build_semantic_brief(goal_query) brief = semantic_brief or build_semantic_brief(goal_query)
@@ -1121,6 +1144,7 @@ def run_progression_roadmap_pipeline(
brief=brief, brief=brief,
cur=cur, cur=cur,
include_llm=include_llm_start_target, include_llm=include_llm_start_target,
catalog=catalog,
) )
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query) parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
llm_goal_query = _roadmap_llm_goal_block( llm_goal_query = _roadmap_llm_goal_block(
@@ -1152,7 +1176,9 @@ def run_progression_roadmap_pipeline(
topic_override=topic_override, topic_override=topic_override,
) )
if include_llm_roadmap and cur is not None: if include_llm_roadmap and cur is not None:
llm_ga, ga_ok = try_llm_goal_analysis(cur, goal_query=llm_goal_query, brief=brief) llm_ga, ga_ok = try_llm_goal_analysis(
cur, goal_query=llm_goal_query, brief=brief, catalog=catalog
)
if ga_ok and llm_ga: if ga_ok and llm_ga:
goal_analysis = _merge_structured_into_goal_analysis( goal_analysis = _merge_structured_into_goal_analysis(
llm_ga, llm_ga,
@@ -1172,6 +1198,7 @@ def run_progression_roadmap_pipeline(
brief=brief, brief=brief,
goal_analysis=goal_analysis, goal_analysis=goal_analysis,
max_steps=max_steps, max_steps=max_steps,
catalog=catalog,
) )
if rm_ok and llm_rm: if rm_ok and llm_rm:
roadmap = llm_rm roadmap = llm_rm
@@ -1217,6 +1244,8 @@ def run_progression_roadmap_pipeline(
resolved.target_state, resolved.target_state,
), ),
primary_topic=goal_analysis.primary_topic, primary_topic=goal_analysis.primary_topic,
cur=cur,
catalog=catalog,
) )
heuristic_specs = build_stage_specs( heuristic_specs = build_stage_specs(
@@ -1234,6 +1263,7 @@ def run_progression_roadmap_pipeline(
major_steps=roadmap.major_steps, major_steps=roadmap.major_steps,
intent_context=intent.to_api_dict(), intent_context=intent.to_api_dict(),
semantic_brief=brief, semantic_brief=brief,
catalog=catalog,
) )
if spec_ok and llm_specs: if spec_ok and llm_specs:
stage_specs = list(llm_specs) stage_specs = list(llm_specs)
+140
View File
@@ -0,0 +1,140 @@
"""
Zentrale Mustache-Variablen für Planungs-KI-Prompts.
Orchestratoren bauen domänenspezifische Basis-Variablen; dieses Modul merged
erweiterbare Provider (Katalog-Slots, später weitere Kontexte).
"""
from __future__ import annotations
from typing import Any, Callable, Dict, Mapping, Optional
from catalog_prompt_slots import all_placeholder_keys, empty_catalog_variables
from planning_catalog_context import ProgressionPlanningCatalogContext
PlanningPromptVariableProvider = Callable[..., Dict[str, str]]
def _catalog_slot_variables(
*,
cur,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
slug: Optional[str] = None,
**_: Any,
) -> Dict[str, str]:
if cur is None or catalog is None:
return empty_catalog_variables()
from catalog_prompt_slots import resolve_catalog_prompt_variables
resolved = resolve_catalog_prompt_variables(cur, catalog, slug=slug)
return {k: str(resolved.get(k) or "") for k in all_placeholder_keys()}
_PLANNING_PROMPT_VARIABLE_PROVIDERS: tuple[PlanningPromptVariableProvider, ...] = (
_catalog_slot_variables,
)
def catalog_exercise_hints_block(
cur,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
*,
slug: Optional[str] = None,
) -> str:
"""Kombinierte hints_on_exercise aus aktivem Katalog-Kontext (Gap-Fill / Intent)."""
if cur is None or catalog is None:
return ""
from catalog_prompt_slots import CATALOG_KINDS, placeholder_key
merged = merge_planning_prompt_variables(cur, {}, catalog=catalog, slug=slug)
lines: list[str] = []
for cfg in CATALOG_KINDS:
key = placeholder_key(cfg.kind, "hints_on_exercise")
text = (merged.get(key) or "").strip()
if text:
lines.append(f"{cfg.label_de}: {text}")
return "\n".join(lines)
def merge_planning_prompt_variables(
cur,
base_variables: Mapping[str, str],
*,
catalog: Optional[ProgressionPlanningCatalogContext] = None,
slug: Optional[str] = None,
) -> Dict[str, str]:
"""Merged Basis-Variablen mit allen registrierten Planungs-Providern."""
out = {str(k): "" if v is None else str(v) for k, v in base_variables.items()}
ctx: Dict[str, Any] = {"cur": cur, "catalog": catalog, "slug": slug}
for provider in _PLANNING_PROMPT_VARIABLE_PROVIDERS:
out.update(provider(**ctx))
return out
def planning_prompt_placeholder_catalog() -> dict:
"""Platzhalter-Katalog für Admin — Slot-Typ × Dimension + Aggregat."""
from catalog_prompt_slots import CATALOG_KINDS, SLOT_KEYS, placeholder_key
slot_labels = {
"description": "Allgemeine Beschreibung",
"hints_on_progression": "Hinweise Progressionsgraph / Stufen",
"hints_on_exercise": "Hinweise Übungsanlage / Gap-Fill",
"hints_on_path_qa": "Bewertungsmaßstäbe Pfad-QS",
"anti_patterns": "Anti-Patterns (Fehlbewertung vermeiden)",
"rematch_guard": "Rematch-Guard (primär Code, optional Prompt)",
}
kind_labels = {c.kind: c.label_de for c in CATALOG_KINDS}
slugs_common = [
"planning_exercise_path_qa",
"planning_progression_roadmap",
"planning_progression_stage_spec",
"planning_progression_goal_analysis",
"planning_progression_start_target",
]
defs = []
for cfg in CATALOG_KINDS:
for slot in SLOT_KEYS:
key = placeholder_key(cfg.kind, slot)
defs.append(
{
"key": key,
"placeholder": "{{" + key + "}}",
"description": (
f"{kind_labels.get(cfg.kind, cfg.kind)} — "
f"{slot_labels.get(slot, slot)} (aktiver Eintrag aus planning_catalog_context)."
),
"used_by_slugs": slugs_common,
}
)
defs.extend(
[
{
"key": "catalog_guidance_block",
"placeholder": "{{catalog_guidance_block}}",
"description": "Aggregierter Markdown-Block aus aktiven Slots (slug-spezifisches Profil).",
"used_by_slugs": slugs_common,
},
{
"key": "catalog_context_json",
"placeholder": "{{catalog_context_json}}",
"description": "Audit-JSON der gewählten Katalog-Einträge und befüllten Slots.",
"used_by_slugs": slugs_common[:3],
},
{
"key": "has_catalog_guidance",
"placeholder": "{{has_catalog_guidance}}",
"description": "„true“ wenn mindestens ein LLM-Slot gesetzt; sonst leer.",
"used_by_slugs": slugs_common[:3],
},
]
)
return {"context": "planning", "placeholders": defs}
__all__ = [
"catalog_exercise_hints_block",
"merge_planning_prompt_variables",
"planning_prompt_placeholder_catalog",
]
@@ -37,6 +37,7 @@ class GraphPlanningRoadmapArtifact(BaseModel):
path_skill_expectations: Optional[Dict[str, Any]] = None path_skill_expectations: Optional[Dict[str, Any]] = None
slot_contents: Optional[List[SlotContentEntry]] = None slot_contents: Optional[List[SlotContentEntry]] = None
last_findings: Optional[Dict[str, Any]] = None last_findings: Optional[Dict[str, Any]] = None
findings_stale: bool = Field(default=False)
planning_catalog_context: Optional[Dict[str, Any]] = None planning_catalog_context: Optional[Dict[str, Any]] = None
@field_validator("progression_roadmap", "path_skill_expectations", "last_findings", "planning_catalog_context", mode="before") @field_validator("progression_roadmap", "path_skill_expectations", "last_findings", "planning_catalog_context", mode="before")
+1 -1
View File
@@ -13,7 +13,7 @@ router = APIRouter(prefix="/api/admin", tags=["admin_users"])
_SAFE_PROFILE_COLS = """ _SAFE_PROFILE_COLS = """
id, name, email, role, tier, email_verified, active_club_id, id, name, email, role, tier, email_verified, active_club_id,
created_at, updated_at, auth_type created_at, updated_at, auth_type, totp_enabled
""" """
+29 -2
View File
@@ -14,9 +14,15 @@ from auth import require_auth
from club_tenancy import is_superadmin from club_tenancy import is_superadmin
from ai_prompt_context import ExerciseFormAiPromptContext from ai_prompt_context import ExerciseFormAiPromptContext
from ai_prompt_job import resolve_exercise_form_variables from ai_prompt_job import resolve_exercise_form_variables
from ai_prompt_planning_preview import (
PlanningPromptPreviewInput,
is_planning_prompt_slug,
resolve_planning_prompt_preview_variables,
)
from ai_prompt_runtime import render_ai_prompt_template_for_row from ai_prompt_runtime import render_ai_prompt_template_for_row
from db import get_cursor, get_db, r2d from db import get_cursor, get_db, r2d
from prompt_resolver import exercise_placeholder_catalog from prompt_resolver import exercise_placeholder_catalog
from planning_prompt_variables import planning_prompt_placeholder_catalog
router = APIRouter(tags=["admin_ai_prompts"]) router = APIRouter(tags=["admin_ai_prompts"])
@@ -62,12 +68,22 @@ class AiPromptUpdateBody(BaseModel):
class AiPromptPreviewBody(ExerciseFormAiPromptContext): class AiPromptPreviewBody(ExerciseFormAiPromptContext):
"""Preview-POST: gleiche Felder wie ExerciseFormAiPromptContext (focus_hint, nicht focus_area_hint).""" """Preview-POST: Übungs-KI und Planungs-Prompts."""
goal_query: Optional[str] = Field(default=None, max_length=2000)
user_notes: Optional[str] = Field(default=None, max_length=2000)
max_steps: Optional[int] = Field(default=None, ge=2, le=10)
search_query: Optional[str] = Field(default=None, max_length=2000)
@router.get("/api/admin/ai-prompts/catalog/placeholders") @router.get("/api/admin/ai-prompts/catalog/placeholders")
def get_ai_prompt_placeholders_catalog(session: dict = Depends(_require_superadmin)): def get_ai_prompt_placeholders_catalog(session: dict = Depends(_require_superadmin)):
return exercise_placeholder_catalog() exercise = exercise_placeholder_catalog()
planning = planning_prompt_placeholder_catalog()
return {
"context": "all",
"placeholders": list(exercise.get("placeholders") or []) + list(planning.get("placeholders") or []),
}
@router.get("/api/admin/ai-prompts") @router.get("/api/admin/ai-prompts")
@@ -223,6 +239,17 @@ def preview_ai_prompt(prompt_id: int, body: AiPromptPreviewBody, session: dict =
vars_map = resolve_exercise_form_variables(cur, slug, body) vars_map = resolve_exercise_form_variables(cur, slug, body)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e raise HTTPException(status_code=400, detail=str(e)) from e
elif is_planning_prompt_slug(slug):
planning_in = PlanningPromptPreviewInput(
goal_query=(body.goal_query or "Mae Geri vom Grundschritt bis zur Kumite-Nähe").strip(),
user_notes=(body.user_notes or "").strip(),
max_steps=body.max_steps if body.max_steps is not None else 5,
search_query=(body.search_query or body.goal_query or "").strip() or None,
)
try:
vars_map = resolve_planning_prompt_preview_variables(cur, slug, planning_in)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
elif slug == "pipeline": elif slug == "pipeline":
vars_map = {} vars_map = {}
warn = "Pipeline-Slug: keine Kontextsubstitution fuer Vorschau." warn = "Pipeline-Slug: keine Kontextsubstitution fuer Vorschau."
+449 -72
View File
@@ -14,12 +14,41 @@ from email.mime.text import MIMEText
from fastapi import APIRouter, HTTPException, Header, Depends from fastapi import APIRouter, HTTPException, Header, Depends
from starlette.requests import Request from starlette.requests import Request
import ipaddress
from slowapi import Limiter from slowapi import Limiter
from slowapi.util import get_remote_address
from db import get_db, get_cursor from db import get_db, get_cursor
from auth import hash_pin, verify_pin, make_token, require_auth from auth import (
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest get_limited_session,
get_session,
hash_pin,
make_token,
require_auth,
revoke_profile_sessions,
session_lifetime_days,
verify_pin,
verify_pin_for_login,
)
from media_grant import MEDIA_GRANT_TTL_SECONDS, issue_media_grant
from models import (
ChangePasswordRequest,
LoginRequest,
LoginTotpRequest,
PasswordResetRequest,
PasswordResetConfirm,
RegisterRequest,
ResendVerificationRequest,
TotpCodeRequest,
TotpDisableRequest,
)
from totp_auth import (
generate_recovery_codes,
generate_totp_secret,
hash_recovery_code,
otpauth_uri,
verify_totp,
)
from password_reset_mail import ( from password_reset_mail import (
insert_password_reset_session, insert_password_reset_session,
password_reset_email_body, password_reset_email_body,
@@ -27,47 +56,158 @@ from password_reset_mail import (
) )
router = APIRouter(prefix="/api/auth", tags=["auth"]) router = APIRouter(prefix="/api/auth", tags=["auth"])
limiter = Limiter(key_func=get_remote_address)
LOGIN_LOCK_AFTER = 8
LOGIN_LOCK_MINUTES = 15
_ADMIN_ROLES = ("admin", "superadmin")
@router.post("/login") def _client_ip(request: Request) -> str:
@limiter.limit("30/minute") """Echte Client-IP nur, wenn der direkte Peer ein vertrauenswürdiger Proxy ist."""
async def login(req: LoginRequest, request: Request): peer = request.client.host if request.client and request.client.host else ""
"""Login with email + password.""" if _is_trusted_proxy(peer):
with get_db() as conn: real = (request.headers.get("x-real-ip") or "").split(",")[0].strip()
cur = get_cursor(conn) if real:
cur.execute("SELECT * FROM profiles WHERE email=%s", (req.email.lower().strip(),)) return real[:64]
prof = cur.fetchone() return peer or "unknown"
if not prof:
raise HTTPException(401, "Ungültige Zugangsdaten")
# Verify password
if not verify_pin(req.password, prof['pin_hash']):
raise HTTPException(401, "Ungültige Zugangsdaten")
# Auto-upgrade from SHA256 to bcrypt def _is_trusted_proxy(host: str) -> bool:
if prof['pin_hash'] and not prof['pin_hash'].startswith('$2'): if not host:
new_hash = hash_pin(req.password) return False
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id'])) try:
ip = ipaddress.ip_address(host)
except ValueError:
return False
return ip.is_private or ip.is_loopback or ip.is_link_local
# Create session
limiter = Limiter(key_func=_client_ip)
def _admin_totp_required() -> bool:
"""Nur wenn REQUIRE_ADMIN_TOTP ausdrücklich an ist. Standard: der Nutzer entscheidet selbst."""
raw = (os.getenv("REQUIRE_ADMIN_TOTP") or "").strip().lower()
return raw in ("1", "true", "yes")
def _issue_session(cur, profile_id: int, *, days: int, purpose: str = "full") -> tuple[str, datetime]:
token = make_token() token = make_token()
session_days = prof.get('session_days', 30) expires = datetime.now(timezone.utc) + timedelta(days=days if purpose == "full" else 0, minutes=0)
expires = datetime.now() + timedelta(days=session_days) if purpose == "totp_challenge":
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)", expires = datetime.now(timezone.utc) + timedelta(minutes=5)
(token, prof['id'], expires.isoformat())) elif purpose == "totp_enroll":
expires = datetime.now(timezone.utc) + timedelta(minutes=30)
cur.execute(
"""
INSERT INTO sessions (token, profile_id, expires_at, created_at, purpose)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP, %s)
""",
(token, profile_id, expires, purpose),
)
return token, expires
def _login_payload(prof: dict, token: str, expires: datetime) -> dict:
return { return {
"token": token, "token": token,
"profile_id": prof['id'], "profile_id": prof["id"],
"email": prof.get("email"), "email": prof.get("email"),
"name": prof.get("name"), "name": prof.get("name"),
"role": prof.get("role"), "role": prof.get("role"),
"tier": prof.get("tier"), "tier": prof.get("tier"),
"expires_at": expires.isoformat(), "expires_at": expires.isoformat(),
"totp_enabled": bool(prof.get("totp_enabled")),
} }
def _record_failed_login(cur, profile_id: int) -> None:
cur.execute(
"""
UPDATE profiles
SET failed_login_count = CASE
WHEN failed_login_count + 1 >= %s THEN 0
ELSE failed_login_count + 1
END,
locked_until = CASE
WHEN failed_login_count + 1 >= %s
THEN CURRENT_TIMESTAMP + (%s * INTERVAL '1 minute')
ELSE locked_until
END
WHERE id = %s
""",
(LOGIN_LOCK_AFTER, LOGIN_LOCK_AFTER, LOGIN_LOCK_MINUTES, profile_id),
)
def _clear_login_lock(cur, profile_id: int) -> None:
cur.execute(
"UPDATE profiles SET failed_login_count = 0, locked_until = NULL WHERE id = %s",
(profile_id,),
)
@router.post("/login")
@limiter.limit("10/minute")
async def login(req: LoginRequest, request: Request):
"""Login with email + password. Bei aktivem TOTP folgt ein zweiter Schritt."""
email = req.email.lower().strip()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT *,
(locked_until IS NOT NULL AND locked_until > CURRENT_TIMESTAMP) AS is_locked
FROM profiles WHERE email=%s
""",
(email,),
)
prof = cur.fetchone()
password_ok = verify_pin_for_login(req.password, prof["pin_hash"] if prof else None)
if not prof or not password_ok:
if prof and not prof.get("is_locked"):
_record_failed_login(cur, prof["id"])
outcome = "invalid"
elif prof.get("is_locked"):
outcome = "locked"
else:
outcome = "ok"
if prof["pin_hash"] and not str(prof["pin_hash"]).startswith("$2"):
cur.execute(
"UPDATE profiles SET pin_hash=%s WHERE id=%s",
(hash_pin(req.password), prof["id"]),
)
_clear_login_lock(cur, prof["id"])
if outcome == "invalid":
raise HTTPException(401, "Ungültige Zugangsdaten")
if outcome == "locked":
raise HTTPException(429, "Zu viele Anmeldeversuche. Bitte später erneut versuchen.")
with get_db() as conn:
cur = get_cursor(conn)
role = (prof.get("role") or "").strip().lower()
if prof.get("totp_enabled"):
token, expires = _issue_session(cur, prof["id"], days=1, purpose="totp_challenge")
return {
"totp_required": True,
"challenge_token": token,
"expires_at": expires.isoformat(),
}
if role in _ADMIN_ROLES and _admin_totp_required() and not prof.get("totp_enabled"):
token, expires = _issue_session(cur, prof["id"], days=1, purpose="totp_enroll")
return {
"totp_enrollment_required": True,
"token": token,
"email": prof.get("email"),
"expires_at": expires.isoformat(),
}
token, expires = _issue_session(cur, prof["id"], days=session_lifetime_days(prof))
return _login_payload(prof, token, expires)
@router.post("/logout") @router.post("/logout")
def logout(x_auth_token: Optional[str]=Header(default=None)): def logout(x_auth_token: Optional[str]=Header(default=None)):
"""Logout (delete session).""" """Logout (delete session)."""
@@ -94,21 +234,246 @@ def auth_status():
@router.put("/pin") @router.put("/pin")
def change_pin(req: dict, session: dict=Depends(require_auth)): def change_pin(req: ChangePasswordRequest, session: dict = Depends(require_auth)):
"""Change PIN/password for current user.""" """Passwort wechseln. Das aktuelle Passwort ist Pflicht; alle Sitzungen werden ersetzt."""
pid = session['profile_id'] pid = session["profile_id"]
new_pin = req.get('pin', '')
if len(new_pin) < 8:
raise HTTPException(400, "Passwort muss mind. 8 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid)) cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not verify_pin(req.current_password, prof["pin_hash"]):
raise HTTPException(400, "Aktuelles Passwort ist falsch")
cur.execute(
"UPDATE profiles SET pin_hash=%s WHERE id=%s",
(hash_pin(req.new_password), pid),
)
revoke_profile_sessions(cur, int(pid))
token, expires = _issue_session(cur, int(pid), days=session_lifetime_days(prof))
return {"ok": True, "token": token, "expires_at": expires.isoformat()}
@router.post("/login/totp")
@limiter.limit("10/minute")
async def login_totp(req: LoginTotpRequest, request: Request):
"""Zweiter Login-Schritt: Authenticator-Code oder Wiederherstellungscode."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT s.*, p.role, p.name, p.email
FROM sessions s JOIN profiles p ON s.profile_id = p.id
WHERE s.token = %s AND s.expires_at > CURRENT_TIMESTAMP AND s.purpose = 'totp_challenge'
""",
(req.challenge_token,),
)
challenge = cur.fetchone()
error = None
payload = None
if not challenge:
error = "Anmeldung abgelaufen. Bitte erneut anmelden."
else:
pid = int(challenge["profile_id"])
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not prof.get("totp_enabled"):
error = "Anmeldung abgelaufen. Bitte erneut anmelden."
else:
code_ok = verify_totp(prof.get("totp_secret"), req.code) or _consume_recovery_code(
cur, pid, req.code
)
if not code_ok:
attempts = int(challenge.get("failed_attempts") or 0) + 1
if attempts >= 5:
cur.execute("DELETE FROM sessions WHERE token=%s", (req.challenge_token,))
else:
cur.execute(
"UPDATE sessions SET failed_attempts=%s WHERE token=%s",
(attempts, req.challenge_token),
)
error = "Ungültiger Code"
else:
revoke_profile_sessions(cur, pid)
token, expires = _issue_session(cur, pid, days=session_lifetime_days(prof))
payload = _login_payload(prof, token, expires)
if error:
raise HTTPException(401, error)
return payload
def _consume_recovery_code(cur, profile_id: int, code: str) -> bool:
digest = hash_recovery_code(code)
cur.execute(
"""
UPDATE profile_recovery_codes
SET used_at = CURRENT_TIMESTAMP
WHERE profile_id = %s AND code_hash = %s AND used_at IS NULL
RETURNING id
""",
(profile_id, digest),
)
return cur.fetchone() is not None
def _setup_session_or_401(token: str) -> dict:
full = None
if token:
full = get_session(token)
if full:
return full
enroll = get_limited_session(token, "totp_enroll") if token else None
if not enroll:
raise HTTPException(401, "Nicht eingeloggt")
return enroll
@router.get("/totp/status")
def totp_status(x_auth_token: Optional[str] = Header(default=None)):
session = _setup_session_or_401(x_auth_token or "")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT email, role, totp_enabled FROM profiles WHERE id=%s",
(session["profile_id"],),
)
prof = cur.fetchone()
if not prof:
raise HTTPException(401, "Nicht eingeloggt")
role = (prof.get("role") or session.get("role") or "").strip().lower()
enrollment = (session.get("purpose") or "full") == "totp_enroll"
return {
"totp_enabled": bool(prof.get("totp_enabled")),
"enrollment_required": enrollment or (
role in _ADMIN_ROLES and _admin_totp_required() and not prof.get("totp_enabled")
),
"email": prof.get("email"),
"role": role,
}
@router.post("/totp/setup")
def totp_setup(x_auth_token: Optional[str] = Header(default=None)):
"""Neues Geheimnis erzeugen. Wirksam erst nach /totp/confirm."""
session = _setup_session_or_401(x_auth_token or "")
secret = generate_totp_secret()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT email FROM profiles WHERE id=%s", (session["profile_id"],))
prof = cur.fetchone()
if not prof:
raise HTTPException(404, "Profil nicht gefunden")
cur.execute(
"UPDATE profiles SET totp_pending_secret=%s WHERE id=%s",
(secret, session["profile_id"]),
)
email = prof.get("email") or "konto"
return {
"secret": secret,
"otpauth_uri": otpauth_uri(secret=secret, account_name=email),
}
@router.post("/totp/confirm")
def totp_confirm(req: TotpCodeRequest, x_auth_token: Optional[str] = Header(default=None)):
session = _setup_session_or_401(x_auth_token or "")
pid = int(session["profile_id"])
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not prof.get("totp_pending_secret"):
raise HTTPException(400, "Zuerst ein neues Geheimnis erzeugen")
if not verify_totp(prof.get("totp_pending_secret"), req.code):
raise HTTPException(400, "Code stimmt nicht. Uhrzeit des Geräts prüfen.")
cur.execute(
"""
UPDATE profiles
SET totp_secret=%s, totp_pending_secret=NULL, totp_enabled=TRUE
WHERE id=%s
""",
(prof["totp_pending_secret"], pid),
)
plain_codes = _replace_recovery_codes(cur, pid)
prof = dict(prof)
prof["totp_enabled"] = True
prof["totp_secret"] = None
revoke_profile_sessions(cur, pid)
token, expires = _issue_session(cur, pid, days=session_lifetime_days(prof))
payload = _login_payload(prof, token, expires)
payload["recovery_codes"] = plain_codes
return payload
def _replace_recovery_codes(cur, profile_id: int) -> list[str]:
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (profile_id,))
plain_codes = generate_recovery_codes()
for code in plain_codes:
cur.execute(
"""
INSERT INTO profile_recovery_codes (profile_id, code_hash)
VALUES (%s, %s)
""",
(profile_id, hash_recovery_code(code)),
)
return plain_codes
@router.post("/totp/recovery-codes")
def regenerate_recovery_codes(req: TotpDisableRequest, session: dict = Depends(require_auth)):
"""Neue Codes ausgeben. Die bisherigen werden ungültig. Passwort und aktueller App-Code sind Pflicht."""
pid = int(session["profile_id"])
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not prof.get("totp_enabled"):
raise HTTPException(400, "Zwei-Faktor ist nicht aktiv")
if not verify_pin(req.current_password, prof["pin_hash"]):
raise HTTPException(400, "Aktuelles Passwort ist falsch")
if not verify_totp(prof.get("totp_secret"), req.code):
raise HTTPException(400, "Code aus der App stimmt nicht")
plain_codes = _replace_recovery_codes(cur, pid)
return {"recovery_codes": plain_codes}
@router.post("/totp/disable")
def totp_disable(req: TotpDisableRequest, session: dict = Depends(require_auth)):
pid = int(session["profile_id"])
role = (session.get("role") or "").strip().lower()
if role in _ADMIN_ROLES and _admin_totp_required():
raise HTTPException(400, "Für Plattform-Admins bleibt die Zwei-Faktor-Anmeldung aktiv.")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not verify_pin(req.current_password, prof["pin_hash"]):
raise HTTPException(400, "Aktuelles Passwort ist falsch")
if not (
verify_totp(prof.get("totp_secret"), req.code)
or _consume_recovery_code(cur, pid, req.code)
):
raise HTTPException(400, "Code stimmt nicht")
cur.execute(
"""
UPDATE profiles
SET totp_enabled=FALSE, totp_secret=NULL, totp_pending_secret=NULL
WHERE id=%s
""",
(pid,),
)
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (pid,))
return {"ok": True} return {"ok": True}
@router.post("/media-grant")
def media_grant(session: dict = Depends(require_auth)):
"""Kurzlebiges Token nur für Medien-Dateien. Ersetzt das Sitzungstoken in Bild-URLs."""
token, exp = issue_media_grant(int(session["profile_id"]), ttl_seconds=MEDIA_GRANT_TTL_SECONDS)
return {
"token": token,
"expires_at": datetime.fromtimestamp(exp, tz=timezone.utc).isoformat(),
}
@router.post("/forgot-password") @router.post("/forgot-password")
@limiter.limit("3/minute") @limiter.limit("3/minute")
async def password_reset_request(req: PasswordResetRequest, request: Request): async def password_reset_request(req: PasswordResetRequest, request: Request):
@@ -146,10 +511,17 @@ def password_reset_confirm(req: PasswordResetConfirm):
if not sess: if not sess:
raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link") raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link")
pid = sess['profile_id'] pid = sess["profile_id"]
new_hash = hash_pin(req.new_password) new_hash = hash_pin(req.new_password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid)) cur.execute(
cur.execute("DELETE FROM sessions WHERE token=%s", (f"reset_{req.token}",)) """
UPDATE profiles
SET pin_hash=%s, failed_login_count=0, locked_until=NULL
WHERE id=%s
""",
(new_hash, pid),
)
revoke_profile_sessions(cur, int(pid))
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"} return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
@@ -272,11 +644,14 @@ async def register(req: RegisterRequest, request: Request):
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
# Check if email already exists cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
cur.execute("SELECT id FROM profiles WHERE email=%s", (email,)) existing = cur.fetchone()
if cur.fetchone(): if existing:
raise HTTPException(400, "E-Mail-Adresse bereits registriert") existing_name = existing.get("name")
else:
existing_name = None
if existing is None:
# Generate verification token # Generate verification token
verification_token = secrets.token_urlsafe(32) verification_token = secrets.token_urlsafe(32)
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24) verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
@@ -322,6 +697,24 @@ async def register(req: RegisterRequest, request: Request):
(new_profile_id, int(req_club)), (new_profile_id, int(req_club)),
) )
generic = {
"ok": True,
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse.",
}
if existing is not None:
send_email(
email,
"Shinkan Jinkendo – Registrierung",
f"""Hallo {existing_name or name},
für diese E-Mail-Adresse gibt es bereits ein Konto. Es wurde kein neues Passwort gesetzt.
Wenn du den Zugang brauchst, melde dich an oder fordere ein neues Passwort an.
Dein Shinkan Jinkendo Team
""",
)
return generic
verify_url = verification_link(verification_token) verify_url = verification_link(verification_token)
email_body = f"""Hallo {name}, email_body = f"""Hallo {name},
@@ -340,10 +733,7 @@ Dein Shinkan Jinkendo Team
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body): if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.") print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.")
return { return generic
"ok": True,
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse."
}
@router.get("/verify/{token}") @router.get("/verify/{token}")
@@ -402,44 +792,34 @@ async def verify_email(token: str):
@router.post("/resend-verification") @router.post("/resend-verification")
@limiter.limit("3/hour") @limiter.limit("3/hour")
async def resend_verification(req: dict, request: Request): async def resend_verification(req: ResendVerificationRequest, request: Request):
"""Resend verification email for unverified account.""" """Bestätigung erneut senden. Bekannte und unbekannte Adressen antworten gleich."""
email = req.get('email', '').strip().lower() email = str(req.email).lower().strip()
generic = {
if not email: "ok": True,
raise HTTPException(400, "E-Mail-Adresse erforderlich") "message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet.",
}
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
# Find profile by email
cur.execute(""" cur.execute("""
SELECT id, name, email, email_verified, verification_token, verification_expires SELECT id, name, email, email_verified, verification_token, verification_expires
FROM profiles FROM profiles
WHERE email=%s WHERE email=%s
""", (email,)) """, (email,))
prof = cur.fetchone() prof = cur.fetchone()
if not prof or prof["email_verified"]:
return generic
if not prof:
# Don't leak info about existing emails
return {"ok": True, "message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet."}
if prof['email_verified']:
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
# Generate new verification token
verification_token = secrets.token_urlsafe(32) verification_token = secrets.token_urlsafe(32)
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24) verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
cur.execute(""" cur.execute("""
UPDATE profiles UPDATE profiles
SET verification_token=%s, verification_expires=%s SET verification_token=%s, verification_expires=%s
WHERE id=%s WHERE id=%s
""", (verification_token, verification_expires, prof['id'])) """, (verification_token, verification_expires, prof["id"]))
verify_url = verification_link(verification_token) verify_url = verification_link(verification_token)
email_body = f"""Hallo {prof['name']}, email_body = f"""Hallo {prof['name']},
du hast eine neue Bestätigungs-E-Mail angefordert. du hast eine neue Bestätigungs-E-Mail angefordert.
@@ -452,8 +832,5 @@ Dieser Link ist 24 Stunden gültig.
Dein Shinkan Jinkendo Team Dein Shinkan Jinkendo Team
""" """
send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body)
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body): return generic
raise HTTPException(502, "E-Mail konnte nicht versendet werden. SMTP-Einstellungen und Container-Logs prüfen.")
return {"ok": True, "message": "Bestätigungs-E-Mail wurde erneut versendet."}
+97
View File
@@ -0,0 +1,97 @@
"""
API: Katalog-Prompt-Slots (Stammdaten × Slot-Typ).
Globaler Admin-Katalog (wie catalogs.py) — require_auth + Admin-Rolle, kein TenantContext.
Eingetragen in backend/scripts/check_access_layer_hints.py EXEMPT_ROUTERS.
"""
from __future__ import annotations
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from auth import require_auth
from catalog_prompt_slots import (
CATALOG_KINDS,
get_catalog_entry_slots,
list_slot_type_definitions,
upsert_catalog_entry_slots,
)
from db import get_cursor, get_db
router = APIRouter(prefix="/api", tags=["catalog_prompt_slots"])
_VALID_KINDS = frozenset(c.kind for c in CATALOG_KINDS)
class CatalogPromptSlotsBody(BaseModel):
slots: Dict[str, Optional[str]] = Field(default_factory=dict)
def _require_admin(session: dict = Depends(require_auth)) -> dict:
role = (session.get("role") or "").strip().lower()
if role not in ("admin", "superadmin"):
raise HTTPException(status_code=403, detail="Nur Admins")
return session
def _slots_table_ready(cur) -> bool:
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.catalog_prompt_slots",))
row = cur.fetchone()
if not row:
return False
val = row.get("t") if isinstance(row, dict) else row[0]
return val is not None and str(val).strip() != ""
@router.get("/catalog-prompt-slot-types")
def api_list_catalog_prompt_slot_types(session: dict = Depends(_require_admin)):
with get_db() as conn:
cur = get_cursor(conn)
if not _slots_table_ready(cur):
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
return {"slot_types": list_slot_type_definitions(cur)}
@router.get("/catalog-prompt-slots/{catalog_kind}/{catalog_id}")
def api_get_catalog_prompt_slots(
catalog_kind: str,
catalog_id: int,
session: dict = Depends(_require_admin),
):
kind = (catalog_kind or "").strip().lower()
if kind not in _VALID_KINDS:
raise HTTPException(status_code=400, detail=f"Unbekannter catalog_kind: {catalog_kind!r}")
with get_db() as conn:
cur = get_cursor(conn)
if not _slots_table_ready(cur):
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
try:
return get_catalog_entry_slots(cur, kind, catalog_id)
except LookupError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.put("/catalog-prompt-slots/{catalog_kind}/{catalog_id}")
def api_put_catalog_prompt_slots(
catalog_kind: str,
catalog_id: int,
body: CatalogPromptSlotsBody,
session: dict = Depends(_require_admin),
):
kind = (catalog_kind or "").strip().lower()
if kind not in _VALID_KINDS:
raise HTTPException(status_code=400, detail=f"Unbekannter catalog_kind: {catalog_kind!r}")
with get_db() as conn:
cur = get_cursor(conn)
if not _slots_table_ready(cur):
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
try:
return upsert_catalog_entry_slots(cur, kind, catalog_id, body.slots or {})
except LookupError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+13 -1
View File
@@ -28,11 +28,12 @@ import os
import re import re
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, Header, HTTPException from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field, field_validator
from club_tenancy import is_platform_admin, is_superadmin from club_tenancy import is_platform_admin, is_superadmin
from db import get_db, get_cursor, r2d from db import get_db, get_cursor, r2d
from routers.auth import limiter
from media_legal_hold import ( from media_legal_hold import (
LEGAL_HOLD_REASON_CODES, LEGAL_HOLD_REASON_CODES,
assert_superadmin_for_legal_hold, assert_superadmin_for_legal_hold,
@@ -324,6 +325,7 @@ def _resolve_optional_auth(cur, x_auth_token: Optional[str]) -> tuple[Optional[i
INNER JOIN profiles p ON p.id = s.profile_id INNER JOIN profiles p ON p.id = s.profile_id
WHERE s.token = %s WHERE s.token = %s
AND (s.expires_at IS NULL OR s.expires_at > NOW()) AND (s.expires_at IS NULL OR s.expires_at > NOW())
AND COALESCE(s.purpose, 'full') = 'full'
""", """,
(x_auth_token,), (x_auth_token,),
) )
@@ -431,8 +433,17 @@ def _report_row_to_dict(row) -> dict:
# ─── Endpoints ────────────────────────────────────────────────────────────── # ─── Endpoints ──────────────────────────────────────────────────────────────
def _content_report_rate_marker(request: Request) -> None:
"""SlowAPI-Ziel für 10 Meldungen pro Stunde. Nicht als Route: der Decorator bricht die Annotationen."""
return None
limiter.limit("10/hour")(_content_report_rate_marker)
@router.post("/content-reports", status_code=201) @router.post("/content-reports", status_code=201)
def submit_content_report( def submit_content_report(
request: Request,
body: ContentReportCreate, body: ContentReportCreate,
x_auth_token: Optional[str] = Header(default=None), x_auth_token: Optional[str] = Header(default=None),
): ):
@@ -450,6 +461,7 @@ def submit_content_report(
status_code=400, status_code=400,
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.", detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
) )
limiter._check_request_limit(request, _content_report_rate_marker, False)
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal" priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
+118 -9
View File
@@ -4,7 +4,7 @@ Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral. AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
""" """
import json import json
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Mapping, Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
@@ -19,6 +19,7 @@ from club_tenancy import (
assert_library_content_editable, assert_library_content_editable,
assert_library_content_governance_transition, assert_library_content_governance_transition,
assert_valid_governance_visibility, assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile, library_content_visible_to_profile,
) )
@@ -176,6 +177,87 @@ def _assert_variant_for_exercise(cur, exercise_id: int, variant_id: Optional[int
raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung") raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung")
def _exercise_allowed_in_progression_graph(
exercise_row: Mapping[str, Any],
*,
graph_visibility: str,
graph_club_id: Optional[int],
profile_id: int,
role: str,
) -> bool:
"""Prüft, ob eine Übung zur Sichtbarkeit des Progressionsgraphen passt."""
ex_vis = (exercise_row.get("visibility") or "private").strip().lower()
gvis = (graph_visibility or "private").strip().lower()
if gvis == "private":
if ex_vis == "official":
return True
if ex_vis == "club":
return True
if ex_vis == "private":
if is_platform_admin(role):
return True
try:
return int(exercise_row.get("created_by") or 0) == int(profile_id)
except (TypeError, ValueError):
return False
return False
if gvis == "club":
if ex_vis == "official":
return True
if ex_vis != "club":
return False
ex_club = exercise_row.get("club_id")
if ex_club is None:
return False
if graph_club_id is None:
return True
return int(ex_club) == int(graph_club_id)
return ex_vis == "official"
def _assert_exercises_allowed_in_graph(
cur,
graph_id: int,
profile_id: int,
role: str,
*exercise_ids: int,
) -> None:
"""400 wenn eine Übung nicht zur Graph-Sichtbarkeit passt."""
row = _graph_row(cur, graph_id)
gvis = (row.get("visibility") or "private").strip().lower()
gclub_raw = row.get("club_id")
gclub = int(gclub_raw) if gclub_raw is not None else None
unique = list(dict.fromkeys(exercise_ids))
if not unique:
return
ph = ",".join(["%s"] * len(unique))
cur.execute(
f"SELECT id, title, visibility, club_id, created_by FROM exercises WHERE id IN ({ph})",
tuple(unique),
)
by_id = {int(r2d(r)["id"]): r2d(r) for r in cur.fetchall()}
for eid in unique:
ex = by_id.get(int(eid))
if not ex:
continue
if _exercise_allowed_in_progression_graph(
ex,
graph_visibility=gvis,
graph_club_id=gclub,
profile_id=profile_id,
role=role,
):
continue
title = (ex.get("title") or "").strip() or f"#{eid}"
raise HTTPException(
status_code=400,
detail=(
f"Übung „{title}“ (Sichtbarkeit: {ex.get('visibility') or 'private'}) "
f"passt nicht zum Progressionsgraphen ({gvis})."
),
)
def _insert_edge_row( def _insert_edge_row(
cur, cur,
graph_id: int, graph_id: int,
@@ -312,6 +394,22 @@ def _collect_graph_referenced_exercise_ids(cur, graph_id: int) -> set[int]:
return ids return ids
def _graph_promotion_transition(graph_visibility: str, target_visibility: str) -> Optional[tuple[str, ...]]:
"""
Erlaubte Graph-Promotions und welche Übungs-Sichtbarkeiten mit angehoben werden müssen.
Returns None wenn kein Übungs-Promotion-Hinweis nötig.
"""
gvis = (graph_visibility or "private").strip().lower()
tvis = (target_visibility or "").strip().lower()
transitions: Dict[tuple[str, str], tuple[str, ...]] = {
("private", "club"): ("private",),
("private", "official"): ("private", "club"),
("club", "official"): ("private", "club"),
}
return transitions.get((gvis, tvis))
@router.get("/exercise-progression-graphs/{graph_id}/visibility-promotion-candidates") @router.get("/exercise-progression-graphs/{graph_id}/visibility-promotion-candidates")
def list_visibility_promotion_candidates( def list_visibility_promotion_candidates(
graph_id: int, graph_id: int,
@@ -319,7 +417,9 @@ def list_visibility_promotion_candidates(
tenant: TenantContext = Depends(get_tenant_context), tenant: TenantContext = Depends(get_tenant_context),
): ):
""" """
Private Übungen im Graph, die bei Promotion des Graphen mit angehoben werden müssten. Übungen im Graph, die bei Promotion des Graphen mit angehoben werden müssten.
Unterstützt: private→club, private→official, club→official.
""" """
profile_id = tenant.profile_id profile_id = tenant.profile_id
role = tenant.global_role role = tenant.global_role
@@ -327,11 +427,13 @@ def list_visibility_promotion_candidates(
cur = get_cursor(conn) cur = get_cursor(conn)
row = _require_graph_read(cur, graph_id, profile_id, role) row = _require_graph_read(cur, graph_id, profile_id, role)
graph_vis = (row.get("visibility") or "private").strip().lower() graph_vis = (row.get("visibility") or "private").strip().lower()
if graph_vis != "private" or target_visibility != "club": target_vis = (target_visibility or "club").strip().lower()
need_vis = _graph_promotion_transition(graph_vis, target_vis)
if not need_vis:
return { return {
"graph_id": graph_id, "graph_id": graph_id,
"graph_visibility": graph_vis, "graph_visibility": graph_vis,
"target_visibility": target_visibility, "target_visibility": target_vis,
"exercises": [], "exercises": [],
} }
ref_ids = _collect_graph_referenced_exercise_ids(cur, graph_id) ref_ids = _collect_graph_referenced_exercise_ids(cur, graph_id)
@@ -339,19 +441,20 @@ def list_visibility_promotion_candidates(
return { return {
"graph_id": graph_id, "graph_id": graph_id,
"graph_visibility": graph_vis, "graph_visibility": graph_vis,
"target_visibility": target_visibility, "target_visibility": target_vis,
"exercises": [], "exercises": [],
} }
vis_placeholders = ",".join(["%s"] * len(need_vis))
ph = ",".join(["%s"] * len(ref_ids)) ph = ",".join(["%s"] * len(ref_ids))
cur.execute( cur.execute(
f""" f"""
SELECT id, title, visibility, club_id, created_by SELECT id, title, visibility, club_id, created_by
FROM exercises FROM exercises
WHERE id IN ({ph}) WHERE id IN ({ph})
AND LOWER(TRIM(COALESCE(visibility, ''))) = 'private' AND LOWER(TRIM(COALESCE(visibility, ''))) IN ({vis_placeholders})
ORDER BY title ORDER BY title
""", """,
list(ref_ids), list(ref_ids) + list(need_vis),
) )
exercises = [] exercises = []
for ex in cur.fetchall(): for ex in cur.fetchall():
@@ -359,8 +462,10 @@ def list_visibility_promotion_candidates(
if not library_content_visible_to_profile( if not library_content_visible_to_profile(
cur, cur,
profile_id, profile_id,
(exd.get("visibility") or "private").strip().lower(),
exd.get("club_id"),
exd.get("created_by"),
role, role,
exd,
): ):
continue continue
exercises.append( exercises.append(
@@ -373,7 +478,7 @@ def list_visibility_promotion_candidates(
return { return {
"graph_id": graph_id, "graph_id": graph_id,
"graph_visibility": graph_vis, "graph_visibility": graph_vis,
"target_visibility": target_visibility, "target_visibility": target_vis,
"exercises": exercises, "exercises": exercises,
} }
@@ -565,6 +670,9 @@ def create_progression_edge(
cur = get_cursor(conn) cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role) _require_graph_write(cur, graph_id, profile_id, role)
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id) _assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
_assert_exercises_allowed_in_graph(
cur, graph_id, profile_id, role, body.from_exercise_id, body.to_exercise_id
)
fv = body.from_exercise_variant_id fv = body.from_exercise_variant_id
tv = body.to_exercise_variant_id tv = body.to_exercise_variant_id
_assert_variant_for_exercise(cur, body.from_exercise_id, fv) _assert_variant_for_exercise(cur, body.from_exercise_id, fv)
@@ -613,6 +721,7 @@ def create_progression_sequence(
ex_ids = [s.exercise_id for s in steps] ex_ids = [s.exercise_id for s in steps]
_assert_exercises_exist(cur, *ex_ids) _assert_exercises_exist(cur, *ex_ids)
_assert_exercises_allowed_in_graph(cur, graph_id, profile_id, role, *ex_ids)
try: try:
for i in range(n_seg): for i in range(n_seg):
+27 -33
View File
@@ -163,24 +163,9 @@ ALLOWED_UPLOAD_MIMES = frozenset(
} }
) )
# Dateiendung → MIME wenn der Client keinen sinnvollen Content-Type sendet (häufig mobil / iOS).
_UPLOAD_FILENAME_MIME_FALLBACK = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".heic": "image/heic",
".heif": "image/heif",
".mp4": "video/mp4",
".mov": "video/quicktime",
".pdf": "application/pdf",
}
def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]: def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
"""Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic).""" """Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic)."""
if len(raw) < 12:
return None
if raw[:3] == b"\xff\xd8\xff": if raw[:3] == b"\xff\xd8\xff":
return "image/jpeg" return "image/jpeg"
if raw[:8] == b"\x89PNG\r\n\x1a\n": if raw[:8] == b"\x89PNG\r\n\x1a\n":
@@ -189,7 +174,7 @@ def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
return "image/gif" return "image/gif"
if raw[:4] == b"%PDF": if raw[:4] == b"%PDF":
return "application/pdf" return "application/pdf"
if raw[4:8] != b"ftyp": if len(raw) < 12 or raw[4:8] != b"ftyp":
return None return None
brand = raw[8:12] brand = raw[8:12]
# HEIC / HEIF (u. a. iPhone „高效率“) # HEIC / HEIF (u. a. iPhone „高效率“)
@@ -208,17 +193,11 @@ def resolve_upload_mime_type(
content_type: Optional[str], content_type: Optional[str],
filename: Optional[str], filename: Optional[str],
) -> str: ) -> str:
"""Ermittelt ein erlaubtes MIME (Client-Header, Magic Bytes oder Dateiendung).""" """MIME nur aus dem Dateiinhalt. Client-Header und Dateiendung entscheiden nicht."""
ct = (content_type or "").split(";")[0].strip().lower()
if ct in ALLOWED_UPLOAD_MIMES:
return ct
guessed = _sniff_allowed_upload_mime(raw) guessed = _sniff_allowed_upload_mime(raw)
if guessed in ALLOWED_UPLOAD_MIMES: if guessed in ALLOWED_UPLOAD_MIMES:
return guessed return guessed
ext = Path(filename or "").suffix.lower() ct = (content_type or "").split(";")[0].strip().lower()
fb = _UPLOAD_FILENAME_MIME_FALLBACK.get(ext)
if fb in ALLOWED_UPLOAD_MIMES:
return fb
raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}") raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}")
@@ -3083,16 +3062,28 @@ def delete_exercise_variant(
return {"ok": True} return {"ok": True}
def _content_disposition_inline(filename: Optional[str]) -> str: def _safe_download_name(filename: Optional[str]) -> str:
"""Inline-Darstellung im Browser (<video>/<img>), keine attachment-Download-Leiste.""" """Dateiname ohne Steuerzeichen und ohne Anführungszeichen für Content-Disposition."""
if not filename: if not filename:
return "inline" return ""
fn = str(filename).strip() cleaned = []
for ch in str(filename):
if ch < " " or ch == "\x7f" or ch in {'"', "\\", ";"}:
continue
cleaned.append(ch)
return "".join(cleaned).strip()[:180]
def _content_disposition(filename: Optional[str], *, attachment: bool) -> str:
"""Bilder und Videos inline. PDF als Anhang. Dateiname ohne Steuerzeichen."""
disposition = "attachment" if attachment else "inline"
fn = _safe_download_name(filename)
if not fn:
return disposition
quoted = quote(fn, safe="") quoted = quote(fn, safe="")
escaped = fn.replace('"', "\\")
if quoted != fn: if quoted != fn:
return f"inline; filename*=utf-8''{quoted}" return f"{disposition}; filename*=utf-8''{quoted}"
return f'inline; filename="{escaped}"' return f'{disposition}; filename="{fn}"'
def _parse_bytes_range_single(range_header: str, file_size: int) -> Optional[Tuple[int, int]]: def _parse_bytes_range_single(range_header: str, file_size: int) -> Optional[Tuple[int, int]]:
@@ -3152,7 +3143,10 @@ def _binary_media_response(
path_str = str(path_arg.resolve()) path_str = str(path_arg.resolve())
stat_r = os.stat(path_str) stat_r = os.stat(path_str)
file_size = int(stat_r.st_size) file_size = int(stat_r.st_size)
cd_val = _content_disposition_inline(download_name) cd_val = _content_disposition(
download_name,
attachment=(mime_type or "").split(";")[0].strip().lower() == "application/pdf",
)
base_h = {"accept-ranges": "bytes", "content-disposition": cd_val} base_h = {"accept-ranges": "bytes", "content-disposition": cd_val}
if request.method.upper() == "HEAD": if request.method.upper() == "HEAD":
@@ -3224,7 +3218,7 @@ def download_exercise_media_file(
tenant: TenantContext = Depends(get_tenant_context_flexible), tenant: TenantContext = Depends(get_tenant_context_flexible),
): ):
""" """
Dateiauslieferung mit Governance wie GET Übung — Auth via X-Auth-Token oder ?ssetoken (für <img>/<video>). Dateiauslieferung mit Governance wie GET Übung — Header-Sitzung oder kurzlebiges Medien-Token (?ssetoken).
Unterstützt HTTP Range (206) für MP4-Streaming und Content-Disposition: inline (kein attachment). Unterstützt HTTP Range (206) für MP4-Streaming und Content-Disposition: inline (kein attachment).
""" """
with get_db() as conn: with get_db() as conn:
+1 -1
View File
@@ -1225,7 +1225,7 @@ def download_media_asset_file(
asset_id: int, asset_id: int,
tenant: TenantContext = Depends(get_tenant_context_flexible), tenant: TenantContext = Depends(get_tenant_context_flexible),
): ):
"""Direktzugriff auf Archiv-Datei (Thumbnail/Vorschau); Auth wie Übungs-Medien (?ssetoken).""" """Direktzugriff auf Archiv-Datei. Auth per Header oder kurzlebigem Medien-Token (?ssetoken)."""
from routers.exercises import _binary_media_response from routers.exercises import _binary_media_response
with get_db() as conn: with get_db() as conn:
+15 -3
View File
@@ -7,6 +7,7 @@ from db import get_db, get_cursor
from tenant_context import TenantContext, get_tenant_context from tenant_context import TenantContext, get_tenant_context
from planning_exercise_suggest import PlanningExerciseSuggestRequest, suggest_planning_exercises from planning_exercise_suggest import PlanningExerciseSuggestRequest, suggest_planning_exercises
from planning_exercise_path_builder import ProgressionPathSuggestRequest, suggest_progression_path from planning_exercise_path_builder import ProgressionPathSuggestRequest, suggest_progression_path
from planning_llm_usage import planning_llm_call_meter
from account_lifecycle import assert_min_account_state from account_lifecycle import assert_min_account_state
from capabilities import probe_capability from capabilities import probe_capability
from club_features import ( from club_features import (
@@ -46,19 +47,25 @@ def post_planning_exercise_suggest(
) )
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
with planning_llm_call_meter() as llm_meter:
result = suggest_planning_exercises(cur, tenant=tenant, body=body) result = suggest_planning_exercises(cur, tenant=tenant, body=body)
if uses_ai: if uses_ai and llm_meter.count > 0:
usage = consume_club_feature_with_usage( usage = consume_club_feature_with_usage(
feature_id="ai_calls", feature_id="ai_calls",
club_id=club_id, club_id=club_id,
profile_id=tenant.profile_id, profile_id=tenant.profile_id,
portal_role=tenant.global_role, portal_role=tenant.global_role,
action="planning_suggest", action="planning_suggest",
amount=llm_meter.count,
cur=cur, cur=cur,
tenant=tenant, tenant=tenant,
conn=conn, conn=conn,
) )
result = merge_feature_usage_into_response(result, usage) result = merge_feature_usage_into_response(result, usage)
if isinstance(result, dict):
result["llm_call_count"] = llm_meter.count
elif uses_ai and isinstance(result, dict):
result["llm_call_count"] = 0
return result return result
@@ -70,7 +77,6 @@ def post_progression_path_suggest(
uses_ai = ( uses_ai = (
body.include_llm_intent body.include_llm_intent
or body.include_llm_path_qa or body.include_llm_path_qa
or body.include_ai_gap_fill
or body.include_llm_roadmap or body.include_llm_roadmap
or body.include_llm_start_target or body.include_llm_start_target
or (body.start_target_only and body.include_llm_start_target) or (body.start_target_only and body.include_llm_start_target)
@@ -98,17 +104,23 @@ def post_progression_path_suggest(
) )
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
with planning_llm_call_meter() as llm_meter:
result = suggest_progression_path(cur, tenant=tenant, body=body) result = suggest_progression_path(cur, tenant=tenant, body=body)
if uses_ai: if uses_ai and llm_meter.count > 0:
usage = consume_club_feature_with_usage( usage = consume_club_feature_with_usage(
feature_id="ai_calls", feature_id="ai_calls",
club_id=club_id, club_id=club_id,
profile_id=tenant.profile_id, profile_id=tenant.profile_id,
portal_role=tenant.global_role, portal_role=tenant.global_role,
action="progression_path_suggest", action="progression_path_suggest",
amount=llm_meter.count,
cur=cur, cur=cur,
tenant=tenant, tenant=tenant,
conn=conn, conn=conn,
) )
result = merge_feature_usage_into_response(result, usage) result = merge_feature_usage_into_response(result, usage)
if isinstance(result, dict):
result["llm_call_count"] = llm_meter.count
elif uses_ai and isinstance(result, dict):
result["llm_call_count"] = 0
return result return result
+56 -10
View File
@@ -14,7 +14,7 @@ from psycopg2.extras import Json
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field, field_validator
from db import get_db, get_cursor, r2d from db import get_db, get_cursor, r2d
from auth import require_auth, hash_pin from auth import require_auth, hash_pin, revoke_profile_sessions
from club_tenancy import ( from club_tenancy import (
assert_club_member, assert_club_member,
club_ids_for_profile_with_roles, club_ids_for_profile_with_roles,
@@ -30,6 +30,19 @@ router = APIRouter(prefix="/api", tags=["profiles"])
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"}) _ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"}) _CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
_PROFILE_SECRET_FIELDS = (
"pin_hash",
"totp_secret",
"totp_pending_secret",
"verification_token",
)
def _public_profile_row(row) -> dict:
data = r2d(row)
for key in _PROFILE_SECRET_FIELDS:
data.pop(key, None)
return data
class ManagementPasswordResetBody(BaseModel): class ManagementPasswordResetBody(BaseModel):
@@ -103,8 +116,7 @@ def get_current_profile(
row = cur.fetchone() row = cur.fetchone()
if not row: if not row:
raise HTTPException(404, "Profil nicht gefunden") raise HTTPException(404, "Profil nicht gefunden")
data = r2d(row) data = _public_profile_row(row)
data.pop("pin_hash", None)
clubs = memberships_with_roles(cur, profile_id, active_only=False) clubs = memberships_with_roles(cur, profile_id, active_only=False)
data["clubs"] = clubs data["clubs"] = clubs
ac_raw = data.get("active_club_id") ac_raw = data.get("active_club_id")
@@ -140,9 +152,7 @@ def list_profiles(session=Depends(require_auth)):
rows = cur.fetchall() rows = cur.fetchall()
out = [] out = []
for r in rows: for r in rows:
d = r2d(r) out.append(_public_profile_row(r))
d.pop("pin_hash", None)
out.append(d)
return out return out
@@ -203,9 +213,7 @@ def profile_document(pid: str) -> dict:
row = cur.fetchone() row = cur.fetchone()
if not row: if not row:
raise HTTPException(404, "Profil nicht gefunden") raise HTTPException(404, "Profil nicht gefunden")
d = r2d(row) return _public_profile_row(row)
d.pop("pin_hash", None)
return d
@router.post("/profiles/{pid}/management-password-reset") @router.post("/profiles/{pid}/management-password-reset")
@@ -245,9 +253,14 @@ def management_password_reset(
_assert_can_management_password_help(cur, tenant, target, via_email=False) _assert_can_management_password_help(cur, tenant, target, via_email=False)
new_hash = hash_pin(body.new_password) new_hash = hash_pin(body.new_password)
cur.execute( cur.execute(
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s", """
UPDATE profiles
SET pin_hash = %s, failed_login_count = 0, locked_until = NULL, updated_at = NOW()
WHERE id = %s
""",
(new_hash, target), (new_hash, target),
) )
revoke_profile_sessions(cur, target)
return {"ok": True, "mode": "direct"} return {"ok": True, "mode": "direct"}
_assert_can_management_password_help(cur, tenant, target, via_email=True) _assert_can_management_password_help(cur, tenant, target, via_email=True)
@@ -270,6 +283,39 @@ def management_password_reset(
return {"ok": True, "mode": "email", "email_sent": bool(sent)} return {"ok": True, "mode": "email", "email_sent": bool(sent)}
@router.post("/profiles/{pid}/totp-reset")
def management_totp_reset(pid: str, tenant: TenantContext = Depends(get_tenant_context)):
"""Superadmin schaltet Zwei-Faktor ab, wenn der Nutzer den Authenticator nicht mehr hat."""
if not is_superadmin(tenant.global_role or ""):
raise HTTPException(status_code=403, detail="Nur Super-Admins")
try:
target = int(pid)
except ValueError:
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
if target == int(tenant.profile_id):
raise HTTPException(status_code=400, detail="Eigenen Zwei-Faktor unter Einstellungen ändern")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id, totp_enabled FROM profiles WHERE id=%s", (target,))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
if not row.get("totp_enabled"):
return {"ok": True, "totp_enabled": False, "changed": False}
cur.execute(
"""
UPDATE profiles
SET totp_enabled=FALSE, totp_secret=NULL, totp_pending_secret=NULL, updated_at=NOW()
WHERE id=%s
""",
(target,),
)
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (target,))
revoke_profile_sessions(cur, target)
return {"ok": True, "totp_enabled": False, "changed": True}
@router.get("/profiles/{pid}") @router.get("/profiles/{pid}")
def get_profile(pid: str, session=Depends(require_auth)): def get_profile(pid: str, session=Depends(require_auth)):
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT).""" """Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
@@ -29,6 +29,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
"admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant "admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant
"admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant "admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant
"catalogs.py", "catalogs.py",
"catalog_prompt_slots.py", # Admin Stammdaten KI-Prompt-Slots; require_auth + admin/superadmin — globaler Katalog, kein Vereinsmandant
"skills.py", "skills.py",
"maturity_models.py", "maturity_models.py",
"matrix_stack_bundle.py", "matrix_stack_bundle.py",
+2 -2
View File
@@ -2,12 +2,12 @@
""" """
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig). Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
Lauf z. B. täglich per Cron: Einzellauf (der tägliche Planer ist media_retention_scheduler.py):
cd /path/to/backend && python scripts/media_retention_job.py cd /path/to/backend && python scripts/media_retention_job.py
Umgebung wie Backend (DB_*), optional: Umgebung wie Backend (DB_*), optional:
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30) MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 90) MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 30)
""" """
from __future__ import annotations from __future__ import annotations
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Täglicher Start von media_retention_job.py um 03:00 Europe/Berlin.
Der Prozess löscht beim Start nichts. Ein Lauf sofort nach dem Start nur mit
RETENTION_RUN_ON_START=1. Ein fehlgeschlagener Lauf bleibt im Log
(RETENTION_FAIL); der Prozess bleibt aktiv, damit Docker ihn nicht sofort
erneut startet.
"""
from __future__ import annotations
import logging
import os
import subprocess
import sys
import time
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
LOG = logging.getLogger("retention.scheduler")
DEFAULT_TZ = "Europe/Berlin"
_RUN_ON_START = "RETENTION_RUN_ON_START"
_TZ_ENV = "RETENTION_TZ"
def retention_zone() -> ZoneInfo:
name = os.environ.get(_TZ_ENV, DEFAULT_TZ).strip() or DEFAULT_TZ
return ZoneInfo(name)
def next_run_at(now: datetime, *, hour: int = 3) -> datetime:
"""Nächste Uhrzeit `hour`:00 in der Zeitzone von `now`.
`now` muss zeitzonenbewusst sein. Die Zone von `now` ist die Planungszone.
"""
if now.tzinfo is None:
raise ValueError("now muss eine Zeitzone tragen")
zone = now.tzinfo
local = now.astimezone(zone)
day = local.date()
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
if target.timestamp() <= local.timestamp():
day = day + timedelta(days=1)
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
return target
def seconds_until_next_0300(now: datetime, *, hour: int = 3) -> float:
"""Sekunden bis zum nächsten Lauf, als absolute Dauer.
`target - now` zieht bei gleicher tzinfo die Wanduhr ab und liegt an
Umstellungstagen um eine Stunde daneben. `timestamp()` rechnet in UTC.
"""
target = next_run_at(now, hour=hour)
local = now.astimezone(target.tzinfo)
return target.timestamp() - local.timestamp()
def _job_path() -> str:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "media_retention_job.py")
def _run_on_start() -> bool:
return os.environ.get(_RUN_ON_START, "").strip() == "1"
def run_job() -> int:
"""Startet den Retention-Job. Führt keine Löschung in diesem Prozess aus."""
LOG.info("Retention-Lauf startet")
completed = subprocess.run([sys.executable, "-u", _job_path()], check=False)
if completed.returncode != 0:
LOG.error("RETENTION_FAIL exit=%s", completed.returncode)
else:
LOG.info("RETENTION_OK")
return int(completed.returncode)
def serve(
*,
iterations: int | None = None,
sleep=time.sleep,
clock=None,
run=None,
) -> None:
zone = retention_zone()
if clock is None:
def clock() -> datetime:
return datetime.now(zone)
execute = run if run is not None else run_job
if _run_on_start():
LOG.info("Sofortlauf wegen RETENTION_RUN_ON_START=1")
execute()
completed = 0
while iterations is None or completed < iterations:
target = next_run_at(clock())
LOG.info("Nächster Retention-Lauf %s", target.isoformat(timespec="seconds"))
while True:
remaining = target.timestamp() - clock().timestamp()
if remaining <= 1:
break
LOG.info("Warte %.0f Sekunden bis %s", remaining, target.isoformat(timespec="seconds"))
sleep(remaining)
execute()
completed += 1
def main() -> int:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stdout,
force=True,
)
serve()
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,89 @@
"""Admin-Vorschau für Planungs-Prompt-Slugs."""
from unittest.mock import MagicMock, patch
import pytest
from ai_prompt_planning_preview import (
PLANNING_PROMPT_SLUGS,
PlanningPromptPreviewInput,
is_planning_prompt_slug,
resolve_planning_prompt_preview_variables,
)
def test_is_planning_prompt_slug():
assert is_planning_prompt_slug("planning_progression_roadmap")
assert is_planning_prompt_slug("PLANNING_EXERCISE_PATH_QA")
assert not is_planning_prompt_slug("exercise_summary")
assert not is_planning_prompt_slug("")
def test_resolve_roadmap_preview_variables():
body = PlanningPromptPreviewInput(goal_query="Mae Geri Basics", max_steps=4)
vars_map = resolve_planning_prompt_preview_variables(
MagicMock(),
"planning_progression_roadmap",
body,
)
assert vars_map["goal_query"] == "Mae Geri Basics"
assert vars_map["max_steps"] == "4"
assert "goal_analysis_json" in vars_map
assert "semantic_brief_json" in vars_map
def test_resolve_stage_spec_includes_intent_context():
body = PlanningPromptPreviewInput(user_notes="Breitensport")
vars_map = resolve_planning_prompt_preview_variables(
MagicMock(),
"planning_progression_stage_spec",
body,
)
assert "intent_context_json" in vars_map
assert "major_steps_json" in vars_map
@patch("ai_prompt_planning_preview._load_catalog_variables")
def test_resolve_search_intent_includes_catalogs(mock_catalog):
mock_catalog.return_value = {
"skills_catalog_json": "[]",
"focus_areas_catalog_json": "[]",
"training_types_catalog_json": "[]",
"style_directions_catalog_json": "[]",
"target_groups_catalog_json": "[]",
}
body = PlanningPromptPreviewInput(search_query="Mae Geri nächster Schritt")
vars_map = resolve_planning_prompt_preview_variables(
MagicMock(),
"planning_exercise_search_intent",
body,
)
assert vars_map["search_query"] == "Mae Geri nächster Schritt"
assert vars_map["skills_catalog_json"] == "[]"
def test_non_planning_slug_raises():
with pytest.raises(ValueError, match="Kein Planungs-Prompt-Slug"):
resolve_planning_prompt_preview_variables(
MagicMock(),
"exercise_summary",
PlanningPromptPreviewInput(),
)
def test_all_registered_slugs_resolve():
for slug in PLANNING_PROMPT_SLUGS:
with patch("ai_prompt_planning_preview._load_catalog_variables") as mock_catalog:
mock_catalog.return_value = {
"skills_catalog_json": "[]",
"focus_areas_catalog_json": "[]",
"training_types_catalog_json": "[]",
"style_directions_catalog_json": "[]",
"target_groups_catalog_json": "[]",
}
vars_map = resolve_planning_prompt_preview_variables(
MagicMock(),
slug,
PlanningPromptPreviewInput(),
)
assert isinstance(vars_map, dict)
assert len(vars_map) >= 1
+86
View File
@@ -0,0 +1,86 @@
"""Login-Sperre, TOTP und Medien-Grant ohne Datenbank."""
from __future__ import annotations
import os
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
os.environ.setdefault("REQUIRE_ADMIN_TOTP", "0")
import pytest
from fastapi.testclient import TestClient
from main import app
from media_grant import issue_media_grant, profile_id_from_media_grant
from totp_auth import generate_totp_secret, totp_code, verify_totp
import time
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
def test_totp_accepts_current_code() -> None:
secret = generate_totp_secret()
code = totp_code(secret, int(time.time()) // 30)
assert verify_totp(secret, code)
assert not verify_totp(secret, "000000") or code == "000000"
def test_media_grant_rejects_session_shaped_token() -> None:
assert profile_id_from_media_grant("not-a-media-grant") is None
token, _exp = issue_media_grant(42, ttl_seconds=60)
assert profile_id_from_media_grant(token) == 42
assert profile_id_from_media_grant(token + "x") is None
def test_change_password_requires_current_password() -> None:
from pydantic import ValidationError
from models import ChangePasswordRequest
with pytest.raises(ValidationError):
ChangePasswordRequest.model_validate({"pin": "neuespasswort"})
def test_password_reset_rejects_header_injection() -> None:
from pydantic import ValidationError
from models import PasswordResetRequest, ResendVerificationRequest
with pytest.raises(ValidationError):
PasswordResetRequest.model_validate({"email": "trainer@example.com\nBcc: x@y.z"})
with pytest.raises(ValidationError):
ResendVerificationRequest.model_validate({"email": "nicht-eine-email"})
def test_upload_mime_comes_from_bytes_not_client_header() -> None:
from routers.exercises import _content_disposition, resolve_upload_mime_type
jpeg = b"\xff\xd8\xff" + b"\x00" * 16
assert resolve_upload_mime_type(jpeg, "text/html", "evil.html") == "image/jpeg"
pdf = b"%PDF-1.4\n" + b"0" * 8
assert resolve_upload_mime_type(pdf, "image/png", "bild.png") == "application/pdf"
try:
resolve_upload_mime_type(b"<html><script>alert(1)</script></html>", "image/jpeg", "x.jpg")
raised = False
except ValueError:
raised = True
assert raised
disposition = _content_disposition('bericht.pdf\r\nX-Evil: 1', attachment=True)
assert disposition.startswith("attachment")
assert "\r" not in disposition
assert "\n" not in disposition
def test_totp_reset_requires_auth(client: TestClient) -> None:
response = client.post("/api/profiles/1/totp-reset")
assert response.status_code == 401
def test_login_rejects_oversized_password(client: TestClient) -> None:
response = client.post(
"/api/auth/login",
json={"email": "trainer@example.com", "password": "x" * 200},
)
assert response.status_code == 422
@@ -0,0 +1,38 @@
"""Tests Namens-Fallback für Katalog-Prompt-Slots."""
from catalog_slot_fallbacks import get_fallback_slots_for_entry, merge_stored_slots_with_fallbacks
from catalog_prompt_slots import _resolve_entry_slot_values
def test_karate_fallback_has_path_qa():
pack = get_fallback_slots_for_entry("focus_area", "Karate")
assert "Kohärente Progression" in pack.get("hints_on_path_qa", "")
def test_db_value_overrides_fallback():
merged = merge_stored_slots_with_fallbacks(
{"hints_on_path_qa": "Eigener QS-Text."},
catalog_kind="focus_area",
name="Karate",
stammdaten_description="Traditionelles Karate",
)
assert merged["hints_on_path_qa"] == "Eigener QS-Text."
def test_empty_db_uses_karate_fallback():
merged = _resolve_entry_slot_values(
{},
{"name": "Karate", "description": "Traditionelles Karate"},
"focus_area",
)
assert "Kihon-Progression" in merged["description"] or "Technik-Curriculum" in merged["description"]
assert "Kohärente Progression" in merged["hints_on_path_qa"]
def test_gewaltschutz_fallback_no_kumite():
merged = _resolve_entry_slot_values(
{},
{"name": "Gewaltschutz", "description": "Gewaltprävention"},
"focus_area",
)
assert "Deeskalation" in merged["hints_on_path_qa"]
assert "Kumite-Tiefe" in merged["anti_patterns"]
@@ -0,0 +1,80 @@
"""Sichtbarkeit: Progressionsgraph ↔ Übungen (Promotion, Kanten, Match)."""
from routers.exercise_progression_graphs import (
_exercise_allowed_in_progression_graph,
_graph_promotion_transition,
)
def test_graph_promotion_transition_private_to_club():
assert _graph_promotion_transition("private", "club") == ("private",)
def test_graph_promotion_transition_private_to_official():
assert _graph_promotion_transition("private", "official") == ("private", "club")
def test_graph_promotion_transition_club_to_official():
assert _graph_promotion_transition("club", "official") == ("private", "club")
def test_graph_promotion_transition_noop():
assert _graph_promotion_transition("club", "club") is None
assert _graph_promotion_transition("official", "club") is None
assert _graph_promotion_transition("private", "private") is None
def test_club_graph_rejects_private_exercise():
assert not _exercise_allowed_in_progression_graph(
{"visibility": "private", "club_id": None, "created_by": 1},
graph_visibility="club",
graph_club_id=5,
profile_id=1,
role="trainer",
)
def test_club_graph_accepts_matching_club_exercise():
assert _exercise_allowed_in_progression_graph(
{"visibility": "club", "club_id": 5, "created_by": 2},
graph_visibility="club",
graph_club_id=5,
profile_id=1,
role="trainer",
)
def test_club_graph_accepts_official_exercise():
assert _exercise_allowed_in_progression_graph(
{"visibility": "official", "club_id": None, "created_by": 99},
graph_visibility="club",
graph_club_id=5,
profile_id=1,
role="trainer",
)
def test_private_graph_accepts_own_private_exercise():
assert _exercise_allowed_in_progression_graph(
{"visibility": "private", "club_id": None, "created_by": 7},
graph_visibility="private",
graph_club_id=None,
profile_id=7,
role="trainer",
)
def test_official_graph_requires_official_exercise():
assert not _exercise_allowed_in_progression_graph(
{"visibility": "club", "club_id": 5, "created_by": 2},
graph_visibility="official",
graph_club_id=None,
profile_id=1,
role="trainer",
)
assert _exercise_allowed_in_progression_graph(
{"visibility": "official", "club_id": None, "created_by": 2},
graph_visibility="official",
graph_club_id=None,
profile_id=1,
role="trainer",
)
+21 -1
View File
@@ -10,11 +10,31 @@ from exercise_rich_text import (
assert_no_inline_media_references_on_create, assert_no_inline_media_references_on_create,
collect_inline_exercise_media_ids, collect_inline_exercise_media_ids,
normalize_inline_exercise_media_markup, normalize_inline_exercise_media_markup,
sanitize_exercise_rich_html,
validate_inline_exercise_media_ids_for_exercise, validate_inline_exercise_media_ids_for_exercise,
) )
def test_normalize_curly_to_span() -> None: def test_normalize_strips_script_and_handlers() -> None:
raw = '<p onclick="alert(1)">Hallo <script>alert(1)</script></p><a href="javascript:alert(1)">Link</a>'
out = normalize_inline_exercise_media_markup(raw)
assert out is not None
lowered = out.lower()
assert "script" not in lowered
assert "onclick" not in lowered
assert "javascript:" not in lowered
assert "Hallo" in out
assert "Link" in out
def test_normalize_keeps_inline_media_span() -> None:
raw = '<span class="shinkan-inline-media evil" data-shinkan-exercise-media="7" data-shinkan-exercise-media-size="full">x</span>'
out = sanitize_exercise_rich_html(raw)
assert out is not None
assert 'data-shinkan-exercise-media="7"' in out
assert 'data-shinkan-exercise-media-size="full"' in out
assert "shinkan-inline-media" in out
assert "evil" not in out
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>' s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
out = normalize_inline_exercise_media_markup(s) out = normalize_inline_exercise_media_markup(s)
assert 'data-shinkan-exercise-media="42"' in out assert 'data-shinkan-exercise-media="42"' in out
@@ -0,0 +1,167 @@
"""Scheduler für den Papierkorb-Job: 03:00 Europe/Berlin, ohne echten Löschlauf."""
from __future__ import annotations
import logging
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
from scripts.media_retention_scheduler import (
next_run_at,
run_job,
seconds_until_next_0300,
serve,
)
BERLIN = ZoneInfo("Europe/Berlin")
def _compose_file() -> Path | None:
"""Repo-Root lokal. Im Backend-Image liegt nur /app, ohne docker-compose.yml."""
for parent in Path(__file__).resolve().parents:
candidate = parent / "docker-compose.yml"
if candidate.is_file():
return candidate
return None
def test_winter_afternoon_waits_until_next_morning() -> None:
now = datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
assert seconds_until_next_0300(now) == 17 * 3600
def test_summer_before_three_is_same_morning() -> None:
now = datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)
assert next_run_at(now).isoformat() == "2026-07-15T03:00:00+02:00"
assert seconds_until_next_0300(now) == 3600
def test_exactly_0300_waits_until_next_day() -> None:
now = datetime(2026, 1, 15, 3, 0, tzinfo=BERLIN)
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
assert seconds_until_next_0300(now) == 24 * 3600
def test_spring_forward_sleeps_absolute_22_hours() -> None:
now = datetime(2026, 3, 28, 4, 0, tzinfo=BERLIN)
target = next_run_at(now)
assert target.isoformat() == "2026-03-29T03:00:00+02:00"
assert seconds_until_next_0300(now) == 22 * 3600
assert (target - now).total_seconds() == 23 * 3600
def test_fall_back_sleeps_absolute_24_hours() -> None:
now = datetime(2026, 10, 24, 4, 0, tzinfo=BERLIN)
target = next_run_at(now)
assert target.isoformat() == "2026-10-25T03:00:00+01:00"
assert seconds_until_next_0300(now) == 24 * 3600
assert (target - now).total_seconds() == 23 * 3600
def test_naive_datetime_is_rejected() -> None:
with pytest.raises(ValueError):
next_run_at(datetime(2026, 1, 15, 10, 0))
def test_serve_sleeps_before_first_run(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
events: list[tuple] = []
def clock() -> datetime:
return state["now"]
def sleep(seconds: float) -> None:
events.append(("sleep", seconds))
state["now"] = state["now"] + timedelta(seconds=seconds)
def run() -> None:
events.append(("run",))
serve(iterations=1, sleep=sleep, clock=clock, run=run)
assert events == [("sleep", 17 * 3600), ("run",)]
def test_serve_can_run_once_on_start(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("RETENTION_RUN_ON_START", "1")
state = {"now": datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)}
events: list[str] = []
def sleep(seconds: float) -> None:
events.append("sleep")
state["now"] = state["now"] + timedelta(seconds=seconds)
serve(
iterations=1,
sleep=sleep,
clock=lambda: state["now"],
run=lambda: events.append("run"),
)
assert events == ["run", "sleep", "run"]
def test_serve_continues_after_failed_run(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
runs: list[int] = []
def sleep(seconds: float) -> None:
state["now"] = state["now"] + timedelta(seconds=seconds)
def run() -> int:
runs.append(1)
return 1
serve(iterations=2, sleep=sleep, clock=lambda: state["now"], run=run)
assert runs == [1, 1]
def test_run_job_logs_failure_without_starting_real_job(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
class Done:
returncode = 1
monkeypatch.setattr(
"scripts.media_retention_scheduler.subprocess.run",
lambda *args, **kwargs: Done(),
)
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
assert run_job() == 1
assert "RETENTION_FAIL exit=1" in caplog.text
def test_run_job_logs_success(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
class Done:
returncode = 0
seen: list[list[str]] = []
def fake_run(cmd, check=False):
seen.append(list(cmd))
return Done()
monkeypatch.setattr("scripts.media_retention_scheduler.subprocess.run", fake_run)
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
assert run_job() == 0
assert seen and seen[0][-1].endswith("media_retention_job.py")
assert "RETENTION_OK" in caplog.text
assert "RETENTION_FAIL" not in caplog.text
def test_compose_starts_scheduler_script() -> None:
compose = _compose_file()
if compose is None:
pytest.skip("docker-compose.yml liegt nicht im Backend-Image")
text = compose.read_text(encoding="utf-8")
start = text.index(" retention-cron:")
block = text[start : text.index("\nvolumes:", start)]
assert 'command: ["python", "-u", "scripts/media_retention_scheduler.py"]' in block
assert "python -c" not in block
assert 'PYTHONUNBUFFERED: "1"' in block
assert "RETENTION_RUN_ON_START" not in block
+17 -1
View File
@@ -73,8 +73,24 @@ def test_submit_requires_good_faith():
good_faith_confirmed=False, good_faith_confirmed=False,
) )
from routers.content_reports import submit_content_report from routers.content_reports import submit_content_report
from starlette.requests import Request
request = Request(
{
"type": "http",
"http_version": "1.1",
"method": "POST",
"scheme": "http",
"path": "/api/content-reports",
"raw_path": b"/api/content-reports",
"query_string": b"",
"headers": [],
"client": ("127.0.0.1", 50000),
"server": ("testserver", 80),
}
)
with pytest.raises(HTTPException) as exc: with pytest.raises(HTTPException) as exc:
submit_content_report(body) submit_content_report(request, body)
assert exc.value.status_code == 400 assert exc.value.status_code == 400
assert "Gutglauben" in exc.value.detail assert "Gutglauben" in exc.value.detail
@@ -0,0 +1,31 @@
"""Tests Trainer-Pfad-Schutz (preserve_slot_assignments)."""
from planning_exercise_path_builder import (
EvaluateStepPayload,
ProgressionPathSuggestRequest,
_assignment_preservation_active,
)
def test_assignment_preservation_explicit_flag():
body = ProgressionPathSuggestRequest(
query="Kumite Beinarbeit Progression",
preserve_slot_assignments=True,
)
assert _assignment_preservation_active(body)
def test_assignment_preservation_not_auto_from_slot_assignments():
"""Nur explizites preserve_slot_assignments — sonst wäre compare/match blockiert."""
body = ProgressionPathSuggestRequest(
query="Kumite Beinarbeit Progression",
slot_assignments=[
EvaluateStepPayload(exercise_id=10, roadmap_major_step_index=0),
EvaluateStepPayload(exercise_id=11, roadmap_major_step_index=1),
],
)
assert not _assignment_preservation_active(body)
def test_assignment_preservation_inactive_without_assignments():
body = ProgressionPathSuggestRequest(query="Kumite Beinarbeit Progression")
assert not _assignment_preservation_active(body)
@@ -45,3 +45,34 @@ def test_normalize_planning_roadmap_with_catalog_context():
} }
) )
assert out["planning_catalog_context"]["focus_areas"][0]["id"] == 4 assert out["planning_catalog_context"]["focus_areas"][0]["id"] == 4
def test_multistage_qa_splits_llm_highlights_from_fix_hints():
from planning_path_qa_pipeline import run_multistage_path_qa
result = run_multistage_path_qa(
off_topic_steps=[],
stripped_off_topic=[
{
"issue": "roadmap_unfilled",
"step_index": 1,
"reasons": ["Keine passende Übung"],
}
],
gaps=[],
llm_qa={
"overall_ok": True,
"quality_score": 0.88,
"recommendations": [
"Gute didaktische Progression",
"Optional: Vertiefung Koordination",
],
},
llm_applied=True,
)
hints = result["optimization_hints"]
llm_hints = [h for h in hints if h.get("issue") == "llm_recommendation"]
fix_hints = [h for h in hints if h.get("issue") != "llm_recommendation"]
assert len(llm_hints) >= 2
assert any(h.get("issue") == "roadmap_unfilled" for h in fix_hints)
assert result["qa_tiers"][2]["recommendations"][0].startswith("Gute didaktische")
@@ -0,0 +1,168 @@
"""Tests Katalog-Prompt-Slots (H2)."""
from unittest.mock import MagicMock
from catalog_prompt_slots import (
build_catalog_guidance_for_prompt,
pick_active_catalog_item,
placeholder_key,
resolve_catalog_prompt_variables,
)
from planning_catalog_context import PlanningCatalogContextItem, ProgressionPlanningCatalogContext
from planning_prompt_variables import merge_planning_prompt_variables
def _mock_cur(
rows_by_table=None,
slots_by_kind_id=None,
slot_types_ready=True,
):
rows_by_table = rows_by_table or {}
slots_by_kind_id = slots_by_kind_id or {}
cur = MagicMock()
def execute(sql, params=None):
sql_l = (sql or "").lower()
if "to_regclass" in sql_l:
cur.fetchone.return_value = {"t": "catalog_prompt_slot_types" if slot_types_ready else None}
return
if "from catalog_prompt_slot_types" in sql_l:
cur.fetchall.return_value = []
return
if "from catalog_prompt_slots" in sql_l:
kind, cid = params[0], int(params[1])
slot_map = slots_by_kind_id.get((kind, cid), {})
cur.fetchall.return_value = [
{"slot_key": k, "content": v} for k, v in slot_map.items()
]
return
for table, rows in rows_by_table.items():
if f"from {table}" in sql_l:
item_id = int(params[0])
raw = rows.get(item_id)
if raw is None:
cur.fetchone.return_value = None
elif isinstance(raw, dict):
cur.fetchone.return_value = {
"id": item_id,
"name": raw.get("name", ""),
"description": raw.get("description", ""),
}
else:
cur.fetchone.return_value = {
"id": item_id,
"name": str(raw),
"description": "",
}
return
cur.fetchone.return_value = None
cur.fetchall.return_value = []
cur.execute.side_effect = execute
return cur
def test_pick_active_catalog_item_primary_wins():
items = [
PlanningCatalogContextItem(id=1, is_primary=False, weight=0.9),
PlanningCatalogContextItem(id=2, is_primary=True, weight=0.5),
]
assert pick_active_catalog_item(items).id == 2
def test_granular_placeholder_focus_area_hints_on_path_qa():
cur = _mock_cur(
rows_by_table={"focus_areas": {4: {"name": "Gewaltschutz"}}},
slots_by_kind_id={
("focus_area", 4): {
"description": "Planung zielt auf Prävention und Deeskalation.",
"hints_on_path_qa": "Lücken sind fehlende Deeskalations-Stufen.",
"anti_patterns": "Nicht nach Kumite-Tiefe bewerten.",
}
},
)
catalog = ProgressionPlanningCatalogContext(
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
)
resolved = resolve_catalog_prompt_variables(cur, catalog, slug="planning_exercise_path_qa")
assert "Deeskalation" in resolved[placeholder_key("focus_area", "hints_on_path_qa")]
assert "Deeskalation" in resolved["catalog_guidance_block"]
assert resolved["has_catalog_guidance"] == "true"
def test_unknown_focus_uses_default_description_pack():
cur = _mock_cur(
rows_by_table={
"focus_areas": {
4: {
"name": "Sonderfokus Alpha",
"description": "Kurze Stammdaten-Beschreibung",
}
}
},
slots_by_kind_id={("focus_area", 4): {}},
)
catalog = ProgressionPlanningCatalogContext(
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
)
resolved = resolve_catalog_prompt_variables(cur, catalog)
desc = resolved[placeholder_key("focus_area", "description")]
assert "Technik- oder Themen-Curriculum" in desc
assert resolved[placeholder_key("focus_area", "hints_on_path_qa")]
def test_empty_without_catalog():
cur = MagicMock()
out = build_catalog_guidance_for_prompt(cur, None)
assert out["has_catalog_guidance"] is False
assert out["catalog_guidance_block"] == ""
def test_unknown_entry_gets_default_technique_fallback():
cur = _mock_cur(rows_by_table={"focus_areas": {99: {"name": "Unbekannter Fokus XYZ"}}})
catalog = ProgressionPlanningCatalogContext(
focus_areas=[PlanningCatalogContextItem(id=99, is_primary=True)],
)
out = build_catalog_guidance_for_prompt(cur, catalog)
assert out["has_catalog_guidance"] is True
assert "Unbekannter Fokus XYZ" in out["catalog_context_json"]
assert "Zwischenstufen" in out["catalog_guidance_block"] or "Progression" in out["catalog_guidance_block"]
def test_merge_planning_prompt_variables_granular_keys():
cur = _mock_cur(
rows_by_table={"focus_areas": {4: {"name": "Gewaltschutz"}}},
slots_by_kind_id={
("focus_area", 4): {"hints_on_path_qa": "Deeskalation und Grenzen."}
},
)
catalog = ProgressionPlanningCatalogContext(
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
)
merged = merge_planning_prompt_variables(
cur,
{"goal_query": "Deeskalation Kinder"},
catalog=catalog,
slug="planning_exercise_path_qa",
)
assert merged[placeholder_key("focus_area", "hints_on_path_qa")].startswith("Deeskalation")
assert merged["has_catalog_guidance"] == "true"
def test_priority_order_in_guidance_block():
cur = _mock_cur(
rows_by_table={
"focus_areas": {1: {"name": "Gewaltschutz"}},
"training_types": {2: {"name": "Breitensport"}},
},
slots_by_kind_id={
("focus_area", 1): {"description": "Fokus-Text"},
("training_type", 2): {"description": "Stil-Text"},
},
)
catalog = ProgressionPlanningCatalogContext(
focus_areas=[PlanningCatalogContextItem(id=1, is_primary=True)],
training_types=[PlanningCatalogContextItem(id=2, is_primary=True)],
)
block = build_catalog_guidance_for_prompt(cur, catalog)["catalog_guidance_block"]
assert block.index("Primärfokus") < block.index("Trainingsstil")
@@ -0,0 +1,127 @@
"""Tests Vergleichs-Diffs (triviale ID-Tausche markieren, Rematch-Filter)."""
from planning_exercise_path_builder import (
_actionable_slot_diffs,
_annotate_slot_diffs,
_build_progression_compare_response,
_build_progression_slot_diffs,
_build_rematch_suggestion_diffs,
)
def test_annotate_trivial_id_swap():
diffs = [
{
"roadmap_major_step_index": 1,
"baseline_exercise_id": 10,
"baseline_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
"proposed_exercise_id": 99,
"proposed_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
}
]
annotated = _annotate_slot_diffs(diffs)
assert len(annotated) == 1
assert annotated[0]["trivial_id_swap"] is True
assert _actionable_slot_diffs(annotated) == []
def test_annotate_keeps_real_title_change():
diffs = [
{
"roadmap_major_step_index": 1,
"baseline_exercise_id": 10,
"baseline_title": "Alt",
"proposed_exercise_id": 99,
"proposed_title": "Neu",
}
]
annotated = _annotate_slot_diffs(diffs)
assert annotated[0]["trivial_id_swap"] is False
assert len(_actionable_slot_diffs(annotated)) == 1
def test_build_slot_diffs_then_annotate():
baseline = [
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
{"roadmap_major_step_index": 1, "exercise_id": 10, "title": "Gleich"},
]
proposed = [
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
{"roadmap_major_step_index": 1, "exercise_id": 77, "title": "Gleich"},
]
raw = _build_progression_slot_diffs(baseline, proposed)
annotated = _annotate_slot_diffs(raw)
assert len(annotated) == 1
assert annotated[0]["trivial_id_swap"] is True
assert _actionable_slot_diffs(annotated) == []
def test_rematch_suggestion_skips_filled_baseline_slot():
baseline = [
{
"roadmap_major_step_index": 1,
"exercise_id": 5727,
"title": "Einführung von Richtungswechseln",
"slot_status": "preserved",
},
]
rematch_log = [
{
"roadmap_major_step_index": 1,
"action": "replaced",
"round": 3,
"new_exercise_id": 5594,
"new_title": "Kumite Beinarbeit — vertiefung",
"replaced_exercise_id": 5727,
},
]
assert _build_rematch_suggestion_diffs(baseline, rematch_log) == []
def test_rematch_suggestion_keeps_empty_baseline_slot():
baseline = [
{"roadmap_major_step_index": 1, "exercise_id": None, "title": "Lernziel Slot 2"},
]
rematch_log = [
{
"roadmap_major_step_index": 1,
"action": "replaced",
"round": 1,
"new_exercise_id": 101,
"new_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
},
]
diffs = _build_rematch_suggestion_diffs(baseline, rematch_log)
assert len(diffs) == 1
assert diffs[0]["proposed_exercise_id"] == 101
def test_compare_response_no_step_diffs_uses_baseline_qa_not_pipeline():
baseline = {
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
"path_qa": {"overall_ok": True, "quality_score": 0.88},
}
proposed = {
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
"path_qa": {"overall_ok": False, "quality_score": 0.65, "rematch_log": [{"action": "replaced"}]},
}
compare = _build_progression_compare_response(baseline, proposed, proposed_eval=None)
assert compare["slot_diff_count"] == 0
assert compare["slot_diffs_source"] == "steps"
assert compare["proposed_path_qa"]["quality_score"] == 0.65
def test_compare_wrapper_snaps_proposed_qa_to_baseline_without_diffs():
baseline = {
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
"path_qa": {"overall_ok": True, "quality_score": 0.88},
}
proposed = {
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
"path_qa": {"overall_ok": False, "quality_score": 0.65},
}
raw = _build_progression_compare_response(baseline, proposed, proposed_eval=None)
assert raw["proposed_path_qa"]["quality_score"] == 0.65
if raw.get("slot_diff_count", 0) == 0:
fair = baseline["path_qa"]
raw["proposed_path_qa"] = fair
assert raw["proposed_path_qa"]["quality_score"] == 0.88
@@ -0,0 +1,30 @@
"""Deterministische Pfad-QS ohne LLM."""
from planning_exercise_path_qa import compute_deterministic_path_quality_score
def test_deterministic_quality_score_penalizes_off_topic():
steps = [{"roadmap_major_step_index": 0, "exercise_id": 1}]
base = compute_deterministic_path_quality_score(gaps=[], off_topic_steps=[], steps=steps)
with_off = compute_deterministic_path_quality_score(
gaps=[],
off_topic_steps=[{"roadmap_major_step_index": 1}],
steps=steps,
)
assert with_off < base
def test_deterministic_quality_score_penalizes_empty_slots():
filled = [{"roadmap_major_step_index": 0, "exercise_id": 1}]
base = compute_deterministic_path_quality_score(gaps=[], off_topic_steps=[], steps=filled)
with_empty = compute_deterministic_path_quality_score(
gaps=[],
off_topic_steps=[],
steps=[{"roadmap_major_step_index": 0, "exercise_id": None}, {"roadmap_major_step_index": 1, "exercise_id": 2}],
)
all_empty = compute_deterministic_path_quality_score(
gaps=[],
off_topic_steps=[],
steps=[{"roadmap_major_step_index": 0, "exercise_id": None}] * 4,
)
assert with_empty < base
assert all_empty <= 0.15
@@ -83,6 +83,20 @@ def test_strip_off_topic_steps_from_path():
assert [s["exercise_id"] for s in out] == [1, 2, 4] assert [s["exercise_id"] for s in out] == [1, 2, 4]
def test_build_gap_fill_goal_text_includes_catalog_exercise_hints():
from planning_exercise_semantics import build_semantic_brief
brief = build_semantic_brief("Mae Geri")
text = build_gap_fill_goal_text(
goal_query="Mae Geri lernen",
brief=brief,
spec={"source": "roadmap_unfilled", "phase": "grundlage", "title_hint": "Stand"},
catalog_exercise_hints="Primärfokus: Kihon und Partnerübungen mit Technikbezug.",
)
assert "Katalog-Hinweise Übungsanlage" in text
assert "Kihon" in text
def test_build_gap_fill_goal_text_includes_topic(): def test_build_gap_fill_goal_text_includes_topic():
brief = build_semantic_brief("Mae Geri Perfektion") brief = build_semantic_brief("Mae Geri Perfektion")
text = build_gap_fill_goal_text( text = build_gap_fill_goal_text(
@@ -0,0 +1,39 @@
"""Tests inkrementelles Slot-Diff-Scoring (nur messbare Verbesserungen)."""
from planning_exercise_path_builder import (
_apply_slot_diff_to_steps,
_slot_diff_improves_path,
)
def test_slot_diff_improves_path_fill_neutral_or_positive():
fill = {"baseline_exercise_id": None, "proposed_exercise_id": 101}
assert _slot_diff_improves_path(fill, 0.0) is True
assert _slot_diff_improves_path(fill, 0.04) is True
assert _slot_diff_improves_path(fill, -0.01) is False
def test_slot_diff_improves_path_off_topic_allows_neutral_replace():
repl = {"baseline_exercise_id": 10, "proposed_exercise_id": 99}
assert _slot_diff_improves_path(repl, 0.0, off_topic=True) is True
assert _slot_diff_improves_path(repl, -0.02, off_topic=True) is False
def test_apply_slot_diff_merges_proposed_step():
baseline = [
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
{"roadmap_major_step_index": 1, "exercise_id": None, "title": "Leer"},
]
proposed = [
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
{"roadmap_major_step_index": 1, "exercise_id": 55, "title": "Neu", "slot_status": "matched"},
]
diff = {
"roadmap_major_step_index": 1,
"baseline_exercise_id": None,
"proposed_exercise_id": 55,
"proposed_title": "Neu",
}
merged = _apply_slot_diff_to_steps(baseline, diff, proposed)
assert merged[0]["exercise_id"] == 1
assert merged[1]["exercise_id"] == 55
assert merged[1]["title"] == "Neu"
+94
View File
@@ -0,0 +1,94 @@
"""LLM-Zählung für Planungs-APIs (P1-C2)."""
from unittest.mock import MagicMock, patch
import pytest
from planning_llm_usage import (
current_planning_llm_call_counter,
planning_llm_call_meter,
record_planning_llm_call,
)
def test_meter_inactive_by_default():
assert current_planning_llm_call_counter() is None
record_planning_llm_call(3)
assert current_planning_llm_call_counter() is None
def test_meter_counts_within_scope():
with planning_llm_call_meter() as meter:
record_planning_llm_call(1)
record_planning_llm_call(2)
assert meter.count == 3
def test_openrouter_increments_active_meter():
from openrouter_chat import openrouter_chat_completion
fake_resp = MagicMock()
fake_resp.status_code = 200
fake_resp.json.return_value = {
"choices": [{"message": {"content": "ok"}, "finish_reason": "stop"}],
}
with planning_llm_call_meter() as meter:
with patch("openrouter_chat.httpx.Client") as client_cls:
client = MagicMock()
client.__enter__.return_value = client
client.post.return_value = fake_resp
client_cls.return_value = client
out = openrouter_chat_completion(
api_key="test-key",
model="test/model",
user_content="hello",
)
assert out == "ok"
assert meter.count == 1
def test_openrouter_skips_meter_on_http_error():
from openrouter_chat import OpenRouterError, openrouter_chat_completion
fake_resp = MagicMock()
fake_resp.status_code = 500
fake_resp.json.return_value = {"error": {"message": "fail"}}
fake_resp.text = "fail"
with planning_llm_call_meter() as meter:
with patch("openrouter_chat.httpx.Client") as client_cls:
client = MagicMock()
client.__enter__.return_value = client
client.post.return_value = fake_resp
client_cls.return_value = client
with pytest.raises(OpenRouterError):
openrouter_chat_completion(
api_key="test-key",
model="test/model",
user_content="hello",
)
assert meter.count == 0
def test_uses_ai_gap_fill_not_counted_without_openrouter():
"""Regression: Gap-Fill-Flag allein löst keinen OpenRouter-Aufruf aus."""
from planning_exercise_path_builder import ProgressionPathSuggestRequest
body = ProgressionPathSuggestRequest(
query="Mae Geri Progression",
include_llm_intent=False,
include_llm_path_qa=False,
include_llm_roadmap=False,
include_llm_start_target=False,
include_ai_gap_fill=True,
evaluate_only=True,
evaluate_steps=[],
)
uses_ai = (
body.include_llm_intent
or body.include_llm_path_qa
or body.include_llm_roadmap
or body.include_llm_start_target
or (body.start_target_only and body.include_llm_start_target)
)
assert uses_ai is False
@@ -0,0 +1,62 @@
"""Getrennte Roadmap- vs. Besetzungs-QS."""
from planning_exercise_path_qa import (
build_assignment_qa_snapshot,
build_path_qa_summary,
compute_assignment_quality_score,
merge_path_quality_scores,
)
def _empty_steps(n: int):
return [{"roadmap_major_step_index": i, "exercise_id": None} for i in range(n)]
def test_assignment_quality_all_empty_slots_is_low():
steps = _empty_steps(5)
score = compute_assignment_quality_score(steps=steps, off_topic_steps=[], gaps=[])
assert score <= 0.15
def test_assignment_quality_all_filled_is_high():
steps = [{"roadmap_major_step_index": i, "exercise_id": i + 1} for i in range(5)]
score = compute_assignment_quality_score(steps=steps, off_topic_steps=[], gaps=[])
assert score >= 0.9
def test_build_path_qa_summary_caps_llm_score_when_slots_empty():
steps = _empty_steps(4)
summary = build_path_qa_summary(
gaps=[],
bridge_inserts=[],
ai_proposals=[],
off_topic_steps=[],
stripped_off_topic=[],
llm_qa={
"overall_ok": True,
"quality_score": 0.88,
"topic_coverage": "Roadmap deckt Ziel gut ab",
"issues": [],
"recommendations": ["Feinschliff Stufe 3"],
},
llm_applied=True,
steps=steps,
)
assert summary["roadmap_qa"]["quality_score"] == 0.88
assert summary["assignment_qa"]["empty_slot_count"] == 4
assert summary["assignment_qa"]["quality_score"] <= 0.15
assert summary["quality_score"] <= 0.15
assert summary["overall_ok"] is False
def test_merge_path_quality_uses_minimum():
assert merge_path_quality_scores(
{"quality_score": 0.88},
{"quality_score": 0.12},
) == 0.12
def test_assignment_snapshot_reports_empty_slots():
snap = build_assignment_qa_snapshot(steps=_empty_steps(3), off_topic_steps=[], gaps=[])
assert snap["empty_slot_count"] == 3
assert snap["overall_ok"] is False
assert any("ohne Übung" in issue for issue in snap["issues"])
+127
View File
@@ -214,6 +214,7 @@ def test_rematch_unfilled_leaves_placeholder_step():
slot_indices={1}, slot_indices={1},
rematch_reasons={1: "stage_mismatch"}, rematch_reasons={1: "stage_mismatch"},
match_slot_fn=_no_match, match_slot_fn=_no_match,
rejected_by_major={1: {99}},
) )
assert len(ordered) == 2 assert len(ordered) == 2
@@ -235,3 +236,129 @@ def test_prune_filled_from_roadmap_unfilled():
unfilled_steps = [{"exercise_id": None, "roadmap_major_step_index": 5}] unfilled_steps = [{"exercise_id": None, "roadmap_major_step_index": 5}]
kept2 = _prune_filled_from_roadmap_unfilled(unfilled_steps, [(4, spec)]) kept2 = _prune_filled_from_roadmap_unfilled(unfilled_steps, [(4, spec)])
assert len(kept2) == 1 assert len(kept2) == 1
def test_rematch_keeps_same_exercise_when_not_rejected():
"""Regression: slot_assignment_history blockierte gültige Wiederzuordnung → leere Slots."""
specs = _stage_specs()
ctx = ProgressionRoadmapContext(
goal_query="Mae Geri",
max_steps=3,
stage_specs=specs,
)
steps = [
{"exercise_id": 10, "title": "OK", "roadmap_major_step_index": 0},
{"exercise_id": 42, "title": "Gut", "roadmap_major_step_index": 1},
]
def _same_match(cur, *, stage_spec, slot_priority_exercise_id=None, **kwargs):
assert slot_priority_exercise_id == 42
return (
{"exercise_id": 42, "title": "Gut", "roadmap_major_step_index": stage_spec.major_step_index},
None,
)
ordered, log, unfilled = rematch_roadmap_slots(
None,
tenant=None,
body=None,
goal_query="Mae Geri",
max_steps=3,
semantic_brief=None,
path_target_profile=None,
path_intent="",
roadmap_ctx=ctx,
steps=steps,
slot_indices={1},
rematch_reasons={1: "refine_stage_spec"},
match_slot_fn=_same_match,
rejected_by_major={},
)
assert ordered[1]["exercise_id"] == 42
assert log[0]["action"] == "replaced"
assert not unfilled
def test_rematch_restores_when_match_fails_and_not_rejected():
specs = _stage_specs()
ctx = ProgressionRoadmapContext(
goal_query="Mae Geri",
max_steps=3,
stage_specs=specs,
)
steps = [
{"exercise_id": 10, "title": "OK", "roadmap_major_step_index": 0},
{"exercise_id": 42, "title": "Gut", "roadmap_major_step_index": 1},
]
def _no_match(cur, *, stage_spec, **kwargs):
return None, stage_spec
ordered, log, unfilled = rematch_roadmap_slots(
None,
tenant=None,
body=None,
goal_query="Mae Geri",
max_steps=3,
semantic_brief=None,
path_target_profile=None,
path_intent="",
roadmap_ctx=ctx,
steps=steps,
slot_indices={1},
rematch_reasons={1: "refine_stage_spec"},
match_slot_fn=_no_match,
rejected_by_major={},
)
assert ordered[1]["exercise_id"] == 42
assert log[0]["action"] == "restored"
assert not unfilled
def test_filter_rematch_skips_preserved_slots():
from planning_path_rematch import filter_rematch_slot_indices
steps = [
{
"exercise_id": 10,
"roadmap_major_step_index": 0,
"roadmap_match_source": "slot_best_match",
"slot_status": "preserved",
},
{"exercise_id": 20, "roadmap_major_step_index": 1},
]
filtered = filter_rematch_slot_indices(
steps,
{0, 1},
stripped_off_topic=[],
off_topic_steps=[],
)
assert filtered == {1}
def test_apply_rematch_catalog_guard_skips_unfilled_only():
from planning_path_rematch import apply_rematch_catalog_guard
indices = {0, 1, 2}
reasons = {
0: "QS-Tier-1",
1: "Keine passende Übung für Roadmap-Stufe",
2: "Passt nicht zur Haupttechnik",
}
filtered = apply_rematch_catalog_guard(
indices,
reasons,
rematch_guard="Keine leeren Slots erzwingen.",
)
assert filtered == {0, 2}
def test_apply_rematch_catalog_guard_inactive_without_guard():
from planning_path_rematch import apply_rematch_catalog_guard
indices = {1}
reasons = {1: "Keine passende Übung für Roadmap-Stufe"}
assert apply_rematch_catalog_guard(indices, reasons, rematch_guard=None) == {1}
assert apply_rematch_catalog_guard(indices, reasons, rematch_guard="") == {1}
@@ -0,0 +1,152 @@
"""Schachstellen-Erkennung für unified Slot-Review."""
from planning_exercise_path_builder import (
_parse_slot_refs_from_text,
_problematic_slots_from_path_qa,
_slot_auto_select_ai,
_slot_auto_select_library,
_slot_suggestion_accepted,
)
from planning_progression_roadmap import StageSpecArtifact
def _spec(midx: int) -> StageSpecArtifact:
return StageSpecArtifact(
major_step_index=midx,
learning_goal=f"Lernziel Slot {midx + 1}",
load_profile=[],
exercise_type="",
success_criteria=[],
anti_patterns=[],
)
def test_problematic_slots_from_optimization_hints():
qa = {
"optimization_hints": [
{
"action": "rematch_slot",
"step_index": 1,
"issue": "stage_mismatch",
"reason": "Übung passt nicht zur Stufe",
}
],
"off_topic_steps": [],
}
steps = [
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
{"roadmap_major_step_index": 1, "exercise_id": 2, "title": "B"},
]
specs = [_spec(0), _spec(1)]
problems = _problematic_slots_from_path_qa(qa, steps, specs)
assert 1 in problems
assert any("Stufe" in r or "passt" in r for r in problems[1])
def test_slot_suggestion_accepted_for_problem_slot():
diff = {"baseline_exercise_id": 10, "proposed_exercise_id": 99}
assert _slot_suggestion_accepted(
baseline_qa={"optimization_hints": [{"action": "rematch_slot", "roadmap_major_step_index": 1}]},
projected_qa={"optimization_hints": []},
baseline_score=0.7,
projected_score=0.7,
diff=diff,
off_topic=False,
major_idx=1,
slot_problem=True,
)
def test_parse_slot_refs_schritt_is_one_based():
assert _parse_slot_refs_from_text("Schritt 8 (Ukemi Vorwärts) entfernen") == {7}
assert _parse_slot_refs_from_text("slot 3 und Stufe 5") == {2, 4}
def test_problematic_slots_from_refine_stage_spec_hint():
qa = {
"optimization_hints": [
{
"action": "refine_stage_spec",
"step_index": 7,
"issue": "stage_mismatch",
"reason": "Stufen-Fit zu schwach (0.00) für „Integration von Täuschung“",
}
],
"off_topic_steps": [],
}
steps = [
{"roadmap_major_step_index": i, "exercise_id": i + 1, "title": f"Übung {i + 1}"}
for i in range(8)
]
steps[7]["title"] = "Ukemi Vorwärts"
specs = [_spec(i) for i in range(8)]
problems = _problematic_slots_from_path_qa(qa, steps, specs)
assert 7 in problems
def test_problematic_slots_from_llm_schritt_text():
qa = {
"optimization_hints": [],
"off_topic_steps": [],
"issues": [
"Schritt 8 (Ukemi Vorwärts) hat keinen Bezug zur Kumite-Beinarbeit",
],
}
steps = [
{"roadmap_major_step_index": 7, "exercise_id": 99, "title": "Ukemi Vorwärts"},
]
specs = [_spec(7)]
problems = _problematic_slots_from_path_qa(qa, steps, specs)
assert 7 in problems
def test_slot_auto_select_requires_higher_score():
assert _slot_auto_select_library(
baseline_slot_score=0.5,
proposed_slot_score=0.51,
baseline_exercise_id=1,
proposed_exercise_id=2,
)
assert not _slot_auto_select_library(
baseline_slot_score=0.5,
proposed_slot_score=0.5,
baseline_exercise_id=1,
proposed_exercise_id=2,
)
def test_slot_auto_select_empty_slot_requires_good_fit():
assert not _slot_auto_select_library(
baseline_slot_score=None,
proposed_slot_score=0.35,
baseline_exercise_id=None,
proposed_exercise_id=2,
)
assert _slot_auto_select_library(
baseline_slot_score=None,
proposed_slot_score=0.55,
baseline_exercise_id=None,
proposed_exercise_id=2,
)
def test_slot_auto_select_ai_when_library_not_selected():
assert _slot_auto_select_ai(library_auto_select=False, has_ai=True)
assert not _slot_auto_select_ai(library_auto_select=True, has_ai=True)
assert not _slot_auto_select_ai(library_auto_select=False, has_ai=False)
def test_off_topic_slot_gap_spec_for_filled_slot():
from planning_exercise_path_builder import _build_off_topic_slot_gap_spec
spec = _build_off_topic_slot_gap_spec(
{
"roadmap_major_step_index": 7,
"exercise_id": 99,
"title": "Ukemi Vorwärts",
"roadmap_learning_goal": "Integration Täuschung",
}
)
assert spec is not None
assert spec["source"] == "off_topic"
assert spec["roadmap_major_step_index"] == 7
assert "Ukemi" in spec["rationale"]
@@ -57,3 +57,15 @@ def test_normalize_slot_contents():
) )
assert len(out["slot_contents"]) == 2 assert len(out["slot_contents"]) == 2
assert out["slot_contents"][1]["primary"]["kind"] == "proposal" assert out["slot_contents"][1]["primary"]["kind"] == "proposal"
def test_normalize_planning_roadmap_with_findings_stale():
out = normalize_planning_roadmap_payload(
{
"goal_query": "Mae Geri",
"last_findings": {"overall_ok": False},
"findings_stale": True,
}
)
assert out["findings_stale"] is True
assert out["last_findings"]["overall_ok"] is False
+63
View File
@@ -0,0 +1,63 @@
"""TOTP (RFC 6238) und einmalige Wiederherstellungscodes — nur Standardbibliothek."""
from __future__ import annotations
import base64
import hashlib
import hmac
import secrets
import struct
import time
from typing import Optional
from urllib.parse import quote
def generate_totp_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
def _decode_secret(secret: str) -> bytes:
raw = "".join(ch for ch in (secret or "").upper() if ch.isalnum())
pad = "=" * ((8 - len(raw) % 8) % 8)
return base64.b32decode(raw + pad, casefold=True)
def totp_code(secret: str, counter: int) -> str:
digest = hmac.new(_decode_secret(secret), struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
binary = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF
return f"{binary % 1_000_000:06d}"
def verify_totp(secret: Optional[str], code: str, *, window: int = 1, now: Optional[int] = None) -> bool:
if not secret:
return False
digits = "".join(ch for ch in (code or "") if ch.isdigit())
if len(digits) != 6:
return False
moment = int(time.time() if now is None else now)
counter = moment // 30
for delta in range(-window, window + 1):
if hmac.compare_digest(totp_code(secret, counter + delta), digits):
return True
return False
def otpauth_uri(*, secret: str, account_name: str, issuer: str = "Shinkan Jinkendo") -> str:
label = quote(f"{issuer}:{account_name}")
return (
f"otpauth://totp/{label}?secret={quote(secret)}"
f"&issuer={quote(issuer)}&algorithm=SHA1&digits=6&period=30"
)
def generate_recovery_codes(count: int = 8) -> list[str]:
codes = []
for _ in range(count):
raw = secrets.token_hex(4)
codes.append(f"{raw[:4]}-{raw[4:]}")
return codes
def hash_recovery_code(code: str) -> str:
normalized = "".join(ch for ch in (code or "").lower() if ch.isalnum())
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
+116 -9
View File
@@ -1,13 +1,13 @@
# Shinkan Jinkendo Version Information # Shinkan Jinkendo Version Information
APP_VERSION = "0.8.233" APP_VERSION = "0.8.246"
BUILD_DATE = "2026-05-22" BUILD_DATE = "2026-10-29"
DB_SCHEMA_VERSION = "20260607090" DB_SCHEMA_VERSION = "20261012096"
MODULE_VERSIONS = { MODULE_VERSIONS = {
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste) "legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
"auth": "1.2.3", # P-05b: reset-password min_length=8 via Pydantic PasswordResetConfirm "auth": "1.3.3", # Registrierung und Bestätigung antworten gleich; Reset-Mail nur mit gültiger E-Mail
"profiles": "1.8.1", # GET /profiles/me: account_state + club_roles "profiles": "1.8.2", # Superadmin: POST /profiles/{id}/totp-reset
"tenant_context": "1.1.0", # M3: account_state + email_verified im TenantContext "tenant_context": "1.1.0", # M3: account_state + email_verified im TenantContext
"capabilities": "1.2.0", # Registry-first: module-Spalte; Admin nur registrierte Rechte "capabilities": "1.2.0", # Registry-first: module-Spalte; Admin nur registrierte Rechte
"rights_registry": "1.0.0", # register_capability/feature + startup sync "rights_registry": "1.0.0", # register_capability/feature + startup sync
@@ -16,7 +16,7 @@ MODULE_VERSIONS = {
"club_memberships": "1.0.1", # Depends(get_tenant_context) "club_memberships": "1.0.1", # Depends(get_tenant_context)
"club_join_requests": "1.0.1", # Depends(get_tenant_context) "club_join_requests": "1.0.1", # Depends(get_tenant_context)
"club_creation_requests": "1.0.1", # superseded wenn freigegebener Verein gelöscht "club_creation_requests": "1.0.1", # superseded wenn freigegebener Verein gelöscht
"admin_users": "1.0.0", # GET /api/admin/users "admin_users": "1.0.1", # GET /api/admin/users inkl. totp_enabled
"club_features": "1.6.0", "club_features": "1.6.0",
"admin_rights": "1.1.0", # Matrix UX, Enforcement-Audit, clear club grants by capability "admin_rights": "1.1.0", # Matrix UX, Enforcement-Audit, clear club grants by capability
"capability_enforcement_audit": "1.0.0", "capability_enforcement_audit": "1.0.0",
@@ -29,7 +29,7 @@ MODULE_VERSIONS = {
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets "media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
"admin_ai_skill_retrieval": "1.0.0", # Superadmin CRUD /api/admin/ai-skill-retrieval-profiles (Migration 068) "admin_ai_skill_retrieval": "1.0.0", # Superadmin CRUD /api/admin/ai-skill-retrieval-profiles (Migration 068)
"exercise_enrichment_admin": "1.1.1", # Preview max 3/Request + parallel LLM (Gateway-504 vermeiden) "exercise_enrichment_admin": "1.1.1", # Preview max 3/Request + parallel LLM (Gateway-504 vermeiden)
"admin_ai_prompts": "1.0.3", # Migration 070: openrouter_model; PUT/Liste/Detail "admin_ai_prompts": "1.0.5", # H2: granulare Katalog-Slot-Platzhalter im Katalog
"ai_prompt_job": "0.2.1", # want_instructions; run_exercise_form_ai_suggestion "ai_prompt_job": "0.2.1", # want_instructions; run_exercise_form_ai_suggestion
"ai_prompt_context": "0.2.0", # preparation/trainer_notes; has_instruction_source_text "ai_prompt_context": "0.2.0", # preparation/trainer_notes; has_instruction_source_text
"ai_prompt_runtime": "0.2.2", # Slug planning_exercise_expectation_profile "ai_prompt_runtime": "0.2.2", # Slug planning_exercise_expectation_profile
@@ -37,7 +37,7 @@ MODULE_VERSIONS = {
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder "skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions "skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
"methods": "0.1.0", "methods": "0.1.0",
"exercises": "2.37.1", # KI-Endpoints: feature_usage nach ai_calls consume "exercises": "2.37.2", # Upload-MIME nur aus Magic Bytes; PDF als Anhang; Rich-Text-Allowlist beim Speichern
"planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil "planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint "training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
"training_programs": "0.1.0", "training_programs": "0.1.0",
@@ -49,10 +49,117 @@ MODULE_VERSIONS = {
"membership": "1.0.0", "membership": "1.0.0",
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012) "catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
"maturity_models": "1.4.0", # matrix_stack_bundle: vollständiger Katalog+Modelle+Bindings Export/Import "maturity_models": "1.4.0", # matrix_stack_bundle: vollständiger Katalog+Modelle+Bindings Export/Import
"content_reports": "1.5.1", # P-13: Fruehzeitige 403 fuer plain Admin in set_legal_hold_from_report (CI-Fix) "content_reports": "1.5.3", # Gutglauben vor dem Stundenlimit; Direktaufruf im Test mit Request
} }
CHANGELOG = [ CHANGELOG = [
{
"version": "0.8.246",
"date": "2026-10-29",
"changes": [
"Zweites Prod-Deployment auf llm-node: eigener Workflow, Konfiguration aus /etc/shinkan/prod.env, Medien über docker-compose.llm-node.yml ohne automatisch angelegte Host-Pfade. Die Medienbereinigung startet dort nur nach ausdrücklicher Freigabe. Der Deploy gilt erst als erfolgreich, wenn /api/health/ready Datenbank und Schema bestätigt.",
],
},
{
"version": "0.8.245",
"date": "2026-10-28",
"changes": [
"Papierkorb-Retention läuft täglich um 03:00 Uhr Europe/Berlin. Ein fehlgeschlagener Lauf bleibt im Container-Log sichtbar und löscht beim Containerstart nichts.",
],
},
{
"version": "0.8.244",
"date": "2026-10-13",
"changes": [
"Inhaltsmeldungen ohne Gutglaubenserklärung zählen nicht auf das Stundenlimit.",
],
},
{
"version": "0.8.243",
"date": "2026-10-13",
"changes": [
"Übungstexte werden beim Speichern und in der Anzeige auf eine feste HTML-Allowlist gekürzt.",
"Uploads: der Dateityp kommt aus dem Inhalt. PDF wird als Anhang ausgeliefert.",
"Registrierung und erneute Bestätigung verraten nicht, ob die E-Mail existiert. Passwort-Reset verlangt eine gültige Adresse.",
"Anonyme und angemeldete Inhaltsmeldungen sind auf 10 pro Stunde und IP begrenzt.",
],
},
{
"version": "0.8.242",
"date": "2026-10-13",
"changes": [
"Superadmin kann die Zwei-Faktor-Anmeldung eines anderen Kontos aufheben, wenn der Authenticator verloren ist.",
"Passwort-Reset ändert nur das Passwort. Zwei-Faktor bleibt aktiv, der Link meldet nicht an.",
],
},
{
"version": "0.8.241",
"date": "2026-10-13",
"changes": [
"Zwei-Faktor-Einrichtung zeigt einen QR-Code. Die Authenticator-App kann das Konto scannen, das Geheimnis bleibt als Ersatz sichtbar.",
],
},
{
"version": "0.8.240",
"date": "2026-10-13",
"changes": [
"Zwei-Faktor ist freiwillig. REQUIRE_ADMIN_TOTP erzwingt es nur noch, wenn die Variable ausdrücklich true ist.",
"Wiederherstellungscodes bleiben sichtbar, bis sie bestätigt sind. Neue Codes lassen sich in den Einstellungen erzeugen.",
],
},
{
"version": "0.8.239",
"date": "2026-10-12",
"changes": [
"Login: 8 Fehlversuche sperren das Konto 15 Minuten, gleiche bcrypt-Laufzeit bei unbekannter E-Mail, Limit 10/Minute an der echten Client-IP hinter dem Proxy.",
"Passwortwechsel verlangt das aktuelle Passwort und beendet alle Sitzungen. Reset-Tokens sind keine Login-Sitzung.",
"Zwei-Faktor (TOTP) für Plattform-Admins Pflicht, für andere Konten in den Einstellungen aktivierbar. Migration 096.",
"Medienabruf nutzt ein 10-Minuten-Token (?ssetoken), nicht mehr das Sitzungstoken. API- und Dev-DB-Ports nur an 127.0.0.1. AUTO_ADMIN_FIRST_USER standardmäßig aus.",
],
},
{
"version": "0.8.238",
"date": "2026-05-22",
"changes": [
"Planungs-KI H1.5: rematch_guard im Auto-Rematch (kein Rematch nur wegen leerer Roadmap-Stufe).",
"hints_on_exercise in Gap-Fill, Übungs-KI-Kontext und intent_context_json (Roadmap-Pipeline).",
"Migration 095: keine Migrations-Seeds in catalog_prompt_slots (Prod-sichere Katalogstruktur).",
],
},
{
"version": "0.8.237",
"date": "2026-05-22",
"changes": [
"Migration 094/095: Katalog-Prompt-Slots ohne Migrations-Seeds — Inhalte Admin oder Laufzeit-Fallback.",
"catalog_slot_fallbacks: Namens-Fallback bis Admin-Override — gleiche Qualität wie H1-Registry.",
],
},
{
"version": "0.8.236",
"date": "2026-05-22",
"changes": [
"Stammdaten-Katalog: CatalogPromptSlotsEditor für Fokus, Trainingsstil, Zielgruppe, Stilrichtung.",
"Migration 093: ai_prompts mit granularen Slot-Platzhaltern (focus_area_hints_on_path_qa etc.).",
],
},
{
"version": "0.8.235",
"date": "2026-05-22",
"changes": [
"Planungs-KI H2: catalog_prompt_slot_types + catalog_prompt_slots — Slot-Werte pro Katalog-Eintrag.",
"Granulare Platzhalter focus_area_hints_on_progression etc.; Resolver catalog_prompt_slots.py.",
"Admin-API GET/PUT /api/catalog-prompt-slots/{kind}/{id}; H1-Registry entfernt.",
],
},
{
"version": "0.8.234",
"date": "2026-05-22",
"changes": [
"Planungs-KI H1: Katalog-Snippets (planning_catalog_prompt_snippets) + zentrale Platzhalter (planning_prompt_variables).",
"Pfad-QS, Roadmap, Stufenspec: {{catalog_guidance_block}} aus Trainer-Katalog; Migration 091.",
"Admin: Planungs-Platzhalter-Katalog; Preview mit optional planning_catalog_context.",
],
},
{ {
"version": "0.8.226", "version": "0.8.226",
"date": "2026-05-22", "date": "2026-05-22",
+4 -2
View File
@@ -12,7 +12,7 @@ services:
volumes: volumes:
- dev-shinkan-db-data:/var/lib/postgresql/data - dev-shinkan-db-data:/var/lib/postgresql/data
ports: ports:
- "5435:5432" - "127.0.0.1:5435:5432"
restart: unless-stopped restart: unless-stopped
networks: networks:
- dev-shinkan-network - dev-shinkan-network
@@ -38,6 +38,8 @@ services:
APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}" APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}"
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}" ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}"
ENVIRONMENT: "${ENVIRONMENT:-development}" ENVIRONMENT: "${ENVIRONMENT:-development}"
AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-false}"
REQUIRE_ADMIN_TOTP: "${REQUIRE_ADMIN_TOTP:-false}"
# M5: Hard-Block Vereins-Kontingente (Default aus — in .env auf 1 setzen zum Testen) # M5: Hard-Block Vereins-Kontingente (Default aus — in .env auf 1 setzen zum Testen)
CLUB_FEATURE_ENFORCE: "${CLUB_FEATURE_ENFORCE:-1}" CLUB_FEATURE_ENFORCE: "${CLUB_FEATURE_ENFORCE:-1}"
MEDIAWIKI_API_URL: "${MEDIAWIKI_API_URL:-https://karatetrainer.net/api.php}" MEDIAWIKI_API_URL: "${MEDIAWIKI_API_URL:-https://karatetrainer.net/api.php}"
@@ -51,7 +53,7 @@ services:
volumes: volumes:
- ${SHINKAN_MEDIA_HOST:-/shinkan-media/dev}:${MEDIA_ROOT:-/app/media} - ${SHINKAN_MEDIA_HOST:-/shinkan-media/dev}:${MEDIA_ROOT:-/app/media}
ports: ports:
- "8098:8000" - "127.0.0.1:8098:8000"
depends_on: depends_on:
- postgres - postgres
restart: unless-stopped restart: unless-stopped
+32
View File
@@ -0,0 +1,32 @@
# Ergänzung zu docker-compose.yml für das Prod-Deployment auf llm-node.
# Nur zusammen mit der Basisdatei verwenden:
# docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.yml \
# --env-file /etc/shinkan/prod.env ...
# Pi und Dev nutzen diese Datei nicht.
services:
backend:
environment:
MEDIA_ROOT: /app/media
# Ersetzt den Medien-Mount der Basisdatei (gleiches Ziel /app/media).
# Kein create_host_path: fehlt das NFS-Verzeichnis, startet der Container nicht,
# statt auf die lokale Platte zu schreiben.
volumes:
- type: bind
source: /srv/shinkan/prod/media
target: /app/media
bind:
create_host_path: false
# Pi und llm-node teilen den Medienbestand, haben aber getrennte Datenbanken.
# Die Bereinigung startet hier nur mit Profil media-retention (siehe PROD_DEPLOYMENTS.md).
retention-cron:
profiles: ["media-retention"]
environment:
MEDIA_ROOT: /app/media
volumes:
- type: bind
source: /srv/shinkan/prod/media
target: /app/media
bind:
create_host_path: false
+5 -16
View File
@@ -38,7 +38,8 @@ services:
SMTP_SSL: ${SMTP_SSL:-} SMTP_SSL: ${SMTP_SSL:-}
SMTP_STARTTLS: ${SMTP_STARTTLS:-} SMTP_STARTTLS: ${SMTP_STARTTLS:-}
# Erste Self-Registration → Admin; oder ADMIN_BOOTSTRAP_EMAILS=mail@…,weitere@… # Erste Self-Registration → Admin; oder ADMIN_BOOTSTRAP_EMAILS=mail@…,weitere@…
AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-true}" AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-false}"
REQUIRE_ADMIN_TOTP: "${REQUIRE_ADMIN_TOTP:-false}"
ADMIN_BOOTSTRAP_EMAILS: "${ADMIN_BOOTSTRAP_EMAILS:-}" ADMIN_BOOTSTRAP_EMAILS: "${ADMIN_BOOTSTRAP_EMAILS:-}"
# Werte wie in .env (APP_URL, ALLOWED_ORIGINS, ENVIRONMENT) — keine zweite „Wahrheit“ in YAML # Werte wie in .env (APP_URL, ALLOWED_ORIGINS, ENVIRONMENT) — keine zweite „Wahrheit“ in YAML
APP_URL: "${APP_URL:-https://shinkan.jinkendo.de}" APP_URL: "${APP_URL:-https://shinkan.jinkendo.de}"
@@ -61,7 +62,7 @@ services:
volumes: volumes:
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media} - ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
ports: ports:
- "8003:8000" - "127.0.0.1:8003:8000"
depends_on: depends_on:
- postgres - postgres
restart: unless-stopped restart: unless-stopped
@@ -88,20 +89,7 @@ services:
context: ./backend context: ./backend
dockerfile: Dockerfile dockerfile: Dockerfile
container_name: shinkan-retention-cron container_name: shinkan-retention-cron
command: > command: ["python", "-u", "scripts/media_retention_scheduler.py"]
python -c "
import time, subprocess, sys, os, datetime
def next_3am():
now = datetime.datetime.now()
target = now.replace(hour=3, minute=0, second=0, microsecond=0)
if target <= now:
target += datetime.timedelta(days=1)
return (target - now).total_seconds()
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
while True:
time.sleep(next_3am())
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
"
working_dir: /app working_dir: /app
environment: environment:
DB_HOST: postgres DB_HOST: postgres
@@ -109,6 +97,7 @@ services:
DB_NAME: shinkan DB_NAME: shinkan
DB_USER: shinkan_user DB_USER: shinkan_user
DB_PASSWORD: ${DB_PASSWORD} DB_PASSWORD: ${DB_PASSWORD}
PYTHONUNBUFFERED: "1"
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}" MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
# Loeschkonzept (Audit P-03b): 30 Tage Soft-Trash, dann 30 Tage Hidden, dann Purge (gesamt 60 Tage). # Loeschkonzept (Audit P-03b): 30 Tage Soft-Trash, dann 30 Tage Hidden, dann Purge (gesamt 60 Tage).
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS: "${MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS:-30}" MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS: "${MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS:-30}"
+47 -16
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover # Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-06-07 **Stand:** 2026-05-22 (Katalog-Prompt-Slots H2/H1.5, **0.8.238**)
**App-Version / DB-Schema:** App **`0.8.208`** (Planungs-KI Phase D); DB **`20260606086`** — maßgeblich **`backend/version.py`**. **App-Version / DB-Schema:** App **`0.8.238`**; DB Migration **095** (keine Slot-Seeds; Prod-sichere Katalogstruktur).
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**. Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
@@ -37,6 +37,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` | | Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` | | Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
| **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` | | **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
| **Planungs-KI — Katalog-Prompt-Snippets (H1)** | **`docs/architecture/PLANNING_CATALOG_PROMPT_SNIPPETS.md`** |
| **Lieferliste inkl. Medien & Formular-UX** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §6, §16 | | **Lieferliste inkl. Medien & Formular-UX** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §6, §16 |
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** | | **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
@@ -89,7 +90,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **Varianten:** Speichern in der **Aktionsleiste** persistiert zuerst geänderte Varianten (`persistPendingVariantChanges`), dann Übungs-Stammdaten; „Variante anlegen“ als `type="button"` ohne verschachteltes Formular (`createVariantFromDraft`) - **Varianten:** Speichern in der **Aktionsleiste** persistiert zuerst geänderte Varianten (`persistPendingVariantChanges`), dann Übungs-Stammdaten; „Variante anlegen“ als `type="button"` ohne verschachteltes Formular (`createVariantFromDraft`)
- **Governance (Übungen):** Owner = `created_by`; Bearbeiten = Ersteller, Plattform-Admin oder `can_plan_in_club` bei `visibility=club`; Löschen `club` = nur `club_admin`; Details **`FEATURES_DELIVERED_2026-Q2.md`** §16, **`EXERCISES_API_SPEC.md`** Permissions - **Governance (Übungen):** Owner = `created_by`; Bearbeiten = Ersteller, Plattform-Admin oder `can_plan_in_club` bei `visibility=club`; Löschen `club` = nur `club_admin`; Details **`FEATURES_DELIVERED_2026-Q2.md`** §16, **`EXERCISES_API_SPEC.md`** Permissions
### 2.8 KI Assistenz Übungen & Planungs-KI (Stand **0.8.217**) ### 2.8 KI Assistenz Übungen & Planungs-KI (Stand **0.8.233**)
**Zentrale Ist-Doku (Progressionsgraph-KI):** **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`** — bei Drift zuerst dort pflegen. **Zentrale Ist-Doku (Progressionsgraph-KI):** **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`** — bei Drift zuerst dort pflegen.
@@ -108,20 +109,47 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| **F7** | `planning_skill_expectations` — Retrieval + UI + Gap | ✅ **0.8.215–216** | | **F7** | `planning_skill_expectations` — Retrieval + UI + Gap | ✅ **0.8.215–216** |
| **F8** | Editierbare `stage_specs` (Belastung, Erfolgskriterien) | ✅ **0.8.216** | | **F8** | Editierbare `stage_specs` (Belastung, Erfolgskriterien) | ✅ **0.8.216** |
| **F9** | `planning_roadmap` JSONB am Graph (Migration **088**) | ✅ **0.8.217** | | **F9** | `planning_roadmap` JSONB am Graph (Migration **088**) | ✅ **0.8.217** |
| **F10** | Stufen-Lernziel-Gate, kein blindes Rank-Fallback | ✅ **0.8.218** |
| **F11** | Auto-Rematch + Stufen-Spec-Refine + mehrstufige QS | ✅ **0.8.225–0.8.230** |
| **F12** | Post-Match-Gate, LLM-QA nach Rematch, Gap-Timing, `roadmap_unfilled`-Sync | ✅ **0.8.231–0.8.232** |
| **F13** | **`planning_catalog_context`** (Fokus/Stil/TT/ZG) im Match + Graph-Artefakt | ✅ **0.8.233** |
| **F14** | **`ProgressionGraphEditor`** — Slot-UI + Planungskontext-Dropdowns | ✅ **0.8.233** |
| **F15** | Unified Slot-Review (Match-Dialog), getrennte Pfad-QS, `findings_stale` | ✅ lokal (nach 0.8.233) |
| **H1–H2.1** | Katalog-Prompt-Slots (DB, Resolver, Admin-UI, granulare Prompts) | ✅ **0.8.234–238** — Spec **`docs/architecture/PLANNING_CATALOG_PROMPT_SNIPPETS.md`** |
| **H1.5** | `rematch_guard`, `hints_on_exercise` in Rematch/Gap-Fill/Intent | ✅ **0.8.238** |
**Architektur (verbindlich):** Progressionsgraph = **Roadmap-first**, **keine Gruppenanalyse**. Bestehender Graph = **leichter Nachfolger-Bias** ab Schritt 2, **kein** automatisches Erweitern ab letztem Knoten (siehe Ist-Doku §5). Trainingsplanung = **eigene Pipeline** (Phase G), wiederverwendet `planning_skill_expectations`. **Architektur (verbindlich):** Drei Schichten — (1) **Katalog-Dimensionen** (DB, jetzt im Match verdrahtet; **H1:** zusätzlich Prompt-Snippets), (2) **Technik-Disambiguierung** (Code, nur bei `topic_type=technique`), (3) **Didaktik** (Roadmap + LLM-QS, nicht im Vokabular). Progressionsgraph = **Roadmap-first**, **keine Gruppenanalyse**. Bestehender Graph = **leichter Nachfolger-Bias** ab Schritt 2. Trainingsplanung = **eigene Pipeline** (Phase G) — Wiederverwendung der Bausteine, siehe Ist-Doku §16.
**Backend-Kern:** `planning_progression_roadmap.py`, `planning_exercise_path_builder.py`, `planning_skill_expectations.py`, `planning_exercise_form_context.py`, `planning_exercise_path_ai_fill.py`, `progression_graph_planning_artifact.py` **Validierung (Mae Geri, Härtetest):** Roadmap-QS nach Trainer-Roadmap oft **~85–88 %** — gilt **Stufenlogik**, nicht leere Slots. **Gesamt-Pfad-QS** = Minimum aus **`roadmap_qa`** + **`assignment_qa`** (leere Slots → Besetzung ~8–15 %). Workbench universell; Mae Geri Referenzfall.
**API:** `POST /api/planning/progression-path-suggest` · `PUT /api/exercise-progression-graphs/:id` (`planning_roadmap`) · `POST …/edges/sequence` #### F15 — Match-Dialog, Bewertung, Pfad-QS (Stand 2026-05-22)
**Frontend:** `ExerciseProgressionPathBuilder`, `ExerciseGapFillPrepModal`, `planningContextForExerciseAi.js` | Thema | Ist |
|--------|-----|
| **„Übungen matchen“** | Schritt 1: `evaluate_only` (wie „Graph bewerten“) · Schritt 2: `unified_slot_review: true` → Dialog **pro Slot** (Bewertung, Bibliotheks-Alternative, optional KI) |
| **Vorauswahl Dialog** | Bibliothek nur bei Stufen-Fit **≥ 50 %** und besser als aktuell; bei leerem Slot + schwacher Bibliothek → **KI-Vorschlag** vorausgewählt |
| **Übernahme** | Nur gewählte Slots speichern — **keine** automatische teure Nach-Bewertung |
| **Bewertung veraltet** | Nach Graph-Änderungen Hinweis im Findings-Panel; persistiert als **`findings_stale`** im `planning_roadmap`-Artefakt (mit Speichern) |
| **Getrennte QS** | `path_qa.roadmap_qa` (Stufen/Roadmap/LLM) + `path_qa.assignment_qa` (Slot-Befüllung); **`quality_score`** = Minimum beider |
| **UX-Fix** | Slot-Karten: stabiler React-Key (`slot-{index}`) — Lernziel editierbar ohne Fokusverlust |
**Code:** `ProgressionOptimizeCompareModal.jsx`, `planning_exercise_path_builder.py` (`_build_unified_slot_review_entry`, `_slot_auto_select_*`), `planning_exercise_path_qa.py` (`build_*_qa_snapshot`), `progression_graph_planning_artifact.py` (`findings_stale`), `progressionGraphDraft.js`
**Backend-Kern:** `planning_progression_roadmap.py`, `planning_exercise_path_builder.py`, `planning_catalog_context.py`, `planning_path_rematch.py`, `planning_path_refine_stage.py`, `planning_path_qa_pipeline.py`, `planning_skill_expectations.py`, `planning_exercise_form_context.py`, `planning_exercise_path_ai_fill.py`, `progression_graph_planning_artifact.py`
**API:** `POST /api/planning/progression-path-suggest` · `PUT /api/exercise-progression-graphs/:id` (`planning_roadmap`, `planning_catalog_context`) · `POST …/edges/sequence`
**Frontend:** **`ProgressionGraphEditor`** (primäre Workbench), `ExerciseProgressionPathBuilder`, `ExerciseGapFillPrepModal`, `progressionGraphDraft.js`, `planningContextForExerciseAi.js`
**Offen (priorisiert):** **Offen (priorisiert):**
1. UI-Wizard (Scroll-Monolith → 4 Schritte) — **separater UI-Chat** 1. Dev-Regression: Gewaltschutz / Breitensport / Kinder (nicht nur Mae Geri)
2. Graph-Erweiterungsmodus (Start ab Knoten) 2. **PathBuilder-Parität** — gleiche Katalog-Dropdowns wie GraphEditor
3. Trainingsplanung Phase G (Gruppenkontext) 3. UI-Wizard (4 Schritte: Ziel → Roadmap → Match → Lücken)
4. Kontext-Anzeige auf allen Pfad-Schritten 4. Graph-Erweiterungsmodus (Start ab Knoten)
5. Phase D′ — Auto KI-Gap-Fill bei persistent leeren Slots
6. **Trainingsplanung Phase G** — Gruppenkontext-Pack, Scopes `training_section` / `framework_slot` (Ist-Doku §16)
7. Technik-Katalog konfigurierbar (Backlog)
8. **H1–H2.1** — Katalog-Prompt-Slots ✅ · **Prompt-Editor-Überarbeitung** → eigene Session
#### Übungs-KI Formular / Schnellanlage (Stand **0.8.171**) #### Übungs-KI Formular / Schnellanlage (Stand **0.8.171**)
@@ -256,11 +284,14 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
### Planungs-KI (priorisiert) ### Planungs-KI (priorisiert)
1. **Phase F2:** LLM für Roadmap (Prompts **078**) + `roadmap_first` Retrieval aus `stage_specs`. 1. **H1 Katalog-Prompt-Snippets:** modulare LLM-Anweisungen — **`docs/architecture/PLANNING_CATALOG_PROMPT_SNIPPETS.md`** (Priorität: Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung).
2. **Phase F4:** Roadmap-Review UI (Major Steps editierbar vor Übungs-Match). 2. **Dev-Regression:** Katalog-Match für Gewaltschutz, Breitensport, Kinder — nicht nur Mae-Geri-Härtetest.
3. **Enrichment:** Skills/Tags pro Technik (Feinauflösung statt nur Geri Waza). 3. **PathBuilder-Parität:** `planning_catalog_context`-Dropdowns auch in `ExerciseProgressionPathBuilder`.
4. **D — Neu-Anlage:** `planning_context_json` an `POST /api/exercises/ai/suggest`. 4. **UI-Wizard:** 4 Schritte (Ziel & Katalog → Roadmap → Match → Lücken); Backend-Pipeline unverändert.
5. **Trainingsplanung G:** Kontext-Pack Gruppe/Historie — eigene Pipeline (`AI_PLANNING_KI_MULTISTAGE_FORECAST`); Mitai Workflow-Engine erst danach. 5. **Phase D′:** automatisches KI-Gap-Fill bei persistent `roadmap_unfilled`.
6. **Trainingsplanung G0–G4:** Katalog in Einheits-Editor, Scopes `training_section`/`framework_slot`, Abschnitts-QS, Gruppenkontext-Pack — Details **`PLANNING_PROGRESSION_GRAPH_KI.md`** §16, **`PLANNING_KI_ROADMAP.md`**.
7. **Technik-Katalog externalisieren** (Backlog): `concept_groups` konfigurierbar statt Code-Tuples.
8. **Mitai Workflow-Engine** erst nach stabiler Phase G.
### Allgemein ### Allgemein
@@ -0,0 +1,219 @@
# Planungs-KI — Katalog-Prompt-Slots (Snippets)
**Stand:** 2026-05-22
**Status:** **H2.1** umgesetzt (0.8.236) · **H1.5** Rematch-Guard + Gap-Fill-Hints (0.8.238) · **Prompt-Editor-Überarbeitung** bewusst ausgelagert
**Bezüge:** `PLANNING_PROGRESSION_GRAPH_KI.md` §4.4 · `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.4 · `planning_catalog_context.py` · `catalog_prompt_slots.py`
---
## 1. Problem
Seit **F13 (0.8.233)** fließen Primärfokus, Trainingsstil, Zielgruppe und Stilrichtung als `planning_catalog_context` in **Retrieval und Scoring**.
Die **LLM-Prompts** brauchen zusätzlich **fachliche Textbausteine** pro gewähltem Katalog-Eintrag — editierbar, ohne Code-Deploy, unabhängig von fest codierten Katalog-Namen.
**Ziel:** Prompts in `ai_prompts` referenzieren **Slot-Typen** (Vokabular). Inhalte hängen an **Katalog-Zeilen** (Stammdaten). Der Resolver füllt Platzhalter zur Laufzeit.
---
## 2. Zwei Ebenen (Kern des Modells)
| Ebene | Was | Wer pflegt | Beispiel |
|-------|-----|------------|----------|
| **Slot-Typ** | Art des Textes (festes, erweiterbares Vokabular) | Produkt / Architektur | `hints_on_progression`, `hints_on_path_qa` |
| **Slot-Wert** | Konkreter Text pro Katalog-Eintrag | Admin / Redakteur | Gewaltschutz → `hints_on_path_qa`: „Lücken = fehlende Deeskalation …“ |
**Nicht:** feste Attribute pro Eintrag im Code (`planning_lens`, `qa_criteria` …).
**Sondern:** beliebig viele Katalog-Einträge × definierte Slot-Typen.
---
## 3. Dimensionen & Priorität
| Rang | Dimension | `catalog_kind` | DB-Tabelle |
|------|-----------|----------------|------------|
| **1** | Primärfokus | `focus_area` | `focus_areas` |
| **2** | Trainingsstil | `training_type` | `training_types` |
| **3** | Zielgruppe | `target_group` | `target_groups` |
| **4** | Stilrichtung | `style_direction` | `style_directions` |
**Kaskade:** Bei widersprüchlichen Hinweisen gilt Fokus → Trainingsstil → Zielgruppe → Stilrichtung.
Pro Dimension im Request: **ein aktiver Eintrag** (`is_primary`, sonst höchstes `weight`).
---
## 4. Slot-Typ-Register (Vokabular)
Definiert in **`catalog_prompt_slot_types`** (DB) + Spiegel in `catalog_prompt_slots.py`.
| `slot_key` | Anzeige (DE) | LLM-Prompt | Code-only |
|------------|--------------|------------|-----------|
| `description` | Allgemeine Beschreibung | Roadmap, Goal-Analyse, Start/Ziel | — |
| `hints_on_progression` | Hinweise Progressionsgraph / Stufen | Roadmap, Stage-Spec | — |
| `hints_on_path_qa` | Bewertungsmaßstäbe Pfad-QS | Path-QA | — |
| `hints_on_exercise` | Hinweise Übungsanlage / Gap-Fill | Exercise-AI, Suggest (später) | — |
| `anti_patterns` | Explizit vermeiden (Fehlbewertung) | Path-QA, Stage-Spec | — |
| `rematch_guard` | Kein Auto-Rematch erzwingen | — | Rematch-Loop (H1.5) |
**Erweiterung:** neuer Slot-Typ = eine Zeile in `catalog_prompt_slot_types` + Resolver/Admin-Katalog — **kein** neues Python-Feld pro Eintrag.
**Fallback `description`:** Wenn kein Slot-Wert gesetzt → `focus_areas.description` (bzw. `description`-Spalte der jeweiligen Katalog-Tabelle).
---
## 5. Platzhalter in `ai_prompts`
Mustache-Keys: **`{catalog_kind}_{slot_key}`** (nur `[a-z0-9_]`).
| Platzhalter | Bedeutung |
|-------------|-----------|
| `{{focus_area_description}}` | Aktiver Primärfokus — Beschreibung |
| `{{focus_area_hints_on_progression}}` | … — Progressions-Hinweise |
| `{{focus_area_hints_on_path_qa}}` | … — QS-Hinweise |
| `{{focus_area_hints_on_exercise}}` | … — Übungsanlage |
| `{{focus_area_anti_patterns}}` | … — Anti-Patterns |
| `{{training_type_description}}` | Aktiver Trainingsstil — … |
| `{{training_type_hints_on_progression}}` | … |
| `{{target_group_hints_on_path_qa}}` | Aktive Zielgruppe — … |
| `{{style_direction_hints_on_progression}}` | Aktive Stilrichtung — … |
| *(analog für alle Slot-Typen × Dimension)* | |
| `{{catalog_guidance_block}}` | **Aggregat** (Abwärtskompatibel): kaskadierter Markdown-Block aus aktiven Slots |
| `{{catalog_context_json}}` | Audit: IDs, Namen, gesetzte Slot-Keys |
| `{{has_catalog_guidance}}` | `"true"` oder leer |
**Hinweis:** `prompt_resolver` unterstützt **keine** `{{#if}}`-Blöcke — leere Slots = leerer String.
### 5.1 Prompt-Profile (welche Slots im Aggregat)
| Prompt-Slug | Aggregat enthält primär |
|-------------|-------------------------|
| `planning_exercise_path_qa` | `*_hints_on_path_qa`, `*_anti_patterns`, `*_description` |
| `planning_progression_roadmap` | `*_description`, `*_hints_on_progression`, `*_anti_patterns` |
| `planning_progression_stage_spec` | `*_hints_on_progression`, `*_anti_patterns` |
| `planning_progression_goal_analysis` | `*_description` |
Feinsteuerung: im Admin-Template **granulare** Platzhalter nutzen; Aggregat optional.
---
## 6. Speicherung (DB)
### 6.1 `catalog_prompt_slot_types`
Metadaten je Slot-Typ (`slot_key`, `display_name`, `description`, `applicable_kinds[]`, `sort_order`, `for_llm`, `for_code`).
### 6.2 `catalog_prompt_slots`
```text
catalog_kind — focus_area | training_type | target_group | style_direction
catalog_id — FK auf jeweilige Stammtabelle (logisch, kein polymorpher FK)
slot_key — FK → catalog_prompt_slot_types
content — TEXT (Markdown/Plain für LLM)
UNIQUE (catalog_kind, catalog_id, slot_key)
```
Neuer Katalog-Eintrag im Admin → **keine** Code-Änderung; Slots optional befüllen.
**Keine Migrations-Seeds:** Primärfokus und andere Stammdaten sind pro Umgebung unterschiedlich. Leere `catalog_prompt_slots` sind normal; zur Laufzeit greifen Namens-Fallbacks (`catalog_slot_fallbacks.py`) und die `description`-Spalte der Stammdaten.
---
## 7. Laufzeit-Architektur
```text
planning_catalog_context (Request / Graph-Artefakt)
↓
catalog_prompt_slots.resolve_catalog_prompt_variables(cur, catalog, slug?)
↓
planning_prompt_variables.merge_planning_prompt_variables(...)
↓
load_and_render_ai_prompt (ai_prompts Template)
```
**Module:**
| Modul | Rolle |
|-------|--------|
| `catalog_prompt_slots.py` | Slot-Typen, DB-Lese/Schreib, Resolver, Aggregat-Block |
| `planning_prompt_variables.py` | Zentrale Provider-Liste (erweiterbar) |
| `planning_catalog_prompt_snippets.py` | Deprecated Re-Exports (Tests/Kompatibilität) |
---
## 8. Admin-API
| Methode | Pfad | Beschreibung |
|---------|------|--------------|
| GET | `/api/catalog-prompt-slot-types` | Slot-Typ-Register |
| GET | `/api/catalog-prompt-slots/{kind}/{catalog_id}` | Alle Slots eines Eintrags |
| PUT | `/api/catalog-prompt-slots/{kind}/{catalog_id}` | Slots upserten (Admin) |
`kind`: `focus_area` · `training_type` · `target_group` · `style_direction`
**Später:** UI-Tabs am Katalog-Editor; Versionierung/Audit wie `ai_prompts`.
---
## 9. Rollout-Phasen
### H1 — Bootstrap (0.8.234) ✓
Hardcodierte `SNIPPET_REGISTRY` — Proof of Concept für `catalog_guidance_block`.
### H2 — Slot-Modell (0.8.235) ✓
- [x] Tabellen `catalog_prompt_slot_types`, `catalog_prompt_slots`
- [x] Seed aus H1-Texten (Name-Match auf Stammdaten) — **entfernt (095)**: keine Migrations-Seeds; Inhalte Admin oder `catalog_slot_fallbacks.py`
- [x] Resolver mit granularen Platzhaltern + Aggregat
- [x] Admin-API GET/PUT
- [x] `SNIPPET_REGISTRY` aus Laufzeit-Pfad entfernt
### H2.1 — Admin-UI
- [x] Slot-Editor an Fokusbereich / Trainingsstil / Zielgruppe / Stilrichtung (`CatalogPromptSlotsEditor`, Stammdaten-Katalog)
- [x] Prompt-Templates mit granularen Platzhaltern (Migration 093)
- [ ] **Prompt-Editor komplett überarbeiten** (Platzhalter-Hilfe, UX) — **eigene Session**
### H1.5 ✓ (0.8.238)
- [x] `rematch_guard` im Rematch-Loop (`apply_rematch_catalog_guard`)
- [x] Gap-Fill + Intent: `hints_on_exercise` via `catalog_exercise_hints_block` / `intent_context_json`
### H3 — Trainingsplanung (Phase G)
- [ ] Gleicher Resolver, andere Orchestratoren
---
## 10. Tests & Akzeptanz
| Test | Erwartung |
|------|-----------|
| Slot aus DB | Gewaltschutz + `hints_on_path_qa` → Platzhalter enthält Deeskalation |
| Ohne Katalog | Alle `{{focus_area_*}}` leer; `has_catalog_guidance` leer |
| Neuer Eintrag | Leere Slots, kein Crash; `description`-Fallback aus Stammdaten |
| Priorität | Aggregat: Primärfokus vor Trainingsstil |
---
## 11. Abgrenzung
| Thema | Hinweis |
|-------|---------|
| Retrieval-Gewichte | `merge_catalog_context_into_target` — unverändert |
| Technik-Gates | `planning_exercise_semantics` — unverändert |
| Prompt-Text | `ai_prompts` — editierbar, referenziert Slot-Platzhalter |
---
## 12. Changelog
| Datum | Änderung |
|-------|----------|
| 2026-05-22 | **H1.5** (0.8.238): rematch_guard; hints_on_exercise in Gap-Fill/Intent; Migration 095 ohne Seeds |
| 2026-05-22 | **H2.1** (0.8.236): Admin-UI `CatalogPromptSlotsEditor`; Migration 093 granulare Prompt-Templates |
| 2026-05-22 | **H2** (0.8.235): Slot-Typ-Register + `catalog_prompt_slots` DB, granulare Platzhalter, Admin-API |
| 2026-05-22 | Konzept §4–§8: zwei Ebenen Slot-Typ vs. Slot-Wert; Platzhalter `{kind}_{slot_key}` |
| 2026-05-22 | H1 (0.8.234): Bootstrap-Registry — durch H2 ersetzt |
| 2026-05-22 | Erstfassung |
+138 -59
View File
@@ -1,7 +1,7 @@
# Planungs-KI — Produkt-Roadmap # Planungs-KI — Produkt-Roadmap
**Stand:** 2026-05-22 **Stand:** 2026-05-22
**App-Version:** **0.8.217** — maßgeblich `backend/version.py` **App-Version:** **0.8.233** — maßgeblich `backend/version.py`
Diese Roadmap ergänzt die **Architektur-Refaktor-Roadmap** (`UMSETZUNGSPLAN_ROADMAP.md`) und gilt **nur für KI-gestützte Trainingsplanungsunterstützung**. Diese Roadmap ergänzt die **Architektur-Refaktor-Roadmap** (`UMSETZUNGSPLAN_ROADMAP.md`) und gilt **nur für KI-gestützte Trainingsplanungsunterstützung**.
@@ -13,9 +13,10 @@ Diese Roadmap ergänzt die **Architektur-Refaktor-Roadmap** (`UMSETZUNGSPLAN_ROA
## Strategische Entscheidung (verbindlich) ## Strategische Entscheidung (verbindlich)
1. **Progressionsgraph:** Planung **vom Ziel rückwärts** (Roadmap-first), nicht Bibliothek-first. 1. **Progressionsgraph:** Planung **vom Ziel rückwärts** (Roadmap-first), nicht Bibliothek-first.
2. **Keine Gruppenanalyse** im Graphen — Kontext = Zieltext, Thema, Schrittanzahl, optional Graph-Kanten. 2. **Keine Gruppenanalyse** im Graphen — Kontext = Zieltext, Katalog-Dimensionen, Start/Ziel, Roadmap, optional Graph-Kanten.
3. **Trainingsplanung** (Einheit, Rahmen, Abschnitt): eigene Pipeline später, **mit** Gruppenkontext — siehe `AI_PLANNING_KI_MULTISTAGE_FORECAST.md` S0–S4. 3. **Drei Schichten statt monolithischem Vokabular:** Katalog (DB) · Technik-Disambiguierung (Code, nur bei Technik-Themen) · Didaktik (Roadmap + LLM-QS).
4. **Orchestrierung:** Workflow-**lite** jetzt (`planning_progression_roadmap.py`); Mitai Workflow-Engine **später**, wenn 2–3 Pipelines stabil sind. 4. **Trainingsplanung** (Einheit, Rahmen, Abschnitt): eigene Pipeline (Phase G), **mit** Gruppenkontext — siehe `AI_PLANNING_KI_MULTISTAGE_FORECAST.md` S0–S4 und Ist-Doku §16.
5. **Orchestrierung:** Workflow-**lite** jetzt (`planning_progression_roadmap.py`, `planning_exercise_path_builder.py`); Mitai Workflow-Engine **später**, wenn Phase G stabil ist.
--- ---
@@ -27,84 +28,162 @@ Diese Roadmap ergänzt die **Architektur-Refaktor-Roadmap** (`UMSETZUNGSPLAN_ROA
| A–C2 | Übungssuche | Voll-Library, Graph, Varianten | ✅ | | A–C2 | Übungssuche | Voll-Library, Graph, Varianten | ✅ |
| C3 | Progressionsgraph | Pfad-Builder (retrieval-first) | ✅ | | C3 | Progressionsgraph | Pfad-Builder (retrieval-first) | ✅ |
| E–E3 | Progressionsgraph | Semantik, QA, Lücken-Angebote | ✅ | | E–E3 | Progressionsgraph | Semantik, QA, Lücken-Angebote | ✅ |
| **F0–F4** | Progressionsgraph | Roadmap-Pipeline, LLM, roadmap-first, UI Review | ✅ **0.8.204–209** | | **F0–F4** | Progressionsgraph | Roadmap-Pipeline, LLM, roadmap_first, UI Review | ✅ **0.8.204–209** |
| **F5–F9** | Progressionsgraph | Start/Ziel, Gap-Prep, Skill-Expectations, Persistenz | ✅ **0.8.210–217** | | **F5–F9** | Progressionsgraph | Start/Ziel, Gap-Prep, Skill-Expectations, Persistenz | ✅ **0.8.210–217** |
| **F10** | Progressionsgraph | Stufen-Lernziel-Gate, kein blindes Rank-Fallback | ✅ **0.8.218** |
| **F11–F12** | Progressionsgraph | Auto-Rematch, Spec-Refine, QS-Pipeline-Timing | ✅ **0.8.225–0.8.232** |
| **F13–F14** | Progressionsgraph | Katalog-Kontext + GraphEditor-Workbench | ✅ **0.8.233** |
| D | Übungs-Neuanlage | `planning_context` an `suggestExerciseAi` | ✅ **0.8.208** | | D | Übungs-Neuanlage | `planning_context` an `suggestExerciseAi` | ✅ **0.8.208** |
| **UX** | Progressionsgraph | Wizard/Stepper statt Scroll-UI | 🔲 | | **UX** | Progressionsgraph | Wizard/Stepper; PathBuilder-Parität Katalog | 🔲 |
| G | Trainingsplanung | Kontext-Pack Gruppe/Historie, S0–S4 | 🔲 | | **D′** | Progressionsgraph | Auto KI-Gap-Fill bei persistent leeren Slots | 🔲 Backlog |
| H | Plattform | Mitai-Workflow-Engine (optional) | 🔲 Backlog | | **G** | Trainingsplanung | Kontext-Pack Gruppe/Historie, G0–G4 | 🔲 |
| **H** | Plattform | Technik-Katalog konfigurierbar; Mitai-Workflow | 🔲 Backlog |
--- ---
## Phase F — Progressions-Roadmap (aktiver Fokus) ## Phase F — Progressions-Roadmap (abgeschlossen bis F14)
### F0 — Foundation (0.8.204) Details und Module: **`PLANNING_PROGRESSION_GRAPH_KI.md`**.
- [x] Spec `PLANNING_PROGRESSION_ROADMAP_SPEC.md` ### F0–F9 — (Kurz, siehe Ist-Doku)
- [x] Modul `planning_progression_roadmap.py` (Pydantic, Pipeline-Skeleton)
- [x] Migration **078** Prompt-Slugs (Zielanalyse, Roadmap)
- [x] API: `include_roadmap_preview` auf `progression-path-suggest`
- [x] Doku: HANDOVER, PLANNING_EXERCISE_SUGGEST_CONTEXT, MULTISTAGE_FORECAST
### F1 — Deterministische Roadmap - [x] F0 Foundation (0.8.204) — Spec, Pipeline-Skeleton, Prompts 078
- [x] F1 Deterministische Roadmap — Phase A/B/C heuristisch
- [x] F2 LLM Roadmap (0.8.205) — Prompts 078/079
- [x] F3 roadmap-first (0.8.206) — Match pro `stage_spec`, `roadmap_unfilled`
- [x] F4 UI Review (0.8.207) — `roadmap_override`, Major Steps editierbar
- [x] F5 Start/Ziel (0.8.210–214) — Prompt **087**, Zwei-Schritt-UI
- [x] F6 Gap-KI-Kontext (0.8.212–214) — `ExerciseGapFillPrepModal`
- [x] F7 Fähigkeiten-Scoring (0.8.215–216) — `planning_skill_expectations`
- [x] F8 Stufen-Details UI (0.8.216) — editierbare `stage_specs`
- [x] F9 Persistenz (0.8.217) — Migration **088** `planning_roadmap` JSONB
- [x] Phase A aus Semantic Brief ### F10 — Stufen-Qualität (0.8.218)
- [x] Phase B: `micro_objectives` aus `development_arc` + Konsolidierung auf N
- [x] Phase C: heuristische `stage_specs`
- [ ] pytest für Konsolidierung
### F2 — LLM Roadmap (0.8.205) - [x] Stufen-Lernziel-Gate — kein Rank-Fallback ohne Pass
- [x] Anti-Pattern-Sanitizer, `stage_mismatch` → leerer Slot + Gap
- [x] Prompts **078/079** in `ai_prompts` — Code nur Slugs (`PROMPT_SLUG_*`) ### F11 — Auto-Optimierung (0.8.225–0.8.230)
- [x] `include_llm_roadmap` + `load_and_render_ai_prompt` + JSON-Validierung
- [x] Deterministischer Fallback wenn Prompt/OpenRouter fehlt
- [ ] Response/UI: genutzte `prompt_slugs` sichtbar machen (Admin-Hinweis)
### F3 — roadmap-first (0.8.206) - [x] `planning_path_rematch.py` — Rematch-Schleife für `rematch_slot` / `roadmap_unfilled`
- [x] `planning_path_refine_stage.py` — Spec-Schärfung aus QS
- [x] `planning_path_qa_pipeline.py` — mehrstufige QS
- [x] Retrieval pro `major_step` + `stage_spec` statt iterativem Pfad-Bau ### F12 — Pipeline-Timing & Sync (0.8.231–0.8.232)
- [x] Gap-Angebote für unbesetzte Roadmap-Stufen (`roadmap_unfilled`)
- [x] QA/Lücken an Roadmap gekoppelt (`roadmap_first_lite`: keine Brücken/Reorder zwischen Major Steps)
### F4 — UI (0.8.207) - [x] Post-Match-Gate vor Rematch-Akzeptanz
- [x] LLM Pfad-QS **nach** Rematch
- [x] Gap-Offers vor `path_qa`-Summary
- [x] Frontend: `applyMatchStepsToSlots` sync per `majorStepIndex`
- [x] Roadmap-Review im `ExerciseProgressionPathBuilder` ### F13 — Katalog-Kontext (0.8.233)
- [x] Major Steps editierbar (Phase, Lernziel, Reihenfolge) vor Übungs-Match
- [x] API `roadmap_only` + `roadmap_override`
### F5 — Start/Ziel (0.8.210–214) - [x] `planning_catalog_context.py` — Fokus, Stil, Trainingsstil, Zielgruppe
- [x] Merge in `PlanningTargetProfile` + Text-Signale
- [x] Persistenz im Graph-Artefakt
- [x] Technik-Gates nur bei `topic_type == "technique"`
- [x] Strukturierte Felder `start_situation`, `target_state`, `roadmap_notes` ### F14 — GraphEditor Workbench (0.8.233)
- [x] Prompt **087** `planning_progression_start_target`
- [x] Priorität: Trainer > KI > Regex (`resolve_roadmap_structured_input`)
- [x] Zwei-Schritt-UI: „Start/Ziel analysieren“ / „Roadmap vorschlagen“
### F6 — Gap-KI-Kontext (0.8.212–214) - [x] `ProgressionGraphEditor` — primäre UI für Roadmap + Match + Lücken
- [x] Vier Planungskontext-Dropdowns im Editor
- [x] `progressionGraphDraft.js` — Artefakt + API-Payload
- [x] `ExerciseGapFillPrepModal` vor KI-Call ### F15 — Match-Dialog & getrennte Pfad-QS (2026-05-22, lokal)
- [x] `planning_exercise_form_context.py` — Gap-Snapshot, `context_preview`
- [x] Migration **085** — `planning_context` in Übungs-Prompts
### F7 — Fähigkeiten-Scoring (0.8.215–216) - [x] **`unified_slot_review`** — Dialog pro Slot (Bibliothek + KI, Stufen-Fit-Vergleich)
- [x] Vorauswahl: Bibliothek nur bei Stufen-Fit ≥ 50 %; sonst KI bei leerem/schwachem Slot
- [x] Übernahme ohne teure Auto-Nach-Bewertung; manuell „Graph bewerten“
- [x] **`path_qa.roadmap_qa`** + **`path_qa.assignment_qa`**; Gesamt = Minimum
- [x] **`findings_stale`** im Graph-Artefakt — Hinweis „Bewertung veraltet“ (persistiert)
- [x] Slot-Key-Fix — Lernziel editierbar ohne Fokusverlust
- [x] `planning_skill_expectations.py` (Scopes: `progression_stage`, `progression_path`) ### Validierung (Referenz Mae Geri, 2026-05)
- [x] Pro-Stufe-Retrieval + `path_skill_expectations` + UI-Tags
- [x] `expected_skills` in Gap-Fill
### F8 — Stufen-Details UI (0.8.216) | Phase | Roadmap-QS | Besetzung | Gesamt | Ergebnis |
|-------|------------|-----------|--------|----------|
| Vor Roadmap/KI | — | — | ~65 % | Lücken, Off-Topic |
| Roadmap ok, Slots leer | ~88 % | ~8–15 % | **~8–15 %** | Besetzung fehlt |
| Nach Match + Fill | ~88 % | hoch | **~85 %+** | Vollständige Abdeckung |
- [x] Editierbare `stage_specs` in `roadmap_override` (Belastung, Erfolgskriterien, Vermeiden) **Fazit:** Roadmap-QS und Besetzungs-QS getrennt betrachten; Workbench + Katalog + Roadmap universell.
### F9 — Persistenz (0.8.217) ---
- [x] Migration **088** — `planning_roadmap` JSONB am Graph ## UX — UI-Überarbeitung (offen)
- [x] Laden/Speichern über `GET/PUT` Graph + Sequenz-Endpoint
### UX — UI-Überarbeitung (offen) - [ ] Wizard mit 4 Schritten (Ziel & Katalog → Roadmap → Match → Lücken)
- [ ] Progressive disclosure — Details in Panels
- [ ] PathBuilder-Parität: gleiche Katalog-Dropdowns wie GraphEditor
- [ ] QS-UI: positive LLM-Hinweise als Highlights
- Briefing: `PLANNING_PROGRESSION_GRAPH_KI.md` §12
- [ ] Wizard mit 4 Schritten (Ziel → Roadmap → Match → Lücken) ---
- [ ] Progressive disclosure — Details in Panels, nicht alles gleichzeitig
- [ ] Briefing: `PLANNING_PROGRESSION_GRAPH_KI.md` §10 ## Phase D′ — Auto Gap-Fill (Backlog)
- [ ] Bei persistent `roadmap_unfilled` automatisch KI-Vorschlag vorbereiten (ohne manuelles Modal)
- [ ] Governance: Trainer bestätigt vor Persistenz
---
## Phase G — Trainingsplanung (komplexere Domäne)
**Ziel:** Einheiten, Rahmen-Slots, Abschnitte und parallele Streams KI-gestützt planen — **ohne** zweite Retrieval-Welt.
### Wiederverwendung aus Progressionsgraph
| Baustein | Progressionsgraph | Trainingsplanung |
|----------|-------------------|------------------|
| `PlanningTargetProfile` | Curriculum-Query + Katalog | Einheit + Abschnitt + Slot + Katalog + Historie |
| `planning_catalog_context` | Am Graph gespeichert | Pro Einheit / Slot / Voreinstellung |
| `planning_skill_expectations` | `progression_stage`, `progression_path` | **`training_section`**, **`framework_slot`** |
| `planning_exercise_retrieval` | Roadmap-Stufen-Match | `suggest_planning_exercises` — **bereits produktiv** |
| `planning_path_qa_pipeline` | Curriculum-QS | Abschnitts-QS (Kohärenz, Streams) |
| `planning_exercise_form_context` | Pfad-Lücken | Abschnitts-/Slot-Lücken |
| Roadmap-Pipeline | Major Steps über Wochen | **Nicht 1:1** — Phasen/Streams + Vorlagen |
### Was Phase G neu braucht
- Gruppen-/Historie-Kontext-Pack (`AI_PLANNING_KI_MULTISTAGE_FORECAST` S0–S4)
- Abschnitts-Didaktik — Dauer, Parallel-Streams, Coaching
- Rahmen-Blueprint-Anbindung (`training_framework_programs`, Slot-Blueprints)
- Eigene Orchestrierung pro Einheit (kein Curriculum über N Wochen)
### Integrations-Reihenfolge G0–G4
| Schritt | Inhalt | Abhängigkeit |
|---------|--------|--------------|
| **G0** | Katalog in Einheits-Editor → bestehende Suggest-Pipeline | F13 ✅ |
| **G1** | Scope `training_section` + Skill-Erwartungen aktiv | F7 ✅ |
| **G2** | Abschnitts-QS (Hint-Struktur wie Graph) | F11–F12 ✅ |
| **G3** | Framework-Slot + Gap-Fill | G0, G1 |
| **G4** | Gruppenkontext-Pack | G0–G3 |
**Nicht:** Roadmap-first-Loop 1:1 auf Trainingseinheit mappen.
Details: **`PLANNING_PROGRESSION_GRAPH_KI.md`** §16 · Domäne **`DOMAIN_MODEL.md`** §1–2.
---
## Phase H1 — Katalog-Prompt-Snippets (Spez geplant)
**Spec:** **`PLANNING_CATALOG_PROMPT_SNIPPETS.md`**
Modulare Textbausteine pro Katalog-Ausprägung in LLM-Prompts (Roadmap, Pfad-QS, Stufen-Spec) — **nicht** neue Retrieval-Welt.
**Priorität (absteigend):** Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung.
- [ ] `planning_catalog_prompt_snippets.py` + Registry (5–8 Snippets)
- [ ] Platzhalter `{{catalog_guidance_block}}` in Pfad-QS + Roadmap-Prompts
- [ ] Dev-Regression: Gewaltschutz / Breitensport / Kinder — QS-Hinweise passend zum Kontext
---
## Phase H — Plattform (Backlog)
- [ ] Technik-Disambiguierung konfigurierbar (DB statt `_GERI_TECHNIQUES` in Code)
- [ ] Mitai Workflow-Engine — erst wenn G0–G4 stabil
--- ---
@@ -112,10 +191,10 @@ Diese Roadmap ergänzt die **Architektur-Refaktor-Roadmap** (`UMSETZUNGSPLAN_ROA
| Von | Nach | Hinweis | | Von | Nach | Hinweis |
|-----|------|---------| |-----|------|---------|
| F2 | Enrichment / Skills | Bessere Roadmap bei technikspezifischen Skills | | F13 | G0, **H1** | Katalog-Kontext in Einheitsplanung; Snippets in LLM-Prompts |
| F3 | F2 | LLM-Roadmap oder stabile heuristische B | | F7, F11 | G1, G2 | Skill-Expectations + QS-Muster |
| G | F4 | Trainingsplanung kann Roadmap aus Graph referenzieren | | F4, F9 | G3 | Graph-Roadmap kann Rahmen referenzieren |
| H | G + F4 | Workflow-Engine lohnt bei verzweigten Planungsflows | | G | H | Workflow-Engine lohnt bei verzweigten Planungsflows |
--- ---
@@ -1,7 +1,7 @@
# Progressionsgraph — KI-Planung (Ist-Stand) # Progressionsgraph — KI-Planung (Ist-Stand)
**Stand:** 2026-05-22 (Dokumentation) · **App-Version:** **0.8.218** · **DB:** Migration **088** **Stand:** 2026-05-22 (Dokumentation) · **App-Version:** **0.8.233** · **DB:** Migration **088**
**Maßgeblich für Code:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`) **Maßgeblich für Code:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS.planning_exercise_suggest`)
> **Diese Datei ist die zentrale Referenz** für die KI-gestützte Planung im Progressionsgraph. > **Diese Datei ist die zentrale Referenz** für die KI-gestützte Planung im Progressionsgraph.
> Ältere Abschnitte in `HANDOVER.md` §2.8 und `PLANNING_KI_ROADMAP.md` verweisen hierher. > Ältere Abschnitte in `HANDOVER.md` §2.8 und `PLANNING_KI_ROADMAP.md` verweisen hierher.
@@ -10,6 +10,7 @@
`.claude/docs/working/PLANNING_PROGRESSION_ROADMAP_SPEC.md` (Zielarchitektur) · `.claude/docs/working/PLANNING_PROGRESSION_ROADMAP_SPEC.md` (Zielarchitektur) ·
`.claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md` (Retrieval/Scoring) · `.claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md` (Retrieval/Scoring) ·
`.claude/docs/technical/SKILL_SCORING_SPEC.md` (Fähigkeiten-Scoring) · `.claude/docs/technical/SKILL_SCORING_SPEC.md` (Fähigkeiten-Scoring) ·
**`PLANNING_CATALOG_PROMPT_SNIPPETS.md`** (H1 — modulare Katalog-Prompts) ·
`docs/architecture/PLANNING_KI_ROADMAP.md` (Produkt-Roadmap Phase G+) `docs/architecture/PLANNING_KI_ROADMAP.md` (Produkt-Roadmap Phase G+)
--- ---
@@ -30,19 +31,20 @@
## 2. Trainer-Workflow (UI) ## 2. Trainer-Workflow (UI)
Aktuell in `ExerciseProgressionPathBuilder.jsx` (eingebettet in `ExerciseProgressionGraphPanel.jsx`): **Primär:** `ProgressionGraphEditor.jsx` (integrierter Slot-Editor, Phase B).
**Legacy/Parallel:** `ExerciseProgressionPathBuilder.jsx` (Scroll-Monolith — gleiche API, Katalog-Kontext-Dropdowns dort noch nachziehen).
``` ```
① Ziel eingeben (+ optional Start/Ziel-Felder manuell) ① Ziel eingeben (+ Planungskontext: Primärfokus, Stil, Trainingsstil, Zielgruppe)
② „Start/Ziel analysieren“ (optional, start_target_only) ② Optional: Start/Ziel-Felder manuell oder „Start/Ziel analysieren“
③ „Roadmap vorschlagen“ (roadmap_only, LLM-Roadmap) ③ „Roadmap generieren“ (roadmap_only, LLM-Roadmap)
④ Roadmap bearbeiten (Major Steps + Stufen-Details) ④ Roadmap bearbeiten (Major Steps + Stufen-Details)
⑤ „Übungen matchen“ (roadmap_first + roadmap_override) ⑤ „Übungen matchen“ (roadmap_first + roadmap_override + Auto-QS/Rematch)
⑥ Lücken mit KI schließen (gap_fill_offers + Vorbereitungs-Dialog) ⑥ Lücken: KI-Angebote → „KI anlegen“ (Gap-Prep-Modal) → in Slot
⑦ „Pfad in Graph speichern“ (Sequenz-Kanten) ⑦ „Graph speichern“ (planning_roadmap + optional Kanten-Sequenz)
``` ```
**Bekannte UX-Schuld:** Alle Schritte liegen auf **einer langen Scroll-Seite** — Überarbeitung als Wizard/Stepper ist geplant (separater UI-Chat). Briefing-Vorlage siehe unten §10. **Bekannte UX-Schuld:** PathBuilder = lange Scroll-Seite; GraphEditor = kompakter, aber noch kein Wizard. Stepper geplant (separater UI-Chat). Briefing §12.
--- ---
@@ -51,6 +53,7 @@ Aktuell in `ExerciseProgressionPathBuilder.jsx` (eingebettet in `ExerciseProgres
```mermaid ```mermaid
flowchart TB flowchart TB
subgraph ui [Frontend] subgraph ui [Frontend]
PGE[ProgressionGraphEditor]
EPB[ExerciseProgressionPathBuilder] EPB[ExerciseProgressionPathBuilder]
GFM[ExerciseGapFillPrepModal] GFM[ExerciseGapFillPrepModal]
PCtx[planningContextForExerciseAi.js] PCtx[planningContextForExerciseAi.js]
@@ -71,6 +74,10 @@ flowchart TB
subgraph match [Match + QA] subgraph match [Match + QA]
PB[planning_exercise_path_builder.py] PB[planning_exercise_path_builder.py]
PCC[planning_catalog_context.py]
REM[planning_path_rematch.py]
REF[planning_path_refine_stage.py]
QAP[planning_path_qa_pipeline.py]
RET[planning_exercise_retrieval.py] RET[planning_exercise_retrieval.py]
PG[planning_exercise_progression.py] PG[planning_exercise_progression.py]
SEM[planning_exercise_semantics.py] SEM[planning_exercise_semantics.py]
@@ -88,11 +95,16 @@ flowchart TB
end end
EPB --> PPS EPB --> PPS
EPB --> SEQ PGE --> PPS
EPB --> PUT PGE --> SEQ
PGE --> PUT
GFM --> EAI GFM --> EAI
PPS --> PR PPS --> PR
PPS --> PB PPS --> PB
PB --> PCC
PB --> REM
PB --> REF
PB --> QAP
PB --> RET PB --> RET
PB --> PG PB --> PG
PB --> PSE PB --> PSE
@@ -108,12 +120,18 @@ flowchart TB
| Modul | Aufgabe | | Modul | Aufgabe |
|--------|---------| |--------|---------|
| `planning_progression_roadmap.py` | Phasen A–C: Zielanalyse, Roadmap, `stage_specs`; Start/Ziel-Auflösung (Trainer > KI > Regex) | | `planning_progression_roadmap.py` | Phasen A–C: Zielanalyse, Roadmap, `stage_specs`; Start/Ziel-Auflösung (Trainer > KI > Regex) |
| `planning_exercise_path_builder.py` | `suggest_progression_path`: roadmap_first Match, QA, Gap-Offers | | `planning_exercise_path_builder.py` | `suggest_progression_path`: roadmap_first Match, Auto-QS, Rematch, Gap-Offers |
| `planning_catalog_context.py` | **Expliziter Katalog-Kontext** (Fokus, Stil, Trainingsstil, Zielgruppe) → `PlanningTargetProfile` |
| `planning_path_rematch.py` | Auto-Rematch betroffener Slots (`max_rematch_rounds`) |
| `planning_path_refine_stage.py` | Stufen-Spec-Verfeinerung bei `stage_mismatch` (Phase C) |
| `planning_path_qa_pipeline.py` | Mehrstufige QS → `optimization_hints` |
| `planning_exercise_progression.py` | Graph auflösen, Nachfolger-Kanten für Retrieval-Bias | | `planning_exercise_progression.py` | Graph auflösen, Nachfolger-Kanten für Retrieval-Bias |
| `planning_skill_expectations.py` | Skill-Erwartungen pro Scope (`progression_stage`, `progression_path`, später `training_section`) | | `planning_skill_expectations.py` | Skill-Erwartungen pro Scope (`progression_stage`, `progression_path`, später `training_section`) |
| `planning_exercise_form_context.py` | `planning_context` / Gap-Snapshot für Übungs-KI | | `planning_exercise_form_context.py` | `planning_context` / Gap-Snapshot für Übungs-KI |
| `planning_exercise_path_ai_fill.py` | Gap-Fill-Angebote, `goal_for_ai`, `context_preview` | | `planning_exercise_path_ai_fill.py` | Gap-Fill-Angebote, `goal_for_ai`, `context_preview` |
| `progression_graph_planning_artifact.py` | Validierung `planning_roadmap` JSON (Schema v1, max. 64 KB) | | `progression_graph_planning_artifact.py` | Validierung `planning_roadmap` JSON (Schema v1, max. 64 KB) |
| `planning_exercise_profiles.py` | **Katalog-Scoring** (Fokus/Stil/TT/ZG/Skills) — gemeinsam mit Einheitsplanung |
| `planning_exercise_target_pipeline.py` | Query-Intent-Pipeline — Progressionsgraph nutzt `query_only`-Modus + Katalog-Overlay |
--- ---
@@ -131,10 +149,18 @@ flowchart TB
| `start_target_only` | bool | Nur Start/Ziel-Analyse | | `start_target_only` | bool | Nur Start/Ziel-Analyse |
| `roadmap_override` | object | Trainer-bearbeitete `major_steps` + `stage_specs` | | `roadmap_override` | object | Trainer-bearbeitete `major_steps` + `stage_specs` |
| `start_situation`, `target_state`, `roadmap_notes` | string? | Strukturierte Eingabe (Priorität vor KI) | | `start_situation`, `target_state`, `roadmap_notes` | string? | Strukturierte Eingabe (Priorität vor KI) |
| `planning_catalog_context` | object? | Primärfokus, Stilrichtung, Trainingsstil, Zielgruppe (IDs + `is_primary`) |
| `include_llm_start_target` | bool | LLM-Extraktion Start/Ziel (Prompt **087**) | | `include_llm_start_target` | bool | LLM-Extraktion Start/Ziel (Prompt **087**) |
| `include_llm_roadmap` | bool | LLM Roadmap (Prompts **078/079**) | | `include_llm_roadmap` | bool | LLM Roadmap (Prompts **078/079**) |
| `include_llm_intent` | bool | LLM Intent für Semantic Brief (Roadmap-Vorschlag: **true** seit 0.8.217) | | `include_llm_intent` | bool | LLM Intent für Semantic Brief |
| `include_path_qa`, `include_ai_gap_fill` | bool | QS, Lücken-Angebote | | `auto_rematch_after_qa` | bool | Auto-Rematch nach QS (Default **true**) |
| `auto_refine_stage_spec` | bool | Stufen-Spec bei `stage_mismatch` schärfen (Default **true**) |
| `max_rematch_rounds` | int | Rematch-Runden 0–4 (Default **3**) |
| `include_path_qa`, `include_llm_path_qa`, `include_ai_gap_fill` | bool | QS, LLM-Ganzpfad, Lücken-Angebote |
| `evaluate_only` | bool | Nur QS auf `evaluate_steps[]` — kein Match |
| `unified_slot_review` | bool | Pro-Slot-Review (Bibliothek + optional KI) für Match-Dialog; erfordert `baseline_evaluate_steps` + Roadmap |
| `baseline_evaluate_steps` | array? | Slot-Stand für Schritt 1 / Review-Baseline |
| `baseline_path_qa_snapshot` | object? | `path_qa` aus evaluate_only (Schritt 1 des Match-Flows) |
### 4.2 Wichtige Response-Felder ### 4.2 Wichtige Response-Felder
@@ -144,7 +170,31 @@ flowchart TB
| `steps[]` | Gematchte Übungen; pro Schritt u. a. `roadmap_*`, `skill_expectations` | | `steps[]` | Gematchte Übungen; pro Schritt u. a. `roadmap_*`, `skill_expectations` |
| `path_skill_expectations` | Pfadweite Skill-Erwartungen | | `path_skill_expectations` | Pfadweite Skill-Erwartungen |
| `gap_fill_offers[]` | Lücken mit `context_preview`, `goal_for_ai` | | `gap_fill_offers[]` | Lücken mit `context_preview`, `goal_for_ai` |
| `path_qa` | QS inkl. `roadmap_qa_mode: roadmap_first_lite` | | `path_qa` | QS inkl. `qa_tiers`, `optimization_hints`, `rematch_log`, `refine_log`; **F15:** auch `roadmap_qa`, `assignment_qa` (siehe §8.1) |
| `slot_reviews[]` | Bei `unified_slot_review`: je Slot `library_alternative`, `ai_alternative`, `auto_select`-Flags |
| `findings_stale` | Im Graph-Artefakt (nicht API-Response): Bewertung veraltet seit letztem „Graph bewerten“ |
| `target_profile_summary` | Erwartungsprofil inkl. Katalog-Dimensionen (nach Match) |
| `match_summary` | `library_matches`, `gap_fill_offer_count`, `roadmap_unfilled_count` |
---
## 4.4 Planungskontext — Katalog vs. Technik-Vokabular
Shinkan unterscheidet **drei Schichten** (kein monolithisches „Vokabular“):
| Schicht | Was | Wo | Beispiel |
|---------|-----|-----|----------|
| **Katalog-Dimensionen** | Was für Training? | DB: `focus_areas`, `style_directions`, `training_types`, `target_groups`, `skills` | Gewaltschutz, Breitensport, Shotokan |
| **Disambiguierung (Technik)** | Verwechslungs-Nachbarn | Code: `planning_exercise_semantics.py` (`_GERI_TECHNIQUES`, …) | Mae Geri ≠ Mawashi Geri |
| **Didaktik / Kausalität** | Reihenfolge, Lernphasen | Roadmap + LLM Pfad-QS | Grundlagen vor Geschwindigkeit |
**Seit 0.8.233:** `planning_catalog_context` im Request und im Graph-Artefakt (`planning_catalog_context` JSON). Fließt in `PlanningTargetProfile` → Hybrid-Retrieval (`score_exercise_against_target`: „Fokusbereich passend“, …). Zusätzlich additive Text-Signale aus Anfrage + Start/Ziel + Notizen (`planning_exercise_text_signals`).
**Geplant (H1):** dieselben Dimensionen als **kaskadierte Prompt-Snippets** in Roadmap-, Stufen-Spec- und Pfad-QS-Prompts — Priorität Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung — siehe **`PLANNING_CATALOG_PROMPT_SNIPPETS.md`**.
**Technik-Gates** (`technique_scope`, Geschwister-Ausschluss) nur bei `topic_type == "technique"` — Fokus-Pfade (Gewaltschutz, Fitness, …) werden nicht wie Mae-Geri-Pfade behandelt.
Fallback: fehlt `planning_catalog_context` im Request, wird aus gespeichertem `planning_roadmap` am Graph geladen.
### 4.3 Prompt-Slugs (nur in `ai_prompts`, nie Hardcoding) ### 4.3 Prompt-Slugs (nur in `ai_prompts`, nie Hardcoding)
@@ -157,17 +207,33 @@ flowchart TB
--- ---
## 5. Roadmap-Match — Stufen-Qualität (0.8.218) ## 5. Roadmap-Match — Stufen-Qualität (0.8.218–0.8.233)
Pro Major Step gilt: Pro Major Step gilt:
1. **Stufen-Brief** — `semantic_brief_for_stage()` ergänzt `must_phrases` um das Stufen-Lernziel. 1. **Stufen-Brief** — `build_stage_match_brief()` aus Lernziel, `anti_patterns`, Erfolgskriterien, Pfad-Kontext.
2. **Stufen-Gate** — `exercise_passes_stage_learning_goal_gate()` prüft Lernziel-Text in Titel/Summary/Ziel oder Mindest-`semantic_score`. 2. **Stufen-Gate** — `exercise_passes_stage_fit()` / `exercise_passes_stage_learning_goal_gate()` auf vollem Übungstext.
3. **Kein Fallback** — Bei `roadmap_first` wird **nicht** auf die globale `goal_query` zurückgefallen; passt keine Übung → **Lücke** (`roadmap_unfilled`) statt themenfremder Übung. 3. **Kein blindes Rank-Fallback** — ohne Gate-Passung → `roadmap_unfilled`, nicht themenfremde Übung.
4. **Retrieval** — Bonus/Strafe im Hybrid-Score je nach Stufen-Passung. 4. **Post-Match-Gate** — `_roadmap_step_passes_post_match_gate()` = gleiche QS wie `detect_off_topic_steps` (kein Rematch-Treffer, der sofort wieder `stage_mismatch` wäre).
5. **QS** — `detect_off_topic_steps` erkennt `stage_mismatch` anhand `roadmap_learning_goal`. 5. **Retrieval** — Hybrid-Score: Volltext + Semantik + **Profil/Katalog** + Skill-Erwartungen + optional Graph-Bias.
6. **Auto-Optimierung (ein Match-Lauf):**
- **Phase B:** Rematch-Schleife (`planning_path_rematch.py`) für `rematch_slot` / `roadmap_unfilled`
- **Phase C:** `planning_path_refine_stage.py` — `anti_patterns` / Erfolgskriterien aus QS
- Purge persistent `stage_mismatch` → Slot leeren + KI-Gap
- LLM Pfad-QS **nach** Rematch auf finalem Pfad
- Gap-Offers für alle leeren Slots **vor** `path_qa`-Summary
Tests: `test_planning_roadmap_stage_match.py` Tests: `test_planning_roadmap_stage_match.py`, `test_planning_path_rematch.py`, `test_planning_path_refine_stage.py`, `test_planning_catalog_context.py`
### Referenz-Validierung (Mae Geri, 2026-05)
| Phase | Roadmap-QS | Besetzung | Gesamt (min) | Ergebnis |
|-------|------------|-----------|--------------|----------|
| Vor Roadmap/KI-Anpassung | — | — | ~65 % | Strukturelle Lücken |
| Nach Trainer-Roadmap, **Slots leer** | ~85–88 % | ~8–15 % | **~8–15 %** | Roadmap ok, Besetzung fehlt |
| Nach Match + befüllte Slots | ~85–88 % | hoch | **~85 %+** | Vollständige Curriculum-Abdeckung |
**Lesson:** **`roadmap_qa`** und **`assignment_qa`** getrennt interpretieren; Gesamt-QS allein bei leerer Roadmap irreführend (historisch nur LLM-Roadmap-Score).
--- ---
@@ -209,7 +275,15 @@ Gespeichert am **Graph-Container** (`exercise_progression_graphs`), Schema v1:
"roadmap_notes": "…", "roadmap_notes": "…",
"max_steps": 5, "max_steps": 5,
"progression_roadmap": { }, "progression_roadmap": { },
"path_skill_expectations": { } "path_skill_expectations": { },
"planning_catalog_context": {
"focus_areas": [{ "id": 1, "is_primary": true }],
"style_directions": [],
"training_types": [{ "id": 2, "is_primary": true }],
"target_groups": []
},
"slot_contents": [ ],
"last_findings": { }
} }
``` ```
@@ -263,6 +337,21 @@ API: `path_qa.qa_tiers`, `path_qa.optimization_hints` — **kein** anfrage-spezi
Phase G: gleiche Tiers für Abschnitts-QS nach Einheits-Match. Phase G: gleiche Tiers für Abschnitts-QS nach Einheits-Match.
### 8.1 Getrennte Pfad-QS — Roadmap vs. Übungsbesetzung (F15)
`build_path_qa_summary()` in `planning_exercise_path_qa.py` liefert drei Ebenen:
| Feld | Inhalt | Score-Logik |
|------|--------|-------------|
| **`roadmap_qa`** | Stufenlogik, LLM `topic_coverage`, Roadmap-Hinweise | LLM-`quality_score` oder heuristisch (Lücken, Hints) |
| **`assignment_qa`** | Leere Slots, Off-Topic auf belegten Slots, Fill-Statistik | Stark abwertend bei leeren Slots (~8–15 % bei 100 % leer) |
| **`quality_score`** (gesamt) | Anzeige „Pfad-QS gesamt“ | **`min(roadmap_qa, assignment_qa)`** |
| **`overall_ok`** | Gesamt-OK | Beide Dimensionen müssen OK sein |
UI: **`ProgressionFindingsPanel`** — zwei Unterblöcke; Match-Dialog zeigt Roadmap- vs. Besetzungs-Prozent. Nach Graph-Änderung: **`findings_stale: true`** im Artefakt → Hinweis „Bewertung veraltet“ (bis erneut „Graph bewerten“ + Speichern).
Tests: `test_planning_path_qa_split.py`, `test_planning_deterministic_quality_score.py`
## 9. Fähigkeiten-Scoring-Anbindung ## 9. Fähigkeiten-Scoring-Anbindung
Modul: `planning_skill_expectations.py` Modul: `planning_skill_expectations.py`
@@ -307,26 +396,75 @@ Kontext-Helfer: `frontend/src/utils/planningContextForExerciseAi.js`
| F7 | `planning_skill_expectations` (Retrieval + UI + Gap) | ✅ | 0.8.215–216 | | F7 | `planning_skill_expectations` (Retrieval + UI + Gap) | ✅ | 0.8.215–216 |
| F8 | Editierbare `stage_specs` in UI | ✅ | 0.8.216 | | F8 | Editierbare `stage_specs` in UI | ✅ | 0.8.216 |
| F9 | `planning_roadmap` Persistenz (Migration **088**) | ✅ | 0.8.217 | | F9 | `planning_roadmap` Persistenz (Migration **088**) | ✅ | 0.8.217 |
| F10 | Stufen-Lernziel-Gate beim Match (kein goal_query-Fallback) | ✅ | 0.8.218 | | F10 | Stufen-Lernziel-Gate + kein goal_query-Fallback | ✅ | 0.8.218 |
| **G** | Trainingsplanung eigene Pipeline + Graph-Referenz | 🔲 | — | | **F11** | Auto-Rematch + Stufen-Spec-Refine + mehrstufige QS | ✅ | 0.8.225–0.8.230 |
| **UX** | Wizard/Stepper statt Scroll-Monolith | 🔲 | separater Chat | | **F12** | Post-Match-Gate, LLM-QA nach Rematch, Gap-Timing, `roadmap_unfilled`-Sync | ✅ | 0.8.231–0.8.232 |
| **F13** | **Katalog-Kontext** (`planning_catalog_context`) im Match + Graph-Artefakt | ✅ | **0.8.233** |
| **F14** | `ProgressionGraphEditor` Slot-UI + Planungskontext-Dropdowns | ✅ | 0.8.233 |
| **F15** | Unified Slot-Review, getrennte Pfad-QS, `findings_stale`, Match-Vorauswahl | ✅ | lokal (2026-05-22) |
| **H1** | **Katalog-Prompt-Snippets** — modulare LLM-Anweisungen pro Dimension | 🔲 | Spec **`PLANNING_CATALOG_PROMPT_SNIPPETS.md`** |
| **G** | Trainingsplanung: eigene Pipeline + Wiederverwendung Bausteine (§16) | 🔲 | — |
| **UX** | Wizard/Stepper; PathBuilder-Parität Katalog | 🔲 | — |
| **H** | Technik-Disambiguierung konfigurierbar (DB statt Code-Tuples) | 🔲 | Backlog |
| **D′** | Auto Gap-Fill (KI generiert bei persistent `roadmap_unfilled`) | 🔲 | Backlog |
--- ---
## 12. Offenes Backlog (priorisiert) ## 12. Offenes Backlog (priorisiert)
1. **UI-Überarbeitung** — Wizard mit 4 Schritten, progressive disclosure (Briefing unten) 1. **H1 Katalog-Prompt-Snippets** — modulare LLM-Anweisungen (Priorität: Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung) — **`PLANNING_CATALOG_PROMPT_SNIPPETS.md`**
2. **Graph-Erweiterungsmodus** — Start ab gewähltem Knoten / letzter Sequenz 2. **Dev-Regression:** Gewaltschutz + Breitensport + Kinder (ohne Mae Geri) — Katalog-Match verifizieren
3. **Kontext auf allen Pfad-Schritten** in UI (nicht nur Lücken) 3. **PathBuilder-Parität** — gleiche `planning_catalog_context`-Dropdowns in `ExerciseProgressionPathBuilder`
4. **Trainingsplanung Phase G** — Pipeline mit Gruppenkontext, Wiederverwendung `planning_skill_expectations` 4. **UI-Wizard** — 4 Schritte (Ziel → Roadmap → Match → Lücken); Backend unverändert
5. Enrichment / Prompt-Feintuning 5. **Graph-Erweiterungsmodus** — Start ab gewähltem Knoten / letzter Sequenz
6. Mitai Workflow-Engine (langfristig) 6. **Phase D′** — automatisches KI-Gap-Fill bei persistent leeren Slots
7. **Trainingsplanung Phase G** — siehe §16
8. **Technik-Katalog externalisieren** — konfigurierbare `concept_groups` (Backlog)
9. Graph-Metadaten: Primärfokus/Stil als Spalten (Reporting)
10. Mitai Workflow-Engine (langfristig)
### Briefing-Vorlage UI-Chat (Copy-Paste) ### Briefing-Vorlage UI-Chat
Siehe Nutzer-Chat 2026-05-22 oder `HANDOVER.md` §2.8 — Abschnitt „UI-Überarbeitung“. Kern: Wizard ① Ziel & Planungskontext → ② Roadmap → ③ Match → ④ Lücken & Speichern; Backend-Pipeline unverändert lassen.
Kern: Wizard ① Ziel & Start/Ziel → ② Roadmap → ③ Match → ④ Lücken & Speichern; Backend-Pipeline unverändert lassen. ---
## 16. Wiederverwendung in der Trainingsplanung (Phase G)
Die **komplexere Trainingsplanung** (Einheit, Rahmen-Slot, Abschnitt, parallele Streams) soll **keine zweite Retrieval-Welt** bauen, sondern bestehende Module mit **anderem Kontext-Pack** nutzen.
### 16.1 Was Progressionsgraph liefert (Workbench-Muster)
| Baustein | Progressionsgraph | Trainingsplanung (Ziel) |
|----------|-------------------|-------------------------|
| `PlanningTargetProfile` | Query + Katalog + Skills | Einheit + Abschnitt + Slot + Katalog + Historie |
| `planning_catalog_context` | Am Graph gespeichert | Pro Einheit / Slot / Trainer-Voreinstellung |
| `planning_skill_expectations` | `progression_stage` / `progression_path` | **`training_section`**, **`framework_slot`** |
| `planning_exercise_retrieval` | Roadmap-Stufen-Match | Abschnitts-Suche (`suggest_planning_exercises`) — **produktiv** |
| `planning_path_qa_pipeline` | Curriculum-QS | Abschnitts-QS (Kohärenz, Streams) |
| `planning_intent_context` | Pfad-Ausschlüsse → Stufen | Abschnitts-Guidance → Brief |
| `planning_exercise_form_context` | Pfad-Lücken | Abschnitts-/Slot-Lücken |
| Roadmap-Pipeline | Curriculum Major Steps | **Nicht 1:1** — Phasen/Streams + Vorlagen |
| Technik-Disambiguierung | bei `topic_type=technique` | nur bei explizitem Technik-Abschnitt |
### 16.2 Was Phase G neu braucht
- **Gruppen-/Historie-Kontext-Pack** (`AI_PLANNING_KI_MULTISTAGE_FORECAST` S0–S4)
- **Abschnitts-Didaktik** — Dauer, Parallel-Streams, Coaching (`training_unit_phases`)
- **Rahmen-Blueprint** — bereits `training_framework_programs` / Slot-Blueprints
- **Eigene Orchestrierung** pro Einheit — kein Curriculum über N Wochen
### 16.3 Integrations-Reihenfolge (Phase G)
1. **G0** — Katalog in Einheits-Editor → bestehende Suggest-Pipeline
2. **G1** — Scope `training_section` + Skill-Erwartungen aktiv
3. **G2** — Abschnitts-QS (Hint-Struktur wie Graph)
4. **G3** — Framework-Slot + Gap-Fill
5. **G4** — Gruppenkontext-Pack
**Nicht:** Roadmap-first-Loop 1:1 auf Trainingseinheit mappen.
Domänenbezug: **`DOMAIN_MODEL.md`** §1–2 (Katalog-Dimensionen).
--- ---
@@ -342,6 +480,10 @@ Kern: Wizard ① Ziel & Start/Ziel → ② Roadmap → ③ Match → ④ Lücken
| `test_planning_exercise_form_context.py` | `planning_context`, Gap-Snapshot | | `test_planning_exercise_form_context.py` | `planning_context`, Gap-Snapshot |
| `test_progression_graph_planning_artifact.py` | JSONB-Artefakt-Validierung | | `test_progression_graph_planning_artifact.py` | JSONB-Artefakt-Validierung |
| `test_planning_exercise_progression.py` | Graph-Auflösung, Nachfolger | | `test_planning_exercise_progression.py` | Graph-Auflösung, Nachfolger |
| `test_planning_path_rematch.py` | Auto-Rematch, unfilled-Platzhalter |
| `test_planning_path_refine_stage.py` | Stufen-Spec-Refine |
| `test_planning_stage_anti_patterns.py` | Anti-Pattern-Sanitizer, Stufen-Gate |
| `test_planning_catalog_context.py` | Katalog-Kontext → Target-Profil |
--- ---
@@ -366,3 +508,4 @@ Kern: Wizard ① Ziel & Start/Ziel → ② Roadmap → ③ Match → ④ Lücken
| Datum | Änderung | | Datum | Änderung |
|-------|----------| |-------|----------|
| 2026-05-22 | Erstfassung Ist-Stand 0.8.217 — zentrale Referenz nach F5–F9 | | 2026-05-22 | Erstfassung Ist-Stand 0.8.217 — zentrale Referenz nach F5–F9 |
| 2026-05-22 | F11–F14: Auto-Optimierung, Katalog-Kontext, GraphEditor, Mae-Geri-Validierung, Phase-G-Wiederverwendung §16 |
@@ -0,0 +1,358 @@
# Designprinzipien – Abgleich Mitai ↔ Shinkan
**Status:** Review / Entscheidungsgrundlage
**Stand:** 2026-07-04
**Zweck:** Widersprüche, bewusste Abweichungen und Implementierungslücken zwischen den Designprinzipien-Serien identifizieren — Basis für **Familien-Entscheidungen** und langfristige Konvergenz von Mitai und Shinkan.
**Quellen:**
| App | Index |
|-----|--------|
| Mitai (Foundation) | [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md) — 9 Module |
| Shinkan | [design-principles/DESIGN_PRINCIPLES_INDEX.md](./design-principles/DESIGN_PRINCIPLES_INDEX.md) — 15 Module |
---
## 1. Kurzfassung
| Kategorie | Anzahl | Bedeutung |
|-----------|--------|-----------|
| **Familien-Konsens** | 12 Muster | In beiden Serien gleich oder kompatibel — **verbindlich für neue Apps** |
| **Bewusste Produkt-Abweichung** | 8 | Fachlich/Architektur begründet — **nicht angleichen**, aber im Familienmodell verankern |
| **Konzeptuelle Spannung** | 6 | Widersprüche oder gegenläufige Defaults — **Familien-Entscheidung nötig** |
| **Ist vs. Prinzip (Schuld)** | 14+ | Mindestens eine App verletzt eigene oder Schwester-Prinzipien — **Remediation** |
| **Nur Shinkan** | 6 Module | Mandanten-/Domänen-Bausteine ohne Mitai-Pendant |
| **Nur Mitai (reifer)** | 3 Muster | Data Layer, Widget-Dashboard, Universal Import — Shinkan vereinfacht oder fehlt |
**Kernbefund:** Mitai und Shinkan teilen dieselbe **technische Basis** (Auth, Migration, Nav-SSoT, Registry-Denken, Probe→Enforce), divergieren aber strukturell bei **Entitlement-Subjekt** (Profil vs. Verein), **Berechnungsarchitektur** (generischer Data Layer vs. domänenspezifisches Scoring) und **KI-Reife** (Unified Executor vs. schmale Laufzeit).
---
## 2. Familien-Konsens (für neue Produkte übernehmen)
Diese Muster sind in beiden Serien explizit oder implizit tragfähig:
| # | Muster | Mitai | Shinkan |
|---|--------|-------|---------|
| F1 | Server-Sessions + `Depends(require_auth)` | Auth #1–3 | Auth #1–2 |
| F2 | `profile_id` aus Session, nie aus Client-Header | Auth #3 | Auth #3 |
| F3 | Auth getrennt von Authorization/Entitlements | Auth #10 | Capabilities + Access Layer |
| F4 | Nummerierte SQL-Migrationen + Tracking beim Container-Start | Migration #1–5 | Migration #1–3 |
| F5 | Fail-fast, kein Auto-Rollback | Migration #5 | Migration #2 |
| F6 | `appNav` / zentrale Nav-Config als SSoT | Navigation #1 | Navigation #1 |
| F7 | Admin als eigener Hub/Realm | Navigation #6–7 | Navigation #2 |
| F8 | DB-konfigurierbare KI-Prompts (nicht hardcoded Prod) | Prompt #2 | AI Runtime #2 |
| F9 | Template vs. Kontext/Daten trennen | Prompt #5 | AI Runtime #4 |
| F10 | Ingest ≠ Interpretation beim Import | Import #2 | Wiki Import #1 |
| F11 | Preview/Dry-Run vor Massenimport | Import #3+ | Wiki Import #2 |
| F12 | 4-Phasen-Rollout Entitlements (Log → Enforce) | Feature #8 | Capability #2 |
**Empfehlung:** Als **`JINKENDO_FOUNDATION_CHECKLIST`** in künftigen Apps verpflichtend; Details pro Modul in den Einzeldokumenten.
---
## 3. Modul-Abgleich (9 vergleichbare Paare)
Legende **Bewertung:**
| Symbol | Bedeutung |
|--------|-----------|
| ✅ | Prinzipien aligned / kompatibel |
| ⚠️ | Teilweise aligned; Lücken in Implementierung oder Doku |
| 🔀 | Bewusste Produkt-Divergenz (kein Bug) |
| ❌ | Widerspruch oder gegenläufiges Konzept — Entscheidung nötig |
| 🏗️ | Ist-Stand verletzt dokumentierte Prinzipien (Architekturschuld) |
---
### 3.1 Prompt Engine (Mitai #1) ↔ AI Prompt Runtime (Shinkan #5)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Single Entry Point | `execute_prompt` / Unified System | `ai_prompt_runtime` + verteilte Orchestratoren | ❌ Konzept |
| Prompt-Typen | base / pipeline / workflow | nur slug + Mustache | 🔀 Shinkan bewusst schlanker |
| Platzhalter-Registry | zentral, API-Verträge | Kontext-Arten (`AiPromptContextKind`), kein Registry-Katalog | ⚠️ |
| Data Layer-Anbindung | Layer 1 → Resolver | Domänen-Builder ad hoc | ⚠️ |
| Debug/Preview | ausgereift | Admin-Vorschau, weniger Runtime-Transparenz | ⚠️ |
| Feature-Gating an Execute | teils fehlend (Legacy) | Capability geplant, teils Probe | 🏗️ beide |
**Widersprüche / gegenläufig:**
- Mitai: **Ein Executor** ist Kernprinzip. Shinkan: **kein** vergleichbarer Executor — Planungs-KI umgeht teils die Laufzeit.
- Beide warnen vor **parallelen KI-Pfaden**; beide haben sie noch (Mitai `insights.py`, Shinkan Router-OpenRouter).
**Familien-Entscheidung (Vorschlag):**
| Option | Inhalt |
|--------|--------|
| **Zielbild** | Gemeinsame **`prompt_executor`-Fassade** (Package oder Copy mit Namespace); Shinkan-Kontext-Builder als Plugins |
| **Shinkan-Roadmap** | Planungs-Orchestrierung in Laufzeit ziehen; keine Workflow-Graphs vor Planungs-Kontext-Reife |
| **Nicht kopieren** | Mitai: doppelte Pipeline-Modelle, PLACEHOLDER_MAP-Duplikat, Roh-SQL im Executor |
---
### 3.2 Data Layer (Mitai #2) ↔ Skill Scoring (Shinkan #8)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Berechnungs-SSoT | `data_layer/` Layer 0→1→2 | nur `skill_scoring.py` | ❌ Abdeckung |
| Router delegieren | explizites Prinzip #13 | Skill-Router ja; Planung teils nicht | ⚠️ |
| Confidence / data_points | Pflicht-Metadaten | nicht analog | 🔀 Domäne anders |
| Chart/KPI-Anbindung | Layer 2b Adapter | KPI-Dashboard ruft Router-Helfer | ⚠️ |
| Import-Grenze | keine Scores beim Insert | Wiki: explizit kein Scoring beim Insert | ✅ |
**Widerspruch:**
- Mitai postuliert **generische Berechnungsschicht** für die ganze App. Shinkan hat **kein** Data Layer — nur ein **domänenspezifisches** Scoring-Modul. Das ist keine Implementierungslücke allein, sondern **unterschiedliche Architektur-Tiefe**.
**Familien-Entscheidung (Vorschlag):**
| Option | Inhalt |
|--------|--------|
| **Familien-Prinzip** | „Berechnungen in benannter Schicht, nicht in Router/React“ — **Ja** |
| **Implementierung** | Mitai: `data_layer/` bleibt Referenz. Shinkan: Skill Scoring **ist** Layer-1-Vorbild; langfristig **`planning_metrics/`** o. ä. statt Router-SQL |
| **Nicht verallgemeinern** | Mitai-Formeln (TDEE, WHR) — nur Schichtenmodell übernehmen |
---
### 3.3 Feature & Entitlement (Mitai #3) ↔ Capability & Club Features (Shinkan #2)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Subjekt | **Profil** + Tier | **Verein** (`club_id`) + Plan | ❌ Scope |
| Auflösungs-API | `check_feature_access` | `check_capability` + `club_features` + `/me/entitlements` | 🔀 |
| Rollout 4 Phasen | ja | ja (Env-Flags) | ✅ |
| Registry | DB `features` + Tiers | Code-Registry → DB Sync | ⚠️ |
| Capabilities vs. Features | Features only | Capabilities **und** Kontingente getrennt | 🔀 Shinkan feiner |
| Widget/Layout-Gating | zentral | Entitlements-API, kein Widget-Layout | ⚠️ |
**Größter Familien-Konflikt:**
Mitai-Dokument #3 „Nicht übernehmen“ Punkt 10: *„Profile as Entitlement-Subject — Multi-App-Familie braucht separates Identity/Subscription-Boundary.“*
Shinkan **ist** die Antwort mit Verein als Subjekt — aber es gibt **kein gemeinsames Familienmodell**, das Profil-Tier **und** Org-Limits kombiniert.
**Familien-Entscheidung (Vorschlag):**
```
Entitlement-Subjekt (familie):
├── account (profile_id) → Tier, persönliche Limits (Mitai)
└── tenant (club_id?) → Org-Plan, Capabilities (Shinkan, optional null)
API: GET /me/entitlements?tenant_id=
Enforcement: eine resolve_entitlement(subject, capability|feature)
```
| App | Remediation |
|-----|-------------|
| Mitai | Org-Scope reservieren; Tier-Drift (#3 Schuld) bereinigen |
| Shinkan | `CLUB_FEATURE_ENFORCE=1` produktiv; Mitai-Legacy `check_feature_access` nicht nutzen (bereits Regel) |
---
### 3.4 Registry / Plugin (Mitai #4) ↔ Rights Registry (Shinkan #3)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Registry-first | Platzhalter, Widgets, CSV-Module | Capabilities + Features only | ⚠️ Abdeckung |
| Validierung an Grenze | ja | ja (`register_*` wirft) | ✅ |
| Runtime + DB | Dual (Katalog + DB-Overrides) | Code → DB Upsert | ✅ |
| Dual Registry FE/BE | Widgets + `registerDashboardWidgets` | nicht vorhanden | 🔀 |
| Metadaten-Tiefe | nach Risiko (Matrix in Doc) | schlankere Dataclasses | ✅ |
**Kein Widerspruch** — Shinkan Rights Registry ist **Teilmenge** des Mitai-Meta-Musters.
**Familien-Entscheidung:** Mitai-Registry-Matrix (Platzhalter / UI-Plugin / Import-Modul / Rechte) als **Familien-Taxonomie**; Shinkan erweitert um Import-/Prompt-Registry wenn Wiki-Import generisch wird.
---
### 3.5 Auth & Session (Mitai #5 ↔ Shinkan #4)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Session-Modell | opaque token | gleich (shared `auth.py`) | ✅ |
| Depends-Pattern | ja | ja (+ TenantContext) | ✅ |
| IDOR Profile-Header | dokumentierte Schwäche | Shinkan: Session-only betont | ⚠️ prüfen |
| RBAC | `role` admin/user | Portal-Rolle **+** Vereinsrollen | 🔀 |
| Rate Limiting | ja | (Mitai-spezifisch in Router) | ⚠️ |
| Feature-Flags in Session | Legacy-Spalten | Account-Lifecycle separat | 🏗️ Mitai |
**Gegenläufig:** Shinkan **erweitert** Auth um Mandanten — darf Mandantenlogik **nicht** in `auth.py` legen (Shinkan-Prinzip „Nicht übernehmen“).
**Familien-Entscheidung:** Gemeinsames Auth-Modul; **TenantContext** als optionales Add-on-Pattern für mandantenfähige Apps.
---
### 3.6 Universal Import (Mitai #6) ↔ Wiki Import (Shinkan #11)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| Ingest ≠ Interpretation | ✅ | ✅ | ✅ |
| Modul-Registry | zentral | fehlt (wiki-hardcoded) | ⚠️ |
| SAVEPOINT pro Zeile | ja | nicht dokumentiert | ⚠️ |
| Vorlagen/Mappings | generisch | SMW-Kategorien via Env | 🔀 |
| Feature-Limits | an Import gebunden | Admin-only | ⚠️ |
**Kein Konflikt** — unterschiedliche Reife. Shinkan ist **Spezialfall** des Mitai-Musters.
**Familien-Entscheidung:** Neue Import-Quellen über **Universal-Import-Gerüst** (Mitai); Wiki als `import_type=mediawiki` registrieren.
---
### 3.7 Dashboard Widgets (Mitai #7) ↔ Dashboard KPIs (Shinkan #14)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| UX-Modell | konfigurierbares Widget-Layout | festes KPI-Aggregat | ❌ UX-Konzept |
| Chatty Client vermeiden | via Widget-Daten | via `/dashboard/kpis` | ✅ Ziel |
| Entitlements | `allowed` pro Widget | TenantContext auf KPIs | ✅ |
| Data Layer | Widgets konsumieren Layer 1 | intern Router-Helfer | ⚠️ |
**Gegenläufig:** Mitai: **Nutzer konfiguriert Dashboard**. Shinkan: **Produkt definiert feste Kacheln** — bewusste MVP-Vereinfachung.
**Familien-Entscheidung:**
| App-Typ | Dashboard-Pattern |
|---------|-------------------|
| Personal Tracking (Mitai) | Widget-Katalog + Layout-JSON |
| Trainer/Verein (Shinkan) | Aggregierte KPI-Endpoints ausreichend; Widget-System optional Phase 2 |
| Neue App | Aggregat-Endpoint **mindestens**; Widget-System wenn Personalisierung nötig |
---
### 3.8 Navigation / IA (Mitai #8 ↔ Shinkan #12)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| appNav SSoT | ja | ja | ✅ |
| Admin-Hub | Shell + Hub-Gruppen | horizontale `AdminPageNav` | ⚠️ |
| Breakpoint 1024px | explizit | „prüfen“ | ⚠️ |
| Onboarding-Nav | — | reduziert ohne Verein | 🔀 Shinkan |
| adminNav.js SSoT | empfohlen | hardcoded Array in JSX | 🏗️ Shinkan |
| Safe Area PWA | ja | Design-System, weniger explizit | ⚠️ |
**Familien-Entscheidung:** `appNav.js` + **`adminNav.js`** als Pflicht; Shinkan `AdminPageNav` refactoren.
---
### 3.9 Migration & Deploy (Mitai #9 ↔ Shinkan #13)
| Aspekt | Mitai | Shinkan | Bewertung |
|--------|-------|---------|-----------|
| XXX_*.sql + schema_migrations | ✅ | ✅ | ✅ |
| Startup vor App | ✅ | ✅ | ✅ |
| develop/main | ✅ | ✅ | ✅ |
| Feste Ports | ✅ | ✅ | ✅ |
| Immutabler Docker-Build | dokumentiert | nicht im Shinkan-Doc | ⚠️ Doku |
| Health-Check / PG wait | ausführlich | kürzer | ⚠️ Doku |
**Aligned** — Shinkan-Dokument ist **Untermenge**; Implementierung vermutlich gleich (shared Infra).
---
## 4. Nur Shinkan (6 Module) — Einordnung für die Familie
| Modul | Familien-Relevanz | Mitai-Bezug |
|-------|-------------------|------------|
| **Access Layer & Tenant** | **Pflicht** für mandantenfähige Apps | Mitai #3 fordert Org-Boundary — hier ausformuliert |
| **Media Assets & Archiv** | Optional (Content-Apps) | — |
| **Exercise Catalog** | Shinkan-Domäne | — |
| **Training Planning** | Shinkan-Domäne | — |
| **Content Reports (P-13)** | Empfohlen für UGC/Plattform | — |
| **Maturity Models** | Optional (Kompetenz-Apps) | — |
**Kein Widerspruch zu Mitai** — ergänzen das Familienmodell um **Mandant + Content-Governance**.
---
## 5. Querschnitt: Ist-Stand vs. dokumentierte Prinzipien
Gemeinsame **Architekturschuld** (beide Apps verletzen teils eigene „Nicht übernehmen“-Listen):
| Thema | Mitai | Shinkan |
|-------|-------|---------|
| Parallele KI-Pfade | `insights.py` Legacy | OpenRouter direkt in Routern |
| Entitlement Enforcement | teils UI-only / Legacy-Spalten | Env Probe-only |
| Registry-Sync / Duplikat | PLACEHOLDER_MAP + Registry | Capabilities-Sync, kein Prompt-Registry |
| Frontend ohne Backend-Gate | teils | Capabilities Probe |
| Dokumentations-Drift | Tier vs. Enforcement-Docs | Endpoint-Audit unvollständig |
| Monolithische Pages/Client | God Pages, api.js | God Pages, api.js (Roadmap Phase 4) |
| Fehlende JSON-Schema-KI | TODO | TODO (explizit vermeiden) |
---
## 6. Entscheidungs-Matrix (Priorisiert)
| Prio | Entscheidung | Betroffene Apps | Empfohlene Familien-Regel |
|------|--------------|-----------------|---------------------------|
| **P0** | Entitlement-Subjekt: Profil **und** optional Tenant | Mitai, Shinkan, neu | Ein API-Shape `/me/entitlements`; zwei Subjekt-Ebenen |
| **P0** | Kein Client-`profile_id` für AuthZ | alle | Session-only; Tenant via Header + Membership |
| **P1** | KI: ein Executor pro App | Mitai (fertig), Shinkan (Ziel) | `execute_prompt(slug, context_dto)` |
| **P1** | Berechnungs-SSoT-Schicht | Shinkan erweitern | Mindestens ein `*/metrics.py` pro Domäne mit KPIs |
| **P1** | Enforcement produktiv | beide | Phase 4 Enforce in Prod für kritische Features |
| **P2** | Registry-Taxonomie vereinheitlichen | beide | Rechte / Platzhalter / Import / UI-Plugin |
| **P2** | Admin-Nav SSoT | Shinkan | `adminNav.js` wie Mitai |
| **P2** | Import: Universal + Spezialmodule | Shinkan | Wiki als registriertes Modul |
| **P3** | Dashboard: Aggregat vs. Widgets | produktabhängig | Entscheidungsbaum §3.7 |
| **P3** | Shared `auth.py` / `db_init` | beide | Monorepo-Package oder Sync-Disziplin |
---
## 7. Konvergenz-Roadmap (langfristig)
```mermaid
flowchart LR
subgraph foundation [Familien-Foundation]
M9[Migration]
M5[Auth]
F3[Entitlements 2-Ebenen]
R4[Registry Meta]
end
subgraph mitai [Mitai]
DL[Data Layer]
PE[Prompt Engine]
DW[Dashboard Widgets]
end
subgraph shinkan [Shinkan]
AL[Access Layer]
AR[AI Runtime → Executor]
SS[Skill Scoring → Layer 1]
end
M9 --> mitai
M9 --> shinkan
M5 --> mitai
M5 --> shinkan
F3 --> mitai
F3 --> shinkan
R4 --> mitai
R4 --> shinkan
AL -.->|Mandanten-Apps| foundation
PE -.->|Konvergenz| AR
DL -.->|Schichtenmodell| SS
```
| Phase | Mitai | Shinkan |
|-------|-------|---------|
| **Kurz** | Legacy KI-Pfade entfernen; Enforcement-Doku vereinheitlichen | Access-Layer-Audit abschließen; `CAPABILITY_ENFORCE` |
| **Mittel** | Org-Scope in Entitlements vorbereiten | `ai_prompt_runtime` → Unified Executor; Router-Helfer statt KPI-Duplikat |
| **Lang** | SSO/Identity (Vision) | Data-Layer-ähnliche Module für Planung; optional Widget-Dashboard |
---
## 8. Nächste Schritte
1. **Review-Workshop:** Tabelle §6 P0–P1 durchgehen und Familien-Regeln verbindlich markieren.
2. ~~**`FAMILY_ENTITLEMENT_MODEL.md`** anlegen (P0)~~ → [FAMILY_ENTITLEMENT_MODEL.md](./FAMILY_ENTITLEMENT_MODEL.md) (Entwurf 2026-07-04)
3. **Shinkan-Index** und **Mitai-Foundation-README** auf dieses Dokument verlinken.
4. **`FAMILY_ENTITLEMENT_MODEL.md`** — Entwurf angelegt (§6 Produkt-Abweichungen, §8 Regeln neue Apps).
5. Pro **P1-Punkt** Issue/Remediation-Eintrag in jeweiliger `SCHULDEN_UND_REMEDIATION` / Mitai-Äquivalent.
---
## 9. Changelog
| Datum | Änderung |
|-------|----------|
| 2026-07-04 | Erstfassung Abgleich Mitai Foundation (9) ↔ Shinkan (15) |
@@ -0,0 +1,316 @@
# Familien-Modell: Entitlements & Limits
**Status:** Entwurf / verbindliche Zielrichtung (mit bewussten Produkt-Ausnahmen)
**Stand:** 2026-07-04
**Bezüge:**
- [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) — Abgleich Mitai ↔ Shinkan
- Mitai: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
- Shinkan: [CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md)
---
## 1. Zweck
Dieses Dokument definiert das **gemeinsame Entitlement-Modell** der Jinkendo-Produktfamilie:
- **Was** für neue Apps und Refactors **Standard** ist
- **Welche Produkt-Profile** welche Scopes nutzen (Account, Tenant, beides, keins)
- **Wie** bewusste Abweichungen dokumentiert werden — Abweichung ist erlaubt, **Undokumentiertheit** nicht
**Nicht enthalten:** Stripe/SSO (`auth.jinkendo.de`), vollständige Billing-Implementierung, app-spezifische Feature-IDs.
---
## 2. Leitgedanke: Vier getrennte Fragen
Jede geschützte Aktion durchläuft konzeptionell **vier unabhängige Prüfungen**. Nicht jede App implementiert alle vier — siehe §6.
| # | Frage | Familien-Begriff | Typische Quelle |
|---|--------|------------------|-----------------|
| **A** | Wer ist eingeloggt? | **Auth** (Identität) | Session → `profile_id` |
| **B** | Darf diese Rolle die **Funktion** ausführen? | **Capability** (Permission) | Rollen-Matrix, `min_account_state` |
| **C** | Ist das **Kontingent** erschöpft? | **Feature / Limit** (Quota) | Plan, Tier, Usage-Zähler |
| **D** | Darf ich **dieses Objekt** lesen/ändern? | **Governance** (Object ACL) | `visibility`, `club_id`, Owner |
```
Request → Auth (A) → [Capability (B)] → [Feature-Limit (C)] → [Governance (D)] → Handler
```
**Familien-Regel:** B, C und D **nicht** in React-Widgets oder Router-Inline-Logik vermischen — jeweils eine Auflösungsfunktion pro Ebene.
**Shinkan-Ergänzung:** Governance ist dort ausgebaut (`TenantContext`, Access Layer); Mitai fokussiert A+B+C auf Profil-Ebene.
---
## 3. Familien-Standard: Zwei Subjekt-Ebenen
Limits und Pläne können an **zwei Subjekte** hängen. Beide sind im Familienmodell **first-class** — Apps wählen, welche sie nutzen (§6).
| Subjekt | ID | Typische Frage | Beispiel |
|---------|-----|----------------|----------|
| **Account** | `profile_id` | Was darf **ich** als Nutzer (Tarif)? | Mitai Free vs. Premium |
| **Tenant** | `tenant_id` (z. B. `club_id`) | Was darf **meine Organisation**? | Shinkan Vereinsplan, KI-Kontingent |
### 3.1 Auflösungs-Reihenfolge (wenn beide Ebenen aktiv)
Für eine Aktion mit Capability `X` und Feature `Y`:
1. **Account-Lifecycle** — z. B. E-Mail verifiziert, Onboarding abgeschlossen
2. **Capability(B)** — Rolle darf Funktion (Account- und/oder Tenant-Rollen)
3. **Feature(C)** — Kontingent am **primären Billing-Subjekt** der App (siehe Produkt-Profil)
4. **Governance(D)** — Objekt sichtbar/bearbeitbar
**AND-Verknüpfung:** Alle aktiven Ebenen müssen passieren. Ausnahmen nur in §6.3 dokumentiert.
### 3.2 Primäres Billing-Subjekt pro App
| Profil | Primäres Subjekt für Limits | Capability-Subjekt |
|--------|----------------------------|-------------------|
| Personal App (Mitai) | **Account** | Account |
| Mandanten-App (Shinkan) | **Tenant** | Account + Tenant-Rolle |
| Hybrid (Zukunft) | konfigurierbar | beide |
---
## 4. Familien-Standard: Capabilities vs. Features
| Konzept | Familien-Definition | Subjekt | Beispiel |
|---------|---------------------|---------|----------|
| **Capability** | Binäre oder rollenbasierte **Erlaubnis** („darf ich?“) | meist Account + Tenant-Kontext | `exercises.ai.suggest` |
| **Feature** | **Kontingent** oder Boolean-Limit („wie oft/noch?“) | Account **oder** Tenant | `ai_calls` / Monat |
| **Verknüpfung** | Capability kann `linked_feature_id` haben | — | KI-Capability → KI-Kontingent |
**Familien-Regel:**
- Capabilities **registry-first** registrieren (Code → DB-Sync, Shinkan-Muster).
- Feature-IDs **nicht** in UI hardcoden — nur aus Entitlements-Response.
- `NULL` Limit = unbegrenzt; `0` = deaktiviert (Mitai-Semantik, familienweit).
---
## 5. Familien-Standard: API & Enforcement
### 5.1 Ziel-API (neue Apps)
Ein **einheitlicher Snapshot** für das Frontend:
```
GET /api/me/entitlements
?tenant_id=<optional>
Response (skizziert):
{
"account": {
"profile_id": 1,
"account_state": "active_member",
"tier_id": "premium", // optional, Account-Apps
"features": { "ai_calls": { "allowed", "used", "limit", "remaining", "reset_at" } },
"capabilities": { "analysis.run": { "allowed": true, "reason": null } }
},
"tenant": { // null wenn App keinen Tenant kennt
"tenant_id": 42,
"tenant_type": "club",
"plan_id": "pro",
"features": { ... },
"capabilities": { ... },
"roles": ["trainer"]
},
"enforcement": {
"capabilities": "enforce|probe",
"features": "enforce|probe"
}
}
```
**Familien-Regel:** UI liest **nur** diesen Snapshot (oder domänenspezifische Teilmenge) — keine parallelen `/subscription/me` + `/features/usage` + Ad-hoc-Checks in neuen Apps.
### 5.2 Ist-API (bestehende Apps — Abweichung dokumentiert)
| App | Endpoint heute | Familien-Ziel |
|-----|----------------|---------------|
| **Mitai** | `/subscription/me`, `/features/usage`, `check_feature_access` | Snapshot schrittweise; Account-Block reicht |
| **Shinkan** | `GET /api/me/entitlements?club_id=` | Tenant-Block + Capabilities; Account-Tier fehlt bewusst |
Migration: **kein Big-Bang** — alte Endpoints als Facade auf Snapshot mappen.
### 5.3 Vier-Phasen-Rollout (familienweit verbindlich)
| Phase | Verhalten | Env-Beispiel |
|-------|-----------|--------------|
| **1** | Cleanup Legacy-Flags | — |
| **2** | **Probe** — JSON-Log, HTTP 200 | `*_ENFORCE=0` |
| **3** | Frontend-Gates aus Entitlements | — |
| **4** | **Enforce** — HTTP 403 | `*_ENFORCE=1` |
**Familien-Regel:** Phase 4 für **neue** kritische Features von Anfang an planbar; Bestands-Apps dürfen in Phase 2–3 bleiben bis kalibriert.
### 5.4 Enforcement-Priorität
1. **API** — autoritativ (`403`)
2. **Frontend** — UX (Badges, disabled Buttons)
3. **Niemals** — nur UI ohne API-Gate
---
## 6. Produkt-Profile & bewusste Abweichungen
Abweichungen vom Familien-Standard sind **zulässig**, wenn sie in der Tabelle **§6.2** stehen und begründet sind.
### 6.1 Profil-Matrix (Soll)
| Profil | Apps | Account-Limits | Tenant-Limits | Capabilities | Governance (Objekt) |
|--------|------|----------------|---------------|--------------|---------------------|
| **P1 Personal** | Mitai | ✅ primär | ❌ | ✅ Account | minimal / privat |
| **P2 Mandant** | Shinkan | ⚠️ Lifecycle only | ✅ primär | ✅ Account + Tenant-Rollen | ✅ Access Layer |
| **P3 Minimal** | Miken, Ikigai (geplant) | optional | ❌ | optional | minimal |
| **P4 Hybrid** | (Reserve) | ✅ | ✅ | ✅ beide | ✅ |
### 6.2 Registrierter Abweichungs-Katalog
| ID | App | Abweichung vom Familien-Standard | Begründung | Review |
|----|-----|----------------------------------|------------|--------|
| **DEV-01** | Mitai | Kein `tenant`-Block in Entitlements | Persönliche Tracking-App; kein Verein | Beibehalten (P1) |
| **DEV-02** | Mitai | Kein Capability-Katalog (nur Features+Tier) | RBAC = admin/user ausreichend | Optional später `account.*` Capabilities |
| **DEV-03** | Mitai | Mehrere Nutzer-APIs statt einem Snapshot | Historisch gewachsen | Facade → Snapshot (mittelfristig) |
| **DEV-04** | Mitai | Legacy Session-Spalten (`ai_enabled`, …) parallel Features | Migrationsschuld | Bereinigen, nicht in neue Apps |
| **DEV-05** | Shinkan | Kein Account-Tier / `profiles.tier` | Verein zahlt, nicht Trainer | Beibehalten (P2) |
| **DEV-06** | Shinkan | Capabilities **und** Governance (zwei Achsen) | Trainer vs. Objekt-Rechte | Familien-Vorbild für P2/P4 |
| **DEV-07** | Shinkan | `check_feature_access` (Mitai-Legacy) explizit verboten | Falsches Subjekt | Beibehalten |
| **DEV-08** | Shinkan | Enforcement oft Probe-only | Rollout-Sicherheit | → Phase 4 bis Datum X |
| **DEV-09** | Shinkan | Inventar-Features live gezählt | Drift-Vermeidung | Abweichung OK; in P2 dokumentieren |
| **DEV-10** | Beide | Kein atomares Check+Increment | Race bei Parallel-Requests | Familien-Backlog; Workaround dokumentieren |
| **DEV-11** | Neue Apps | dürfen **nur** Account **oder** nur Tenant wählen | MVP | Eintrag hier anlegen vor Launch |
**Neue Abweichung:** Zeile in §6.2 + ggf. ein Satz im App-`CLAUDE.md`.
### 6.3 Dokumentierte Ausnahmen (Bypass)
| Ausnahme | Apps | Regel |
|----------|------|-------|
| Plattform-Admin Audit | Shinkan | Quota-Bypass über Grants, nicht pauschal superadmin |
| Admin ohne Auto-Bypass | Mitai | Admins unterliegen Limits (Produktentscheid) |
| Öffentliche Routen ohne Auth | alle | Kein Entitlement-Check |
---
## 7. Mapping: Familien-Begriff ↔ Implementierung
### 7.1 Mitai (Profil P1)
| Familien | Mitai-Implementierung |
|----------|----------------------|
| Account-Features | `features`, `tier_limits`, `user_feature_usage` |
| Account-Tier | `get_effective_tier()`, `access_grants` |
| Check | `check_feature_access(profile_id, feature_id)` |
| Increment | `increment_feature_usage(profile_id, …)` |
| UI | `UsageBadge`, Widget `allowed` |
### 7.2 Shinkan (Profil P2)
| Familien | Shinkan-Implementierung |
|----------|-------------------------|
| Tenant-Features | `club_plan_limits`, `club_feature_usage`, `club_features.py` |
| Tenant-Plan | `get_effective_club_plan(club_id)` |
| Capabilities | `check_capability`, `capabilities` + `rights_registry` |
| Snapshot | `build_me_entitlements()` → `GET /me/entitlements` |
| Governance | `TenantContext`, `club_tenancy` — **kein** Ersatz für Capabilities |
### 7.3 Gemeinsame Muster (copy-ready)
| Muster | Mitai | Shinkan |
|--------|-------|---------|
| Feature-Registry in DB | ✅ | ✅ (`app='shinkan'`) |
| Plan × Feature Matrix | `tier_limits` | `club_plan_limits` |
| Admin-Override | `user_feature_restrictions` | `club_feature_overrides` |
| Promo/Trial | `access_grants` | `club_access_grants` |
| 4-Phasen-Rollout | ✅ | ✅ |
| Registry-first neue IDs | ⚠️ teils hardcoded | ✅ `rights_registrations/` |
---
## 8. Entscheidungsregeln für neue Produkte
### 8.1 Pflicht (alle Apps mit Auth)
- [ ] Session → `profile_id`; kein Client-Header als Autorität
- [ ] Entitlements-Auflösung **eine Funktion pro Ebene** (Capability, Feature)
- [ ] API-Enforcement vor UI-Gate
- [ ] 4-Phasen-Rollout dokumentiert
- [ ] Produkt-Profil (P1–P4) gewählt + Abweichungen in §6.2
### 8.2 Wenn Personal App (P1)
- [ ] Primäres Subjekt = Account
- [ ] `tenant`-Block in API = `null` (DEV-01-Analog)
- [ ] Feature-Registry + Tier-Matrix
### 8.3 Wenn Mandanten-App (P2)
- [ ] Primäres Subjekt = Tenant
- [ ] `TenantContext` + Governance getrennt von Capabilities
- [ ] Capabilities registry-first
- [ ] Account nur Lifecycle (verified, member) — kein Tier nötig (DEV-05-Analog erlaubt)
### 8.4 Wenn Minimal App (P3)
- [ ] Explizit: „keine Limits“ oder nur Boolean-Features — in §6.2 eintragen
- [ ] Kein halbes Mitai-v9c kopieren
---
## 9. Konvergenz-Roadmap (optional, nicht blockierend)
| Schritt | Mitai | Shinkan | Familie |
|---------|-------|---------|---------|
| **Kurz** | Legacy Session-Flags entfernen | `CAPABILITY_ENFORCE` / `CLUB_FEATURE_ENFORCE` Prod | DEV-04, DEV-08 schließen |
| **Mittel** | `/me/entitlements` Account-Block | Snapshot um `tenant`-Typ metadata erweitern | Facade alte APIs |
| **Lang** | Optional `tenant_id` reservieren (null) | Optional Account-Tier für Cross-Sell | Shared package `jinkendo_entitlements` |
| **Vision** | SSO + zentraler Billing | Vereins-Abo Stripe | `CENTRAL_SUBSCRIPTION_SYSTEM` |
**Wichtig:** Konvergenz ist **empfohlen**, nicht Pflicht — solange §6.2 aktuell bleibt.
---
## 10. Anti-Patterns (familienweit verboten)
1. Tier- oder Plan-Namen in React-Komponenten hardcoden
2. Limit-Logik nur im Frontend
3. Shinkan-Vereinslimits über Mitai `check_feature_access(profile_id)`
4. Capability-Check durch Governance ersetzen (oder umgekehrt)
5. Neue Feature-IDs nur in SQL-Migration ohne Registry
6. Enforcement Phase 4 „vergessen“ bei paid Features ohne dokumentierte Probe-Phase
7. Undokumentierte Produkt-Abweichung (nicht in §6.2)
---
## 11. Offene Familien-Entscheidungen (Backlog)
| ID | Frage | Optionen | Default wenn unentschieden |
|----|-------|----------|----------------------------|
| **FD-01** | Atomares check+increment | DB-Lock / Transaction / Queue | Status quo + Retry-Hinweis in Doku |
| **FD-02** | Shared Python-Modul | Monorepo-Paket vs. Copy+Sync | Copy+Sync mit gleicher API-Shape |
| **FD-03** | Capability-Namespace global | `jinkendo.*` vs. app-prefix | `{app}.{domain}.{action}` |
| **FD-04** | Mitai bekommt Capability-Layer? | ja/nein/später | nein (DEV-02) bis Bedarf |
| **FD-05** | Ein `features.app` für alle Apps | gemeinsame DB vs. pro Deploy | pro Deploy (heute) |
---
## 12. Verwandte Dokumente
| Dokument | Inhalt |
|----------|--------|
| [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) | Vollständiger Mitai ↔ Shinkan Abgleich |
| [design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md) | Shinkan Ist-Prinzipien |
| [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./design-principles/ACCESS_LAYER_DESIGN_PRINCIPLES.md) | Governance (Ebene D) |
| Mitai Foundation #3 | Feature & Entitlement Ist Mitai |
| Shinkan `CLUB_MEMBERSHIP_AND_FEATURES.v1.md` | Vereins-Abo Detail |
| Shinkan `CAPABILITY_CATALOG.v1.md` | Capability-IDs |
---
## 13. Changelog
| Datum | Änderung |
|-------|----------|
| 2026-07-04 | Entwurf: Familien-Standard, Produkt-Profile P1–P4, Abweichungs-Katalog DEV-01–11 |
+48
View File
@@ -0,0 +1,48 @@
# Jinkendo Produktfamilie – Dokumentation
**Zweck:** Querschnitts-Dokumentation, die **über einzelne Apps hinaus** gilt (Mitai, Shinkan, künftige Schwester-Produkte).
**Stand:** 2026-07-04
---
## Inhalt
| Verzeichnis | Zweck |
|-------------|--------|
| [design-principles/](./design-principles/) | Extrahierte **Designprinzipien** pro Modul — Foundation für neue Apps und Familien-Review |
---
## Designprinzipien
**Einstieg Shinkan:** [design-principles/DESIGN_PRINCIPLES_INDEX.md](./design-principles/DESIGN_PRINCIPLES_INDEX.md)
**Einstieg Mitai (Foundation):** [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md)
**Abgleich & Entscheidungen:** [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) — Widersprüche, Abweichungen, Familien-Entscheidungs-Matrix
Die Serie dokumentiert:
- **Mitai** (9 Module) — Referenzimplementierung unter `mitai-jinkendo/.claude/docs/jinkendo-foundation/`
- **Shinkan** (15 Module) — in [design-principles/](./design-principles/)
Geplanter nächster Schritt: **FD-***-Entscheidungen im [FAMILY_ENTITLEMENT_MODEL.md](./FAMILY_ENTITLEMENT_MODEL.md) durcharbeiten; Enforcement Phase 4 wo vorgesehen.
| Dokument | Inhalt |
|----------|--------|
| [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) | Mitai ↔ Shinkan Abgleich |
| [FAMILY_ENTITLEMENT_MODEL.md](./FAMILY_ENTITLEMENT_MODEL.md) | **Familien-Standard** Entitlements + Produkt-Abweichungen |
---
## Bezug zu App-spezifischer Doku
| Ebene | Ort (Beispiel Shinkan) |
|-------|-------------------------|
| **Familie** (Prinzipien) | `docs/jinkendo-family/` |
| **App-Architektur** | `docs/architecture/` |
| **Technische Specs** | `.claude/docs/technical/` |
| **Agent-Regeln** | `.claude/rules/`, `CLAUDE.md` |
Implementierungsdetails und Domänen-Specs bleiben in den jeweiligen App-Repositories; Designprinzipien beschreiben **übertragbare Muster** und **bewusste Lücken**.
@@ -0,0 +1,170 @@
# Access Layer & Tenant – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Access Layer & Tenant Governance“ — keine Shinkan-Gesamtarchitektur, keine Kampfsport-Domänenlogik
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 1 von 15
**Mitai-Vergleich:** kein direktes Gegenstück (Mitai ist profil-zentriert, kein Vereins-Mandant)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| TenantContext | `backend/tenant_context.py` |
| Governance-Helfer | `backend/club_tenancy.py` |
| Listenfilter SQL | `library_content_visibility_sql()` in `tenant_context.py` |
| Endpoint-Audit | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
| Cursor-Regel | `.cursor/rules/access-layer.mdc` |
| Heuristik-Check | `backend/scripts/check_access_layer_hints.py` |
| Normative Spec | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
---
## Modul
**Access Layer & Tenant Governance**
Zentraler Querschnitt für Mandanten-Kontext (`club_id`), Sichtbarkeit (`private`/`club`/`official`) und einheitliche Les-/Schreibregeln für Bibliotheksartefakte (Übungen, Medien, Rahmenprogramme, Vorlagen, Progressionsgraphen).
---
## Fachliche Verantwortung
1. **TenantContext pro HTTP-Request** — Auflösung aus Session + Header `X-Active-Club-Id` + Profilfeld `active_club_id`.
2. **Datenisolierung** — `club_id` als Grenze für vereinsgeteilte Inhalte; Cross-Verein ausgeschlossen.
3. **Einheitliche Sichtbarkeits-Semantik** — gleiche Enums und Prüflogik über alle Bibliotheksmodule.
4. **Governance-Transitionen** — Regeln beim Wechsel `private` → `club` → `official` und beim Löschen.
5. **Listenfilter** — SQL-Baustein statt „SELECT *“ in jedem Router.
### Administrierte Konfigurationen
| Konfiguration | Speicherort | Inhalt |
|---------------|-------------|--------|
| Aktiver Verein | `profiles.active_club_id` | Persistierter UI-Kontext |
| Request-Override | Header `X-Active-Club-Id` | Client-seitiger Mandantenwechsel |
| Sichtbarkeit | Spalte `visibility` je Objekt | `private`, `club`, `official` |
| Vereinszuordnung | Spalte `club_id` | Pflicht bei `club`-Inhalten |
### Bewusst nicht hardcodiert
- Welche Objekte welchen Verein haben (Daten)
- Individuelle Freigabeentscheidungen (Workflow)
### Hardcodiert (Code)
- Enum-Werte und Leseregeln in `club_tenancy.py` / `library_content_visibility_sql`
- Plattform-Admin-Ausnahmen (`is_platform_admin`, `is_superadmin`)
- Rollencodes für Schreib-/Löschregeln (`club_admin`, `trainer`, …)
---
## Designprinzipien
### 1. Ein Mandant pro Request (`TenantContext`)
| | |
|---|---|
| **Prinzip** | `Depends(get_tenant_context)` liefert `profile_id`, `global_role`, `effective_club_id`, Mitgliedschaften — einmal pro Request. |
| **Begründung** | Kein verteiltes „Rates“ aus Headers; konsistente Filter in allen Routern. |
| **Quelle** | `tenant_context.py`; `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` §2 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Nicht alle Endpoints migriert; Audit-Tabelle zeigt Restbestand mit nur `require_auth`. |
### 2. `club_id` als Datenisolierungsgrenze
| | |
|---|---|
| **Prinzip** | Vereinsgeteilte Inhalte sind nur für aktive Mitglieder des Objekt-`club_id` lesbar — nie Cross-Verein. |
| **Begründung** | Mandantenfähigkeit für Vereinsplattform; Compliance bei geteilten Trainingsinhalten. |
| **Quelle** | `library_content_visibility_sql()`; Tests `test_access_layer*.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | `division`-Verschärfung noch nicht durchgängig; reserviert im Plan. |
### 3. Einheitliche Visibility-Semantik
| | |
|---|---|
| **Prinzip** | `private` \| `club` \| `official` mit gleicher Bedeutung für Übungen, Medien, Rahmen, Module, Graphen. |
| **Begründung** | Nutzer und Trainer verstehen ein Freigabemodell; UI-Feld „Freigabelevel“ durchgängig. |
| **Quelle** | `club_tenancy.py`; `FACHLICHE_NUTZERFUNKTIONEN.md` §4.7 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | `community`-Stufe nur dokumentiert, nicht implementiert. |
### 4. Zentraler SQL-Filter für Bibliothekslisten
| | |
|---|---|
| **Prinzip** | Listen nutzen `library_content_visibility_sql(alias, profile_id, role, effective_club_id)` — nicht handgeschriebene WHERE-Kopien. |
| **Begründung** | Drift-Vermeidung; ein Fix gilt für alle Kataloge. |
| **Quelle** | `tenant_context.py`; Router `exercises.py`, `training_framework_programs.py`, … |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Einzelne Legacy-Queries können noch abweichen. |
### 5. Governance-Transitionen explizit prüfen
| | |
|---|---|
| **Prinzip** | Wechsel von `visibility`/`club_id` über `assert_library_content_governance_transition` + `assert_valid_governance_visibility`. |
| **Begründung** | „Privat → Verein teilen“ und „official herabstufen“ sind sicherheitsrelevante Aktionen. |
| **Quelle** | `club_tenancy.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Nicht jedes Modul ruft Transition-Helper bei PATCH auf. |
### 6. Löschregeln nach Visibility-Stufe
| | |
|---|---|
| **Prinzip** | `assert_library_content_deletable`: privat → Ersteller/Vereinsadmin-Kontext; club → Vereinsadmin; official → Plattform-Admin. |
| **Begründung** | Schutz vor versehentlichem Löschen fremder oder offizieller Inhalte. |
| **Quelle** | `club_tenancy.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Medien-Lifecycle hat zusätzliche Stufen (Papierkorb) — Schnittmenge beachten. |
### 7. Aktiver Verein: Header + Profil synchron
| | |
|---|---|
| **Prinzip** | Frontend sendet `X-Active-Club-Id`; Backend validiert gegen Mitgliedschaft; Profil speichert `active_club_id`. |
| **Begründung** | Einheitlicher Mandanten-Kontext über API und UI. |
| **Quelle** | `frontend/src/api/client.js` (`mergeActiveClubHeader`); `profiles` Router |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Onboarding-Nutzer ohne Verein: eingeschränkter Nav-Modus. |
### 8. Plattform-Admin als Audit-Pfad, nicht als Bypass
| | |
|---|---|
| **Prinzip** | Plattform-Admins sehen fremde `club`-Inhalte nur mit expliziter Regel (Mitgliedschaft oder Audit-Ausnahme in SQL). |
| **Begründung** | Superuser-Zugriff ohne Mandanten-Leak in normalen Trainer-Flows. |
| **Quelle** | `library_content_visibility_sql` — `club_ok_plat`-Zweig |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Feinheiten zwischen `admin` und `superadmin` (z. B. `official`, Legal Hold) separat geregelt. |
### 9. Endpoint-Audit als lebendes Inventar
| | |
|---|---|
| **Prinzip** | Jeder sicherheitsrelevante Endpoint-Eintrag in `ACCESS_LAYER_ENDPOINT_AUDIT.md`; PR-Checkliste verlangt Update. |
| **Begründung** | Sichtbarkeit des Migrationsstands; kein stilles Ausweichen auf `require_auth` allein. |
| **Quelle** | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`; `check_access_layer_hints.py` |
| **Tragfähigkeit** | **hoch** (prozessual) |
| **Einschränkung** | CI-Strict-Modus optional, nicht überall aktiv. |
---
## Nicht übernehmen
1. **Endpoints nur mit `require_auth`** bei tenant-sensitiven Daten — führt zu IDOR und fehlenden Listenfiltern.
2. **Visibility-Logik pro Router duplizieren** — historische Drift zwischen Übungen und Planung.
3. **`division` vor stabiler Vereins-Isolation** — Reihenfolge im Plan: erst Stufe C, dann D.
4. **Community-Freigabe ohne additive Felder** — würde `club`-Isolation brechen.
5. **Client-seitige Mandantenfilter ohne Server-Enforcement** — UI-Hiding reicht nicht.
---
## Verwandte Dokumentation
- [ACCESS_LAYER_AND_GOVERNANCE_PLAN.md](../../../.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md)
- [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../../../.claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,140 @@
# AI Prompt Runtime – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „AI Prompt Runtime“ — Shinkan-KI-Schicht, keine Planungs-Gesamtarchitektur
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 5 von 15
**Mitai-Vergleich:** [PROMPT_ENGINE_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/PROMPT_ENGINE_DESIGN_PRINCIPLES.md) (#1)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Laufzeit | `backend/ai_prompt_runtime.py`, `backend/prompt_resolver.py` |
| Domänen-Orchestrierung | `backend/exercise_ai.py`, `backend/planning_exercise_*.py` |
| OpenRouter | `backend/openrouter_chat.py` |
| Admin | `backend/routers/ai_prompts_admin.py` |
| Zielbild | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
| Job-Kontext | `backend/ai_prompt_job.py`, `backend/ai_prompt_context.py` |
---
## Modul
**AI Prompt Runtime**
Schmale Ausführungsschicht für admin-konfigurierbare Prompts in `ai_prompts`: Laden, Mustache-Rendering, Kontext-Arten, OpenRouter-Aufruf. **Kein** vollständiges Unified Prompt System wie Mitai (keine Workflows/Pipelines in Produktion).
---
## Fachliche Verantwortung
1. **Prompt-Laden aus DB** — `load_ai_prompt_row`, `load_and_render_ai_prompt`
2. **Platzhalter-Ersetzung** — Mustache `{{key}}` via `prompt_resolver.py`
3. **Kontext-Arten** — `AiPromptContextKind` trennt Übungs-KI vs. Planungs-KI
4. **Domänen-Builder** — `exercise_ai`, Planungs-Pipelines bauen Variablen-Maps
5. **Admin CRUD + Preview** — ohne LLM in Preview-Pfaden wo vorgesehen
---
## Designprinzipien
### 1. Eine Laufzeit-Fassade für DB-Prompts
| | |
|---|---|
| **Prinzip** | Produktive Aufrufe laden Slugs über `ai_prompt_runtime` — nicht Roh-SQL auf `ai_prompts` in Routern. |
| **Begründung** | Einheitliches inactive-Handling, Modell-Feld, Render-Metadaten. |
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.1; `ai_prompt_runtime.py` |
| **Tragfähigkeit** | **hoch** (Zielrichtung) |
| **Einschränkung** | Planungs-KI hat noch verteilte Orchestratoren; kein einzelner `execute_prompt` wie Mitai. |
### 2. Konfigurierbare Bibliothek in `ai_prompts`
| | |
|---|---|
| **Prinzip** | Template-Texte in DB; Admins ändern ohne Deploy (`ai_prompts_admin`). |
| **Begründung** | Gleiches Familien-Muster wie Mitai Prompt-Bibliothek. |
| **Quelle** | Migration 069+; Admin-UI |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Keine Pipeline/Workflow-Typen; Slugs hardcoded in `context_kind_for_slug`. |
### 3. Kontext-Namespaces statt globaler Platzhalter-Soup
| | |
|---|---|
| **Prinzip** | `AiPromptContextKind` (z. B. `exercise_form_ai`, `planning_exercise_search`) begrenzt erlaubte Builder. |
| **Begründung** | Planungs-Kontext wächst ohne Kollision mit Übungs-Keys. |
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.3 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Noch keine zentrale Platzhalter-Registry wie Mitai — Mustache ad hoc pro Builder. |
### 4. Trennung Template vs. Domänen-Kontext
| | |
|---|---|
| **Prinzip** | UI/Router liefern Pydantic-DTOs → Builder erzeugen `variables`-Map → `render_mustache_template`. |
| **Begründung** | Prompt-Autoren ändern Text, nicht Python in Routern. |
| **Quelle** | `prompt_resolver.py`; `ExerciseFormAiPromptContext` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Große Planungs-Kontexte noch nicht vollständig über DTOs. |
### 5. Transport (OpenRouter) getrennt von Semantik
| | |
|---|---|
| **Prinzip** | `openrouter_chat.py` für HTTP; Validierung/JSON-Parsing in Domänen-Schicht. |
| **Begründung** | Modellwechsel ohne Router-Anpassung. |
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §2.2 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Modell teils global Env, teils Spalte `openrouter_model` — Konvergenz offen. |
### 6. Reset-to-default für System-Prompts
| | |
|---|---|
| **Prinzip** | `default_template` + Admin-Reset — kein vollständiges Versionsmodell. |
| **Begründung** | Familien-Muster aus Mitai; Schutz vor Fehlkonfiguration. |
| **Quelle** | Migration 069 |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Keine Historie benutzerdefinierter Änderungen. |
### 7. Admin-only Schreiben, authentifiziertes Ausführen
| | |
|---|---|
| **Prinzip** | Prompt-CRUD nur Admin; Ausführung mit Capability + Feature-Kontingent. |
| **Begründung** | Systemkonfiguration vs. Nutzung; Kostenkontrolle. |
| **Quelle** | `ai_prompts_admin.py`; `exercises.ai.suggest` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Enforcement teils noch Probe-Phase. |
### 8. Skill-Retrieval orthogonal zu Prompts
| | |
|---|---|
| **Prinzip** | `ai_skill_retrieval_profiles` steuert Katalog für `{{skills_catalog}}` — unabhängig vom Prompt-Text. |
| **Begründung** | Anweisung vs. Kontextfenster trennbar konfigurierbar. |
| **Quelle** | `AI_PROMPT_TARGET_ARCHITECTURE.md` §3.3 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
---
## Nicht übernehmen (Shinkan-Ist / Mitai-Vermeidung)
1. **Direkte OpenRouter-Calls in Routern** ohne Laufzeit-Schicht — historische Schuld, abbauen.
2. **Hardcodierte Prompt-Strings in Produktion** — nur Fallback/Dev.
3. **Mitai-Workflow-Graph vorreifen** — Shinkan braucht erst Planungs-Kontext-Reife.
4. **Globale Platzhalter-Map ohne Namespace** — Mitai-Lektion `PLACEHOLDER_MAP`-Duplikat.
5. **Fehlende JSON-Schema-Validierung** bei `output_format=json` — Mitai-TODO übernehmen vermeiden.
---
## Verwandte Dokumentation
- [AI_PROMPT_TARGET_ARCHITECTURE.md](../../../.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md)
- [AI_PROMPT_SYSTEM_SPEC.md](../../../.claude/docs/technical/AI_PROMPT_SYSTEM_SPEC.md)
- [PLANNING_PROGRESSION_GRAPH_KI.md](../../architecture/PLANNING_PROGRESSION_GRAPH_KI.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,114 @@
# Auth & Session – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Auth & Session“ — gemeinsame Mitai-Basis in Shinkan
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 4 von 15
**Mitai-Vergleich:** [AUTH_SESSION_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/AUTH_SESSION_DESIGN_PRINCIPLES.md) (#5)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Auth-Kern | `backend/auth.py` |
| Router | `backend/routers/auth.py`, `profiles.py` |
| Frontend | `frontend/src/context/AuthContext.jsx`, `frontend/src/api/client.js` |
| Account-Lifecycle | `backend/account_lifecycle.py` |
---
## Modul
**Auth & Session**
Token-basierte Server-Sessions (`sessions`-Tabelle), bcrypt-Passwörter, FastAPI-Dependencies `require_auth` / `require_admin`. Geteilter Code mit Mitai (App-Familie).
---
## Fachliche Verantwortung
1. **Login/Logout/Session-Lebensdauer**
2. **Passwort-Hashing** (bcrypt, Legacy-SHA256-Upgrade)
3. **Auth-Dependencies** für Router
4. **Account-States** (Verifizierung, Onboarding-Gates)
---
## Designprinzipien
### 1. Server-Side Sessions mit Token
| | |
|---|---|
| **Prinzip** | `X-Auth-Token` Header → Lookup in `sessions` mit Ablaufzeit. |
| **Begründung** | Widerrufbar; kein JWT-Drift zwischen Apps. |
| **Quelle** | `auth.py` `get_session`, `require_auth` |
| **Tragfähigkeit** | **hoch** (Familien-Standard) |
| **Einschränkung** | Kein Refresh-Token-Rotation-Modell. |
### 2. `require_auth` als separater Depends-Parameter
| | |
|---|---|
| **Prinzip** | `session: dict = Depends(require_auth)` — nie in Header-Default eingebettet. |
| **Begründung** | Bekannter FastAPI-Footgun führt zu ungeschützten Endpoints. |
| **Quelle** | `CLAUDE.md` Kritische Regeln |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Code-Review/Lint erzwingt das nicht automatisch. |
### 3. Profile-ID immer aus Session
| | |
|---|---|
| **Prinzip** | `profile_id` aus `session['profile_id']`, nie aus Client-Header als Autorität. |
| **Begründung** | IDOR-Vermeidung. |
| **Quelle** | Architektur-Regeln; Shinkan ergänzt `TenantContext.profile_id` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Mitai-Dokument nennt Profile-Header-Schwäche — in Shinkan prüfen ob analog. |
### 4. bcrypt für alle Passwort-Operationen
| | |
|---|---|
| **Prinzip** | `hash_pin` / `verify_pin` mit bcrypt; SHA256 nur Legacy-Verify + Upgrade. |
| **Begründung** | Familien-konsistente Kryptografie. |
| **Quelle** | `auth.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 5. Portal-Rollen vs. Vereinsrollen trennen
| | |
|---|---|
| **Prinzip** | `profiles.role` (admin/superadmin/user) ≠ `club_member_roles` im Verein. |
| **Begründung** | Shinkan-Mandantenmodell; Plattform-Admin ≠ Vereins-Trainer. |
| **Quelle** | `club_tenancy.py`; `TenantContext.global_role` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | UI muss beide Ebenen korrekt anzeigen. |
### 6. Account-Lifecycle als Capability-Voraussetzung
| | |
|---|---|
| **Prinzip** | `min_account_state` auf Capabilities (z. B. verifiziertes Mitglied). |
| **Begründung** | Gates vor sensiblen Aktionen ohne Sonderchecks in Routern. |
| **Quelle** | `account_lifecycle.py`; `capabilities.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Nicht alle Flows nutzen Lifecycle einheitlich. |
---
## Nicht übernehmen
1. **Auth-Parameter in Header-Defaults vermischen** — dokumentierter Anti-Pattern.
2. **Client-gesteuerte `profile_id`** für Autorisierung.
3. **Shinkan-spezifische Mandantenlogik in `auth.py`** — gehört in `tenant_context.py`.
---
## Verwandte Dokumentation
- [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./ACCESS_LAYER_DESIGN_PRINCIPLES.md)
- Mitai: [AUTH_SESSION_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/AUTH_SESSION_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,125 @@
# Capability & Club Features – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Capabilities & Vereins-Feature-Kontingente“ — nicht Billing/Stripe
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 2 von 15
**Mitai-Vergleich:** [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md) (#3)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Capabilities | `backend/capabilities.py` |
| Vereins-Features | `backend/club_features.py` |
| Entitlements-API | `backend/entitlements.py`, `backend/routers/me_entitlements.py` |
| Quota-Bypass | `backend/club_quota_bypass.py` |
| Spez | `CAPABILITY_CATALOG.v1.md`, `CLUB_MEMBERSHIP_AND_FEATURES.v1.md` |
---
## Modul
**Capability & Club Feature Entitlements**
Zwei Schichten: **Capabilities** (darf Nutzer X im Verein Y?) und **Club Features** (Kontingente/Limits pro Verein, Subjekt `club_id`). Zusammenführung in `GET /api/me/entitlements`.
---
## Fachliche Verantwortung
1. **Capability-Checks** — `check_capability`, `probe_capability`, `require_capability` mit Env `CAPABILITY_ENFORCE`.
2. **Vereins-Kontingente** — `probe_club_feature_access`, `consume_club_feature_with_usage` mit Env `CLUB_FEATURE_ENFORCE`.
3. **Entitlements-Snapshot** — Frontend erhält `capabilities` + `features` + Plan für UI-Gating ohne Tier-Logik in Widgets.
4. **Account-Lifecycle** — `min_account_state` blockiert Capabilities vor Verifizierung.
### Unterschied zu Mitai
| Aspekt | Mitai | Shinkan |
|--------|-------|---------|
| Limit-Subjekt | Profil / Subscription | **Verein** (`club_id`) |
| Rollen | Tier + Features | Vereinsrollen + Portal-Rolle |
| Legacy | `check_feature_access` (001) | Explizit **nicht** für Shinkan-Limits nutzen |
---
## Designprinzipien
### 1. Eine Entitlements-API für das Frontend
| | |
|---|---|
| **Prinzip** | `GET /api/me/entitlements?club_id=` liefert Capabilities-Map + Feature-Kontingente + Plan. |
| **Begründung** | Keine Tier-Logik in React-Komponenten; ein Roundtrip pro Mandantenwechsel. |
| **Quelle** | `entitlements.py`, `me_entitlements.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Nicht alle UI-Stellen nutzen Entitlements konsequent. |
### 2. 4-Phasen-Rollout (Probe → Enforce)
| | |
|---|---|
| **Prinzip** | Phase 2: JSON-Log ohne Block; Phase 3+: `CAPABILITY_ENFORCE=1` / `CLUB_FEATURE_ENFORCE=1` → HTTP 403. |
| **Begründung** | Sicheres Einführen ohne Produktions-Crash; Audit vor Hard-Block. |
| **Quelle** | `capabilities.py`, `club_features.py`; Mitai-Vorbild in Spec |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Env-Flags müssen pro Umgebung bewusst gesetzt werden. |
### 3. Capabilities verknüpft mit Features
| | |
|---|---|
| **Prinzip** | Capability kann `linked_feature_id` haben — Kontingent-Check vor Ausführung. |
| **Begründung** | Recht und Limit bleiben getrennt modelliert aber gemeinsam enforcebar. |
| **Quelle** | `capabilities`-Tabelle; `check_capability` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Nicht jede Capability hat linked Feature. |
### 4. Enforcement an der API, nicht in der UI
| | |
|---|---|
| **Prinzip** | Router rufen `require_capability` / `probe_club_feature_access` — UI blendet nur vor. |
| **Begründung** | API ist Source of Truth; UI-Gating allein ist umgehbar. |
| **Quelle** | `exercise_ai.py`, Planungs-KI-Router |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Teilweise noch Probe-only in Prod. |
### 5. Bestands-Features als Live-Zählung
| | |
|---|---|
| **Prinzip** | Inventar-Features (`exercises`, `training_groups`, …) zählen live in DB, nicht nur `club_feature_usage`. |
| **Begründung** | Keine Drift zwischen tatsächlichem Bestand und Usage-Tabelle. |
| **Quelle** | `_INVENTORY_FEATURES` in `club_features.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Performance bei großen Vereinen — ggf. Cache nötig. |
### 6. Quota-Bypass für Plattform-Rollen
| | |
|---|---|
| **Prinzip** | Konfigurierbare Bypass-Capabilities (`domain=quota_bypass`) für Support/Admin ohne harte Limits. |
| **Begründung** | Betrieb und Demos ohne Plan-Upgrade. |
| **Quelle** | `club_quota_bypass.py`; `entitlements.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Missbrauchsrisiko — nur dokumentierte Grants. |
---
## Nicht übernehmen
1. **Mitai `auth.check_feature_access` für Shinkan-Vereinslimits** — profil-zentriert, falscher Subjekt-Scope.
2. **Tier-Logik in Frontend-Widgets** — gehört in Entitlements-Response.
3. **Enforcement ohne Probe-Phase** — bricht bestehende Vereine ohne Vorwarnung.
4. **Capabilities ohne DB-Sync aus Registry** — siehe Rights-Registry-Dokument.
---
## Verwandte Dokumentation
- [CAPABILITY_CATALOG.v1.md](../../../.claude/docs/technical/CAPABILITY_CATALOG.v1.md)
- [CLUB_MEMBERSHIP_AND_FEATURES.v1.md](../../../.claude/docs/technical/CLUB_MEMBERSHIP_AND_FEATURES.v1.md)
- [RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md](./RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,117 @@
# Content Reports (P-13) – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Content Reports“ — Meldeverfahren, Posteingang, Legal Hold
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 10 von 15
**Mitai-Vergleich:** — (Compliance-spezifisch)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| API | `backend/routers/content_reports.py` |
| Legal Hold | `backend/media_legal_hold.py` |
| Inbox-Integration | `GET /api/me/inbox/content-reports` |
| Frontend | `InboxPage.jsx` |
| Migration | 052, 053 |
---
## Modul
**Content Reports & Compliance (P-13)**
Meldeverfahren für problematische Inhalte (Medien, Übungen), Admin-Posteingang mit Statusworkflow, Priorisierung sensibler Gründe, Anbindung Legal Hold und Medien-Audit.
---
## Designprinzipien
### 1. Eine Tabelle, ein Workflow — keine separate Admin-Queue
| | |
|---|---|
| **Prinzip** | `content_reports` + bestehende Inbox-UI für Änderungsanfragen und Meldungen. |
| **Begründung** | Admin-Arbeit an einem Ort; weniger Navigations-Fragmentierung. |
| **Quelle** | `content_reports.py` Docstring |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Zwei Vorgangstypen in einer UI — klare Typ-Kennzeichnung nötig. |
### 2. Melden optional ohne Auth (eingeschränkt)
| | |
|---|---|
| **Prinzip** | Anonym/offline Meldung für `official`-Medien erlaubt; sonst Auth empfohlen. |
| **Begründung** | DSA-Anforderungen; öffentliche Plattform-Inhalte meldbar. |
| **Quelle** | Router-Berechtigungen |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Missbrauchsschutz (Rate Limit) prüfen. |
### 3. Priorität bei sensiblen Gründen
| | |
|---|---|
| **Prinzip** | `minors`, `illegal_content`, `youth_protection` → HIGH_PRIORITY automatisch. |
| **Begründung** | SLA und Admin-Aufmerksamkeit fachlich korrekt. |
| **Quelle** | `HIGH_PRIORITY_REASONS` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 4. Rollengetrennte Sicht (Plattform vs. Verein)
| | |
|---|---|
| **Prinzip** | Plattform-Admin: alle; Club-Admin: nur Vereinsmedien-Meldungen. |
| **Begründung** | Mandanten-Grenze auch im Compliance-Kontext. |
| **Quelle** | Router-Listenfilter |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 5. Legal Hold nur Superadmin aus Meldung
| | |
|---|---|
| **Prinzip** | Mapping `report_reason` → `legal_hold reason_code`; `set_legal_hold` superadmin-geschützt. |
| **Begründung** | Hochrisiko-Aktion; Anschluss P-11. |
| **Quelle** | `_REASON_TO_HOLD_CODE`; `media_legal_hold.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 6. Audit-Spur bei Medien-Meldungen
| | |
|---|---|
| **Prinzip** | `media_asset_audit_log` Event `content_report_filed` bei media_asset-Bezug. |
| **Begründung** | Lifecycle-Entscheidungen nachvollziehbar. |
| **Quelle** | Migration 053; `write_audit_log_entry` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 7. E-Mail best-effort, kein Hard-Fail
| | |
|---|---|
| **Prinzip** | Bestätigung an Melder + Admin-Benachrichtigung; SMTP-Fehler blockieren Speichern nicht. |
| **Begründung** | Meldung geht nicht verloren wenn Mail down. |
| **Quelle** | Router-Implementierung |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Admins müssen Posteingang auch ohne Mail prüfen. |
---
## Nicht übernehmen
1. **Separate Compliance-Queue-App** — Inbox-Reuse ist bewusst.
2. **Legal Hold durch Club-Admin** — Superadmin-only.
3. **Meldungen ohne Statusworkflow/Archiv** — Wiedereröffnen muss möglich sein.
4. **Fehlende Verknüpfung Medien-Lifecycle** — Hold muss Purge blockieren.
---
## Verwandte Dokumentation
- [MEDIA_ASSETS_DESIGN_PRINCIPLES.md](./MEDIA_ASSETS_DESIGN_PRINCIPLES.md)
- [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./ACCESS_LAYER_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,105 @@
# Dashboard KPIs – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Dashboard KPI Aggregation“ — vereinfacht vs. Mitai Widgets
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 14 von 15
**Mitai-Vergleich:** [DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md) (#7, vereinfacht)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| API | `backend/routers/dashboard.py` — `GET /api/dashboard/kpis` |
| Frontend | Dashboard/Übersicht-Page |
| Refaktor-Kontext | `docs/architecture/SCHULDEN_UND_REMEDIATION.md` A3, B1 |
---
## Modul
**Dashboard KPI Aggregation**
Ein Backend-Roundtrip liefert Übungs-KPIs, YTD-Einheiten, Trainings-Home (nächste Termine, Vermerke, offene Rückschau) — Ersatz für mehrere parallele Client-Listen-Calls.
---
## Designprinzipien
### 1. Aggregierter Endpoint statt Chatty Client
| | |
|---|---|
| **Prinzip** | `GET /dashboard/kpis` ruft intern `list_exercises_like_get` + `list_training_units` mit gleichen Filtern wie zuvor im UI. |
| **Begründung** | Weniger Latenz; eine TenantContext-Auflösung; Refaktor Phase 1 Dashboard. |
| **Quelle** | `dashboard.py`; SCHULDEN A3/B1 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Noch keine konfigurierbaren Widgets wie Mitai. |
### 2. Gleiche Filtersemantik wie Einzel-Endpoints
| | |
|---|---|
| **Prinzip** | KPI-Zählungen nutzen dieselben Helfer wie `/exercises` und `/training-units` — keine zweite Query-Logik. |
| **Begründung** | Zahlen auf Dashboard = Zahlen in Fachmodulen. |
| **Quelle** | Import aus `exercises`, `training_planning` Routern |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Interne Funktionsaufrufe statt HTTP — Kopplung an Router-Helfer. |
### 3. TenantContext für Mandanten-KPIs
| | |
|---|---|
| **Prinzip** | `Depends(get_tenant_context)` — assigned_to_me, created_by_me respektieren Verein/Rolle. |
| **Begründung** | Keine globalen KPIs für Trainer fremder Vereine. |
| **Quelle** | `get_dashboard_kpis` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 4. Festes Dashboard-Layout (kein Widget-Katalog)
| | |
|---|---|
| **Prinzip** | Shinkan-Übersicht zeigt definierte Kacheln — nicht nutzerkonfigurierbares Layout-JSON. |
| **Begründung** | MVP-Fokus Trainer-Verein; weniger Komplexität als Mitai. |
| **Quelle** | Produktentscheidung vs. Mitai #7 |
| **Tragfähigkeit** | **mittel** (bewusste Vereinfachung) |
| **Einschränkung** | Erweiterung braucht Backend+Frontend-Change, nicht Admin-Config. |
### 5. Profil nicht redundant laden
| | |
|---|---|
| **Prinzip** | Dashboard soll Auth-Profil nutzen — kein zweites `/profiles/me` nach Login+Reload (E2E Test 8). |
| **Begründung** | Architekturschuld A3 explizit adressiert. |
| **Quelle** | `tests/dev-smoke-test.spec.js`; Roadmap |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Frontend-Umsetzung muss mitziehen. |
### 6. Slice-Logik für Trainings-Home im Backend
| | |
|---|---|
| **Prinzip** | `_slice_training_home_notes` filtert Einheiten mit Vermerken — max. N Stück serverseitig. |
| **Begründung** | Kleiner Payload; klare Semantik. |
| **Quelle** | `dashboard.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Grenzwert hardcoded — ggf. Query-Param später. |
---
## Nicht übernehmen
1. **Drei parallele fast gleiche `listTrainingUnits`-Calls** im Client — behoben durch KPI-Endpoint.
2. **Mitai Widget-Dual-Registry vorreifen** ohne Produktbedarf — Over-Engineering für Shinkan MVP.
3. **KPI-Berechnung im Frontend** aus Volllisten — skaliert nicht.
4. **Dashboard ohne Tenant-Filter** — Mandanten-Leak.
---
## Verwandte Dokumentation
- [docs/architecture/SCHULDEN_UND_REMEDIATION.md](../../architecture/SCHULDEN_UND_REMEDIATION.md)
- Mitai: [DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,143 @@
# Designprinzipien – Index (Jinkendo Produktfamilie)
**Status:** Arbeitspapier / Übergabe
**Stand:** 2026-07-04
**Zweck:** Zentraler Einstieg für **tragfähige Designprinzipien** der Jinkendo-Produktfamilie — Shinkan-Serie (15 Module), Abgleich mit Mitai (9 Module), Basis für Schwester-Apps.
**Nicht enthalten:** App-Gesamtarchitektur, domänenspezifische Fachlogik im Detail, vollständige API-Referenz.
**Ablage (Shinkan-Serie):** `docs/jinkendo-family/design-principles/*_DESIGN_PRINCIPLES.md`
**Übergeordnet:** [docs/jinkendo-family/README.md](../README.md)
**Mitai-Serie:** [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md)
**Abgleich Mitai ↔ Shinkan:** [DESIGN_PRINCIPLES_ALIGNMENT.md](../DESIGN_PRINCIPLES_ALIGNMENT.md)
---
## Wofür diese Serie?
Shinkan implementiert wiederkehrende **Querschnittsmuster** (Mandanten-Zugriff, Capabilities, Medien-Archiv, Planungsdomäne, KI-Laufzeit, Import, Navigation, Deploy) sowie **domänenspezifische Bausteine** (Übungskatalog, Fähigkeiten-Scoring, Trainingsplanung, Compliance-Meldungen). Die 15 Dokumente destillieren daraus:
- **Was** übertragbar ist (Prinzip + Begründung + Tragfähigkeit)
- **Was** bewusst nicht kopiert werden soll („Nicht übernehmen“)
- **Wo** im Code nachgeschaut werden kann (Pfade, Specs)
- **Mitai-Abgleich** — welches Schwester-Dokument vergleichbar ist
Jedes Dokument ist **eigenständig lesbar**; dieser Index ordnet Abhängigkeiten, Lese-Reihenfolge und den geplanten Familien-Review.
---
## Dokumente (15/15)
| # | Modul | Datei | Kernidee (1 Satz) | Mitai-Vergleich |
|---|-------|-------|-------------------|-----------------|
| 1 | Access Layer & Tenant | [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./ACCESS_LAYER_DESIGN_PRINCIPLES.md) | Ein `TenantContext` pro Request; einheitliche `visibility`/`club_id`-Semantik für Bibliotheksartefakte. | — (Shinkan-spezifisch) |
| 2 | Capability & Club Features | [CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md) | Capabilities + Vereins-Kontingente; `GET /me/entitlements`; 4-Phasen-Rollout mit Env-Flags. | #3 Feature & Entitlement |
| 3 | Rights Registry | [RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md](./RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md) | Module registrieren Capabilities/Features bei Startup — kein vollständiger Vorab-Katalog in Migrationen. | #4 Registry / Plugin |
| 4 | Auth & Session | [AUTH_SESSION_DESIGN_PRINCIPLES.md](./AUTH_SESSION_DESIGN_PRINCIPLES.md) | Server-Sessions, `require_auth` als Depends; gemeinsame Mitai-Basis. | #5 Auth & Session |
| 5 | AI Prompt Runtime | [AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md](./AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md) | Schmale Laufzeit (`ai_prompt_runtime`); DB-Templates + Mustache; Kontext-Arten pro Domäne. | #1 Prompt Engine |
| 6 | Media Assets & Archiv | [MEDIA_ASSETS_DESIGN_PRINCIPLES.md](./MEDIA_ASSETS_DESIGN_PRINCIPLES.md) | Physisches Asset einmal, mehrfach verknüpft; Lifecycle, Legal Hold, Inline-Rich-Text. | — |
| 7 | Exercise Catalog | [EXERCISE_CATALOG_DESIGN_PRINCIPLES.md](./EXERCISE_CATALOG_DESIGN_PRINCIPLES.md) | Übung als Kernobjekt; Varianten, Governance, Progressionsgraph, Kombinationsübungen. | — |
| 8 | Skill Scoring | [SKILL_SCORING_DESIGN_PRINCIPLES.md](./SKILL_SCORING_DESIGN_PRINCIPLES.md) | Regelbasiertes gewichtetes Profil; Peer-Vergleich nur unter gleichem Artefakttyp. | #2 Data Layer (teilweise) |
| 9 | Training Planning | [TRAINING_PLANNING_DESIGN_PRINCIPLES.md](./TRAINING_PLANNING_DESIGN_PRINCIPLES.md) | Einheiten mit Phasen/Streams; Rahmen-Bibliothek + Module; Coach/Durchführung getrennt. | — |
| 10 | Content Reports (P-13) | [CONTENT_REPORTS_DESIGN_PRINCIPLES.md](./CONTENT_REPORTS_DESIGN_PRINCIPLES.md) | Melde-Workflow in Posteingang; Priorität sensibler Gründe; Legal-Hold-Anschluss. | — |
| 11 | Wiki Import | [WIKI_IMPORT_DESIGN_PRINCIPLES.md](./WIKI_IMPORT_DESIGN_PRINCIPLES.md) | SMW-API-Ingest + Mapper; Preview/Dry-Run; Duplikat-Tracking — kein Raw-Wiki in DB. | #6 Universal Import |
| 12 | Navigation / IA | [NAVIGATION_IA_DESIGN_PRINCIPLES.md](./NAVIGATION_IA_DESIGN_PRINCIPLES.md) | `appNav.js` als SSoT; Admin-Hub horizontal; Onboarding-Nav ohne Verein. | #8 Navigation / IA |
| 13 | Migration & Deploy | [MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md](./MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md) | `XXX_*.sql` beim Container-Start; develop/main → Dev/Prod; fail-fast. | #9 Migration & Deploy |
| 14 | Dashboard KPIs | [DASHBOARD_KPI_DESIGN_PRINCIPLES.md](./DASHBOARD_KPI_DESIGN_PRINCIPLES.md) | Aggregierter `/dashboard/kpis`-Roundtrip statt mehrerer Listen-Calls. | #7 Dashboard Widgets (vereinfacht) |
| 15 | Maturity Models | [MATURITY_MODELS_DESIGN_PRINCIPLES.md](./MATURITY_MODELS_DESIGN_PRINCIPLES.md) | Kontextsensitive Matrix-Auflösung; Export/Import-Stack für Admin-Portabilität. | — |
---
## Empfohlene Lesereihenfolge
### Schnellüberblick (45 Min)
1. [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./ACCESS_LAYER_DESIGN_PRINCIPLES.md) — Shinkan-Kernunterscheidung zu Mitai
2. [RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md](./RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md) — Meta-Muster für Erweiterbarkeit
3. [MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md](./MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md) — Familien-Basis
### Vollständige Implementierung (neues Produkt)
```
Foundation: (13) Migration & Deploy → (4) Auth → (1) Access Layer → (2) Capabilities → (3) Registry
Domäne: (7) Exercise Catalog → (6) Media → (9) Training Planning → (8) Skill Scoring
Erweiterung: (5) AI Prompt Runtime → (11) Wiki Import → (15) Maturity Models
Compliance: (10) Content Reports
Oberfläche: (12) Navigation → (14) Dashboard KPIs
```
### Nur Familien-Review (Mitai ↔ Shinkan)
| Mitai-Dokument | Shinkan-Gegenstück | Review-Fokus |
|----------------|-------------------|--------------|
| #1 Prompt Engine | #5 AI Prompt Runtime | Executor-Reife, Registry, Workflows |
| #2 Data Layer | #8 Skill Scoring | Berechnungs-SSoT vs. Router-Duplikat |
| #3 Feature & Entitlement | #2 Capability & Club Features | Subjekt: Profil vs. Verein |
| #4 Registry | #3 Rights Registry | Registrierungsmuster |
| #5 Auth | #4 Auth & Session | Gemeinsamer Code, IDOR-Risiken |
| #6 Universal Import | #11 Wiki Import | Ingest ≠ Interpretation |
| #7 Dashboard Widgets | #14 Dashboard KPIs | Konfigurierbarkeit vs. Aggregation |
| #8 Navigation | #12 Navigation | appNav-Pattern |
| #9 Migration & Deploy | #13 Migration & Deploy | Gleiches Startup-Muster |
---
## Querschnittsthemen (über alle Docs)
| Thema | Primär | Ergänzend |
|-------|--------|-----------|
| Mandanten-Isolation (`club_id`) | #1 Access Layer | #6 Media, #7 Exercise, #9 Planning |
| Sichtbarkeit `private`/`club`/`official` | #1 Access Layer | #6 Media, #7 Exercise |
| Capability-Gating | #2 Entitlement | #3 Registry, #5 AI Runtime |
| Validierung an der Grenze | #3 Registry | #6 Inline-Media, #11 Import-Mapper |
| Single Source of Truth (Berechnung) | #8 Skill Scoring | #5 AI Kontext-Builder |
| Dual Registry (Code + DB) | #3 Rights Registry | #2 Capabilities in DB |
| Bekannte Lücken dokumentieren | alle „Nicht übernehmen“ | Endpoint-Audit, Architekturschuld |
---
## Verwandte normative Docs (Shinkan-spezifisch)
| Thema | Agent-Guide / Spec |
|-------|-------------------|
| Zugriffsschicht | [ACCESS_LAYER_AND_GOVERNANCE_PLAN.md](../../../.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md), [ACCESS_LAYER_ENDPOINT_AUDIT.md](../../../.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md) |
| Capabilities | [CAPABILITY_CATALOG.v1.md](../../../.claude/docs/technical/CAPABILITY_CATALOG.v1.md) |
| Vereins-Features | [CLUB_MEMBERSHIP_AND_FEATURES.v1.md](../../../.claude/docs/technical/CLUB_MEMBERSHIP_AND_FEATURES.v1.md) |
| Medien | [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../../../.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) |
| KI-Zielbild | [AI_PROMPT_TARGET_ARCHITECTURE.md](../../../.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md) |
| Planung Streams | [PARALLEL_TRAINING_STREAMS_SPEC.md](../../../.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md) |
| Skill Scoring | [SKILL_SCORING_SPEC.md](../../../.claude/docs/technical/SKILL_SCORING_SPEC.md) |
| Architektur-Schuld | [docs/architecture/SCHULDEN_UND_REMEDIATION.md](../../architecture/SCHULDEN_UND_REMEDIATION.md) |
---
## Übergabe-Checkliste (Familien-Review)
```
[ ] Pro Modul: Prinzipien vs. Mitai-Gegenstück abgleichen
[ ] Architekturschuld pro Modul in SCHULDEN_UND_REMEDIATION / „Nicht übernehmen“ verknüpfen
[ ] Gemeinsame Familien-Prinzipien aus Übereinstimmungen ableiten
[ ] Abweichungen bewusst dokumentieren (z. B. Vereins- vs. Profil-Entitlements)
[ ] Shared Code (auth.py, db_init) — eine Quelle oder Fork-Drift?
```
---
## Pflege
| Aktion | Wo |
|--------|-----|
| Neues Querschnittsmodul extrahiert | Neues `*_DESIGN_PRINCIPLES.md` + Zeile in Tabelle oben |
| Shinkan-Implementierung ändert Muster | Betroffenes Einzeldokument + ggf. Querschnittstabelle |
| Mitai-Review abgeschlossen | Abschnitt „Familien-Prinzipien“ (separates Doc, Backlog) |
---
## Changelog Index
| Datum | Änderung |
|-------|----------|
| 2026-07-04 | Verweis auf [FAMILY_ENTITLEMENT_MODEL.md](../FAMILY_ENTITLEMENT_MODEL.md) |
| 2026-07-04 | Verweis auf [DESIGN_PRINCIPLES_ALIGNMENT.md](../DESIGN_PRINCIPLES_ALIGNMENT.md) |
| 2026-07-04 | Shinkan-Serie nach `docs/jinkendo-family/design-principles/` verschoben (Familien-Foundation) |
| 2026-07-04 | Index angelegt; Serie 1–15 aus Shinkan-Ist-Stand extrahiert |
@@ -0,0 +1,128 @@
# Exercise Catalog – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Exercise Catalog“ — Kernobjekt Übung, Varianten, Graphen, Kombination
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 7 von 15
**Mitai-Vergleich:** — (domänenspezifisch)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| API | `backend/routers/exercises.py`, `exercise_progression_graphs.py` |
| Rich-Text | `backend/exercise_rich_text.py` |
| KI | `backend/exercise_ai.py` |
| Frontend | `frontend/src/pages/Exercises*.jsx`, Tab-Formular |
| Specs | `EXERCISES_ARCHITECTURE.md`, `EXERCISES_API_SPEC.md`, Kombinations-Spec |
---
## Modul
**Exercise Catalog**
Shinkans Kernobjekt: Übungen mit mehrdimensionaler Einordnung (Skills, Fokus, Stile), Varianten, Progressionsgraphen, Kombinationsübungen (`method_archetype`, Stationen), Governance und Medien-Anbindung.
---
## Designprinzipien
### 1. Übung als zentrales Aggregate Root
| | |
|---|---|
| **Prinzip** | Varianten, Medien, Skills, Graph-Knoten hängen an `exercises.id` — Owner/Governance auf Eltern-Übung. |
| **Begründung** | Eine Freigabe- und Lösch-Semantik; Varianten ohne eigenen Owner. |
| **Quelle** | `FACHLICHE_NUTZERFUNKTIONEN.md` §4.1, §4.7 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Große Monolith-Router/Seiten — Refaktor-Roadmap. |
### 2. Tab-Formular statt Scroll-Monolith
| | |
|---|---|
| **Prinzip** | Register: Stammdaten · Anleitung · Einordnung · Kombination · Varianten · Medien — Varianten/Medien erst nach erstem Save. |
| **Begründung** | UX für komplexe Objekte; klare Abhängigkeiten (IDs für Medien/Varianten). |
| **Quelle** | Nutzerfunktionen §4.1 |
| **Tragfähigkeit** | **hoch** (UI-Muster) |
| **Einschränkung** | Frontend-God-Page-Schuld dokumentiert. |
### 3. Mehrdimensionale Filter-SSoT
| | |
|---|---|
| **Prinzip** | Suche/Filter über Skills, Fokus, Stil, Zielgruppe, Status, Freigabelevel — Backend-Query + gespeicherte Präferenzen. |
| **Begründung** | Trainer finden Inhalte in großen Vereins-Katalogen. |
| **Quelle** | `SEARCH_FILTER_SPEC.md`; `exercises.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Performance schwere Listen — Baseline/Roadmap. |
### 4. Varianten mit Voraussetzungskette
| | |
|---|---|
| **Prinzip** | `exercise_variants` mit Reihenfolge, optional `prerequisite_variant_id`. |
| **Begründung** | Didaktische Abstufung innerhalb einer Übung. |
| **Quelle** | Migration 030; Planung nutzt Varianten-ID pro Eintrag |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 5. Progressionsgraph als gerichtete Übungs-Beziehungen
| | |
|---|---|
| **Prinzip** | Knoten = Übungen/Varianten; Kanten = „weiter“-Beziehungen; eigener Router + UI in Übungswelt. |
| **Begründung** | Didaktik und Planungs-KI nutzen denselben Graph. |
| **Quelle** | `exercise_progression_graphs.py`; `PLANNING_PROGRESSION_GRAPH_KI.md` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Graph-Editor-Komplexität; KI-Artefakte separat. |
### 6. Kombinationsübungen als Sonderform im gleichen Katalog
| | |
|---|---|
| **Prinzip** | `exercise_type=combination` mit Stationen, `method_archetype`, optionalem `method_profile`. |
| **Begründung** | In Planung wie normale Übung; Coach zeigt Stations-Layer. |
| **Quelle** | Migration 056/057; Kombinations-Spec V2 |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Archetyp-Stufen B/C noch ausbaubar. |
### 7. Governance integriert (nicht separates CMS)
| | |
|---|---|
| **Prinzip** | `visibility`, `status` (draft/review/…), Access-Layer-Lösch/Transition-Regeln. |
| **Begründung** | Trainer-Workflow ohne externes Freigabe-Tool. |
| **Quelle** | `club_tenancy.py`; Content Change Requests → Posteingang |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Formales Review-Workflow noch leichtgewichtig. |
### 8. Rich-Text-Felder mit Inline-Medien
| | |
|---|---|
| **Prinzip** | Einheitliche Platzhalter/Render für `summary`, `goal`, `execution`, … |
| **Begründung** | Medienreicher Inhalt ohne iframe-Split. |
| **Quelle** | `exercise_rich_text.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
---
## Nicht übernehmen
1. **Varianten mit eigenem Owner/Freigabe** — widerspricht Domänenmodell.
2. **Übungsliste ohne Tenant-Filter** — Access-Layer-Pflicht.
3. **KI-generierte Übungen ohne Governance-Felder** — immer draft/private Default.
4. **Progressionsgraph-Logik im Frontend allein** — Server validiert Kanten.
---
## Verwandte Dokumentation
- [EXERCISES_ARCHITECTURE.md](../../../.claude/docs/technical/EXERCISES_ARCHITECTURE.md)
- [MEDIA_ASSETS_DESIGN_PRINCIPLES.md](./MEDIA_ASSETS_DESIGN_PRINCIPLES.md)
- [SKILL_SCORING_DESIGN_PRINCIPLES.md](./SKILL_SCORING_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,117 @@
# Maturity Models – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Maturity Models / Fähigkeitsmatrix“ — kontextsensitive Auflösung
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 15 von 15
**Mitai-Vergleich:** — (domänenspezifisch)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| API | `backend/routers/maturity_models.py`, `matrix_editor.py`, `matrix_stack_bundle.py` |
| Admin-UI | `/admin/maturity-models` |
| Import | Wiki-Import Typ Modelle; Matrix-Stack Export/Import |
| Spec | `.claude/docs/technical/SKILLS_MATRIX_SPEC.md` |
---
## Modul
**Maturity Models & Matrix Stack**
Matrixbasierte Reifegradmodelle mit Stufen und Zelltexten; kontextsensitive Auflösung über Bindings (Fokusbereich, Stilrichtung, Zielgruppe); Admin-Export/Import einzelner Modelle und Komplett-Stack.
---
## Designprinzipien
### 1. Kontext-Bindings M:N (leer = überall)
| | |
|---|---|
| **Prinzip** | Modell verknüpft mit Fokus/Stil/Zielgruppe; leere Bindings = global gültig. |
| **Begründung** | Ein Stack deckt mehrere Trainingskontexte ab. |
| **Quelle** | `maturity_models.py` `_attach_context` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Auflösungs-Priorität bei mehreren Treffern dokumentieren. |
### 2. Resolve-API für Laufzeit-Nutzung
| | |
|---|---|
| **Prinzip** | Authentifizierte Nutzer listen/auflösen; Admin-only für Roh-ID-GET in Admin-UI. |
| **Begründung** | Trainer sehen passende Matrix; Rohdaten-Edit geschützt. |
| **Quelle** | Router-Docstring; Rollen-Checks |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 3. Matrix-Editor als separates Admin-Tool
| | |
|---|---|
| **Prinzip** | `matrix_editor` Router für Zellbearbeitung — nicht im Trainer-Flow. |
| **Begründung** | Komplexe UI; Plattform-Redaktionsaufgabe. |
| **Quelle** | Admin-Nav „Fähigkeitsmatrix“ |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Frontend-Komplexität — eigene Schuld-Kategorie. |
### 4. Stack-Bundle Export/Import
| | |
|---|---|
| **Prinzip** | `matrix_stack_bundle` — Komplett-Stack zwischen Umgebungen (Dev→Prod, Backup). |
| **Begründung** | Analog Prompt Import/Export — Konfiguration versionierbar außerhalb DB. |
| **Quelle** | Admin-Werkzeuge; Wiki-Import ergänzt |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Kein Diff/Merge wie Mitai Prompt-Import. |
### 5. Plattform-Admin-Schreibschutz
| | |
|---|---|
| **Prinzip** | Schreiben nur `admin`/`superadmin`; Lesen breiter für authentifizierte Nutzer (Resolve). |
| **Begründung** | Offizielle Kompetenzrahmen zentral gepflegt. |
| **Quelle** | `_require_admin` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 6. Integration Wiki-Import für Modelle
| | |
|---|---|
| **Prinzip** | SMW-Kategorie Modelle → Import-Pfad neben Übungen/Skills. |
| **Begründung** | Bestehende Wissensbasis karatetrainer.net nutzen. |
| **Quelle** | `import_wiki.py` `CATEGORY_MODELS` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Gap-Analyse SMW — nicht alle Wiki-Felder gemappt. |
### 7. Orthogonal zu Skill Scoring
| | |
|---|---|
| **Prinzip** | Matrix = beschreibende Stufen; Skill Scoring = gewichtete Übungs-Aggregation — getrennte Module. |
| **Begründung** | Keine Vermischung von Kompetenz-Raster und Trainings-KPI. |
| **Quelle** | Domänen-Trennung in Specs |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | UI kann beides nebenan zeigen — klare Labels nötig. |
---
## Nicht übernehmen
1. **Matrix-Zellen in Übungs-Score-Formel mischen** — ohne fachliche Spec.
2. **Trainer-Edit globaler offizieller Matrizen** — Admin-only.
3. **Import ohne Stack-Integrität** — Bundle-Validierung beachten.
4. **Resolve ohne Kontext-Parameter** wenn Mehrdeutigkeit — falsche Matrix.
---
## Verwandte Dokumentation
- [SKILLS_MATRIX_SPEC.md](../../../.claude/docs/technical/SKILLS_MATRIX_SPEC.md)
- [WIKI_IMPORT_DESIGN_PRINCIPLES.md](./WIKI_IMPORT_DESIGN_PRINCIPLES.md)
- [SKILL_SCORING_DESIGN_PRINCIPLES.md](./SKILL_SCORING_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,119 @@
# Media Assets & Archiv – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Media Assets & Archiv“ — physische Medien, Lifecycle, Inline
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 6 von 15
**Mitai-Vergleich:** — (Mitai hat kein vergleichbares Medien-Archiv)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| API | `backend/routers/media_assets.py`, `platform_media_storage.py` |
| Speicher | `backend/media_storage.py`, `MEDIA_ROOT` |
| Rechte/Audit | `backend/media_rights.py`, `media_legal_hold.py` |
| Inline Rich-Text | `backend/exercise_rich_text.py` |
| Retention-Job | `backend/scripts/media_retention_job.py` |
| Spec | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
---
## Modul
**Media Assets & Archiv**
Zentrale Verwaltung physischer Dateien (`media_assets`), Verknüpfung zu Übungen (`exercise_media`), mehrstufiger Lifecycle (Papierkorb, Legal Hold), Inline-Einbettung in Rich-Text.
---
## Designprinzipien
### 1. Physisches Asset einmal, mehrfach verknüpft
| | |
|---|---|
| **Prinzip** | Datei in `media_assets`; Übungen referenzieren via `exercise_media.media_asset_id`. |
| **Begründung** | Keine Dubletten auf Platte; Wiederverwendung im Archiv. |
| **Quelle** | `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §1 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Legacy-Pfade ohne Asset-ID können noch existieren. |
### 2. Gleiche Visibility-Semantik wie Übungen
| | |
|---|---|
| **Prinzip** | `private`/`club`/`official` + `club_id` — Access Layer für Download und Liste. |
| **Begründung** | Ein Freigabemodell für alle Bibliotheksartefakte. |
| **Quelle** | Spec §4; `media_rights.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Promotion Übung→official muss Assets mithheben — UI-Dialog Pflicht. |
### 3. Lifecycle getrennt von Übungs-Verknüpfung
| | |
|---|---|
| **Prinzip** | Verknüpfung in Übung lösen ≠ Asset physisch löschen; Papierkorb-Stufen separat. |
| **Begründung** | Trainer dürfen Link entfernen ohne Archiv-Löschrecht. |
| **Quelle** | Spec §5 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Retention-Job muss in Betrieb überwacht werden. |
### 4. Legal Hold blockiert automatisierten Lifecycle
| | |
|---|---|
| **Prinzip** | `legal_hold` schützt Asset vor Purge; Anbindung an Content Reports (Superadmin). |
| **Begründung** | Compliance bei Meldungen (P-11/P-13). |
| **Quelle** | `media_legal_hold.py`; `content_reports.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 5. Inline-Medien: kanonisches Markup + Validierung
| | |
|---|---|
| **Prinzip** | `{{exerciseMedia:id}}` → `<span data-shinkan-exercise-media="id">`; IDs müssen zur Übung gehören. |
| **Begründung** | Ein Render-Pfad; keine broken References nach Medien-Löschung. |
| **Quelle** | `exercise_rich_text.py`; Spec §11 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Beim Erst-Anlegen der Übung keine Inline-Refs (Chicken-Egg). |
### 6. Speicher-Abstraktion (local + konfigurierbarer Root)
| | |
|---|---|
| **Prinzip** | `get_effective_media_root()` + `library/…`-Pfadkonvention; kein hardcodierter `/app/media` in Routern. |
| **Begründung** | NAS/externer Speicher vorbereitet. |
| **Quelle** | `media_storage.py`; `platform_media_storage` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | S3-Backend noch nicht vollständig. |
### 7. Audit-Log für sensitive Aktionen
| | |
|---|---|
| **Prinzip** | `media_asset_audit_log` bei Meldungen, Hold, kritischen Lifecycle-Events. |
| **Begründung** | Nachvollziehbarkeit für Admins und Compliance. |
| **Quelle** | `media_rights.write_audit_log_entry` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Nicht jede Admin-Aktion geloggt. |
---
## Nicht übernehmen
1. **Download nur mit Übungs-ID ohne Asset-Governance** — Seitenkanal-Risiko.
2. **Copyright leer bei `official`** — Spec verbietet das fachlich.
3. **Physisches Löschen bei Referenzanzahl > 0** — Spec §5.3.
4. **Embed-URLs durch Lifecycle-Purge** — Embeds haben anderen Lebenszyklus.
---
## Verwandte Dokumentation
- [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../../../.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)
- [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./ACCESS_LAYER_DESIGN_PRINCIPLES.md)
- [CONTENT_REPORTS_DESIGN_PRINCIPLES.md](./CONTENT_REPORTS_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,117 @@
# Migration & Deploy – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Migration & Deploy“ — Schema-Evolution, Container-Start
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 13 von 15
**Mitai-Vergleich:** [MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md) (#9)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| DB-Init | `backend/db_init.py` |
| Migrationen | `backend/migrations/XXX_*.sql` |
| Version | `backend/version.py` (`DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) |
| Docker | `docker-compose.yml`, `docker-compose.dev-env.yml` |
| Deploy | develop → dev.shinkan · main → shinkan (Pi) |
---
## Modul
**Migration & Deploy**
Nummerierte SQL-Migrationen beim Container-Start, Tracking in `schema_migrations`, Git-Branch → Umgebung, fail-fast ohne Auto-Rollback.
---
## Designprinzipien
### 1. Nummerierte Migrationen `XXX_*.sql`
| | |
|---|---|
| **Prinzip** | Nur nummerierte Dateien in `backend/migrations/`; lexikographische Reihenfolge. |
| **Begründung** | Familien-Standard Mitai/Shinkan; vorhersagbare Anwendung. |
| **Quelle** | `db_init.py`; `CLAUDE.md` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Manuelle Nummern-Kollisionen vermeiden — Team-Disziplin. |
### 2. Startup vor App — Migrationen blockieren Start bei Fehler
| | |
|---|---|
| **Prinzip** | `db_init.py` wartet auf Postgres, wendet fehlende Migrationen an, dann FastAPI. |
| **Begründung** | Keine App mit veraltetem Schema. |
| **Quelle** | Container-Entrypoint / startup |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Kein automatisches Rollback — manuelle Recovery. |
### 3. `schema_migrations` Tracking-Tabelle
| | |
|---|---|
| **Prinzip** | Jede angewendete Datei wird persistiert; Wiederholung überspringt Bekannte. |
| **Begründung** | Idempotenz über Deploys hinweg. |
| **Quelle** | `ensure_migration_table`, `get_applied_migrations` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Geänderte Migration nach Apply — nicht neu ausführen (neue Nummer). |
### 4. `DB_SCHEMA_VERSION` als dokumentierter Stand
| | |
|---|---|
| **Prinzip** | `version.py` führt Schema-Version; MODULE_VERSIONS für Subsysteme. |
| **Begründung** | Support und Handover wissen erwarteten Stand. |
| **Quelle** | `backend/version.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Manuell pflegen bei Migration — Drift möglich. |
### 5. develop/main → Dev/Prod mit festen Ports
| | |
|---|---|
| **Prinzip** | Dev 3098/8098 · Prod 3003/8003 — nie ändern ohne explizite Freigabe. |
| **Begründung** | Deploy-Infrastruktur auf Pi/Synology stabil. |
| **Quelle** | `CLAUDE.md` Deployment |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 6. Neue Spalten nur via Migration
| | |
|---|---|
| **Prinzip** | Kein ad-hoc ALTER in Routern; Coding Rules. |
| **Begründung** | Reproduzierbare Umgebungen. |
| **Quelle** | `.claude/rules/CODING_RULES.md` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 7. IF NOT EXISTS / defensive SQL wo sinnvoll
| | |
|---|---|
| **Prinzip** | Migrationen tolerant bei Wiederanlauf in Dev — aber Tracking verhindert Doppel-Apply. |
| **Begründung** | Recovery in Entwicklung erleichtern. |
| **Quelle** | Mitai-Migrations-Muster |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Nicht alles idempotent — komplexe Migrationen brauchen Transaktion. |
---
## Nicht übernehmen
1. **Manuelle psql-Schritte in Prod** ohne nummerierte Migration im Repo.
2. **Schema-Drift nur in schema.sql** ohne Migration — Init vs. Upgrade verwechseln.
3. **Auto-Rollback bei fehlgeschlagener Migration** — fail-fast, manuell fixen.
4. **Port-Änderung ohne Infra-Update** — bricht Fritz!Box/NAS-Routing.
---
## Verwandte Dokumentation
- [DATABASE_SCHEMA.md](../../../.claude/docs/technical/DATABASE_SCHEMA.md)
- Mitai: [MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,107 @@
# Navigation / IA – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Navigation & Information Architecture“
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 12 von 15
**Mitai-Vergleich:** [NAVIGATION_IA_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/NAVIGATION_IA_DESIGN_PRINCIPLES.md) (#8)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Hauptnav | `frontend/src/config/appNav.js` |
| Admin-Nav | `frontend/src/components/AdminPageNav.jsx` |
| Shells | `RequireAdmin`, App-Layout in `App.jsx` |
| Return-Kontext | `.claude/docs/technical/NAV_RETURN_CONTEXT_SPEC.md` |
| Styles | `frontend/src/app.css` (`.admin-top-nav`, Bottom-Nav) |
---
## Modul
**Navigation / IA**
Single Source of Truth für Hauptnavigation (Mobile Bottom + Desktop Sidebar), separater Admin-Hub, Onboarding-Nav ohne Vereinsfeatures, rollen- und kontextabhängige Einblendung (Posteingang, Admin).
---
## Designprinzipien
### 1. `appNav.js` als SSoT für Hauptnavigation
| | |
|---|---|
| **Prinzip** | `getMainNavItems(isAdmin, opts)` liefert Route, Label, Icon — eine Liste für Mobile und Desktop. |
| **Begründung** | Gleiches Familien-Muster wie Mitai `appNav`; keine divergierenden Nav-Arrays. |
| **Quelle** | `appNav.js` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Tiefe Unterrouten (Übung bearbeiten) nicht in Top-Nav — Shell/Back. |
### 2. Admin als separater Hub
| | |
|---|---|
| **Prinzip** | `/admin/*` mit horizontaler `AdminPageNav` — Plattform-Werkzeuge gebündelt. |
| **Begründung** | Trainer-Nav bleibt schlank; Admin-IA skaliert unabhängig. |
| **Quelle** | `AdminPageNav.jsx` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Admin-Nav hardcoded Array — kein `adminNav.js` SSoT wie Mitai ideal. |
### 3. Onboarding-Nav reduziert
| | |
|---|---|
| **Prinzip** | `getOnboardingNavItems()` — nur Verein + Einstellungen ohne Übungen/Planung. |
| **Begründung** | Nutzer ohne Vereinsmitgliedschaft nicht in leere Bereiche führen. |
| **Quelle** | `appNav.js` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 4. Kontextabhängige Items (Posteingang)
| | |
|---|---|
| **Prinzip** | `showInbox` Flag steuert Posteingang-Eintrag — Berechtigung aus Entitlements/Rolle. |
| **Begründung** | Kein toter Nav-Link für Trainer ohne Inbox-Recht. |
| **Quelle** | `baseItems({ showInbox })` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Logik zur `showInbox`-Setzung in App.jsx pflegen. |
### 5. Responsive: Bottom-Nav Mobile, Sidebar Desktop
| | |
|---|---|
| **Prinzip** | Gleiche Items, unterschiedliche Präsentation; CSS-Variablen für Abstände. |
| **Begründung** | PWA-typisches Muster; 80px Bottom-Padding für Nav. |
| **Quelle** | `app.css`; Design-System in `CLAUDE.md` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Breakpoint-Konsistenz mit Mitai (1024px) prüfen beim Familien-Review. |
### 6. Return-Kontext für tiefe Bearbeitung
| | |
|---|---|
| **Prinzip** | Spez `NAV_RETURN_CONTEXT_SPEC` — zurück zur Herkunftsliste mit Filter-State. |
| **Begründung** | Übungs-Editor aus Suche/Planung ohne Navigations-Verlust. |
| **Quelle** | Return-Context Spec |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Nicht alle Flows implementiert. |
---
## Nicht übernehmen
1. **Zwei unterschiedliche Nav-Arrays** für Mobile vs. Desktop.
2. **Admin-Routen in Haupt-Bottom-Nav** mischen (außer ein Admin-Einstieg).
3. **Hardcodierte Nav in jeder Page** — zentral in `appNav.js`.
4. **Fehlender Onboarding-Gate** — volle Nav ohne Verein verwirrt.
---
## Verwandte Dokumentation
- [NAV_RETURN_CONTEXT_SPEC.md](../../../.claude/docs/technical/NAV_RETURN_CONTEXT_SPEC.md)
- Mitai: [NAVIGATION_IA_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/NAVIGATION_IA_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,114 @@
# Rights Registry – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Rights Registry“ — Capabilities & Features zur Laufzeit registrieren
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 3 von 15
**Mitai-Vergleich:** [REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md) (#4)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Registry-Kern | `backend/rights_registry.py` |
| Modul-Registrierungen | `backend/rights_registrations/` (`exercises.py`, `planning.py`, `platform.py`, `club_creation.py`) |
| Startup-Sync | Import in `backend/main.py` |
| Tests | `backend/tests/test_rights_registry.py` |
---
## Modul
**Rights Registry (Registry-first für Capabilities & Features)**
Module deklarieren bei Implementierung, welche Rechte und Kontingente sie anbieten. Beim App-Start werden Definitionen in die DB synchronisiert (`capabilities`, `features`, Default-Grants).
---
## Fachliche Verantwortung
1. **Runtime-Registrierung** — `register_capability()`, `register_feature()` vor DB-Sync.
2. **Modul-Ownership** — Jedes Feature/Capability trägt `module`-Feld für Admin-Filter „Rollen & Rechte“.
3. **Default Club Grants** — Rollen → Capability-Mapping bei Erst-Sync.
4. **Kein vollständiger Vorab-Katalog in SQL-Migration** — nur was Module wirklich liefern.
---
## Designprinzipien
### 1. Registry-first statt Migrations-Monolith
| | |
|---|---|
| **Prinzip** | Neue Rechte erscheinen durch Code-Registrierung + Startup-Upsert — nicht durch manuelle 079-Katalog-Migration pro Feature. |
| **Begründung** | Modul und Recht entstehen zusammen; weniger vergessene Katalog-Einträge. |
| **Quelle** | `rights_registry.py`; Docstring; `rights_registrations/` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Erste Basismigration seedet noch initiale Zeilen. |
### 2. Modul-Datei pro Domäne
| | |
|---|---|
| **Prinzip** | `rights_registrations/exercises.py` registriert nur Übungs-Rechte; Planung/Platform analog. |
| **Begründung** | Ownership klar; Merge-Konflikte lokalisiert. |
| **Quelle** | `rights_registrations/__init__.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Import-Reihenfolge muss in `main.py` garantiert sein. |
### 3. Frozen Dataclass-Definitionen
| | |
|---|---|
| **Prinzip** | `CapabilityRegistration` / `FeatureRegistration` als immutable `@dataclass(frozen=True)`. |
| **Begründung** | Keine nachträgliche Mutation nach Registrierung. |
| **Quelle** | `rights_registry.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 4. Validierung an der Registrierungsgrenze
| | |
|---|---|
| **Prinzip** | `register_*` wirft bei fehlendem `id` oder `module`. |
| **Begründung** | Fehler beim Import/Startup, nicht erst im Admin-UI. |
| **Quelle** | `rights_registry.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Keine Schema-Validierung für `limit_type`/`reset_period` zur Compile-Zeit. |
### 5. DB als persistierter Katalog, Code als SSoT für neue IDs
| | |
|---|---|
| **Prinzip** | Startup `sync_rights_registry_to_db()` upsertet aus In-Memory-Registry. |
| **Begründung** | Admin-UI liest DB; Entwickler erweitern Code-Registry. |
| **Quelle** | `rights_registry.py`; `main.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Deaktivierte Capabilities in DB vs. fehlende im Code — Reconcile-Policy dokumentieren. |
### 6. Default Grants als Code-Daten
| | |
|---|---|
| **Prinzip** | `default_club_grants: (role_code, capability_id)` pro Capability. |
| **Begründung** | Neue Module bringen sinnvolle Standard-Rollen mit. |
| **Quelle** | `rights_registrations/exercises.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Admin-Overrides in DB können bei Re-Sync überschrieben werden — ON CONFLICT-Verhalten beachten. |
---
## Nicht übernehmen
1. **Capabilities nur in SQL-Migration pflegen** — driftet vom implementierten Modul weg.
2. **Registrierung ohne Endpoint-Verdrahtung** — Spec: „nur Rechte mit echter Endpoint-Verdrahtung“.
3. **Zweite Registry-Philosophie** für Custom Roles — gleiche Capability-IDs wiederverwenden (Plan Stufe E).
---
## Verwandte Dokumentation
- [CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md)
- [CAPABILITY_CATALOG.v1.md](../../../.claude/docs/technical/CAPABILITY_CATALOG.v1.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,107 @@
# Skill Scoring – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Skill Scoring & Profile“ — gewichtete Fähigkeiten-KPIs
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 8 von 15
**Mitai-Vergleich:** [DATA_LAYER_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/DATA_LAYER_DESIGN_PRINCIPLES.md) (#2, analog: Berechnungs-SSoT)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Kern | `backend/skill_scoring.py` |
| Profile-API | `backend/routers/skill_profiles.py` |
| Planungs-Vorschläge | Planung-Router + Fähigkeiten-Seite |
| Spec | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
---
## Modul
**Skill Scoring & Profiles**
Regelbasierte Aggregation von `exercise_skills` über Artefakte (Module, Rahmenprogramme, Pläne, Graphen) zu gewichteten Profilen mit Peer-Vergleich innerhalb desselben Artefakttyps.
---
## Designprinzipien
### 1. Berechnung in einer Schicht (`skill_scoring.py`)
| | |
|---|---|
| **Prinzip** | Scores, Gewichte, Peer-Perzentile — nicht in React oder Router-SQL duplizieren. |
| **Begründung** | Analog Mitai Data Layer: Charts, Listen-KPIs, Planungs-Vorschläge nutzen dieselbe Logik. |
| **Quelle** | `SKILL_SCORING_SPEC.md`; `skill_scoring.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Einzelne UI-Fallbacks können noch vereinfacht rechnen. |
### 2. Gewichtung aus Trainings-Signalen
| | |
|---|---|
| **Prinzip** | Dauer, Vorkommen, Intensität (`niedrig`/`mittel`/`hoch`), Stufen-Spanne — explizite Multiplikatoren. |
| **Begründung** | Nachvollziehbares Ranking ohne Black-Box-ML. |
| **Quelle** | `_INTENSITY_MULT`, `_level_range_multiplier` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | `is_primary` / `development_contribution` bewusst ignoriert. |
### 3. Peer-Vergleich nur unter gleichem Artefakttyp
| | |
|---|---|
| **Prinzip** | Modul vs. Modul, Rahmen vs. Rahmen — nie Modul vs. Plan gemischt. |
| **Begründung** | Fachlich sinnvoller Vergleich; vermeidet irreführende Prozentwerte. |
| **Quelle** | Phase 3 Lieferung; Nutzerfunktionen §4.2 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | UI muss Typ-Kontext klar labeln. |
### 4. Sichtbarkeits-filterte Peer-Menge
| | |
|---|---|
| **Prinzip** | Peer-Pool = nur für Nutzer sichtbare Artefakte (Access Layer). |
| **Begründung** | Keine Leaks über Scores fremder Vereins-Inhalte. |
| **Quelle** | `skill_scoring.py` + Tenant-Filter in Aufrufern |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Performance bei großen Pools. |
### 5. Planungs-Vorschläge aus Profil-Delta
| | |
|---|---|
| **Prinzip** | Fähigkeiten-Schwerpunkte → sortierte Vorschläge für Module/Rahmen/Regressionspfade. |
| **Begründung** | Schließt Loop zwischen Katalog und Planung. |
| **Quelle** | Fähigkeiten-Seite Phase 3 |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | KI-Suche über Volltext — Backlog. |
### 6. Default-Minuten für fehlende Dauer
| | |
|---|---|
| **Prinzip** | `DEFAULT_ITEM_MINUTES` / `GRAPH_DEFAULT_ITEM_MINUTES` als explizite Konstanten. |
| **Begründung** | Deterministische Scores bei unvollständigen Planungsdaten. |
| **Quelle** | `skill_scoring.py` |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Fachlich kalibrierbar — dokumentieren statt verstecken. |
---
## Nicht übernehmen
1. **Score-Berechnung im Frontend** für Listen-KPIs.
2. **Peer-Vergleich über Artefakttypen hinweg** — irreführend.
3. **ML-Black-Box statt regelbasierter Gewichte** — ohne explizite Produktentscheidung.
4. **Ignorieren der Tenant-Sichtbarkeit** im Peer-Pool.
---
## Verwandte Dokumentation
- [SKILL_SCORING_SPEC.md](../../../.claude/docs/technical/SKILL_SCORING_SPEC.md)
- [EXERCISE_CATALOG_DESIGN_PRINCIPLES.md](./EXERCISE_CATALOG_DESIGN_PRINCIPLES.md)
- [TRAINING_PLANNING_DESIGN_PRINCIPLES.md](./TRAINING_PLANNING_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,129 @@
# Training Planning – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „Training Planning“ — Einheiten, Phasen, Rahmen, Coach
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 9 von 15
**Mitai-Vergleich:** — (domänenspezifisch)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Kalender-Einheiten | `backend/routers/training_planning.py` |
| Module | `backend/routers/training_modules.py` |
| Rahmen | `backend/routers/training_framework_programs.py` |
| Phasen/Streams | Migration 063; `PARALLEL_TRAINING_STREAMS_SPEC.md` |
| Frontend | `TrainingPlanningPage`, `TrainingCoachPage`, `TrainingUnitRunPage` |
| Utils | `frontend/src/utils/trainingPlanUtils.js` |
---
## Modul
**Training Planning & Frameworks**
Planbare Trainingseinheiten mit Sektionen, **Phasen** (Ganzgruppe/Parallel) und **Streams**, Bibliotheks-**Rahmenprogramme** (Ziele/Slots), **Trainingsmodule**, Materialisierung aus Slots, Durchführungs- und Coaching-Ansichten.
---
## Designprinzipien
### 1. Einheit als planbares Aggregate
| | |
|---|---|
| **Prinzip** | `training_units` + `training_unit_sections` + Items; Kopf: Gruppe, Datum, Trainer, Status. |
| **Begründung** | Klare Grenze Kalender vs. Bibliothek. |
| **Quelle** | Domain Model; `training_planning.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Große Router-Datei — Refaktor-Schuld. |
### 2. Phasen/Streams als explizites Modell (nicht Marker-Sektionen)
| | |
|---|---|
| **Prinzip** | `training_unit_phases` + `training_unit_parallel_streams`; Sektionen an Phase oder Stream gebunden. |
| **Begründung** | Breakout-Trainings fachlich korrekt; Coach/Rejoin-Logik. |
| **Quelle** | `PARALLEL_TRAINING_STREAMS_SPEC.md` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Legacy-Einheiten → Default-Ganzgruppenphase; Vorlagen-Phasen teils offen. |
### 3. API: verschachtelte `phases` + flache `sections`
| | |
|---|---|
| **Prinzip** | GET liefert beides; PUT akzeptiert `phases` atomar; höchstens eines von phases/sections/exercises pro Request. |
| **Begründung** | Frontend normalisiert; Server validiert CHECK-Regeln. |
| **Quelle** | Spec §4; Planning-Router |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Server-Spiegelung neuer Abschnitte in phases — Handover offen. |
### 4. Rahmen-Bibliothek: Slot = Blueprint-Unit
| | |
|---|---|
| **Prinzip** | `framework_slot_id` auf Blueprint-`training_units`; Materialisierung → Kalender-Einheit für Gruppe. |
| **Begründung** | Wiederverwendbare Programme ohne Duplikat-Logik pro Slot-Typ. |
| **Quelle** | Migration 035–037 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | UI „Aus Rahmen übernehmen“ nicht flächendeckend. |
### 5. Trainingsmodule als wiederverwendbare Übungsfolgen
| | |
|---|---|
| **Prinzip** | Bibliotheks-Objekt mit Skill-Profil; Übernahme in geplante Einheit. |
| **Begründung** | Trainer-Bausteine zwischen Einzelübung und Rahmen. |
| **Quelle** | `training_modules.py`; Skill Scoring Phase 3 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 6. Drei Durchführungsmodi getrennt
| | |
|---|---|
| **Prinzip** | Planung (edit) · Plan & Ablauf (run) · Coaching (step timeline, Stream-Picks, Nachbereitung). |
| **Begründung** | Unterschiedliche UX und Payloads; Coach speichert → Run-Ansicht. |
| **Quelle** | Nutzerfunktionen §4.4; `TrainingCoachPage` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Stream-Tabs in Run-Ansicht optional offen. |
### 7. Governance über Gruppe/Verein, keine neuen Mandanten-Entitäten
| | |
|---|---|
| **Prinzip** | Einheit → `training_group` → Verein; Access Layer für Bibliotheks-Rahmen/Module. |
| **Begründung** | Planung erbt Organisations-Kontext. |
| **Quelle** | `PARALLEL_TRAINING_STREAMS_SPEC.md` §4 |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Stream-Trainer-Zuweisung UI unvollständig. |
### 8. Kombinationsübungen in Planung transparent
| | |
|---|---|
| **Prinzip** | Items ohne Variante; Coach zeigt Stations-Kandidaten + Archetyp-Hinweise. |
| **Begründung** | Gleiche Item-Schicht für Standard- und Kombi-Übungen. |
| **Quelle** | Migration 057; Kombinations-Spec Anhang A |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Archetyp-Stufen B/C ausbaubar. |
---
## Nicht übernehmen
1. **Parallele Phasen als reine UI-Konvention ohne DB-Phasen** — Minimalvariante verworfen.
2. **Rahmen-Slots als separate Exercise-Join-Tabelle** — Legacy `training_framework_slot_exercises` abgelöst.
3. **Planungs-KI direkt in Router-Strings** — AI Prompt Runtime nutzen.
4. **Blueprint-Einheiten in Kalenderlisten** — Filter `framework_slot_id IS NOT NULL`.
---
## Verwandte Dokumentation
- [PARALLEL_TRAINING_STREAMS_SPEC.md](../../../.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md)
- [TRAINING_FRAMEWORK_SPEC.md](../../../.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md)
- [SKILL_SCORING_DESIGN_PRINCIPLES.md](./SKILL_SCORING_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
@@ -0,0 +1,118 @@
# Wiki Import – Designprinzipien (Extraktion)
**Status:** Analyse / Arbeitspapier
**Stand:** 2026-07-04
**Geltungsbereich:** Modul „MediaWiki Import“ — SMW-Ingest, Mapping, Tracking
**Serie:** Designprinzipien für Produktfamilie · Shinkan Dokument 11 von 15
**Mitai-Vergleich:** [UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md) (#6)
**Kernkomponenten:**
| Bereich | Pfade |
|---------|-------|
| Router | `backend/routers/import_wiki.py`, `import_wiki_admin.py` |
| Client | `backend/smw_client.py` |
| Mapper | `backend/smw_mapper.py` |
| Tracking | `wiki_import_log`, `wiki_import_references` |
| Spec | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
---
## Modul
**Wiki Import (Semantic MediaWiki)**
Import von Übungen, Fähigkeiten, Methoden und Reifegradmodellen aus externem Wiki via API — Preview, Dry-Run, Duplikat-Erkennung, Admin-only.
---
## Designprinzipien
### 1. Ingest ≠ Interpretation
| | |
|---|---|
| **Prinzip** | `SmwClient` holt Rohdaten; `smw_mapper` mappt auf Shinkan-Modelle — getrennte Schichten. |
| **Begründung** | Analog Mitai Import: Transport/Parser ≠ Domänen-Insert. |
| **Quelle** | `import_wiki.py`; Mitai Universal Import |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Keine generische Import-Registry wie Mitai CSV — wiki-spezifisch. |
### 2. Preview und Dry-Run vor Execute
| | |
|---|---|
| **Prinzip** | `/preview` zeigt Kandidaten; `dry_run=true` ohne DB-Schreiben. |
| **Begründung** | Admin sieht Auswirkungen; sichere Iteration. |
| **Quelle** | `ImportExecuteRequest` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 3. Duplikat-Tracking über Wiki-Referenzen
| | |
|---|---|
| **Prinzip** | `wiki_import_references` speichert Wiki-Titel ↔ Shinkan-ID für Re-Import. |
| **Begründung** | Idempotenz und Update statt blindem Duplicate. |
| **Quelle** | Domain Model Import-Tabellen |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Gap-Analyse in `SMW_IMPORTER_GAP_ANALYSIS.md` beachten. |
### 4. Import-Typ als expliziter Parameter
| | |
|---|---|
| **Prinzip** | `import_type`: `exercise` \| `skill` \| `method` \| Modelle — eigener Mapper-Pfad. |
| **Begründung** | Klare Verantwortung pro Ziel-Entität. |
| **Quelle** | `map_wiki_to_*` in `smw_mapper.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | Kein Plug-in-Registry-Pattern wie Mitai Module-Registry. |
### 5. Superadmin/Admin-only Execute
| | |
|---|---|
| **Prinzip** | `require_admin` auf Execute — Massenimport ist Plattform-Risiko. |
| **Begründung** | Governance und Datenqualität. |
| **Quelle** | `import_wiki.py` |
| **Tragfähigkeit** | **hoch** |
| **Einschränkung** | — |
### 6. Kategorie aus Env mit Fallback
| | |
|---|---|
| **Prinzip** | `MEDIAWIKI_CATEGORY_*` Env-Variablen; leere Query → Default je Typ. |
| **Begründung** | Wiki-Struktur konfigurierbar ohne Code-Deploy. |
| **Quelle** | `CATEGORY_EXERCISES` etc. |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Hardcoded Wiki-URL in Doku — Umgebungsspezifisch halten. |
### 7. Background Tasks für lange Imports
| | |
|---|---|
| **Prinzip** | FastAPI `BackgroundTasks` für Execute — HTTP nicht blockieren. |
| **Begründung** | Große Kategorien ohne Timeout. |
| **Quelle** | Execute-Endpoint |
| **Tragfähigkeit** | **mittel** |
| **Einschränkung** | Kein Job-Status-Polling-UI wie Mitai — Log-Tabelle nutzen. |
---
## Nicht übernehmen
1. **Rohe Wiki-HTML ungemappt in DB** — immer Mapper.
2. **Import ohne Log/Re-Import-Referenz** — Duplikat-Chaos.
3. **Trainer-self-service Wiki-Import** — Admin-only.
4. **Skill-Scoring beim Insert** — Scores gehören in `skill_scoring`-Schicht.
---
## Verwandte Dokumentation
- [MEDIAWIKI_IMPORT_SPEC.md](../../../.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md)
- [EXERCISE_CATALOG_DESIGN_PRINCIPLES.md](./EXERCISE_CATALOG_DESIGN_PRINCIPLES.md)
- Mitai: [UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/technical/UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md)
- [DESIGN_PRINCIPLES_INDEX.md](./DESIGN_PRINCIPLES_INDEX.md)
+3
View File
@@ -11,9 +11,11 @@
}, },
"dependencies": { "dependencies": {
"@tanstack/react-virtual": "^3.13.24", "@tanstack/react-virtual": "^3.13.24",
"dompurify": "^3.4.17",
"jspdf": "^4.2.1", "jspdf": "^4.2.1",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
"marked": "^18.0.3", "marked": "^18.0.3",
"qrcode": "^1.5.4",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
@@ -22,6 +24,7 @@
}, },
"devDependencies": { "devDependencies": {
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"jsdom": "^29.1.1",
"vite": "^5.1.4", "vite": "^5.1.4",
"vitest": "^3.0.5" "vitest": "^3.0.5"
} }
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more