mindnet/docs/05_Development/05_developer_guide.md
Lars ec759dd1dc
All checks were successful
Deploy mindnet to llm-node / deploy (push) Successful in 4s
docs
2025-12-15 14:13:10 +01:00

304 lines
12 KiB
Markdown

---
doc_type: developer_guide
audience: developer
scope: workflow, testing, architecture, modules
status: active
version: 2.6
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna (Deep Dive), Setup, Git-Workflow und Erweiterungs-Anleitungen."
---
# Mindnet Developer Guide & Workflow
**Quellen:** `developer_guide.md`, `dev_workflow.md`
Dieser Guide vereint das technische Verständnis der Module mit dem operativen Workflow zwischen Windows (Dev) und Linux (Runtime).
---
## 1. Die physische Architektur
Mindnet läuft in einer verteilten Umgebung (Post-WP15 Setup).
* **Windows 11 (VS Code):** Hier schreibst du Code. **Nie** direkt auf `main` arbeiten!
* **Beelink (Runtime):** Der Server. Hier läuft die Software. Wir nutzen **Systemd-Services**:
* **PROD:** API (8001) + UI (8501). Ordner: `~/mindnet`.
* **DEV:** API (8002) + UI (8502). Ordner: `~/mindnet_dev`.
* **Gitea:** Der "Safe" (Raspberry Pi). Speichert den Code und verwaltet Versionen.
---
## 2. Projektstruktur & Referenz
### 2.1 Verzeichnisbaum
```text
mindnet/
├── app/
│ ├── core/ # Ingestion, Chunker, Qdrant Wrapper
│ ├── routers/ # FastAPI Endpoints
│ ├── services/ # Ollama Client, Traffic Control
│ ├── models/ # Pydantic DTOs
│ └── frontend/ # Streamlit UI Module
├── config/ # YAML Configs (Single Source of Truth)
├── scripts/ # CLI Tools (Import, Diagnose, Reset)
├── tests/ # Pytest Suite & Smoke Scripts
└── vault/ # Lokaler Test-Content
```
### 2.2 Vollständige Datei-Referenz (Auto-Scan)
Eine Übersicht aller Skripte und Module im System.
| Datei/Pfad | Typ | Beschreibung |
| :--- | :--- | :--- |
| **Backend Core** | | |
| `app/main.py` | Skript | Bootstrap der FastAPI API. |
| `app/config.py` | Config | Zentrale Konfiguration (Pydantic Settings). |
| `app/core/ingestion.py` | Core Modul | Async Ingestion Service & Change Detection. |
| `app/core/chunker.py` | Core Modul | Smart Chunker Orchestrator. |
| `app/core/retriever.py` | Core Modul | Hybrider Such-Algorithmus (Semantik + Graph). |
| `app/core/ranking.py` | Core Modul | Kombiniertes Scoring (WP-04). |
| `app/core/graph_adapter.py` | Core Modul | Adjazenzaufbau & Subgraph-Expansion. |
| `app/core/qdrant.py` | Core Modul | Qdrant Client Wrapper. |
| `app/core/qdrant_points.py` | Core Modul | Robuste Point-Helper für Qdrant (Retry-Logik). |
| `app/core/derive_edges.py` | Core Modul | Edge-Erzeugung aus Markdown. |
| `app/core/edges.py` | Core Modul | Datenstrukturen für Kanten. |
| `app/core/edges_writer.py` | Core Modul | Schreibt Kanten in die DB. |
| `app/core/note_payload.py` | Core Modul | Builder für Note-Metadaten. |
| `app/core/chunk_payload.py` | Core Modul | Builder für Chunk-Payloads. |
| `app/core/type_registry.py` | Core Modul | Logik zum Laden der `types.yaml`. |
| `app/core/schema_loader.py` | Core Modul | Lädt JSON-Schemas für Validierung. |
| `app/core/env_vars.py` | Core Modul | Environment-Variablen Konstanten. |
| **API Router** | | |
| `app/routers/chat.py` | API Router | RAG Endpunkt & Hybrid Router. |
| `app/routers/query.py` | API Router | Query-Endpunkte (WP-04). |
| `app/routers/graph.py` | API Router | Graph-Endpunkte (WP-04). |
| `app/routers/ingest.py` | API Router | Ingestion-Trigger & Analyse. |
| `app/routers/feedback.py` | API Router | Feedback-Endpunkt. |
| `app/routers/tools.py` | API Router | Tool-Definitionen für Ollama/n8n/MCP. |
| `app/routers/admin.py` | API Router | Admin-/Monitoring-Endpunkte. |
| **Services** | | |
| `app/services/llm_service.py` | Service | LLM Client mit Traffic Control. |
| `app/services/llm_ollama.py` | Service | Legacy: Ollama-Integration & Prompt-Bau. |
| `app/services/embeddings_client.py` | Service | Async Text→Embedding Service. |
| `app/services/semantic_analyzer.py` | Service | Smart Edge Validation & Filtering. |
| `app/services/discovery.py` | Service | Backend Intelligence (Matrix-Logik). |
| `app/services/feedback_service.py` | Service | Schreibt JSONL-Logs. |
| **Frontend** | | |
| `app/frontend/ui.py` | Frontend | Entrypoint (Streamlit). |
| `app/frontend/ui_editor.py` | Frontend | Editor-View & Logic. |
| `app/frontend/ui_chat.py` | Frontend | Chat-View. |
| `app/frontend/ui_graph_cytoscape.py` | Frontend | Graph-Visualisierung (Modern). |
| `app/frontend/ui_graph.py` | Frontend | Graph-Visualisierung (Legacy). |
| `app/frontend/ui_graph_service.py` | Frontend | Datenaufbereitung für Graphen. |
| `app/frontend/ui_callbacks.py` | Frontend | Event-Handler. |
| `app/frontend/ui_api.py` | Frontend | Backend-Bridge. |
| `app/frontend/ui_utils.py` | Frontend | Helper (Healing Parser). |
| `app/frontend/ui_config.py` | Frontend | Konstanten (Farben, URLs). |
| **CLI & Scripts** | | |
| `scripts/import_markdown.py` | Skript | Haupt-Importer CLI. |
| `scripts/reset_qdrant.py` | Skript | Löscht Collections (`--mode wipe`). |
| `scripts/payload_dryrun.py` | Skript | Zeigt Payloads VOR dem Upsert. |
| `scripts/edges_dryrun.py` | Skript | Erzeugt Edges ohne DB-Write. |
| `scripts/edges_full_check.py` | Skript | Prüft Graph-Integrität. |
| `scripts/resolve_unresolved_references.py`| Skript | Löst Wikilinks nachträglich auf. |
| `scripts/audit_vault_vs_qdrant.py` | Skript | Konsistenz-Check File vs. DB. |
| `scripts/audit_edges_vs_expectations.py`| Skript | Prüft Kanten gegen Erwartungswert. |
| `scripts/setup_mindnet_collections.py` | Skript | Richtet Collections initial ein. |
| `scripts/export_markdown.py` | Skript | Exportiert Qdrant zurück zu Markdown. |
| `scripts/wp04_smoketest.py` | Skript | E2E-Schnelltest der WP-04 Endpunkte. |
| `scripts/health_check_mindnet.py` | Skript | System Health Check. |
| `scripts/report_hashes.py` | Skript | Übersicht bei Mehrfach-Hashes. |
| `scripts/make_test_vault.py` | Skript | Erzeugt minimalen Test-Vault. |
| `scripts/ollama_tool_runner.py` | Skript | Minimaler Tool-Caller für Ollama. |
---
## 3. Core-Module im Detail (Architektur)
Hier wird erklärt, *wie* die wichtigsten Komponenten unter der Haube arbeiten.
### 3.1 Der Importer (`scripts.import_markdown`)
Dies ist das komplexeste Modul.
* **Orchestrierung:** Es ruft `app.core.chunker` für die Textzerlegung und `app.services.semantic_analyzer` für Smart Edges auf.
* **Idempotenz:** Der Importer kann beliebig oft laufen. Er nutzt deterministische IDs (UUIDv5) und überschreibt vorhandene Einträge konsistent.
* **Robustheit:** In `ingestion.py` sind Mechanismen wie Change Detection (Hash-Vergleich) und Robust File I/O implementiert.
### 3.2 Der Hybrid Router (`app.routers.chat`)
Hier liegt die Logik für Intent Detection (WP06) und Interview-Modus (WP07).
* **Question Detection:** Prüft zuerst regelbasiert, ob der Input eine Frage ist (`?`, W-Wörter). Falls ja -> RAG.
* **Keyword Match:** Prüft Keywords aus `decision_engine.yaml` und `types.yaml`.
* **Priority:** Ruft `llm_service` mit `priority="realtime"` auf, um die Import-Warteschlange zu umgehen.
### 3.3 Der Retriever (`app.core.retriever`)
Hier passiert das Scoring (WP04a).
* **Hybrid Search:** Der Chat-Endpoint erzwingt `mode="hybrid"`.
* **Strategic Retrieval:** In `chat.py` wird der Retriever ggf. *zweimal* aufgerufen, wenn ein Intent (z.B. `DECISION`) eine Injection (`value`) erfordert.
### 3.4 Das Frontend (`app.frontend.ui`)
Eine Streamlit-App (WP10/19).
* **Resurrection Pattern:** Das UI nutzt ein spezielles State-Management (`st.session_state`), um Eingaben bei Tab-Wechseln (Chat <-> Editor) zu erhalten. Widgets synchronisieren sich via Callbacks.
* **Healing Parser:** Die Funktion `parse_markdown_draft` repariert defekte YAML-Frontmatter (z.B. fehlendes `---`) vom LLM automatisch.
### 3.5 Traffic Control (`app.services.llm_service`)
Neu in v2.6. Stellt sicher, dass Batch-Prozesse (Import) den Live-Chat nicht ausbremsen.
* **Methode:** `generate_raw_response(..., priority="background")` aktiviert eine Semaphore.
* **Limit:** Konfigurierbar über `MINDNET_LLM_BACKGROUND_LIMIT` (Default: 2).
---
## 4. Lokales Setup (Development)
**Voraussetzungen:** Python 3.10+, Docker, Ollama.
**Installation:**
```bash
# 1. Repo & Venv
git clone <repo> mindnet
cd mindnet
python3 -m venv .venv
source .venv/bin/activate
# 2. Dependencies
pip install -r requirements.txt
# 3. Ollama (Nomic ist Pflicht!)
ollama pull phi3:mini
ollama pull nomic-embed-text
```
**Konfiguration (`.env`):**
```ini
QDRANT_URL="http://localhost:6333"
COLLECTION_PREFIX="mindnet_dev"
VECTOR_DIM=768
MINDNET_LLM_BACKGROUND_LIMIT=2
MINDNET_API_URL="http://localhost:8002"
MINDNET_LLM_TIMEOUT=300.0
```
---
## 5. Der Entwicklungs-Zyklus (Workflow)
### Phase 1: Windows (Code)
1. **Basis aktualisieren:** `git checkout main && git pull`.
2. **Branch erstellen:** `git checkout -b feature/mein-feature`.
3. **Coden & Committen.**
4. **Push:** `git push origin feature/mein-feature`.
### Phase 2: Beelink (Test / Dev)
Hier prüfst du, ob dein Code auf Linux läuft.
1. **Einloggen:** `ssh user@beelink`.
2. **Ordner:** `cd ~/mindnet_dev`.
3. **Code holen:** `git fetch && git checkout feature/mein-feature && git pull`.
4. **Dependencies:** `pip install -r requirements.txt`.
5. **Restart:** `sudo systemctl restart mindnet-dev`.
6. **Validierung (Smoke Tests):**
* **Last-Test:** Starte `python3 -m scripts.import_markdown ...` im Terminal und chatte gleichzeitig im UI (Port 8502).
* **API Check:** `curl -X POST "http://localhost:8002/ingest/analyze" ...`
### Phase 3: Release & Deployment (Prod)
Wenn alles getestet ist:
1. **Gitea:** Pull Request erstellen und mergen.
2. **Deploy auf Prod (Beelink):**
```bash
cd ~/mindnet
git pull origin main
# Sicherstellen, dass Prod-Dependencies aktuell sind
source .venv/bin/activate
pip install -r requirements.txt
ollama pull nomic-embed-text # Falls neue Modelle nötig sind
# Restart
sudo systemctl restart mindnet-prod
sudo systemctl restart mindnet-ui-prod
```
3. **Cleanup:** Branch löschen (lokal und remote).
---
## 6. Erweiterungs-Guide: "Teach-the-AI"
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**.
### Workflow A: Neuen Typ implementieren (z. B. `type: risk`)
1. **Physik (`config/types.yaml`):**
```yaml
risk:
retriever_weight: 0.90 # Sehr wichtig
edge_defaults: ["blocks"] # Automatische Kante
detection_keywords: ["gefahr", "risiko"]
```
2. **Strategie (`config/decision_engine.yaml`):**
```yaml
DECISION:
inject_types: ["value", "risk"] # <--- "risk" hinzufügen
```
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
### Workflow B: Interview-Schema anpassen (WP07)
Wenn Mindnet neue Fragen stellen soll (z.B. "Budget" bei Projekten):
1. **Schema (`config/types.yaml`):**
```yaml
project:
schema:
- "Titel"
- "Ziel"
- "Budget (Neu)"
```
2. **Kein Code nötig:** Der `One-Shot Extractor` (Prompt Template) liest diese Liste dynamisch.
---
## 7. Tests & Debugging
**Unit Tests (Pytest):**
```bash
pytest tests/test_retriever_basic.py
pytest tests/test_chunking.py
```
**Pipeline Tests (Integration):**
```bash
# JSON-Schema prüfen
python3 -m scripts.payload_dryrun --vault ./test_vault
# Graph-Integrität prüfen
python3 -m scripts.edges_full_check
```
**E2E Smoke Tests:**
```bash
# Decision Engine
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
# Feedback
python tests/test_feedback_smoke.py --url http://localhost:8002/query
```
---
## 8. Troubleshooting & One-Liners
**DB komplett zurücksetzen (Vorsicht!):**
```bash
# --yes überspringt die Bestätigung
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
```
**Einen einzelnen File inspizieren (Parser-Sicht):**
```bash
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
```
**Live-Logs sehen:**
```bash
journalctl -u mindnet-dev -f
journalctl -u mindnet-ui-dev -f
```
**"UnicodeDecodeError in .env":**
* Ursache: Umlaute oder Sonderzeichen in der `.env`.
* Lösung: Datei bereinigen (nur ASCII) und sicherstellen, dass UTF-8 ohne BOM genutzt wird.