Compare commits

..
15 Commits
Author SHA1 Message Date
LarsandClaude Opus 5.5 347ca50e71 Container: Vault-Prüfung ohne festen Dateiaufbau (wie systemd)
Deploy mindnet DEV (Container) / deploy (push) Successful in 50s
Der Preflight verlangte _system/dictionary/edge_vocabulary.md, die es nur
im NAS-Vault gibt. Der Dev-Vault vault_master ist anders aufgebaut, systemd
prüft nichts davon. Jetzt: Vault muss lesbar und nicht leer sein; eine
bestimmte Datei nur noch optional über MINDNET_VAULT_SENTINEL. Default für
MINDNET_VAULT_ROOT wie in app/config.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:47:24 +01:00
LarsandClaude Opus 5.5 6a2ab522fc Docs: Gitea-Runner läuft als llmadmin, nicht als root
Deploy mindnet DEV (Container) / deploy (push) Failing after 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:43:19 +01:00
LarsandClaude Opus 5.5 666719ca4c Merge feature/containerization into develop
Deploy mindnet DEV (Container) / deploy (push) Failing after 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:22:08 +01:00
LarsandClaude Opus 5.5 6cdad8b046 Run the containers with the systemd configuration, 1:1
The containers now read the unchanged .env of the matching systemd instance
(/home/llmadmin/mindnet_dev/.env, /home/llmadmin/mindnet/.env) and use the
same Qdrant, Ollama, vault and collection prefix, so both can be compared
side by side. Only container-specific values are overridden: host service
addresses (host.docker.internal instead of 127.0.0.1) and the read-only vault.

- deploy/appenv.py derives the vault mount and prefix from that .env and
  rejects application keys in the container-only file.
- Remove the separate dev Qdrant, the synthetic test vault and the import step.
- UI binds 0.0.0.0 like systemd; API stays loopback by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:22:08 +01:00
LarsandClaude Opus 5.5 eae30775e3 Merge feature/containerization into develop
Deploy mindnet DEV (Container) / deploy (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:06:44 +01:00
LarsandClaude Opus 5.5 10a3524b59 Import the synthetic test vault after each dev deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:06:44 +01:00
LarsandClaude Opus 5.5 6c15b51e7a Merge feature/containerization into develop
Deploy mindnet DEV (Container) / deploy (push) Failing after 56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:45:19 +01:00
LarsandClaude Opus 5.5 26fa7732e9 Check out from our own Gitea instead of actions/checkout
The runner host failed to resolve github.com; deploys must not depend on
internet DNS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:45:19 +01:00
LarsandClaude Opus 5.5 5016ed6996 Merge feature/containerization into develop
Deploy mindnet DEV (Container) / deploy (push) Failing after 11s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:43:23 +01:00
LarsandClaude Opus 5.5 c4af7606da Give the test image the repo files its static checks read
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:43:23 +01:00
LarsandClaude Opus 5.5 ded97fc58c Merge feature/containerization into develop
Deploy mindnet DEV (Container) / deploy (push) Failing after 1m11s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:37:24 +01:00
LarsandClaude Opus 5.5 9d5b52a3c1 Activate dev container deploy on push to develop
- .gitea/workflows/deploy-dev.yml: prepares the host (synthetic test vault,
  dev.env from the example on first run, never overwritten), then runs
  deploy/deploy.sh dev. Prod workflow stays an inactive template.
- deploy/testvault: synthetic notes from scripts/make_test_vault.py plus
  synthetic edge_vocabulary.md/graph_schema.md (vault sentinel).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:37:23 +01:00
LarsandClaude Opus 5.5 7f5cdeb4cb Merge feature/containerization into develop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:17:39 +01:00
LarsandClaude Opus 5.5 8f9f83aa79 Add reachability checks and develop/main container pipeline (inactive)
- preflight --live: Ollama/Qdrant reachable from the container, required
  Ollama models present, 768 dimensions; clear abort instead of traceback.
  Static check rejects unset or container-local service URLs.
- deploy/smoke.py: non-writing post-start check via published ports.
- deploy/deploy.sh: test (no network), build, preflight, up --wait, smoke;
  prod rolls back to the last good image tag.
- Workflow templates deploy-dev.yml (push develop) and deploy-prod.yml
  (push main) following the Kansho pattern; not under .gitea/workflows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:01:37 +01:00
LarsandClaude Opus 5.5 7a225ba2b6 Prepare containerized dev/prod deployment (inactive)
Add a Docker image and separate Compose projects for development and
production, based on the stable main behaviour without the privacy
gateway. Nothing is wired into the existing systemd deploy workflow.

- One non-root image (api | ui | preflight), base image pinned by
  digest, dependencies from a hash-locked universal lock without torch
  and sentence-transformers (MiniLM is not on the runtime path)
- Preflight aborts on: VECTOR_DIM != 768 or non-nomic embedding
  profile, implicit or cross-env collection prefix, cloud keys without
  explicit egress acknowledgement, missing/empty or writable vault mount
- Vault is a read-only NAS bind mount without host-path autocreation;
  healthcheck turns unhealthy when the vault sentinel disappears
- Dev runs its own Qdrant; prod reuses the existing host instance
- API published on loopback only; read-only rootfs, cap_drop ALL,
  no-new-privileges
- Dev workflow kept as an inactive template outside .gitea/workflows
- Docs: operations guide and migration plan with release gates, test
  baseline classification, R2/R3 and privacy gateway requirements

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:33:18 +01:00
51 changed files with 3843 additions and 5651 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# Allowlist: Nur was hier ausdrücklich freigegeben ist, gelangt in den Build-Kontext.
# Damit landen weder .env-Dateien, Vault-Inhalte, Logs noch lokale venvs im Image.
**
!app/
!config/
!scripts/
!tests/
!deploy/
# Nur für die statischen Prüfungen in der Test-Stage (nicht im Laufzeit-Image):
!.dockerignore
!.gitea/workflows/
# Innerhalb der freigegebenen Ordner wieder ausschließen
**/__pycache__/
**/*.pyc
**/.pytest_cache/
config/*.env
config/*.local.*
config/*_old*
config/* - Kopie*
deploy/env/*.env
tests/temp_*/
+2
View File
@@ -0,0 +1,2 @@
# Shell-Skripte laufen im Container bzw. auf dem Linux-Runner.
*.sh text eol=lf
+53
View File
@@ -0,0 +1,53 @@
# Mindnet DEV als Container: jeder Push auf develop baut und startet den Dev-Stack
# auf dem Runner-Host (Muster wie Kansho). Gleiche Konfiguration wie die systemd-
# Dev-Instanz (8002/8502), parallel auf 8012/8512. systemd und Prod bleiben unberührt.
# Ablauf und Abbruchbedingungen: deploy/deploy.sh. Prod-Gegenstück (noch inaktiv):
# deploy/gitea-workflows/deploy-prod.yml.
name: Deploy mindnet DEV (Container)
on:
push:
branches: [develop]
workflow_dispatch:
concurrency:
group: deploy-mindnet-dev
cancel-in-progress: false
jobs:
deploy:
# Runner auf dem Zielhost (heute llm-node). Bei einem Umzug auf einen anderen
# Mini-PC nur das Label und die beiden Pfade anpassen.
runs-on: linux_host
env:
# Unveränderte Konfiguration der systemd-Dev-Instanz.
MINDNET_APP_ENV_FILE: /home/llmadmin/mindnet_dev/.env
# Nur Container-Angaben (Vorlage: deploy/env/dev.env.example).
MINDNET_ENV_FILE: /home/llmadmin/docker/mindnet-dev/container.env
steps:
# Ohne actions/checkout: kein Abruf von github.com (DNS/Internet auf dem Host
# nicht nötig). Holt genau den Commit des Pushes vom eigenen Gitea, mit Job-Token.
- name: Checkout
run: |
set -euo pipefail
git init -q .
git -c http.extraHeader="Authorization: token ${{ github.token }}" \
fetch -q --depth 1 "${{ github.server_url }}/${{ github.repository }}.git" "${{ github.sha }}"
git checkout -q --force FETCH_HEAD
git clean -q -ffdx
git log -1 --format='Checkout %H %s'
- name: Container-Datei beim ersten Lauf anlegen
run: |
set -euo pipefail
install -d -m 0750 "$(dirname "$MINDNET_ENV_FILE")"
if [ ! -f "$MINDNET_ENV_FILE" ]; then
install -m 0600 deploy/env/dev.env.example "$MINDNET_ENV_FILE"
echo "Container-Datei aus Vorlage angelegt: $MINDNET_ENV_FILE"
fi
docker version --format 'Docker {{.Server.Version}}'
docker compose version
- name: Test, Build, Preflight, Start, Smoke
run: bash deploy/deploy.sh dev
+3 -19
View File
@@ -1,17 +1,13 @@
"""
FILE: app/core/chunking/chunking_models.py
DESCRIPTION: Datenklassen für das Chunking-System.
WP-26 v1.0: Erweiterung um section_type für typ-spezifische Sektionen.
"""
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
@dataclass
class RawBlock:
"""
Repräsentiert einen logischen Block aus dem Markdown-Parsing.
WP-26 v1.0: Erweitert um section_type für typ-spezifische Sektionen.
"""
"""Repräsentiert einen logischen Block aus dem Markdown-Parsing."""
kind: str
text: str
level: Optional[int]
@@ -19,17 +15,10 @@ class RawBlock:
section_title: Optional[str]
exclude_from_chunking: bool = False # WP-24c v4.2.0: Flag für Edge-Zonen, die nicht gechunkt werden sollen
is_meta_content: bool = False # WP-24c v4.2.6: Flag für Meta-Content (Callouts), der später entfernt wird
# WP-26 v1.0: Section-Type für typ-spezifische Sektionen
section_type: Optional[str] = None # z.B. "insight", "decision", "experience"
# WP-26 v1.0: Block-ID für Intra-Note-Links (z.B. "^sit" aus "## Situation ^sit")
block_id: Optional[str] = None
@dataclass
class Chunk:
"""
Das finale Chunk-Objekt für Embedding und Graph-Speicherung.
WP-26 v1.0: Erweitert um section_type für effektiven Typ.
"""
"""Das finale Chunk-Objekt für Embedding und Graph-Speicherung."""
id: str
note_id: str
index: int
@@ -41,9 +30,4 @@ class Chunk:
neighbors_prev: Optional[str]
neighbors_next: Optional[str]
candidate_pool: List[Dict[str, Any]] = field(default_factory=list)
suggested_edges: Optional[List[str]] = None
# WP-26 v1.0: Section-Type für typ-spezifische Sektionen
# Wenn gesetzt, wird dieser als "effektiver Typ" verwendet statt note_type
section_type: Optional[str] = None
# WP-26 v1.0: Block-ID für Intra-Note-Links
block_id: Optional[str] = None
suggested_edges: Optional[List[str]] = None
+9 -140
View File
@@ -5,28 +5,16 @@ DESCRIPTION: Zerlegt Markdown in logische Einheiten (RawBlocks).
Stellt die Funktion parse_edges_robust zur Verfügung.
WP-24c v4.2.0: Identifiziert Edge-Zonen und markiert sie für Chunking-Ausschluss.
WP-24c v4.2.5: Callout-Exclusion - Callouts werden als separate RawBlocks identifiziert und ausgeschlossen.
WP-26 v1.0: Section-Type-Erkennung via [!section]-Callouts und automatische Section-Erkennung.
"""
import re
import os
import logging
from typing import List, Tuple, Set, Dict, Any, Optional
from .chunking_models import RawBlock
from .chunking_utils import extract_frontmatter_from_text
logger = logging.getLogger(__name__)
_WS = re.compile(r'\s+')
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
# WP-26 v1.0: Pattern für [!section]-Callouts
# Matches: > [!section] type-name
_SECTION_CALLOUT_PATTERN = re.compile(r'^\s*>\s*\[!section\]\s*(\w+)', re.IGNORECASE)
# WP-26 v1.0: Pattern für Block-IDs in Überschriften
# Matches: ## Titel ^block-id
_BLOCK_ID_PATTERN = re.compile(r'\^([a-zA-Z0-9_-]+)\s*$')
def split_sentences(text: str) -> list[str]:
"""Teilt Text in Sätze auf unter Berücksichtigung deutscher Interpunktion."""
text = _WS.sub(' ', text.strip())
@@ -39,18 +27,12 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
Zerlegt Text in logische Einheiten (RawBlocks), inklusive H1-H6.
WP-24c v4.2.0: Identifiziert Edge-Zonen (LLM-Validierung & Note-Scope) und markiert sie für Chunking-Ausschluss.
WP-24c v4.2.6: Callouts werden mit is_meta_content=True markiert (werden gechunkt, aber später entfernt).
WP-26 v1.0: Section-Type-Erkennung via [!section]-Callouts und automatische Section-Erkennung.
"""
blocks = []
h1_title = "Dokument"
section_path = "/"
current_section_title = None
# WP-26 v1.0: State-Machine für Section-Type-Tracking
current_section_type: Optional[str] = None # Aktueller Section-Type (oder None für note_type Fallback)
section_introduced_at_level: Optional[int] = None # Ebene, auf der erste Section eingeführt wurde
current_block_id: Optional[str] = None # Block-ID der aktuellen Sektion
# Frontmatter entfernen
fm, text_without_fm = extract_frontmatter_from_text(md_text)
@@ -88,9 +70,8 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
buffer = []
# WP-24c v4.2.5: Callout-Erkennung (auch verschachtelt: >>)
# WP-26 v1.0: Erweitert um [!section]-Callouts
# Regex für Callouts: >\s*[!edge], >\s*[!abstract], >\s*[!section] (auch mit mehreren >)
callout_pattern = re.compile(r'^\s*>{1,}\s*\[!(edge|abstract|section)\]', re.IGNORECASE)
# Regex für Callouts: >\s*[!edge] oder >\s*[!abstract] (auch mit mehreren >)
callout_pattern = re.compile(r'^\s*>{1,}\s*\[!(edge|abstract)\]', re.IGNORECASE)
# WP-24c v4.2.5: Markiere verarbeitete Zeilen, um sie zu überspringen
processed_indices = set()
@@ -105,39 +86,13 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
# Prüfe, ob diese Zeile ein Callout startet
callout_match = callout_pattern.match(line)
if callout_match:
callout_type = callout_match.group(1).lower() # "edge", "abstract", oder "section"
# WP-26 v1.0: [!section] Callout-Behandlung
if callout_type == "section":
# Extrahiere Section-Type aus dem Callout
section_match = _SECTION_CALLOUT_PATTERN.match(line)
if section_match:
new_section_type = section_match.group(1).lower()
current_section_type = new_section_type
# Tracke die Ebene, auf der die erste Section eingeführt wurde
# Wir nehmen die Ebene der letzten Überschrift (section_path basiert)
if section_introduced_at_level is None:
# Bestimme Ebene aus section_path
# "/" = H1, "/Title" = H2, "/Title/Sub" = H3, etc.
path_depth = section_path.count('/') if section_path else 1
section_introduced_at_level = max(1, path_depth + 1)
logger.debug(f"WP-26: Section-Type erkannt: '{new_section_type}' bei '{current_section_title}' (Level: {section_introduced_at_level})")
# [!section] Callout wird nicht als Block hinzugefügt (ist nur Metadaten)
processed_indices.add(i)
continue
# Vorherigen Text-Block abschließen
if buffer:
content = "\n".join(buffer).strip()
if content:
blocks.append(RawBlock(
"paragraph", content, None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
buffer = []
@@ -165,9 +120,7 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
blocks.append(RawBlock(
"callout", callout_content, None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone, # Nur Edge-Zonen werden ausgeschlossen
is_meta_content=True, # WP-24c v4.2.6: Markierung für spätere Entfernung
section_type=current_section_type,
block_id=current_block_id
is_meta_content=True # WP-24c v4.2.6: Markierung für spätere Entfernung
))
continue
@@ -180,32 +133,13 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
if content:
blocks.append(RawBlock(
"paragraph", content, None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
buffer = []
level = len(heading_match.group(1))
title = heading_match.group(2).strip()
# WP-26 v1.0: Block-ID aus Überschrift extrahieren (z.B. "## Titel ^block-id")
block_id_match = _BLOCK_ID_PATTERN.search(title)
if block_id_match:
current_block_id = block_id_match.group(1)
# Entferne Block-ID aus dem Titel für saubere Anzeige
title = _BLOCK_ID_PATTERN.sub('', title).strip()
else:
current_block_id = None
# WP-26 v1.0: Section-Type State-Machine
# Wenn eine Section eingeführt wurde und wir auf gleicher oder höherer Ebene sind:
# -> Automatisch neue Section erkennen (FA-02b)
if section_introduced_at_level is not None and level <= section_introduced_at_level:
# Neue Überschrift auf gleicher oder höherer Ebene -> Reset auf None (note_type Fallback)
current_section_type = None
logger.debug(f"WP-26: Neue Section erkannt bei H{level} '{title}' -> Reset auf note_type")
# WP-24c v4.2.0: Prüfe, ob dieser Header eine Edge-Zone startet
is_llm_validation_zone = (
level == llm_validation_level and
@@ -236,9 +170,7 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
# Die Überschrift selbst als regulären Block hinzufügen (auch markiert, wenn in Zone)
blocks.append(RawBlock(
"heading", stripped, level, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
continue
@@ -249,17 +181,13 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
if content:
blocks.append(RawBlock(
"paragraph", content, None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
buffer = []
if stripped == "---":
blocks.append(RawBlock(
"separator", "---", None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
else:
buffer.append(line)
@@ -269,70 +197,11 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
if content:
blocks.append(RawBlock(
"paragraph", content, None, section_path, current_section_title,
exclude_from_chunking=in_exclusion_zone,
section_type=current_section_type,
block_id=current_block_id
exclude_from_chunking=in_exclusion_zone
))
# WP-26 v1.3: Post-Processing - Section-Type rückwirkend setzen
# Der [!section] Callout kann IRGENDWO im Abschnitt stehen und gilt rückwirkend
# für die gesamte Heading-Sektion (vom Heading bis zum nächsten Heading gleicher/höherer Ebene)
blocks = _propagate_section_type_backwards(blocks, split_level=2)
return blocks, h1_title
def _propagate_section_type_backwards(blocks: List[RawBlock], split_level: int = 2) -> List[RawBlock]:
"""
WP-26 v1.3: Propagiert section_type rückwirkend für Heading-Sektionen.
Der [!section] Callout kann irgendwo im Abschnitt stehen (nicht nur direkt nach dem Heading).
Diese Funktion findet den section_type innerhalb einer Heading-Sektion und setzt ihn
rückwirkend für ALLE Blöcke dieser Sektion (inklusive dem Heading selbst).
Args:
blocks: Liste von RawBlock-Objekten
split_level: Heading-Ebene, die eine neue Sektion startet (Standard: 2 für H2)
Returns:
Liste von RawBlock-Objekten mit korrigiertem section_type
"""
if not blocks:
return blocks
# Gruppiere Blöcke nach Heading-Sektionen
sections: List[List[int]] = [] # Liste von Index-Listen
current_section_indices: List[int] = []
for idx, block in enumerate(blocks):
if block.kind == "heading" and block.level is not None and block.level <= split_level:
# Neues Heading startet neue Sektion
if current_section_indices:
sections.append(current_section_indices)
current_section_indices = [idx]
else:
current_section_indices.append(idx)
# Letzte Sektion hinzufügen
if current_section_indices:
sections.append(current_section_indices)
# Für jede Sektion: Finde den section_type und setze ihn rückwirkend
for section_indices in sections:
# Finde den section_type innerhalb dieser Sektion
section_type_found = None
for idx in section_indices:
if blocks[idx].section_type:
section_type_found = blocks[idx].section_type
break # Erster gefundener section_type gewinnt
# Wenn ein section_type gefunden wurde, setze ihn für alle Blöcke der Sektion
if section_type_found:
for idx in section_indices:
blocks[idx].section_type = section_type_found
return blocks
def parse_edges_robust(text: str) -> List[Dict[str, Any]]:
"""
Extrahiert Kanten-Kandidaten aus Wikilinks und Callouts.
+36 -141
View File
@@ -6,11 +6,6 @@ DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.9.
- Strikte Einhaltung von Sektionsgrenzen via Look-Ahead.
- Fix: Synchronisierung der Parameter mit dem Orchestrator (context_prefix).
WP-24c v4.2.5: Strict-Mode ohne Carry-Over - Bei strict_heading_split wird nach jeder Sektion geflasht.
WP-26 v1.0: section_type und block_id werden an Chunks weitergegeben.
WP-26 v1.1: Section-Type-Wechsel erzwingt IMMER einen neuen Chunk (unabhängig vom Profil).
WP-26 v1.3: Parser propagiert section_type rückwirkend für Heading-Sektionen.
Der [!section] Callout kann irgendwo im Abschnitt stehen.
Alle Blöcke einer Heading-Sektion haben den korrekten section_type.
"""
from typing import List, Dict, Any, Optional
from .chunking_models import RawBlock, Chunk
@@ -41,60 +36,41 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
chunks: List[Chunk] = []
def _emit(txt, title, path, section_type=None, block_id=None):
"""
Schreibt den finalen Chunk ohne Text-Modifikationen.
WP-26 v1.0: Erweitert um section_type und block_id.
"""
def _emit(txt, title, path):
"""Schreibt den finalen Chunk ohne Text-Modifikationen."""
idx = len(chunks)
win = _create_win(context_prefix, title, txt)
chunks.append(Chunk(
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
text=txt, window=win, token_count=estimate_tokens(txt),
section_title=title, section_path=path, neighbors_prev=None, neighbors_next=None,
section_type=section_type, block_id=block_id
section_title=title, section_path=path, neighbors_prev=None, neighbors_next=None
))
# --- SCHRITT 1: Gruppierung in atomare Sektions-Einheiten ---
# WP-26 v1.3: Der Parser propagiert section_type bereits rückwirkend für Heading-Sektionen.
# Alle Blöcke einer Heading-Sektion (inkl. Heading selbst) haben bereits den korrekten section_type.
sections: List[Dict[str, Any]] = []
curr_blocks = []
def _flush_section():
"""Hilfsfunktion zum Abschließen einer Sektion."""
nonlocal curr_blocks
if not curr_blocks:
return
# WP-26 v1.3: section_type wird vom Parser bereits korrekt gesetzt (rückwirkend)
# Alle Blöcke einer Heading-Sektion haben denselben section_type
effective_section_type = next((cb.section_type for cb in curr_blocks if cb.section_type), None)
effective_block_id = next((cb.block_id for cb in curr_blocks if cb.block_id), None)
sections.append({
"text": "\n\n".join([x.text for x in curr_blocks]),
"meta": curr_blocks[0],
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading",
"section_type": effective_section_type,
"block_id": effective_block_id
})
curr_blocks = []
for b in blocks:
if b.kind == "heading" and b.level <= split_level:
# Heading-basierter Split
_flush_section()
if curr_blocks:
sections.append({
"text": "\n\n".join([x.text for x in curr_blocks]),
"meta": curr_blocks[0],
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
})
curr_blocks = [b]
else:
curr_blocks.append(b)
_flush_section()
if curr_blocks:
sections.append({
"text": "\n\n".join([x.text for x in curr_blocks]),
"meta": curr_blocks[0],
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
})
# --- SCHRITT 2: Verarbeitung der Queue ---
queue = list(sections)
current_chunk_text = ""
# WP-26 v1.0: Erweitert um section_type und block_id
current_meta = {"title": None, "path": "/", "section_type": None, "block_id": None}
current_meta = {"title": None, "path": "/"}
# Bestimmung des Modus: Hard-Split wenn smart_edge=False ODER strict=True
is_hard_split_mode = (not smart_edge) or (strict)
@@ -107,9 +83,6 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
if not current_chunk_text:
current_meta["title"] = item["meta"].section_title
current_meta["path"] = item["meta"].section_path
# WP-26 v1.0: section_type und block_id aus Item übernehmen
current_meta["section_type"] = item.get("section_type")
current_meta["block_id"] = item.get("block_id")
# FALL A: HARD SPLIT MODUS (WP-24c v4.2.5: Strict-Mode ohne Carry-Over)
if is_hard_split_mode:
@@ -117,23 +90,18 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
# Kein Carry-Over erlaubt, auch nicht für leere Überschriften
if current_chunk_text:
# Flashe vorherigen Chunk
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
current_chunk_text = ""
# Neue Sektion: Initialisiere Meta
current_meta["title"] = item["meta"].section_title
current_meta["path"] = item["meta"].section_path
# WP-26 v1.0: section_type und block_id aus Item übernehmen
current_meta["section_type"] = item.get("section_type")
current_meta["block_id"] = item.get("block_id")
# WP-24c v4.2.5: Auch leere Sektionen werden als separater Chunk erstellt
# (nur Überschrift, kein Inhalt)
if item.get("is_empty", False):
# Leere Sektion: Nur Überschrift als Chunk
_emit(item_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(item_text, current_meta["title"], current_meta["path"])
else:
# Normale Sektion: Prüfe auf Token-Limit
if estimate_tokens(item_text) > max_tokens:
@@ -145,54 +113,21 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
while sents:
s = sents.pop(0); slen = estimate_tokens(s)
if take_len + slen > target and take_sents:
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
take_sents = [s]; take_len = slen
else:
take_sents.append(s); take_len += slen
if take_sents:
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
else:
# Sektion passt: Direkt als Chunk
_emit(item_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(item_text, current_meta["title"], current_meta["path"])
current_chunk_text = ""
continue
# FALL B: SMART MODE (Regel 1-3)
# WP-26 v1.1: Prüfe auf Section-Type-Wechsel AUCH in Schritt 2
# Wenn sich der section_type zwischen current_meta und item ändert, muss gesplittet werden
item_section_type = item.get("section_type")
current_section_type_meta = current_meta.get("section_type")
# Section-Type-Wechsel: Von None zu einem Typ ODER von einem Typ zu einem anderen
is_section_type_change_step2 = (
current_chunk_text and # Es gibt bereits Content
(
# Wechsel von None zu einem Typ
(current_section_type_meta is None and item_section_type is not None) or
# Wechsel von einem Typ zu None
(current_section_type_meta is not None and item_section_type is None) or
# Wechsel zwischen verschiedenen Typen
(current_section_type_meta is not None and item_section_type is not None
and current_section_type_meta != item_section_type)
)
)
if is_section_type_change_step2:
# WP-26 v1.1: Section-Type-Wechsel erzwingt Split
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
current_chunk_text = ""
# Reset Meta für nächsten Chunk
current_meta["title"] = item["meta"].section_title
current_meta["path"] = item["meta"].section_path
current_meta["section_type"] = item_section_type
current_meta["block_id"] = item.get("block_id")
combined_text = (current_chunk_text + "\n\n" + item_text).strip() if current_chunk_text else item_text
combined_est = estimate_tokens(combined_text)
@@ -202,8 +137,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
else:
if current_chunk_text:
# Regel 2: Flashen an Sektionsgrenze, Item zurücklegen
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
current_chunk_text = ""
queue.insert(0, item)
else:
@@ -218,8 +152,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
sents.insert(0, s); break
take_sents.append(s); take_len += slen
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
if sents:
remainder = " ".join(sents)
@@ -227,69 +160,31 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
if header_prefix and not remainder.startswith(header_prefix):
remainder = header_prefix + "\n\n" + remainder
# Carry-Over: Rest wird vorne in die Queue geschoben
# WP-26 v1.0: section_type und block_id weitergeben
queue.insert(0, {"text": remainder, "meta": item["meta"], "is_split": True,
"section_type": item.get("section_type"), "block_id": item.get("block_id")})
queue.insert(0, {"text": remainder, "meta": item["meta"], "is_split": True})
if current_chunk_text:
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
current_meta["section_type"], current_meta["block_id"])
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
return chunks
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
"""
Standard-Sliding-Window für flache Texte ohne Sektionsfokus.
WP-26 v1.0: Erweitert um section_type und block_id Weitergabe.
WP-26 v1.3: Parser propagiert section_type rückwirkend - vereinfachte Logik.
"""
"""Standard-Sliding-Window für flache Texte ohne Sektionsfokus."""
target = config.get("target", 400); max_tokens = config.get("max", 600)
chunks: List[Chunk] = []; buf: List[RawBlock] = []
current_section_type = None # Tracking des aktuellen section_type
def _flush_buffer():
"""Hilfsfunktion zum Flushen des Buffers."""
nonlocal buf, current_section_type
if not buf:
return
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
win = _create_win(context_prefix, buf[0].section_title, txt)
# WP-26 v1.3: section_type wird bereits vom Parser rückwirkend propagiert
effective_section_type = next((b.section_type for b in buf if b.section_type), None)
effective_block_id = next((b.block_id for b in buf if b.block_id), None)
chunks.append(Chunk(
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
text=txt, window=win, token_count=sum(estimate_tokens(x.text) for x in buf),
section_title=buf[0].section_title, section_path=buf[0].section_path,
neighbors_prev=None, neighbors_next=None,
section_type=effective_section_type, block_id=effective_block_id
))
buf = []
current_section_type = effective_section_type
for b in blocks:
b_tokens = estimate_tokens(b.text)
curr_tokens = sum(estimate_tokens(x.text) for x in buf) if buf else 0
block_section_type = b.section_type
# WP-26 v1.3: Prüfe auf Section-Type-Wechsel
# Da der Parser section_type rückwirkend setzt, haben alle Blöcke einer
# Heading-Sektion denselben section_type. Ein Wechsel bedeutet neue Sektion.
is_section_type_change = (
buf and # Es gibt bereits Blöcke im Buffer
current_section_type != block_section_type # Typ hat sich geändert
)
# Flush wenn: Token-Limit überschritten ODER Section-Type-Wechsel
if (curr_tokens + b_tokens > max_tokens and buf) or is_section_type_change:
_flush_buffer()
if curr_tokens + b_tokens > max_tokens and buf:
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
win = _create_win(context_prefix, buf[0].section_title, txt)
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=curr_tokens, section_title=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
buf = []
buf.append(b)
# Update section_type
if block_section_type:
current_section_type = block_section_type
# Letzten Buffer flushen
_flush_buffer()
if buf:
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
win = _create_win(context_prefix, buf[0].section_title, txt)
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=estimate_tokens(txt), section_title=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
return chunks
+2 -113
View File
@@ -24,7 +24,7 @@ DESCRIPTION: Hauptlogik zur Kanten-Aggregation und De-Duplizierung.
- Chunk-Scope gewinnt zwingend über Note-Scope (außer explicit:note_zone)
- Confidence-Werte: candidate_pool explicit:callout = 1.0, globaler Scan = 0.7
- Key-Generierung gehärtet für konsistente Deduplizierung
VERSION: 4.4.0 (WP-26 v1.4: Automatische Backlinks für Intra-Note-Edges)
VERSION: 4.3.1 (WP-24c: Präzisions-Priorität)
STATUS: Active
"""
import re
@@ -32,14 +32,8 @@ import logging
from typing import List, Optional, Dict, Tuple, Set
from .graph_utils import (
_get, _edge, _mk_edge_id, _dedupe_seq, parse_link_target,
PROVENANCE_PRIORITY, load_types_registry, get_edge_defaults_for,
get_typical_edge_for # WP-26 v1.1: Für automatische Intra-Note-Edges
PROVENANCE_PRIORITY, load_types_registry, get_edge_defaults_for
)
# WP-26 v1.4: Für automatische Backlinks bei Intra-Note-Edges
try:
from app.services.edge_registry import registry as edge_registry
except ImportError:
edge_registry = None
from .graph_extractors import (
extract_typed_relations, extract_callout_relations, extract_wikilinks
)
@@ -651,53 +645,6 @@ def build_edges_for_note(
"edge_id": _mk_edge_id("prev", next_id, cid, "chunk"),
"provenance": "structure", "rule_id": "structure:order", "confidence": PROVENANCE_PRIORITY["structure:order"]
}))
# 1b) WP-26 v1.1: Automatische Intra-Note-Edges zwischen Sektionen mit unterschiedlichen Typen
# Wenn sich der section_type zwischen aufeinanderfolgenden Chunks ändert,
# wird eine semantische Kante basierend auf graph_schema.md erstellt.
for idx, ch in enumerate(chunks):
if idx >= len(chunks) - 1:
continue # Kein nächster Chunk
cid = _get(ch, "chunk_id", "id")
next_ch = chunks[idx + 1]
next_id = _get(next_ch, "chunk_id", "id")
if not cid or not next_id:
continue
# Hole die effective_types der Chunks
# WP-26 v1.1: section_type oder note_type (effective_type)
current_section_type = ch.get("section_type")
next_section_type = next_ch.get("section_type")
current_type = current_section_type or ch.get("type") or note_type
next_type = next_section_type or next_ch.get("type") or note_type
# Prüfe, ob es einen Section-Type-Wechsel gibt
# Nur wenn beide einen expliziten section_type haben oder sich die effective_types unterscheiden
is_section_change = (
(current_section_type is not None or next_section_type is not None) and
current_type != next_type
)
if is_section_change:
# Ermittle den passenden Edge-Typ aus graph_schema.md
edge_kind = get_typical_edge_for(current_type, next_type)
logger.debug(f"WP-26 Intra-Note-Edge: {current_type} -> {next_type} = {edge_kind}")
# Erstelle die automatische Edge (Forward-Richtung)
edges.append(_edge(edge_kind, "chunk", cid, next_id, note_id, {
"chunk_id": cid,
"edge_id": _mk_edge_id(edge_kind, cid, next_id, "chunk"),
"provenance": "rule",
"rule_id": "inferred:section_transition",
"source_hint": "schema_default",
"confidence": PROVENANCE_PRIORITY.get("schema_default", 0.85),
"is_internal": True, # Explizit als Intra-Note-Edge markieren
"virtual": True, # WP-26 v1.4: Automatisch generierte Section-Transitions sind virtuell
"section_transition": f"{current_type}->{next_type}" # Debug-Info
}))
# 2) Inhaltliche Kanten (Explicit & Candidate Pool)
reg = load_types_registry()
@@ -1058,62 +1005,4 @@ def build_edges_for_note(
final_edges.append(winner)
# WP-26 v1.4: Automatische Backlinks für Intra-Note-Edges (Chunk-Level)
# Erstelle inverse Edges für alle Intra-Note-Edges, wenn noch nicht vorhanden
if edge_registry:
# Erstelle Set aller existierenden Edge-Keys für schnelle Lookup
existing_edge_keys: Set[Tuple[str, str, str, Optional[str]]] = set()
for e in final_edges:
source = e.get("source_id", "")
target = e.get("target_id", "")
kind = e.get("kind", "")
target_section = e.get("target_section")
existing_edge_keys.add((source, target, kind, target_section))
# Durchlaufe alle Edges und erstelle Backlinks für Intra-Note-Edges
backlinks_to_add: List[dict] = []
for e in final_edges:
is_internal = e.get("is_internal", False)
scope = e.get("scope", "chunk")
source_id = e.get("source_id", "")
target_id = e.get("target_id", "")
kind = e.get("kind", "")
target_section = e.get("target_section")
# Nur Intra-Note-Edges auf Chunk-Level berücksichtigen
if not is_internal or scope != "chunk":
continue
# Prüfe, ob bereits ein inverser Edge existiert
inv_kind = edge_registry.get_inverse(kind) if edge_registry else None
if not inv_kind:
continue # Kein inverser Edge-Type verfügbar
# Prüfe, ob inverser Edge bereits existiert
inv_key = (target_id, source_id, inv_kind, None) # Backlink hat keine target_section
if inv_key in existing_edge_keys:
continue # Backlink bereits vorhanden
# Erstelle automatischen Backlink
backlink_edge = _edge(inv_kind, "chunk", target_id, source_id, note_id, {
"chunk_id": target_id, # Backlink geht vom Target-Chunk aus
"edge_id": _mk_edge_id(inv_kind, target_id, source_id, "chunk"),
"provenance": "rule",
"rule_id": "derived:intra_note_backlink",
"source_hint": "automatic_backlink",
"confidence": PROVENANCE_PRIORITY.get("derived:backlink", 0.8),
"is_internal": True,
"virtual": True, # WP-26 v1.4: Automatisch generierte Backlinks sind virtuell
"original_edge_kind": kind # Debug-Info: Welcher Edge-Type wurde invertiert
})
backlinks_to_add.append(backlink_edge)
existing_edge_keys.add(inv_key) # Verhindere Duplikate
logger.debug(f"WP-26 Backlink erstellt: {target_id} --[{inv_kind}]--> {source_id} (Original: {kind})")
# Füge Backlinks zu final_edges hinzu
if backlinks_to_add:
final_edges.extend(backlinks_to_add)
logger.info(f"WP-26: {len(backlinks_to_add)} automatische Backlinks für Intra-Note-Edges erstellt")
return final_edges
+3 -56
View File
@@ -5,56 +5,18 @@ DESCRIPTION: In-Memory Repräsentation eines Graphen für Scoring und Analyse.
WP-15c Update: Erhalt von Metadaten (target_section, provenance)
für präzises Retrieval-Reasoning.
WP-24c v4.1.0: Scope-Awareness und Section-Filtering Support.
WP-26 v1.0: is_internal-Boost für Intra-Note-Edges.
VERSION: 1.4.0 (WP-26: Intra-Note-Edge-Boost)
VERSION: 1.3.0 (WP-24c: Gold-Standard v4.1.0)
STATUS: Active
"""
import os
import math
from functools import lru_cache
from collections import defaultdict
from typing import Dict, List, Optional, DefaultDict, Any, Set
from qdrant_client import QdrantClient
try:
import yaml
except ImportError:
yaml = None
# Lokale Paket-Imports
from .graph_weights import EDGE_BASE_WEIGHTS, calculate_edge_weight
from .graph_db_adapter import fetch_edges_from_qdrant
import logging
logger = logging.getLogger(__name__)
@lru_cache
def get_edge_scoring_config() -> Dict[str, float]:
"""
WP-26 v1.0: Lädt Edge-Scoring-Konfiguration aus retriever.yaml.
Returns:
Dict mit internal_edge_boost und external_edge_boost
"""
defaults = {
"internal_edge_boost": 1.2, # +20% Boost für Intra-Note-Edges
"external_edge_boost": 1.0 # Standard für Inter-Note-Edges
}
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
if yaml and os.path.exists(config_path):
try:
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
edge_scoring = data.get("edge_scoring", {})
defaults["internal_edge_boost"] = float(edge_scoring.get("internal_edge_boost", defaults["internal_edge_boost"]))
defaults["external_edge_boost"] = float(edge_scoring.get("external_edge_boost", defaults["external_edge_boost"]))
except Exception as e:
logger.warning(f"Edge-Scoring-Konfiguration konnte nicht geladen werden: {e}")
return defaults
class Subgraph:
"""
Leichtgewichtiger Subgraph mit Adjazenzlisten & Kennzahlen.
@@ -74,39 +36,24 @@ class Subgraph:
"""
Fügt eine Kante hinzu und aktualisiert Indizes.
WP-15c: Speichert das vollständige Payload für den Explanation Layer.
WP-26 v1.0: Wendet is_internal-Boost auf Intra-Note-Edges an.
"""
src = e.get("source")
tgt = e.get("target")
kind = e.get("kind")
# Basis-Gewicht aus Payload oder Edge-Weights
base_weight = e.get("weight", EDGE_BASE_WEIGHTS.get(kind, 0.0))
# WP-26 v1.0: is_internal-Boost anwenden
is_internal = e.get("is_internal", False)
edge_scoring = get_edge_scoring_config()
if is_internal:
weight_multiplier = edge_scoring["internal_edge_boost"]
else:
weight_multiplier = edge_scoring["external_edge_boost"]
final_weight = base_weight * weight_multiplier
# Das gesamte Payload wird als Kanten-Objekt behalten
# Wir stellen sicher, dass alle relevanten Metadaten vorhanden sind
edge_data = {
"source": src,
"target": tgt,
"kind": kind,
"weight": final_weight,
"weight": e.get("weight", EDGE_BASE_WEIGHTS.get(kind, 0.0)),
"provenance": e.get("provenance", "rule"),
"confidence": e.get("confidence", 1.0),
"target_section": e.get("target_section"), # Essentiell für Präzision
"is_super_edge": e.get("is_super_edge", False),
"virtual": e.get("virtual", False), # WP-24c v4.1.0: Für Authority-Priorisierung
"chunk_id": e.get("chunk_id"), # WP-24c v4.1.0: Für RAG-Kontext
"is_internal": is_internal # WP-26 v1.0: Flag für Debugging
"chunk_id": e.get("chunk_id") # WP-24c v4.1.0: Für RAG-Kontext
}
owner = e.get("note_id")
+11 -334
View File
@@ -12,87 +12,28 @@ STATUS: Active
import os
import uuid
import hashlib
from typing import Dict, Iterable, List, Optional, Set, Any, Tuple
from typing import Iterable, List, Optional, Set, Any, Tuple
try:
import yaml
except ImportError:
yaml = None
# WP-26 v1.0: Provenance-Literale auf valide EdgeDTO-Werte reduziert
# Legacy-Prioritäten für interne Verarbeitung (werden zu source_hint gemappt)
# WP-15b: Prioritäten-Ranking für die De-Duplizierung von Kanten unterschiedlicher Herkunft
PROVENANCE_PRIORITY = {
# Explizite Kanten (provenance: "explicit")
"explicit:wikilink": 1.00,
"inline:rel": 0.95,
"callout:edge": 0.90,
"explicit:callout": 0.90,
"explicit:note_scope": 1.00,
"explicit:note_zone": 1.00,
# Regel-basierte Kanten (provenance: "rule")
"derived:backlink": 0.90,
"edge_defaults": 0.70,
"schema_default": 0.85,
"inferred:section_transition": 0.85, # WP-26 v1.1: Automatische Section-Übergänge
# Struktur-Kanten (provenance: "structure")
"explicit:callout": 0.90, # WP-24c v4.2.7: Callout-Kanten aus candidate_pool
"semantic_ai": 0.90, # Validierte KI-Kanten
"structure:belongs_to": 1.00,
"structure:order": 0.95,
# KI-generierte Kanten (provenance: "smart")
"semantic_ai": 0.90,
"global_pool": 0.80,
"structure:order": 0.95, # next/prev
"explicit:note_scope": 1.00,
"explicit:note_zone": 1.00, # WP-24c v4.2.0: Note-Scope Zonen (höchste Priorität)
"derived:backlink": 0.90,
"edge_defaults": 0.70 # Heuristik basierend auf types.yaml
}
# WP-26 v1.0: Mapping von internen Provenance-Werten zu EdgeDTO-konformen Literalen
PROVENANCE_TO_DTO = {
# explicit
"explicit:wikilink": ("explicit", "wikilink"),
"explicit:callout": ("explicit", "callout"),
"explicit:note_scope": ("explicit", "note_scope"),
"explicit:note_zone": ("explicit", "note_zone"),
"inline:rel": ("explicit", "inline_rel"),
"callout:edge": ("explicit", "callout"),
"explicit": ("explicit", None),
# rule
"derived:backlink": ("rule", "backlink"),
"edge_defaults": ("rule", "edge_defaults"),
"schema_default": ("rule", "schema_default"),
"inferred:schema": ("rule", "schema_default"),
"inferred:section_transition": ("rule", "schema_default"), # WP-26 v1.1
"rule": ("rule", None),
# structure
"structure:belongs_to": ("structure", "belongs_to"),
"structure:order": ("structure", "order"),
"structure": ("structure", None),
# smart
"semantic_ai": ("smart", None),
"global_pool": ("smart", "global_pool"),
"smart": ("smart", None),
}
def normalize_provenance(internal_provenance: str) -> Tuple[str, Optional[str]]:
"""
WP-26 v1.0: Normalisiert interne Provenance-Werte zu EdgeDTO-konformen Literalen.
Args:
internal_provenance: Interner Provenance-String (z.B. "explicit:callout")
Returns:
Tuple (provenance, source_hint) mit validen EdgeDTO-Werten
"""
if internal_provenance in PROVENANCE_TO_DTO:
return PROVENANCE_TO_DTO[internal_provenance]
# Fallback: Versuche Präfix-Matching
if internal_provenance.startswith("explicit"):
return ("explicit", internal_provenance.split(":")[-1] if ":" in internal_provenance else None)
if internal_provenance.startswith("structure"):
return ("structure", internal_provenance.split(":")[-1] if ":" in internal_provenance else None)
if internal_provenance.startswith("rule") or internal_provenance.startswith("derived"):
return ("rule", internal_provenance.split(":")[-1] if ":" in internal_provenance else None)
# Default: explicit ohne source_hint
return ("explicit", None)
# ---------------------------------------------------------------------------
# Pfad-Auflösung (Integration der .env Umgebungsvariablen)
# ---------------------------------------------------------------------------
@@ -131,12 +72,6 @@ def parse_link_target(raw: str, current_note_id: Optional[str] = None) -> Tuple[
Trennt einen Obsidian-Link [[Target#Section]] in seine Bestandteile Target und Section.
Behandelt Self-Links (z.B. [[#Ziele]]), indem die aktuelle note_id eingesetzt wird.
WP-26 v1.1: Extrahiert Block-ID aus Section-Strings.
- Wenn Section "^block-id" enthält, wird nur der Block-ID-Teil extrahiert
- Beispiel: "📖 Diagnose: Glioblastom ^kontext" -> section = "kontext"
- Beispiel: "^learning" -> section = "learning"
- Beispiel: " ^sit" (nur Block-ID) -> section = "sit"
Returns:
Tuple (target_id, target_section)
"""
@@ -147,16 +82,6 @@ def parse_link_target(raw: str, current_note_id: Optional[str] = None) -> Tuple[
target = parts[0].strip()
section = parts[1].strip() if len(parts) > 1 else None
# WP-26 v1.1: Block-ID-Extraktion aus Section
# Wenn die Section ein "^" enthält, extrahiere nur den Block-ID-Teil
if section and "^" in section:
# Finde den ^block-id Teil
import re
block_id_match = re.search(r'\^([a-zA-Z0-9_-]+)', section)
if block_id_match:
# Ersetze die gesamte Section durch nur die Block-ID
section = block_id_match.group(1)
# Spezialfall: Self-Link innerhalb derselben Datei
if not target and section and current_note_id:
target = current_note_id
@@ -198,15 +123,7 @@ def _mk_edge_id(kind: str, s: str, t: str, scope: str, target_section: Optional[
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
"""
Konstruiert ein standardisiertes Kanten-Payload für Qdrant.
WP-26 v1.0: Erweitert um is_internal Flag und Provenance-Normalisierung.
Args:
kind: Kantentyp (z.B. "derives", "caused_by")
scope: Granularität ("chunk" oder "note")
source_id: ID der Quelle (Chunk oder Note)
target_id: ID des Ziels (Chunk oder Note)
note_id: ID der Note (für Kontext)
extra: Zusätzliche Payload-Felder
Wird von graph_derive_edges.py benötigt.
"""
pl = {
"kind": kind,
@@ -217,24 +134,8 @@ def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, e
"note_id": note_id,
"virtual": False # Standardmäßig explizit, solange nicht anders in Phase 2 gesetzt
}
# WP-26 v1.0: is_internal Flag berechnen
# Intra-Note-Edge: Source und Target gehören zur gleichen Note
source_note = source_id.split("#")[0] if "#" in source_id else source_id
target_note = target_id.split("#")[0] if "#" in target_id else target_id
pl["is_internal"] = (source_note == target_note) or (source_note == note_id and target_note == note_id)
if extra:
pl.update(extra)
# WP-26 v1.0: Provenance normalisieren, falls vorhanden
if "provenance" in extra:
internal_prov = extra["provenance"]
dto_prov, source_hint = normalize_provenance(internal_prov)
pl["provenance"] = dto_prov
if source_hint:
pl["source_hint"] = source_hint
return pl
# ---------------------------------------------------------------------------
@@ -273,228 +174,4 @@ def get_edge_defaults_for(note_type: Optional[str], reg: dict) -> List[str]:
if isinstance(v, dict) and isinstance(v.get("edge_defaults"), list):
return [str(x) for x in v["edge_defaults"] if isinstance(x, str)]
return []
# ---------------------------------------------------------------------------
# WP-26 v1.1: Graph-Schema Parser für automatische Edge-Typ-Ableitung
# ---------------------------------------------------------------------------
# Cache für geladenes Schema (vermeidet mehrfaches Parsen)
_GRAPH_SCHEMA_CACHE: Optional[Dict[str, Dict[str, List[str]]]] = None
# WP-26 v1.3: Erweitertes Schema mit prohibited edges
_GRAPH_SCHEMA_FULL_CACHE: Optional[Dict[str, Dict[str, Dict[str, List[str]]]]] = None
def load_graph_schema() -> Dict[str, Dict[str, List[str]]]:
"""
WP-26 v1.1: Parst das graph_schema.md und extrahiert Typical Edge-Types.
Das Schema hat folgendes Format:
## Source: `experience`
| Target-Note-type | Typical Edge-Types | Prohibited Edge-Types |
| :--- | :--- | :--- |
| `event` | `caused_by` | `consists_of` |
Returns:
Dict[source_type, Dict[target_type, List[typical_edges]]]
Beispiel: {"experience": {"event": ["caused_by"], "insight": ["resulted_in"]}}
"""
global _GRAPH_SCHEMA_CACHE
if _GRAPH_SCHEMA_CACHE is not None:
return _GRAPH_SCHEMA_CACHE
# Nutze das erweiterte Schema und extrahiere nur typical
full_schema = load_graph_schema_full()
schema: Dict[str, Dict[str, List[str]]] = {}
for source_type, targets in full_schema.items():
schema[source_type] = {}
for target_type, edge_info in targets.items():
schema[source_type][target_type] = edge_info.get("typical", [])
_GRAPH_SCHEMA_CACHE = schema
return schema
def load_graph_schema_full() -> Dict[str, Dict[str, Dict[str, List[str]]]]:
"""
WP-26 v1.3: Parst das graph_schema.md und extrahiert sowohl Typical als auch Prohibited Edge-Types.
Returns:
Dict[source_type, Dict[target_type, {"typical": [...], "prohibited": [...]}]]
Beispiel: {"experience": {"event": {"typical": ["caused_by"], "prohibited": ["consists_of"]}}}
"""
global _GRAPH_SCHEMA_FULL_CACHE
if _GRAPH_SCHEMA_FULL_CACHE is not None:
return _GRAPH_SCHEMA_FULL_CACHE
import re
import logging
logger = logging.getLogger(__name__)
schema_path = get_schema_path()
# Versuche verschiedene Pfade
paths_to_try = [
schema_path,
os.path.join(os.getcwd(), "config", "graph_schema.md"),
os.path.join(os.path.dirname(__file__), "..", "..", "..", "config", "graph_schema.md"),
]
# Falls MINDNET_OBSIDIAN_DICTIONARY gesetzt ist, nutze diesen Pfad
obsidian_dict = os.getenv("MINDNET_OBSIDIAN_DICTIONARY")
if obsidian_dict:
paths_to_try.insert(0, os.path.join(obsidian_dict, "graph_schema.md"))
content = None
for path in paths_to_try:
if os.path.isfile(path):
try:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
logger.debug(f"Graph-Schema geladen von: {path}")
break
except Exception as e:
logger.warning(f"Fehler beim Laden von {path}: {e}")
if not content:
logger.warning("Graph-Schema nicht gefunden. Fallback auf leeres Schema.")
_GRAPH_SCHEMA_FULL_CACHE = {}
return _GRAPH_SCHEMA_FULL_CACHE
schema: Dict[str, Dict[str, Dict[str, List[str]]]] = {}
current_source = None
# Regex für Source-Header: ## Source: `experience`
source_pattern = re.compile(r'^##\s+Source:\s*`(\w+)`', re.IGNORECASE)
# Regex für Tabellen-Zeile: | `event` | `caused_by` | `consists_of` |
# oder | `event` | `caused_by`, `resulted_in` | - |
table_row_pattern = re.compile(
r'^\|\s*`(\w+)`\s*\|\s*([^|]+)\s*\|\s*([^|]*)\s*\|'
)
edge_pattern = re.compile(r'`(\w+)`')
for line in content.split('\n'):
stripped = line.strip()
# Prüfe auf Source-Header
source_match = source_pattern.match(stripped)
if source_match:
current_source = source_match.group(1).lower()
if current_source not in schema:
schema[current_source] = {}
continue
# Prüfe auf Tabellen-Zeile (nur wenn wir einen Source haben)
if current_source:
row_match = table_row_pattern.match(stripped)
if row_match:
target_type = row_match.group(1).lower()
typical_edges_raw = row_match.group(2).strip()
prohibited_edges_raw = row_match.group(3).strip()
# Parse die Edge-Types
typical_edges = edge_pattern.findall(typical_edges_raw)
prohibited_edges = edge_pattern.findall(prohibited_edges_raw)
schema[current_source][target_type] = {
"typical": typical_edges,
"prohibited": prohibited_edges
}
logger.info(f"Graph-Schema (full) geladen: {len(schema)} Source-Types")
_GRAPH_SCHEMA_FULL_CACHE = schema
return schema
def get_topology_info(source_type: str, target_type: str) -> Dict[str, List[str]]:
"""
WP-26 v1.3: Ermittelt Typical und Prohibited Edge-Types für ein Typ-Paar.
Args:
source_type: Typ der Quell-Sektion (z.B. "experience")
target_type: Typ der Ziel-Sektion (z.B. "insight")
Returns:
Dict mit "typical" und "prohibited" Listen
Beispiel: {"typical": ["resulted_in"], "prohibited": ["solves"]}
"""
schema = load_graph_schema_full()
source_lower = source_type.lower() if source_type else "default"
target_lower = target_type.lower() if target_type else "any"
result = {"typical": [], "prohibited": []}
# 1. Exakter Match
if source_lower in schema and target_lower in schema[source_lower]:
return schema[source_lower][target_lower]
# 2. Fallback auf "any" Target
if source_lower in schema and "any" in schema[source_lower]:
return schema[source_lower]["any"]
# 3. Fallback auf "default" Source
if "default" in schema:
if target_lower in schema["default"]:
return schema["default"][target_lower]
if "any" in schema["default"]:
return schema["default"]["any"]
# 4. Absoluter Fallback: alles erlaubt
return {"typical": ["related_to", "references"], "prohibited": []}
def get_typical_edge_for(source_type: str, target_type: str) -> Optional[str]:
"""
WP-26 v1.1: Ermittelt den ersten "Typical Edge-Type" für ein Typ-Paar.
Args:
source_type: Typ der Quell-Sektion (z.B. "experience")
target_type: Typ der Ziel-Sektion (z.B. "insight")
Returns:
Der erste Typical Edge-Type (z.B. "resulted_in") oder None
"""
schema = load_graph_schema()
source_lower = source_type.lower() if source_type else "default"
target_lower = target_type.lower() if target_type else "any"
# 1. Exakter Match
if source_lower in schema:
source_rules = schema[source_lower]
if target_lower in source_rules:
edges = source_rules[target_lower]
if edges:
return edges[0]
# 2. Fallback auf "any" Target
if "any" in source_rules:
edges = source_rules["any"]
if edges:
return edges[0]
# 3. Fallback auf "default" Source
if "default" in schema:
default_rules = schema["default"]
if target_lower in default_rules:
edges = default_rules[target_lower]
if edges:
return edges[0]
if "any" in default_rules:
edges = default_rules["any"]
if edges:
return edges[0]
# 4. Absoluter Fallback
return "related_to"
def clear_graph_schema_cache():
"""
WP-26 v1.1: Löscht den Cache für das Graph-Schema.
Nützlich für Tests oder wenn das Schema neu geladen werden soll.
WP-26 v1.3: Löscht auch den erweiterten Schema-Cache.
"""
global _GRAPH_SCHEMA_CACHE, _GRAPH_SCHEMA_FULL_CACHE
_GRAPH_SCHEMA_CACHE = None
_GRAPH_SCHEMA_FULL_CACHE = None
return []
+4 -30
View File
@@ -3,8 +3,7 @@ FILE: app/core/ingestion/ingestion_chunk_payload.py
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
Fix v2.4.3: Integration der zentralen Registry (WP-14) für konsistente Defaults.
WP-24c v4.3.0: candidate_pool wird explizit übernommen für Chunk-Attribution.
WP-26 v1.0: Erweiterung um effective_type (section_type || note_type) und note_type-Feld.
VERSION: 2.5.0 (WP-26 v1.0)
VERSION: 2.4.4 (WP-24c v4.3.0)
STATUS: Active
"""
from __future__ import annotations
@@ -92,35 +91,14 @@ def make_chunk_payloads(note: Dict[str, Any], note_path: str, chunks_from_chunke
section = getattr(ch, "section_title", "") if not is_dict else ch.get("section", "")
# WP-24c v4.3.0: candidate_pool muss erhalten bleiben für Chunk-Attribution
candidate_pool = getattr(ch, "candidate_pool", []) if not is_dict else ch.get("candidate_pool", [])
# WP-26 v1.0: Section-Type für typ-spezifische Sektionen
section_type = getattr(ch, "section_type", None) if not is_dict else ch.get("section_type")
# WP-26 v1.0: Block-ID für Intra-Note-Links
block_id = getattr(ch, "block_id", None) if not is_dict else ch.get("block_id")
# WP-26 v1.0: Effektiver Typ = section_type || note_type (FA-03)
effective_type = section_type if section_type else note_type
# WP-26 v1.0: retriever_weight basiert auf effektivem Typ (FA-09b)
# Wenn section_type vorhanden, nutze dessen retriever_weight
effective_rw = rw
if section_type:
effective_rw = _resolve_val(section_type, reg, "retriever_weight", rw)
try:
effective_rw = float(effective_rw)
except:
effective_rw = rw
pl: Dict[str, Any] = {
"note_id": nid or fm.get("id"),
"chunk_id": cid,
"title": title,
"index": int(index),
"ord": int(index) + 1,
# WP-26 v1.0: type enthält den effektiven Typ (section_type || note_type)
"type": effective_type,
# WP-26 v1.0: note_type ist immer der ursprüngliche Note-Typ (für Filterung)
"note_type": note_type,
"type": note_type,
"tags": tags,
"text": text,
"window": window,
@@ -129,13 +107,9 @@ def make_chunk_payloads(note: Dict[str, Any], note_path: str, chunks_from_chunke
"section": section,
"path": note_path,
"source_path": kwargs.get("file_path") or note_path,
# WP-26 v1.0: retriever_weight basiert auf effektivem Typ
"retriever_weight": effective_rw,
"retriever_weight": rw,
"chunk_profile": cp,
"candidate_pool": candidate_pool, # WP-24c v4.3.0: Kritisch für Chunk-Attribution
# WP-26 v1.0: Optionale Felder für Section-Type-Tracking
"section_type": section_type, # Expliziter Section-Type (oder None)
"block_id": block_id, # Block-ID für Intra-Note-Links (oder None)
"candidate_pool": candidate_pool # WP-24c v4.3.0: Kritisch für Chunk-Attribution
}
# Audit: Cleanup Pop (Vermeidung von redundanten Alias-Feldern)
+1 -26
View File
@@ -41,7 +41,7 @@ from app.services.llm_service import LLMService
# Package-Interne Imports (Refactoring WP-14)
from .ingestion_utils import load_type_registry, resolve_note_type, get_chunk_config_by_profile
from .ingestion_db import fetch_note_payload, artifacts_missing, purge_artifacts, is_explicit_edge_present
from .ingestion_validation import validate_edge_candidate, validate_edge_against_schema
from .ingestion_validation import validate_edge_candidate
from .ingestion_note_payload import make_note_payload
from .ingestion_chunk_payload import make_chunk_payloads
@@ -621,31 +621,6 @@ class IngestionService:
v_edge["target_section"] = target_section
self.symmetry_buffer.append(v_edge)
# WP-26 v1.3: Schema-Validierung für Intra-Note-Edges (FA-12)
# Prüfe is_internal Edges gegen graph_schema.md
if explicit_edges:
chunks_by_id = {c.get("chunk_id", c.get("id", "")): c for c in chunk_pls}
schema_validated_edges = []
schema_rejected_count = 0
for e in explicit_edges:
is_valid, updated_edge = validate_edge_against_schema(
edge=e,
chunks_by_id=chunks_by_id,
strict_mode=False # Im normalen Modus: atypische Edges erlaubt mit reduzierter Confidence
)
if is_valid:
schema_validated_edges.append(updated_edge)
else:
schema_rejected_count += 1
logger.info(f"🚫 [SCHEMA-VALIDATION] Edge abgelehnt: {e.get('source_id')} -> {e.get('target_id')} ({e.get('kind')})")
if schema_rejected_count > 0:
logger.info(f"📊 [SCHEMA-VALIDATION] {schema_rejected_count} Intra-Note-Edges aufgrund von Schema-Verletzungen abgelehnt")
explicit_edges = schema_validated_edges
# DB Upsert
if purge_before and old_payload: purge_artifacts(self.client, self.prefix, note_id)
+2 -123
View File
@@ -3,145 +3,24 @@ FILE: app/core/ingestion/ingestion_validation.py
DESCRIPTION: WP-15b semantische Validierung von Kanten gegen den LocalBatchCache.
WP-24c: Erweiterung um automatische Symmetrie-Generierung (Inverse Kanten).
WP-25b: Konsequente Lazy-Prompt-Orchestration (prompt_key + variables).
WP-26 v1.3: Schema-Validierung für Intra-Note-Edges gegen graph_schema.md.
VERSION: 3.1.0 (WP-26: Intra-Note-Edge Schema-Validation)
VERSION: 3.0.0 (WP-24c: Symmetric Edge Management)
STATUS: Active
FIX:
- WP-24c: Integration der EdgeRegistry zur dynamischen Inversions-Ermittlung.
- WP-24c: Implementierung von validate_and_symmetrize für bidirektionale Graphen.
- WP-25b: Beibehaltung der hierarchischen Prompt-Resolution und Modell-Spezi-Logik.
- WP-26: FA-12 Schema-Validierung gegen effektiven Chunk-Typ.
"""
import logging
from typing import Dict, Any, Optional, List, Tuple
from typing import Dict, Any, Optional, List
from app.core.parser import NoteContext
# Import der neutralen Bereinigungs-Logik zur Vermeidung von Circular Imports
from app.core.registry import clean_llm_text
# WP-24c: Zugriff auf das dynamische Vokabular
from app.services.edge_registry import registry as edge_registry
# WP-26 v1.3: Graph-Schema für Validierung
from app.core.graph.graph_utils import get_topology_info
logger = logging.getLogger(__name__)
# ==============================================================================
# WP-26 v1.3: Schema-Validierung für Intra-Note-Edges (FA-12)
# ==============================================================================
def validate_intra_note_edge(
edge: Dict[str, Any],
source_chunk: Dict[str, Any],
target_chunk: Dict[str, Any],
strict_mode: bool = False
) -> Tuple[bool, float, Optional[str]]:
"""
WP-26 v1.3 (FA-12): Validiert eine Intra-Note-Edge gegen das graph_schema.md.
Verwendet den EFFEKTIVEN Typ (section_type || note_type) beider Chunks.
Args:
edge: Das Edge-Dict mit "kind", "source_id", "target_id"
source_chunk: Chunk-Payload der Quelle mit "type" (effektiver Typ)
target_chunk: Chunk-Payload des Ziels mit "type" (effektiver Typ)
strict_mode: Wenn True, werden atypische Edges abgelehnt (nicht nur gewarnt)
Returns:
Tuple (is_valid, confidence, reason)
- is_valid: True wenn die Edge erlaubt ist
- confidence: Angepasste Confidence (0.7 für atypische, 0.0 für prohibited)
- reason: Optional Begründung für Ablehnung/Warnung
"""
# Effektive Typen extrahieren (section_type hat Vorrang vor note_type)
source_type = source_chunk.get("type") or source_chunk.get("note_type") or "default"
target_type = target_chunk.get("type") or target_chunk.get("note_type") or "default"
edge_kind = edge.get("kind", "related_to")
# Schema-Lookup
topology = get_topology_info(source_type, target_type)
typical_edges = topology.get("typical", [])
prohibited_edges = topology.get("prohibited", [])
# 1. Prüfung: Ist die Edge verboten?
if edge_kind in prohibited_edges:
reason = f"Edge '{edge_kind}' von {source_type} → {target_type} ist verboten (prohibited)"
logger.warning(f"🚫 [SCHEMA-VALIDATION] {reason}")
return (False, 0.0, reason)
# 2. Prüfung: Ist die Edge typisch?
if edge_kind in typical_edges:
# Edge ist typisch → volle Confidence
logger.debug(f"✅ [SCHEMA-VALIDATION] Edge '{edge_kind}' von {source_type} → {target_type} ist typisch")
return (True, 1.0, None)
# 3. Edge ist atypisch (weder typical noch prohibited)
reason = f"Edge '{edge_kind}' von {source_type} → {target_type} ist atypisch (nicht in typical: {typical_edges})"
if strict_mode:
# Im Strict-Mode werden atypische Edges abgelehnt
logger.warning(f"⚠️ [SCHEMA-VALIDATION] {reason} - ABGELEHNT (strict_mode)")
return (False, 0.0, reason)
else:
# Im normalen Modus: Edge erlaubt, aber mit reduzierter Confidence (0.7)
logger.info(f"ℹ️ [SCHEMA-VALIDATION] {reason} - erlaubt mit reduzierter Confidence")
return (True, 0.7, reason)
def validate_edge_against_schema(
edge: Dict[str, Any],
chunks_by_id: Dict[str, Dict[str, Any]],
strict_mode: bool = False
) -> Tuple[bool, Dict[str, Any]]:
"""
WP-26 v1.3: Wrapper für die Schema-Validierung mit Chunk-Lookup.
Args:
edge: Das Edge-Dict
chunks_by_id: Dictionary von chunk_id → chunk_payload
strict_mode: Wenn True, werden atypische Edges abgelehnt
Returns:
Tuple (is_valid, updated_edge)
- is_valid: True wenn die Edge erlaubt ist
- updated_edge: Edge mit ggf. angepasster Confidence
"""
source_id = edge.get("source_id", "")
target_id = edge.get("target_id", "")
is_internal = edge.get("is_internal", False)
# Nur Intra-Note-Edges validieren
if not is_internal:
return (True, edge)
# Chunks nachschlagen
source_chunk = chunks_by_id.get(source_id, {})
target_chunk = chunks_by_id.get(target_id, {})
# Wenn Chunks nicht gefunden → Edge erlauben (Integrität vor Präzision)
if not source_chunk or not target_chunk:
logger.debug(f"[SCHEMA-VALIDATION] Chunks nicht gefunden für {source_id} / {target_id} - Edge erlaubt")
return (True, edge)
# Schema-Validierung durchführen
is_valid, confidence, reason = validate_intra_note_edge(
edge=edge,
source_chunk=source_chunk,
target_chunk=target_chunk,
strict_mode=strict_mode
)
if not is_valid:
return (False, edge)
# Confidence anpassen wenn nötig
updated_edge = edge.copy()
if confidence < 1.0:
original_confidence = edge.get("confidence", 1.0)
updated_edge["confidence"] = min(original_confidence, confidence)
updated_edge["schema_validation_note"] = reason
return (True, updated_edge)
async def validate_edge_candidate(
chunk_text: str,
edge: Dict,
+14 -40
View File
@@ -2,40 +2,21 @@ import logging
import os
from logging.handlers import RotatingFileHandler
# Umgebungsvariablen für Log-Begrenzung (weniger Zeilen, bessere Auswertbarkeit)
# LOG_LEVEL: INFO | WARNING | ERROR | DEBUG (Default: INFO, oder DEBUG wenn DEBUG=true)
# LOG_MAX_BYTES: Max. Größe einer Log-Datei in Bytes (Default: 1MB)
# LOG_BACKUP_COUNT: Anzahl rotierter Backups (Default: 2)
_LOG_LEVEL_MAP = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
}
# Laute Bibliotheken: nur WARNING+ in Datei/Konsole, reduziert Zeilen deutlich
_NOISY_LOGGERS = ("uvicorn", "uvicorn.access", "httpx", "httpcore", "qdrant_client")
def setup_logging(log_level: int = None):
"""
Konfiguriert das Logging-System mit File- und Console-Handler.
WP-24c v4.4.0-DEBUG: Unterstützt DEBUG-Level für End-to-End Tracing.
Log-Auswertbarkeit: Rotation und LOG_LEVEL begrenzen Dateigröße/Zeilen.
Args:
log_level: Optionales Log-Level (logging.DEBUG, logging.INFO, etc.)
Falls nicht gesetzt: LOG_LEVEL env, sonst DEBUG env, sonst INFO.
Falls nicht gesetzt, wird aus DEBUG Umgebungsvariable gelesen.
"""
# 1. Log-Level bestimmen (LOG_LEVEL hat Vorrang vor DEBUG)
# 1. Log-Level bestimmen
if log_level is None:
env_level = (os.getenv("LOG_LEVEL") or "").strip().lower()
if env_level and env_level in _LOG_LEVEL_MAP:
log_level = _LOG_LEVEL_MAP[env_level]
else:
debug_mode = os.getenv("DEBUG", "false").lower() == "true"
log_level = logging.DEBUG if debug_mode else logging.INFO
# WP-24c v4.4.0-DEBUG: Unterstützung für DEBUG-Level via Umgebungsvariable
debug_mode = os.getenv("DEBUG", "false").lower() == "true"
log_level = logging.DEBUG if debug_mode else logging.INFO
# 2. Log-Verzeichnis erstellen (falls nicht vorhanden)
log_dir = "logs"
if not os.path.exists(log_dir):
@@ -49,31 +30,24 @@ def setup_logging(log_level: int = None):
datefmt='%Y-%m-%d %H:%M:%S'
)
# 4. Rotation: kleinere Dateien = weniger Zeilen pro Datei, bessere Auswertbarkeit
max_bytes = int(os.getenv("LOG_MAX_BYTES", str(1 * 1024 * 1024))) # Default 1 MB
backup_count = int(os.getenv("LOG_BACKUP_COUNT", "2"))
# 4. File Handler: Schreibt in Datei (max. 5MB pro Datei, behält 5 Backups)
file_handler = RotatingFileHandler(
log_file, maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8'
log_file, maxBytes=5*1024*1024, backupCount=5, encoding='utf-8'
)
file_handler.setFormatter(formatter)
file_handler.setLevel(log_level)
file_handler.setLevel(log_level) # WP-24c v4.4.0-DEBUG: Respektiert log_level
# 5. Stream Handler: Schreibt weiterhin auf die Konsole
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(log_level)
console_handler.setLevel(log_level) # WP-24c v4.4.0-DEBUG: Respektiert log_level
# 6. Root Logger konfigurieren
logging.basicConfig(
level=log_level,
handlers=[file_handler, console_handler],
force=True
force=True # Überschreibt bestehende Konfiguration
)
# 7. Laute Bibliotheken drosseln (weniger Zeilen bei uvicorn/httpx/qdrant)
for name in _NOISY_LOGGERS:
logging.getLogger(name).setLevel(logging.WARNING)
level_name = logging.getLevelName(log_level)
logging.info(f"📝 Logging initialized (Level: {level_name}). File: {log_file}, maxBytes={max_bytes}, backups={backup_count}")
level_name = "DEBUG" if log_level == logging.DEBUG else "INFO"
logging.info(f"📝 Logging initialized (Level: {level_name}). Writing to {log_file}")
+13 -56
View File
@@ -3,8 +3,7 @@ FILE: app/core/retrieval/retriever.py
DESCRIPTION: Haupt-Schnittstelle für die Suche. Orchestriert Vektorsuche und Graph-Expansion.
WP-15c Update: Note-Level Diversity Pooling & Super-Edge Aggregation.
WP-24c v4.1.0: Gold-Standard - Scope-Awareness, Section-Filtering, Authority-Priorisierung.
WP-26 v1.0: Konfigurierbare Aggregation (note/chunk Level).
VERSION: 0.9.0 (WP-26: Aggregation-Level)
VERSION: 0.8.0 (WP-24c: Gold-Standard v4.1.0)
STATUS: Active
DEPENDENCIES: app.config, app.models.dto, app.core.database*, app.core.graph_adapter
"""
@@ -35,39 +34,8 @@ from qdrant_client.http import models as rest
# Mathematische Engine importieren
from app.core.retrieval.retriever_scoring import get_weights, compute_wp22_score
try:
import yaml
except ImportError:
yaml = None
logger = logging.getLogger(__name__)
def _get_aggregation_config() -> Dict[str, Any]:
"""
WP-26 v1.0: Lädt Aggregation-Konfiguration aus retriever.yaml.
Returns:
Dict mit level ("note" oder "chunk") und max_chunks_per_note
"""
defaults = {
"level": "note", # "note" (Default) oder "chunk"
"max_chunks_per_note": 3 # Limit bei "note"-Level
}
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
if yaml and os.path.exists(config_path):
try:
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
aggregation = data.get("aggregation", {})
defaults["level"] = str(aggregation.get("level", defaults["level"])).lower()
defaults["max_chunks_per_note"] = int(aggregation.get("max_chunks_per_note", defaults["max_chunks_per_note"]))
except Exception as e:
logger.warning(f"Aggregation-Konfiguration konnte nicht geladen werden: {e}")
return defaults
# ==============================================================================
# 1. CORE HELPERS & CONFIG LOADERS
# ==============================================================================
@@ -348,33 +316,22 @@ def _build_hits_from_semantic(
# 1. Sortierung nach finalem mathematischen Score
enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True)
# 2. WP-26 v1.0: Konfigurierbare Aggregation (Note-Level oder Chunk-Level)
aggregation_config = _get_aggregation_config()
aggregation_level = aggregation_config["level"]
max_chunks_per_note = aggregation_config["max_chunks_per_note"]
# 2. WP-15c: Note-Level Diversity Pooling
# Wir behalten pro note_id nur den Hit mit dem höchsten total_score.
# Dies verhindert, dass 10 Chunks derselben Note andere KeyNotes verdrängen.
unique_note_hits = []
seen_notes = set()
if aggregation_level == "chunk":
# WP-26 v1.0: Chunk-Level - alle Chunks individuell ranken (keine Deduplizierung)
logger.debug(f"📊 [AGGREGATION] Chunk-Level: Alle {len(enriched_sorted)} Chunks individuell")
pooled_hits = enriched_sorted
else:
# WP-15c: Note-Level Diversity Pooling (Default)
# Behalten pro note_id bis zu max_chunks_per_note Hits
pooled_hits = []
note_chunk_count: Dict[str, int] = defaultdict(int)
for item in enriched_sorted:
_, _, payload, _ = item
note_id = str(payload.get("note_id", "unknown"))
for item in enriched_sorted:
_, _, payload, _ = item
note_id = str(payload.get("note_id", "unknown"))
if note_chunk_count[note_id] < max_chunks_per_note:
pooled_hits.append(item)
note_chunk_count[note_id] += 1
logger.debug(f"📊 [AGGREGATION] Note-Level: {len(pooled_hits)} Chunks (max {max_chunks_per_note}/Note)")
if note_id not in seen_notes:
unique_note_hits.append(item)
seen_notes.add(note_id)
# 3. Begrenzung auf top_k nach dem Diversity-Pooling
limited_hits = pooled_hits[: max(1, top_k)]
limited_hits = unique_note_hits[: max(1, top_k)]
results: List[QueryHit] = []
for pid, s_score, pl, dbg in limited_hits:
+9 -11
View File
@@ -46,18 +46,16 @@ class EdgeDTO(BaseModel):
target: str
weight: float
direction: Literal["out", "in", "undirected"] = "out"
# WP-26 v1.0: Provenance auf valide Literale reduziert (EdgeDTO-Constraint)
# Detail-Informationen werden über source_hint transportiert
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
# WP-26 v1.0: Neues Feld für Detail-Informationen zur Herkunft
source_hint: Optional[Literal[
"callout", "wikilink", "inline_rel", "schema_default", "note_scope",
"note_zone", "belongs_to", "order", "backlink", "edge_defaults", "global_pool"
]] = None
# WP-24c v4.5.3: Erweiterte Provenance-Werte für Chunk-Aware Edges
# Unterstützt alle tatsächlich verwendeten Provenance-Typen im System
provenance: Optional[Literal[
"explicit", "rule", "smart", "structure",
"explicit:callout", "explicit:wikilink", "explicit:note_zone", "explicit:note_scope",
"inline:rel", "callout:edge", "semantic_ai", "structure:belongs_to", "structure:order",
"derived:backlink", "edge_defaults", "global_pool"
]] = "explicit"
confidence: float = 1.0
target_section: Optional[str] = None
# WP-26 v1.0: Flag für Intra-Note-Edges
is_internal: Optional[bool] = None
target_section: Optional[str] = None
# --- Request Models ---
+1 -13
View File
@@ -1,16 +1,4 @@
version: 1.3
# WP-26 Phase 2: Aggregation-Level für Retrieval
# - note: Beste Chunk pro Note (Default, wie bisher)
# - chunk: Alle Chunks individuell ranken
aggregation:
level: note # "note" (default) oder "chunk"
max_chunks_per_note: 3 # Optional: Limit bei "note"-Level
# WP-26 Phase 2: Edge-Scoring mit Intra-Note-Boost
edge_scoring:
internal_edge_boost: 1.2 # +20% Boost für Intra-Note-Edges (is_internal=true)
external_edge_boost: 1.0 # Standard für Inter-Note-Edges
version: 1.2
scoring:
# W_sem: skaliert den Term (semantic_score * retriever_weight)
+1
View File
@@ -0,0 +1 @@
__pycache__/
+66
View File
@@ -0,0 +1,66 @@
# syntax=docker/dockerfile:1.7
#
# Mindnet-Image für API und Streamlit-UI (ein Image, Modus per CMD: api | ui | preflight).
# Build-Kontext ist das Repository-Root; die Allowlist steht in /.dockerignore.
#
# docker build -f deploy/Dockerfile -t mindnet:<git-sha> .
#
# Reproduzierbarkeit: Basis-Image per Digest, Abhängigkeiten per Hash-Lock
# (deploy/requirements.lock). Kein torch / sentence-transformers: Embeddings
# kommen ausschließlich von Ollama (nomic-embed-text, 768 Dimensionen).
ARG PYTHON_IMAGE=python:3.12-slim-bookworm@sha256:e697c81897302a4c4333bade000d98038fbb21eb064f8ee1fd42d02ebcd9d337
# --- Abhängigkeiten in ein isoliertes venv -----------------------------------
FROM ${PYTHON_IMAGE} AS deps
ENV PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1 \
PYTHONDONTWRITEBYTECODE=1
COPY deploy/requirements.lock /tmp/requirements.lock
RUN python -m venv /opt/venv \
&& /opt/venv/bin/pip install --require-hashes --no-deps -r /tmp/requirements.lock
# --- Laufzeit-Image -------------------------------------------------------------
FROM ${PYTHON_IMAGE} AS runtime
ARG MINDNET_UID=10001
ENV PATH=/opt/venv/bin:${PATH} \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONPATH=/app \
HOME=/tmp \
STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
RUN groupadd --system --gid ${MINDNET_UID} mindnet \
&& useradd --system --uid ${MINDNET_UID} --gid mindnet --no-create-home --shell /usr/sbin/nologin mindnet
COPY --from=deps /opt/venv /opt/venv
WORKDIR /app
# Code und Konfiguration gehören root und sind für den Laufzeitnutzer nur lesbar.
COPY app/ app/
COPY config/ config/
COPY scripts/ scripts/
COPY deploy/entrypoint.py deploy/healthcheck.py /opt/mindnet/
# Einzige beschreibbare Pfade (als Volumes gemountet): Logs und Laufzeitdaten.
RUN install -d -o mindnet -g mindnet -m 0750 /app/logs /app/data /app/data/logs
USER mindnet:mindnet
EXPOSE 8000 8501
ENTRYPOINT ["python", "/opt/mindnet/entrypoint.py"]
CMD ["api"]
# --- Test-Image (nur für nichtproduktive Läufe) ---------------------------------
FROM runtime AS test
USER root
COPY deploy/requirements-test.lock /tmp/requirements-test.lock
RUN pip install --no-cache-dir --require-hashes --no-deps -r /tmp/requirements-test.lock
COPY tests/ tests/
COPY deploy/ deploy/
COPY .dockerignore ./
COPY .gitea/workflows/ .gitea/workflows/
USER mindnet:mindnet
ENTRYPOINT []
CMD ["python", "-m", "pytest", "-q", "-p", "no:cacheprovider", \
"tests/test_container_preflight.py", "tests/test_container_connectivity.py", \
"tests/test_container_appenv.py"]
+96
View File
@@ -0,0 +1,96 @@
"""
FILE: deploy/appenv.py
DESCRIPTION: Liest die unveränderte .env der systemd-Instanz und leitet daraus ab, was
Compose für denselben Betrieb im Container braucht:
- Vault: Host-Pfad und Einhängepunkt so, dass MINDNET_VAULT_ROOT der .env im
Container auf dasselbe Verzeichnis zeigt (relativ -> unter /app, wie unter
dem WorkingDirectory der systemd-Unit)
- erwartetes Collection-Präfix für den Smoke-Test
Prüft außerdem, dass die Container-Datei nur Container-Angaben enthält und
damit keine Anwendungskonfiguration überschreibt.
Nur Standardbibliothek (läuft direkt auf dem Runner).
VERSION: 1.0.0
STATUS: Active
USAGE: appenv.py <systemd.env> <container.env> -> Shell-Zuweisungen auf stdout
"""
from __future__ import annotations
import posixpath
import shlex
import sys
from pathlib import Path
# Einzige Schlüssel, die die Container-Datei setzen darf.
CONTAINER_KEYS = {
"MINDNET_API_PORT", "MINDNET_API_BIND", "MINDNET_UI_PORT", "MINDNET_UI_BIND",
"MINDNET_API_MEM_LIMIT", "MINDNET_UI_MEM_LIMIT", "MINDNET_ALLOW_CLOUD_EGRESS",
"MINDNET_VAULT_SENTINEL",
}
APP_WORKDIR = "/app"
DEFAULT_VAULT_ROOT = "./vault_master" # Default aus app/config.py
DEFAULT_PREFIX = "mindnet" # Default aus app/config.py
class AppEnvError(RuntimeError):
pass
def parse(path: str) -> dict[str, str]:
"""Einfacher dotenv-Parser (KEY=VALUE, optional 'export', Quotes, Kommentare)."""
values = {}
for raw in Path(path).read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
if line.startswith("export "):
line = line[len("export "):].lstrip()
key, value = (part.strip() for part in line.split("=", 1))
if len(value) >= 2 and value[0] in "\"'" and value[-1] == value[0]:
value = value[1:-1]
elif " #" in value:
value = value.split(" #", 1)[0].rstrip()
values[key] = value
return values
def vault_mount(app_env_path: str, values: dict[str, str]) -> tuple[str, str]:
root = values.get("MINDNET_VAULT_ROOT") or DEFAULT_VAULT_ROOT
if posixpath.isabs(root):
return posixpath.normpath(root), posixpath.normpath(root)
# systemd startet im Ordner der .env (WorkingDirectory), der Container in /app.
host_dir = posixpath.dirname(Path(app_env_path).as_posix())
return posixpath.normpath(posixpath.join(host_dir, root)), posixpath.normpath(posixpath.join(APP_WORKDIR, root))
def derive(app_env_path: str, container_env_path: str) -> dict[str, str]:
extra = sorted(set(parse(container_env_path)) - CONTAINER_KEYS)
if extra:
raise AppEnvError(
f"{container_env_path} darf nur Container-Angaben enthalten; "
f"Anwendungswerte gehören in {app_env_path}: {', '.join(extra)}"
)
values = parse(app_env_path)
host, target = vault_mount(app_env_path, values)
return {
"MINDNET_VAULT_HOST_PATH": host,
"MINDNET_VAULT_TARGET": target,
"MINDNET_EXPECTED_PREFIX": values.get("COLLECTION_PREFIX") or DEFAULT_PREFIX,
}
def main(argv: list[str]) -> int:
if len(argv) != 3:
print("Aufruf: appenv.py <systemd.env> <container.env>", file=sys.stderr)
return 2
try:
derived = derive(argv[1], argv[2])
except (OSError, AppEnvError) as e:
print(f"appenv: {e}", file=sys.stderr)
return 1
for key, value in derived.items():
print(f"{key}={shlex.quote(value)}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+98
View File
@@ -0,0 +1,98 @@
# Mindnet ENTWICKLUNG als Container: dieselbe Anwendung mit derselben Konfiguration
# wie die systemd-Dev-Instanz (8002/8502), parallel auf 8012/8512 zum Vergleich.
#
# Gestartet über deploy/deploy.sh dev. Zwei Dateien, beide nur auf dem Host:
# - MINDNET_APP_ENV_FILE: die unveränderte .env der systemd-Dev-Instanz
# - MINDNET_ENV_FILE: nur Container-Angaben (Ports, Bind-Adressen, Freigaben)
# Fest überschrieben wird nur, was im Container anders lauten muss: die Adressen
# der Host-Dienste (statt 127.0.0.1). Vault-Pfad und Präfix kommen aus der .env.
name: mindnet-dev
x-hardening: &hardening
image: mindnet:${MINDNET_IMAGE_TAG:-dev}
build:
context: ..
dockerfile: deploy/Dockerfile
target: runtime
env_file:
- ${MINDNET_APP_ENV_FILE:?MINDNET_APP_ENV_FILE auf die .env der systemd-Dev-Instanz setzen}
- ${MINDNET_ENV_FILE:-env/dev.env}
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
init: true
pids_limit: 256
restart: unless-stopped
extra_hosts: ["host.docker.internal:host-gateway"]
logging:
driver: json-file
options: {max-size: "10m", max-file: "3"}
networks: [mindnet-dev]
# Container-bedingte Werte; haben Vorrang vor beiden env-Dateien.
x-container-env: &container-env
MINDNET_ENV: dev
QDRANT_URL: http://host.docker.internal:6333
MINDNET_OLLAMA_URL: http://host.docker.internal:11434
VECTOR_DIM: "768"
MINDNET_EXPECTED_VECTOR_DIM: "768"
MINDNET_EXPECTED_EMBEDDING_MODEL: nomic-embed-text
MINDNET_VAULT_READONLY: "true"
services:
api:
<<: *hardening
command: ["api"]
environment:
<<: *container-env
volumes:
# Derselbe Vault wie systemd-Dev, eingehängt dort, wo MINDNET_VAULT_ROOT hinzeigt.
# Nur lesend, solange beide Instanzen parallel laufen.
- type: bind
source: ${MINDNET_VAULT_HOST_PATH:?wird von deploy/deploy.sh aus der .env abgeleitet}
target: ${MINDNET_VAULT_TARGET:?wird von deploy/deploy.sh aus der .env abgeleitet}
read_only: true
bind:
create_host_path: false
propagation: rslave
- logs:/app/logs
- data:/app/data
ports: ["${MINDNET_API_BIND:-127.0.0.1}:${MINDNET_API_PORT:-8012}:8000"]
mem_limit: ${MINDNET_API_MEM_LIMIT:-2g}
healthcheck:
test: ["CMD", "python", "/opt/mindnet/healthcheck.py", "api"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
ui:
<<: *hardening
command: ["ui"]
environment:
<<: *container-env
MINDNET_VAULT_REQUIRED: "false"
MINDNET_API_URL: http://api:8000
volumes:
- data:/app/data:ro
# Wie systemd (STREAMLIT_SERVER_ADDRESS=0.0.0.0): im LAN erreichbar.
ports: ["${MINDNET_UI_BIND:-0.0.0.0}:${MINDNET_UI_PORT:-8512}:8501"]
mem_limit: ${MINDNET_UI_MEM_LIMIT:-1g}
depends_on:
api: {condition: service_healthy}
healthcheck:
test: ["CMD", "python", "/opt/mindnet/healthcheck.py", "ui"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
volumes:
logs:
data:
networks:
mindnet-dev:
driver: bridge
+100
View File
@@ -0,0 +1,100 @@
# Mindnet PRODUKTION als Container (Vorlage, noch NICHT aktiv): dieselbe Anwendung
# mit derselben Konfiguration wie die systemd-Prod-Instanz (8001/8501), parallel auf
# 8011/8511 zum Vergleich. Umschaltung erst mit Freigabe (Gate G5).
#
# Gestartet über deploy/deploy.sh prod. Zwei Dateien, beide nur auf dem Host:
# - MINDNET_APP_ENV_FILE: die unveränderte .env der systemd-Prod-Instanz
# - MINDNET_ENV_FILE: nur Container-Angaben (Ports, Bind-Adressen, Freigaben)
# Fest überschrieben wird nur, was im Container anders lauten muss: die Adressen
# der Host-Dienste (statt 127.0.0.1). Vault-Pfad und Präfix kommen aus der .env.
# Vault nur lesend, bis R2 (Pfadsicherheit beim Speichern) behoben ist.
name: mindnet-prod
x-hardening: &hardening
image: mindnet:${MINDNET_IMAGE_TAG:?MINDNET_IMAGE_TAG setzen (z. B. prod-<commit>)}
build:
context: ..
dockerfile: deploy/Dockerfile
target: runtime
env_file:
- ${MINDNET_APP_ENV_FILE:?MINDNET_APP_ENV_FILE auf die .env der systemd-Prod-Instanz setzen}
- ${MINDNET_ENV_FILE:-env/prod.env}
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
init: true
pids_limit: 256
restart: unless-stopped
extra_hosts: ["host.docker.internal:host-gateway"]
logging:
driver: json-file
options: {max-size: "10m", max-file: "3"}
networks: [mindnet-prod]
# Container-bedingte Werte; haben Vorrang vor beiden env-Dateien.
x-container-env: &container-env
MINDNET_ENV: prod
QDRANT_URL: http://host.docker.internal:6333
MINDNET_OLLAMA_URL: http://host.docker.internal:11434
VECTOR_DIM: "768"
MINDNET_EXPECTED_VECTOR_DIM: "768"
MINDNET_EXPECTED_EMBEDDING_MODEL: nomic-embed-text
MINDNET_VAULT_READONLY: "true"
services:
api:
<<: *hardening
command: ["api"]
environment:
<<: *container-env
volumes:
# Derselbe Vault wie systemd-Prod, eingehängt dort, wo MINDNET_VAULT_ROOT hinzeigt.
# Nur lesend, solange beide Instanzen parallel laufen.
- type: bind
source: ${MINDNET_VAULT_HOST_PATH:?wird von deploy/deploy.sh aus der .env abgeleitet}
target: ${MINDNET_VAULT_TARGET:?wird von deploy/deploy.sh aus der .env abgeleitet}
read_only: true
bind:
create_host_path: false
propagation: rslave
- logs:/app/logs
- data:/app/data
ports: ["${MINDNET_API_BIND:-127.0.0.1}:${MINDNET_API_PORT:-8011}:8000"]
mem_limit: ${MINDNET_API_MEM_LIMIT:-2g}
healthcheck:
test: ["CMD", "python", "/opt/mindnet/healthcheck.py", "api"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
ui:
<<: *hardening
command: ["ui"]
environment:
<<: *container-env
MINDNET_VAULT_REQUIRED: "false"
MINDNET_API_URL: http://api:8000
volumes:
- data:/app/data:ro
# Wie systemd (STREAMLIT_SERVER_ADDRESS=0.0.0.0): im LAN erreichbar.
ports: ["${MINDNET_UI_BIND:-0.0.0.0}:${MINDNET_UI_PORT:-8511}:8501"]
mem_limit: ${MINDNET_UI_MEM_LIMIT:-1g}
depends_on:
api: {condition: service_healthy}
healthcheck:
test: ["CMD", "python", "/opt/mindnet/healthcheck.py", "ui"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
volumes:
logs:
data:
networks:
mindnet-prod:
driver: bridge
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
# Baut, prüft und startet einen Mindnet-Container-Stack. Genutzt von den
# Gitea-Workflows (develop -> dev, main -> prod) und für manuelle Deploys.
#
# MINDNET_APP_ENV_FILE=/home/llmadmin/mindnet_dev/.env # MINDNET_ENV_FILE=/home/llmadmin/docker/mindnet-dev/container.env deploy/deploy.sh dev
#
# MINDNET_APP_ENV_FILE ist die unveränderte .env der systemd-Instanz (gleiche Konfiguration),
# MINDNET_ENV_FILE enthält nur Container-Angaben (deploy/env/<env>.env.example).
#
# Ablauf (jeder Schritt bricht ab, bevor der laufende Stack angefasst wird):
# 1. Container-Tests im Test-Image, ohne Netzwerk (blockierend)
# 2. volle Testsuite ohne Netzwerk (informativ, bekannte Fehler siehe Migrationsplan)
# 3. Image bauen, Tag = Umgebung + Commit
# 4. preflight --live: Ollama/Qdrant erreichbar, Modelle, 768 Dimensionen, Vault (nur lesend)
# 5. up --wait (Healthchecks), danach smoke.py über die veröffentlichten Ports
# 6. Prod: bei Fehler Rückkehr zum letzten erfolgreichen Tag
#
# Beide Dateien liegen auf dem Host außerhalb von Git; im Verzeichnis der Container-Datei
# merkt sich das Skript den letzten erfolgreichen Image-Tag (last_good_tag).
set -euo pipefail
cd "$(dirname "$0")/.."
ENV="${1:-}"
case "$ENV" in
dev|prod) ;;
*) echo "Aufruf: deploy/deploy.sh dev|prod" >&2; exit 2 ;;
esac
: "${MINDNET_APP_ENV_FILE:?MINDNET_APP_ENV_FILE auf die .env der systemd-Instanz setzen}"
: "${MINDNET_ENV_FILE:?MINDNET_ENV_FILE auf die Container-Datei des Hosts setzen}"
for f in "$MINDNET_APP_ENV_FILE" "$MINDNET_ENV_FILE"; do
[ -f "$f" ] || { echo "env-Datei fehlt: $f" >&2; exit 1; }
done
export MINDNET_APP_ENV_FILE MINDNET_ENV_FILE
# Vault-Mount und Präfix aus der systemd-.env ableiten (gleiches Verzeichnis wie heute).
DERIVED="$(python3 deploy/appenv.py "$MINDNET_APP_ENV_FILE" "$MINDNET_ENV_FILE")"
eval "$DERIVED"
export MINDNET_VAULT_HOST_PATH MINDNET_VAULT_TARGET
PREFIX="$MINDNET_EXPECTED_PREFIX"
echo "$DERIVED"
SHA="$(git rev-parse --short=12 HEAD)"
export MINDNET_IMAGE_TAG="$ENV-$SHA"
LAST_GOOD="$(dirname "$MINDNET_ENV_FILE")/last_good_tag"
dc() { docker compose -f "deploy/compose.$ENV.yml" --env-file "$MINDNET_ENV_FILE" "$@"; }
step() { printf '\n=== %s\n' "$*"; }
show_logs() { dc ps || true; dc logs --tail 150 api ui || true; }
published() { dc port "$1" "$2" | head -n 1 | sed 's/^0\.0\.0\.0:/127.0.0.1:/'; }
smoke() {
python3 deploy/smoke.py --api "http://$(published api 8000)" --ui "http://$(published ui 8501)" \
--prefix "$PREFIX" --require-data
}
step "1/5 Container-Tests (ohne Netzwerk)"
docker build -f deploy/Dockerfile --target test -t "mindnet:test-$SHA" .
docker run --rm --network none "mindnet:test-$SHA"
step "2/5 Volle Testsuite (informativ, ohne Netzwerk)"
if ! docker run --rm --network none "mindnet:test-$SHA" \
python -m pytest tests -q -p no:cacheprovider --continue-on-collection-errors --basetemp=/tmp/pytest; then
echo "WARNUNG: Testsuite nicht grün. Bekannte Fehler: docs/05_Development/05_docker_migration_plan.md"
fi
docker image rm "mindnet:test-$SHA" >/dev/null || true
step "3/5 Image bauen ($MINDNET_IMAGE_TAG)"
dc build api ui
step "4/5 Preflight mit Erreichbarkeit (nur lesend)"
dc run --rm --no-deps api preflight --live
step "5/5 Start ($MINDNET_IMAGE_TAG) und Smoke"
if dc up -d --wait --no-build --remove-orphans && smoke; then
echo "$MINDNET_IMAGE_TAG" > "$LAST_GOOD"
echo "=== mindnet-$ENV läuft mit $MINDNET_IMAGE_TAG"
exit 0
fi
show_logs
PREV="$(cat "$LAST_GOOD" 2>/dev/null || true)"
if [ "$ENV" = prod ] && [ -n "$PREV" ] && [ "$PREV" != "$MINDNET_IMAGE_TAG" ]; then
step "Rollback auf $PREV"
export MINDNET_IMAGE_TAG="$PREV"
if dc up -d --wait --no-build --remove-orphans && smoke; then
echo "Rollback erfolgreich; Deploy von $ENV-$SHA ist trotzdem fehlgeschlagen."
else
show_logs
echo "ROLLBACK FEHLGESCHLAGEN, manueller Eingriff nötig." >&2
fi
fi
exit 1
+258
View File
@@ -0,0 +1,258 @@
"""
FILE: deploy/entrypoint.py
DESCRIPTION: Container-Entrypoint für Mindnet (API, UI, Preflight).
Prüft vor dem Start alle Annahmen, deren Verletzung still Daten
verfälschen oder Inhalte nach außen geben würde, und bricht sonst ab:
- Vektor-Dimension und Embedding-Modell (768 / nomic-embed-text)
- explizite Umgebung und Collection-Präfix (Dev nie auf Prod-Präfix)
- Vault: vorhanden, Sentinel lesbar (NAS gemountet), schreibgeschützt
- kein Cloud-LLM-Key ohne ausdrückliche Freigabe
- Dienst-URLs gesetzt und nicht auf den Container selbst (localhost)
Mit 'preflight --live' zusätzlich (nur lesend): Ollama und Qdrant
erreichbar, benötigte Modelle vorhanden, Dimensionen stimmen.
VERSION: 1.1.0
STATUS: Active
USAGE: entrypoint.py api | ui | preflight [--live]
"""
from __future__ import annotations
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
import yaml
CLOUD_KEYS = ("OPENROUTER_API_KEY", "GOOGLE_API_KEY")
CLOUD_EGRESS_ACK = "MINDNET_ALLOW_CLOUD_EGRESS"
SERVICE_URLS = ("MINDNET_OLLAMA_URL", "QDRANT_URL")
LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
class PreflightError(RuntimeError):
pass
def _flag(name: str, default: str) -> bool:
return os.getenv(name, default).strip().lower() == "true"
def check_environment() -> str:
env = os.getenv("MINDNET_ENV", "").strip()
if env not in {"dev", "prod"}:
raise PreflightError("MINDNET_ENV muss 'dev' oder 'prod' sein.")
prefix = os.getenv("COLLECTION_PREFIX", "").strip()
if not prefix:
# Ohne Präfix fällt die App still auf 'mindnet' (= Produktion) zurück.
raise PreflightError("COLLECTION_PREFIX muss explizit gesetzt sein.")
if env == "dev" and not prefix.endswith("_dev"):
raise PreflightError(f"Dev-Umgebung verlangt ein Präfix mit Suffix '_dev' (ist: '{prefix}').")
if env == "prod" and prefix.endswith("_dev"):
raise PreflightError(f"Prod-Umgebung mit Dev-Präfix '{prefix}'.")
return env
def _load_profiles(profiles_path: str | None = None) -> dict:
# Gleicher Pfad wie in der App (Settings kennt keinen Override dafür).
path = Path(profiles_path or "config/llm_profiles.yaml")
try:
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError) as e:
raise PreflightError(f"LLM-Profile nicht lesbar: {path} ({type(e).__name__}).") from None
return data.get("profiles") or {}
def check_embeddings(profiles_path: str | None = None) -> None:
expected_dim = int(os.getenv("MINDNET_EXPECTED_VECTOR_DIM", "768"))
expected_model = os.getenv("MINDNET_EXPECTED_EMBEDDING_MODEL", "nomic-embed-text")
# qdrant.py fällt ohne VECTOR_DIM auf 384 (MiniLM) zurück.
dim = os.getenv("VECTOR_DIM", "").strip()
if dim != str(expected_dim):
raise PreflightError(f"VECTOR_DIM muss {expected_dim} sein (ist: '{dim or 'nicht gesetzt'}').")
env_model = os.getenv("MINDNET_EMBEDDING_MODEL", "").strip()
if env_model and env_model != expected_model:
raise PreflightError(f"MINDNET_EMBEDDING_MODEL='{env_model}' weicht von '{expected_model}' ab.")
# Das Profil hat Vorrang vor der Umgebung; fehlt es, fällt der Client auf das Chat-Modell zurück.
profile = _load_profiles(profiles_path).get("embedding_expert") or {}
if profile.get("provider", "ollama") != "ollama" or profile.get("model") != expected_model:
raise PreflightError(f"Profil embedding_expert muss ollama/{expected_model} sein.")
if int(profile.get("dimensions") or 0) != expected_dim:
raise PreflightError(f"Profil embedding_expert muss dimensions={expected_dim} haben.")
def check_cloud_egress() -> None:
configured = [k for k in CLOUD_KEYS if os.getenv(k, "").strip()]
if configured and not _flag(CLOUD_EGRESS_ACK, "false"):
# Ohne Privacy Gateway würden Vault-Inhalte unmaskiert an Cloud-Provider gehen.
raise PreflightError(
f"Cloud-Keys gesetzt ({', '.join(configured)}), aber {CLOUD_EGRESS_ACK}=true fehlt. "
"Ohne Privacy Gateway gehen Vault-Inhalte unmaskiert an den Provider."
)
def _is_read_only_mount(path: Path) -> bool:
if not hasattr(os, "statvfs"):
return False # nicht prüfbar -> als beschreibbar behandeln (fail closed)
return bool(os.statvfs(path).f_flag & os.ST_RDONLY)
DEFAULT_VAULT_ROOT = "./vault_master" # Default aus app/config.py
def check_vault() -> None:
if not _flag("MINDNET_VAULT_REQUIRED", "true"):
return
root = Path(os.getenv("MINDNET_VAULT_ROOT") or DEFAULT_VAULT_ROOT)
if not root.is_dir():
raise PreflightError(f"Vault-Verzeichnis fehlt: '{root}'.")
# Ein ausgefallenes NAS hinterlässt einen leeren Mountpunkt.
try:
empty = next(root.iterdir(), None) is None
except OSError:
raise PreflightError(f"Vault '{root}' nicht lesbar (NAS nicht gemountet?).") from None
if empty:
raise PreflightError(f"Vault '{root}' ist leer (NAS nicht gemountet?).")
# Optional: zusätzlich eine bestimmte Datei verlangen (z. B. auf dem NAS-Vault).
sentinel_name = os.getenv("MINDNET_VAULT_SENTINEL", "").strip()
if sentinel_name:
sentinel = root / sentinel_name
try:
with sentinel.open("rb") as f:
f.read(1)
except OSError:
raise PreflightError(f"Vault-Sentinel nicht lesbar: '{sentinel}' (NAS nicht gemountet?).") from None
if _flag("MINDNET_VAULT_READONLY", "true") and not _is_read_only_mount(root):
raise PreflightError(f"Vault '{root}' ist nicht schreibgeschützt gemountet (':ro' erforderlich).")
def check_service_urls() -> None:
for name in SERVICE_URLS:
url = os.getenv(name, "").strip()
if not url:
# Die App fiele sonst still auf http://127.0.0.1:... zurück, also auf den Container selbst.
raise PreflightError(f"{name} muss explizit gesetzt sein.")
if urllib.parse.urlsplit(url).hostname in LOOPBACK_HOSTS:
raise PreflightError(
f"{name}='{url}' zeigt im Container auf den Container selbst. "
"Host-Dienste über host.docker.internal ansprechen."
)
def _fetch_json(url: str, payload: dict | None = None, headers: dict | None = None, timeout: float = 10):
"""GET (oder POST mit payload). Netzwerkfehler werden zu PreflightError, HTTPError bleibt erhalten."""
req = urllib.request.Request(
url, method="POST" if payload is not None else "GET",
data=json.dumps(payload).encode() if payload is not None else None,
headers={"Content-Type": "application/json", **(headers or {})},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
return json.load(res)
except urllib.error.HTTPError:
raise
except (urllib.error.URLError, OSError) as e:
hint = ""
if urllib.parse.urlsplit(url).hostname == "host.docker.internal":
hint = " Lauscht der Dienst auf dem Host nur an 127.0.0.1?"
raise PreflightError(f"{url} nicht erreichbar ({getattr(e, 'reason', e)}).{hint}") from None
except ValueError:
raise PreflightError(f"{url} liefert kein JSON.") from None
def required_ollama_models(profiles_path: str | None = None) -> set[str]:
models = {p["model"] for p in _load_profiles(profiles_path).values()
if isinstance(p, dict) and p.get("provider") == "ollama" and p.get("model")}
# Lokales Chat-Modell: Endpunkt der Fallback-Kette ohne Cloud-Keys (Review R4).
if os.getenv("MINDNET_LLM_MODEL", "").strip():
models.add(os.environ["MINDNET_LLM_MODEL"].strip())
return models
def _has_model(required: str, available: set[str]) -> bool:
return required in available or (":" not in required and f"{required}:latest" in available)
def check_live(profiles_path: str | None = None) -> None:
"""Laufzeitprüfung (nur lesend): Erreichbarkeit, Modelle, Embedding- und Collection-Dimension."""
expected_dim = int(os.getenv("MINDNET_EXPECTED_VECTOR_DIM", "768"))
ollama = os.getenv("MINDNET_OLLAMA_URL", "").rstrip("/")
model = os.getenv("MINDNET_EXPECTED_EMBEDDING_MODEL", "nomic-embed-text")
tags = _fetch_json(f"{ollama}/api/tags")
available = {m.get("name") for m in tags.get("models") or []}
missing = sorted(m for m in required_ollama_models(profiles_path) if not _has_model(m, available))
if missing:
raise PreflightError(f"Ollama ({ollama}) fehlen die Modelle: {', '.join(missing)}.")
embedding = _fetch_json(f"{ollama}/api/embeddings", {"model": model, "prompt": "preflight"}, timeout=30)
got = len(embedding.get("embedding") or [])
if got != expected_dim:
raise PreflightError(f"Ollama liefert {got} Dimensionen für '{model}', erwartet {expected_dim}.")
print(f"preflight: Ollama erreichbar ({ollama}), Modelle vorhanden, '{model}' = {got} Dimensionen.")
qdrant = os.getenv("QDRANT_URL", "").rstrip("/")
headers = {"api-key": os.environ["QDRANT_API_KEY"]} if os.getenv("QDRANT_API_KEY") else {}
try:
_fetch_json(f"{qdrant}/collections", headers=headers)
except urllib.error.HTTPError as e:
raise PreflightError(f"Qdrant ({qdrant}) antwortet mit HTTP {e.code}.") from None
prefix = os.getenv("COLLECTION_PREFIX", "")
for suffix in ("notes", "chunks"):
name = f"{prefix}_{suffix}"
try:
info = _fetch_json(f"{qdrant}/collections/{name}", headers=headers)
except urllib.error.HTTPError as e:
if e.code == 404:
print(f"preflight: Collection '{name}' existiert noch nicht.")
continue
raise PreflightError(f"Qdrant-Collection '{name}': HTTP {e.code}.") from None
vectors = info["result"]["config"]["params"]["vectors"]
sizes = [vectors["size"]] if "size" in vectors else [v["size"] for v in vectors.values()]
if any(s != expected_dim for s in sizes):
raise PreflightError(f"Collection '{name}' hat Dimension {sizes}, erwartet {expected_dim}.")
print(f"preflight: Qdrant erreichbar ({qdrant}), Collections '{prefix}_*' passen.")
def run_checks(mode: str) -> None:
check_environment()
check_embeddings()
check_cloud_egress()
if mode in {"api", "preflight"}:
check_service_urls()
check_vault()
COMMANDS = {
"api": ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"],
"ui": ["streamlit", "run", "app/frontend/ui.py", "--server.address", "0.0.0.0",
"--server.port", "8501", "--server.headless", "true", "--browser.gatherUsageStats", "false"],
}
def main(argv: list[str]) -> int:
mode = argv[1] if len(argv) > 1 else "api"
if mode not in {*COMMANDS, "preflight"}:
print(f"Unbekannter Modus '{mode}'. Erlaubt: api, ui, preflight [--live]", file=sys.stderr)
return 2
try:
run_checks(mode)
if mode == "preflight" and "--live" in argv:
check_live()
except PreflightError as e:
print(f"preflight: ABBRUCH: {e}", file=sys.stderr)
return 1
if mode == "preflight":
print("preflight: OK")
return 0
os.execvp(COMMANDS[mode][0], COMMANDS[mode])
return 0 # nicht erreichbar
if __name__ == "__main__":
sys.exit(main(sys.argv))
+2
View File
@@ -0,0 +1,2 @@
*.env
!*.env.example
+15
View File
@@ -0,0 +1,15 @@
# Mindnet DEV (Container): NUR Container-Angaben. Liegt auf dem Host außerhalb von Git.
# Die Anwendungskonfiguration kommt unverändert aus der .env der systemd-Instanz
# (MINDNET_APP_ENV_FILE im Workflow). deploy/appenv.py lehnt hier andere Schlüssel ab,
# damit diese Datei die Anwendungskonfiguration nicht überschreibt.
MINDNET_API_PORT=8012
# API ohne Authentisierung; die UI erreicht sie intern. Für Zugriff von außen auf 0.0.0.0 setzen.
MINDNET_API_BIND=127.0.0.1
MINDNET_UI_PORT=8512
MINDNET_UI_BIND=0.0.0.0
# Enthält die systemd-.env Cloud-Keys (OpenRouter/Gemini), startet der Container nur mit
# ausdrücklicher Bestätigung. true = gleiches Verhalten wie heute: Vault-Inhalte gehen
# ohne Privacy Gateway an den Cloud-Provider.
MINDNET_ALLOW_CLOUD_EGRESS=false
+15
View File
@@ -0,0 +1,15 @@
# Mindnet PROD (Container): NUR Container-Angaben. Liegt auf dem Host außerhalb von Git.
# Die Anwendungskonfiguration kommt unverändert aus der .env der systemd-Instanz
# (MINDNET_APP_ENV_FILE im Workflow). deploy/appenv.py lehnt hier andere Schlüssel ab,
# damit diese Datei die Anwendungskonfiguration nicht überschreibt.
MINDNET_API_PORT=8011
# API ohne Authentisierung; die UI erreicht sie intern. Für Zugriff von außen auf 0.0.0.0 setzen.
MINDNET_API_BIND=127.0.0.1
MINDNET_UI_PORT=8511
MINDNET_UI_BIND=0.0.0.0
# Enthält die systemd-.env Cloud-Keys (OpenRouter/Gemini), startet der Container nur mit
# ausdrücklicher Bestätigung. true = gleiches Verhalten wie heute: Vault-Inhalte gehen
# ohne Privacy Gateway an den Cloud-Provider.
MINDNET_ALLOW_CLOUD_EGRESS=false
+58
View File
@@ -0,0 +1,58 @@
# VORLAGE, NICHT AKTIV: liegt absichtlich nicht unter .gitea/workflows/.
# Aktivierung erst bei der Umschaltung (Gate G5, eigene Freigabe), und zwar im
# selben Commit, der .gitea/workflows/deploy.yml (systemd) entfernt:
# git rm .gitea/workflows/deploy.yml
# git mv deploy/gitea-workflows/deploy-prod.yml .gitea/workflows/deploy-prod.yml
# Sonst deployen bei jedem Push auf main beide Wege.
#
# Prod nur über Merge-Commit develop -> main (git merge --no-ff develop), wie bei Kansho.
# Ablauf, Abbruchbedingungen und Rollback: deploy/deploy.sh.
name: Deploy mindnet PROD (Container)
on:
push:
branches: [main]
workflow_dispatch:
concurrency:
# Gleiche Gruppe wie der systemd-Workflow: nie zwei Prod-Deploys gleichzeitig.
group: deploy-mindnet
cancel-in-progress: false
jobs:
deploy:
# Runner auf dem Zielhost (heute llm-node). Bei einem Umzug auf einen anderen
# Mini-PC nur das Label und die beiden Pfade anpassen.
runs-on: linux_host
env:
# Unveränderte Konfiguration der systemd-Prod-Instanz.
MINDNET_APP_ENV_FILE: /home/llmadmin/mindnet/.env
# Nur Container-Angaben (Vorlage: deploy/env/prod.env.example).
MINDNET_ENV_FILE: /home/llmadmin/docker/mindnet/container.env
steps:
# Ohne actions/checkout: kein Abruf von github.com (DNS/Internet auf dem Host
# nicht nötig). Holt genau den Commit des Pushes vom eigenen Gitea, mit Job-Token.
- name: Checkout
run: |
set -euo pipefail
git init -q .
git -c http.extraHeader="Authorization: token ${{ github.token }}" \
fetch -q --depth 1 "${{ github.server_url }}/${{ github.repository }}.git" "${{ github.sha }}"
git checkout -q --force FETCH_HEAD
git clean -q -ffdx
git log -1 --format='Checkout %H %s'
- name: Container-Datei beim ersten Lauf anlegen
run: |
set -euo pipefail
install -d -m 0750 "$(dirname "$MINDNET_ENV_FILE")"
if [ ! -f "$MINDNET_ENV_FILE" ]; then
install -m 0600 deploy/env/prod.env.example "$MINDNET_ENV_FILE"
echo "Container-Datei aus Vorlage angelegt: $MINDNET_ENV_FILE"
fi
docker version --format 'Docker {{.Server.Version}}'
docker compose version
- name: Test, Build, Preflight, Start, Smoke (Rollback bei Fehler)
run: bash deploy/deploy.sh prod
+44
View File
@@ -0,0 +1,44 @@
"""
FILE: deploy/healthcheck.py
DESCRIPTION: Docker-Healthcheck für API und UI.
API ist nur gesund, wenn /healthz antwortet UND der Vault-Sentinel
lesbar ist. Ein zur Laufzeit ausgefallenes NAS wird so als
'unhealthy' sichtbar, statt still auf einem leeren Mountpunkt zu laufen.
USAGE: healthcheck.py api | ui
"""
from __future__ import annotations
import os
import sys
import urllib.request
from pathlib import Path
URLS = {
"api": "http://127.0.0.1:8000/healthz",
"ui": "http://127.0.0.1:8501/_stcore/health",
}
def main(mode: str) -> int:
try:
with urllib.request.urlopen(URLS[mode], timeout=5) as res:
if res.status != 200:
return 1
except Exception as e:
print(f"health: {mode} nicht erreichbar ({type(e).__name__})")
return 1
if mode == "api" and os.getenv("MINDNET_VAULT_REQUIRED", "true").lower() == "true":
root = Path(os.getenv("MINDNET_VAULT_ROOT") or "./vault_master")
sentinel_name = os.getenv("MINDNET_VAULT_SENTINEL", "").strip()
try:
ok = (root / sentinel_name).is_file() if sentinel_name else next(root.iterdir(), None) is not None
except OSError:
ok = False
if not ok:
print(f"health: Vault leer oder nicht lesbar ({root})")
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "api"))
+2
View File
@@ -0,0 +1,2 @@
-c requirements.lock
pytest>=8.4.2
+28
View File
@@ -0,0 +1,28 @@
colorama==0.4.6 ; sys_platform == 'win32' \
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
# via
# -c requirements.lock
# pytest
iniconfig==2.3.0 \
--hash=sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730 \
--hash=sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12
# via pytest
packaging==26.0 \
--hash=sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4 \
--hash=sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529
# via
# -c requirements.lock
# pytest
pluggy==1.6.0 \
--hash=sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3 \
--hash=sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746
# via pytest
pygments==2.19.2 \
--hash=sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887 \
--hash=sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b
# via pytest
pytest==9.0.2 \
--hash=sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b \
--hash=sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11
# via -r requirements-test.in
+24
View File
@@ -0,0 +1,24 @@
# Laufzeit-Abhängigkeiten für die Container-Images (API + UI).
# Abgeleitet aus requirements.txt OHNE torch, sentence-transformers und pytest:
# - app/embeddings.py (MiniLM) wird von keinem eingebundenen Router importiert;
# Embeddings laufen über Ollama (embedding_expert, nomic-embed-text, 768 Dim.).
# - pytest steckt nur im Test-Target (requirements-test.in).
# Lock neu erzeugen: siehe docs/04_Operations/04_docker_deployment.md, Abschnitt "Lock".
fastapi>=0.116.1
uvicorn[standard]>=0.35.0
httpx>=0.28.1
qdrant-client>=1.15.1
pydantic>=2.11.7
numpy>=2.3.2
python-frontmatter>=1.1.0
markdown-it-py>=3.0.0
PyYAML>=6.0.2
python-slugify>=8.0.4
python-dotenv>=1.1.1
requests>=2.32.5
tqdm>=4.67.1
streamlit>=1.39.0
streamlit-agraph>=0.0.45
st-cytoscape
google-genai>=0.3.0
openai>=1.50.0
File diff suppressed because it is too large. Load diff
+113
View File
@@ -0,0 +1,113 @@
"""
FILE: deploy/smoke.py
DESCRIPTION: Nicht-schreibender Smoke-Test gegen einen laufenden Mindnet-Stack,
aus Sicht des Hosts über die veröffentlichten Ports. Nur Standardbibliothek,
läuft daher direkt auf dem Runner (python3), ohne venv.
- API /healthz: Status ok, erwartetes Collection-Präfix
- API /admin/stats: Vektorgröße 768; API erreicht Qdrant (Collection-Counts)
- UI /_stcore/health
--require-data (Prod): alle Collections vorhanden und Notes nicht leer.
VERSION: 1.0.0
STATUS: Active
USAGE: smoke.py --api http://127.0.0.1:8012 --ui http://127.0.0.1:8512 --prefix mindnet_dev [--require-data]
"""
from __future__ import annotations
import argparse
import json
import sys
import time
import urllib.error
import urllib.request
EXPECTED_VECTOR_SIZE = 768
class SmokeError(RuntimeError):
pass
def _get(url: str, timeout: float = 15) -> bytes:
try:
with urllib.request.urlopen(url, timeout=timeout) as res:
return res.read()
except urllib.error.HTTPError as e:
raise SmokeError(f"{url}: HTTP {e.code}") from None
except (urllib.error.URLError, OSError) as e:
raise SmokeError(f"{url} nicht erreichbar ({getattr(e, 'reason', e)})") from None
def _get_json(url: str) -> dict:
try:
return json.loads(_get(url))
except ValueError:
raise SmokeError(f"{url} liefert kein JSON") from None
def check_api(api: str, prefix: str, require_data: bool) -> list[str]:
"""Gibt Warnungen zurück; harte Fehler als SmokeError."""
health = _get_json(f"{api}/healthz")
if health.get("status") != "ok":
raise SmokeError(f"/healthz meldet {health.get('status')!r}")
if health.get("prefix") != prefix:
raise SmokeError(f"API nutzt Präfix {health.get('prefix')!r}, erwartet {prefix!r}")
stats = _get_json(f"{api}/admin/stats")
size = (stats.get("config") or {}).get("vector_size")
if size != EXPECTED_VECTOR_SIZE:
raise SmokeError(f"API-Vektorgröße {size}, erwartet {EXPECTED_VECTOR_SIZE}")
warnings = []
collections = stats.get("collections") or {}
for kind in ("notes", "chunks", "edges"):
entry = collections.get(kind) or {}
count = entry.get("count", -1)
if count < 0:
# -1: Collection fehlt oder Qdrant ist aus dem API-Container nicht erreichbar.
msg = f"Collection {entry.get('name', kind)!r} nicht lesbar (fehlt oder Qdrant nicht erreichbar)"
if require_data:
raise SmokeError(msg)
warnings.append(msg)
if require_data and (collections.get("notes") or {}).get("count", 0) <= 0:
raise SmokeError("Notes-Collection ist leer")
return warnings
def check_ui(ui: str) -> None:
body = _get(f"{ui}/_stcore/health").decode("utf-8", "replace").strip()
if body != "ok":
raise SmokeError(f"UI-Health meldet {body!r}")
def run(api: str, ui: str, prefix: str, require_data: bool = False, attempts: int = 1, delay: float = 5) -> int:
api, ui = api.rstrip("/"), ui.rstrip("/")
for attempt in range(1, attempts + 1):
try:
warnings = check_api(api, prefix, require_data)
check_ui(ui)
except SmokeError as e:
if attempt == attempts:
print(f"smoke: FEHLER: {e}", file=sys.stderr)
return 1
time.sleep(delay)
continue
for w in warnings:
print(f"smoke: WARNUNG: {w}")
print(f"smoke: OK (api={api}, ui={ui}, prefix={prefix})")
return 0
return 1
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("USAGE:")[0])
parser.add_argument("--api", required=True)
parser.add_argument("--ui", required=True)
parser.add_argument("--prefix", required=True)
parser.add_argument("--require-data", action="store_true")
parser.add_argument("--attempts", type=int, default=3)
args = parser.parse_args(argv)
return run(args.api, args.ui, args.prefix, args.require_data, args.attempts)
if __name__ == "__main__":
sys.exit(main())
+3 -21
View File
@@ -3,9 +3,9 @@ id: 01-authoring-guidelines
title: Authoring Guidelines – Handbuch für den Digitalen Zwilling
type: principle
status: stable
version: 1.4.0
version: 1.3.0
area: system_documentation
tags: [handbuch, authoring, methodik, obsidian, mindnet, best-practice, section_types, wp26]
tags: [handbuch, authoring, methodik, obsidian, mindnet, best-practice]
retriever_weight: 2.0
---
@@ -18,7 +18,7 @@ Dieses Handbuch ist dein primäres Werkzeug, um Wissen so zu strukturieren, dass
## ⚡ Die 6 Goldenen Regeln (TL;DR)
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Trenne z. B. „Meditation“ von „Mobility“.
2. **Explizite Typen:** Nutze den `type` im Frontmatter (z. B. `insight`, `experience`, `value`), um die mathematische Gewichtung zu steuern. **Section Types (WP-26):** Innerhalb einer Note können Abschnitte eigene Types haben (`> [!section] insight`), um präzisere semantische Verarbeitung zu ermöglichen.
2. **Explizite Typen:** Nutze den `type` im Frontmatter (z. B. `insight`, `experience`, `value`), um die mathematische Gewichtung zu steuern.
3. **H3-Hub-Pairing (NEU):** Nutze H3-Überschriften in Hubs, um spezifische Links und ihre Bedeutung (Edges) in isolierten Chunks für die KI zu fixieren, ohne die Obsidian-Graphen-Logik zu brechen.
4. **Werte & Ziele definieren:** Erstelle für jeden Kernwert eine eigene Notiz (`type: value`). Ohne explizite Maßstäbe kann die Decision Engine nicht in deinem Sinne abwägen.
5. **Emotionales Bridging:** Nutze Begriffe wie „Druck“, „Faszination“ oder „Angst“, um die Empathie-Ebene der KI zu aktivieren.
@@ -81,13 +81,6 @@ Nutze das kanonische Vokabular in `[!edge]` Callouts innerhalb der H3-Sektionen:
* **`part_of` / `gehört_zu`**: Bindet Details an einen übergeordneten Cluster oder Hub.
* **`guides` / `steuert`**: Prinzipien oder Werte, die eine Sektion oder ein Vorhaben leiten.
**Intra-Note-Edges (WP-26):** Für Verbindungen innerhalb derselben Note nutze Block-References:
```markdown
> [!edge] derives
> [[#^block-id]]
```
Dies erzeugt semantische Verbindungen zwischen Chunks derselben Note (`is_internal: true`).
### 4.2 Forward-Mapping (Strategische Lücken)
Setze bewusst Links auf Dateien, die noch nicht existieren (z. B. `[[Die beste Version meiner selbst]]`). Die KI erkennt diese Lücken und stellt proaktiv Fragen, um diese Felder gemeinsam mit dir zu füllen.
@@ -99,17 +92,6 @@ Setze bewusst Links auf Dateien, die noch nicht existieren (z. B. `[[Die beste V
**Ziel:** Den „Spiegel“ (Empathy) mit deiner Biografie kalibrieren.
* **Struktur:** Kontext (Was ist passiert?), Emotions-Check (Gefühle?), Lektion (Was gelernt?).
* **Deep-Edge:** Verknüpfe es immer mit einer Rolle: `[[rel:supports Meine Rollenlandkarte 2025#Vater]]`.
* **Section Types (WP-26):** Nutze unterschiedliche Section-Types für verschiedene Abschnitte:
```markdown
## Situation ^sit
> [!section] experience
## Reflexion ^ref
> [!section] insight
> [!edge] derives
> [[#^sit]]
```
Dies ermöglicht präzisere semantische Verarbeitung und Intra-Note-Verbindungen.
### 5.2 Eine Beobachtung festhalten (`type: insight`)
**Ziel:** Den „Berater“ (Decision) mit Mustern versorgen.
+3 -252
View File
@@ -1,10 +1,10 @@
---
doc_type: user_manual
audience: user, author
scope: vault, markdown, schema, agentic_validation, note_scope, section_types, intra_note_edges
scope: vault, markdown, schema, agentic_validation, note_scope
status: active
version: 4.6.0
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren. Inkludiert WP-24c Phase 3 Agentic Edge Validation, automatische Spiegelkanten, Note-Scope Zonen und WP-26 Section Types mit Intra-Note-Edges."
version: 4.5.8
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren. Inkludiert WP-24c Phase 3 Agentic Edge Validation, automatische Spiegelkanten und Note-Scope Zonen."
---
# Knowledge Design Manual
@@ -198,169 +198,6 @@ Damit dein System sauber bleibt, beachte diese Regeln:
---
## 4. Section Types & Intra-Note-Edges (WP-26) [NEU]
### 4.0 Übersicht: Section Types
**Section Types** ermöglichen es, innerhalb einer Note unterschiedliche Typen für verschiedene Abschnitte zu definieren. Dies erlaubt präzisere semantische Verarbeitung und Intra-Note-Verbindungen zwischen Chunks.
**Kernkonzept:**
- Eine Note hat einen **Note-Type** (im Frontmatter: `type: experience`)
- Abschnitte innerhalb der Note können einen eigenen **Section-Type** haben (z.B. `insight`, `decision`)
- Der **effektive Typ** eines Chunks ist: `section_type` falls vorhanden, sonst `note_type`
- Section Types ermöglichen **Intra-Note-Edges** – semantische Verbindungen zwischen Chunks derselben Note
### 4.0.1 Section-Type-Deklaration
**Syntax:**
```markdown
## Überschrift ^block-id
> [!section] type-name
```
**Beispiel:**
```markdown
---
type: experience
title: Konflikt im Team-Meeting
---
# Konflikt im Team-Meeting
## Situation ^sit
> [!section] experience
Am 15. Januar kam es zu einer Eskalation...
## Reflexion ^ref
> [!section] insight
Diese Erfahrung zeigt mir, dass...
## Nächste Schritte ^next
> [!section] decision
Ich werde in Zukunft früher eingreifen.
```
**Regeln:**
- Der Section-Type gilt ab der Überschrift bis zur nächsten Überschrift **gleicher oder höherer Ebene**
- Das `[!section]`-Callout kann **an beliebiger Stelle** innerhalb des Abschnitts stehen (muss nicht direkt unter der Überschrift sein)
- Das `[!section]`-Callout ist **unabhängig** von `[!edge]`-Callouts und kann separat platziert werden
- Bei Fehlen eines `[!section]`-Callouts gilt der Note-Type als Fallback
- Valide Section-Types müssen in `types.yaml` definiert sein
**Automatische Section-Erkennung:**
Sobald eine Section auf einer bestimmten Überschriften-Ebene eingeführt wurde (z.B. H2), beginnt bei **jeder weiteren Überschrift auf dieser Ebene automatisch eine neue Section** – auch ohne explizites `[!section]`-Callout.
**Beispiel:**
```markdown
## Situation ^sit
> [!section] experience
Text A... → type = "experience" (explizit)
## Reflexion ^ref
<!-- KEIN [!section] Callout -->
Text B... → type = "experience" (note_type Fallback)
→ ABER: Neue Section erkannt, neuer Chunk!
## Learnings ^learn
> [!section] insight
Text C... → type = "insight" (explizit)
```
**Body-Section:**
Textblöcke, die **vor dem ersten `[!section]`-Callout** stehen, erhalten:
- `section: "body"`
- `type: note_type` (Fallback)
- `section_type: None`
### 4.0.2 Intra-Note-Edges (Verbindungen innerhalb einer Note)
**Block-References als Link-Format:**
Das bevorzugte Format für Intra-Note-Links:
```markdown
> [!edge] derives
> [[#^block-id]]
```
**Fallback (mit Einschränkungen):**
```markdown
> [!edge] derives
> [[#Section-Name]]
```
**Vollständiges Beispiel:**
```markdown
## Situation ^sit
> [!section] experience
Die Geschichte...
## Reflexion ^ref
> [!section] insight
> [!edge] derives
> [[#^sit]]
Was ich daraus lerne...
```
**Ergebnis:**
- Chunk der Reflexion (`#ref`) erhält eine `derives`-Kante zum Chunk der Situation (`#sit`)
- Beide Chunks sind in derselben Note → `is_internal: true`
- Scope ist `chunk` (nicht `note`)
**Automatische Backlinks:**
Für alle Intra-Note-Edges werden automatisch inverse Backlinks erzeugt:
- Forward-Edge: `#ref --[derives]--> #sit`
- Backlink: `#sit --[derived_from]--> #ref` (automatisch)
**Default-Edges aus graph_schema.md:**
Wenn keine expliziten Intra-Note-Edges definiert sind, aber Section-Types vorhanden:
- System ermittelt Source-Type und Target-Type (benachbarte Sektionen)
- Lookup in `graph_schema.md` via `get_topology_info(source_type, target_type)`
- Erster Eintrag aus `typical` wird als Default-Edge-Type verwendet
**Beispiel:**
```markdown
## Situation ^sit
> [!section] experience
## Reflexion ^ref
> [!section] insight
<!-- Kein expliziter [!edge] -->
```
**Ergebnis:** Automatische Edge `experience --[resulted_in]--> insight` (aus Schema)
### 4.0.3 Effektiver Typ & Retrieval
**Kernregel:** Der **Section-Type (sofern vorhanden) hat immer Vorrang** vor dem `note_type` für:
- Vektor-Embedding (Suche)
- `retriever_weight` Lookup
- Type-Filter in Queries
- Graph-Expansion
**Beispiel:**
Ein Chunk mit `type: "insight"` und `note_type: "experience"` erhält:
- `retriever_weight: 1.20` (aus `types.yaml` für `insight`, nicht `experience`)
- Wird bei `filter: {type: "insight"}` gefunden
- Wird bei `filter: {note_type: "experience"}` ebenfalls gefunden
**Chunk-Payload-Struktur:**
```python
{
"type": "insight", # Effektiver Typ (section_type || note_type)
"note_type": "experience", # Ursprünglicher Note-Typ (immer vorhanden)
"section": "Reflexion",
"section_type": "insight", # Expliziter Section-Type (optional)
...
}
```
---
## 4. Edges & Verlinkung
Mindnet versteht Zusammenhänge durch Kanten.
@@ -377,15 +214,6 @@ Du kannst auch auf spezifische Abschnitte innerhalb einer Note verlinken:
Das System trennt automatisch den Note-Namen (`Mein Leitbild`) vom Abschnitts-Namen (`P3 – Disziplin`), sodass mehrere Links zur gleichen Note möglich sind, wenn sie auf verschiedene Abschnitte zeigen.
**Intra-Note-Links mit Block-IDs (WP-26):**
Für Verbindungen **innerhalb derselben Note** nutze Block-References:
```markdown
> [!edge] derives
> [[#^block-id]]
```
Dies erzeugt eine Intra-Note-Edge mit `is_internal: true` und `scope: "chunk"`.
**Gültige Relationen:**
* `depends_on`: Hängt ab von / Benötigt.
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
@@ -407,24 +235,6 @@ Für Zusammenfassungen am Ende einer Notiz, oder eines Absatzes:
**Multi-Line Support (v2.9.1):**
Callout-Blocks mit mehreren Zeilen werden korrekt verarbeitet. Das System erkennt automatisch, wenn mehrere Links im gleichen Callout-Block stehen, und erstellt für jeden Link eine separate Kante (auch bei Deep-Links zu verschiedenen Sections).
**Verschachtelte Edge-Callouts in Containern (WP-26):**
Für übersichtliche Gruppierung von Edges kannst du verschachtelte Callouts nutzen:
```markdown
> [!abstract] Semantic Edges
>> [!edge] derived_from
>> [[Wikilink#Abschnitt]]
>
>> [!edge] solves
>> [[Wikilink2]]
```
**Regeln:**
- Container-Callouts wie `[!abstract]` werden als Gruppierung erkannt, aber nicht semantisch verarbeitet
- Eingebettete `>> [!edge]` Callouts werden korrekt extrahiert
- Die Einrückungsebene (Anzahl `>`) bestimmt die Zugehörigkeit zum Block
- Leere Zeilen innerhalb des Containers (mit `>`) beenden den Edge-Block nicht
**Format-agnostische De-Duplizierung:**
Wenn Kanten bereits via `[!edge]` Callout vorhanden sind, werden sie nicht mehrfach injiziert. Das System erkennt vorhandene Kanten unabhängig vom Format (Inline, Callout, Wikilink).
@@ -642,65 +452,6 @@ Wir haben uns für Qdrant entschieden.
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
```
### 6.3 Beispiel: Section Types & Intra-Note-Edges (WP-26)
Eine Erfahrungs-Notiz mit unterschiedlichen Section-Types und Intra-Note-Verbindungen:
```markdown
---
id: erlebnis-konflikt-team
title: Konflikt im Team-Meeting
type: experience
tags: [team, konflikt, learning]
---
# Konflikt im Team-Meeting
## Situation ^sit
> [!section] experience
Am 15. Januar 2026 kam es im Sprint-Review zu einer Eskalation...
## Meine Reaktion ^react
> [!section] experience
> [!edge] followed_by
> [[#^sit]]
Ich habe versucht zu deeskalieren, aber...
## Reflexion ^ref
> [!section] insight
Diese Erfahrung zeigt mir, dass ich in Konfliktsituationen...
> [!abstract] Semantic Edges
>> [!edge] derives
>> [[#^sit]]
>> [[#^react]]
## Nächste Schritte ^next
> [!section] decision
Ich werde in Zukunft:
1. Früher eingreifen
2. Neutrale Sprache verwenden
> [!edge] caused_by
> [[#^ref]]
```
**Ergebnis:**
- **4 Chunks** mit unterschiedlichen Types:
- `#sit`: `type: experience` (explizit)
- `#react`: `type: experience` (explizit)
- `#ref`: `type: insight` (explizit, überschreibt `note_type`)
- `#next`: `type: decision` (explizit, überschreibt `note_type`)
- **Intra-Note-Edges:**
- `#react --[followed_by]--> #sit`
- `#ref --[derives]--> #sit`
- `#ref --[derives]--> #react`
- `#next --[caused_by]--> #ref`
- Alle Edges haben `is_internal: true` und `scope: "chunk"`
---
## 7. Virtual Schema Layer
@@ -1,10 +1,10 @@
---
doc_type: technical_reference
audience: developer, power_user
scope: obsidian, scripts, workflow, section_types, intra_note_edges
scope: obsidian, scripts, workflow
status: active
version: 1.1.0
context: "Setup und Dokumentation der Obsidian-Integration für Mindnet v2.9. Inkludiert WP-26 Section Types und Intra-Note-Edges."
version: 1.0.0
context: "Setup und Dokumentation der Obsidian-Integration für Mindnet v2.9."
---
# Obsidian Integration Guide
@@ -67,87 +67,6 @@ Damit die Skripte funktionieren, müssen folgende Pfade im Vault existieren:
---
## 5. Section Types & Intra-Note-Edges (WP-26)
### 5.1 Section-Type-Syntax
Das Backend unterstützt nun **Section Types** innerhalb von Notes:
**Format:**
```markdown
## Überschrift ^block-id
> [!section] type-name
```
**Beispiel:**
```markdown
---
type: experience
---
# Meine Erfahrung
## Situation ^sit
> [!section] experience
Die Geschichte...
## Reflexion ^ref
> [!section] insight
> [!edge] derives
> [[#^sit]]
Was ich daraus lerne...
```
**Wichtige Regeln:**
- Das `[!section]`-Callout kann an beliebiger Stelle innerhalb des Abschnitts stehen
- Der Section-Type gilt bis zur nächsten Überschrift gleicher oder höherer Ebene
- Bei Fehlen eines `[!section]`-Callouts gilt der Note-Type als Fallback
- Valide Section-Types müssen in `types.yaml` definiert sein
### 5.2 Intra-Note-Edges mit Block-References
Für Verbindungen **innerhalb derselben Note** nutze Block-References:
**Bevorzugtes Format:**
```markdown
> [!edge] derives
> [[#^block-id]]
```
**Fallback:**
```markdown
> [!edge] derives
> [[#Section-Name]]
```
**Verschachtelte Edge-Callouts:**
Für übersichtliche Gruppierung kannst du verschachtelte Callouts nutzen:
```markdown
> [!abstract] Semantic Edges
>> [!edge] derived_from
>> [[#^sit]]
>> [[#^react]]
>
>> [!edge] supports
>> [[Externe Note]]
```
### 5.3 Automatische Features
**Automatische Section-Erkennung:**
Sobald eine Section auf einer bestimmten Überschriften-Ebene eingeführt wurde, beginnt bei jeder weiteren Überschrift auf dieser Ebene automatisch eine neue Section – auch ohne explizites `[!section]`-Callout.
**Automatische Backlinks:**
Für alle Intra-Note-Edges werden automatisch inverse Backlinks erzeugt:
- Forward-Edge: `#ref --[derives]--> #sit`
- Backlink: `#sit --[derived_from]--> #ref` (automatisch)
**Default-Edges aus graph_schema.md:**
Wenn keine expliziten Intra-Note-Edges definiert sind, aber Section-Types vorhanden, werden automatisch Default-Edges aus dem Graph-Schema generiert.
## 6. Wartung & Updates
## 5. Wartung & Updates
Bei Änderungen an den Notiz-Typen in der `types.yaml` müssen die entsprechenden Markdown-Vorlagen im Ordner `creation` manuell synchronisiert werden, um die Konsistenz zwischen Obsidian und dem Backend zu wahren.
@@ -55,9 +55,6 @@ Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts. Seit der
| `MINDNET_NOTE_SCOPE_ZONE_HEADERS` | `Smart Edges,Relationen,Global Links,Note-Level Relations,Globale Verbindungen` | **Neu (v4.2.0, WP-24c):** Komma-separierte Header-Namen für Note-Scope Zonen. Links in diesen Zonen werden als `scope: note` behandelt und nutzen Note-Summary/Text in Phase 3 Validierung. |
| `MINDNET_NOTE_SCOPE_HEADER_LEVEL` | `2` | **Neu (v4.2.0, WP-24c):** Header-Ebene für Note-Scope Zonen (1-6, Default: 2 für ##). Bestimmt, welche Überschriften als Note-Scope Zonen erkannt werden. |
| `MINDNET_IGNORE_FOLDERS` | *(leer)* | **Neu (v4.1.0):** Komma-separierte Liste von Ordnernamen, die beim Import ignoriert werden. Beispiel: `.trash,.obsidian,.git,.sync` |
| `LOG_LEVEL` | *(siehe Text)* | **Logging:** `INFO`, `WARNING`, `ERROR` oder `DEBUG`. Default: `INFO` (bzw. `DEBUG` wenn `DEBUG=true`). Reduziert Log-Zeilen bei `INFO`/`WARNING`. |
| `LOG_MAX_BYTES` | `1048576` (1 MB) | **Logging:** Max. Größe einer Log-Datei in Bytes vor Rotation. Kleinere Werte = kürzere Einzeldateien. |
| `LOG_BACKUP_COUNT` | `2` | **Logging:** Anzahl rotierter Backup-Dateien für `logs/mindnet.log`. |
---
-14
View File
@@ -137,20 +137,6 @@ Administratoren sollten regelmäßig das Log für unbekannte Kanten-Typen prüfe
* **Pfad:** `data/logs/unknown_edges.jsonl`.
* **Aktion:** Wenn neue Typen häufig auftreten, sollten diese als Alias in die `01_edge_vocabulary.md` aufgenommen werden.
### 3.2.1 Logging begrenzen (Dateigröße / Zeilen)
Das Hauptlog liegt unter `logs/mindnet.log`. Bei sehr langen Logs (z. B. >80.000 Zeilen) kannst du die Ausgabe eingrenzen:
| Umgebungsvariable | Bedeutung | Default |
|-------------------|-----------|---------|
| **`LOG_LEVEL`** | `INFO`, `WARNING`, `ERROR` oder `DEBUG` | `INFO` (bzw. `DEBUG` wenn `DEBUG=true`) |
| **`LOG_MAX_BYTES`** | Max. Größe einer Log-Datei in Bytes vor Rotation | `1048576` (1 MB) |
| **`LOG_BACKUP_COUNT`** | Anzahl rotierter Backup-Dateien | `2` |
**Empfehlung bei zu langen Logs:**
* **`LOG_LEVEL=INFO`** (oder **`WARNING`**) in `.env` setzen – reduziert die Zeilen deutlich gegenüber `DEBUG`.
* Uvicorn-, HTTP- und Qdrant-Logs werden intern auf WARNING gedrosselt, sodass weniger Framework-Zeilen anfallen.
* Kleinere **`LOG_MAX_BYTES`** (z. B. `524288` = 512 KB) führt zu häufigerer Rotation und kürzeren Einzeldateien.
### 3.3 Troubleshooting Guide
Dieser Abschnitt hilft bei häufigen Problemen und deren Lösung.
+207
View File
@@ -0,0 +1,207 @@
---
doc_type: operations_manual
audience: devops, deployment_engineer
scope: docker, compose, container_security, nas_mount
status: draft
version: 0.3.0
context: "Container-Betrieb von Mindnet (Dev/Prod) auf llm-node. Vorbereitung, noch keine produktive Umschaltung."
---
# Container-Betrieb (Docker Compose)
Stand: 28.10.2026. **Status: Dev aktiv (Push auf `develop`), Prod vorbereitet, nicht aktiv.** Produktion läuft unverändert über systemd und `.gitea/workflows/deploy.yml` (siehe [Deployment Guide](04_deployment_guide.md)). Der Containerstand basiert auf dem stabilen `main`-Verhalten **ohne** Privacy Gateway.
**Grundsatz: 1:1-Migration.** Der Container betreibt dieselbe Anwendung mit derselben Konfiguration wie die jeweilige systemd-Instanz, damit beide parallel verglichen werden können. Er liest deren `.env` unverändert. Konfigurationsänderungen sind nachgelagerte Schritte.
## 1. Überblick
| | Dev | Prod |
| --- | --- | --- |
| Vergleichsinstanz (systemd) | 8002/8502, `/home/llmadmin/mindnet_dev` | 8001/8501, `/home/llmadmin/mindnet` |
| Anwendungskonfiguration | `/home/llmadmin/mindnet_dev/.env`, unverändert | `/home/llmadmin/mindnet/.env`, unverändert |
| Container-Angaben | `/home/llmadmin/docker/mindnet-dev/container.env` | `/home/llmadmin/docker/mindnet/container.env` |
| Compose-Datei / Projekt | `deploy/compose.dev.yml` / `mindnet-dev` | `deploy/compose.prod.yml` / `mindnet-prod` |
| API (Standard nur `127.0.0.1`) | 8012 | 8011 |
| UI (Standard `0.0.0.0`, wie systemd) | 8512 | 8511 |
| Qdrant, Ollama | gemeinsame Host-Dienste, wie systemd | gemeinsame Host-Dienste, wie systemd |
| Präfix, Vault | aus der `.env` der systemd-Instanz | aus der `.env` der systemd-Instanz |
Die Ports kollidieren weder untereinander noch mit systemd (8001/8002/8501/8502), damit Container und systemd parallel laufen und verglichen werden können.
**Abweichungen vom heutigen Verhalten, bewusst und nur diese:**
- **Adressen der Host-Dienste:** `QDRANT_URL` und `MINDNET_OLLAMA_URL` zeigen auf `host.docker.internal`. `127.0.0.1` wäre im Container der Container selbst. Ziel sind dieselben Dienste.
- **Vault nur lesend:** Zwei Instanzen sollen nicht parallel in denselben Vault schreiben. Außerdem ist R2 offen. Speichern aus der Container-UI schlägt deshalb fehl, lesen und suchen funktionieren.
- **Cloud-Keys:** Enthält die `.env` Cloud-Keys, startet der Container nur, wenn in der Container-Datei `MINDNET_ALLOW_CLOUD_EGRESS=true` steht. Mit `true` verhält er sich wie heute; die Entscheidung trifft der Betreiber.
- **Bind-Adresse der API:** Standard ist `127.0.0.1`; über `MINDNET_API_BIND` lässt sie sich wie bei systemd auf `0.0.0.0` setzen.
Alle Dateien liegen unter `deploy/`. Dieser Ordner gehört nicht zu `DEPLOY_DIRS` des bestehenden Workflows und wird daher nicht automatisch auf den Server synchronisiert. Der alte Ordner `docker/` (MiniLM-Embed-Dienst, Port 8990) bleibt unverändert, siehe Abschnitt 9.
## 2. Image
`deploy/Dockerfile`, Build-Kontext ist das Repository-Root:
```bash
docker build -f deploy/Dockerfile -t mindnet:$(git rev-parse --short HEAD) .
```
- **Ein Image, drei Modi:** `api` (uvicorn, 1 Worker), `ui` (Streamlit), `preflight [--live]`.
- **Reproduzierbar:** Basis `python:3.12-slim-bookworm` per Digest; Abhängigkeiten aus `deploy/requirements.lock` mit `--require-hashes`.
- **Ohne torch/sentence-transformers:** Der MiniLM-Pfad (`app/embeddings.py`, `embed_router`) ist im Laufzeitcode nicht eingebunden. Embeddings kommen ausschließlich von Ollama.
- **Nicht-root:** Nutzer `mindnet` (UID 10001). Code und Config gehören root und sind nur lesbar.
- **Build-Kontext als Allowlist** (`/.dockerignore`): Nur `app/`, `config/`, `scripts/`, `tests/` und `deploy/` gelangen in den Build-Kontext. Ausgeschlossen bleiben `.env`-Dateien, `config/*.env`, Vault, Logs und venvs.
- **Test-Target:** `docker build --target test …` installiert zusätzlich pytest.
### Lock neu erzeugen
Nur bewusst, z. B. bei Sicherheitsupdates, und danach die Testsuite laufen lassen:
```bash
cd deploy
uv pip compile requirements.in --universal --python-version 3.12 \
--exclude-newer <ISO-Datum> --generate-hashes --no-header -o requirements.lock
uv pip compile requirements-test.in --universal --python-version 3.12 \
--exclude-newer <ISO-Datum> --generate-hashes --no-header -o requirements-test.lock
```
Der aktuelle Lock wurde mit `--exclude-newer 2026-01-22` erzeugt, also dem Stand nach dem letzten `main`-Commit, den das systemd-Deploy damals per `pip install` gezogen haben dürfte. **Offen:** Abgleich mit `pip freeze` der produktiven venv auf llm-node (nur lesend, erfordert Freigabe).
## 3. Preflight (Abbruch statt stiller Fehler)
`deploy/entrypoint.py` prüft vor jedem Start und bricht mit Exit-Code 1 ab, wenn:
| Prüfung | Schützt vor |
| --- | --- |
| `MINDNET_ENV` ∈ {dev, prod}; `COLLECTION_PREFIX` explizit; Dev nur `*_dev`, Prod nie `*_dev` | Dev schreibt in Prod-Collections; stiller Default `mindnet` |
| `VECTOR_DIM == 768`, Profil `embedding_expert` = ollama/`nomic-embed-text`/768, kein abweichendes `MINDNET_EMBEDDING_MODEL` | stiller Rückfall auf 384 (MiniLM) in `qdrant.py` bzw. auf das Chat-Modell als Embedding |
| Cloud-Key gesetzt ohne `MINDNET_ALLOW_CLOUD_EGRESS=true` | unmaskierte Vault-Inhalte an OpenRouter/Gemini |
| Vault fehlt, leer oder nicht lesbar, optionaler Sentinel fehlt, Mount nicht `ro` (`statvfs` `ST_RDONLY`) | Arbeiten auf leerem NAS-Mountpunkt; Schreiben in den Vault (R2) |
| `MINDNET_OLLAMA_URL`/`QDRANT_URL` fehlen oder zeigen auf `localhost`/`127.0.0.1` | App fiele still auf `127.0.0.1` zurück, im Container also auf sich selbst |
Umgebung, Dimension, Schreibschutz und die Adressen der Host-Dienste stehen in den Compose-Dateien unter `environment` und haben Vorrang vor beiden env-Dateien. Präfix und Vault-Pfad kommen aus der `.env` der systemd-Instanz. Die Präfix-Regel gilt trotzdem: Dev nur `*_dev`, Prod nie.
`preflight --live` prüft zusätzlich **nur lesend** aus dem Container heraus, also über dasselbe Netz wie die API:
| Prüfung | Fehlerbild bei Abbruch |
| --- | --- |
| Ollama `/api/tags` erreichbar | `… nicht erreichbar`; bei `host.docker.internal` mit Hinweis auf eine `127.0.0.1`-Bindung |
| Alle Ollama-Modelle vorhanden: Profile mit `provider: ollama` (heute `nomic-embed-text`, `phi3:mini`) plus `MINDNET_LLM_MODEL` | `Ollama fehlen die Modelle: …` |
| Ollama liefert für `nomic-embed-text` 768 Dimensionen | `Ollama liefert N Dimensionen` |
| Qdrant `/collections` erreichbar (mit `QDRANT_API_KEY`, falls gesetzt) | `nicht erreichbar` bzw. `HTTP 401` |
| `<prefix>_notes`/`<prefix>_chunks` haben 768 Dimensionen; fehlende Collections sind erlaubt (Hinweis) | `Collection … hat Dimension …` |
Netzwerkfehler enden als klarer Abbruch mit Exit-Code 1, nicht als Traceback.
```bash
docker compose -f deploy/compose.dev.yml --env-file "$MINDNET_ENV_FILE" run --rm --no-deps api preflight --live # Variablen wie in Abschnitt 7
```
## 4. Vault auf dem NAS
- **Gleicher Vault wie systemd:** `deploy/appenv.py` liest `MINDNET_VAULT_ROOT` aus der `.env`. Ein relativer Pfad wird wie bei systemd gegen das `WorkingDirectory` (Ordner der `.env`) aufgelöst und im Container unter `/app/<pfad>` eingehängt, ein absoluter Pfad 1:1. Dadurch zeigt derselbe Wert im Container auf dasselbe Verzeichnis. Fehlt der Wert, gilt der App-Default `./vault_master`.
- Der Bind-Mount ist `read_only: true`, mit `create_host_path: false` (kein stilles Anlegen) und `propagation: rslave`. Ein später wieder eingehängtes NAS wird dadurch im Container sichtbar, sofern der Host-Mountpunkt `shared` ist.
- **Sentinel:** Standardmäßig wird nur geprüft, dass der Vault lesbar und nicht leer ist; einen bestimmten Aufbau verlangt der Container nicht (wie systemd). Optional kann `MINDNET_VAULT_SENTINEL` in der Container-Datei eine Datei relativ zum Vault vorschreiben, z. B. `_system/dictionary/edge_vocabulary.md` für den NAS-Vault.
- **NAS beim Start nicht verfügbar:** Die API startet nicht. `restart: unless-stopped` versucht es mit Backoff weiter. Die UI hängt an der gesunden API.
- **NAS fällt im Betrieb aus:** Der Healthcheck meldet die API als `unhealthy`. Lesende Abfragen gegen Qdrant laufen weiter. Speichern ist wegen des schreibgeschützten Mounts ohnehin ausgeschlossen. `/ingest/save` würde ohne `ro` den fehlenden Vault-Ordner per `os.makedirs` neu anlegen; genau das verhindert der Mount.
- **Berechtigungen:** Der Container läuft als UID 10001. Der Vault muss für diese UID **lesbar** sein, z. B. über `others: r-x` oder eine passende Gruppe auf dem NAS-Export. Bei CIFS-Mounts gelten `uid`/`gid`/`file_mode` aus den Mount-Optionen des Hosts. Prüfen, ohne am NAS etwas zu ändern:
```bash
mountpoint <vault-pfad>; findmnt -o TARGET,SOURCE,FSTYPE,OPTIONS,PROPAGATION <vault-pfad>
sudo -u '#10001' test -r <vault-pfad>/_system/dictionary/edge_vocabulary.md && echo lesbar
```
## 5. Netzwerk und gemeinsame Dienste
Die Container erreichen Host-Dienste über `host.docker.internal` (`host-gateway`). **Voraussetzung, vor dem ersten Start auf llm-node nur lesend zu prüfen:**
```bash
ss -ltnp | grep -E ':(6333|11434)\b' # Binden Qdrant/Ollama nur an 127.0.0.1?
docker inspect qdrant --format '{{json .HostConfig.PortBindings}}'
```
Sind Qdrant oder Ollama nur an `127.0.0.1` gebunden, ist der Host-Gateway nicht erreichbar. Lösungsmöglichkeiten, jede nur mit Freigabe: Ollama an die Bridge-Adresse binden (`OLLAMA_HOST`), den Prod-Container an das bestehende Docker-Netz von `qdrant` anhängen (externes Netz), oder `network_mode: host` für die API. Keine davon ist umgesetzt.
Ollama ist seit dem 28.10.2026 für die Docker-Netze freigegeben: `OLLAMA_HOST=0.0.0.0:11434` und `ufw allow from 172.16.0.0/12 to any port 11434`, das LAN bleibt gesperrt. Die Prod-Qdrant ist über ihren veröffentlichten Port 6333 erreichbar.
Die API hat keine Authentisierung und wird standardmäßig nur an `127.0.0.1` veröffentlicht. Die UI erreicht sie intern über `http://api:8000`. Die UI ist wie bei systemd im LAN erreichbar (`MINDNET_UI_BIND=0.0.0.0`).
## 6. Härtung
Für `api` und `ui`: `read_only`-Rootfs, `tmpfs /tmp`, `cap_drop: ALL`, `no-new-privileges`, `init`, `pids_limit`, `mem_limit`, rotierende json-Logs. Beschreibbar sind nur die Volumes `logs` (`/app/logs`) und `data` (`/app/data`). Die UI bindet `data` nur lesend ein.
## 7. Bedienung
Normalerweise über das Deploy-Skript (Abschnitt 8), auch manuell:
```bash
export MINDNET_APP_ENV_FILE=/home/llmadmin/mindnet_dev/.env # systemd-Dev, unverändert
export MINDNET_ENV_FILE=/home/llmadmin/docker/mindnet-dev/container.env # aus deploy/env/dev.env.example
deploy/deploy.sh dev
```
Für Einzelschritte von Hand braucht Compose zusätzlich die abgeleiteten Vault-Werte:
```bash
eval "$(python3 deploy/appenv.py "$MINDNET_APP_ENV_FILE" "$MINDNET_ENV_FILE")"
export MINDNET_VAULT_HOST_PATH MINDNET_VAULT_TARGET MINDNET_IMAGE_TAG=dev-manual
docker compose -f deploy/compose.dev.yml --env-file "$MINDNET_ENV_FILE" up -d --wait
```
Einen Import startet der Container-Workflow nicht; die Daten sind dieselben wie bei systemd.
**Ohne Cloud-Keys** (Prod-Standard) ruft der stabile Code für Cloud-Profile Ollama mit der Cloud-Modell-ID auf. Das scheitert zunächst und endet über `fallback_profile` bei `identity_safe` (phi3:mini). Chat funktioniert damit lokal, aber mit Verzögerung durch Fehlversuche (Review R4).
## 8. Gitea-Pipeline: `develop` → Dev, `main` → Prod
Gleiches Muster wie Kansho, aber auf dem eigenen Runner des Zielhosts (heute llm-node, Label `linux_host`, läuft als `llmadmin`, nicht wie im [Server-Handbuch](04_server_operation_manual.md) angegeben als `root`). Gitea führt nur `.gitea/workflows/` aus:
| Workflow | Trigger | Status |
| --- | --- | --- |
| `.gitea/workflows/deploy-dev.yml` | Push `develop`, manuell | **aktiv** (G3) |
| `deploy/gitea-workflows/deploy-prod.yml` | Push `main`, manuell | Vorlage. Aktivierung bei G5, im **selben Commit** `git rm .gitea/workflows/deploy.yml` (systemd), sonst deployen beide |
Fehlt die Container-Datei, legt der Workflow sie beim ersten Lauf aus `deploy/env/<env>.env.example` an. Sie enthält nur Ports, Bind-Adressen und Freigaben. Eine vorhandene Datei wird nie überschrieben. `deploy/appenv.py` bricht ab, wenn darin Anwendungswerte stehen, damit sie die `.env` der systemd-Instanz nicht überschreiben kann.
Prod nur über einen Merge-Commit `develop` → `main` (`git merge --no-ff develop`), wie bei Kansho.
Beide Workflows rufen nur `deploy/deploy.sh dev|prod` auf. Jeder Schritt bricht ab, **bevor** der laufende Stack angefasst wird:
1. Container-Tests im Test-Image mit `--network none` (Preflight, Erreichbarkeit gegen Fake-Server, statische Compose-/Workflow-Prüfungen), **blockierend**.
2. Volle Testsuite mit `--network none`, **informativ**, bis die 17 bekannten Fehler behoben sind ([Migrationsplan §4](../05_Development/05_docker_migration_plan.md)). Ohne Netzwerk kann kein Test einen echten Dienst erreichen.
3. Image bauen, Tag `<env>-<commit>`.
4. Vault und Präfix aus der systemd-`.env` ableiten (`deploy/appenv.py`), danach `preflight --live` in einem Wegwerf-Container.
5. `up -d --wait` (Healthchecks) und danach `deploy/smoke.py` über die veröffentlichten Ports, also aus Sicht des Hosts:
- API `/healthz`: Status `ok`, erwartetes Präfix.
- API `/admin/stats`: Vektorgröße 768; die API erreicht Qdrant (Collection-Counts ≠ −1).
- UI `/_stcore/health`.
- `--require-data`: alle Collections lesbar, Notes nicht leer, denn die Daten der systemd-Instanz sind vorhanden.
6. Erfolg: Der Tag wird in `last_good_tag` neben der Container-Datei vermerkt. Verwaiste Container früherer Stände entfernt `--remove-orphans`. Prod bei Fehler: Rückkehr zum letzten erfolgreichen Tag und erneuter Smoke-Test; der Workflow bleibt trotzdem rot.
Beide env-Dateien liegen nur auf dem Host (Tabelle in Abschnitt 1). Compose liest sie direkt über `MINDNET_APP_ENV_FILE` und `MINDNET_ENV_FILE`; Secrets landen nicht im Runner-Workspace.
**Unterschiede zu Kansho, bewusst:**
| | Kansho | Mindnet |
| --- | --- | --- |
| Checkout | `git clone`/`reset --hard` im Zielordner | `git fetch` genau des Push-Commits vom eigenen Gitea in den Runner-Workspace, mit Job-Token (auch bei privatem Repo). Keine externen Actions, also kein Zugriff auf github.com nötig. Compose-Projektnamen sind fest, daher ist der Ordner egal |
| Tests | eigener `test.yml` nach dem Dev-Deploy | Teil des Deploys, **vor** dem Start; ohne Netzwerk |
| Prüfung vor Start | keine | `preflight --live` (Dienste, Modelle, Dimensionen, Vault) |
| Image | `build --no-cache`, kein Tag | Hash-Lock, Tag pro Commit, Rollback in Prod |
| Zustand des Hosts | `.env` im Checkout | env-Datei und `last_good_tag` außerhalb des Checkouts |
**Umzug auf einen anderen Mini-PC:** Runner dort registrieren, in beiden Workflows `runs-on`, `MINDNET_APP_ENV_FILE` und `MINDNET_ENV_FILE` anpassen. Hostspezifisch ist sonst nur `host.docker.internal` (über `host-gateway`, funktioniert auf jedem Linux-Docker).
## 9. Altbestand `docker/` (MiniLM)
`docker/docker-compose.yml` und `docker/embeddings.Dockerfile` bauen einen MiniLM-Dienst (384 Dimensionen, Port 8990). Laut [Server-Handbuch](04_server_operation_manual.md) läuft `mindnet-embed` auf llm-node. Im Anwendungscode wird er nicht genutzt; außerdem verweist das Dockerfile auf `app/embed_server.py`, das im Repository nicht mehr existiert. **Nicht entfernen, bevor geprüft ist**, ob der Container auf llm-node noch läuft und von irgendetwas angesprochen wird. Grund: `deploy.yml` synchronisiert `docker/` mit `rsync --delete`; eine Löschung auf `main` entfernt die Dateien auch auf dem Server.
## 10. Noch nicht verifiziert
- Kein `docker build` und kein Compose-Start: Auf der Entwicklungsmaschine ist kein Docker installiert. Verifiziert sind:
- die Preflight-Logik und die Erreichbarkeitsprüfungen gegen einen Fake-Server (`tests/test_container_connectivity.py`),
- statische Compose-, Dockerfile- und Workflow-Zusagen (`tests/test_container_preflight.py`),
- der Ablauf von `deploy.sh` mit einer Docker-Attrappe: Erfolg, Abbruch im Preflight vor dem Start, Prod-Startfehler mit Rollback,
- die Testsuite mit exakt den gelockten Versionen (frische venv aus dem Lock, Windows).
- Runner auf llm-node: Docker-Compose-Version (benötigt `up --wait` und Interpolation in `env_file`), Rechte des Runner-Nutzers auf `/home/llmadmin/docker/`.
- Healthcheck von `qdrant/qdrant` nutzt `bash` und `/dev/tcp`; beim ersten Dev-Build prüfen.
- Der Abgleich mit den produktiven Paketversionen fehlt (Abschnitt 2).
@@ -1,387 +0,0 @@
# WP-26 Manuelle Testszenarien
**Version:** 1.3
**Datum:** 25. Januar 2026
**Status:** Alle Phasen (Phase 1-3) implementiert
---
## 1. Überblick
Dieses Dokument beschreibt die manuellen Testszenarien für WP-26 Phase 1: Section-Types und Intra-Note-Edges.
---
## 2. Voraussetzungen
1. **Python-Umgebung** mit allen Dependencies aus `requirements.txt`
2. **Qdrant-Instanz** erreichbar (lokal oder Docker)
3. **Vault mit Test-Note** (siehe Abschnitt 3)
---
## 3. Test-Note erstellen
Erstelle eine neue Markdown-Datei im Vault mit folgendem Inhalt:
```markdown
---
id: wp26-test-experience
title: WP-26 Test Experience
type: experience
tags: [test, wp26]
---
# WP-26 Test Experience
## Situation ^sit
> [!section] experience
Am 25. Januar 2026 testete ich das neue Section-Type Feature.
Dies ist der Experience-Teil der Note.
## Meine Reaktion ^react
> [!section] experience
> [!edge] followed_by
> [[#^sit]]
Ich war zunächst skeptisch, aber die Implementierung sah solide aus.
## Reflexion ^ref
> [!section] insight
Diese Erfahrung zeigt mir, dass typ-spezifische Sektionen
die semantische Präzision des Retrievals verbessern können.
> [!abstract] Semantic Edges
>> [!edge] derives
>> [[#^sit]]
>> [[#^react]]
## Nächste Schritte ^next
> [!section] decision
Ich werde:
1. Die Tests ausführen
2. Die Ergebnisse dokumentieren
> [!edge] caused_by
> [[#^ref]]
```
---
## 4. Testszenarien
### 4.1 TS-01: Section-Type-Erkennung
**Ziel:** Prüfen, ob `[!section]`-Callouts korrekt erkannt werden.
**Schritte:**
1. Importiere die Test-Note via `scripts/import_markdown.py`
2. Prüfe die Chunks in Qdrant via API oder Debug-Skript
**Prüfkriterien:**
| Chunk | Erwarteter `type` | Erwarteter `note_type` | Erwarteter `section` |
|-------|-------------------|------------------------|----------------------|
| #c00 | experience | experience | Situation |
| #c01 | experience | experience | Meine Reaktion |
| #c02 | insight | experience | Reflexion |
| #c03 | decision | experience | Nächste Schritte |
**Prüf-Script:**
```python
# scripts/check_wp26_chunks.py
from qdrant_client import QdrantClient
client = QdrantClient("http://localhost:6333")
note_id = "wp26-test-experience"
# Hole alle Chunks der Note
result = client.scroll(
collection_name="mindnet_chunks",
scroll_filter={"must": [{"key": "note_id", "match": {"value": note_id}}]},
with_payload=True,
limit=100
)
for point in result[0]:
p = point.payload
print(f"Chunk: {p.get('chunk_id')}")
print(f" type: {p.get('type')}")
print(f" note_type: {p.get('note_type')}")
print(f" section: {p.get('section')}")
print(f" section_type: {p.get('section_type')}")
print(f" block_id: {p.get('block_id')}")
print()
```
---
### 4.2 TS-02: Block-ID-Erkennung
**Ziel:** Prüfen, ob Block-IDs (`^id`) aus Überschriften korrekt extrahiert werden.
**Prüfkriterien:**
| Chunk | Erwartete `block_id` |
|-------|---------------------|
| #c00 | sit |
| #c01 | react |
| #c02 | ref |
| #c03 | next |
---
### 4.3 TS-03: is_internal Flag für Edges
**Ziel:** Prüfen, ob Intra-Note-Edges das `is_internal: true` Flag erhalten.
**Schritte:**
1. Importiere die Test-Note
2. Prüfe die Edges in Qdrant
**Prüfkriterien:**
| Edge | `is_internal` |
|------|---------------|
| #c01 → #c00 (followed_by) | `true` |
| #c02 → #c00 (derives) | `true` |
| #c02 → #c01 (derives) | `true` |
| #c03 → #c02 (caused_by) | `true` |
| Alle structure edges (next/prev) | `true` |
**Prüf-Script:**
```python
# scripts/check_wp26_edges.py
from qdrant_client import QdrantClient
client = QdrantClient("http://localhost:6333")
note_id = "wp26-test-experience"
# Hole alle Edges der Note
result = client.scroll(
collection_name="mindnet_edges",
scroll_filter={"must": [{"key": "note_id", "match": {"value": note_id}}]},
with_payload=True,
limit=100
)
for point in result[0]:
p = point.payload
kind = p.get('kind', 'unknown')
source = p.get('source_id', '?')
target = p.get('target_id', '?')
is_internal = p.get('is_internal', 'MISSING')
provenance = p.get('provenance', '?')
source_hint = p.get('source_hint', '-')
print(f"{source} --[{kind}]--> {target}")
print(f" is_internal: {is_internal}")
print(f" provenance: {provenance}")
print(f" source_hint: {source_hint}")
print()
```
---
### 4.4 TS-04: Provenance-Normalisierung
**Ziel:** Prüfen, ob Provenance-Werte korrekt normalisiert werden.
**Prüfkriterien:**
| Altes Provenance | Neues `provenance` | `source_hint` |
|------------------|-------------------|---------------|
| explicit:callout | explicit | callout |
| explicit:wikilink | explicit | wikilink |
| structure:belongs_to | structure | belongs_to |
| structure:order | structure | order |
| edge_defaults | rule | edge_defaults |
---
### 4.5 TS-05: Automatische Section-Erkennung
**Ziel:** Prüfen, ob neue Überschriften ohne `[!section]` automatisch neue Chunks erstellen.
**Test-Note:**
```markdown
---
id: wp26-test-auto-section
type: experience
---
# Test Auto Section
## Section A ^a
> [!section] insight
Content A (insight).
## Section B ^b
Content B (sollte experience sein - Fallback).
## Section C ^c
> [!section] decision
Content C (decision).
```
**Prüfkriterien:**
| Chunk | `type` | Grund |
|-------|--------|-------|
| Section A | insight | Explizites `[!section]` |
| Section B | experience | Fallback auf `note_type` |
| Section C | decision | Explizites `[!section]` |
---
## 5. Unit-Tests ausführen
```bash
# Im Projekt-Root
cd c:\Dev\cursor\mindnet
# Aktiviere virtuelle Umgebung (falls vorhanden)
# .venv\Scripts\activate
# Führe WP-26 Tests aus
python -m pytest tests/test_wp26_section_types.py -v
```
**Erwartetes Ergebnis:** Alle Tests grün.
---
## 6. Bekannte Einschränkungen
1. **Block-ID-Stability:** Obsidian aktualisiert Block-IDs nicht automatisch bei Umbenennung von Überschriften.
2. **Heading-Links:** Links wie `[[#Section Name]]` werden unterstützt, aber Block-References (`[[#^id]]`) werden bevorzugt.
3. **Nested Callouts:** Verschachtelte Callouts (`>> [!edge]`) werden korrekt verarbeitet.
---
## 7. Phase 2: Retriever-Anpassungen
### 7.1 is_internal-Boost
**Konfiguration:** `config/retriever.yaml`
```yaml
edge_scoring:
internal_edge_boost: 1.2 # +20% Boost für Intra-Note-Edges
external_edge_boost: 1.0 # Standard für Inter-Note-Edges
```
**Manuelle Prüfung:**
1. Führe eine Suche durch, die eine Note mit internen Edges trifft
2. Prüfe im Debug-Log, dass `is_internal: True` Edges höheres Gewicht erhalten
### 7.2 Aggregation-Level
**Konfiguration:** `config/retriever.yaml`
```yaml
aggregation:
level: note # "note" (default) oder "chunk"
max_chunks_per_note: 3 # Limit bei "note"-Level
```
**Test mit Chunk-Level:**
1. Setze `level: chunk` in `retriever.yaml`
2. Führe Suche durch
3. Prüfe, dass mehrere Chunks derselben Note zurückgegeben werden (keine Deduplizierung)
### 7.3 Unit-Tests Phase 2
```bash
python -m pytest tests/test_wp26_phase2_retriever.py -v
```
---
## 8. Phase 3: Schema-Validierung (FA-12)
### 8.1 get_topology_info()
Die neue Funktion ermittelt typische und verbotene Edge-Types für ein Source/Target-Typ-Paar.
**Beispiel:**
```python
from app.core.graph.graph_utils import get_topology_info
topology = get_topology_info("experience", "insight")
# Gibt: {"typical": ["resulted_in", ...], "prohibited": [...]}
```
### 8.2 validate_intra_note_edge()
Validiert Intra-Note-Edges gegen das `graph_schema.md`.
**Verhalten:**
| Edge-Typ | Ergebnis | Confidence |
|----------|----------|------------|
| In `typical` | ✅ Erlaubt | 1.0 |
| Nicht in `typical`, nicht in `prohibited` | ✅ Erlaubt (atypisch) | 0.7 |
| In `prohibited` | ❌ Abgelehnt | 0.0 |
### 8.3 Manuelle Prüfung
1. Erstelle eine Note mit einer verbotenen Edge-Kombination
2. Führe Ingestion durch
3. Prüfe, dass die Edge abgelehnt wurde (Log: `🚫 [SCHEMA-VALIDATION]`)
### 8.4 Unit-Tests Phase 3
```bash
python -m pytest tests/test_wp26_phase3_validation.py -v
```
---
## 9. Alle WP-26 Tests ausführen
```bash
# Alle WP-26 Unit-Tests
python -m pytest tests/test_wp26_section_types.py tests/test_wp26_phase2_retriever.py tests/test_wp26_phase3_validation.py -v
# Nur fehlgeschlagene Tests erneut ausführen
python -m pytest --lf -v
```
---
## 10. Bekannte Einschränkungen
1. **Block-ID-Stability:** Obsidian aktualisiert Block-IDs nicht automatisch bei Umbenennung von Überschriften.
2. **Heading-Links:** Links wie `[[#Section Name]]` werden unterstützt, aber Block-References (`[[#^id]]`) werden bevorzugt.
3. **Nested Callouts:** Verschachtelte Callouts (`>> [!edge]`) werden korrekt verarbeitet.
4. **Strict-Mode:** `strict_mode=True` in der Validierung lehnt atypische Edges ab (Standard: `False`).
---
## 11. Zusammenfassung
| Phase | Status | Beschreibung |
|-------|--------|--------------|
| Phase 1 | ✅ | Section-Types, Block-IDs, Intra-Note-Edges |
| Phase 2 | ✅ | is_internal-Boost, Aggregation-Level |
| Phase 3 | ✅ | Schema-Validierung (FA-12) |
---
**Ende der Testdokumentation (WP-26 v1.3)**
@@ -1,344 +0,0 @@
# WP-26 Anforderungen-Checkliste
**Version:** 1.3
**Datum:** 25. Januar 2026
**Status:** Implementierung abgeschlossen
---
## Phase 1: Section-Types & Parsing
### ✅ FA-01: Neues Callout-Format `[!section]`
**Status:** ✅ Implementiert
**Implementierung:**
- `chunking_parser.py`: Regex für `[!section]` Callout-Erkennung
- State-Machine für `current_section_type` und `section_introduced_at_level`
- Retroaktive Propagation via `_propagate_section_type_backwards()`
**Dateien:**
- `app/core/chunking/chunking_parser.py`
- `app/core/chunking/chunking_models.py` (RawBlock, Chunk)
**Tests:**
- `tests/test_wp26_section_types.py::TestSectionTypeRecognition`
---
### ✅ FA-01b: Verschachtelte Edge-Callouts
**Status:** ✅ Implementiert
**Implementierung:**
- `graph_derive_edges.py`: `extract_callout_relations()` unterstützt verschachtelte Callouts
- Einrückungsebene (`>>`) wird korrekt erkannt
**Dateien:**
- `app/core/graph/graph_derive_edges.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestNestedEdgeCallouts`
---
### ✅ FA-02: Scope-Beendigung
**Status:** ✅ Implementiert
**Implementierung:**
- Scope endet bei Überschrift gleicher oder höherer Ebene
- `section_introduced_at_level` Tracking
**Dateien:**
- `app/core/chunking/chunking_parser.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestSectionTypeScope`
---
### ✅ FA-02b: Automatische Section-Erkennung
**Status:** ✅ Implementiert
**Implementierung:**
- Neue Überschrift auf `section_introduced_at_level` erzeugt automatisch neue Section
- Fallback auf `note_type` wenn kein `[!section]` Callout vorhanden
**Dateien:**
- `app/core/chunking/chunking_parser.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestAutomaticSectionRecognition`
---
### ✅ FA-03: `type`-Feld-Befüllung
**Status:** ✅ Implementiert
**Implementierung:**
- `effective_type = section_type if section_type else note_type`
- Wird in `ingestion_chunk_payload.py` berechnet
- `type`-Feld enthält immer den effektiven Typ
**Dateien:**
- `app/core/ingestion/ingestion_chunk_payload.py`
**Tests:**
- `tests/test_wp26_section_types.py` (implizit)
---
### ✅ FA-03b: Body-Section Handling
**Status:** ✅ Implementiert
**Implementierung:**
- Textblöcke vor erstem `[!section]` erhalten `section: "body"`
- `section_type: None` (Fallback auf `note_type`)
**Dateien:**
- `app/core/chunking/chunking_parser.py`
---
### ✅ FA-04: Optionales Feld `note_type`
**Status:** ✅ Implementiert
**Implementierung:**
- Neues Feld `note_type` im Chunk-Payload
- Keyword-Index in Qdrant erstellt
**Dateien:**
- `app/core/ingestion/ingestion_chunk_payload.py`
- `scripts/setup_mindnet_collections.py`
**Tests:**
- `tests/test_wp26_section_types.py` (implizit)
---
### ✅ FA-05: Block-Reference als Link-Format
**Status:** ✅ Implementiert
**Implementierung:**
- `parse_link_target()` extrahiert Block-ID aus `[[#^block-id]]`
- Unterstützt auch `[[#Section Name ^block-id]]` Format
**Dateien:**
- `app/core/graph/graph_utils.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestBlockIdParsing`
---
### ✅ FA-06: Section-zu-Chunk-Mapping
**Status:** ✅ Implementiert
**Implementierung:**
- Mapping erfolgt implizit über Block-IDs und Heading-Matches
- `parse_link_target()` löst Section-Referenzen auf
**Dateien:**
- `app/core/graph/graph_derive_edges.py`
- `app/core/graph/graph_utils.py`
---
### ✅ FA-07: Edge-Erstellung für Intra-Note-Links
**Status:** ✅ Implementiert
**Implementierung:**
- Intra-Note-Links werden zu Chunk-Scope Edges
- `scope: "chunk"` für Intra-Note-Edges
**Dateien:**
- `app/core/graph/graph_derive_edges.py`
---
### ✅ FA-07b: Metadaten-Erweiterung (`is_internal` Flag)
**Status:** ✅ Implementiert
**Implementierung:**
- `is_internal: True` für Edges innerhalb derselben Note
- Automatische Berechnung in `graph_utils._edge()`
- Boolean-Index in Qdrant
**Dateien:**
- `app/core/graph/graph_utils.py`
- `scripts/setup_mindnet_collections.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestIsInternalFlag`
---
### ✅ FA-08: Default-Edges aus graph_schema.md
**Status:** ✅ Implementiert
**Implementierung:**
- `get_typical_edge_for()` ermittelt Default-Edge aus Schema
- Automatische Edge-Erstellung bei Section-Transitions
- `provenance: "rule"`, `rule_id: "inferred:section_transition"`
**Dateien:**
- `app/core/graph/graph_derive_edges.py`
- `app/core/graph/graph_utils.py`
**Tests:**
- `tests/test_wp26_section_types.py::TestAutomaticIntraNoteEdges`
- `tests/test_wp26_section_types.py::TestGraphSchemaParser`
---
## Phase 2: Retriever-Anpassungen
### ✅ FA-09: Edge-Gewichtung für Intra-Note-Edges
**Status:** ✅ Implementiert
**Implementierung:**
- `internal_edge_boost` und `external_edge_boost` in `retriever.yaml`
- Boost wird in `Subgraph.add_edge()` angewendet
**Dateien:**
- `app/core/graph/graph_subgraph.py`
- `config/retriever.yaml`
**Tests:**
- `tests/test_wp26_phase2_retriever.py::TestIsInternalBoost`
---
### ✅ FA-09b: Retrieval-Priorisierung (Section-Type vor Note-Type)
**Status:** ✅ Implementiert
**Implementierung:**
- `effective_type` wird für `retriever_weight` Lookup verwendet
- `type`-Feld enthält bereits den effektiven Typ
**Dateien:**
- `app/core/ingestion/ingestion_chunk_payload.py`
---
### ✅ FA-10: Optionale Chunk-Level-Deduplizierung
**Status:** ✅ Implementiert
**Implementierung:**
- `aggregation.level` in `retriever.yaml` (`"note"` oder `"chunk"`)
- `max_chunks_per_note` für Note-Level-Limitierung
- Implementiert in `retriever._score_and_pool_hits()`
**Dateien:**
- `app/core/retrieval/retriever.py`
- `config/retriever.yaml`
**Tests:**
- `tests/test_wp26_phase2_retriever.py::TestNoteLevelAggregation`
- `tests/test_wp26_phase2_retriever.py::TestChunkLevelAggregation`
---
## Phase 3: Schema-Validierung
### ✅ FA-12: Schema-Validierung gegen effektiven Chunk-Typ
**Status:** ✅ Implementiert
**Implementierung:**
- `validate_intra_note_edge()` prüft gegen `graph_schema.md`
- Verwendet `effective_type` (type-Feld) beider Chunks
- `get_topology_info()` liefert `typical` und `prohibited` Listen
- Integration in Ingestion-Pipeline (nach LLM-Validierung)
**Dateien:**
- `app/core/ingestion/ingestion_validation.py`
- `app/core/graph/graph_utils.py`
- `app/core/ingestion/ingestion_processor.py`
**Tests:**
- `tests/test_wp26_phase3_validation.py`
**Verhalten:**
- Edge in `prohibited` → ❌ Abgelehnt (confidence: 0.0)
- Edge in `typical` → ✅ Erlaubt (confidence: 1.0)
- Edge atypisch → ✅ Erlaubt (confidence: 0.7)
---
## Abwärtskompatibilität
### ✅ FA-11: Fallback-Verhalten
**Status:** ✅ Implementiert
**Garantien:**
- Notes ohne `[!section]` Callouts funktionieren unverändert
- `Chunk.type = note_type` (wie bisher)
- Keine Breaking Changes für bestehende Notes
---
## Zusammenfassung
| Phase | Requirements | Status |
|-------|--------------|--------|
| **Phase 1** | FA-01 bis FA-08 | ✅ 8/8 |
| **Phase 2** | FA-09, FA-09b, FA-10 | ✅ 3/3 |
| **Phase 3** | FA-12 | ✅ 1/1 |
| **Kompatibilität** | FA-11 | ✅ 1/1 |
| **GESAMT** | | ✅ **13/13** |
---
## Manuelle Tests
### 1. Umfassendes Test-Script ausführen
```bash
cd c:\Dev\cursor\mindnet
python scripts/test_wp26_comprehensive.py
```
### 2. Unit-Tests ausführen
```bash
# Alle WP-26 Tests
python -m pytest tests/test_wp26_section_types.py tests/test_wp26_phase2_retriever.py tests/test_wp26_phase3_validation.py -v
# Einzelne Phasen
python -m pytest tests/test_wp26_section_types.py -v
python -m pytest tests/test_wp26_phase2_retriever.py -v
python -m pytest tests/test_wp26_phase3_validation.py -v
```
### 3. Integrationstest mit echter Note
1. Erstelle Test-Note im Vault (siehe `05_WP26_Manual_Testing.md`)
2. Importiere via `scripts/import_markdown.py`
3. Prüfe Chunks und Edges in Qdrant
---
## Bekannte Einschränkungen
1. **Block-ID-Stability:** Obsidian aktualisiert Block-IDs nicht automatisch bei Umbenennung
2. **Heading-Links:** `[[#Section Name]]` funktioniert, aber `[[#^block-id]]` wird bevorzugt
3. **Strict-Mode:** Schema-Validierung im Strict-Mode lehnt atypische Edges ab (Standard: `False`)
---
**Ende der Checkliste**
@@ -0,0 +1,112 @@
---
doc_type: development_plan
audience: developer, devops
scope: docker_migration, release_gates, test_baseline, privacy_gateway
status: draft
version: 0.1.0
context: "Migrationsplan Mindnet → Container (Dev/Prod) mit Freigabe-Gates, Testbaseline und Anforderungen an das Privacy Gateway."
---
# Migrationsplan: Containerisierung
Stand: 28.10.2026. Betriebsdetails: [Container-Betrieb](../04_Operations/04_docker_deployment.md). Die Review-Befunde R1–R9 stehen in `05_review_2026-09-25.md` auf dem Branch `codex/privacy-gateway`. Der Link funktioniert erst, wenn beide Stände in `develop` zusammengeführt sind.
## 1. Rahmenbedingungen (entschieden)
- Ziel-Host bleibt vorerst `llm-node`; nichts ist auf diesen Host oder auf lokale Python-Umgebungen zugeschnitten.
- Ollama und GLiNER sind gemeinsame Dienste pro Host. Dev und Prod haben getrennte Konfiguration, Volumes und Compose-Projekte.
- Die produktive Qdrant-Instanz bleibt unverändert; Dev hat eine eigene Instanz.
- Embeddings: `nomic-embed-text`, 768 Dimensionen. Ein Rückfall auf MiniLM/384 wird technisch verhindert.
- Vault vom NAS, nur lesend. Dev bekommt Testdaten. Prod-Schreibzugriff bleibt gesperrt, bis R2 behoben ist.
- Containerisierung und Privacy Gateway sind getrennt. Keine echten Vault-Inhalte an Cloud-Anbieter.
## 2. Befunde aus Phase 0
| Befund | Auswirkung |
| --- | --- |
| **Gitea-Repo `Lars/mindnet` ist öffentlich** (`private: false`, anonymes `git ls-remote` möglich) | Push der Gateway-Arbeit **nicht** durchgeführt. Sicherung nur lokal (Commits + Bundle). |
| Push auf `main` löst `.gitea/workflows/deploy.yml` aus: `rsync --delete` von `app scripts schemas docker tests config …` nach `/home/llmadmin/mindnet` plus Neustart | Jeder Merge nach `main` ist ein Produktions-Deploy. Container-Dateien liegen deshalb in `deploy/` (nicht synchronisiert). |
| `config/prod.env` ist versioniert; Key-Felder enthalten in allen Ständen nur Platzhalter (Länge 9/12) | Kein Leak. Datei bleibt ungenutzt; das Image schließt `config/*.env` aus. |
| MiniLM: `app/embeddings.py` und `embed_router` sind nicht eingebunden. `docker/embeddings.Dockerfile` kopiert das nicht mehr existierende `app/embed_server.py`. `mindnet-embed` läuft laut Handbuch auf llm-node | Nicht entfernt. Abschaltung erst nach Prüfung auf llm-node (Gate G2). |
| `qdrant.py` fällt ohne `VECTOR_DIM` auf 384 zurück; `IngestionProcessor` legt Collections beim Start an | Preflight erzwingt `VECTOR_DIM=768`. |
| Ohne Cloud-Keys ruft der stabile Code Ollama mit Cloud-Modell-IDs auf (R4) | Chat lokal nur über Fallback-Kette; langsamer, aber ohne Egress. |
## 3. Branches
| Branch | Basis | Inhalt | Ort |
| --- | --- | --- | --- |
| `main` | — | Produktion (systemd, Auto-Deploy) | Gitea |
| `develop` | `origin/main` (`0d61a9e`) | Integrationszweig nach Kansho-Muster; Push deployt Dev (G3) | Gitea |
| `feature/containerization` | `develop` | Phase 1 | **nur lokal** |
| `codex/privacy-gateway` | `origin/main` | Gateway (2 Commits), unverändert | **nur lokal** + Bundle |
| `origin/SectionType` | `origin/main` | WP-26; R3 offen | Gitea |
Reihenfolge: `feature/containerization` → `develop`. Das Gateway folgt erst nach der Docker-Anpassung aus Abschnitt 6 und als eigener Merge. Ein Konflikt mit dem Gateway-Branch ist nicht zu erwarten: `deploy/`, `.dockerignore` und die neuen Docs/Tests sind neu, `.gitignore` nur auf dem Gateway-Branch.
## 4. Testbaseline (17 bestehende Fehler, kategorisiert)
Gleiches Ergebnis mit lokaler venv und mit einer frischen venv aus `deploy/requirements.lock`: 12 failed, 5 errors. Keiner davon wurde deaktiviert.
| Kategorie | Tests | Ursache | Empfehlung |
| --- | --- | --- | --- |
| **A – echter Produktfehler** | `test_query_text_embed_unit::test_query_with_text` | `app/routers/query.py:28` übergibt `log_search(req, res)`; Signatur ist `(query_id, query_text, results, …)`. Das Suchprotokoll für `/query` schlägt im Hintergrund fehl. | Aufruf korrigieren (eigener Fix). |
| **A – echter Produktfehler** | `test_query_unit::test_query_hybrid_with_monkeypatch`, `test_retriever_basic::test_hybrid_retrieve_basic` | `retriever.py:401` loggt `req.query[:100]`; bei reiner Vektor-Abfrage ist `query=None` → `TypeError` → HTTP 500. | Logging `None`-sicher machen (eigener Fix). |
| **B – veralteter Test (API umgebaut)** | `test_final_wp15_validation`, `test_smart_chunking_integration`, `test_wp15_final` (Collection-Error) | `from app.core import chunker` – Modul existiert nicht mehr (jetzt `app/core/chunking/`). | Auf neue API portieren oder bewusst archivieren. |
| B | `test_WP22_intelligence` (4) | `EdgeRegistry(vault_root=…)` – Parameter entfernt. | Portieren. |
| B | `test_dialog_full_flow` (2) | `save_note()` verlangt `background_tasks`. | Portieren. |
| **C – fachlich klären** | `test_type_registry::test_defaults_when_missing` | Test erwartet `chunk_profile`, Code liefert `chunking_profile`. | Entscheiden, welcher Schlüssel gilt. |
| C | `test_retriever_edges::test_hybrid_retrieve_uses_edge_scores` | Erwartetes Ranking (`note:2` vor `note:1`) tritt nicht ein. | Prüfen, ob Edge-Scoring regressiert oder Erwartung veraltet ist. |
| **D – braucht Infrastruktur / falsch gepatcht** | `test_graph_unit::test_graph_neighbors` | Patcht nicht mehr die tatsächlich aufgerufene Funktion → echte Qdrant-Verbindung. | Patch korrigieren; danach Unit-Test ohne Qdrant. |
| **E – kein pytest-Test** | `test_interview_intent::test_intent`, `test_wp06_decision::test_decision_engine` | Funktionsparameter `message`/`query` werden als Fixture interpretiert; manuelle Skripte gegen laufende Dienste. | Nach `scripts/` verschieben oder als Integrationstest mit Marker. |
Für eine CI-Pipeline wie bei Kansho: zuerst A beheben, B/D portieren, C entscheiden, E umziehen. Danach ist die Baseline ehrlich grün. Bis dahin läuft die volle Suite in `deploy/deploy.sh` nur informativ; blockierend sind die Container-Tests. Nächster Schritt dafür: eine explizite Liste dieser 17 Fälle, gegen die neue Fehler den Deploy stoppen.
## 5. Freigabe-Gates
| Gate | Inhalt | Wer |
| --- | --- | --- |
| **G0** | Repo `Lars/mindnet` auf privat stellen (oder anderes privates Ziel benennen); danach Push von `codex/privacy-gateway`, `develop`, `feature/containerization` | Lars |
| **G1** | Review dieses Stands; Merge `feature/containerization` → `develop` | Lars |
| **G2** | **Nur lesende** Prüfungen auf llm-node: Docker-/Compose-Version, Port-Bindung Qdrant/Ollama (`ss -ltnp`), `docker ps` (läuft `mindnet-embed`?), `pip freeze` der Prod-venv, NAS-Mount (`findmnt`), Lesbarkeit für UID 10001 | Freigabe Lars |
| **G3** | Dev-Container auf llm-node mit derselben Konfiguration wie systemd-Dev (`.env`, Vault, Qdrant-Präfix), parallel auf 8012/8512, `preflight --live`; `.gitea/workflows/deploy-dev.yml` aktiv, jeder Push auf `develop` deployt Dev | **freigegeben 28.10.2026** |
| **G4** | Prod-Container parallel zu systemd starten (nur lesend auf Prod-Qdrant, Vault `ro`), Vergleich der Antworten | Freigabe Lars |
| **G5** | Umschaltung Prod auf Container; systemd 2–3 Wochen als Rückfallebene; im selben Commit `deploy-prod.yml` aktivieren und `.gitea/workflows/deploy.yml` entfernen | Freigabe Lars; Voraussetzung R2, falls Schreibzugriff nötig |
### R2 – Pfadsicherheit beim Speichern (Pflicht vor beschreibbarem Vault)
`create_from_text` setzt `folder`/`filename` per `os.path.join` zusammen und schreibt ungeprüft. Die Container verhindern das derzeit nur über den schreibgeschützten Mount. Vor jedem beschreibbaren Prod-Vault: aufgelösten Zielpfad gegen den aufgelösten Vault prüfen, absolute Pfade und `..` ablehnen, Symlinks berücksichtigen, Überschreibregeln festlegen, Tests ergänzen. Zusätzlich gehört vor `/ingest/*` eine Zugriffsgrenze (Authentisierung).
### R3 – Section-Types (Pflichtkorrektur vor Integration von `SectionType`)
`_propagate_section_type_backwards` gruppiert fest auf H2 und überträgt den ersten Typ auf alle Blöcke. Zwei H3-Abschnitte mit unterschiedlichen Typen erhalten denselben Typ, und der H2-Elterntext wird umtypisiert (Reproduktion im Review). **Gesonderte Korrektur** auf dem `SectionType`-Branch mit verschachteltem Regressionstest. Erst danach Merge nach `develop`. In diesem Arbeitspaket bewusst nicht behoben.
## 6. Phase 2: Privacy Gateway im Container (Anforderungen)
Gilt für die spätere Anpassung von `require_local_endpoint` und `LocalDetector`. Grundsatz bleibt fail-closed.
**Zielverbindungen.** Eine Host-Allowlist mit einmaliger DNS-Auflösung reicht nicht. Zwischen Prüfung und Verbindung kann der Name auf eine andere Adresse zeigen (DNS-Rebinding), und Redirects oder Proxies können das Ziel wechseln. Anforderungen:
1. Allowlist erlaubter Dienste mit Name, Port und Schema (`ollama:11434`, `gliner:8090`), keine Wildcards.
2. Auflösung **pro Verbindung**; alle aufgelösten Adressen müssen in erlaubten Netzen liegen (bevorzugt im Compose-Subnetz statt pauschal RFC1918). Sonst Abbruch.
3. **Verbinden auf die geprüfte IP** (Pinning über eigenen httpx-Transport bzw. Resolver), Host-Header bzw. SNI bleibt der Name. Danach die tatsächliche Gegenstelle des Sockets (`getpeername`) gegen die geprüfte IP vergleichen.
4. `follow_redirects=False`, `trust_env=False` (keine Proxies), keine URL-Credentials; Antwort-Redirects sind Fehler.
5. Netzwerkseitig zusätzlich absichern: Detector und Ollama in einem `internal: true`-Netz ohne Internetzugang. Ausgehender Cloud-Verkehr nur aus dem API-Container und perspektivisch über einen Egress-Proxy mit Provider-Allowlist.
6. Tests: Rebinding-Simulation (zweite Auflösung liefert öffentliche IP), Redirect-Antwort, Proxy-Variablen gesetzt, IPv6-mapped-IPv4, Link-Local/Metadaten-IP (`169.254.169.254`).
**Ausfall der Personenerkennung.** Cloud-Aufrufe werden blockiert (`PrivacyError`, kein Fallback). Das ist im Gateway-Branch bereits so umgesetzt.
**Wiederholungsmechanismus für die Ingestion (Entwurf).** Bisher bekommt eine Notiz `status: error`, wenn die Kantenvalidierung an einem `PrivacyError` scheitert. Ziel ist eine nachvollziehbare, nicht stille Wiederholung:
1. **Kein Teil-Commit:** Note, Chunks und explizite Kanten werden geschrieben. Kandidaten-Kanten, deren Validierung nicht möglich war, werden **nicht** verworfen und **nicht** als validiert markiert. Sie bleiben mit `validation_state: pending` und einem Reason-Code (`local_detection_failed`, `local_endpoint_required`, …) erhalten.
2. **Persistente Warteschlange** im `data`-Volume (z. B. SQLite `data/ingest_retry.db`), Schlüssel `(note_id, content_hash)`: Versuchszähler, `next_attempt_at` mit exponentiellem Backoff, letzter Reason-Code. Keine Inhalte, nur Referenzen.
3. **Idempotenz:** Ändert sich die Notiz, wird der alte Eintrag durch den neuen Hash ersetzt. Wiederholung verarbeitet nur die offenen Kandidaten.
4. **Auslösung:** Zunächst **manuell** (CLI-Skript bzw. Admin-Endpoint). Ein automatischer Scheduler erst nach gesonderter Freigabe, weil er gegen Produktivdaten läuft.
5. **Sichtbarkeit:** `/admin/stats` und Healthcheck-Details melden Anzahl `pending`/`failed`; nach `max_attempts` Status `failed` mit Reason-Code, nie stilles Verwerfen.
6. **Tests:** Detector-Ausfall während der Ingestion → Note vorhanden, Kandidaten `pending`, Queue-Eintrag. Erneuter Lauf mit verfügbarem Detector → validiert, Eintrag entfernt.
## 7. Nächste Schritte
1. G0: Repo-Sichtbarkeit klären.
2. G1: Review/Merge von `feature/containerization` nach `develop`.
3. G2: lesende Prüfungen auf llm-node (Kommandos in [Container-Betrieb §4–5](../04_Operations/04_docker_deployment.md)).
4. Fix-Pakete A (query/retriever) und R3 separat; Gateway-Anpassung nach Abschnitt 6.
File diff suppressed because it is too large. Load diff
+2 -19
View File
@@ -2,9 +2,9 @@
# -*- coding: utf-8 -*-
"""
FILE: scripts/setup_mindnet_collections.py
VERSION: 2.2.0 (2026-01-25)
VERSION: 2.1.0 (2025-12-15)
STATUS: Active
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b), WP-26 (Intra-Note-Edges)
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
Zweck:
-------
@@ -107,12 +107,6 @@ class QdrantHTTP:
payload = {"field_name": field, "field_schema": {"type": "text"}}
self.rq("PUT", f"/collections/{collection}/index", json=payload)
print(f"[+] Index text on {collection}.{field}")
def create_bool_index(self, collection: str, field: str) -> None:
"""WP-26 v1.0: Boolean-Index für Filterung (z.B. is_internal)."""
payload = {"field_name": field, "field_schema": "bool"}
self.rq("PUT", f"/collections/{collection}/index", json=payload)
print(f"[+] Index bool on {collection}.{field}")
def list_collections(self) -> Dict[str, Any]:
r = self.rq("GET", "/collections")
@@ -135,9 +129,6 @@ def setup_mindnet_collections(q: QdrantHTTP, prefix: str, dim: int, distance: st
q.create_keyword_index(chunks, f)
for f in ["tags", "Rolle", "links"]:
q.create_keyword_index(chunks, f)
# WP-26 v1.0: note_type für Filterung (Section-Type vs Note-Type)
q.create_keyword_index(chunks, "note_type")
q.create_keyword_index(chunks, "type") # Effektiver Typ (section_type || note_type)
q.create_text_index(chunks, "text") # Volltextsuche auf dem Textfeld
# mindnet_notes: Metadaten der Notizen
@@ -154,16 +145,8 @@ def setup_mindnet_collections(q: QdrantHTTP, prefix: str, dim: int, distance: st
"dst_chunk_id",
"link_text",
"relation",
"kind", # WP-26 v1.0: Kantentyp für Filterung
"source_id", # WP-26 v1.0: Source-ID für Graph-Queries
"target_id", # WP-26 v1.0: Target-ID für Graph-Queries
"scope", # WP-26 v1.0: "chunk" oder "note"
"provenance", # WP-26 v1.0: Herkunft der Kante
]:
q.create_keyword_index(edges, f)
# WP-26 v1.0: Boolean-Index für is_internal (Intra-Note-Edge-Filterung)
q.create_bool_index(edges, "is_internal")
def parse_args() -> argparse.Namespace:
-561
View File
@@ -1,561 +0,0 @@
"""
FILE: scripts/test_wp26_comprehensive.py
DESCRIPTION: Umfassendes Test-Script für WP-26 - Prüft alle FA-Requirements
aus dem Lastenheft v1.3
VERSION: 1.0.0
"""
import sys
import os
from pathlib import Path
# Füge Projekt-Root zum Python-Pfad hinzu
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from typing import Dict, List, Tuple, Optional
from qdrant_client import QdrantClient
import yaml
import json
# Farben für Terminal-Output
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
BOLD = '\033[1m'
def print_header(text: str):
print(f"\n{Colors.BOLD}{Colors.BLUE}{'='*70}{Colors.RESET}")
print(f"{Colors.BOLD}{Colors.BLUE}{text}{Colors.RESET}")
print(f"{Colors.BOLD}{Colors.BLUE}{'='*70}{Colors.RESET}\n")
def print_success(text: str):
print(f"{Colors.GREEN}✓ {text}{Colors.RESET}")
def print_error(text: str):
print(f"{Colors.RED}✗ {text}{Colors.RESET}")
def print_warning(text: str):
print(f"{Colors.YELLOW}⚠ {text}{Colors.RESET}")
def print_info(text: str):
print(f" {text}")
# ============================================================================
# PHASE 1: Section-Types & Parsing
# ============================================================================
def test_fa01_section_callout_format():
"""FA-01: Neues Callout-Format [!section]"""
print_header("FA-01: Section-Callout-Format")
from app.core.chunking.chunking_parser import parse_blocks
markdown = """## Test Section ^test-id
> [!section] insight
Content here.
"""
blocks, _ = parse_blocks(markdown)
section_found = False
for block in blocks:
if block.section_type == "insight":
section_found = True
print_success(f"Section-Type 'insight' erkannt in Block: {block.text[:50]}...")
break
if not section_found:
print_error("Section-Type wurde nicht erkannt")
return False
return True
def test_fa01b_nested_edge_callouts():
"""FA-01b: Verschachtelte Edge-Callouts"""
print_header("FA-01b: Verschachtelte Edge-Callouts")
from app.core.graph.graph_derive_edges import extract_callout_relations
markdown = """> [!abstract] Semantic Edges
>> [!edge] derives
>> [[#^sit]]
>>
>> [!edge] supports
>> [[Target]]
"""
pairs, _ = extract_callout_relations(markdown)
if len(pairs) >= 2:
print_success(f"Verschachtelte Callouts erkannt: {len(pairs)} Edges gefunden")
for kind, target in pairs:
print_info(f" - {kind} -> {target}")
return True
else:
print_error(f"Verschachtelte Callouts nicht korrekt erkannt: {len(pairs)} Edges")
return False
def test_fa02_scope_termination():
"""FA-02: Scope-Beendigung"""
print_header("FA-02: Scope-Beendigung")
from app.core.chunking.chunking_parser import parse_blocks
markdown = """## Section A ^a
> [!section] insight
Content A.
## Section B ^b
<!-- Kein Callout -->
Content B (sollte note_type verwenden).
"""
blocks, _ = parse_blocks(markdown)
section_a_type = None
section_b_type = None
for block in blocks:
if "Section A" in block.text or block.section_type == "insight":
section_a_type = block.section_type
if "Section B" in block.text:
section_b_type = block.section_type
if section_a_type == "insight":
print_success(f"Section A hat korrekten Type: {section_a_type}")
else:
print_error(f"Section A hat falschen Type: {section_a_type}")
return False
# Section B sollte None haben (Fallback auf note_type)
if section_b_type is None:
print_success("Section B verwendet Fallback (None = note_type)")
else:
print_warning(f"Section B hat Type: {section_b_type} (erwartet: None)")
return True
def test_fa03_type_field():
"""FA-03: type-Feld-Befüllung mit effective_type"""
print_header("FA-03: type-Feld-Befüllung")
from app.core.ingestion.ingestion_chunk_payload import make_chunk_payloads
from app.core.chunking.chunking_parser import parse_blocks
from app.core.chunking.chunking_strategies import strategy_by_heading
# Mock Note
markdown = """---
type: experience
---
## Situation ^sit
> [!section] experience
Text.
## Reflexion ^ref
> [!section] insight
Text.
"""
blocks, h1_title = parse_blocks(markdown)
# Korrekte Signatur: strategy_by_heading(blocks, config, note_id, context_prefix)
config = {
"max": 500,
"target": 400,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, note_id="test-note")
# Erstelle Payloads
# Signatur: make_chunk_payloads(note, note_path, chunks_from_chunker, **kwargs)
payloads = make_chunk_payloads(
note={"frontmatter": {"type": "experience"}},
note_path="test.md",
chunks_from_chunker=chunks,
file_path="test.md",
types_cfg={}
)
# Prüfe effective_type
for p in payloads:
effective_type = p.get("type")
note_type = p.get("note_type")
section_type = p.get("section_type")
print_info(f"Chunk: type={effective_type}, note_type={note_type}, section_type={section_type}")
# Section-Type sollte Vorrang haben
if section_type:
if effective_type != section_type:
print_error(f"effective_type ({effective_type}) != section_type ({section_type})")
return False
print_success("effective_type wird korrekt berechnet (section_type || note_type)")
return True
def test_fa04_note_type_field():
"""FA-04: Optionales Feld note_type"""
print_header("FA-04: note_type-Feld")
from app.core.ingestion.ingestion_chunk_payload import make_chunk_payloads
from app.core.chunking.chunking_parser import parse_blocks
from app.core.chunking.chunking_strategies import strategy_by_heading
markdown = """---
type: experience
---
## Section ^sec
> [!section] insight
Text.
"""
blocks, _ = parse_blocks(markdown)
# Korrekte Signatur: strategy_by_heading(blocks, config, note_id, context_prefix)
config = {
"max": 500,
"target": 400,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, note_id="test-note")
# Signatur: make_chunk_payloads(note, note_path, chunks_from_chunker, **kwargs)
payloads = make_chunk_payloads(
note={"frontmatter": {"type": "experience"}},
note_path="test.md",
chunks_from_chunker=chunks,
file_path="test.md",
types_cfg={}
)
for p in payloads:
if "note_type" not in p:
print_error("note_type-Feld fehlt im Payload")
return False
if p["note_type"] != "experience":
print_error(f"note_type ist falsch: {p['note_type']} (erwartet: experience)")
return False
print_success("note_type-Feld ist vorhanden und korrekt")
return True
def test_fa05_block_reference():
"""FA-05: Block-Reference als Link-Format"""
print_header("FA-05: Block-Reference")
from app.core.graph.graph_utils import parse_link_target
# Test Block-ID-Extraktion
target, section = parse_link_target("[[#^block-id]]", "test-note")
if section == "block-id":
print_success(f"Block-ID korrekt extrahiert: {section}")
else:
print_error(f"Block-ID falsch extrahiert: {section} (erwartet: block-id)")
return False
# Test mit Section-String
target2, section2 = parse_link_target("[[#📖 Diagnose ^kontext]]", "test-note")
if section2 == "kontext":
print_success(f"Block-ID aus Section-String extrahiert: {section2}")
else:
print_error(f"Block-ID aus Section-String falsch: {section2} (erwartet: kontext)")
return False
return True
def test_fa07_is_internal_flag():
"""FA-07b: is_internal Flag"""
print_header("FA-07b: is_internal Flag")
from app.core.graph.graph_utils import _edge
# Intra-Note-Edge
edge1 = _edge("derives", "chunk", "note1#c01", "note1#c02", "note1", {})
if edge1.get("is_internal") is True:
print_success("Intra-Note-Edge hat is_internal=True")
else:
print_error(f"Intra-Note-Edge hat is_internal={edge1.get('is_internal')}")
return False
# Inter-Note-Edge (würde normalerweise False sein, aber _edge prüft nur note_id)
# Für echten Test müsste man build_edges_for_note aufrufen
return True
def test_fa08_default_edges_from_schema():
"""FA-08: Default-Edges aus graph_schema.md"""
print_header("FA-08: Default-Edges aus Schema")
from app.core.graph.graph_utils import get_typical_edge_for, clear_graph_schema_cache
clear_graph_schema_cache()
# Test für experience -> insight
edge_type = get_typical_edge_for("experience", "insight")
if edge_type:
print_success(f"Typische Edge gefunden: {edge_type}")
print_info(f" experience -> insight: {edge_type}")
else:
print_warning("Keine typische Edge gefunden (Fallback auf 'any' oder 'default')")
return True
# ============================================================================
# PHASE 2: Retriever-Anpassungen
# ============================================================================
def test_fa09_internal_edge_boost():
"""FA-09: Edge-Gewichtung für Intra-Note-Edges"""
print_header("FA-09: Internal Edge Boost")
from app.core.graph.graph_subgraph import Subgraph, get_edge_scoring_config
from app.core.graph.graph_utils import clear_graph_schema_cache
clear_graph_schema_cache()
get_edge_scoring_config.cache_clear()
config = get_edge_scoring_config()
if "internal_edge_boost" in config and "external_edge_boost" in config:
print_success(f"Edge-Scoring-Config geladen:")
print_info(f" internal_edge_boost: {config['internal_edge_boost']}")
print_info(f" external_edge_boost: {config['external_edge_boost']}")
# Test Subgraph
sg = Subgraph()
sg.add_edge({
"source": "note1#c01",
"target": "note1#c02",
"kind": "derives",
"weight": 1.0,
"is_internal": True
})
edges = sg.adj.get("note1#c01", [])
if edges:
final_weight = edges[0]["weight"]
expected_weight = 1.0 * config["internal_edge_boost"]
if abs(final_weight - expected_weight) < 0.01:
print_success(f"Boost korrekt angewendet: {final_weight} (erwartet: {expected_weight})")
else:
print_error(f"Boost falsch: {final_weight} (erwartet: {expected_weight})")
return False
else:
print_error("Edge-Scoring-Config fehlt")
return False
return True
def test_fa10_chunk_level_aggregation():
"""FA-10: Optionale Chunk-Level-Deduplizierung"""
print_header("FA-10: Aggregation-Level")
from app.core.retrieval.retriever import _get_aggregation_config
config = _get_aggregation_config()
if "level" in config and "max_chunks_per_note" in config:
print_success(f"Aggregation-Config geladen:")
print_info(f" level: {config['level']}")
print_info(f" max_chunks_per_note: {config['max_chunks_per_note']}")
if config["level"] in ["note", "chunk"]:
print_success("Aggregation-Level ist gültig")
else:
print_error(f"Aggregation-Level ist ungültig: {config['level']}")
return False
else:
print_error("Aggregation-Config fehlt")
return False
return True
# ============================================================================
# PHASE 3: Schema-Validierung
# ============================================================================
def test_fa12_schema_validation():
"""FA-12: Schema-Validierung gegen effektiven Chunk-Typ"""
print_header("FA-12: Schema-Validierung")
from app.core.ingestion.ingestion_validation import validate_intra_note_edge
from app.core.graph.graph_utils import clear_graph_schema_cache
clear_graph_schema_cache()
# Test 1: Typische Edge
edge1 = {"kind": "resulted_in", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk1 = {"type": "experience"}
target_chunk1 = {"type": "insight"}
is_valid1, confidence1, reason1 = validate_intra_note_edge(
edge=edge1,
source_chunk=source_chunk1,
target_chunk=target_chunk1,
strict_mode=False
)
if is_valid1:
print_success(f"Typische Edge validiert: {edge1['kind']} (confidence: {confidence1})")
else:
print_error(f"Typische Edge abgelehnt: {reason1}")
return False
# Test 2: Atypische Edge (sollte mit reduzierter Confidence erlaubt sein)
edge2 = {"kind": "very_unusual_edge_xyz123", "source_id": "chunk1", "target_id": "chunk2"}
is_valid2, confidence2, reason2 = validate_intra_note_edge(
edge=edge2,
source_chunk=source_chunk1,
target_chunk=target_chunk1,
strict_mode=False
)
if is_valid2 and confidence2 == 0.7:
print_success(f"Atypische Edge erlaubt mit reduzierter Confidence: {confidence2}")
else:
print_warning(f"Atypische Edge: valid={is_valid2}, confidence={confidence2}")
# Test 3: Effektiver Typ wird verwendet
edge3 = {"kind": "related_to", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk3 = {"type": "insight", "note_type": "experience"} # type hat Vorrang
target_chunk3 = {"type": "decision", "note_type": "experience"}
is_valid3, confidence3, reason3 = validate_intra_note_edge(
edge=edge3,
source_chunk=source_chunk3,
target_chunk=target_chunk3,
strict_mode=False
)
if is_valid3:
print_success("Effektiver Typ (type-Feld) wird für Validierung verwendet")
else:
print_error(f"Validierung mit effektivem Typ fehlgeschlagen: {reason3}")
return False
return True
# ============================================================================
# QDRANT-INTEGRATION TESTS
# ============================================================================
def test_qdrant_indices():
"""Prüft Qdrant-Indizes für WP-26"""
print_header("Qdrant-Indizes")
try:
client = QdrantClient("http://localhost:6333")
# Prüfe Collections
collections = client.get_collections().collections
chunks_collection = None
edges_collection = None
for col in collections:
if "chunks" in col.name.lower():
chunks_collection = col.name
if "edges" in col.name.lower():
edges_collection = col.name
if not chunks_collection or not edges_collection:
print_warning("Collections nicht gefunden - möglicherweise noch nicht initialisiert")
print_info("Führe 'python scripts/setup_mindnet_collections.py' aus")
return True # Nicht kritisch für Funktionalität
print_success(f"Collections gefunden: {chunks_collection}, {edges_collection}")
# Prüfe Indizes (vereinfacht - echte Prüfung würde Collection-Info benötigen)
print_info("Indizes sollten vorhanden sein für:")
print_info(" - chunks: note_type, type, block_id")
print_info(" - edges: is_internal (bool), kind, source_id, target_id")
return True
except Exception as e:
print_warning(f"Qdrant-Verbindung fehlgeschlagen: {e}")
print_info("Stelle sicher, dass Qdrant läuft: docker-compose up -d")
return True # Nicht kritisch
# ============================================================================
# MAIN
# ============================================================================
def main():
"""Führt alle Tests aus"""
print(f"\n{Colors.BOLD}{Colors.BLUE}")
print("="*70)
print("WP-26 Umfassende Funktionsprüfung")
print("Lastenheft v1.3 - Alle FA-Requirements")
print("="*70)
print(f"{Colors.RESET}\n")
tests = [
# Phase 1
("FA-01: Section-Callout-Format", test_fa01_section_callout_format),
("FA-01b: Verschachtelte Edge-Callouts", test_fa01b_nested_edge_callouts),
("FA-02: Scope-Beendigung", test_fa02_scope_termination),
("FA-03: type-Feld-Befüllung", test_fa03_type_field),
("FA-04: note_type-Feld", test_fa04_note_type_field),
("FA-05: Block-Reference", test_fa05_block_reference),
("FA-07b: is_internal Flag", test_fa07_is_internal_flag),
("FA-08: Default-Edges aus Schema", test_fa08_default_edges_from_schema),
# Phase 2
("FA-09: Internal Edge Boost", test_fa09_internal_edge_boost),
("FA-10: Aggregation-Level", test_fa10_chunk_level_aggregation),
# Phase 3
("FA-12: Schema-Validierung", test_fa12_schema_validation),
# Integration
("Qdrant-Indizes", test_qdrant_indices),
]
results = []
for test_name, test_func in tests:
try:
result = test_func()
results.append((test_name, result))
except Exception as e:
print_error(f"Test '{test_name}' fehlgeschlagen mit Exception: {e}")
import traceback
traceback.print_exc()
results.append((test_name, False))
# Zusammenfassung
print_header("ZUSAMMENFASSUNG")
passed = sum(1 for _, result in results if result)
total = len(results)
for test_name, result in results:
if result:
print_success(test_name)
else:
print_error(test_name)
print(f"\n{Colors.BOLD}Ergebnis: {passed}/{total} Tests bestanden{Colors.RESET}\n")
if passed == total:
print(f"{Colors.GREEN}{Colors.BOLD}✓ Alle Tests bestanden! WP-26 ist vollständig implementiert.{Colors.RESET}\n")
return 0
else:
print(f"{Colors.RED}{Colors.BOLD}✗ Einige Tests fehlgeschlagen. Bitte prüfe die Fehler oben.{Colors.RESET}\n")
return 1
if __name__ == "__main__":
sys.exit(main())
+78
View File
@@ -0,0 +1,78 @@
"""
FILE: tests/test_container_appenv.py
DESCRIPTION: Prüft deploy/appenv.py: Aus der unveränderten .env der systemd-Instanz
werden Vault-Mount und Präfix so abgeleitet, dass der Container dieselbe
Konfiguration nutzt; die Container-Datei darf nichts davon überschreiben.
"""
import importlib.util
import shlex
from pathlib import Path
import pytest
DEPLOY = Path(__file__).resolve().parents[1] / "deploy"
_spec = importlib.util.spec_from_file_location("mindnet_appenv", DEPLOY / "appenv.py")
appenv = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(appenv)
APP_ENV = "/home/llmadmin/mindnet_dev/.env"
def _files(tmp_path, app_text, container_text="MINDNET_UI_PORT=8512\n"):
app = tmp_path / "app.env"
app.write_text(app_text, encoding="utf-8")
container = tmp_path / "container.env"
container.write_text(container_text, encoding="utf-8")
return str(app), str(container)
def test_parse_handles_export_quotes_and_comments(tmp_path):
app, _ = _files(tmp_path, '# Kommentar\nexport A=1\nB="mit # Raute"\nC=wert # Kommentar\nD=\n')
assert appenv.parse(app) == {"A": "1", "B": "mit # Raute", "C": "wert", "D": ""}
@pytest.mark.parametrize("root, host, target", [
("./vault", "/home/llmadmin/mindnet_dev/vault", "/app/vault"),
("vault_dev", "/home/llmadmin/mindnet_dev/vault_dev", "/app/vault_dev"),
("../shared/vault", "/home/llmadmin/shared/vault", "/shared/vault"),
("/mnt/nas/vault/", "/mnt/nas/vault", "/mnt/nas/vault"),
])
def test_vault_mount_points_where_the_app_looks(root, host, target):
# Relativ: systemd löst gegen WorkingDirectory (= Ordner der .env) auf, der Container gegen /app.
assert appenv.vault_mount(APP_ENV, {"MINDNET_VAULT_ROOT": root}) == (host, target)
def test_vault_mount_uses_app_default_when_unset():
assert appenv.vault_mount(APP_ENV, {}) == ("/home/llmadmin/mindnet_dev/vault_master", "/app/vault_master")
def test_derive_takes_prefix_from_systemd_env(tmp_path):
app, container = _files(tmp_path, "COLLECTION_PREFIX=mindnet_dev\nMINDNET_VAULT_ROOT=/srv/vault\n")
derived = appenv.derive(app, container)
assert derived["MINDNET_EXPECTED_PREFIX"] == "mindnet_dev"
assert derived["MINDNET_VAULT_HOST_PATH"] == derived["MINDNET_VAULT_TARGET"] == "/srv/vault"
def test_derive_falls_back_to_app_default_prefix(tmp_path):
app, container = _files(tmp_path, "MINDNET_VAULT_ROOT=/srv/vault\n")
assert appenv.derive(app, container)["MINDNET_EXPECTED_PREFIX"] == "mindnet"
@pytest.mark.parametrize("key", ["COLLECTION_PREFIX", "MINDNET_VAULT_ROOT", "OPENROUTER_API_KEY", "QDRANT_URL"])
def test_container_env_must_not_override_app_config(tmp_path, key):
app, container = _files(tmp_path, "COLLECTION_PREFIX=mindnet_dev\n", f"MINDNET_UI_PORT=8512\n{key}=x\n")
with pytest.raises(appenv.AppEnvError, match=key):
appenv.derive(app, container)
def test_main_prints_shell_safe_assignments(tmp_path, capsys):
app, container = _files(tmp_path, "COLLECTION_PREFIX=mindnet_dev\nMINDNET_VAULT_ROOT=/srv/my vault\n")
assert appenv.main(["appenv.py", app, container]) == 0
lines = capsys.readouterr().out.splitlines()
parsed = dict(shlex.split(line)[0].split("=", 1) for line in lines)
assert parsed["MINDNET_VAULT_HOST_PATH"] == "/srv/my vault"
def test_main_reports_missing_file(tmp_path, capsys):
assert appenv.main(["appenv.py", str(tmp_path / "fehlt.env"), str(tmp_path / "auch.env")]) == 1
assert "appenv:" in capsys.readouterr().err
+258
View File
@@ -0,0 +1,258 @@
"""
FILE: tests/test_container_connectivity.py
DESCRIPTION: Prüft die Erreichbarkeitsprüfungen der Container-Bereitstellung gegen einen
lokalen Fake-Server (Ollama, Qdrant, Mindnet-API, Streamlit-UI):
- deploy/entrypoint.py: preflight --live (Dienste, Modelle, Dimensionen)
- deploy/smoke.py: Smoke-Test nach dem Start
Läuft ohne Docker und ohne echte Dienste (auch mit --network none).
"""
import importlib.util
import json
import threading
import urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
DEPLOY = Path(__file__).resolve().parents[1] / "deploy"
def _load(name):
spec = importlib.util.spec_from_file_location(f"mindnet_{name}", DEPLOY / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
ep = _load("entrypoint")
smoke = _load("smoke")
class FakeServices(ThreadingHTTPServer):
"""Ein Server für alle Dienste; Zustand pro Test über Attribute steuerbar."""
def __init__(self):
super().__init__(("127.0.0.1", 0), _Handler)
self.models = ["nomic-embed-text:latest", "phi3:mini"]
self.embedding_dim = 768
self.collections = {"mindnet_dev_notes": 768, "mindnet_dev_chunks": 768}
self.api_key = None
self.seen_headers = []
self.health = {"status": "ok", "prefix": "mindnet_dev"}
self.vector_size = 768
self.counts = {"notes": 12, "chunks": 80, "edges": 40}
self.ui_body = b"ok"
@property
def url(self):
return f"http://127.0.0.1:{self.server_address[1]}"
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _send(self, status, body):
data = body if isinstance(body, bytes) else json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
srv = self.server
self.rfile.read(int(self.headers.get("Content-Length") or 0))
if self.path == "/api/embeddings":
return self._send(200, {"embedding": [0.1] * srv.embedding_dim})
self._send(404, {})
def do_GET(self):
srv = self.server
srv.seen_headers.append(dict(self.headers))
if self.path.startswith("/collections") and srv.api_key and self.headers.get("api-key") != srv.api_key:
return self._send(401, {})
if self.path == "/api/tags":
return self._send(200, {"models": [{"name": m} for m in srv.models]})
if self.path == "/collections":
return self._send(200, {"result": {"collections": []}})
if self.path.startswith("/collections/"):
name = self.path.rsplit("/", 1)[1]
if name not in srv.collections:
return self._send(404, {})
size = srv.collections[name]
return self._send(200, {"result": {"config": {"params": {"vectors": {"size": size}}}}})
if self.path == "/healthz":
return self._send(200, srv.health)
if self.path == "/admin/stats":
collections = {k: {"name": f"mindnet_dev_{k}", "count": v} for k, v in srv.counts.items()}
return self._send(200, {"collections": collections, "config": {"vector_size": srv.vector_size}})
if self.path == "/_stcore/health":
return self._send(200, srv.ui_body)
self._send(404, {})
@pytest.fixture
def services():
srv = FakeServices()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
srv.server_close()
@pytest.fixture
def live_env(monkeypatch, services):
for key in ("QDRANT_API_KEY", "MINDNET_EXPECTED_VECTOR_DIM", "MINDNET_EXPECTED_EMBEDDING_MODEL"):
monkeypatch.delenv(key, raising=False)
monkeypatch.chdir(DEPLOY.parent)
monkeypatch.setenv("MINDNET_OLLAMA_URL", services.url)
monkeypatch.setenv("QDRANT_URL", services.url)
monkeypatch.setenv("COLLECTION_PREFIX", "mindnet_dev")
monkeypatch.setenv("MINDNET_LLM_MODEL", "phi3:mini")
return monkeypatch
def _closed_port_url():
srv = ThreadingHTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler)
port = srv.server_address[1]
srv.server_close()
return f"http://127.0.0.1:{port}"
# --- Dienst-URLs (statisch) -------------------------------------------------------------
@pytest.mark.parametrize("url", ["", "http://127.0.0.1:11434", "http://localhost:6333", "http://0.0.0.0:6333"])
def test_service_urls_reject_missing_or_container_local(monkeypatch, url):
monkeypatch.setenv("QDRANT_URL", "http://qdrant:6333")
monkeypatch.setenv("MINDNET_OLLAMA_URL", url)
with pytest.raises(ep.PreflightError, match="MINDNET_OLLAMA_URL"):
ep.check_service_urls()
def test_service_urls_accept_host_gateway_and_compose_service(monkeypatch):
monkeypatch.setenv("MINDNET_OLLAMA_URL", "http://host.docker.internal:11434")
monkeypatch.setenv("QDRANT_URL", "http://qdrant:6333")
ep.check_service_urls()
def test_required_models_come_from_ollama_profiles_and_chat_model(live_env):
live_env.setenv("MINDNET_LLM_MODEL", "llama3:8b")
assert {"nomic-embed-text", "phi3:mini", "llama3:8b"} <= ep.required_ollama_models()
# --- preflight --live ----------------------------------------------------------------------
def test_live_passes_when_everything_matches(live_env, capsys):
ep.check_live()
out = capsys.readouterr().out
assert "Ollama erreichbar" in out and "Qdrant erreichbar" in out
def test_live_reports_missing_ollama_model(live_env, services):
services.models = ["nomic-embed-text:latest"]
with pytest.raises(ep.PreflightError, match="phi3:mini"):
ep.check_live()
def test_live_does_not_accept_other_tag_as_latest(live_env, services):
services.models = ["nomic-embed-text:v1.5", "phi3:mini"]
with pytest.raises(ep.PreflightError, match="nomic-embed-text"):
ep.check_live()
def test_live_rejects_wrong_embedding_dimension(live_env, services):
services.embedding_dim = 384
with pytest.raises(ep.PreflightError, match="384 Dimensionen"):
ep.check_live()
def test_live_rejects_wrong_collection_dimension(live_env, services):
services.collections["mindnet_dev_chunks"] = 384
with pytest.raises(ep.PreflightError, match="mindnet_dev_chunks"):
ep.check_live()
def test_live_accepts_missing_collections(live_env, services, capsys):
services.collections = {}
ep.check_live()
assert "existiert noch nicht" in capsys.readouterr().out
def test_live_sends_qdrant_api_key(live_env, services):
services.api_key = "secret"
with pytest.raises(ep.PreflightError, match="HTTP 401"):
ep.check_live()
live_env.setenv("QDRANT_API_KEY", "secret")
ep.check_live()
@pytest.mark.parametrize("var", ["MINDNET_OLLAMA_URL", "QDRANT_URL"])
def test_live_unreachable_service_is_a_clear_error(live_env, var):
live_env.setenv(var, _closed_port_url())
with pytest.raises(ep.PreflightError, match="nicht erreichbar"):
ep.check_live()
def test_unreachable_host_gateway_hints_at_loopback_binding(monkeypatch):
def refuse(*args, **kwargs):
raise urllib.error.URLError(ConnectionRefusedError(111, "Connection refused"))
monkeypatch.setattr(ep.urllib.request, "urlopen", refuse)
with pytest.raises(ep.PreflightError, match="nur an 127.0.0.1"):
ep._fetch_json("http://host.docker.internal:11434/api/tags")
def test_preflight_live_exits_1_instead_of_traceback(live_env, monkeypatch, tmp_path):
root = tmp_path / "vault"
(root / "_system" / "dictionary").mkdir(parents=True)
(root / "_system" / "dictionary" / "edge_vocabulary.md").write_text("x", encoding="utf-8")
for key, value in {"MINDNET_ENV": "dev", "VECTOR_DIM": "768", "MINDNET_VAULT_ROOT": str(root),
"OPENROUTER_API_KEY": "", "GOOGLE_API_KEY": "", "MINDNET_EMBEDDING_MODEL": ""}.items():
monkeypatch.setenv(key, value)
monkeypatch.setattr(ep, "_is_read_only_mount", lambda path: True)
monkeypatch.setattr(ep, "check_service_urls", lambda: None) # Fake-Server läuft auf 127.0.0.1
assert ep.main(["entrypoint.py", "preflight", "--live"]) == 0
monkeypatch.setenv("QDRANT_URL", _closed_port_url())
assert ep.main(["entrypoint.py", "preflight", "--live"]) == 1
# --- smoke.py ---------------------------------------------------------------------------------
def _smoke(services, **kwargs):
return smoke.run(services.url, services.url, "mindnet_dev", attempts=1, **kwargs)
def test_smoke_ok(services, capsys):
assert _smoke(services) == 0
assert "smoke: OK" in capsys.readouterr().out
@pytest.mark.parametrize("change", [
lambda s: s.health.update(prefix="mindnet"),
lambda s: s.health.update(status="degraded"),
lambda s: setattr(s, "vector_size", 384),
lambda s: setattr(s, "ui_body", b"starting"),
])
def test_smoke_fails_on_wrong_state(services, change):
change(services)
assert _smoke(services) == 1
def test_smoke_unreachable_api():
url = _closed_port_url()
assert smoke.run(url, url, "mindnet_dev", attempts=1) == 1
def test_smoke_missing_collection_warns_in_dev_and_fails_with_require_data(services, capsys):
services.counts["edges"] = -1
assert _smoke(services) == 0
assert "WARNUNG" in capsys.readouterr().out
assert _smoke(services, require_data=True) == 1
def test_smoke_require_data_rejects_empty_notes(services):
services.counts["notes"] = 0
assert _smoke(services) == 0
assert _smoke(services, require_data=True) == 1
+318
View File
@@ -0,0 +1,318 @@
"""
FILE: tests/test_container_preflight.py
DESCRIPTION: Prüft Container-Preflight (deploy/entrypoint.py) und statisch die
Sicherheitszusagen der Compose-/Docker-Dateien. Läuft ohne Docker.
"""
import importlib.util
import re
from pathlib import Path
import pytest
import yaml
ROOT = Path(__file__).resolve().parents[1]
DEPLOY = ROOT / "deploy"
SYSTEMD_PORTS = {8001, 8002, 8501, 8502}
# WorkingDirectory der systemd-Units (llm-node), deren .env der Container unverändert liest.
SYSTEMD_ENV_FILES = {"dev": "/home/llmadmin/mindnet_dev/.env", "prod": "/home/llmadmin/mindnet/.env"}
def _load_deploy_module(name):
spec = importlib.util.spec_from_file_location(f"mindnet_{name}", DEPLOY / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
ep = _load_deploy_module("entrypoint")
@pytest.fixture
def env(monkeypatch):
for key in ("MINDNET_ENV", "COLLECTION_PREFIX", "VECTOR_DIM", "MINDNET_EMBEDDING_MODEL",
"OPENROUTER_API_KEY", "GOOGLE_API_KEY", "MINDNET_ALLOW_CLOUD_EGRESS",
"MINDNET_VAULT_ROOT", "MINDNET_VAULT_SENTINEL", "MINDNET_VAULT_READONLY",
"MINDNET_VAULT_REQUIRED", "MINDNET_EXPECTED_VECTOR_DIM"):
monkeypatch.delenv(key, raising=False)
monkeypatch.chdir(ROOT)
return monkeypatch
# --- Umgebung und Präfix ---------------------------------------------------------
@pytest.mark.parametrize("menv, prefix", [("", "mindnet"), ("staging", "mindnet"), ("prod", ""),
("dev", "mindnet"), ("prod", "mindnet_dev")])
def test_environment_rejects_ambiguous_setups(env, menv, prefix):
env.setenv("MINDNET_ENV", menv)
env.setenv("COLLECTION_PREFIX", prefix)
with pytest.raises(ep.PreflightError):
ep.check_environment()
@pytest.mark.parametrize("menv, prefix", [("dev", "mindnet_dev"), ("prod", "mindnet")])
def test_environment_accepts_explicit_setups(env, menv, prefix):
env.setenv("MINDNET_ENV", menv)
env.setenv("COLLECTION_PREFIX", prefix)
assert ep.check_environment() == menv
# --- Embeddings: keine stille Rückkehr zu 384 Dimensionen -----------------------
@pytest.mark.parametrize("dim", [None, "384", "3072"])
def test_embeddings_reject_wrong_or_missing_dim(env, dim):
if dim:
env.setenv("VECTOR_DIM", dim)
with pytest.raises(ep.PreflightError, match="VECTOR_DIM"):
ep.check_embeddings()
def test_embeddings_accept_repository_profile(env):
env.setenv("VECTOR_DIM", "768")
ep.check_embeddings()
def test_embeddings_reject_minilm_override(env):
env.setenv("VECTOR_DIM", "768")
env.setenv("MINDNET_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
with pytest.raises(ep.PreflightError, match="MINDNET_EMBEDDING_MODEL"):
ep.check_embeddings()
@pytest.mark.parametrize("profile", [
{"provider": "ollama", "model": "all-minilm", "dimensions": 384},
{"provider": "ollama", "model": "nomic-embed-text", "dimensions": 384},
{"provider": "ollama", "model": "nomic-embed-text"},
])
def test_embeddings_reject_bad_profile(env, tmp_path, profile):
env.setenv("VECTOR_DIM", "768")
path = tmp_path / "profiles.yaml"
path.write_text(yaml.safe_dump({"profiles": {"embedding_expert": profile}}), encoding="utf-8")
with pytest.raises(ep.PreflightError, match="embedding_expert"):
ep.check_embeddings(str(path))
# --- Cloud-Egress ------------------------------------------------------------------
def test_cloud_keys_require_explicit_ack(env):
env.setenv("OPENROUTER_API_KEY", "sk-test")
with pytest.raises(ep.PreflightError, match="MINDNET_ALLOW_CLOUD_EGRESS"):
ep.check_cloud_egress()
env.setenv("MINDNET_ALLOW_CLOUD_EGRESS", "true")
ep.check_cloud_egress()
def test_no_cloud_keys_needs_no_ack(env):
ep.check_cloud_egress()
# --- Vault / NAS -----------------------------------------------------------------------
def _vault(tmp_path, with_content=True):
root = tmp_path / "vault"
root.mkdir()
if with_content:
(root / "notiz.md").write_text("# Notiz", encoding="utf-8")
return root
def test_vault_missing_directory(env, tmp_path):
env.setenv("MINDNET_VAULT_ROOT", str(tmp_path / "nope"))
with pytest.raises(ep.PreflightError, match="fehlt"):
ep.check_vault()
def test_vault_empty_mountpoint_is_detected(env, tmp_path):
# Ausgefallenes NAS: Mountpunkt existiert, ist aber leer.
env.setenv("MINDNET_VAULT_ROOT", str(_vault(tmp_path, with_content=False)))
with pytest.raises(ep.PreflightError, match="leer"):
ep.check_vault()
def test_vault_needs_no_specific_file_by_default(env, tmp_path):
# Wie systemd: jeder Vault-Aufbau ist zulässig (vault_master hat kein _system/).
env.setenv("MINDNET_VAULT_ROOT", str(_vault(tmp_path)))
env.setattr(ep, "_is_read_only_mount", lambda path: True)
ep.check_vault()
def test_vault_optional_sentinel_is_enforced(env, tmp_path):
env.setenv("MINDNET_VAULT_ROOT", str(_vault(tmp_path)))
env.setenv("MINDNET_VAULT_SENTINEL", "_system/dictionary/edge_vocabulary.md")
with pytest.raises(ep.PreflightError, match="Sentinel"):
ep.check_vault()
def test_vault_must_be_read_only(env, tmp_path):
env.setenv("MINDNET_VAULT_ROOT", str(_vault(tmp_path)))
env.setattr(ep, "_is_read_only_mount", lambda path: False)
with pytest.raises(ep.PreflightError, match="schreibgeschützt"):
ep.check_vault()
env.setattr(ep, "_is_read_only_mount", lambda path: True)
ep.check_vault()
def test_read_only_check_fails_closed_without_statvfs(env, tmp_path):
env.delattr(ep.os, "statvfs", raising=False)
assert ep._is_read_only_mount(tmp_path) is False
def test_unknown_mode_is_rejected():
assert ep.main(["entrypoint.py", "shell"]) == 2
# --- Statische Prüfung der Deployment-Dateien ---------------------------------------
def _compose(name):
return yaml.safe_load((DEPLOY / name).read_text(encoding="utf-8"))
def _host_port(mapping):
m = re.search(r":(?:\$\{[A-Z_]+:-)?(\d+)\}?:\d+$", mapping)
return int(m.group(1))
COMPOSE = {"dev": _compose("compose.dev.yml"), "prod": _compose("compose.prod.yml")}
APP_SERVICES = ("api", "ui")
def test_compose_projects_are_separate():
assert COMPOSE["dev"]["name"] == "mindnet-dev"
assert COMPOSE["prod"]["name"] == "mindnet-prod"
assert set(COMPOSE["dev"]["networks"]).isdisjoint(COMPOSE["prod"]["networks"])
def test_compose_ports_do_not_collide():
ports = {e: {_host_port(p) for s in c["services"].values() for p in s.get("ports", [])}
for e, c in COMPOSE.items()}
assert ports["dev"].isdisjoint(ports["prod"])
assert not (ports["dev"] | ports["prod"]) & SYSTEMD_PORTS
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_compose_app_services_hardened(envname):
for name in APP_SERVICES:
svc = COMPOSE[envname]["services"][name]
assert svc["read_only"] is True
assert svc["cap_drop"] == ["ALL"]
assert "no-new-privileges:true" in svc["security_opt"]
assert svc["environment"]["VECTOR_DIM"] == "768"
assert svc["environment"]["MINDNET_VAULT_READONLY"] == "true"
assert svc["healthcheck"]["test"][-1] == name
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_compose_vault_is_read_only_bind_without_autocreate(envname):
mounts = [v for v in COMPOSE[envname]["services"]["api"]["volumes"]
if isinstance(v, dict) and v.get("type") == "bind"]
assert len(mounts) == 1
assert mounts[0]["target"].startswith("${MINDNET_VAULT_TARGET:?") # aus der systemd-.env abgeleitet
assert mounts[0]["read_only"] is True
assert mounts[0]["bind"]["create_host_path"] is False
assert not [v for v in COMPOSE[envname]["services"]["ui"]["volumes"] if isinstance(v, dict)]
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_compose_api_defaults_to_loopback(envname):
assert all(p.startswith("${MINDNET_API_BIND:-127.0.0.1}:") for p in COMPOSE[envname]["services"]["api"]["ports"])
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_compose_uses_existing_host_services_and_app_config(envname):
# Wie systemd: gemeinsame Host-Qdrant und Host-Ollama; Präfix/Vault aus der systemd-.env.
assert set(COMPOSE[envname]["services"]) == set(APP_SERVICES)
for name in APP_SERVICES:
env = COMPOSE[envname]["services"][name]["environment"]
assert env["MINDNET_ENV"] == envname
assert env["QDRANT_URL"] == "http://host.docker.internal:6333"
assert env["MINDNET_OLLAMA_URL"] == "http://host.docker.internal:11434"
assert not {"COLLECTION_PREFIX", "MINDNET_VAULT_ROOT", "MINDNET_VOCAB_PATH"} & set(env)
def test_dockerfile_pinned_and_non_root():
text = (DEPLOY / "Dockerfile").read_text(encoding="utf-8")
assert re.search(r"ARG PYTHON_IMAGE=python:3\.12-slim-bookworm@sha256:[0-9a-f]{64}", text)
runtime = text.split("AS runtime", 1)[1].split("AS test", 1)[0]
assert "USER mindnet:mindnet" in runtime
assert "--require-hashes" in text
def test_lock_excludes_torch_and_minilm_and_is_hashed():
lock = (DEPLOY / "requirements.lock").read_text(encoding="utf-8")
pins = re.findall(r"^([a-z0-9][a-z0-9._-]*)==", lock, re.M)
assert pins and not {"torch", "sentence-transformers", "transformers"} & set(pins)
entries = re.split(r"\n(?=[a-z0-9])", lock.strip())
assert all("--hash=sha256:" in e for e in entries if re.match(r"[a-z0-9]", e))
def test_dockerignore_is_allowlist_without_env_files():
lines = [l.strip() for l in (ROOT / ".dockerignore").read_text(encoding="utf-8").splitlines()
if l.strip() and not l.startswith("#")]
assert lines[0] == "**"
assert "config/*.env" in lines and "deploy/env/*.env" in lines
assert not any(l.startswith("!") and ("vault" in l or ".env" in l) for l in lines)
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_container_env_example_has_only_container_keys(envname):
appenv = _load_deploy_module("appenv")
values = appenv.parse(str(DEPLOY / "env" / f"{envname}.env.example"))
assert set(values) <= appenv.CONTAINER_KEYS
assert values["MINDNET_ALLOW_CLOUD_EGRESS"] == "false"
# --- Gitea-Workflows und Deploy-Skript (Muster wie Kansho: develop -> dev, main -> prod) ----
WORKFLOWS = {"deploy-dev.yml": ROOT / ".gitea" / "workflows", # aktiv
"deploy-prod.yml": DEPLOY / "gitea-workflows"} # Vorlage bis zur Umschaltung
def _workflow(name):
data = yaml.safe_load((WORKFLOWS[name] / name).read_text(encoding="utf-8"))
return data, data.get("on", data.get(True)) # PyYAML liest den Schlüssel 'on' als True
@pytest.mark.parametrize("name, branch, envname", [("deploy-dev.yml", "develop", "dev"),
("deploy-prod.yml", "main", "prod")])
def test_workflow_maps_branch_to_environment(name, branch, envname):
wf, on = _workflow(name)
assert on["push"]["branches"] == [branch]
job = wf["jobs"]["deploy"]
assert job["runs-on"] == "linux_host"
assert job["env"]["MINDNET_ENV_FILE"].startswith("/") and job["env"]["MINDNET_ENV_FILE"].endswith("container.env")
assert job["env"]["MINDNET_APP_ENV_FILE"] == SYSTEMD_ENV_FILES[envname]
assert any(s.get("run") == f"bash deploy/deploy.sh {envname}" for s in job["steps"])
def test_prod_workflow_shares_concurrency_with_systemd_deploy():
wf, _ = _workflow("deploy-prod.yml")
systemd = yaml.safe_load((ROOT / ".gitea" / "workflows" / "deploy.yml").read_text(encoding="utf-8"))
assert wf["concurrency"]["group"] == systemd["concurrency"]["group"]
def test_deploy_script_checks_before_touching_running_stack():
script = (DEPLOY / "deploy.sh").read_text(encoding="utf-8")
assert "\r" not in script
steps = script.split('step "1/5', 1)[1] # ohne Kopfkommentar und Funktionsdefinitionen
order = [steps.index(s) for s in ("--network none", "preflight --live", "up -d --wait --no-build --remove-orphans && smoke")]
assert order == sorted(order)
assert "preflight --live" in script and "run --rm --no-deps api preflight" in script
assert "--require-data" in script and "deploy/appenv.py" in script
assert "last_good_tag" in script
@pytest.mark.parametrize("envname", ["dev", "prod"])
def test_compose_reads_systemd_env_then_container_env(envname):
files = COMPOSE[envname]["x-hardening"]["env_file"]
assert files[0].startswith("${MINDNET_APP_ENV_FILE:?")
assert files[1] == f"${{MINDNET_ENV_FILE:-env/{envname}.env}}"
def test_prod_workflow_not_active_before_switchover():
assert not (ROOT / ".gitea" / "workflows" / "deploy-prod.yml").exists()
@pytest.mark.parametrize("name", ["deploy-dev.yml", "deploy-prod.yml"])
def test_workflow_needs_no_external_actions(name):
# Der Runner-Host soll ohne Internet/DNS deployen können (kein github.com).
wf, _ = _workflow(name)
assert not [s["uses"] for s in wf["jobs"]["deploy"]["steps"] if "uses" in s]
-240
View File
@@ -1,240 +0,0 @@
"""
FILE: tests/test_wp26_phase2_retriever.py
DESCRIPTION: Unit-Tests für WP-26 Phase 2: Retriever-Anpassungen
- is_internal-Boost für Intra-Note-Edges
- Konfigurierbare Aggregation (Note/Chunk Level)
VERSION: 1.0.0
"""
import pytest
from unittest.mock import patch, MagicMock
import os
class TestEdgeScoringConfig:
"""UT-19: Edge-Scoring-Konfiguration"""
def test_get_edge_scoring_config_defaults(self):
"""Default-Werte werden korrekt geladen"""
from app.core.graph.graph_subgraph import get_edge_scoring_config
# Cache leeren
get_edge_scoring_config.cache_clear()
# Mit nicht-existierender Config-Datei
with patch.dict(os.environ, {"MINDNET_RETRIEVER_CONFIG": "/nonexistent/path.yaml"}):
get_edge_scoring_config.cache_clear()
config = get_edge_scoring_config()
assert config["internal_edge_boost"] == 1.2
assert config["external_edge_boost"] == 1.0
def test_get_edge_scoring_config_from_yaml(self):
"""Werte werden aus YAML geladen"""
from app.core.graph.graph_subgraph import get_edge_scoring_config
# Cache leeren und echte Config laden
get_edge_scoring_config.cache_clear()
# Mit echter Config-Datei
config = get_edge_scoring_config()
# Die Werte sollten den Defaults entsprechen (aus retriever.yaml)
assert config["internal_edge_boost"] >= 1.0
assert config["external_edge_boost"] >= 1.0
class TestIsInternalBoost:
"""UT-20: is_internal-Boost im Subgraph"""
def test_internal_edge_gets_boost(self):
"""Intra-Note-Edges erhalten höheres Gewicht"""
from app.core.graph.graph_subgraph import Subgraph, get_edge_scoring_config
# Cache leeren
get_edge_scoring_config.cache_clear()
sg = Subgraph()
# Interne Edge (innerhalb derselben Note)
sg.add_edge({
"source": "note1#c01",
"target": "note1#c02",
"kind": "derives",
"weight": 1.0,
"is_internal": True
})
# Prüfe, dass das Gewicht erhöht wurde
edges = sg.adj.get("note1#c01", [])
assert len(edges) == 1
internal_boost = get_edge_scoring_config()["internal_edge_boost"]
assert edges[0]["weight"] == 1.0 * internal_boost
assert edges[0]["is_internal"] is True
def test_external_edge_no_boost(self):
"""Inter-Note-Edges erhalten keinen Boost"""
from app.core.graph.graph_subgraph import Subgraph, get_edge_scoring_config
# Cache leeren
get_edge_scoring_config.cache_clear()
sg = Subgraph()
# Externe Edge (zwischen verschiedenen Notes)
sg.add_edge({
"source": "note1#c01",
"target": "note2#c01",
"kind": "references",
"weight": 1.0,
"is_internal": False
})
edges = sg.adj.get("note1#c01", [])
assert len(edges) == 1
external_boost = get_edge_scoring_config()["external_edge_boost"]
assert edges[0]["weight"] == 1.0 * external_boost
assert edges[0]["is_internal"] is False
def test_edge_bonus_aggregation_with_internal(self):
"""Edge-Bonus aggregiert korrekt mit is_internal-Boost"""
from app.core.graph.graph_subgraph import Subgraph, get_edge_scoring_config
get_edge_scoring_config.cache_clear()
sg = Subgraph()
# Zwei Edges: eine interne, eine externe
sg.add_edge({
"source": "note1",
"target": "note2",
"kind": "solves",
"weight": 1.5,
"is_internal": True
})
sg.add_edge({
"source": "note1",
"target": "note3",
"kind": "references",
"weight": 0.1,
"is_internal": False
})
# Aggregierter Bonus
bonus = sg.edge_bonus("note1")
# Sollte > 0 sein
assert bonus > 0
class TestAggregationConfig:
"""UT-21: Aggregation-Konfiguration"""
def test_get_aggregation_config_defaults(self):
"""Default-Werte werden korrekt geladen"""
from app.core.retrieval.retriever import _get_aggregation_config
# Mit nicht-existierender Config-Datei
with patch.dict(os.environ, {"MINDNET_RETRIEVER_CONFIG": "/nonexistent/path.yaml"}):
config = _get_aggregation_config()
assert config["level"] == "note"
assert config["max_chunks_per_note"] == 3
def test_get_aggregation_config_from_yaml(self):
"""Werte werden aus YAML geladen"""
from app.core.retrieval.retriever import _get_aggregation_config
config = _get_aggregation_config()
# Die Werte sollten aus retriever.yaml kommen
assert config["level"] in ["note", "chunk"]
assert config["max_chunks_per_note"] >= 1
class TestNoteLevelAggregation:
"""UT-22: Note-Level Aggregation mit max_chunks_per_note"""
def test_note_level_limits_chunks(self):
"""Note-Level-Aggregation limitiert Chunks pro Note"""
# Mock-Daten: 5 Chunks von Note1, 3 Chunks von Note2
mock_hits = [
("c1", 0.9, {"note_id": "note1", "chunk_id": "c1"}),
("c2", 0.85, {"note_id": "note1", "chunk_id": "c2"}),
("c3", 0.8, {"note_id": "note2", "chunk_id": "c3"}),
("c4", 0.75, {"note_id": "note1", "chunk_id": "c4"}),
("c5", 0.7, {"note_id": "note2", "chunk_id": "c5"}),
("c6", 0.65, {"note_id": "note1", "chunk_id": "c6"}),
("c7", 0.6, {"note_id": "note1", "chunk_id": "c7"}),
]
# Simuliere Note-Level-Aggregation mit max_chunks_per_note=2
max_chunks_per_note = 2
pooled = []
note_count = {}
for pid, score, payload in sorted(mock_hits, key=lambda x: x[1], reverse=True):
note_id = payload["note_id"]
if note_count.get(note_id, 0) < max_chunks_per_note:
pooled.append((pid, score, payload))
note_count[note_id] = note_count.get(note_id, 0) + 1
# Erwartung: 2 von note1, 2 von note2 = 4 Chunks
assert len(pooled) == 4
# Prüfe, dass jede Note maximal 2 Chunks hat
note1_chunks = [p for p in pooled if p[2]["note_id"] == "note1"]
note2_chunks = [p for p in pooled if p[2]["note_id"] == "note2"]
assert len(note1_chunks) == 2
assert len(note2_chunks) == 2
class TestChunkLevelAggregation:
"""UT-23: Chunk-Level Aggregation (keine Deduplizierung)"""
def test_chunk_level_no_dedup(self):
"""Chunk-Level-Aggregation gibt alle Chunks zurück"""
mock_hits = [
("c1", 0.9, {"note_id": "note1"}),
("c2", 0.85, {"note_id": "note1"}),
("c3", 0.8, {"note_id": "note1"}),
("c4", 0.75, {"note_id": "note1"}),
("c5", 0.7, {"note_id": "note1"}),
]
# Chunk-Level: Keine Deduplizierung
aggregation_level = "chunk"
if aggregation_level == "chunk":
pooled = mock_hits
else:
pooled = [] # Note-Level würde nur 1 behalten
# Alle 5 Chunks sollten erhalten bleiben
assert len(pooled) == 5
class TestQdrantIndexSetup:
"""UT-24: Qdrant-Index-Setup"""
def test_bool_index_method_exists(self):
"""create_bool_index Methode existiert"""
from scripts.setup_mindnet_collections import QdrantHTTP
q = QdrantHTTP("http://localhost:6333")
assert hasattr(q, "create_bool_index")
def test_setup_includes_is_internal_index(self):
"""Setup-Funktion enthält is_internal Index"""
import inspect
from scripts.setup_mindnet_collections import setup_mindnet_collections
# Prüfe den Quellcode der Funktion
source = inspect.getsource(setup_mindnet_collections)
assert "is_internal" in source
assert "create_bool_index" in source
if __name__ == "__main__":
pytest.main([__file__, "-v"])
-331
View File
@@ -1,331 +0,0 @@
"""
FILE: tests/test_wp26_phase3_validation.py
DESCRIPTION: Unit-Tests für WP-26 Phase 3: Schema-Validierung für Intra-Note-Edges
- FA-12: Validierung gegen effektiven Chunk-Typ
- get_topology_info() Funktion
- validate_intra_note_edge() Funktion
VERSION: 1.0.0
"""
import pytest
from typing import Dict, List, Optional
class TestLoadGraphSchemaFull:
"""UT-25: Erweitertes Schema-Laden mit prohibited Edges"""
def test_load_graph_schema_full_returns_dict(self):
"""Schema wird korrekt geladen"""
from app.core.graph.graph_utils import load_graph_schema_full, clear_graph_schema_cache
clear_graph_schema_cache()
schema = load_graph_schema_full()
assert isinstance(schema, dict)
def test_schema_contains_typical_and_prohibited(self):
"""Schema enthält sowohl typical als auch prohibited Listen"""
from app.core.graph.graph_utils import load_graph_schema_full, clear_graph_schema_cache
clear_graph_schema_cache()
schema = load_graph_schema_full()
# Prüfe, dass mindestens ein Eintrag existiert
if schema:
for source_type, targets in schema.items():
for target_type, edge_info in targets.items():
assert "typical" in edge_info
assert "prohibited" in edge_info
assert isinstance(edge_info["typical"], list)
assert isinstance(edge_info["prohibited"], list)
class TestGetTopologyInfo:
"""UT-26: get_topology_info() Funktion"""
def test_get_topology_info_returns_dict(self):
"""get_topology_info() gibt Dict mit typical und prohibited zurück"""
from app.core.graph.graph_utils import get_topology_info, clear_graph_schema_cache
clear_graph_schema_cache()
topology = get_topology_info("experience", "insight")
assert isinstance(topology, dict)
assert "typical" in topology
assert "prohibited" in topology
def test_get_topology_info_fallback(self):
"""Fallback für unbekannte Typen gibt Defaults zurück"""
from app.core.graph.graph_utils import get_topology_info, clear_graph_schema_cache
clear_graph_schema_cache()
topology = get_topology_info("unknown_type_xyz", "another_unknown")
# Fallback sollte mindestens related_to oder references enthalten
assert isinstance(topology["typical"], list)
assert isinstance(topology["prohibited"], list)
def test_get_topology_info_experience_to_insight(self):
"""Typische Edge von experience zu insight"""
from app.core.graph.graph_utils import get_topology_info, clear_graph_schema_cache
clear_graph_schema_cache()
topology = get_topology_info("experience", "insight")
# Basierend auf graph_schema.md
assert len(topology["typical"]) > 0 or len(topology["prohibited"]) == 0
class TestValidateIntraNoteEdge:
"""UT-27: validate_intra_note_edge() Funktion"""
def test_validate_typical_edge_returns_true(self):
"""Typische Edge wird akzeptiert mit Confidence 1.0"""
from app.core.ingestion.ingestion_validation import validate_intra_note_edge
# Mock-Daten
edge = {"kind": "resulted_in", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk = {"type": "experience"}
target_chunk = {"type": "insight"}
is_valid, confidence, reason = validate_intra_note_edge(
edge=edge,
source_chunk=source_chunk,
target_chunk=target_chunk,
strict_mode=False
)
# Edge sollte akzeptiert werden
assert is_valid is True
assert confidence >= 0.7 # Mindestens 0.7 (atypisch) oder 1.0 (typisch)
def test_validate_atypical_edge_reduced_confidence(self):
"""Atypische Edge wird akzeptiert mit reduzierter Confidence"""
from app.core.ingestion.ingestion_validation import validate_intra_note_edge
# Mock-Daten mit sehr ungewöhnlicher Edge
edge = {"kind": "very_unusual_edge_type_xyz", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk = {"type": "experience"}
target_chunk = {"type": "insight"}
is_valid, confidence, reason = validate_intra_note_edge(
edge=edge,
source_chunk=source_chunk,
target_chunk=target_chunk,
strict_mode=False
)
# Atypische Edge sollte akzeptiert werden, aber mit reduzierter Confidence
assert is_valid is True
assert confidence == 0.7
assert reason is not None
def test_validate_atypical_edge_strict_mode_rejected(self):
"""Atypische Edge wird im Strict-Mode abgelehnt"""
from app.core.ingestion.ingestion_validation import validate_intra_note_edge
# Mock-Daten
edge = {"kind": "very_unusual_edge_type_xyz", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk = {"type": "experience"}
target_chunk = {"type": "insight"}
is_valid, confidence, reason = validate_intra_note_edge(
edge=edge,
source_chunk=source_chunk,
target_chunk=target_chunk,
strict_mode=True
)
# Im Strict-Mode sollte die Edge abgelehnt werden
assert is_valid is False
assert confidence == 0.0
def test_validate_uses_effective_type(self):
"""Validierung verwendet effektiven Typ (section_type über note_type)"""
from app.core.ingestion.ingestion_validation import validate_intra_note_edge
# Chunk hat sowohl type (effektiv) als auch note_type
edge = {"kind": "related_to", "source_id": "chunk1", "target_id": "chunk2"}
source_chunk = {"type": "insight", "note_type": "experience"} # type hat Vorrang
target_chunk = {"type": "decision", "note_type": "experience"}
is_valid, confidence, reason = validate_intra_note_edge(
edge=edge,
source_chunk=source_chunk,
target_chunk=target_chunk,
strict_mode=False
)
# Edge sollte gegen insight->decision validiert werden
assert is_valid is True
class TestValidateEdgeAgainstSchema:
"""UT-28: validate_edge_against_schema() Wrapper-Funktion"""
def test_non_internal_edge_passes(self):
"""Nicht-interne Edges werden ohne Schema-Check durchgelassen"""
from app.core.ingestion.ingestion_validation import validate_edge_against_schema
edge = {
"kind": "references",
"source_id": "note1#chunk1",
"target_id": "note2#chunk1",
"is_internal": False
}
chunks_by_id = {}
is_valid, updated_edge = validate_edge_against_schema(
edge=edge,
chunks_by_id=chunks_by_id,
strict_mode=False
)
assert is_valid is True
assert updated_edge == edge
def test_internal_edge_validated(self):
"""Interne Edges werden gegen Schema validiert"""
from app.core.ingestion.ingestion_validation import validate_edge_against_schema
edge = {
"kind": "derived_from",
"source_id": "chunk1",
"target_id": "chunk2",
"is_internal": True,
"confidence": 1.0
}
chunks_by_id = {
"chunk1": {"type": "insight"},
"chunk2": {"type": "experience"}
}
is_valid, updated_edge = validate_edge_against_schema(
edge=edge,
chunks_by_id=chunks_by_id,
strict_mode=False
)
assert is_valid is True
def test_missing_chunks_passes(self):
"""Wenn Chunks nicht gefunden werden, wird Edge erlaubt (Integrität vor Präzision)"""
from app.core.ingestion.ingestion_validation import validate_edge_against_schema
edge = {
"kind": "derived_from",
"source_id": "chunk1",
"target_id": "chunk2",
"is_internal": True
}
chunks_by_id = {} # Keine Chunks
is_valid, updated_edge = validate_edge_against_schema(
edge=edge,
chunks_by_id=chunks_by_id,
strict_mode=False
)
assert is_valid is True
class TestSchemaValidationIntegration:
"""UT-29: Integration der Schema-Validierung"""
def test_clear_cache_clears_both_caches(self):
"""clear_graph_schema_cache() löscht beide Caches"""
from app.core.graph.graph_utils import (
load_graph_schema,
load_graph_schema_full,
clear_graph_schema_cache,
_GRAPH_SCHEMA_CACHE,
_GRAPH_SCHEMA_FULL_CACHE
)
# Lade beide Schemas
load_graph_schema()
load_graph_schema_full()
# Cache leeren
clear_graph_schema_cache()
# Module-Level Variablen prüfen (Zugriff über import)
import app.core.graph.graph_utils as utils_module
assert utils_module._GRAPH_SCHEMA_CACHE is None
assert utils_module._GRAPH_SCHEMA_FULL_CACHE is None
def test_topology_info_consistent_with_typical_edges(self):
"""get_topology_info() ist konsistent mit get_typical_edge_for()"""
from app.core.graph.graph_utils import (
get_topology_info,
get_typical_edge_for,
clear_graph_schema_cache
)
clear_graph_schema_cache()
# Test für experience -> insight
topology = get_topology_info("experience", "insight")
typical_edge = get_typical_edge_for("experience", "insight")
# Wenn get_typical_edge_for einen Wert zurückgibt, sollte er in typical sein
if typical_edge and topology["typical"]:
assert typical_edge in topology["typical"]
class TestConfidenceAdjustment:
"""UT-30: Confidence-Anpassung bei atypischen Edges"""
def test_atypical_edge_confidence_reduced(self):
"""Atypische Edge erhält reduzierte Confidence (0.7)"""
from app.core.ingestion.ingestion_validation import validate_edge_against_schema
edge = {
"kind": "completely_unknown_edge_type_xyz123",
"source_id": "chunk1",
"target_id": "chunk2",
"is_internal": True,
"confidence": 1.0
}
chunks_by_id = {
"chunk1": {"type": "experience"},
"chunk2": {"type": "insight"}
}
is_valid, updated_edge = validate_edge_against_schema(
edge=edge,
chunks_by_id=chunks_by_id,
strict_mode=False
)
assert is_valid is True
# Confidence sollte auf 0.7 reduziert worden sein (da atypisch)
assert updated_edge.get("confidence") == 0.7
def test_schema_validation_note_added(self):
"""Atypische Edge erhält Validierungs-Notiz"""
from app.core.ingestion.ingestion_validation import validate_edge_against_schema
edge = {
"kind": "completely_unknown_edge_type_xyz123",
"source_id": "chunk1",
"target_id": "chunk2",
"is_internal": True,
"confidence": 1.0
}
chunks_by_id = {
"chunk1": {"type": "experience"},
"chunk2": {"type": "insight"}
}
is_valid, updated_edge = validate_edge_against_schema(
edge=edge,
chunks_by_id=chunks_by_id,
strict_mode=False
)
# Validierungs-Notiz sollte hinzugefügt worden sein
assert "schema_validation_note" in updated_edge
if __name__ == "__main__":
pytest.main([__file__, "-v"])
-725
View File
@@ -1,725 +0,0 @@
"""
FILE: tests/test_wp26_section_types.py
DESCRIPTION: Unit-Tests für WP-26 Phase 1: Section-Types und Intra-Note-Edges
WP-26 v1.1: Erweitert um Tests für Section-Split und automatische Edges
WP-26 v1.3: Erweitert um Tests für rückwirkende section_type Propagation
VERSION: 1.4.0 (WP-26 v1.4: Automatische Backlinks)
"""
import pytest
from app.core.chunking.chunking_parser import parse_blocks
from app.core.chunking.chunking_models import RawBlock, Chunk
from app.core.chunking.chunking_strategies import strategy_by_heading, strategy_sliding_window
from app.core.graph.graph_utils import (
normalize_provenance, _edge, get_typical_edge_for,
load_graph_schema, clear_graph_schema_cache
)
class TestSectionTypeRecognition:
"""UT-01: Parser – Section-Type-Erkennung"""
def test_section_type_recognition(self):
"""Testet, ob [!section]-Callouts korrekt erkannt werden."""
md = """
## Reflexion ^ref
> [!section] insight
Content here about insights.
"""
blocks, _ = parse_blocks(md)
# Finde den Paragraph-Block nach dem Section-Callout
paragraph_blocks = [b for b in blocks if b.kind == "paragraph"]
assert len(paragraph_blocks) >= 1
# Der Paragraph-Block sollte section_type "insight" haben
assert paragraph_blocks[0].section_type == "insight"
def test_section_type_with_block_id(self):
"""Testet, ob Block-IDs in Überschriften korrekt extrahiert werden."""
md = """
## Situation ^sit
> [!section] experience
Die Geschichte beginnt hier.
"""
blocks, _ = parse_blocks(md)
# Finde den Heading-Block
heading_blocks = [b for b in blocks if b.kind == "heading"]
assert len(heading_blocks) >= 1
# Block-ID sollte "sit" sein
assert heading_blocks[0].block_id == "sit"
def test_section_type_propagated_backwards_to_heading(self):
"""WP-26 v1.3: section_type wird rückwirkend auf das Heading propagiert."""
md = """
## Lektion ^learning
Einleitender Text ohne section callout.
Noch mehr Text hier...
> [!section] insight
Und dann kommt der eigentliche Insight-Content.
"""
blocks, _ = parse_blocks(md)
# Finde den Heading-Block
heading_blocks = [b for b in blocks if b.kind == "heading"]
assert len(heading_blocks) >= 1
# WP-26 v1.3: Das Heading sollte section_type "insight" haben
# (rückwirkend propagiert, obwohl [!section] später im Abschnitt steht)
assert heading_blocks[0].section_type == "insight", \
f"Heading sollte section_type 'insight' haben, hat aber: {heading_blocks[0].section_type}"
# Alle Paragraphen in dieser Sektion sollten auch section_type "insight" haben
paragraphs = [b for b in blocks if b.kind == "paragraph"]
for p in paragraphs:
assert p.section_type == "insight", \
f"Paragraph sollte section_type 'insight' haben: {p.text[:50]}"
class TestSectionTypeScope:
"""UT-02: Parser – Scope-Beendigung"""
def test_section_type_scope_ends_at_same_level_heading(self):
"""Section-Type endet bei nächster H2."""
md = """
## Section A
> [!section] insight
Content A with insight.
## Section B
Content B without section callout.
"""
blocks, _ = parse_blocks(md)
# Finde Paragraph-Blöcke
paragraphs = [b for b in blocks if b.kind == "paragraph"]
# Erster Paragraph hat section_type "insight"
assert paragraphs[0].section_type == "insight"
# Zweiter Paragraph hat section_type None (Reset)
assert paragraphs[1].section_type is None
class TestProvenanceNormalization:
"""UT für Provenance-Normalisierung (WP-26 v1.0)"""
def test_normalize_explicit_callout(self):
"""explicit:callout -> (explicit, callout)"""
prov, hint = normalize_provenance("explicit:callout")
assert prov == "explicit"
assert hint == "callout"
def test_normalize_explicit_wikilink(self):
"""explicit:wikilink -> (explicit, wikilink)"""
prov, hint = normalize_provenance("explicit:wikilink")
assert prov == "explicit"
assert hint == "wikilink"
def test_normalize_structure_belongs_to(self):
"""structure:belongs_to -> (structure, belongs_to)"""
prov, hint = normalize_provenance("structure:belongs_to")
assert prov == "structure"
assert hint == "belongs_to"
def test_normalize_schema_default(self):
"""inferred:schema -> (rule, schema_default)"""
prov, hint = normalize_provenance("inferred:schema")
assert prov == "rule"
assert hint == "schema_default"
def test_normalize_unknown_fallback(self):
"""Unbekannte Provenance -> (explicit, None)"""
prov, hint = normalize_provenance("unknown_provenance")
assert prov == "explicit"
assert hint is None
class TestIsInternalFlag:
"""UT-13: is_internal Flag für Intra-Note-Edges"""
def test_is_internal_true_for_same_note(self):
"""Edges zwischen Chunks derselben Note haben is_internal=True"""
edge = _edge(
kind="derives",
scope="chunk",
source_id="note1#c01",
target_id="note1#c02",
note_id="note1"
)
assert edge["is_internal"] is True
def test_is_internal_false_for_different_notes(self):
"""Edges zwischen verschiedenen Notes haben is_internal=False"""
edge = _edge(
kind="references",
scope="chunk",
source_id="note1#c01",
target_id="note2#c01",
note_id="note1"
)
assert edge["is_internal"] is False
def test_is_internal_true_for_note_to_chunk(self):
"""Edges von Note zu eigenem Chunk haben is_internal=True"""
edge = _edge(
kind="belongs_to",
scope="chunk",
source_id="note1#c01",
target_id="note1",
note_id="note1"
)
assert edge["is_internal"] is True
class TestEdgeProvenanceInPayload:
"""Test für Provenance-Normalisierung in Edge-Payloads"""
def test_edge_provenance_normalized(self):
"""Provenance wird in Edge-Payloads normalisiert"""
edge = _edge(
kind="derives",
scope="chunk",
source_id="note1#c01",
target_id="note1#c02",
note_id="note1",
extra={"provenance": "explicit:callout"}
)
assert edge["provenance"] == "explicit"
assert edge["source_hint"] == "callout"
class TestAutomaticSectionRecognition:
"""UT-09: Automatische Section-Erkennung bei neuen Überschriften"""
def test_automatic_section_recognition_at_same_heading_level(self):
"""Neue Überschriften auf gleicher Ebene starten automatisch neue Sections"""
md = """
## Situation ^sit
> [!section] experience
Content A.
## Reflexion ^ref
Content B.
## Learnings ^learn
> [!section] insight
Content C.
## Ausblick ^out
Content D.
"""
blocks, _ = parse_blocks(md)
# Sammle alle Paragraph-Blöcke in Reihenfolge
paragraphs = [b for b in blocks if b.kind == "paragraph"]
assert len(paragraphs) == 4
# Chunk 1: Expliziter section_type "experience"
assert paragraphs[0].section_type == "experience"
# Chunk 2: Neue Section ohne Callout → None (Fallback auf note_type)
assert paragraphs[1].section_type is None
# Chunk 3: Expliziter section_type "insight"
assert paragraphs[2].section_type == "insight"
# Chunk 4: Neue Section ohne Callout → None (Fallback auf note_type)
assert paragraphs[3].section_type is None
class TestSeparateSectionCallout:
"""UT-10: Separates Section-Callout an beliebiger Stelle"""
def test_section_callout_separate_from_edge_callout(self):
"""Section-Callout kann separat von Edge-Callouts stehen"""
md = """
## Reflexion ^ref
Einleitender Text hier...
> [!section] insight
Weiterer normaler Inhalt...
> [!edge] derives
> [[#^sit]]
"""
blocks, _ = parse_blocks(md)
# Finde Paragraph-Blöcke nach dem Section-Callout
paragraphs = [b for b in blocks if b.kind == "paragraph"]
# Es sollten mindestens 2 Paragraphen geben
assert len(paragraphs) >= 2
# Der erste Paragraph hat noch keinen section_type (vor dem Callout)
# Der zweite Paragraph hat section_type "insight"
# Hinweis: Die genaue Zuordnung hängt von der Parser-Implementierung ab
section_types = [p.section_type for p in paragraphs]
assert "insight" in section_types
class TestNestedEdgeCallouts:
"""UT-08: Verschachtelte Edge-Callouts in Container"""
def test_nested_callouts_recognized(self):
"""Verschachtelte Callouts werden als Callout-Blöcke erkannt"""
md = """
> [!abstract] Semantic Edges
>> [!edge] derived_from
>> [[Target1#Section]]
>
>> [!edge] solves
>> [[Target2]]
"""
blocks, _ = parse_blocks(md)
# Finde Callout-Blöcke
callouts = [b for b in blocks if b.kind == "callout"]
# Es sollte mindestens ein Callout-Block erkannt werden
assert len(callouts) >= 1
# =============================================================================
# WP-26 v1.1: Tests für Section-Type-Wechsel und automatische Chunk-Splits
# =============================================================================
class TestSectionTypeSplit:
"""UT-14: Section-Type-Wechsel erzwingt neuen Chunk"""
def test_section_type_change_forces_new_chunk_by_heading(self):
"""Section-Type-Wechsel erzwingt neuen Chunk (by_heading Strategie)"""
md = """
## Situation ^sit
> [!section] experience
Die Geschichte beginnt hier.
## Reflexion ^ref
> [!section] insight
Erkenntnisse aus der Situation.
"""
blocks, _ = parse_blocks(md)
# Konfiguration: strict=False (würde normalerweise zusammenfassen)
config = {
"target": 1000, # Hoher Wert, um sicherzustellen, dass nicht wegen Token-Limit gesplittet wird
"max": 2000,
"split_level": 2,
"strict_heading_split": False, # Normalerweise würde zusammengefasst
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, "test-note")
# Es sollten mindestens 2 Chunks geben (wegen Section-Type-Wechsel)
assert len(chunks) >= 2
# Prüfe, dass die Chunks unterschiedliche section_types haben
section_types = [c.section_type for c in chunks if c.section_type]
assert "experience" in section_types
assert "insight" in section_types
def test_same_section_type_follows_normal_behavior(self):
"""Gleicher Section-Type folgt normalem Chunking-Verhalten"""
md = """
## Section A
> [!section] experience
Content A about experience.
## Section B
> [!section] experience
Content B also about experience.
"""
blocks, _ = parse_blocks(md)
# Konfiguration: strict=False (würde zusammenfassen bei gleichem Typ)
config = {
"target": 1000,
"max": 2000,
"split_level": 2,
"strict_heading_split": False,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, "test-note")
# Bei gleichem section_type und strict=False könnten Chunks zusammengefasst werden
# (abhängig von Token-Limits)
# Wichtig: Alle Chunks sollten section_type "experience" haben
for c in chunks:
if c.section_type:
assert c.section_type == "experience"
def test_sliding_window_respects_section_type_change(self):
"""sliding_window Strategie respektiert Section-Type-Wechsel"""
md = """
## Part 1
> [!section] experience
Short content.
## Part 2
> [!section] insight
Another short content.
"""
blocks, _ = parse_blocks(md)
config = {
"target": 1000, # Hoher Wert
"max": 2000
}
chunks = strategy_sliding_window(blocks, config, "test-note")
# Bei Section-Type-Wechsel sollte gesplittet werden
section_types = [c.section_type for c in chunks if c.section_type]
# Beide Typen sollten in separaten Chunks sein
if len(section_types) >= 2:
assert "experience" in section_types or "insight" in section_types
class TestGraphSchemaParser:
"""UT-15: Graph-Schema Parser Tests"""
def test_get_typical_edge_experience_to_insight(self):
"""Typischer Edge von experience zu insight ist 'resulted_in'"""
# Lade Schema (falls verfügbar)
edge = get_typical_edge_for("experience", "insight")
# Sollte entweder 'resulted_in' oder Fallback 'related_to' sein
assert edge in ["resulted_in", "related_to"]
def test_get_typical_edge_insight_to_decision(self):
"""Typischer Edge von insight zu decision"""
edge = get_typical_edge_for("insight", "decision")
# Basierend auf graph_schema.md: foundation_for oder guides
# Fallback über "any"-Regel: references oder related_to
assert edge in ["foundation_for", "guides", "related_to", "references"]
def test_get_typical_edge_fallback(self):
"""Fallback auf 'related_to' für unbekannte Typen"""
edge = get_typical_edge_for("unknown_type_1", "unknown_type_2")
# Fallback sollte immer related_to sein
assert edge == "related_to"
def test_get_typical_edge_any_target(self):
"""Fallback auf 'any' Target-Regel"""
edge = get_typical_edge_for("experience", "unknown_target")
# Sollte Fallback auf "any"-Regel oder "related_to"
assert edge is not None
class TestAutomaticIntraNoteEdges:
"""UT-16: Automatische Intra-Note-Edges zwischen Sektionen"""
def test_edge_payload_has_section_transition(self):
"""Edge zwischen Sektionen enthält section_transition Metadaten"""
edge = _edge(
kind="resulted_in",
scope="chunk",
source_id="note1#c00",
target_id="note1#c01",
note_id="note1",
extra={
"provenance": "rule",
"rule_id": "inferred:section_transition",
"section_transition": "experience->insight",
"is_internal": True
}
)
assert edge["is_internal"] is True
assert edge["section_transition"] == "experience->insight"
assert edge["provenance"] == "rule"
def test_inferred_section_transition_provenance(self):
"""Provenance 'inferred:section_transition' wird korrekt normalisiert"""
prov, hint = normalize_provenance("inferred:section_transition")
assert prov == "rule"
assert hint == "schema_default"
class TestRealWorldScenario:
"""UT-17: Real-World Szenario - Krebsdiagnose Note"""
def test_krebsdiagnose_note_structure(self):
"""Testet die erwartete Struktur der Krebsdiagnose-Note"""
md = """
## 📖 Diagnose: Glioblastom ^kontext
Nach der Operation gab es ein Diagnose-Gespräch.
## 🎭 Emotions-Check ^emotionen
Ich reagierte mit Zittern am Körper.
## 💡 Lektion ^learning
> [!section] insight
Ich habe versucht die nächsten Schritte zu durchdenken.
Meine positive Einstellung hat mir geholfen.
"""
blocks, _ = parse_blocks(md)
# Konfiguration wie structured_smart_edges
config = {
"target": 400,
"max": 600,
"split_level": 2,
"strict_heading_split": False,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, "krebsdiagnose")
# Wegen Section-Type-Wechsel (None -> insight) sollte die Lektion
# ein separater Chunk sein
insight_chunks = [c for c in chunks if c.section_type == "insight"]
# Mindestens ein Chunk mit section_type "insight"
assert len(insight_chunks) >= 1
# WP-26 v1.2: Der insight-Chunk MUSS die Überschrift "💡 Lektion" enthalten!
# (Nicht nur den Inhalt nach dem [!section] Callout)
insight_text = insight_chunks[0].text
assert "Lektion" in insight_text, f"Überschrift '💡 Lektion' fehlt im insight-Chunk: {insight_text[:100]}"
assert "durchdenken" in insight_text.lower() or "positive" in insight_text.lower()
def test_section_type_change_in_smart_mode_forces_split(self):
"""WP-26 v1.1 Fix: Section-Type-Wechsel erzwingt Split auch in SMART MODE (Schritt 2)"""
md = """
## Section A ohne Typ
Inhalt A ohne section_type.
## Section B ohne Typ
Inhalt B ohne section_type.
## Section C mit Typ
> [!section] insight
Inhalt C mit section_type "insight".
"""
blocks, _ = parse_blocks(md)
# SMART MODE: strict=False, smart_edge=True
# Token-Limit hoch genug, dass alles zusammengefasst werden KÖNNTE
config = {
"target": 2000,
"max": 4000,
"split_level": 2,
"strict_heading_split": False,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, "test-note")
# Trotz hohem Token-Limit sollte Section C ein separater Chunk sein
# wegen Section-Type-Wechsel (None -> insight)
assert len(chunks) >= 2, f"Erwartet mindestens 2 Chunks, bekommen: {len(chunks)}"
# Der letzte Chunk sollte section_type "insight" haben
insight_chunks = [c for c in chunks if c.section_type == "insight"]
assert len(insight_chunks) >= 1, "Kein Chunk mit section_type 'insight' gefunden"
def test_heading_belongs_to_new_section_with_section_type(self):
"""WP-26 v1.2: Heading gehört zur neuen Sektion wenn [!section] folgt"""
md = """
## Section A
Inhalt ohne section_type.
## Section B mit Typ
> [!section] insight
Inhalt mit section_type.
"""
blocks, _ = parse_blocks(md)
config = {
"target": 2000,
"max": 4000,
"split_level": 2,
"strict_heading_split": False,
"enable_smart_edge_allocation": True
}
chunks = strategy_by_heading(blocks, config, "test-note")
# Es sollten 2 Chunks geben
assert len(chunks) == 2, f"Erwartet 2 Chunks, bekommen: {len(chunks)}"
# Chunk 1: Section A (section_type = None)
assert chunks[0].section_type is None
assert "Section A" in chunks[0].text
assert "Section B" not in chunks[0].text # Heading B darf NICHT in Chunk 1 sein!
# Chunk 2: Section B (section_type = insight) - MUSS die Überschrift enthalten!
assert chunks[1].section_type == "insight"
assert "Section B mit Typ" in chunks[1].text, "Überschrift 'Section B mit Typ' muss im insight-Chunk sein!"
class TestBlockIdParsing:
"""UT-18: Block-ID-Extraktion aus Section-Referenzen"""
def test_block_id_extraction_from_section(self):
"""Block-ID wird aus Section-String extrahiert"""
from app.core.graph.graph_utils import parse_link_target
# Test: Überschrift mit Block-ID
target, section = parse_link_target("#📖 Diagnose: Glioblastom ^kontext", "note1")
assert target == "note1" # Self-Link
assert section == "kontext", f"Erwartet 'kontext', bekommen: {section}"
def test_block_id_extraction_only_caret(self):
"""Nur Block-ID mit ^"""
from app.core.graph.graph_utils import parse_link_target
target, section = parse_link_target("#^learning", "note1")
assert target == "note1"
assert section == "learning"
def test_block_id_extraction_with_spaces(self):
"""Block-ID mit Text davor"""
from app.core.graph.graph_utils import parse_link_target
target, section = parse_link_target("OtherNote#🎭 Emotions-Check ^emotionen", None)
assert target == "OtherNote"
assert section == "emotionen"
def test_section_without_block_id(self):
"""Section ohne Block-ID bleibt unverändert"""
from app.core.graph.graph_utils import parse_link_target
target, section = parse_link_target("Note#Normale Überschrift", None)
assert target == "Note"
assert section == "Normale Überschrift"
class TestAutomaticBacklinks:
"""UT-18: Automatische Backlinks für Intra-Note-Edges (WP-26 v1.4)"""
def test_backlink_created_for_intra_note_edge(self):
"""Backlink wird automatisch für Intra-Note-Edge erstellt"""
from app.core.graph.graph_derive_edges import build_edges_for_note
# Mock-Chunks mit Section-Types
chunks = [
{
"chunk_id": "note1#c01",
"type": "experience",
"section_type": "experience",
"window": "Situation text"
},
{
"chunk_id": "note1#c02",
"type": "insight",
"section_type": "insight",
"window": "Reflexion text"
}
]
edges = build_edges_for_note(
note_id="note1",
chunks=chunks,
note_level_references=None,
include_note_scope_refs=False,
markdown_body=""
)
# Prüfe, dass sowohl Forward-Edge als auch Backlink vorhanden sind
forward_edges = [e for e in edges if e.get("source_id") == "note1#c01" and e.get("target_id") == "note1#c02"]
backlink_edges = [e for e in edges if e.get("source_id") == "note1#c02" and e.get("target_id") == "note1#c01"]
assert len(forward_edges) > 0, "Forward-Edge sollte vorhanden sein"
assert len(backlink_edges) > 0, "Backlink sollte automatisch erstellt werden"
# Prüfe Backlink-Eigenschaften
backlink = backlink_edges[0]
assert backlink.get("is_internal") is True
assert backlink.get("scope") == "chunk"
assert backlink.get("provenance") == "rule"
assert backlink.get("rule_id") == "derived:intra_note_backlink"
def test_backlink_not_created_if_already_exists(self):
"""Backlink wird nicht erstellt, wenn bereits ein inverser Edge existiert"""
from app.core.graph.graph_derive_edges import build_edges_for_note
# Mock-Chunks
chunks = [
{
"chunk_id": "note1#c01",
"type": "experience",
"section_type": "experience",
"window": "Situation text",
"candidate_pool": [
{
"kind": "derived_from", # Inverser Edge-Type
"to": "note1#c02",
"provenance": "explicit:callout"
}
]
},
{
"chunk_id": "note1#c02",
"type": "insight",
"section_type": "insight",
"window": "Reflexion text",
"candidate_pool": [
{
"kind": "derives", # Forward-Edge
"to": "note1#c01",
"provenance": "explicit:callout"
}
]
}
]
edges = build_edges_for_note(
note_id="note1",
chunks=chunks,
note_level_references=None,
include_note_scope_refs=False,
markdown_body=""
)
# Zähle Backlinks (sollte nicht dupliziert werden)
backlink_edges = [e for e in edges
if e.get("source_id") == "note1#c01"
and e.get("target_id") == "note1#c02"
and e.get("kind") == "derived_from"]
# Sollte genau einen Backlink geben (der explizite, nicht zusätzlich automatischer)
assert len(backlink_edges) == 1, f"Erwartet genau einen Backlink, gefunden: {len(backlink_edges)}"
if __name__ == "__main__":
pytest.main([__file__, "-v"])