Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd5056d4c9 | ||
|
|
39fb821481 | ||
|
|
beb87a8c43 | ||
|
|
4327fc939c | ||
|
|
ef1046c6f5 | ||
|
|
ef8cf719f2 | ||
|
|
6aa6b32a6c | ||
|
|
33dff04d47 | ||
|
|
65d697b7be | ||
|
|
06fc42ed37 | ||
|
|
3c5c567077 | ||
|
|
8f65e550c8 | ||
|
|
6b83879741 | ||
|
|
be265e9cc0 | ||
|
|
680c36ab59 | ||
|
|
96b4f65cd1 | ||
|
|
b1a897e51c | ||
|
|
e5a34efee9 | ||
|
|
f9ac4e4dbf | ||
|
|
1b40e29f40 | ||
|
|
7eba1fb487 | ||
|
|
838083b909 | ||
|
|
8f5eb36b5f | ||
|
|
b7d1bcce3d | ||
|
|
03d3173ca6 | ||
|
|
38a61d7b50 | ||
|
|
0a429e1f7b | ||
|
|
857ba953e3 | ||
|
|
e180018c99 | ||
|
|
ac9956bf00 | ||
|
|
62b5a8bf65 | ||
|
|
303efefcb7 | ||
|
|
feeb7c2d92 | ||
|
|
ea9a54421a | ||
|
|
fdf99b2bb0 | ||
|
|
c7cd641f89 | ||
|
|
18b90c8df3 | ||
|
|
8d3bc1c2e2 | ||
|
|
079d988034 | ||
|
|
aa9d388337 | ||
|
|
92bd3d9a47 | ||
|
|
53058d1504 | ||
|
|
3fe8463a03 | ||
|
|
5c4ce5d727 | ||
|
|
459193e7b1 | ||
|
|
98f21323fb | ||
|
|
515248d438 | ||
|
|
b0c69ad3e0 | ||
|
|
c5f29ab4ae | ||
|
|
876ee898d8 | ||
|
|
e93bab6ea7 | ||
|
|
5225090490 | ||
|
|
e9532e8878 |
No files matched your search
@@ -1,6 +1,8 @@
|
||||
"""
|
||||
FILE: app/core/chunking/chunking_parser.py
|
||||
DESCRIPTION: Zerlegt Markdown in Blöcke und extrahiert Kanten-Strings.
|
||||
DESCRIPTION: Zerlegt Markdown in logische Einheiten (RawBlocks).
|
||||
Hält alle Überschriftenebenen (H1-H6) im Stream.
|
||||
Stellt die Funktion parse_edges_robust zur Verfügung.
|
||||
"""
|
||||
import re
|
||||
from typing import List, Tuple, Set
|
||||
@@ -11,69 +13,86 @@ _WS = re.compile(r'\s+')
|
||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
|
||||
|
||||
def split_sentences(text: str) -> list[str]:
|
||||
"""Teilt Text in Sätze auf."""
|
||||
"""Teilt Text in Sätze auf unter Berücksichtigung deutscher Interpunktion."""
|
||||
text = _WS.sub(' ', text.strip())
|
||||
if not text: return []
|
||||
# Splittet bei Punkt, Ausrufezeichen oder Fragezeichen, gefolgt von Leerzeichen und Großbuchstabe
|
||||
return [p.strip() for p in _SENT_SPLIT.split(text) if p.strip()]
|
||||
|
||||
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||
"""Zerlegt Text in logische Einheiten."""
|
||||
"""Zerlegt Text in logische Einheiten (RawBlocks), inklusive H1-H6."""
|
||||
blocks = []
|
||||
h1_title = "Dokument"; section_path = "/"; current_h2 = None
|
||||
h1_title = "Dokument"
|
||||
section_path = "/"
|
||||
current_section_title = None
|
||||
|
||||
# Frontmatter entfernen
|
||||
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||
|
||||
# H1 für Note-Titel extrahieren (Metadaten-Zweck)
|
||||
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||
if h1_match: h1_title = h1_match.group(1).strip()
|
||||
if h1_match:
|
||||
h1_title = h1_match.group(1).strip()
|
||||
|
||||
lines = text_without_fm.split('\n')
|
||||
buffer = []
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
# H1 ignorieren (ist Doc Title)
|
||||
if stripped.startswith('# '):
|
||||
continue
|
||||
|
||||
# Generische Heading-Erkennung (H2 bis H6) für flexible Split-Levels
|
||||
heading_match = re.match(r'^(#{2,6})\s+(.*)', stripped)
|
||||
# Heading-Erkennung (H1 bis H6)
|
||||
heading_match = re.match(r'^(#{1,6})\s+(.*)', stripped)
|
||||
if heading_match:
|
||||
# Buffer leeren (vorherigen Text abschließen)
|
||||
# Vorherigen Text-Block abschließen
|
||||
if buffer:
|
||||
content = "\n".join(buffer).strip()
|
||||
if content: blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||
if content:
|
||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||
buffer = []
|
||||
|
||||
level = len(heading_match.group(1))
|
||||
title = heading_match.group(2).strip()
|
||||
|
||||
# Pfad-Logik: H2 setzt den Haupt-Pfad
|
||||
if level == 2:
|
||||
current_h2 = title
|
||||
section_path = f"/{current_h2}"
|
||||
# Bei H3+ bleibt der section_path beim Parent, aber das Level wird korrekt gesetzt
|
||||
# Pfad- und Titel-Update für die Metadaten der folgenden Blöcke
|
||||
if level == 1:
|
||||
current_section_title = title; section_path = "/"
|
||||
elif level == 2:
|
||||
current_section_title = title; section_path = f"/{current_section_title}"
|
||||
|
||||
blocks.append(RawBlock("heading", stripped, level, section_path, current_h2))
|
||||
|
||||
elif not stripped:
|
||||
# Die Überschrift selbst als regulären Block hinzufügen
|
||||
blocks.append(RawBlock("heading", stripped, level, section_path, current_section_title))
|
||||
continue
|
||||
|
||||
# Trenner (---) oder Leerzeilen beenden Blöcke, außer innerhalb von Callouts
|
||||
if (not stripped or stripped == "---") and not line.startswith('>'):
|
||||
if buffer:
|
||||
content = "\n".join(buffer).strip()
|
||||
if content: blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||
if content:
|
||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||
buffer = []
|
||||
if stripped == "---":
|
||||
blocks.append(RawBlock("separator", "---", None, section_path, current_section_title))
|
||||
else:
|
||||
buffer.append(line)
|
||||
|
||||
if buffer:
|
||||
content = "\n".join(buffer).strip()
|
||||
if content: blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||
if content:
|
||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||
|
||||
return blocks, h1_title
|
||||
|
||||
def parse_edges_robust(text: str) -> Set[str]:
|
||||
"""Extrahiert Kanten-Kandidaten (Wikilinks, Callouts)."""
|
||||
"""Extrahiert Kanten-Kandidaten aus Wikilinks und Callouts."""
|
||||
found_edges = set()
|
||||
# 1. Wikilinks [[rel:kind|target]]
|
||||
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
||||
for kind, target in inlines:
|
||||
k = kind.strip().lower()
|
||||
t = target.strip()
|
||||
if k and t: found_edges.add(f"{k}:{t}")
|
||||
|
||||
# 2. Callout Edges > [!edge] kind
|
||||
lines = text.split('\n')
|
||||
current_edge_type = None
|
||||
for line in lines:
|
||||
@@ -81,13 +100,16 @@ def parse_edges_robust(text: str) -> Set[str]:
|
||||
callout_match = re.match(r'>\s*\[!edge\]\s*([^:\s]+)', stripped)
|
||||
if callout_match:
|
||||
current_edge_type = callout_match.group(1).strip().lower()
|
||||
# Links in der gleichen Zeile des Callouts
|
||||
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||
for l in links:
|
||||
if "rel:" not in l: found_edges.add(f"{current_edge_type}:{l}")
|
||||
continue
|
||||
# Links in Folgezeilen des Callouts
|
||||
if current_edge_type and stripped.startswith('>'):
|
||||
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||
for l in links:
|
||||
if "rel:" not in l: found_edges.add(f"{current_edge_type}:{l}")
|
||||
elif not stripped.startswith('>'): current_edge_type = None
|
||||
elif not stripped.startswith('>'):
|
||||
current_edge_type = None
|
||||
return found_edges
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
FILE: app/core/chunking/chunking_processor.py
|
||||
DESCRIPTION: Der zentrale Orchestrator für das Chunking-System.
|
||||
AUDIT v3.3.3: Wiederherstellung der "Gold-Standard" Qualität.
|
||||
AUDIT v3.3.4: Wiederherstellung der "Gold-Standard" Qualität.
|
||||
- Fix: Synchronisierung der Parameter (context_prefix) für alle Strategien.
|
||||
- Integriert physikalische Kanten-Injektion (Propagierung).
|
||||
- Stellt H1-Kontext-Fenster sicher.
|
||||
- Baut den Candidate-Pool für die WP-15b Ingestion auf.
|
||||
@@ -30,16 +31,19 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
||||
fm, body_text = extract_frontmatter_from_text(md_text)
|
||||
blocks, doc_title = parse_blocks(md_text)
|
||||
|
||||
# Vorbereitung des H1-Präfix für die Embedding-Fenster
|
||||
# Vorbereitung des H1-Präfix für die Embedding-Fenster (Breadcrumbs)
|
||||
h1_prefix = f"# {doc_title}" if doc_title else ""
|
||||
|
||||
# 2. Anwendung der Splitting-Strategie
|
||||
# Wir übergeben den Dokument-Titel/Präfix für die Window-Bildung.
|
||||
# Alle Strategien nutzen nun einheitlich context_prefix für die Window-Bildung.
|
||||
if config.get("strategy") == "by_heading":
|
||||
chunks = await asyncio.to_thread(strategy_by_heading, blocks, config, note_id, doc_title)
|
||||
chunks = await asyncio.to_thread(
|
||||
strategy_by_heading, blocks, config, note_id, context_prefix=h1_prefix
|
||||
)
|
||||
else:
|
||||
# sliding_window nutzt nun den context_prefix für das Window-Feld.
|
||||
chunks = await asyncio.to_thread(strategy_sliding_window, blocks, config, note_id, context_prefix=h1_prefix)
|
||||
chunks = await asyncio.to_thread(
|
||||
strategy_sliding_window, blocks, config, note_id, context_prefix=h1_prefix
|
||||
)
|
||||
|
||||
if not chunks:
|
||||
return []
|
||||
@@ -52,6 +56,7 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
||||
# Zuerst die explizit im Text vorhandenen Kanten sammeln.
|
||||
for ch in chunks:
|
||||
# Wir extrahieren aus dem bereits (durch Propagation) angereicherten Text.
|
||||
# ch.candidate_pool wird im Modell-Konstruktor als leere Liste initialisiert.
|
||||
for e_str in parse_edges_robust(ch.text):
|
||||
parts = e_str.split(':', 1)
|
||||
if len(parts) == 2:
|
||||
@@ -71,7 +76,7 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
||||
parts = e_str.split(':', 1)
|
||||
if len(parts) == 2:
|
||||
k, t = parts
|
||||
# Diese Kanten werden als "Global Pool" markiert für die spätere KI-Prüfung.
|
||||
# Diese Kanten werden als "global_pool" markiert für die spätere KI-Prüfung.
|
||||
for ch in chunks:
|
||||
ch.candidate_pool.append({"kind": k, "to": t, "provenance": "global_pool"})
|
||||
|
||||
@@ -80,6 +85,7 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
||||
seen = set()
|
||||
unique = []
|
||||
for c in ch.candidate_pool:
|
||||
# Eindeutigkeit über Typ, Ziel und Herkunft (Provenance)
|
||||
key = (c["kind"], c["to"], c["provenance"])
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"""
|
||||
FILE: app/core/chunking/chunking_propagation.py
|
||||
DESCRIPTION: Injiziert Sektions-Kanten physisch in den Text (Embedding-Enrichment).
|
||||
Stellt die "Gold-Standard"-Qualität von v3.1.0 wieder her.
|
||||
VERSION: 3.3.1
|
||||
STATUS: Active
|
||||
Fix v3.3.6: Nutzt robustes Parsing zur Erkennung vorhandener Kanten,
|
||||
um Dopplungen direkt hinter [!edge] Callouts format-agnostisch zu verhindern.
|
||||
"""
|
||||
from typing import List, Dict, Set
|
||||
from .chunking_models import Chunk
|
||||
@@ -12,7 +11,7 @@ from .chunking_parser import parse_edges_robust
|
||||
def propagate_section_edges(chunks: List[Chunk]) -> List[Chunk]:
|
||||
"""
|
||||
Sammelt Kanten pro Sektion und schreibt sie hart in den Text und das Window.
|
||||
Dies ist essenziell für die Vektorisierung der Beziehungen.
|
||||
Verhindert Dopplungen, wenn Kanten bereits via [!edge] Callout vorhanden sind.
|
||||
"""
|
||||
# 1. Sammeln: Alle expliziten Kanten pro Sektions-Pfad aggregieren
|
||||
section_map: Dict[str, Set[str]] = {} # path -> set(kind:target)
|
||||
@@ -36,21 +35,28 @@ def propagate_section_edges(chunks: List[Chunk]) -> List[Chunk]:
|
||||
if not edges_to_add:
|
||||
continue
|
||||
|
||||
# Vorhandene Kanten (Typ:Ziel) in DIESEM Chunk ermitteln,
|
||||
# um Dopplungen (z.B. durch Callouts) zu vermeiden.
|
||||
existing_edges = parse_edges_robust(ch.text)
|
||||
|
||||
injections = []
|
||||
for e_str in edges_to_add:
|
||||
# Sortierung für deterministische Ergebnisse
|
||||
for e_str in sorted(list(edges_to_add)):
|
||||
# Wenn die Kante (Typ + Ziel) bereits vorhanden ist (egal welches Format),
|
||||
# überspringen wir die Injektion für diesen Chunk.
|
||||
if e_str in existing_edges:
|
||||
continue
|
||||
|
||||
kind, target = e_str.split(':', 1)
|
||||
# Nur injizieren, wenn die Kante nicht bereits im Text steht
|
||||
token = f"[[rel:{kind}|{target}]]"
|
||||
if token not in ch.text:
|
||||
injections.append(token)
|
||||
injections.append(f"[[rel:{kind}|{target}]]")
|
||||
|
||||
if injections:
|
||||
# Physische Anreicherung (Der v3.1.0 Qualitäts-Fix)
|
||||
# Physische Anreicherung
|
||||
# Triple-Newline für saubere Trennung im Embedding-Fenster
|
||||
block = "\n\n\n" + " ".join(injections)
|
||||
ch.text += block
|
||||
|
||||
# ENTSCHEIDEND: Auch ins Window schreiben, da Qdrant hier sucht!
|
||||
# Auch ins Window schreiben, da Qdrant hier sucht!
|
||||
if ch.window:
|
||||
ch.window += block
|
||||
else:
|
||||
|
||||
@@ -1,142 +1,166 @@
|
||||
"""
|
||||
FILE: app/core/chunking/chunking_strategies.py
|
||||
DESCRIPTION: Mathematische Splitting-Strategien.
|
||||
AUDIT v3.3.2: 100% Konformität zur 'by_heading' Spezifikation.
|
||||
- Implementiert Hybrid-Safety-Net (Sliding Window für Übergrößen).
|
||||
- Breadcrumb-Kontext im Window (H1 > H2).
|
||||
- Sliding Window mit H1-Kontext (Gold-Standard v3.1.0).
|
||||
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.9.
|
||||
Implementiert das 'Pack-and-Carry-Over' Verfahren nach Regel 1-3.
|
||||
- Keine redundante Kanten-Injektion.
|
||||
- Strikte Einhaltung von Sektionsgrenzen via Look-Ahead.
|
||||
- Fix: Synchronisierung der Parameter mit dem Orchestrator (context_prefix).
|
||||
"""
|
||||
from typing import List, Dict, Any, Optional
|
||||
from .chunking_models import RawBlock, Chunk
|
||||
from .chunking_utils import estimate_tokens
|
||||
from .chunking_parser import split_sentences
|
||||
|
||||
def _create_context_win(doc_title: str, sec_title: Optional[str], text: str) -> str:
|
||||
def _create_win(context_prefix: str, sec_title: Optional[str], text: str) -> str:
|
||||
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
||||
parts = []
|
||||
if doc_title: parts.append(doc_title)
|
||||
if sec_title and sec_title != doc_title: parts.append(sec_title)
|
||||
parts = [context_prefix] if context_prefix else []
|
||||
# Verhindert Dopplung, falls der Context-Prefix (H1) bereits den Sektionsnamen enthält
|
||||
if sec_title and f"# {sec_title}" != context_prefix and sec_title not in (context_prefix or ""):
|
||||
parts.append(sec_title)
|
||||
prefix = " > ".join(parts)
|
||||
return f"{prefix}\n{text}".strip() if prefix else text
|
||||
|
||||
def strategy_sliding_window(blocks: List[RawBlock],
|
||||
config: Dict[str, Any],
|
||||
note_id: str,
|
||||
context_prefix: str = "") -> List[Chunk]:
|
||||
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
||||
"""
|
||||
Fasst Blöcke zusammen und schneidet bei 'target' Tokens.
|
||||
Ignoriert H2-Überschriften beim Splitting, um Kontext zu wahren.
|
||||
"""
|
||||
target = config.get("target", 400)
|
||||
max_tokens = config.get("max", 600)
|
||||
overlap_val = config.get("overlap", (50, 80))
|
||||
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
||||
|
||||
chunks: List[Chunk] = []
|
||||
buf: List[RawBlock] = []
|
||||
|
||||
def _add(txt, sec, path):
|
||||
idx = len(chunks)
|
||||
# H1-Kontext Präfix für das Window-Feld
|
||||
win = f"{context_prefix}\n{txt}".strip() if context_prefix else 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=sec, section_path=path,
|
||||
neighbors_prev=None, neighbors_next=None
|
||||
))
|
||||
|
||||
def flush():
|
||||
nonlocal buf
|
||||
if not buf: return
|
||||
text_body = "\n\n".join([b.text for b in buf])
|
||||
sec_title = buf[-1].section_title; sec_path = buf[-1].section_path
|
||||
|
||||
if estimate_tokens(text_body) <= max_tokens:
|
||||
_add(text_body, sec_title, sec_path)
|
||||
else:
|
||||
sents = split_sentences(text_body); cur_sents = []; cur_len = 0
|
||||
for s in sents:
|
||||
slen = estimate_tokens(s)
|
||||
if cur_len + slen > target and cur_sents:
|
||||
_add(" ".join(cur_sents), sec_title, sec_path)
|
||||
ov_s = []; ov_l = 0
|
||||
for os in reversed(cur_sents):
|
||||
if ov_l + estimate_tokens(os) < overlap:
|
||||
ov_s.insert(0, os); ov_l += estimate_tokens(os)
|
||||
else: break
|
||||
cur_sents = list(ov_s); cur_sents.append(s); cur_len = ov_l + slen
|
||||
else:
|
||||
cur_sents.append(s); cur_len += slen
|
||||
if cur_sents:
|
||||
_add(" ".join(cur_sents), sec_title, sec_path)
|
||||
buf = []
|
||||
|
||||
for b in blocks:
|
||||
# H2-Überschriften werden ignoriert, um den Zusammenhang zu wahren
|
||||
if b.kind == "heading": continue
|
||||
if estimate_tokens("\n\n".join([x.text for x in buf])) + estimate_tokens(b.text) >= target:
|
||||
flush()
|
||||
buf.append(b)
|
||||
flush()
|
||||
return chunks
|
||||
|
||||
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||
"""
|
||||
Splittet Text basierend auf Markdown-Überschriften mit Hybrid-Safety-Net.
|
||||
Universelle Heading-Strategie mit Carry-Over Logik.
|
||||
Synchronisiert auf context_prefix für Kompatibilität mit dem Orchestrator.
|
||||
"""
|
||||
smart_edge = config.get("enable_smart_edge_allocation", True)
|
||||
strict = config.get("strict_heading_split", False)
|
||||
target = config.get("target", 400)
|
||||
max_tokens = config.get("max", 600)
|
||||
split_level = config.get("split_level", 2)
|
||||
overlap = sum(config.get("overlap", (50, 80))) // 2
|
||||
overlap_cfg = config.get("overlap", (50, 80))
|
||||
overlap = sum(overlap_cfg) // 2 if isinstance(overlap_cfg, (list, tuple)) else overlap_cfg
|
||||
|
||||
chunks: List[Chunk] = []
|
||||
buf: List[str] = []
|
||||
cur_tokens = 0
|
||||
|
||||
def _add_to_chunks(txt, title, path):
|
||||
def _emit(txt, title, path):
|
||||
"""Schreibt den finalen Chunk ohne Text-Modifikationen."""
|
||||
idx = len(chunks)
|
||||
win = _create_context_win(doc_title, title, txt)
|
||||
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_title=title, section_path=path, neighbors_prev=None, neighbors_next=None
|
||||
))
|
||||
|
||||
def _flush(title, path):
|
||||
nonlocal buf, cur_tokens
|
||||
if not buf: return
|
||||
full_text = "\n\n".join(buf)
|
||||
if estimate_tokens(full_text) <= max_tokens:
|
||||
_add_to_chunks(full_text, title, path)
|
||||
else:
|
||||
sents = split_sentences(full_text); cur_sents = []; sub_len = 0
|
||||
for s in sents:
|
||||
slen = estimate_tokens(s)
|
||||
if sub_len + slen > target and cur_sents:
|
||||
_add_to_chunks(" ".join(cur_sents), title, path)
|
||||
ov_s = []; ov_l = 0
|
||||
for os in reversed(cur_sents):
|
||||
if ov_l + estimate_tokens(os) < overlap:
|
||||
ov_s.insert(0, os); ov_l += estimate_tokens(os)
|
||||
else: break
|
||||
cur_sents = list(ov_s); cur_sents.append(s); sub_len = ov_l + slen
|
||||
else: cur_sents.append(s); sub_len += slen
|
||||
if cur_sents: _add_to_chunks(" ".join(cur_sents), title, path)
|
||||
buf = []; cur_tokens = 0
|
||||
|
||||
# --- SCHRITT 1: Gruppierung in atomare Sektions-Einheiten ---
|
||||
sections: List[Dict[str, Any]] = []
|
||||
curr_blocks = []
|
||||
for b in blocks:
|
||||
if b.kind == "heading":
|
||||
if b.level < split_level: _flush(b.section_title, b.section_path)
|
||||
elif b.level == split_level:
|
||||
if strict or cur_tokens >= target: _flush(b.section_title, b.section_path)
|
||||
if b.kind == "heading" and b.level <= split_level:
|
||||
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)
|
||||
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 = ""
|
||||
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)
|
||||
|
||||
while queue:
|
||||
item = queue.pop(0)
|
||||
item_text = item["text"]
|
||||
|
||||
# Initialisierung für neuen Chunk
|
||||
if not current_chunk_text:
|
||||
current_meta["title"] = item["meta"].section_title
|
||||
current_meta["path"] = item["meta"].section_path
|
||||
|
||||
# FALL A: HARD SPLIT MODUS
|
||||
if is_hard_split_mode:
|
||||
# Leere Überschriften (z.B. H1 direkt vor H2) verbleiben am nächsten Chunk
|
||||
if item.get("is_empty", False) and queue:
|
||||
current_chunk_text = (current_chunk_text + "\n\n" + item_text).strip()
|
||||
continue
|
||||
|
||||
combined = (current_chunk_text + "\n\n" + item_text).strip()
|
||||
# Wenn durch Verschmelzung das Limit gesprengt würde, vorher flashen
|
||||
if estimate_tokens(combined) > max_tokens and current_chunk_text:
|
||||
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||
current_chunk_text = item_text
|
||||
else:
|
||||
current_chunk_text = combined
|
||||
|
||||
# Im Hard-Split wird nach jeder Sektion geflasht
|
||||
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||
current_chunk_text = ""
|
||||
continue
|
||||
bt = estimate_tokens(b.text)
|
||||
if cur_tokens + bt > max_tokens and buf: _flush(b.section_title, b.section_path)
|
||||
buf.append(b.text); cur_tokens += bt
|
||||
|
||||
# FALL B: SMART MODE (Regel 1-3)
|
||||
combined_text = (current_chunk_text + "\n\n" + item_text).strip() if current_chunk_text else item_text
|
||||
combined_est = estimate_tokens(combined_text)
|
||||
|
||||
if combined_est <= max_tokens:
|
||||
# Regel 1 & 2: Passt rein laut Schätzung -> Aufnehmen
|
||||
current_chunk_text = combined_text
|
||||
else:
|
||||
if current_chunk_text:
|
||||
# Regel 2: Flashen an Sektionsgrenze, Item zurücklegen
|
||||
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||
current_chunk_text = ""
|
||||
queue.insert(0, item)
|
||||
else:
|
||||
# Regel 3: Einzelne Sektion zu groß -> Smart Zerlegung
|
||||
sents = split_sentences(item_text)
|
||||
header_prefix = item["meta"].text if item["meta"].kind == "heading" else ""
|
||||
|
||||
take_sents = []; take_len = 0
|
||||
while sents:
|
||||
s = sents.pop(0); slen = estimate_tokens(s)
|
||||
if take_len + slen > target and take_sents:
|
||||
sents.insert(0, s); break
|
||||
take_sents.append(s); take_len += slen
|
||||
|
||||
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
|
||||
|
||||
if sents:
|
||||
remainder = " ".join(sents)
|
||||
# Kontext-Erhalt: Überschrift für den Rest wiederholen
|
||||
if header_prefix and not remainder.startswith(header_prefix):
|
||||
remainder = header_prefix + "\n\n" + remainder
|
||||
# Carry-Over: Rest wird vorne in die Queue geschoben
|
||||
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"])
|
||||
|
||||
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."""
|
||||
target = config.get("target", 400); max_tokens = config.get("max", 600)
|
||||
chunks: List[Chunk] = []; buf: List[RawBlock] = []
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
if buf:
|
||||
last_b = blocks[-1] if blocks else None
|
||||
_flush(last_b.section_title if last_b else None, last_b.section_path if last_b else "/")
|
||||
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
|
||||
@@ -3,7 +3,7 @@ FILE: app/core/database/qdrant.py
|
||||
DESCRIPTION: Qdrant-Client Factory und Schema-Management.
|
||||
Erstellt Collections und Payload-Indizes.
|
||||
MODULARISIERUNG: Verschoben in das database-Paket für WP-14.
|
||||
VERSION: 2.2.1
|
||||
VERSION: 2.2.2 (WP-Fix: Index für target_section)
|
||||
STATUS: Active
|
||||
DEPENDENCIES: qdrant_client, dataclasses, os
|
||||
"""
|
||||
@@ -124,7 +124,7 @@ def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
||||
Stellt sicher, dass alle benötigten Payload-Indizes für die Suche existieren.
|
||||
- notes: note_id, type, title, updated, tags
|
||||
- chunks: note_id, chunk_id, index, type, tags
|
||||
- edges: note_id, kind, scope, source_id, target_id, chunk_id
|
||||
- edges: note_id, kind, scope, source_id, target_id, chunk_id, target_section
|
||||
"""
|
||||
notes, chunks, edges = collection_names(prefix)
|
||||
|
||||
@@ -156,6 +156,8 @@ def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
||||
("source_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("target_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||
# NEU: Index für Section-Links (WP-15b)
|
||||
("target_section", rest.PayloadSchemaType.KEYWORD),
|
||||
]:
|
||||
_ensure_index(client, edges, field, schema)
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
FILE: app/core/database/qdrant_points.py
|
||||
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
||||
VERSION: 1.5.0
|
||||
VERSION: 1.5.1 (WP-Fix: Explicit Target Section Support)
|
||||
STATUS: Active
|
||||
DEPENDENCIES: qdrant_client, uuid, os
|
||||
LAST_ANALYSIS: 2025-12-15
|
||||
LAST_ANALYSIS: 2025-12-29
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os
|
||||
@@ -46,16 +46,25 @@ def points_for_chunks(prefix: str, chunk_payloads: List[dict], vectors: List[Lis
|
||||
return chunks_col, points
|
||||
|
||||
def _normalize_edge_payload(pl: dict) -> dict:
|
||||
"""Normalisiert Edge-Felder und sichert Schema-Konformität."""
|
||||
kind = pl.get("kind") or pl.get("edge_type") or "edge"
|
||||
source_id = pl.get("source_id") or pl.get("src_id") or "unknown-src"
|
||||
target_id = pl.get("target_id") or pl.get("dst_id") or "unknown-tgt"
|
||||
seq = pl.get("seq") or pl.get("order") or pl.get("index")
|
||||
|
||||
# WP-Fix: target_section explizit durchreichen
|
||||
target_section = pl.get("target_section")
|
||||
|
||||
pl.setdefault("kind", kind)
|
||||
pl.setdefault("source_id", source_id)
|
||||
pl.setdefault("target_id", target_id)
|
||||
|
||||
if seq is not None and "seq" not in pl:
|
||||
pl["seq"] = seq
|
||||
|
||||
if target_section is not None:
|
||||
pl["target_section"] = target_section
|
||||
|
||||
return pl
|
||||
|
||||
def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[rest.PointStruct]]:
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/derive_edges.py
|
||||
DESCRIPTION: Facade für das neue graph Package.
|
||||
WP-14: Modularisierung abgeschlossen.
|
||||
VERSION: 2.2.0
|
||||
"""
|
||||
from .graph.graph_derive_edges import build_edges_for_note
|
||||
from .graph.graph_utils import PROVENANCE_PRIORITY
|
||||
|
||||
__all__ = ["build_edges_for_note", "PROVENANCE_PRIORITY"]
|
||||
@@ -1,10 +1,14 @@
|
||||
"""
|
||||
FILE: app/core/graph/graph_derive_edges.py
|
||||
DESCRIPTION: Hauptlogik zur Kanten-Aggregation und De-Duplizierung.
|
||||
AUDIT:
|
||||
- Nutzt parse_link_target
|
||||
- Übergibt Section als 'variant' an ID-Gen
|
||||
- Dedup basiert jetzt auf Edge-ID (erlaubt Multigraph für Sections)
|
||||
"""
|
||||
from typing import List, Optional, Dict, Tuple
|
||||
from .graph_utils import (
|
||||
_get, _edge, _mk_edge_id, _dedupe_seq,
|
||||
_get, _edge, _mk_edge_id, _dedupe_seq, parse_link_target,
|
||||
PROVENANCE_PRIORITY, load_types_registry, get_edge_defaults_for
|
||||
)
|
||||
from .graph_extractors import (
|
||||
@@ -53,47 +57,85 @@ def build_edges_for_note(
|
||||
|
||||
# Typed & Candidate Pool (WP-15b Integration)
|
||||
typed, rem = extract_typed_relations(raw)
|
||||
for k, t in typed:
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, {
|
||||
"chunk_id": cid, "edge_id": _mk_edge_id(k, cid, t, "chunk", "inline:rel"),
|
||||
for k, raw_t in typed:
|
||||
t, sec = parse_link_target(raw_t, note_id)
|
||||
if not t: continue
|
||||
|
||||
payload = {
|
||||
"chunk_id": cid,
|
||||
# Variant=sec sorgt für eindeutige ID pro Abschnitt
|
||||
"edge_id": _mk_edge_id(k, cid, t, "chunk", "inline:rel", variant=sec),
|
||||
"provenance": "explicit", "rule_id": "inline:rel", "confidence": PROVENANCE_PRIORITY["inline:rel"]
|
||||
}))
|
||||
}
|
||||
if sec: payload["target_section"] = sec
|
||||
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||
|
||||
pool = ch.get("candidate_pool") or ch.get("candidate_edges") or []
|
||||
for cand in pool:
|
||||
t, k, p = cand.get("to"), cand.get("kind", "related_to"), cand.get("provenance", "semantic_ai")
|
||||
raw_t, k, p = cand.get("to"), cand.get("kind", "related_to"), cand.get("provenance", "semantic_ai")
|
||||
t, sec = parse_link_target(raw_t, note_id)
|
||||
if t:
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, {
|
||||
"chunk_id": cid, "edge_id": _mk_edge_id(k, cid, t, "chunk", f"candidate:{p}"),
|
||||
payload = {
|
||||
"chunk_id": cid,
|
||||
"edge_id": _mk_edge_id(k, cid, t, "chunk", f"candidate:{p}", variant=sec),
|
||||
"provenance": p, "rule_id": f"candidate:{p}", "confidence": PROVENANCE_PRIORITY.get(p, 0.90)
|
||||
}))
|
||||
}
|
||||
if sec: payload["target_section"] = sec
|
||||
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||
|
||||
# Callouts & Wikilinks
|
||||
call_pairs, rem2 = extract_callout_relations(rem)
|
||||
for k, t in call_pairs:
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, {
|
||||
"chunk_id": cid, "edge_id": _mk_edge_id(k, cid, t, "chunk", "callout:edge"),
|
||||
for k, raw_t in call_pairs:
|
||||
t, sec = parse_link_target(raw_t, note_id)
|
||||
if not t: continue
|
||||
|
||||
payload = {
|
||||
"chunk_id": cid,
|
||||
"edge_id": _mk_edge_id(k, cid, t, "chunk", "callout:edge", variant=sec),
|
||||
"provenance": "explicit", "rule_id": "callout:edge", "confidence": PROVENANCE_PRIORITY["callout:edge"]
|
||||
}))
|
||||
}
|
||||
if sec: payload["target_section"] = sec
|
||||
|
||||
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||
|
||||
refs = extract_wikilinks(rem2)
|
||||
for r in refs:
|
||||
edges.append(_edge("references", "chunk", cid, r, note_id, {
|
||||
"chunk_id": cid, "ref_text": r, "edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink"),
|
||||
for raw_r in refs:
|
||||
r, sec = parse_link_target(raw_r, note_id)
|
||||
if not r: continue
|
||||
|
||||
payload = {
|
||||
"chunk_id": cid, "ref_text": raw_r,
|
||||
"edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink", variant=sec),
|
||||
"provenance": "explicit", "rule_id": "explicit:wikilink", "confidence": PROVENANCE_PRIORITY["explicit:wikilink"]
|
||||
}))
|
||||
}
|
||||
if sec: payload["target_section"] = sec
|
||||
|
||||
edges.append(_edge("references", "chunk", cid, r, note_id, payload))
|
||||
|
||||
for rel in defaults:
|
||||
if rel != "references":
|
||||
edges.append(_edge(rel, "chunk", cid, r, note_id, {
|
||||
"chunk_id": cid, "edge_id": _mk_edge_id(rel, cid, r, "chunk", f"edge_defaults:{rel}"),
|
||||
def_payload = {
|
||||
"chunk_id": cid,
|
||||
"edge_id": _mk_edge_id(rel, cid, r, "chunk", f"edge_defaults:{rel}", variant=sec),
|
||||
"provenance": "rule", "rule_id": f"edge_defaults:{rel}", "confidence": PROVENANCE_PRIORITY["edge_defaults"]
|
||||
}))
|
||||
refs_all.extend(refs)
|
||||
}
|
||||
if sec: def_payload["target_section"] = sec
|
||||
edges.append(_edge(rel, "chunk", cid, r, note_id, def_payload))
|
||||
|
||||
# Für Note-Scope Sammlung nutzen wir den Original-String zur Dedup, aber gesäubert
|
||||
refs_all.extend([parse_link_target(r, note_id)[0] for r in refs])
|
||||
|
||||
# 3) Note-Scope & De-Duplizierung
|
||||
if include_note_scope_refs:
|
||||
refs_note = _dedupe_seq((refs_all or []) + (note_level_references or []))
|
||||
# refs_all ist jetzt schon gesäubert (nur Targets)
|
||||
# note_level_references müssen auch gesäubert werden
|
||||
cleaned_note_refs = [parse_link_target(r, note_id)[0] for r in (note_level_references or [])]
|
||||
refs_note = _dedupe_seq((refs_all or []) + cleaned_note_refs)
|
||||
|
||||
for r in refs_note:
|
||||
if not r: continue
|
||||
edges.append(_edge("references", "note", note_id, r, note_id, {
|
||||
"edge_id": _mk_edge_id("references", note_id, r, "note", "explicit:note_scope"),
|
||||
"provenance": "explicit", "confidence": PROVENANCE_PRIORITY["explicit:note_scope"]
|
||||
@@ -103,10 +145,13 @@ def build_edges_for_note(
|
||||
"provenance": "rule", "confidence": PROVENANCE_PRIORITY["derived:backlink"]
|
||||
}))
|
||||
|
||||
unique_map: Dict[Tuple[str, str, str], dict] = {}
|
||||
# Deduplizierung: Wir nutzen jetzt die EDGE-ID als Schlüssel.
|
||||
# Da die Edge-ID nun 'variant' (Section) enthält, bleiben unterschiedliche Sections erhalten.
|
||||
unique_map: Dict[str, dict] = {}
|
||||
for e in edges:
|
||||
key = (str(e.get("source_id")), str(e.get("target_id")), str(e.get("kind")))
|
||||
if key not in unique_map or e.get("confidence", 0) > unique_map[key].get("confidence", 0):
|
||||
unique_map[key] = e
|
||||
eid = e["edge_id"]
|
||||
# Bei Konflikt (gleiche ID = exakt gleiche Kante und Section) gewinnt die höhere Confidence
|
||||
if eid not in unique_map or e.get("confidence", 0) > unique_map[eid].get("confidence", 0):
|
||||
unique_map[eid] = e
|
||||
|
||||
return list(unique_map.values())
|
||||
@@ -1,25 +1,36 @@
|
||||
"""
|
||||
FILE: app/core/graph/graph_extractors.py
|
||||
DESCRIPTION: Regex-basierte Extraktion von Relationen aus Text.
|
||||
AUDIT:
|
||||
- Regex für Wikilinks liberalisiert (Umlaute, Sonderzeichen).
|
||||
- Callout-Parser erweitert für Multi-Line-Listen und Header-Typen.
|
||||
"""
|
||||
import re
|
||||
from typing import List, Tuple
|
||||
|
||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
||||
# Erlaube alle Zeichen außer ']' im Target (fängt Umlaute, Emojis, '&', '#' ab)
|
||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]")
|
||||
|
||||
_REL_PIPE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s*\|\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||
_REL_SPACE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s+(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||
_REL_TEXT = re.compile(r"rel\s*:\s*(?P<kind>[a-z_]+)\s*\[\[\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||
|
||||
_CALLOUT_START = re.compile(r"^\s*>\s*\[!edge\]\s*(.*)$", re.IGNORECASE)
|
||||
# Erkennt "kind: targets..."
|
||||
_REL_LINE = re.compile(r"^(?P<kind>[a-z_]+)\s*:\s*(?P<targets>.+?)\s*$", re.IGNORECASE)
|
||||
_WIKILINKS_IN_LINE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||
# Erkennt reine Typen (z.B. "depends_on" im Header)
|
||||
_SIMPLE_KIND = re.compile(r"^[a-z_]+$", re.IGNORECASE)
|
||||
|
||||
def extract_typed_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||
"""Extrahiert [[rel:KIND|Target]]."""
|
||||
def extract_typed_relations(text: str) -> Tuple[List[Tuple[str, str]], str]:
|
||||
"""
|
||||
Findet Inline-Relationen wie [[rel:depends_on Target]].
|
||||
Gibt (Liste[(kind, target)], bereinigter_text) zurück.
|
||||
"""
|
||||
if not text: return [], ""
|
||||
pairs = []
|
||||
def _collect(m):
|
||||
k, t = (m.group("kind") or "").strip().lower(), (m.group("target") or "").strip()
|
||||
if k and t: pairs.append((k, t))
|
||||
k, t = m.group("kind").strip().lower(), m.group("target").strip()
|
||||
pairs.append((k, t))
|
||||
return ""
|
||||
text = _REL_PIPE.sub(_collect, text)
|
||||
text = _REL_SPACE.sub(_collect, text)
|
||||
@@ -27,29 +38,90 @@ def extract_typed_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||
return pairs, text
|
||||
|
||||
def extract_callout_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||
"""Verarbeitet Obsidian [!edge]-Callouts."""
|
||||
"""
|
||||
Verarbeitet Obsidian [!edge]-Callouts.
|
||||
Unterstützt zwei Formate:
|
||||
1. Explizit: "kind: [[Target]]"
|
||||
2. Implizit (Header): "> [!edge] kind" gefolgt von "[[Target]]" Zeilen
|
||||
"""
|
||||
if not text: return [], text
|
||||
lines = text.splitlines(); out_pairs, keep_lines, i = [], [], 0
|
||||
lines = text.splitlines()
|
||||
out_pairs = []
|
||||
keep_lines = []
|
||||
i = 0
|
||||
|
||||
while i < len(lines):
|
||||
m = _CALLOUT_START.match(lines[i])
|
||||
line = lines[i]
|
||||
m = _CALLOUT_START.match(line)
|
||||
if not m:
|
||||
keep_lines.append(lines[i]); i += 1; continue
|
||||
block_lines = [m.group(1)] if m.group(1).strip() else []
|
||||
keep_lines.append(line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Callout-Block gefunden. Wir sammeln alle relevanten Zeilen.
|
||||
block_lines = []
|
||||
|
||||
# Header Content prüfen (z.B. "type" aus "> [!edge] type")
|
||||
header_raw = m.group(1).strip()
|
||||
if header_raw:
|
||||
block_lines.append(header_raw)
|
||||
|
||||
i += 1
|
||||
while i < len(lines) and lines[i].lstrip().startswith('>'):
|
||||
block_lines.append(lines[i].lstrip()[1:].lstrip()); i += 1
|
||||
# Entferne '>' und führende Leerzeichen
|
||||
content = lines[i].lstrip()[1:].lstrip()
|
||||
if content:
|
||||
block_lines.append(content)
|
||||
i += 1
|
||||
|
||||
# Verarbeitung des Blocks
|
||||
current_kind = None
|
||||
|
||||
# Heuristik: Ist die allererste Zeile (meist aus dem Header) ein reiner Typ?
|
||||
# Dann setzen wir diesen als Default für den Block.
|
||||
if block_lines:
|
||||
first = block_lines[0]
|
||||
# Wenn es NICHT wie "Key: Value" aussieht, aber wie ein Wort:
|
||||
if not _REL_LINE.match(first) and _SIMPLE_KIND.match(first):
|
||||
current_kind = first.lower()
|
||||
|
||||
for bl in block_lines:
|
||||
# 1. Prüfen auf explizites "Kind: Targets" (überschreibt Header-Typ für diese Zeile)
|
||||
mrel = _REL_LINE.match(bl)
|
||||
if not mrel: continue
|
||||
kind, targets = mrel.group("kind").strip().lower(), mrel.group("targets") or ""
|
||||
found = _WIKILINKS_IN_LINE.findall(targets)
|
||||
if mrel:
|
||||
line_kind = mrel.group("kind").strip().lower()
|
||||
targets = mrel.group("targets")
|
||||
|
||||
# Links extrahieren
|
||||
found = _WIKILINK_RE.findall(targets)
|
||||
if found:
|
||||
for t in found: out_pairs.append((line_kind, t.strip()))
|
||||
else:
|
||||
# Fallback für kommagetrennten Plaintext
|
||||
for raw in re.split(r"[,;]", targets):
|
||||
if raw.strip(): out_pairs.append((line_kind, raw.strip()))
|
||||
|
||||
# Wenn wir eine explizite Zeile gefunden haben, aktualisieren wir NICHT
|
||||
# den current_kind für nachfolgende Zeilen (Design-Entscheidung: lokal scope),
|
||||
# oder wir machen es doch?
|
||||
# Üblicher ist: Header setzt Default, Zeile überschreibt lokal.
|
||||
# Wir lassen current_kind also unangetastet.
|
||||
continue
|
||||
|
||||
# 2. Kein Key:Value Muster -> Prüfen auf Links, die den current_kind nutzen
|
||||
found = _WIKILINK_RE.findall(bl)
|
||||
if found:
|
||||
for t in found: out_pairs.append((kind, t.strip()))
|
||||
else:
|
||||
for raw in re.split(r"[,;]", targets):
|
||||
if raw.strip(): out_pairs.append((kind, raw.strip()))
|
||||
if current_kind:
|
||||
for t in found: out_pairs.append((current_kind, t.strip()))
|
||||
else:
|
||||
# Link ohne Typ und ohne Header-Typ.
|
||||
# Wird ignoriert oder könnte als 'related_to' fallback dienen.
|
||||
# Aktuell: Ignorieren, um False Positives zu vermeiden.
|
||||
pass
|
||||
|
||||
return out_pairs, "\n".join(keep_lines)
|
||||
|
||||
def extract_wikilinks(text: str) -> List[str]:
|
||||
"""Extrahiert Standard-Wikilinks."""
|
||||
return [m.group(1).strip() for m in _WIKILINK_RE.finditer(text or "")]
|
||||
"""Findet Standard-Wikilinks [[Target]] oder [[Alias|Target]]."""
|
||||
if not text: return []
|
||||
return [m.strip() for m in _WIKILINK_RE.findall(text) if m.strip()]
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
FILE: app/core/graph/graph_utils.py
|
||||
DESCRIPTION: Basale Werkzeuge, ID-Generierung und Provenance-Konfiguration für den Graphen.
|
||||
AUDIT: Erweitert um parse_link_target für sauberes Section-Splitting (WP-Fix).
|
||||
"""
|
||||
import os
|
||||
import hashlib
|
||||
from typing import Iterable, List, Optional, Set, Any
|
||||
from typing import Iterable, List, Optional, Set, Any, Tuple
|
||||
|
||||
try:
|
||||
import yaml
|
||||
@@ -40,10 +41,19 @@ def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
||||
seen.add(s); out.append(s)
|
||||
return out
|
||||
|
||||
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None) -> str:
|
||||
"""Erzeugt eine deterministische 12-Byte ID mittels BLAKE2s."""
|
||||
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None, variant: Optional[str] = None) -> str:
|
||||
"""
|
||||
Erzeugt eine deterministische 12-Byte ID mittels BLAKE2s.
|
||||
|
||||
WP-Fix: 'variant' (z.B. Section) fließt in den Hash ein, um mehrere Kanten
|
||||
zum gleichen Target-Node (aber unterschiedlichen Abschnitten) zu unterscheiden.
|
||||
"""
|
||||
base = f"{kind}:{s}->{t}#{scope}"
|
||||
if rule_id: base += f"|{rule_id}"
|
||||
if rule_id:
|
||||
base += f"|{rule_id}"
|
||||
if variant:
|
||||
base += f"|{variant}" # <--- Hier entsteht die Eindeutigkeit für verschiedene Sections
|
||||
|
||||
return hashlib.blake2s(base.encode("utf-8"), digest_size=12).hexdigest()
|
||||
|
||||
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
|
||||
@@ -59,6 +69,27 @@ def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, e
|
||||
if extra: pl.update(extra)
|
||||
return pl
|
||||
|
||||
def parse_link_target(raw: str, current_note_id: Optional[str] = None) -> Tuple[str, Optional[str]]:
|
||||
"""
|
||||
Zerlegt einen Link (z.B. 'Note#Section') in Target-ID und Section.
|
||||
Behandelt Self-Links ('#Section'), indem current_note_id eingesetzt wird.
|
||||
|
||||
Returns:
|
||||
(target_id, target_section)
|
||||
"""
|
||||
if not raw:
|
||||
return "", None
|
||||
|
||||
parts = raw.split("#", 1)
|
||||
target = parts[0].strip()
|
||||
section = parts[1].strip() if len(parts) > 1 else None
|
||||
|
||||
# Handle Self-Link [[#Section]] -> target wird zu current_note_id
|
||||
if not target and section and current_note_id:
|
||||
target = current_note_id
|
||||
|
||||
return target, section
|
||||
|
||||
def load_types_registry() -> dict:
|
||||
"""Lädt die YAML-Registry."""
|
||||
p = os.getenv("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/graph_adapter.py
|
||||
DESCRIPTION: Facade für das neue graph Package (Adapter-Teil).
|
||||
WP-14: Modularisierung abgeschlossen.
|
||||
VERSION: 0.5.0
|
||||
"""
|
||||
from .graph.graph_subgraph import Subgraph, expand
|
||||
from .graph.graph_weights import EDGE_BASE_WEIGHTS
|
||||
|
||||
__all__ = ["Subgraph", "expand", "EDGE_BASE_WEIGHTS"]
|
||||
@@ -3,9 +3,8 @@ FILE: app/core/ingestion/ingestion_note_payload.py
|
||||
DESCRIPTION: Baut das JSON-Objekt für mindnet_notes.
|
||||
FEATURES:
|
||||
- Multi-Hash (body/full) für flexible Change Detection.
|
||||
- Fix v2.4.4: Integration der zentralen Registry (WP-14) für konsistente Defaults.
|
||||
VERSION: 2.4.4
|
||||
STATUS: Active
|
||||
- Fix v2.4.5: Präzise Hash-Logik für Profil-Änderungen.
|
||||
- Integration der zentralen Registry (WP-14).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import Any, Dict, Tuple, Optional
|
||||
@@ -45,14 +44,23 @@ def _compute_hash(content: str) -> str:
|
||||
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||
|
||||
def _get_hash_source_content(n: Dict[str, Any], mode: str) -> str:
|
||||
"""Generiert den Hash-Input-String basierend auf Body oder Metadaten."""
|
||||
body = str(n.get("body") or "")
|
||||
"""
|
||||
Generiert den Hash-Input-String basierend auf Body oder Metadaten.
|
||||
Fix: Inkludiert nun alle entscheidungsrelevanten Profil-Parameter.
|
||||
"""
|
||||
body = str(n.get("body") or "").strip()
|
||||
if mode == "body": return body
|
||||
if mode == "full":
|
||||
fm = n.get("frontmatter") or {}
|
||||
meta_parts = []
|
||||
# Sortierte Liste für deterministische Hashes
|
||||
for k in sorted(["title", "type", "status", "tags", "chunking_profile", "chunk_profile", "retriever_weight"]):
|
||||
# Wir inkludieren alle Felder, die das Chunking oder Retrieval beeinflussen
|
||||
# Jede Änderung hier führt nun zwingend zu einem neuen Full-Hash
|
||||
keys = [
|
||||
"title", "type", "status", "tags",
|
||||
"chunking_profile", "chunk_profile",
|
||||
"retriever_weight", "split_level", "strict_heading_split"
|
||||
]
|
||||
for k in sorted(keys):
|
||||
val = fm.get(k)
|
||||
if val is not None: meta_parts.append(f"{k}:{val}")
|
||||
return f"{'|'.join(meta_parts)}||{body}"
|
||||
@@ -79,11 +87,11 @@ def _cfg_defaults(reg: dict) -> dict:
|
||||
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||
"""
|
||||
Baut das Note-Payload inklusive Multi-Hash und Audit-Validierung.
|
||||
WP-14: Nutzt nun die zentrale Registry für alle Fallbacks.
|
||||
WP-14: Nutzt die zentrale Registry für alle Fallbacks.
|
||||
"""
|
||||
n = _as_dict(note)
|
||||
|
||||
# Nutzt übergebene Registry oder lädt sie global
|
||||
# Registry & Context Settings
|
||||
reg = kwargs.get("types_cfg") or load_type_registry()
|
||||
hash_source = kwargs.get("hash_source", "parsed")
|
||||
hash_normalize = kwargs.get("hash_normalize", "canonical")
|
||||
@@ -96,7 +104,6 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||
ingest_cfg = reg.get("ingestion_settings", {})
|
||||
|
||||
# --- retriever_weight Audit ---
|
||||
# Priorität: Frontmatter -> Typ-Config -> globale Config -> Env-Var
|
||||
default_rw = float(os.environ.get("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0))
|
||||
retriever_weight = fm.get("retriever_weight")
|
||||
if retriever_weight is None:
|
||||
@@ -107,14 +114,13 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||
retriever_weight = default_rw
|
||||
|
||||
# --- chunk_profile Audit ---
|
||||
# Nutzt nun primär die ingestion_settings aus der Registry
|
||||
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||
if chunk_profile is None:
|
||||
chunk_profile = cfg_type.get("chunking_profile") or cfg_type.get("chunk_profile")
|
||||
if chunk_profile is None:
|
||||
chunk_profile = ingest_cfg.get("default_chunk_profile", cfg_def.get("chunking_profile", "sliding_standard"))
|
||||
|
||||
# --- edge_defaults ---
|
||||
# --- edge_defaults Audit ---
|
||||
edge_defaults = fm.get("edge_defaults")
|
||||
if edge_defaults is None:
|
||||
edge_defaults = cfg_type.get("edge_defaults", cfg_def.get("edge_defaults", []))
|
||||
@@ -138,21 +144,24 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
# --- MULTI-HASH ---
|
||||
# Generiert Hashes für Change Detection
|
||||
# Generiert Hashes für Change Detection (WP-15b)
|
||||
for mode in ["body", "full"]:
|
||||
content = _get_hash_source_content(n, mode)
|
||||
payload["hashes"][f"{mode}:{hash_source}:{hash_normalize}"] = _compute_hash(content)
|
||||
|
||||
# Metadaten Anreicherung
|
||||
# Metadaten Anreicherung (Tags, Aliases, Zeitstempel)
|
||||
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||
if tags: payload["tags"] = _ensure_list(tags)
|
||||
if fm.get("aliases"): payload["aliases"] = _ensure_list(fm.get("aliases"))
|
||||
|
||||
aliases = fm.get("aliases")
|
||||
if aliases: payload["aliases"] = _ensure_list(aliases)
|
||||
|
||||
for k in ("created", "modified", "date"):
|
||||
v = fm.get(k) or n.get(k)
|
||||
if v: payload[k] = str(v)
|
||||
|
||||
if n.get("body"): payload["fulltext"] = str(n["body"])
|
||||
if n.get("body"):
|
||||
payload["fulltext"] = str(n["body"])
|
||||
|
||||
# Final JSON Validation Audit
|
||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||
|
||||
@@ -4,8 +4,8 @@ DESCRIPTION: Der zentrale IngestionService (Orchestrator).
|
||||
WP-14: Modularisierung der Datenbank-Ebene (app.core.database).
|
||||
WP-15b: Two-Pass Workflow mit globalem Kontext-Cache.
|
||||
WP-20/22: Cloud-Resilienz und Content-Lifecycle integriert.
|
||||
AUDIT v2.13.10: Umstellung auf app.core.database Infrastruktur.
|
||||
VERSION: 2.13.10
|
||||
AUDIT v2.13.12: Synchronisierung der Profil-Auflösung mit Registry-Defaults.
|
||||
VERSION: 2.13.12
|
||||
STATUS: Active
|
||||
"""
|
||||
import logging
|
||||
@@ -38,7 +38,7 @@ from .ingestion_chunk_payload import make_chunk_payloads
|
||||
|
||||
# Fallback für Edges (Struktur-Verknüpfung)
|
||||
try:
|
||||
from app.core.derive_edges import build_edges_for_note
|
||||
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||
except ImportError:
|
||||
def build_edges_for_note(*args, **kwargs): return []
|
||||
|
||||
@@ -60,6 +60,7 @@ class IngestionService:
|
||||
self.embedder = EmbeddingsClient()
|
||||
self.llm = LLMService()
|
||||
|
||||
# Festlegen, welcher Hash für die Change-Detection maßgeblich ist
|
||||
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
|
||||
self.batch_cache: Dict[str, NoteContext] = {} # WP-15b LocalBatchCache
|
||||
|
||||
@@ -130,12 +131,18 @@ class IngestionService:
|
||||
)
|
||||
note_id = note_pl["note_id"]
|
||||
|
||||
# Abgleich mit der Datenbank (Qdrant)
|
||||
old_payload = None if force_replace else fetch_note_payload(self.client, self.prefix, note_id)
|
||||
|
||||
# Prüfung gegen den konfigurierten Hash-Modus (body vs. full)
|
||||
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
||||
old_hash = (old_payload or {}).get("hashes", {}).get(check_key)
|
||||
new_hash = note_pl.get("hashes", {}).get(check_key)
|
||||
|
||||
# Check ob Chunks oder Kanten in der DB fehlen (Reparatur-Modus)
|
||||
c_miss, e_miss = artifacts_missing(self.client, self.prefix, note_id)
|
||||
|
||||
# Wenn Hash identisch und Artefakte vorhanden -> Skip
|
||||
if not (force_replace or not old_payload or old_hash != new_hash or c_miss or e_miss):
|
||||
return {**result, "status": "unchanged", "note_id": note_id}
|
||||
|
||||
@@ -146,36 +153,49 @@ class IngestionService:
|
||||
try:
|
||||
body_text = getattr(parsed, "body", "") or ""
|
||||
edge_registry.ensure_latest()
|
||||
profile = fm.get("chunk_profile") or fm.get("chunking_profile") or "sliding_standard"
|
||||
|
||||
# Profil-Auflösung via Registry
|
||||
# FIX: Wir nutzen das Profil, das bereits in make_note_payload unter
|
||||
# Berücksichtigung der types.yaml (Registry) ermittelt wurde.
|
||||
profile = note_pl.get("chunk_profile", "sliding_standard")
|
||||
|
||||
chunk_cfg = get_chunk_config_by_profile(self.registry, profile, note_type)
|
||||
enable_smart = chunk_cfg.get("enable_smart_edge_allocation", False)
|
||||
|
||||
# WP-15b: Chunker-Aufruf bereitet Candidate-Pool vor
|
||||
# WP-15b: Chunker-Aufruf bereitet den Candidate-Pool pro Chunk vor.
|
||||
# assemble_chunks führt intern auch die Propagierung durch.
|
||||
chunks = await assemble_chunks(note_id, body_text, note_type, config=chunk_cfg)
|
||||
|
||||
# Semantische Kanten-Validierung (Smart Edge Allocation)
|
||||
for ch in chunks:
|
||||
filtered = []
|
||||
for cand in getattr(ch, "candidate_pool", []):
|
||||
# WP-15b: Nur global_pool Kandidaten erfordern binäre Validierung
|
||||
# Nur global_pool Kandidaten (aus dem Pool am Ende) erfordern KI-Validierung
|
||||
if cand.get("provenance") == "global_pool" and enable_smart:
|
||||
if await validate_edge_candidate(ch.text, cand, self.batch_cache, self.llm, self.settings.MINDNET_LLM_PROVIDER):
|
||||
filtered.append(cand)
|
||||
else:
|
||||
# Explizite Kanten (Wikilinks/Callouts) werden ungeprüft übernommen
|
||||
filtered.append(cand)
|
||||
ch.candidate_pool = filtered
|
||||
|
||||
# Payload-Erstellung via interne Module
|
||||
# Payload-Erstellung für die Chunks
|
||||
chunk_pls = make_chunk_payloads(
|
||||
fm, note_pl["path"], chunks, file_path=file_path,
|
||||
types_cfg=self.registry
|
||||
)
|
||||
|
||||
# Vektorisierung der Fenster-Texte
|
||||
vecs = await self.embedder.embed_documents([c.get("window") or "" for c in chunk_pls]) if chunk_pls else []
|
||||
|
||||
# Kanten-Aggregation
|
||||
# Aggregation aller finalen Kanten (Edges)
|
||||
edges = build_edges_for_note(
|
||||
note_id, chunk_pls,
|
||||
note_level_references=note_pl.get("references", []),
|
||||
include_note_scope_refs=note_scope_refs
|
||||
)
|
||||
|
||||
# Kanten-Typen via Registry validieren/auflösen
|
||||
for e in edges:
|
||||
e["kind"] = edge_registry.resolve(
|
||||
e.get("kind", "related_to"),
|
||||
@@ -184,16 +204,20 @@ class IngestionService:
|
||||
)
|
||||
|
||||
# 4. DB Upsert via modularisierter Points-Logik
|
||||
# WICHTIG: Wenn sich der Inhalt geändert hat, löschen wir erst alle alten Fragmente.
|
||||
if purge_before and old_payload:
|
||||
purge_artifacts(self.client, self.prefix, note_id)
|
||||
|
||||
# Speichern der Haupt-Note
|
||||
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||
upsert_batch(self.client, n_name, n_pts)
|
||||
|
||||
# Speichern der Chunks
|
||||
if chunk_pls and vecs:
|
||||
c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)[1]
|
||||
upsert_batch(self.client, f"{self.prefix}_chunks", c_pts)
|
||||
|
||||
# Speichern der Kanten
|
||||
if edges:
|
||||
e_pts = points_for_edges(self.prefix, edges)[1]
|
||||
upsert_batch(self.client, f"{self.prefix}_edges", e_pts)
|
||||
@@ -217,4 +241,5 @@ class IngestionService:
|
||||
with open(target_path, "w", encoding="utf-8") as f:
|
||||
f.write(markdown_content)
|
||||
await asyncio.sleep(0.1)
|
||||
# Triggert sofortigen Import mit force_replace/purge_before
|
||||
return await self.process_file(file_path=target_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
||||
@@ -1,22 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/qdrant.py
|
||||
DESCRIPTION: Proxy-Modul zur Aufrechterhaltung der Abwärtskompatibilität (WP-14).
|
||||
Leitet alle Aufrufe an das neue database-Paket weiter.
|
||||
STATUS: Proxy (Legacy-Support)
|
||||
"""
|
||||
from .database.qdrant import (
|
||||
QdrantConfig,
|
||||
get_client,
|
||||
ensure_collections,
|
||||
ensure_payload_indexes,
|
||||
collection_names
|
||||
)
|
||||
|
||||
# Re-Export für 100% Kompatibilität
|
||||
__all__ = [
|
||||
"QdrantConfig",
|
||||
"get_client",
|
||||
"ensure_collections",
|
||||
"ensure_payload_indexes",
|
||||
"collection_names",
|
||||
]
|
||||
@@ -1,24 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/qdrant_points.py
|
||||
DESCRIPTION: Proxy-Modul zur Aufrechterhaltung der Abwärtskompatibilität (WP-14).
|
||||
Leitet Point-Operationen an das neue database-Paket weiter.
|
||||
STATUS: Proxy (Legacy-Support)
|
||||
"""
|
||||
from .database.qdrant_points import (
|
||||
points_for_note,
|
||||
points_for_chunks,
|
||||
points_for_edges,
|
||||
upsert_batch,
|
||||
get_edges_for_sources,
|
||||
search_chunks_by_vector
|
||||
)
|
||||
|
||||
# Re-Export für 100% Kompatibilität
|
||||
__all__ = [
|
||||
"points_for_note",
|
||||
"points_for_chunks",
|
||||
"points_for_edges",
|
||||
"upsert_batch",
|
||||
"get_edges_for_sources",
|
||||
"search_chunks_by_vector"
|
||||
]
|
||||
@@ -25,10 +25,10 @@ import app.core.database.qdrant as qdr
|
||||
import app.core.database.qdrant_points as qp
|
||||
|
||||
import app.services.embeddings_client as ec
|
||||
import app.core.graph_adapter as ga
|
||||
import app.core.graph.graph_subgraph as ga
|
||||
|
||||
# Mathematische Engine importieren (Bleibt vorerst in app.core)
|
||||
from app.core.retriever_scoring import get_weights, compute_wp22_score
|
||||
# Mathematische Engine importieren
|
||||
from app.core.retrieval.retriever_scoring import get_weights, compute_wp22_score
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/retriever.py
|
||||
DESCRIPTION: Proxy-Modul zur Aufrechterhaltung der Abwärtskompatibilität (WP-14).
|
||||
Leitet Retrieval-Anfragen an das neue retrieval-Paket weiter.
|
||||
STATUS: Proxy (Legacy-Support)
|
||||
"""
|
||||
from .retrieval.retriever import (
|
||||
Retriever,
|
||||
hybrid_retrieve,
|
||||
semantic_retrieve
|
||||
)
|
||||
|
||||
# Re-Export für 100% Kompatibilität
|
||||
__all__ = ["Retriever", "hybrid_retrieve", "semantic_retrieve"]
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
FILE: app/core/retriever_scoring.py
|
||||
DESCRIPTION: Proxy-Modul zur Aufrechterhaltung der Abwärtskompatibilität (WP-14).
|
||||
Leitet Scoring-Berechnungen an das neue retrieval-Paket weiter.
|
||||
STATUS: Proxy (Legacy-Support)
|
||||
"""
|
||||
from .retrieval.retriever_scoring import (
|
||||
get_weights,
|
||||
compute_wp22_score,
|
||||
get_status_multiplier
|
||||
)
|
||||
|
||||
# Re-Export für 100% Kompatibilität
|
||||
__all__ = [
|
||||
"get_weights",
|
||||
"compute_wp22_score",
|
||||
"get_status_multiplier"
|
||||
]
|
||||
@@ -69,20 +69,35 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
||||
|
||||
if search_term:
|
||||
hits, _ = graph_service.client.scroll(
|
||||
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||
limit=10,
|
||||
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
||||
)
|
||||
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
||||
|
||||
if options:
|
||||
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
||||
if st.button("Laden", use_container_width=True, key="cy_load"):
|
||||
new_id = options[selected_title]
|
||||
st.session_state.graph_center_id = new_id
|
||||
st.session_state.graph_inspected_id = new_id
|
||||
st.rerun()
|
||||
try:
|
||||
hits, _ = graph_service.client.scroll(
|
||||
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||
limit=10,
|
||||
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
||||
)
|
||||
options = {}
|
||||
for h in hits:
|
||||
if h.payload and 'title' in h.payload and 'note_id' in h.payload:
|
||||
title = h.payload['title']
|
||||
note_id = h.payload['note_id']
|
||||
# Vermeide Duplikate (falls mehrere Chunks/Notes denselben Titel haben)
|
||||
if title not in options:
|
||||
options[title] = note_id
|
||||
|
||||
if options:
|
||||
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
||||
if st.button("Laden", use_container_width=True, key="cy_load"):
|
||||
new_id = options[selected_title]
|
||||
st.session_state.graph_center_id = new_id
|
||||
st.session_state.graph_inspected_id = new_id
|
||||
st.rerun()
|
||||
else:
|
||||
# Zeige Info, wenn keine Ergebnisse gefunden wurden
|
||||
st.info(f"Keine Notizen mit '{search_term}' im Titel gefunden.")
|
||||
except Exception as e:
|
||||
st.error(f"Fehler bei der Suche: {e}")
|
||||
import traceback
|
||||
st.code(traceback.format_exc())
|
||||
|
||||
st.divider()
|
||||
|
||||
@@ -138,6 +153,26 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
)
|
||||
# 2. Detail Daten (Inspector)
|
||||
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
||||
|
||||
# DEBUG: Zeige Debug-Informationen
|
||||
with st.expander("🔍 Debug-Informationen", expanded=False):
|
||||
st.write(f"**Gefundene Knoten:** {len(nodes_data) if nodes_data else 0}")
|
||||
st.write(f"**Gefundene Kanten:** {len(edges_data) if edges_data else 0}")
|
||||
if nodes_data:
|
||||
st.write("**Knoten-IDs:**")
|
||||
for n in nodes_data[:10]:
|
||||
nid = getattr(n, 'id', 'N/A')
|
||||
st.write(f" - {nid}")
|
||||
if len(nodes_data) > 10:
|
||||
st.write(f" ... und {len(nodes_data) - 10} weitere")
|
||||
if edges_data:
|
||||
st.write("**Kanten:**")
|
||||
for e in edges_data[:10]:
|
||||
src = getattr(e, "source", "N/A")
|
||||
tgt = getattr(e, "to", getattr(e, "target", "N/A"))
|
||||
st.write(f" - {src} -> {tgt}")
|
||||
if len(edges_data) > 10:
|
||||
st.write(f" ... und {len(edges_data) - 10} weitere")
|
||||
|
||||
# --- ACTION BAR ---
|
||||
action_container = st.container()
|
||||
@@ -174,7 +209,12 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
||||
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
||||
with col_i2:
|
||||
st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}")
|
||||
tags = inspected_data.get('tags', [])
|
||||
if isinstance(tags, list):
|
||||
tags_str = ', '.join(tags) if tags else "Keine"
|
||||
else:
|
||||
tags_str = str(tags) if tags else "Keine"
|
||||
st.markdown(f"**Tags:** {tags_str}")
|
||||
path_check = "✅" if inspected_data.get('path') else "❌"
|
||||
st.markdown(f"**Pfad:** {path_check}")
|
||||
|
||||
@@ -189,12 +229,27 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
# --- GRAPH ELEMENTS ---
|
||||
cy_elements = []
|
||||
|
||||
# Validierung: Prüfe ob nodes_data vorhanden ist
|
||||
if not nodes_data:
|
||||
st.warning("⚠️ Keine Knoten gefunden. Bitte wähle eine andere Notiz.")
|
||||
# Zeige trotzdem den Inspector, falls Daten vorhanden
|
||||
if inspected_data:
|
||||
st.info(f"**Hinweis:** Die Notiz '{inspected_data.get('title', inspected_id)}' wurde gefunden, hat aber keine Verbindungen im Graphen.")
|
||||
return
|
||||
|
||||
# Erstelle Set aller Node-IDs für schnelle Validierung
|
||||
node_ids = {n.id for n in nodes_data if hasattr(n, 'id') and n.id}
|
||||
|
||||
# Nodes hinzufügen
|
||||
for n in nodes_data:
|
||||
if not hasattr(n, 'id') or not n.id:
|
||||
continue
|
||||
|
||||
is_center = (n.id == center_id)
|
||||
is_inspected = (n.id == inspected_id)
|
||||
|
||||
tooltip_text = n.title if n.title else n.label
|
||||
display_label = n.label
|
||||
tooltip_text = getattr(n, 'title', None) or getattr(n, 'label', '')
|
||||
display_label = getattr(n, 'label', str(n.id))
|
||||
if len(display_label) > 15 and " " in display_label:
|
||||
display_label = display_label.replace(" ", "\n", 1)
|
||||
|
||||
@@ -202,7 +257,7 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
"data": {
|
||||
"id": n.id,
|
||||
"label": display_label,
|
||||
"bg_color": n.color,
|
||||
"bg_color": getattr(n, 'color', '#8395a7'),
|
||||
"tooltip": tooltip_text
|
||||
},
|
||||
# Wir steuern das Aussehen rein über Klassen (.inspected / .center)
|
||||
@@ -211,18 +266,22 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
}
|
||||
cy_elements.append(cy_node)
|
||||
|
||||
for e in edges_data:
|
||||
target_id = getattr(e, "to", getattr(e, "target", None))
|
||||
if target_id:
|
||||
cy_edge = {
|
||||
"data": {
|
||||
"source": e.source,
|
||||
"target": target_id,
|
||||
"label": e.label,
|
||||
"line_color": e.color
|
||||
# Edges hinzufügen - nur wenn beide Nodes im Graph vorhanden sind
|
||||
if edges_data:
|
||||
for e in edges_data:
|
||||
source_id = getattr(e, "source", None)
|
||||
target_id = getattr(e, "to", getattr(e, "target", None))
|
||||
# Nur hinzufügen, wenn beide IDs vorhanden UND beide Nodes im Graph sind
|
||||
if source_id and target_id and source_id in node_ids and target_id in node_ids:
|
||||
cy_edge = {
|
||||
"data": {
|
||||
"source": source_id,
|
||||
"target": target_id,
|
||||
"label": getattr(e, "label", ""),
|
||||
"line_color": getattr(e, "color", "#bdc3c7")
|
||||
}
|
||||
}
|
||||
}
|
||||
cy_elements.append(cy_edge)
|
||||
cy_elements.append(cy_edge)
|
||||
|
||||
# --- STYLESHEET ---
|
||||
stylesheet = [
|
||||
@@ -292,43 +351,47 @@ def render_graph_explorer_cytoscape(graph_service):
|
||||
]
|
||||
|
||||
# --- RENDER ---
|
||||
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
||||
# Nur rendern, wenn Elemente vorhanden sind
|
||||
if not cy_elements:
|
||||
st.warning("⚠️ Keine Graph-Elemente zum Anzeigen gefunden.")
|
||||
else:
|
||||
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
||||
|
||||
clicked_elements = cytoscape(
|
||||
elements=cy_elements,
|
||||
stylesheet=stylesheet,
|
||||
layout={
|
||||
"name": "cose",
|
||||
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
||||
"nodeOverlap": 20,
|
||||
"refresh": 20,
|
||||
"fit": True,
|
||||
"padding": 50,
|
||||
"randomize": False,
|
||||
"componentSpacing": 100,
|
||||
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
||||
"edgeElasticity": 100,
|
||||
"nestingFactor": 5,
|
||||
"gravity": 80,
|
||||
"numIter": 1000,
|
||||
"initialTemp": 200,
|
||||
"coolingFactor": 0.95,
|
||||
"minTemp": 1.0,
|
||||
"animate": False
|
||||
},
|
||||
key=graph_key,
|
||||
height="700px"
|
||||
)
|
||||
clicked_elements = cytoscape(
|
||||
elements=cy_elements,
|
||||
stylesheet=stylesheet,
|
||||
layout={
|
||||
"name": "cose",
|
||||
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
||||
"nodeOverlap": 20,
|
||||
"refresh": 20,
|
||||
"fit": True,
|
||||
"padding": 50,
|
||||
"randomize": False,
|
||||
"componentSpacing": 100,
|
||||
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
||||
"edgeElasticity": 100,
|
||||
"nestingFactor": 5,
|
||||
"gravity": 80,
|
||||
"numIter": 1000,
|
||||
"initialTemp": 200,
|
||||
"coolingFactor": 0.95,
|
||||
"minTemp": 1.0,
|
||||
"animate": False
|
||||
},
|
||||
key=graph_key,
|
||||
height="700px"
|
||||
)
|
||||
|
||||
# --- EVENT HANDLING ---
|
||||
if clicked_elements:
|
||||
clicked_nodes = clicked_elements.get("nodes", [])
|
||||
if clicked_nodes:
|
||||
clicked_id = clicked_nodes[0]
|
||||
|
||||
if clicked_id != st.session_state.graph_inspected_id:
|
||||
st.session_state.graph_inspected_id = clicked_id
|
||||
st.rerun()
|
||||
# --- EVENT HANDLING ---
|
||||
if clicked_elements:
|
||||
clicked_nodes = clicked_elements.get("nodes", [])
|
||||
if clicked_nodes:
|
||||
clicked_id = clicked_nodes[0]
|
||||
|
||||
if clicked_id != st.session_state.graph_inspected_id:
|
||||
st.session_state.graph_inspected_id = clicked_id
|
||||
st.rerun()
|
||||
|
||||
else:
|
||||
st.info("👈 Bitte wähle links eine Notiz aus.")
|
||||
@@ -10,15 +10,19 @@ LAST_ANALYSIS: 2025-12-15
|
||||
import re
|
||||
from qdrant_client import QdrantClient, models
|
||||
from streamlit_agraph import Node, Edge
|
||||
from ui_config import GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
||||
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
||||
|
||||
class GraphExplorerService:
|
||||
def __init__(self, url, api_key=None, prefix="mindnet"):
|
||||
def __init__(self, url, api_key=None, prefix=None):
|
||||
"""
|
||||
Initialisiert den Service. Nutzt COLLECTION_PREFIX aus der Config,
|
||||
sofern kein spezifischer Prefix übergeben wurde.
|
||||
"""
|
||||
self.client = QdrantClient(url=url, api_key=api_key)
|
||||
self.prefix = prefix
|
||||
self.notes_col = f"{prefix}_notes"
|
||||
self.chunks_col = f"{prefix}_chunks"
|
||||
self.edges_col = f"{prefix}_edges"
|
||||
self.prefix = prefix if prefix else COLLECTION_PREFIX
|
||||
self.notes_col = f"{self.prefix}_notes"
|
||||
self.chunks_col = f"{self.prefix}_chunks"
|
||||
self.edges_col = f"{self.prefix}_edges"
|
||||
self._note_cache = {}
|
||||
|
||||
def get_note_with_full_content(self, note_id):
|
||||
@@ -163,31 +167,33 @@ class GraphExplorerService:
|
||||
return previews
|
||||
|
||||
def _find_connected_edges(self, note_ids, note_title=None):
|
||||
"""Findet eingehende und ausgehende Kanten."""
|
||||
"""
|
||||
Findet eingehende und ausgehende Kanten.
|
||||
|
||||
WICHTIG: target_id enthält nur den Titel (ohne #Abschnitt).
|
||||
target_section ist ein separates Feld für Abschnitt-Informationen.
|
||||
"""
|
||||
results = []
|
||||
if not note_ids:
|
||||
return results
|
||||
|
||||
# 1. OUTGOING EDGES (Der "Owner"-Fix)
|
||||
# Wir suchen Kanten, die im Feld 'note_id' (Owner) eine unserer Notizen haben.
|
||||
# Das findet ALLE ausgehenden Kanten, egal ob sie an einem Chunk oder der Note hängen.
|
||||
if note_ids:
|
||||
out_filter = models.Filter(must=[
|
||||
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
||||
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
||||
])
|
||||
# Limit hoch, um alles zu finden
|
||||
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_filter, limit=500, with_payload=True)
|
||||
results.extend(res_out)
|
||||
out_filter = models.Filter(must=[
|
||||
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
||||
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
||||
])
|
||||
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_filter, limit=2000, with_payload=True)
|
||||
results.extend(res_out)
|
||||
|
||||
# 2. INCOMING EDGES (Ziel = Chunk ID oder Titel oder Note ID)
|
||||
# Hier müssen wir Chunks auflösen, um Treffer auf Chunks zu finden.
|
||||
# 2. INCOMING EDGES (Ziel = Chunk ID, Note ID oder Titel)
|
||||
# WICHTIG: target_id enthält nur den Titel, target_section ist separat
|
||||
|
||||
# Chunk IDs der aktuellen Notes holen
|
||||
chunk_ids = []
|
||||
if note_ids:
|
||||
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
||||
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=300)
|
||||
chunk_ids = [c.id for c in chunks]
|
||||
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
||||
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=1000, with_payload=False)
|
||||
chunk_ids = [c.id for c in chunks]
|
||||
|
||||
shoulds = []
|
||||
# Case A: Edge zeigt auf einen unserer Chunks
|
||||
@@ -195,42 +201,92 @@ class GraphExplorerService:
|
||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
|
||||
|
||||
# Case B: Edge zeigt direkt auf unsere Note ID
|
||||
if note_ids:
|
||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
|
||||
|
||||
# Case C: Edge zeigt auf unseren Titel (Wikilinks)
|
||||
if note_title:
|
||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=note_title)))
|
||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
|
||||
|
||||
# Case C: Edge zeigt auf unseren Titel
|
||||
# WICHTIG: target_id enthält nur den Titel (z.B. "Meine Prinzipien 2025")
|
||||
# target_section enthält die Abschnitt-Information (z.B. "P3 – Disziplin"), wenn gesetzt
|
||||
|
||||
# Sammle alle relevanten Titel (inkl. Aliase)
|
||||
titles_to_search = []
|
||||
if note_title:
|
||||
titles_to_search.append(note_title)
|
||||
|
||||
# Lade auch Titel aus den Notes selbst (falls note_title nicht übergeben wurde)
|
||||
for nid in note_ids:
|
||||
note = self._fetch_note_cached(nid)
|
||||
if note:
|
||||
note_title_from_db = note.get("title")
|
||||
if note_title_from_db and note_title_from_db not in titles_to_search:
|
||||
titles_to_search.append(note_title_from_db)
|
||||
# Aliase hinzufügen
|
||||
aliases = note.get("aliases", [])
|
||||
if isinstance(aliases, str):
|
||||
aliases = [aliases]
|
||||
for alias in aliases:
|
||||
if alias and alias not in titles_to_search:
|
||||
titles_to_search.append(alias)
|
||||
|
||||
# Für jeden Titel: Suche nach exaktem Match
|
||||
# target_id enthält nur den Titel, daher reicht MatchValue
|
||||
for title in titles_to_search:
|
||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=title)))
|
||||
|
||||
if shoulds:
|
||||
in_filter = models.Filter(
|
||||
must=[models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))],
|
||||
should=shoulds
|
||||
)
|
||||
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=500, with_payload=True)
|
||||
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=2000, with_payload=True)
|
||||
results.extend(res_in)
|
||||
|
||||
return results
|
||||
|
||||
def _find_connected_edges_batch(self, note_ids):
|
||||
# Wrapper für Level 2 Suche
|
||||
return self._find_connected_edges(note_ids)
|
||||
"""
|
||||
Wrapper für Level 2 Suche.
|
||||
Lädt Titel der ersten Note für Titel-basierte Suche.
|
||||
"""
|
||||
if not note_ids:
|
||||
return []
|
||||
first_note = self._fetch_note_cached(note_ids[0])
|
||||
note_title = first_note.get("title") if first_note else None
|
||||
return self._find_connected_edges(note_ids, note_title=note_title)
|
||||
|
||||
def _process_edge(self, record, nodes_dict, unique_edges, current_depth):
|
||||
"""Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu."""
|
||||
"""
|
||||
Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu.
|
||||
|
||||
WICHTIG: Beide Richtungen werden unterstützt:
|
||||
- Ausgehende Kanten: source_id gehört zu unserer Note (via note_id Owner)
|
||||
- Eingehende Kanten: target_id zeigt auf unsere Note (via target_id Match)
|
||||
"""
|
||||
if not record or not record.payload:
|
||||
return None, None
|
||||
|
||||
payload = record.payload
|
||||
src_ref = payload.get("source_id")
|
||||
tgt_ref = payload.get("target_id")
|
||||
kind = payload.get("kind")
|
||||
provenance = payload.get("provenance", "explicit")
|
||||
|
||||
# Prüfe, ob beide Referenzen vorhanden sind
|
||||
if not src_ref or not tgt_ref:
|
||||
return None, None
|
||||
|
||||
# IDs zu Notes auflösen
|
||||
# WICHTIG: source_id kann Chunk-ID (note_id#c01), Note-ID oder Titel sein
|
||||
# WICHTIG: target_id kann Chunk-ID, Note-ID oder Titel sein (ohne #Abschnitt)
|
||||
src_note = self._resolve_note_from_ref(src_ref)
|
||||
tgt_note = self._resolve_note_from_ref(tgt_ref)
|
||||
|
||||
if src_note and tgt_note:
|
||||
src_id = src_note['note_id']
|
||||
tgt_id = tgt_note['note_id']
|
||||
src_id = src_note.get('note_id')
|
||||
tgt_id = tgt_note.get('note_id')
|
||||
|
||||
# Prüfe, ob beide IDs vorhanden sind
|
||||
if not src_id or not tgt_id:
|
||||
return None, None
|
||||
|
||||
if src_id != tgt_id:
|
||||
# Nodes hinzufügen
|
||||
@@ -245,7 +301,7 @@ class GraphExplorerService:
|
||||
# Bevorzuge explizite Kanten vor Smart Kanten
|
||||
is_current_explicit = (provenance in ["explicit", "rule"])
|
||||
if existing:
|
||||
is_existing_explicit = (existing['provenance'] in ["explicit", "rule"])
|
||||
is_existing_explicit = (existing.get('provenance', '') in ["explicit", "rule"])
|
||||
if is_existing_explicit and not is_current_explicit:
|
||||
should_update = False
|
||||
|
||||
@@ -267,38 +323,109 @@ class GraphExplorerService:
|
||||
return None
|
||||
|
||||
def _resolve_note_from_ref(self, ref_str):
|
||||
"""Löst eine ID (Chunk, Note oder Titel) zu einer Note Payload auf."""
|
||||
if not ref_str: return None
|
||||
"""
|
||||
Löst eine Referenz zu einer Note Payload auf.
|
||||
|
||||
# Fall A: Chunk ID (enthält #)
|
||||
WICHTIG: Wenn ref_str ein Titel#Abschnitt Format hat, wird nur der Titel-Teil verwendet.
|
||||
Unterstützt:
|
||||
- Note-ID: "20250101-meine-note"
|
||||
- Chunk-ID: "20250101-meine-note#c01"
|
||||
- Titel: "Meine Prinzipien 2025"
|
||||
- Titel#Abschnitt: "Meine Prinzipien 2025#P3 – Disziplin" (trennt Abschnitt ab, sucht nur nach Titel)
|
||||
"""
|
||||
if not ref_str:
|
||||
return None
|
||||
|
||||
# Fall A: Enthält # (kann Chunk-ID oder Titel#Abschnitt sein)
|
||||
if "#" in ref_str:
|
||||
try:
|
||||
# Versuch 1: Chunk ID direkt
|
||||
# Versuch 1: Chunk ID direkt (Format: note_id#c01)
|
||||
res = self.client.retrieve(self.chunks_col, ids=[ref_str], with_payload=True)
|
||||
if res: return self._fetch_note_cached(res[0].payload.get("note_id"))
|
||||
except: pass
|
||||
if res and res[0].payload:
|
||||
note_id = res[0].payload.get("note_id")
|
||||
if note_id:
|
||||
return self._fetch_note_cached(note_id)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Versuch 2: NoteID#Section (Hash abtrennen)
|
||||
possible_note_id = ref_str.split("#")[0]
|
||||
if self._fetch_note_cached(possible_note_id): return self._fetch_note_cached(possible_note_id)
|
||||
# Versuch 2: NoteID#Section (Hash abtrennen und als Note-ID versuchen)
|
||||
# z.B. "20250101-meine-note#Abschnitt" -> "20250101-meine-note"
|
||||
possible_note_id = ref_str.split("#")[0].strip()
|
||||
note = self._fetch_note_cached(possible_note_id)
|
||||
if note:
|
||||
return note
|
||||
|
||||
# Versuch 3: Titel#Abschnitt (Hash abtrennen und als Titel suchen)
|
||||
# z.B. "Meine Prinzipien 2025#P3 – Disziplin" -> "Meine Prinzipien 2025"
|
||||
# WICHTIG: target_id enthält nur den Titel, daher suchen wir nur nach dem Titel-Teil
|
||||
possible_title = ref_str.split("#")[0].strip()
|
||||
if possible_title:
|
||||
res, _ = self.client.scroll(
|
||||
collection_name=self.notes_col,
|
||||
scroll_filter=models.Filter(must=[
|
||||
models.FieldCondition(key="title", match=models.MatchValue(value=possible_title))
|
||||
]),
|
||||
limit=1, with_payload=True
|
||||
)
|
||||
if res and res[0].payload:
|
||||
payload = res[0].payload
|
||||
self._note_cache[payload['note_id']] = payload
|
||||
return payload
|
||||
|
||||
# Fallback: Text-Suche für Fuzzy-Matching
|
||||
res, _ = self.client.scroll(
|
||||
collection_name=self.notes_col,
|
||||
scroll_filter=models.Filter(must=[
|
||||
models.FieldCondition(key="title", match=models.MatchText(text=possible_title))
|
||||
]),
|
||||
limit=10, with_payload=True
|
||||
)
|
||||
if res:
|
||||
# Nimm das erste Ergebnis, das exakt oder beginnend mit possible_title übereinstimmt
|
||||
for r in res:
|
||||
if r.payload:
|
||||
note_title = r.payload.get("title", "")
|
||||
if note_title == possible_title or note_title.startswith(possible_title):
|
||||
payload = r.payload
|
||||
self._note_cache[payload['note_id']] = payload
|
||||
return payload
|
||||
|
||||
# Fall B: Note ID direkt
|
||||
if self._fetch_note_cached(ref_str): return self._fetch_note_cached(ref_str)
|
||||
note = self._fetch_note_cached(ref_str)
|
||||
if note:
|
||||
return note
|
||||
|
||||
# Fall C: Titel
|
||||
# Fall C: Titel (exakte Übereinstimmung)
|
||||
res, _ = self.client.scroll(
|
||||
collection_name=self.notes_col,
|
||||
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))]),
|
||||
scroll_filter=models.Filter(must=[
|
||||
models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))
|
||||
]),
|
||||
limit=1, with_payload=True
|
||||
)
|
||||
if res:
|
||||
self._note_cache[res[0].payload['note_id']] = res[0].payload
|
||||
return res[0].payload
|
||||
if res and res[0].payload:
|
||||
payload = res[0].payload
|
||||
self._note_cache[payload['note_id']] = payload
|
||||
return payload
|
||||
|
||||
# Fall D: Titel (Text-Suche für Fuzzy-Matching)
|
||||
res, _ = self.client.scroll(
|
||||
collection_name=self.notes_col,
|
||||
scroll_filter=models.Filter(must=[
|
||||
models.FieldCondition(key="title", match=models.MatchText(text=ref_str))
|
||||
]),
|
||||
limit=1, with_payload=True
|
||||
)
|
||||
if res and res[0].payload:
|
||||
payload = res[0].payload
|
||||
self._note_cache[payload['note_id']] = payload
|
||||
return payload
|
||||
|
||||
return None
|
||||
|
||||
def _add_node_to_dict(self, node_dict, note_payload, level=1):
|
||||
nid = note_payload.get("note_id")
|
||||
if nid in node_dict: return
|
||||
if not nid or nid in node_dict: return
|
||||
|
||||
ntype = note_payload.get("type", "default")
|
||||
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
|
||||
|
||||
+3
-2
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
FILE: app/models/dto.py
|
||||
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
||||
VERSION: 0.6.6 (WP-22 Debug & Stability Update)
|
||||
VERSION: 0.6.7 (WP-Fix: Target Section Support)
|
||||
STATUS: Active
|
||||
DEPENDENCIES: pydantic, typing, uuid
|
||||
LAST_ANALYSIS: 2025-12-18
|
||||
LAST_ANALYSIS: 2025-12-29
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -43,6 +43,7 @@ class EdgeDTO(BaseModel):
|
||||
direction: Literal["out", "in", "undirected"] = "out"
|
||||
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
|
||||
confidence: float = 1.0
|
||||
target_section: Optional[str] = None # Neu: Speichert den Anker (z.B. #Abschnitt)
|
||||
|
||||
|
||||
# --- Request Models ---
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ from pathlib import Path
|
||||
from app.config import get_settings
|
||||
from app.models.dto import ChatRequest, ChatResponse, QueryRequest, QueryHit
|
||||
from app.services.llm_service import LLMService
|
||||
from app.core.retriever import Retriever
|
||||
from app.core.retrieval.retriever import Retriever
|
||||
from app.services.feedback_service import log_search
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -12,7 +12,7 @@ from typing import List, Optional
|
||||
from fastapi import APIRouter, Query
|
||||
from qdrant_client import QdrantClient
|
||||
from app.models.dto import GraphResponse, NodeDTO, EdgeDTO
|
||||
from app.core.graph_adapter import expand
|
||||
from app.core.graph.graph_subgraph import expand
|
||||
from app.config import get_settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -10,7 +10,7 @@ LAST_ANALYSIS: 2025-12-15
|
||||
from __future__ import annotations
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
from app.models.dto import QueryRequest, QueryResponse
|
||||
from app.core.retriever import hybrid_retrieve, semantic_retrieve
|
||||
from app.core.retrieval.retriever import hybrid_retrieve, semantic_retrieve
|
||||
# NEU:
|
||||
from app.services.feedback_service import log_search
|
||||
|
||||
|
||||
@@ -13,9 +13,9 @@ import os
|
||||
from typing import List, Dict, Any, Optional, Set
|
||||
import yaml
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
from app.models.dto import QueryRequest
|
||||
from app.core.retriever import hybrid_retrieve
|
||||
from app.core.retrieval.retriever import hybrid_retrieve
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -18,9 +18,12 @@ Das Repository ist in **logische Domänen** unterteilt.
|
||||
*Zielgruppe: Alle*
|
||||
| Datei | Inhalt & Zweck |
|
||||
| :--- | :--- |
|
||||
| `README.md` | **Einstiegspunkt.** Übersicht über die Dokumentationsstruktur, Schnellzugriff nach Rollen und Navigation. |
|
||||
| `00_quickstart.md` | **Schnellstart.** Installation und erste Schritte in 15 Minuten. Ideal für neue Benutzer. |
|
||||
| `00_vision_and_strategy.md` | **Strategie.** Warum bauen wir das? Prinzipien (Privacy, Local-First), High-Level Architektur. |
|
||||
| `00_glossary.md` | **Definitionen.** Was bedeutet "Smart Edge", "Traffic Control", "Chunk"? Verhindert Begriffsverwirrung. |
|
||||
| `00_documentation_map.md` | **Dieser Index.** Navigationshilfe. |
|
||||
| `00_quality_checklist.md` | **Qualitätsprüfung.** Systematische Checkliste zur Vollständigkeitsprüfung für alle Rollen. |
|
||||
|
||||
### 📂 01_User_Manual (Anwendung)
|
||||
*Zielgruppe: Mindmaster, Autoren, Power-User*
|
||||
@@ -28,7 +31,8 @@ Das Repository ist in **logische Domänen** unterteilt.
|
||||
| :--- | :--- |
|
||||
| `01_chat_usage_guide.md` | **Bedienung.** Wie steuere ich die Personas (Berater, Spiegel)? Wie nutze ich das Feedback? |
|
||||
| `01_knowledge_design.md` | **Content-Regeln.** Die "Bibel" für den Vault. Erklärt Note-Typen, Matrix-Logik und Markdown-Syntax. |
|
||||
| `01-authoring-guidelines` | **Content strukturieren-.** primäres Werkzeug, um Wissen so zu strukturieren, so dass Mindnet die Persönlichkeit spiegelt, empathisch reagiert und strategisch berät |
|
||||
| `01_authoring_guidelines.md` | **Content strukturieren.** Primäres Werkzeug, um Wissen so zu strukturieren, dass Mindnet die Persönlichkeit spiegelt, empathisch reagiert und strategisch berät. |
|
||||
| `01_obsidian_integration_guide.md` | **Obsidian Setup.** Technische Anleitung für die Integration von Mindnet mit Obsidian (Templater, Skripte, Workflows). |
|
||||
|
||||
### 📂 02_Concepts (Fachliche Logik)
|
||||
*Zielgruppe: Architekten, Product Owner*
|
||||
@@ -36,6 +40,7 @@ Das Repository ist in **logische Domänen** unterteilt.
|
||||
| :--- | :--- |
|
||||
| `02_concept_graph_logic.md` | **Graph-Theorie.** Abstrakte Erklärung von Knoten, Kanten, Provenance und Idempotenz. |
|
||||
| `02_concept_ai_personality.md`| **KI-Verhalten.** Konzepte hinter dem Hybrid Router, Empathie-Modell und "Teach-the-AI". |
|
||||
| `02_concept_architecture_patterns.md` | **Architektur-Patterns.** Design-Entscheidungen, modulare Struktur (WP-14), Resilienz-Patterns und Erweiterbarkeit. |
|
||||
|
||||
### 📂 03_Technical_Reference (Technik & Code)
|
||||
*Zielgruppe: Entwickler, DevOps. (Enthält JSON/YAML Beispiele)*
|
||||
@@ -47,12 +52,15 @@ Das Repository ist in **logische Domänen** unterteilt.
|
||||
| `03_tech_chat_backend.md` | **API & LLM.** Implementation des Routers, Traffic Control (Semaphore) und Feedback-Traceability. |
|
||||
| `03_tech_frontend.md` | **UI & Graph.** Architektur des Streamlit-Frontends, State-Management, Cytoscape-Integration und Editor-Logik. |
|
||||
| `03_tech_configuration.md` | **Config.** Referenztabellen für `.env`, `types.yaml` und `retriever.yaml`. |
|
||||
| `03_tech_api_reference.md` | **API-Referenz.** Vollständige Dokumentation aller Endpunkte (`/query`, `/chat`, `/ingest`, `/graph`, etc.). |
|
||||
|
||||
### 📂 04_Operations (Betrieb)
|
||||
*Zielgruppe: Administratoren*
|
||||
| Datei | Inhalt & Zweck |
|
||||
| :--- | :--- |
|
||||
| `04_admin_operations.md` | **Runbook.** Installation, Docker-Setup, Backup/Restore, Troubleshooting Guide. |
|
||||
| `04_server_operation_manual.md` | **Server-Betrieb.** Detaillierte Dokumentation für den Betrieb auf llm-node (Systemd, Borgmatic, Disaster Recovery). |
|
||||
| `04_deployment_guide.md` | **Deployment.** CI/CD-Pipelines, Rollout-Strategien, Versionierung, Rollback und Pre/Post-Deployment-Checklisten. |
|
||||
|
||||
### 📂 05_Development (Code)
|
||||
*Zielgruppe: Entwickler*
|
||||
@@ -60,6 +68,7 @@ Das Repository ist in **logische Domänen** unterteilt.
|
||||
| :--- | :--- |
|
||||
| `05_developer_guide.md` | **Workflow.** Hardware-Setup (Win/Pi/Beelink), Git-Flow, Test-Befehle, Modul-Interna. |
|
||||
| `05_genai_best_practices.md` | **AI Workflow.** Prompt-Library, Templates und Best Practices für die Entwicklung mit LLMs. |
|
||||
| `05_testing_guide.md` | **Testing.** Umfassender Test-Guide: Strategien, Frameworks, Test-Daten, Best Practices. |
|
||||
|
||||
### 📂 06_Roadmap & 99_Archive
|
||||
*Zielgruppe: Projektleitung*
|
||||
@@ -82,7 +91,9 @@ Nutze diese Matrix, wenn du ein Workpackage bearbeitest, um die Dokumentation ko
|
||||
| **Retrieval / Scoring** | `03_tech_retrieval_scoring.md` (Formeln anpassen) |
|
||||
| **Frontend / Visualisierung** | 1. `03_tech_frontend.md` (Technische Details)<br>2. `01_chat_usage_guide.md` (Bedienung) |
|
||||
| **Chat-Logik / Prompts**| 1. `02_concept_ai_personality.md` (Konzept)<br>2. `03_tech_chat_backend.md` (Tech)<br>3. `01_chat_usage_guide.md` (User-Sicht) |
|
||||
| **Deployment / Server** | `04_admin_operations.md` |
|
||||
| **Architektur / Design-Patterns** | 1. `02_concept_architecture_patterns.md` (Patterns & Entscheidungen)<br>2. `02_concept_graph_logic.md` (Graph-Theorie)<br>3. `05_developer_guide.md` (Modulare Struktur) |
|
||||
| **Deployment / Server** | 1. `04_deployment_guide.md` (CI/CD, Rollout)<br>2. `04_admin_operations.md` (Installation, Wartung)<br>3. `04_server_operation_manual.md` (Server-Betrieb) |
|
||||
| **Testing / QA** | 1. `05_testing_guide.md` (Test-Strategien & Frameworks)<br>2. `05_developer_guide.md` (Test-Befehle) |
|
||||
| **Neuen Features (Allg.)**| `06_active_roadmap.md` (Status Update) |
|
||||
|
||||
---
|
||||
@@ -110,4 +121,38 @@ Damit dieses System wartbar bleibt (auch für KI-Agenten wie NotebookLM), gelten
|
||||
audience: developer
|
||||
context: "Beschreibung der Scoring-Formel."
|
||||
---
|
||||
```
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Schnellzugriff & Empfehlungen
|
||||
|
||||
### Für neue Benutzer
|
||||
1. Starte mit **[Schnellstart](00_quickstart.md)** für die Installation
|
||||
2. Lese **[Vision & Strategie](00_vision_and_strategy.md)** für das große Bild
|
||||
3. Nutze **[Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)** für die ersten Schritte
|
||||
|
||||
### Für Entwickler
|
||||
1. **[Developer Guide](../05_Development/05_developer_guide.md)** - Umfassender technischer Guide
|
||||
2. **[Technical References](../03_Technical_References/)** - Detaillierte API- und Architektur-Dokumentation
|
||||
3. **[GenAI Best Practices](../05_Development/05_genai_best_practices.md)** - Workflow mit LLMs
|
||||
|
||||
### Für Administratoren
|
||||
1. **[Admin Operations](../04_Operations/04_admin_operations.md)** - Installation und Wartung
|
||||
2. **[Server Operations Manual](../04_Operations/04_server_operation_manual.md)** - Server-Betrieb und Disaster Recovery
|
||||
3. **[Troubleshooting Guide](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)** - Häufige Probleme und Lösungen
|
||||
|
||||
### Für Autoren
|
||||
1. **[Knowledge Design](../01_User_Manual/01_knowledge_design.md)** - Content-Regeln und Best Practices
|
||||
2. **[Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)** - Strukturierung für den Digitalen Zwilling
|
||||
3. **[Obsidian Integration](../01_User_Manual/01_obsidian_integration_guide.md)** - Workflow-Optimierung
|
||||
|
||||
---
|
||||
|
||||
## 6. Dokumentations-Status
|
||||
|
||||
**Aktuelle Version:** 2.9.1
|
||||
**Letzte Aktualisierung:** 2025-01-XX
|
||||
**Status:** ✅ Vollständig und aktiv gepflegt
|
||||
|
||||
**Hinweis:** Diese Dokumentation wird kontinuierlich aktualisiert. Bei Fragen oder Verbesserungsvorschlägen bitte im Repository melden.
|
||||
@@ -2,7 +2,7 @@
|
||||
doc_type: glossary
|
||||
audience: all
|
||||
status: active
|
||||
version: 2.8.1
|
||||
version: 2.9.1
|
||||
context: "Zentrales Glossar für Mindnet v2.8. Enthält Definitionen zu Hybrid-Cloud Resilienz, WP-14 Modularisierung, WP-15b Two-Pass Ingestion und Mistral-safe Parsing."
|
||||
---
|
||||
|
||||
@@ -14,7 +14,7 @@ context: "Zentrales Glossar für Mindnet v2.8. Enthält Definitionen zu Hybrid-C
|
||||
|
||||
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit. Verfügt über einen **Status** (stable, draft, system), der das Scoring beeinflusst.
|
||||
* **Chunk:** Ein Textabschnitt einer Note. Die technische Sucheinheit (Vektor).
|
||||
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert.
|
||||
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert. Seit v2.9.1 unterstützt Edges **Section-basierte Links** (`target_section`), sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Abschnitte zeigen.
|
||||
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
||||
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`, `status`).
|
||||
|
||||
@@ -47,4 +47,7 @@ context: "Zentrales Glossar für Mindnet v2.8. Enthält Definitionen zu Hybrid-C
|
||||
* **Two-Pass Workflow (WP-15b):** Optimiertes Ingestion-Verfahren:
|
||||
* **Pass 1 (Pre-Scan):** Schnelles Scannen aller Dateien zur Befüllung des LocalBatchCache.
|
||||
* **Pass 2 (Semantic Processing):** Tiefenverarbeitung (Chunking, Embedding, Validierung) nur für geänderte Dateien.
|
||||
* **Circular Import Registry (WP-14):** Entkopplung von Kern-Logik (wie Textbereinigung) in eine neutrale `registry.py`, um Abhängigkeitsschleifen zwischen Diensten und Ingestion-Utilities zu verhindern.
|
||||
* **Circular Import Registry (WP-14):** Entkopplung von Kern-Logik (wie Textbereinigung) in eine neutrale `registry.py`, um Abhängigkeitsschleifen zwischen Diensten und Ingestion-Utilities zu verhindern.
|
||||
* **Deep-Link / Section-basierter Link:** Ein Link wie `[[Note#Section]]`, der auf einen spezifischen Abschnitt innerhalb einer Note verweist. Seit v2.9.1 wird dieser in `target_id="Note"` und `target_section="Section"` aufgeteilt, um "Phantom-Knoten" zu vermeiden und Multigraph-Support zu ermöglichen.
|
||||
* **Atomic Section Logic (v3.9.9):** Chunking-Verfahren, das Sektions-Überschriften und deren Inhalte atomar in Chunks hält (Pack-and-Carry-Over). Verhindert, dass Überschriften über Chunk-Grenzen hinweg getrennt werden.
|
||||
* **Registry-First Profiling (v2.13.12):** Hierarchische Auflösung des Chunking-Profils: Frontmatter > types.yaml Typ-Config > Global Defaults. Stellt sicher, dass Note-Typen automatisch das korrekte Profil erhalten.
|
||||
@@ -0,0 +1,166 @@
|
||||
---
|
||||
doc_type: quality_assurance
|
||||
audience: all
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Qualitätsprüfung der Dokumentation für alle Rollen: Vollständigkeit, Korrektheit und Anwendbarkeit."
|
||||
---
|
||||
|
||||
# Dokumentations-Qualitätsprüfung
|
||||
|
||||
Diese Checkliste dient zur systematischen Prüfung, ob die Dokumentation alle Fragen jeder Rolle vollständig beantwortet.
|
||||
|
||||
## ✅ Entwickler
|
||||
|
||||
### Setup & Installation
|
||||
- [x] **Lokales Setup:** [Developer Guide](../05_Development/05_developer_guide.md#6-lokales-setup-development)
|
||||
- [x] **Schnellstart:** [Quickstart](00_quickstart.md)
|
||||
- [x] **Hardware-Anforderungen:** [Admin Operations](../04_Operations/04_admin_operations.md#11-voraussetzungen)
|
||||
|
||||
### Architektur & Code
|
||||
- [x] **Modulare Struktur:** [Developer Guide - Architektur](../05_Development/05_developer_guide.md#4-projektstruktur--modul-referenz-deep-dive)
|
||||
- [x] **Design-Patterns:** [Architektur-Patterns](../02_concepts/02_concept_architecture_patterns.md)
|
||||
- [x] **API-Referenz:** [API Reference](../03_Technical_References/03_tech_api_reference.md)
|
||||
- [x] **Datenmodell:** [Data Model](../03_Technical_References/03_tech_data_model.md)
|
||||
|
||||
### Entwicklung & Erweiterung
|
||||
- [x] **Workflow:** [Developer Guide - Workflow](../05_Development/05_developer_guide.md#7-der-entwicklungs-zyklus-workflow)
|
||||
- [x] **Erweiterungs-Guide:** [Teach-the-AI](../05_Development/05_developer_guide.md#8-erweiterungs-guide-teach-the-ai)
|
||||
- [x] **GenAI Best Practices:** [GenAI Best Practices](../05_Development/05_genai_best_practices.md)
|
||||
|
||||
### Testing
|
||||
- [x] **Test-Strategien:** [Testing Guide](../05_Development/05_testing_guide.md)
|
||||
- [x] **Test-Frameworks:** [Testing Guide - Frameworks](../05_Development/05_testing_guide.md#3-test-frameworks--tools)
|
||||
- [x] **Test-Daten:** [Testing Guide - Test-Daten](../05_Development/05_testing_guide.md#2-test-daten--vaults)
|
||||
|
||||
### Debugging & Troubleshooting
|
||||
- [x] **Troubleshooting:** [Developer Guide - Troubleshooting](../05_Development/05_developer_guide.md#10-troubleshooting--one-liners)
|
||||
- [x] **Debug-Tools:** [Testing Guide - Debugging](../05_Development/05_testing_guide.md#7-debugging--diagnose)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Administratoren
|
||||
|
||||
### Installation & Setup
|
||||
- [x] **Installation:** [Admin Operations](../04_Operations/04_admin_operations.md#1-installation--setup)
|
||||
- [x] **Docker Setup:** [Admin Operations - Qdrant](../04_Operations/04_admin_operations.md#12-qdrant-docker)
|
||||
- [x] **Systemd Services:** [Admin Operations - Deployment](../04_Operations/04_admin_operations.md#2-deployment-systemd-services)
|
||||
|
||||
### Betrieb & Wartung
|
||||
- [x] **Monitoring:** [Admin Operations - Wartung](../04_Operations/04_admin_operations.md#3-wartung--monitoring)
|
||||
- [x] **Backup & Restore:** [Admin Operations - Backup](../04_Operations/04_admin_operations.md#4-backup--restore)
|
||||
- [x] **Troubleshooting:** [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||
|
||||
### Server-Betrieb
|
||||
- [x] **Server-Konfiguration:** [Server Operations Manual](../04_Operations/04_server_operation_manual.md)
|
||||
- [x] **Disaster Recovery:** [Server Operations - DR](../04_Operations/04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr)
|
||||
- [x] **Backup-Strategie:** [Server Operations - Backup](../04_Operations/04_server_operation_manual.md#4-backup-strategie-borgmatic)
|
||||
|
||||
### Konfiguration
|
||||
- [x] **ENV-Variablen:** [Configuration Reference](../03_Technical_References/03_tech_configuration.md#1-environment-variablen-env)
|
||||
- [x] **YAML-Configs:** [Configuration Reference - YAML](../03_Technical_References/03_tech_configuration.md#2-typ-registry-typesyaml)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Anwender
|
||||
|
||||
### Erste Schritte
|
||||
- [x] **Schnellstart:** [Quickstart](00_quickstart.md)
|
||||
- [x] **Was ist Mindnet:** [Vision & Strategie](00_vision_and_strategy.md)
|
||||
- [x] **Grundlagen:** [Glossar](00_glossary.md)
|
||||
|
||||
### Nutzung
|
||||
- [x] **Chat-Bedienung:** [Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)
|
||||
- [x] **Graph Explorer:** [Chat Usage Guide - Graph](../01_User_Manual/01_chat_usage_guide.md#22-modus--graph-explorer-cytoscape)
|
||||
- [x] **Editor:** [Chat Usage Guide - Editor](../01_User_Manual/01_chat_usage_guide.md#23-modus--manueller-editor)
|
||||
|
||||
### Content-Erstellung
|
||||
- [x] **Knowledge Design:** [Knowledge Design Manual](../01_User_Manual/01_knowledge_design.md)
|
||||
- [x] **Authoring Guidelines:** [Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)
|
||||
- [x] **Obsidian-Integration:** [Obsidian Integration](../01_User_Manual/01_obsidian_integration_guide.md)
|
||||
|
||||
### Häufige Fragen
|
||||
- [x] **Wie strukturiere ich Notizen?** → [Knowledge Design](../01_User_Manual/01_knowledge_design.md)
|
||||
- [x] **Welche Note-Typen gibt es?** → [Knowledge Design - Typ-Referenz](../01_User_Manual/01_knowledge_design.md#31-typ-referenz--stream-logik)
|
||||
- [x] **Wie verknüpfe ich Notizen?** → [Knowledge Design - Edges](../01_User_Manual/01_knowledge_design.md#4-edges--verlinkung)
|
||||
- [x] **Wie nutze ich den Chat?** → [Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Tester
|
||||
|
||||
### Test-Strategien
|
||||
- [x] **Test-Pyramide:** [Testing Guide - Strategien](../05_Development/05_testing_guide.md#1-test-strategie--ebenen)
|
||||
- [x] **Unit Tests:** [Testing Guide - Unit Tests](../05_Development/05_testing_guide.md#11-unit-tests-pytest)
|
||||
- [x] **Integration Tests:** [Testing Guide - Integration](../05_Development/05_testing_guide.md#12-integration-tests)
|
||||
- [x] **E2E Tests:** [Testing Guide - E2E](../05_Development/05_testing_guide.md#13-e2e--smoke-tests)
|
||||
|
||||
### Test-Frameworks
|
||||
- [x] **Pytest:** [Testing Guide - Frameworks](../05_Development/05_testing_guide.md#31-pytest-unit-tests)
|
||||
- [x] **Unittest:** [Testing Guide - Unittest](../05_Development/05_testing_guide.md#32-unittest-e2e-tests)
|
||||
- [x] **Shell-Skripte:** [Testing Guide - Shell](../05_Development/05_testing_guide.md#33-shell-skripte-e2e-roundtrip)
|
||||
|
||||
### Test-Daten & Tools
|
||||
- [x] **Test-Vault erstellen:** [Testing Guide - Test-Daten](../05_Development/05_testing_guide.md#21-test-vault-erstellen)
|
||||
- [x] **Test-Skripte:** [Developer Guide - Scripts](../05_Development/05_developer_guide.md#44-scripts--tooling-die-admin-toolbox)
|
||||
- [x] **Test-Checkliste:** [Testing Guide - Checkliste](../05_Development/05_testing_guide.md#8-test-checkliste-für-pull-requests)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Deployment
|
||||
|
||||
### Deployment-Prozesse
|
||||
- [x] **Deployment-Guide:** [Deployment Guide](../04_Operations/04_deployment_guide.md)
|
||||
- [x] **CI/CD Pipeline:** [Deployment Guide - CI/CD](../04_Operations/04_deployment_guide.md#9-cicd-pipeline-details)
|
||||
- [x] **Rollout-Strategien:** [Deployment Guide - Rollout](../04_Operations/04_deployment_guide.md#4-rollout-strategien)
|
||||
|
||||
### Versionierung & Releases
|
||||
- [x] **Version-Schema:** [Deployment Guide - Versionierung](../04_Operations/04_deployment_guide.md#51-version-schema)
|
||||
- [x] **Release-Prozess:** [Deployment Guide - Release](../04_Operations/04_deployment_guide.md#52-release-prozess)
|
||||
|
||||
### Rollback & Recovery
|
||||
- [x] **Rollback-Strategien:** [Deployment Guide - Rollback](../04_Operations/04_deployment_guide.md#6-rollback-strategien)
|
||||
- [x] **Disaster Recovery:** [Server Operations - DR](../04_Operations/04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr)
|
||||
|
||||
### Pre/Post-Deployment
|
||||
- [x] **Pre-Deployment Checkliste:** [Deployment Guide - Checkliste](../04_Operations/04_deployment_guide.md#7-pre-deployment-checkliste)
|
||||
- [x] **Post-Deployment Validierung:** [Deployment Guide - Validierung](../04_Operations/04_deployment_guide.md#8-post-deployment-validierung)
|
||||
|
||||
---
|
||||
|
||||
## 📊 Zusammenfassung
|
||||
|
||||
### Vollständigkeit nach Rolle
|
||||
|
||||
| Rolle | Abgedeckte Themen | Status |
|
||||
| :--- | :--- | :--- |
|
||||
| **Entwickler** | Setup, Architektur, Code, Testing, Debugging | ✅ Vollständig |
|
||||
| **Administratoren** | Installation, Betrieb, Wartung, Backup, DR | ✅ Vollständig |
|
||||
| **Anwender** | Nutzung, Content-Erstellung, Workflows | ✅ Vollständig |
|
||||
| **Tester** | Test-Strategien, Frameworks, Tools | ✅ Vollständig |
|
||||
| **Deployment** | CI/CD, Rollout, Versionierung, Rollback | ✅ Vollständig |
|
||||
|
||||
### Neue Dokumente
|
||||
|
||||
1. ✅ `05_testing_guide.md` - Umfassender Test-Guide
|
||||
2. ✅ `04_deployment_guide.md` - Vollständiger Deployment-Guide
|
||||
3. ✅ `02_concept_architecture_patterns.md` - Architektur-Patterns
|
||||
4. ✅ `03_tech_api_reference.md` - API-Referenz
|
||||
5. ✅ `00_quickstart.md` - Schnellstart-Anleitung
|
||||
6. ✅ `README.md` - Dokumentations-Einstiegspunkt
|
||||
|
||||
### Aktualisierte Dokumente
|
||||
|
||||
1. ✅ `00_documentation_map.md` - Alle neuen Dokumente aufgenommen
|
||||
2. ✅ `04_admin_operations.md` - Troubleshooting erweitert
|
||||
3. ✅ `05_developer_guide.md` - Modulare Struktur ergänzt
|
||||
4. ✅ `03_tech_ingestion_pipeline.md` - Background Tasks dokumentiert
|
||||
5. ✅ `03_tech_configuration.md` - Fehlende ENV-Variablen ergänzt
|
||||
6. ✅ `00_vision_and_strategy.md` - Design-Entscheidungen ergänzt
|
||||
|
||||
---
|
||||
|
||||
**Status:** ✅ Alle Rollen vollständig abgedeckt
|
||||
**Letzte Prüfung:** 2025-01-XX
|
||||
**Version:** 2.9.1
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
doc_type: quickstart_guide
|
||||
audience: user, developer, admin
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Schnellstart-Anleitung für neue Benutzer von Mindnet"
|
||||
---
|
||||
|
||||
# Mindnet Schnellstart
|
||||
|
||||
Diese Anleitung hilft dir, in 15 Minuten mit Mindnet loszulegen.
|
||||
|
||||
## 🎯 Was ist Mindnet?
|
||||
|
||||
Mindnet ist ein **persönliches KI-Gedächtnis**, das:
|
||||
- Dein Wissen in Markdown-Notizen speichert
|
||||
- Semantisch verknüpft (Wissensgraph)
|
||||
- Als intelligenter Dialogpartner agiert (RAG-Chat)
|
||||
- **Lokal und privat** läuft (Privacy First)
|
||||
|
||||
## 📋 Voraussetzungen
|
||||
|
||||
- **Python 3.10+** installiert
|
||||
- **Docker** installiert (für Qdrant)
|
||||
- **Ollama** installiert (für lokale LLMs)
|
||||
- Optional: **Obsidian** (für komfortables Schreiben)
|
||||
|
||||
## ⚡ Installation (5 Minuten)
|
||||
|
||||
### Schritt 1: Repository klonen
|
||||
|
||||
```bash
|
||||
git clone <repository-url> mindnet
|
||||
cd mindnet
|
||||
```
|
||||
|
||||
### Schritt 2: Virtuelle Umgebung erstellen
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
```
|
||||
|
||||
### Schritt 3: Abhängigkeiten installieren
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### Schritt 4: Qdrant starten (Docker)
|
||||
|
||||
```bash
|
||||
docker compose up -d qdrant
|
||||
```
|
||||
|
||||
### Schritt 5: Ollama-Modelle laden
|
||||
|
||||
```bash
|
||||
ollama pull phi3:mini
|
||||
ollama pull nomic-embed-text
|
||||
```
|
||||
|
||||
### Schritt 6: Konfiguration anpassen
|
||||
|
||||
Erstelle eine `.env`-Datei im Projektroot:
|
||||
|
||||
```ini
|
||||
QDRANT_URL=http://localhost:6333
|
||||
MINDNET_OLLAMA_URL=http://localhost:11434
|
||||
MINDNET_LLM_MODEL=phi3:mini
|
||||
MINDNET_EMBEDDING_MODEL=nomic-embed-text
|
||||
COLLECTION_PREFIX=mindnet
|
||||
MINDNET_VAULT_ROOT=./vault
|
||||
```
|
||||
|
||||
## 🚀 Erste Schritte (5 Minuten)
|
||||
|
||||
### Schritt 1: Backend starten
|
||||
|
||||
```bash
|
||||
uvicorn app.main:app --reload --port 8001
|
||||
```
|
||||
|
||||
### Schritt 2: Frontend starten (neues Terminal)
|
||||
|
||||
```bash
|
||||
streamlit run app/frontend/ui.py --server.port 8501
|
||||
```
|
||||
|
||||
### Schritt 3: Browser öffnen
|
||||
|
||||
Öffne `http://localhost:8501` im Browser.
|
||||
|
||||
### Schritt 4: Erste Notiz importieren
|
||||
|
||||
Erstelle eine Test-Notiz im `vault/` Ordner:
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: 20250101-test
|
||||
title: Meine erste Notiz
|
||||
type: concept
|
||||
status: active
|
||||
---
|
||||
|
||||
# Meine erste Notiz
|
||||
|
||||
Dies ist eine Test-Notiz für Mindnet.
|
||||
|
||||
[[rel:related_to Mindnet]]
|
||||
```
|
||||
|
||||
Dann importiere sie:
|
||||
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply
|
||||
```
|
||||
|
||||
### Schritt 5: Erste Chat-Anfrage
|
||||
|
||||
Im Browser-Chat eingeben:
|
||||
```
|
||||
Was ist Mindnet?
|
||||
```
|
||||
|
||||
## 📚 Nächste Schritte
|
||||
|
||||
Nach dem Schnellstart empfehle ich:
|
||||
|
||||
1. **[Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)** - Lerne die Chat-Funktionen kennen
|
||||
2. **[Knowledge Design](../01_User_Manual/01_knowledge_design.md)** - Verstehe, wie du Notizen strukturierst
|
||||
3. **[Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)** - Lerne Best Practices für das Schreiben
|
||||
|
||||
## 🆘 Hilfe & Troubleshooting
|
||||
|
||||
**Problem:** Qdrant startet nicht
|
||||
- **Lösung:** Prüfe, ob Docker läuft: `docker ps`
|
||||
|
||||
**Problem:** Ollama-Modell nicht gefunden
|
||||
- **Lösung:** Prüfe mit `ollama list`, ob die Modelle geladen sind
|
||||
|
||||
**Problem:** Import schlägt fehl
|
||||
- **Lösung:** Prüfe die Logs und stelle sicher, dass Qdrant läuft
|
||||
|
||||
Für detaillierte Troubleshooting-Informationen siehe [Admin Operations](../04_Operations/04_admin_operations.md#33-troubleshooting-guide).
|
||||
|
||||
## 🔗 Weitere Ressourcen
|
||||
|
||||
- **[Dokumentationskarte](00_documentation_map.md)** - Übersicht aller Dokumente
|
||||
- **[Glossar](00_glossary.md)** - Wichtige Begriffe erklärt
|
||||
- **[Vision & Strategie](00_vision_and_strategy.md)** - Die Philosophie hinter Mindnet
|
||||
|
||||
---
|
||||
|
||||
**Viel Erfolg mit Mindnet!** 🚀
|
||||
|
||||
@@ -64,4 +64,42 @@ Die folgenden Prinzipien steuern jede technische Entscheidung:
|
||||
Jeder Importlauf und jede Retriever-Anfrage ist logbar.
|
||||
|
||||
10. **Local First & Privacy:**
|
||||
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||
|
||||
11. **Modulare Architektur (WP-14):**
|
||||
Core-Logik ist in spezialisierte Pakete unterteilt (`chunking/`, `database/`, `graph/`, `ingestion/`, `parser/`, `retrieval/`). Dies ermöglicht unabhängige Entwicklung, Testbarkeit und Wartbarkeit.
|
||||
|
||||
12. **Resilienz durch Kaskaden:**
|
||||
System nutzt Provider-Kaskaden (Cloud → Rate-Limit-Handling → Lokaler Fallback) für hohe Verfügbarkeit. Deep Fallback erkennt auch kognitive Blockaden (Silent Refusals).
|
||||
|
||||
---
|
||||
|
||||
## 4. Design-Entscheidungen & Trade-offs
|
||||
|
||||
### 4.1 Qdrant als Vektor-DB
|
||||
**Entscheidung:** Self-hosted Qdrant statt Managed Service (Pinecone/Weaviate)
|
||||
**Gründe:** Privacy First, Open Source, lokale Kontrolle
|
||||
**Trade-off:** Mehr Wartungsaufwand, aber vollständige Datenhoheit
|
||||
|
||||
### 4.2 Hybrid Retrieval
|
||||
**Entscheidung:** Kombination von Vektor-Suche (Semantik) und Graph-Expansion
|
||||
**Gründe:** Bessere Relevanz durch strukturelle Verbindungen
|
||||
**Trade-off:** Höhere Komplexität, aber deutlich bessere Ergebnisse
|
||||
|
||||
### 4.3 Background Tasks statt Queue-System
|
||||
**Entscheidung:** FastAPI Background Tasks statt Redis/RabbitMQ
|
||||
**Gründe:** Einfacher Setup, ausreichend für Single-User
|
||||
**Trade-off:** Keine Persistenz bei Server-Neustart, aber weniger Infrastruktur
|
||||
|
||||
### 4.4 Markdown als Source of Truth
|
||||
**Entscheidung:** Markdown-Dateien sind primär, Datenbank ist Cache
|
||||
**Gründe:** Versionierbarkeit, Editierbarkeit, Unabhängigkeit
|
||||
**Trade-off:** Zwei Datenquellen, aber maximale Flexibilität
|
||||
|
||||
---
|
||||
|
||||
## 5. Weitere Informationen
|
||||
|
||||
- **Architektur-Patterns:** Siehe [Architektur-Patterns](../02_concepts/02_concept_architecture_patterns.md)
|
||||
- **Graph-Logik:** Siehe [Graph-Logik](../02_concepts/02_concept_graph_logic.md)
|
||||
- **KI-Persönlichkeit:** Siehe [KI-Persönlichkeit](../02_concepts/02_concept_ai_personality.md)
|
||||
@@ -11,6 +11,8 @@ context: "Anleitung zur Nutzung der Web-Oberfläche, der Chat-Personas und des G
|
||||
|
||||
**Quellen:** `user_guide.md`
|
||||
|
||||
> 💡 **Tipp für Einsteiger:** Falls du noch nie mit Mindnet gearbeitet hast, starte mit dem [Schnellstart](../00_General/00_quickstart.md) und dem [Knowledge Design Manual](01_knowledge_design.md), um die Grundlagen zu verstehen.
|
||||
|
||||
## 1. Was Mindnet für dich tut
|
||||
|
||||
Mindnet ist ein **assoziatives Gedächtnis** mit Persönlichkeit. Es unterscheidet sich von einer reinen Suche dadurch, dass es **kontextsensitiv** agiert.
|
||||
@@ -123,4 +125,86 @@ Wenn du im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei d
|
||||
* **Exakte Treffer:** Das System erkennt Begriffe wie "KI-Gedächtnis" als Alias für "Mindnet".
|
||||
* **Semantische Treffer:** Das System findet inhaltlich verwandte Notizen.
|
||||
* **Klick auf "➕ Einfügen":** Fügt den Link (z.B. `[[rel:related_to Mindnet]]`) an der Cursor-Position ein.
|
||||
4. **Speichern:** Der Text wird sofort in den Vault geschrieben und indiziert.
|
||||
4. **Speichern:** Der Text wird sofort in den Vault geschrieben und indiziert.
|
||||
|
||||
### 6.3 Weg C: Direktes Schreiben in Obsidian
|
||||
Wenn du Obsidian nutzt, kannst du Notizen direkt im Vault erstellen. Nach dem Speichern in Obsidian:
|
||||
|
||||
1. **Automatischer Import (Cron):** Der stündliche Cron-Job importiert neue/geänderte Dateien automatisch.
|
||||
2. **Manueller Import:** Oder führe manuell aus:
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply
|
||||
```
|
||||
|
||||
**Vorteil:** Du arbeitest in deiner gewohnten Obsidian-Umgebung, Mindnet synchronisiert im Hintergrund.
|
||||
|
||||
---
|
||||
|
||||
## 7. Häufige Anwendungsfälle (Use Cases)
|
||||
|
||||
### 7.1 Entscheidungshilfe suchen
|
||||
**Szenario:** Du stehst vor einer schwierigen Entscheidung.
|
||||
|
||||
**Vorgehen:**
|
||||
1. Stelle eine Frage im Chat: *"Soll ich Tool X nutzen?"*
|
||||
2. Mindnet erkennt `DECISION` Intent
|
||||
3. System lädt deine Werte, Prinzipien und Ziele
|
||||
4. Antwort berücksichtigt deine persönlichen Kriterien
|
||||
|
||||
**Beispiel:** *"Soll ich Notion nutzen?"* → System prüft gegen dein Prinzip "Privacy First" und rät ab.
|
||||
|
||||
### 7.2 Erfahrungen dokumentieren
|
||||
**Szenario:** Du willst ein prägendes Erlebnis festhalten.
|
||||
|
||||
**Vorgehen:**
|
||||
1. Chat: *"Neue Erfahrung: Streit am Recyclinghof"*
|
||||
2. System erstellt strukturierte Notiz mit Feldern:
|
||||
- Situation
|
||||
- Reaktion
|
||||
- Learning
|
||||
3. Verknüpfe mit relevanten Rollen: `[[rel:supports Meine Rollenlandkarte 2025#Vater]]`
|
||||
|
||||
### 7.3 Wissen im Graph erkunden
|
||||
**Szenario:** Du willst verstehen, wie Konzepte zusammenhängen.
|
||||
|
||||
**Vorgehen:**
|
||||
1. Wechsle zum **Graph Explorer**
|
||||
2. Suche nach einem Knoten (z.B. "Projekt Alpha")
|
||||
3. Klicke auf "🎯 Als Zentrum setzen"
|
||||
4. Erkunde die Nachbarschaft (Abhängigkeiten, Entscheidungen, ähnliche Projekte)
|
||||
|
||||
### 7.4 Bestehende Notizen verbessern
|
||||
**Szenario:** Eine Notiz ist unvollständig oder unvernetzt.
|
||||
|
||||
**Vorgehen:**
|
||||
1. Öffne die Notiz im **Manuellen Editor**
|
||||
2. Nutze **Intelligence-Tab** für Link-Vorschläge
|
||||
3. Füge semantische Links hinzu: `[[rel:based_on Wert X]]`
|
||||
4. Speichern → System indiziert neu
|
||||
|
||||
---
|
||||
|
||||
## 8. Tipps & Tricks
|
||||
|
||||
### 8.1 Intent-Steuerung
|
||||
- **Frage mit "?":** Löst RAG-Modus aus (Wissen abrufen)
|
||||
- **Aussage ohne "?":** Löst Interview-Modus aus (Wissen speichern)
|
||||
- **Emotionale Wörter:** Aktivieren Empathie-Persona ("Ich fühle...", "Ich bin frustriert...")
|
||||
|
||||
### 8.2 Graph-Navigation
|
||||
- **URL-Persistenz:** Graph-Einstellungen werden in der URL gespeichert → Lesezeichen für spezifische Ansichten
|
||||
- **Deep-Links:** Verlinke präzise Abschnitte: `[[Note#Abschnitt]]` statt nur `[[Note]]`
|
||||
|
||||
### 8.3 Feedback nutzen
|
||||
- **Regelmäßiges Feedback:** Macht das System schlauer
|
||||
- **Granulares Feedback:** Bewerte einzelne Quellen, nicht nur die Gesamtantwort
|
||||
- **Konsequenz:** System lernt deine Präferenzen
|
||||
|
||||
---
|
||||
|
||||
## 9. Weitere Informationen
|
||||
|
||||
- **Knowledge Design:** Siehe [Knowledge Design Manual](01_knowledge_design.md)
|
||||
- **Authoring Guidelines:** Siehe [Authoring Guidelines](01_authoring_guidelines.md)
|
||||
- **Obsidian Integration:** Siehe [Obsidian Integration Guide](01_obsidian_integration_guide.md)
|
||||
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||
@@ -3,7 +3,7 @@ doc_type: user_manual
|
||||
audience: user, author
|
||||
scope: vault, markdown, schema
|
||||
status: active
|
||||
version: 2.8.0
|
||||
version: 2.9.1
|
||||
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
||||
---
|
||||
|
||||
@@ -208,6 +208,12 @@ Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Ding
|
||||
> "Daher [[rel:depends_on Qdrant]]."
|
||||
> "Dieses Konzept ist [[rel:similar_to Pinecone]]."
|
||||
|
||||
**Deep-Links zu Abschnitten (v2.9.1):**
|
||||
Du kannst auch auf spezifische Abschnitte innerhalb einer Note verlinken:
|
||||
> "Siehe [[rel:based_on Mein Leitbild#P3 – Disziplin]]."
|
||||
|
||||
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.
|
||||
|
||||
**Gültige Relationen:**
|
||||
* `depends_on`: Hängt ab von / Benötigt.
|
||||
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||
@@ -226,6 +232,12 @@ Für Zusammenfassungen am Ende einer Notiz, oder eines Absatzes:
|
||||
> [[AI Agents]]
|
||||
```
|
||||
|
||||
**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).
|
||||
|
||||
**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).
|
||||
|
||||
### 4.3 Implizite Bidirektionalität (Edger-Logik) [NEU] [PRÜFEN!]
|
||||
In Mindnet musst du Kanten **nicht** manuell in beide Richtungen pflegen. Der **Edger** übernimmt die Paarbildung automatisch im Hintergrund.
|
||||
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
---
|
||||
doc_type: concept
|
||||
audience: architect, developer
|
||||
scope: architecture, design_patterns, modularization
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Architektur-Patterns, Design-Entscheidungen und modulare Struktur von Mindnet. Basis für Verständnis und Erweiterungen."
|
||||
---
|
||||
|
||||
# Architektur-Patterns & Design-Entscheidungen
|
||||
|
||||
Dieses Dokument beschreibt die zentralen Architektur-Patterns und Design-Entscheidungen, die Mindnet prägen. Es dient als Referenz für Entwickler und Architekten, um das System zu verstehen und konsistent zu erweitern.
|
||||
|
||||
## 1. Kern-Paradigmen
|
||||
|
||||
### 1.1 Filesystem First (Source of Truth)
|
||||
|
||||
**Prinzip:** Markdown-Dateien im Vault sind die einzige Quelle der Wahrheit. Die Datenbank (Qdrant) ist ein abgeleiteter Index.
|
||||
|
||||
**Implikationen:**
|
||||
- Dateien werden immer direkt von der Festplatte gelesen (z.B. im Editor)
|
||||
- Datenbank-Inhalte können aus Markdown rekonstruiert werden
|
||||
- Änderungen erfolgen primär im Vault, nicht in der DB
|
||||
- Die Datenbank ist ein Cache, kein primärer Speicher
|
||||
|
||||
**Code-Beispiele:**
|
||||
- `ui_callbacks.py`: Liest Dateien direkt von Disk
|
||||
- `ingestion_processor.py`: Schreibt zuerst auf Disk, dann in DB
|
||||
|
||||
### 1.2 Late Binding (Späte Semantik)
|
||||
|
||||
**Prinzip:** Struktur und Interpretation werden in Konfigurationen definiert, nicht im Code.
|
||||
|
||||
**Implikationen:**
|
||||
- Neue Note-Typen werden in `types.yaml` definiert, nicht im Code
|
||||
- Prompt-Templates sind in `prompts.yaml` konfigurierbar
|
||||
- Edge-Typen werden in `edge_vocabulary.md` verwaltet
|
||||
- Die "Persönlichkeit" ist Config, kein Code
|
||||
|
||||
**Vorteile:**
|
||||
- Erweiterbarkeit ohne Code-Änderungen
|
||||
- A/B-Testing von Prompt-Strategien
|
||||
- Anpassung an verschiedene Use-Cases
|
||||
|
||||
### 1.3 Virtual Schema Layer
|
||||
|
||||
**Prinzip:** Markdown-Dateien benötigen nur minimale Frontmatter-Angaben. Komplexität wird zur Laufzeit injiziert.
|
||||
|
||||
**Beispiel:**
|
||||
```yaml
|
||||
# Minimal im Frontmatter
|
||||
---
|
||||
id: 20250101-test
|
||||
title: Test
|
||||
type: project
|
||||
---
|
||||
|
||||
# Im Code wird zur Laufzeit ergänzt:
|
||||
# - chunking_profile aus types.yaml
|
||||
# - retriever_weight aus types.yaml
|
||||
# - edge_defaults aus types.yaml
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Robuste Markdown-Dateien (weniger Breaking Changes)
|
||||
- Zentrale Verwaltung von Logik
|
||||
- Einfache Migration zwischen Versionen
|
||||
|
||||
---
|
||||
|
||||
## 2. Modulare Architektur (WP-14)
|
||||
|
||||
### 2.1 Paket-Struktur
|
||||
|
||||
Seit WP-14 ist die Core-Logik in spezialisierte Pakete unterteilt:
|
||||
|
||||
```
|
||||
app/core/
|
||||
├── chunking/ # Text-Segmentierung
|
||||
│ ├── chunking_strategies.py # Sliding/Heading-Strategien
|
||||
│ ├── chunking_processor.py # Orchestrierung
|
||||
│ └── chunking_propagation.py # Edge-Vererbung
|
||||
├── database/ # Qdrant-Infrastruktur
|
||||
│ ├── qdrant.py # Client & Config
|
||||
│ └── qdrant_points.py # Point-Mapping
|
||||
├── graph/ # Graph-Logik
|
||||
│ ├── graph_subgraph.py # Expansion
|
||||
│ └── graph_weights.py # Scoring
|
||||
├── ingestion/ # Import-Pipeline
|
||||
│ ├── ingestion_processor.py # Two-Pass Workflow
|
||||
│ └── ingestion_validation.py # Mistral-safe Parsing
|
||||
├── parser/ # Markdown-Parsing
|
||||
│ ├── parsing_markdown.py # Frontmatter/Body
|
||||
│ └── parsing_scanner.py # File-Scan
|
||||
└── retrieval/ # Suche & Scoring
|
||||
├── retriever.py # Orchestrator
|
||||
└── retriever_scoring.py # Mathematik
|
||||
```
|
||||
|
||||
### 2.2 Design-Pattern: Proxy-Adapter (Abwärtskompatibilität)
|
||||
|
||||
**Problem:** Nach WP-14 Modularisierung müssen alte Import-Pfade weiter funktionieren.
|
||||
|
||||
**Lösung:** Proxy-Module leiten Anfragen an neue Pakete weiter.
|
||||
|
||||
**Beispiel:**
|
||||
```python
|
||||
# app/core/retriever.py (Proxy)
|
||||
from .retrieval.retriever import (
|
||||
Retriever, hybrid_retrieve, semantic_retrieve
|
||||
)
|
||||
__all__ = ["Retriever", "hybrid_retrieve", "semantic_retrieve"]
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Keine Breaking Changes für bestehenden Code
|
||||
- Graduelle Migration möglich
|
||||
- Alte Scripts funktionieren weiter
|
||||
|
||||
### 2.3 Design-Pattern: Singleton (Edge Registry)
|
||||
|
||||
**Problem:** Edge Registry muss konsistent über alle Services sein.
|
||||
|
||||
**Lösung:** Singleton-Pattern mit Lazy Loading.
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# app/services/edge_registry.py
|
||||
class EdgeRegistry:
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Einheitliche Validierung
|
||||
- Keine Duplikation von Vokabular-Daten
|
||||
- Thread-safe Initialisierung
|
||||
|
||||
---
|
||||
|
||||
## 3. Asynchrone Verarbeitung
|
||||
|
||||
### 3.1 Background Tasks Pattern
|
||||
|
||||
**Problem:** Ingestion kann lange dauern (LLM-Calls, Embeddings). Blockiert API nicht.
|
||||
|
||||
**Lösung:** FastAPI Background Tasks für non-blocking Verarbeitung.
|
||||
|
||||
**Flow:**
|
||||
1. API empfängt Request (`/ingest/save`)
|
||||
2. Datei wird sofort auf Disk geschrieben
|
||||
3. API antwortet mit `status: "queued"`
|
||||
4. Background Task startet Ingestion asynchron
|
||||
5. User kann weiterarbeiten
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
@router.post("/save")
|
||||
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||
# Sofortige Persistenz
|
||||
write_to_disk(req.markdown_content)
|
||||
|
||||
# Async Processing
|
||||
background_tasks.add_task(run_ingestion_task, ...)
|
||||
|
||||
return SaveResponse(status="queued", ...)
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Keine Timeouts bei großen Dateien
|
||||
- Bessere User Experience
|
||||
- System bleibt responsiv
|
||||
|
||||
### 3.2 Traffic Control (Semaphore Pattern)
|
||||
|
||||
**Problem:** Parallele LLM-Calls können System überlasten.
|
||||
|
||||
**Lösung:** Semaphore begrenzt parallele Hintergrund-Tasks.
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# app/services/llm_service.py
|
||||
background_semaphore = asyncio.Semaphore(
|
||||
settings.BACKGROUND_LIMIT # Default: 2
|
||||
)
|
||||
|
||||
async def generate(...):
|
||||
if priority == "background":
|
||||
async with background_semaphore:
|
||||
return await _call_llm(...)
|
||||
else: # realtime
|
||||
return await _call_llm(...) # Keine Limitierung
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Schutz vor API-Quoten-Überschreitung
|
||||
- Stabiler Betrieb bei hoher Last
|
||||
- Priorisierung von Echtzeit-Anfragen
|
||||
|
||||
---
|
||||
|
||||
## 4. Resilienz-Patterns
|
||||
|
||||
### 4.1 Provider-Kaskade (Fallback-Kette)
|
||||
|
||||
**Problem:** Cloud-Provider können ausfallen oder Quoten überschreiten.
|
||||
|
||||
**Lösung:** Dreistufige Kaskade mit intelligentem Fallback.
|
||||
|
||||
**Stufen:**
|
||||
1. **Cloud (OpenRouter/Gemini):** Schnell, aber abhängig von Provider
|
||||
2. **Rate-Limit-Handling:** Automatische Retries bei HTTP 429
|
||||
3. **Lokaler Fallback (Ollama):** Langsam, aber immer verfügbar
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# app/services/llm_service.py
|
||||
async def generate(...):
|
||||
try:
|
||||
return await _call_cloud(...)
|
||||
except RateLimitError:
|
||||
await asyncio.sleep(LLM_RATE_LIMIT_WAIT)
|
||||
return await _call_cloud(...) # Retry
|
||||
except Exception:
|
||||
return await _call_ollama(...) # Fallback
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Hohe Verfügbarkeit
|
||||
- Kostenoptimierung (Cloud für Speed, Lokal für Fallback)
|
||||
- Resilienz gegen Provider-Ausfälle
|
||||
|
||||
### 4.2 Deep Fallback (Kognitiver Fallback)
|
||||
|
||||
**Problem:** Cloud liefert technisch erfolgreiche, aber inhaltlich leere Antworten (Silent Refusal).
|
||||
|
||||
**Lösung:** Validierung der Antwort-Qualität, nicht nur HTTP-Status.
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
response = await _call_cloud(...)
|
||||
if is_valid_json(response):
|
||||
return response
|
||||
else:
|
||||
# Deep Fallback: Cloud hat blockiert, lokaler Fallback
|
||||
return await _call_ollama(...)
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Erkennung von Policy-Violations
|
||||
- Datenintegrität trotz Cloud-Filter
|
||||
- Lokale Souveränität
|
||||
|
||||
---
|
||||
|
||||
## 5. Datenfluss-Patterns
|
||||
|
||||
### 5.1 Two-Pass Workflow (WP-15b)
|
||||
|
||||
**Problem:** Smart Edge Validation benötigt globalen Kontext (alle Notizen).
|
||||
|
||||
**Lösung:** Zwei-Phasen-Import mit Pre-Scan.
|
||||
|
||||
**Pass 1: Pre-Scan**
|
||||
- Schnelles Scannen aller Dateien
|
||||
- Aufbau von `LocalBatchCache` (IDs, Titel, Summaries)
|
||||
- Keine LLM-Calls
|
||||
|
||||
**Pass 2: Semantic Processing**
|
||||
- Nur für geänderte Dateien
|
||||
- Binäre Validierung gegen Cache
|
||||
- Effiziente Nutzung von LLM-Quoten
|
||||
|
||||
**Vorteile:**
|
||||
- Reduktion von LLM-Calls (nur Validierung, keine Extraktion)
|
||||
- Konsistente Validierung (globaler Kontext)
|
||||
- Schnellerer Import
|
||||
|
||||
### 5.2 Idempotenz-Pattern
|
||||
|
||||
**Prinzip:** Mehrfache Imports derselben Datei führen zum gleichen Ergebnis.
|
||||
|
||||
**Mechanismen:**
|
||||
- **Deterministische IDs:** UUIDv5 basierend auf Datei-Inhalt
|
||||
- **Hash-basierte Change Detection:** Multi-Hash für `body` und `full`
|
||||
- **Deduplizierung:** Kanten werden anhand Identität erkannt
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# Deterministische ID
|
||||
note_id = uuid.uuid5(NAMESPACE_URL, f"{file_path}#{content_hash}")
|
||||
|
||||
# Change Detection
|
||||
if current_hash == stored_hash:
|
||||
skip_processing() # Idempotent
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Sicherheit bei Re-Imports
|
||||
- Keine Duplikate
|
||||
- Konsistente Datenbank
|
||||
|
||||
---
|
||||
|
||||
## 6. Frontend-Patterns
|
||||
|
||||
### 6.1 Active Inspector Pattern
|
||||
|
||||
**Problem:** Graph-Re-Renders bei Knoten-Selektion führen zu Flackern.
|
||||
|
||||
**Lösung:** CSS-Klassen statt State-Änderungen für Selektion.
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# ui_graph_cytoscape.py
|
||||
stylesheet = [
|
||||
{
|
||||
"selector": ".inspected",
|
||||
"style": {"border-width": 6, "border-color": "#FFC300"}
|
||||
}
|
||||
]
|
||||
# Selektion ändert nur CSS-Klasse, nicht React-Key
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Stabiles UI (kein Re-Render)
|
||||
- Bessere Performance
|
||||
- Smooth User Experience
|
||||
|
||||
### 6.2 Resurrection Pattern
|
||||
|
||||
**Problem:** Streamlit vergisst Eingaben bei Re-Runs.
|
||||
|
||||
**Lösung:** Aggressive Synchronisation in `session_state`.
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
# ui_editor.py
|
||||
if widget_key not in st.session_state:
|
||||
st.session_state[widget_key] = restore_from_data_key()
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Texteingaben überleben Tab-Wechsel
|
||||
- Keine Datenverluste
|
||||
- Bessere UX
|
||||
|
||||
---
|
||||
|
||||
## 7. Erweiterbarkeit: "Teach-the-AI" Paradigma
|
||||
|
||||
Mindnet lernt durch **Konfiguration**, nicht durch Training.
|
||||
|
||||
### 7.1 Drei-Ebenen-Erweiterung
|
||||
|
||||
**1. Daten-Ebene (`types.yaml`):**
|
||||
```yaml
|
||||
risk:
|
||||
retriever_weight: 0.90
|
||||
edge_defaults: ["blocks"]
|
||||
```
|
||||
|
||||
**2. Strategie-Ebene (`decision_engine.yaml`):**
|
||||
```yaml
|
||||
DECISION:
|
||||
inject_types: ["value", "risk"]
|
||||
```
|
||||
|
||||
**3. Kognitive Ebene (`prompts.yaml`):**
|
||||
```yaml
|
||||
risk_definition:
|
||||
ollama: "Ein Risiko ist eine potenzielle Gefahr..."
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Keine Code-Änderungen nötig
|
||||
- Schnelle Iteration
|
||||
- A/B-Testing möglich
|
||||
|
||||
---
|
||||
|
||||
## 8. Design-Entscheidungen & Trade-offs
|
||||
|
||||
### 8.1 Qdrant als Vektor-DB
|
||||
|
||||
**Entscheidung:** Qdrant statt Pinecone/Weaviate
|
||||
|
||||
**Gründe:**
|
||||
- Self-hosted (Privacy First)
|
||||
- Open Source
|
||||
- Gute Performance bei lokaler Installation
|
||||
|
||||
**Trade-off:** Mehr Wartungsaufwand als Managed Service
|
||||
|
||||
### 8.2 Hybrid Retrieval (Semantik + Graph)
|
||||
|
||||
**Entscheidung:** Kombination von Vektor-Suche und Graph-Expansion
|
||||
|
||||
**Gründe:**
|
||||
- Semantik findet ähnliche Inhalte
|
||||
- Graph findet strukturelle Verbindungen
|
||||
- Kombination liefert bessere Relevanz
|
||||
|
||||
**Trade-off:** Höhere Komplexität, mehr Berechnungsaufwand
|
||||
|
||||
### 8.3 Background Tasks statt Queue-System
|
||||
|
||||
**Entscheidung:** FastAPI Background Tasks statt Redis/RabbitMQ
|
||||
|
||||
**Gründe:**
|
||||
- Einfacher Setup (keine zusätzliche Infrastruktur)
|
||||
- Ausreichend für Single-User-Szenario
|
||||
- Weniger Moving Parts
|
||||
|
||||
**Trade-off:** Keine Persistenz bei Server-Neustart (Tasks gehen verloren)
|
||||
|
||||
---
|
||||
|
||||
## 9. Konsistenz-Garantien
|
||||
|
||||
### 9.1 Deterministische IDs
|
||||
|
||||
**Prinzip:** UUIDv5 basierend auf Datei-Inhalt
|
||||
|
||||
**Vorteile:**
|
||||
- Reproduzierbare IDs
|
||||
- Keine Duplikate bei Re-Import
|
||||
- Graph ist aus Markdown rekonstruierbar
|
||||
|
||||
### 9.2 Provenance-Hierarchie
|
||||
|
||||
**Prinzip:** Kanten haben Qualitätsstufen (explicit > smart > rule)
|
||||
|
||||
**Vorteile:**
|
||||
- Menschliche Intention hat Vorrang
|
||||
- System-Heuristiken können überschrieben werden
|
||||
- Transparente Gewichtung
|
||||
|
||||
---
|
||||
|
||||
## 10. Weitere Informationen
|
||||
|
||||
- **Vision & Strategie:** Siehe [Vision & Strategie](../00_General/00_vision_and_strategy.md)
|
||||
- **Graph-Logik:** Siehe [Graph-Logik](02_concept_graph_logic.md)
|
||||
- **KI-Persönlichkeit:** Siehe [KI-Persönlichkeit](02_concept_ai_personality.md)
|
||||
- **Developer Guide:** Siehe [Developer Guide](../05_Development/05_developer_guide.md)
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2025-01-XX
|
||||
**Version:** 2.9.1
|
||||
|
||||
@@ -3,7 +3,7 @@ doc_type: concept
|
||||
audience: architect, product_owner
|
||||
scope: graph, logic, provenance
|
||||
status: active
|
||||
version: 2.7.0
|
||||
version: 2.9.1
|
||||
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance, Matrix-Logik und WP-22 Scoring-Prinzipien."
|
||||
---
|
||||
|
||||
@@ -118,8 +118,30 @@ Der Intent-Router injiziert spezifische Multiplikatoren für kanonische Typen:
|
||||
|
||||
---
|
||||
|
||||
## 6. Idempotenz & Konsistenz
|
||||
## 6. Section-basierte Links & Multigraph-Support
|
||||
|
||||
Seit v2.9.1 unterstützt Mindnet **Deep-Links** zu spezifischen Abschnitten innerhalb einer Note.
|
||||
|
||||
### 6.1 Link-Parsing
|
||||
Links wie `[[Note#Section]]` werden in zwei Komponenten aufgeteilt:
|
||||
* **`target_id`:** Enthält nur den Note-Namen (z.B. "Mein Leitbild")
|
||||
* **`target_section`:** Enthält den Abschnitts-Namen (z.B. "P3 – Disziplin")
|
||||
|
||||
**Vorteil:** Verhindert "Phantom-Knoten", die durch das Einbeziehen des Anchors in die `target_id` entstanden wären.
|
||||
|
||||
### 6.2 Multigraph-Support
|
||||
Die Edge-ID enthält nun einen `variant`-Parameter (die Section), sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Sections zeigen:
|
||||
* `[[Note#Section1]]` → Edge-ID: `src->tgt:kind@Section1`
|
||||
* `[[Note#Section2]]` → Edge-ID: `src->tgt:kind@Section2`
|
||||
|
||||
### 6.3 Semantische Deduplizierung
|
||||
Die Deduplizierung basiert auf dem `src->tgt:kind@sec` Key, um sicherzustellen, dass identische Links (gleiche Quelle, Ziel, Typ und Section) nicht mehrfach erstellt werden.
|
||||
|
||||
---
|
||||
|
||||
## 7. Idempotenz & Konsistenz
|
||||
|
||||
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
||||
* **Stabile IDs:** Deterministische IDs verhindern Duplikate bei Re-Imports.
|
||||
* **Deduplizierung:** Kanten werden anhand ihrer Identität erkannt. Die "stärkere" Provenance gewinnt.
|
||||
* **Deduplizierung:** Kanten werden anhand ihrer Identität (inkl. Section) erkannt. Die "stärkere" Provenance gewinnt.
|
||||
* **Format-agnostische Erkennung:** Kanten werden unabhängig vom Format (Inline, Callout, Wikilink) erkannt, um Dopplungen zu vermeiden.
|
||||
@@ -0,0 +1,438 @@
|
||||
---
|
||||
doc_type: technical_reference
|
||||
audience: developer, integrator
|
||||
scope: api, endpoints, integration
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Vollständige API-Referenz für alle Mindnet-Endpunkte. Basis für Integration und Entwicklung."
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
Diese Dokumentation beschreibt alle verfügbaren API-Endpunkte von Mindnet. Die API basiert auf FastAPI und nutzt automatische OpenAPI-Dokumentation (verfügbar unter `/docs`).
|
||||
|
||||
## Basis-URL
|
||||
|
||||
```
|
||||
http://localhost:8001 # Production
|
||||
http://localhost:8002 # Development
|
||||
```
|
||||
|
||||
## Health Check
|
||||
|
||||
### `GET /healthz`
|
||||
|
||||
Prüft den Status der API und der Verbindung zu Qdrant.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"qdrant": "http://localhost:6333",
|
||||
"prefix": "mindnet"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Query Endpoints
|
||||
|
||||
### `POST /query`
|
||||
|
||||
Führt eine hybride oder semantische Suche im Wissensgraph durch.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"query": "Was ist Mindnet?",
|
||||
"mode": "hybrid", // "hybrid" oder "semantic"
|
||||
"top_k": 10,
|
||||
"expand_depth": 1,
|
||||
"explain": true
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"query_id": "uuid-v4",
|
||||
"hits": [
|
||||
{
|
||||
"chunk_id": "uuid",
|
||||
"note_id": "uuid",
|
||||
"text": "Auszug...",
|
||||
"score": 0.85,
|
||||
"explanation": {
|
||||
"reasons": [...]
|
||||
}
|
||||
}
|
||||
],
|
||||
"stats": {
|
||||
"total_hits": 10,
|
||||
"query_time_ms": 45
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Hinweis:** Das Feedback-Logging erfolgt asynchron im Hintergrund (Background Tasks).
|
||||
|
||||
---
|
||||
|
||||
## Chat Endpoints
|
||||
|
||||
### `POST /chat/`
|
||||
|
||||
Hauptendpunkt für RAG-Chat und Interview-Modus. Unterstützt Streaming.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"message": "Was ist Mindnet?",
|
||||
"history": [], // Optional: Chat-Verlauf
|
||||
"stream": true // Optional: SSE-Streaming
|
||||
}
|
||||
```
|
||||
|
||||
**Response (Non-Streaming):**
|
||||
```json
|
||||
{
|
||||
"intent": "FACT",
|
||||
"response": "Mindnet ist ein persönliches KI-Gedächtnis...",
|
||||
"sources": [...],
|
||||
"query_id": "uuid"
|
||||
}
|
||||
```
|
||||
|
||||
**Response (Streaming):**
|
||||
Server-Sent Events (SSE) mit Chunks der Antwort.
|
||||
|
||||
**Intent-Typen:**
|
||||
- `FACT`: Wissensabfrage
|
||||
- `DECISION`: Entscheidungsfrage
|
||||
- `EMPATHY`: Emotionale Anfrage
|
||||
- `INTERVIEW`: Wissen erfassen
|
||||
|
||||
---
|
||||
|
||||
## Graph Endpoints
|
||||
|
||||
### `GET /graph/{note_id}`
|
||||
|
||||
Lädt den Subgraphen um eine Note herum.
|
||||
|
||||
**Query Parameters:**
|
||||
- `depth` (int, default: 1): Tiefe der Graph-Expansion
|
||||
- `edge_types` (List[str], optional): Filter für Kanten-Typen
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"center_note_id": "uuid",
|
||||
"nodes": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"type": "project",
|
||||
"title": "Projekt Alpha",
|
||||
"tags": ["ki"],
|
||||
"in_degree": 5,
|
||||
"out_degree": 3
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
{
|
||||
"id": "uuid->uuid:depends_on",
|
||||
"kind": "depends_on",
|
||||
"source": "uuid",
|
||||
"target": "uuid",
|
||||
"target_section": "P3 – Disziplin", // Optional: Abschnitts-Name bei Deep-Links
|
||||
"weight": 1.4,
|
||||
"direction": "out",
|
||||
"provenance": "explicit",
|
||||
"confidence": 1.0
|
||||
}
|
||||
],
|
||||
"stats": {
|
||||
"node_count": 10,
|
||||
"edge_count": 15
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ingest Endpoints
|
||||
|
||||
### `POST /ingest/analyze`
|
||||
|
||||
Analysiert einen Text-Draft und liefert Link-Vorschläge (Intelligence-Feature).
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"text": "Markdown-Text...",
|
||||
"type": "concept" // Optional: Notiz-Typ
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"suggestions": [
|
||||
{
|
||||
"text": "Mindnet",
|
||||
"type": "exact_match",
|
||||
"note_id": "uuid",
|
||||
"confidence": 0.95
|
||||
},
|
||||
{
|
||||
"text": "KI-Gedächtnis",
|
||||
"type": "semantic",
|
||||
"note_id": "uuid",
|
||||
"confidence": 0.82
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `POST /ingest/save`
|
||||
|
||||
Speichert eine Notiz und startet die Ingestion im Hintergrund (WP-14: Background Tasks).
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"markdown_content": "---\nid: ...\n---\n# Titel\n...",
|
||||
"filename": "meine-notiz.md", // Optional
|
||||
"folder": "00_Inbox" // Optional, default: "00_Inbox"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "queued",
|
||||
"file_path": "00_Inbox/meine-notiz.md",
|
||||
"note_id": "pending",
|
||||
"message": "Speicherung & Hybrid-KI-Analyse (WP-20) im Hintergrund gestartet.",
|
||||
"stats": {
|
||||
"chunks": -1, // -1 = Async Processing
|
||||
"edges": -1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Wichtig:**
|
||||
- Die Datei wird sofort auf der Festplatte gespeichert
|
||||
- Die Ingestion (Chunking, Embedding, Smart Edges) läuft asynchron im Hintergrund
|
||||
- Dies verhindert Timeouts bei großen Dateien oder langsamen LLM-Calls
|
||||
|
||||
---
|
||||
|
||||
## Feedback Endpoints
|
||||
|
||||
### `POST /feedback`
|
||||
|
||||
Nimmt explizites User-Feedback entgegen (WP-04c).
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"query_id": "uuid",
|
||||
"rating": 5, // 1-5 Sterne
|
||||
"feedback_type": "global", // "global" oder "granular"
|
||||
"chunk_id": "uuid" // Optional für granular feedback
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "recorded",
|
||||
"query_id": "uuid"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tools Endpoints
|
||||
|
||||
### `GET /tools/ollama`
|
||||
|
||||
Liefert JSON-Schemas für die Integration als Tools in externe Agenten (Ollama, OpenAI, etc.).
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "mindnet_query",
|
||||
"description": "Hybrid-Retrieval über mindnet (Semantik + Edges).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "Freitext-Query"
|
||||
},
|
||||
"top_k": {
|
||||
"type": "integer",
|
||||
"default": 10,
|
||||
"minimum": 1,
|
||||
"maximum": 50
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "mindnet_subgraph",
|
||||
"description": "Gibt die Nachbarschaft (Edges) einer Note/Seed-ID zurück.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"note_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"depth": {
|
||||
"type": "integer",
|
||||
"default": 1,
|
||||
"minimum": 0,
|
||||
"maximum": 3
|
||||
}
|
||||
},
|
||||
"required": ["note_id"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Verwendung:** Diese Schemas können direkt in Ollama-Function-Calling oder OpenAI-Tools integriert werden.
|
||||
|
||||
---
|
||||
|
||||
## Admin Endpoints
|
||||
|
||||
### `GET /admin/stats`
|
||||
|
||||
Liefert Statistiken über die Qdrant-Collections und die aktuelle Konfiguration.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"collections": {
|
||||
"notes": {
|
||||
"name": "mindnet_notes",
|
||||
"count": 150
|
||||
},
|
||||
"chunks": {
|
||||
"name": "mindnet_chunks",
|
||||
"count": 1250
|
||||
},
|
||||
"edges": {
|
||||
"name": "mindnet_edges",
|
||||
"count": 3200
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"qdrant": "http://localhost:6333",
|
||||
"prefix": "mindnet",
|
||||
"vector_size": 768,
|
||||
"distance": "Cosine",
|
||||
"retriever": {
|
||||
"w_sem": 0.70,
|
||||
"w_edge": 0.25,
|
||||
"w_cent": 0.05,
|
||||
"top_k": 10,
|
||||
"expand_depth": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Hinweis:** Dieser Endpunkt ist optional und kann deaktiviert sein, wenn der `admin`-Router nicht geladen wird.
|
||||
|
||||
---
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
Alle Endpunkte verwenden standardisierte HTTP-Status-Codes:
|
||||
|
||||
- `200 OK`: Erfolgreiche Anfrage
|
||||
- `201 Created`: Ressource erfolgreich erstellt
|
||||
- `400 Bad Request`: Ungültige Anfrage (z.B. fehlende Parameter)
|
||||
- `500 Internal Server Error`: Server-Fehler
|
||||
|
||||
**Fehler-Response-Format:**
|
||||
```json
|
||||
{
|
||||
"detail": "Fehlerbeschreibung"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Rate Limiting & Timeouts
|
||||
|
||||
- **Chat-Endpunkte:** Keine Retries (max_retries=0) für schnelle Fallback-Kaskade
|
||||
- **Ingest-Endpunkte:** Background Tasks verhindern Timeouts
|
||||
- **Query-Endpunkte:** Standard-Timeout konfigurierbar via `MINDNET_API_TIMEOUT`
|
||||
|
||||
---
|
||||
|
||||
## OpenAPI Dokumentation
|
||||
|
||||
Die vollständige interaktive API-Dokumentation ist verfügbar unter:
|
||||
- Swagger UI: `http://localhost:8001/docs`
|
||||
- ReDoc: `http://localhost:8001/redoc`
|
||||
- OpenAPI JSON: `http://localhost:8001/openapi.json`
|
||||
|
||||
---
|
||||
|
||||
## Integration Beispiele
|
||||
|
||||
### Python (requests)
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
# Query
|
||||
response = requests.post(
|
||||
"http://localhost:8001/query",
|
||||
json={"query": "Was ist Mindnet?", "top_k": 5}
|
||||
)
|
||||
print(response.json())
|
||||
|
||||
# Chat
|
||||
response = requests.post(
|
||||
"http://localhost:8001/chat/",
|
||||
json={"message": "Erkläre mir Mindnet"}
|
||||
)
|
||||
print(response.json())
|
||||
```
|
||||
|
||||
### cURL
|
||||
|
||||
```bash
|
||||
# Health Check
|
||||
curl http://localhost:8001/healthz
|
||||
|
||||
# Query
|
||||
curl -X POST http://localhost:8001/query \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"query": "Was ist Mindnet?", "top_k": 5}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Weitere Informationen
|
||||
|
||||
- **Chat-Backend Details:** Siehe [Chat Backend Dokumentation](03_tech_chat_backend.md)
|
||||
- **Ingestion-Pipeline:** Siehe [Ingestion Pipeline](03_tech_ingestion_pipeline.md)
|
||||
- **Retrieval & Scoring:** Siehe [Retrieval & Scoring](03_tech_retrieval_scoring.md)
|
||||
|
||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
||||
audience: developer, architect
|
||||
scope: backend, chat, llm_service, traffic_control, resilience
|
||||
status: active
|
||||
version: 2.8.1
|
||||
version: 2.9.1
|
||||
context: "Technische Implementierung des FastAPI-Routers, des hybriden LLMService (v3.3.6) und der WP-20 Resilienz-Logik."
|
||||
---
|
||||
|
||||
|
||||
@@ -20,13 +20,15 @@ Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts. Seit der
|
||||
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB API. |
|
||||
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
||||
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||
| `MINDNET_PREFIX` | *(leer)* | **Alternative zu COLLECTION_PREFIX.** Falls gesetzt, wird dieser Wert verwendet. |
|
||||
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||
| `MINDNET_DISTANCE` | `Cosine` | Metrik für Vektor-Ähnlichkeit (`Cosine`, `Euclidean`, `Dot`). |
|
||||
| `MINDNET_VECTOR_NAME` | `default` | **Neu (WP-14):** Basis-Vektorname für Named Vectors Support. |
|
||||
| `NOTES_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Notes-Collection (Override). |
|
||||
| `CHUNKS_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Chunks-Collection (Override). |
|
||||
| `EDGES_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Edges-Collection (Override). |
|
||||
| `MINDNET_VOCAB_PATH` | *(Pfad)* | **Neu (WP-22):** Absoluter Pfad zur `01_edge_vocabulary.md`. Definiert den Ort des Dictionarys. |
|
||||
| `MINDNET_VAULT_ROOT` | `./vault` | Basis-Pfad für Datei-Operationen. |
|
||||
| `MINDNET_VAULT_ROOT` | `./vault_master` | **Achtung:** Standard ist `./vault_master`, nicht `./vault`! Basis-Pfad für Datei-Operationen. |
|
||||
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||
|
||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
||||
audience: developer, architect
|
||||
scope: database, qdrant, schema
|
||||
status: active
|
||||
version: 2.8.0
|
||||
version: 2.9.1
|
||||
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen. Berücksichtigt WP-14 Modularisierung und WP-15b Multi-Hashes."
|
||||
---
|
||||
|
||||
@@ -96,15 +96,19 @@ Es müssen Payload-Indizes für folgende Felder existieren:
|
||||
|
||||
## 4. Edge Payload (`mindnet_edges`)
|
||||
|
||||
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking.
|
||||
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking. Seit v2.9.1 unterstützt das System **Section-basierte Links** (`[[Note#Section]]`), die in `target_id` und `target_section` aufgeteilt werden.
|
||||
|
||||
**JSON-Schema:**
|
||||
|
||||
```json
|
||||
{
|
||||
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind)
|
||||
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind, variant)
|
||||
// variant = target_section (erlaubt Multigraph für Sections)
|
||||
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (bei Unresolved)
|
||||
// WICHTIG: Enthält NUR den Note-Namen, KEINE Section-Info
|
||||
"target_section": "string (keyword)", // Optional: Abschnitts-Name (z.B. "P3 – Disziplin")
|
||||
// Wird aus [[Note#Section]] extrahiert
|
||||
"kind": "string (keyword)", // Beziehungsart (z.B. 'depends_on')
|
||||
"scope": "string (keyword)", // Immer 'chunk' (Legacy-Support: 'note')
|
||||
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
||||
@@ -116,10 +120,16 @@ Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Track
|
||||
}
|
||||
```
|
||||
|
||||
**Section-Support:**
|
||||
* Links wie `[[Note#Section]]` werden in `target_id="Note"` und `target_section="Section"` aufgeteilt.
|
||||
* Die Edge-ID enthält die Section als `variant`, sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Sections zeigen.
|
||||
* Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key, um "Phantom-Knoten" zu vermeiden.
|
||||
|
||||
**Erforderliche Indizes:**
|
||||
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||
* `source_id`
|
||||
* `target_id`
|
||||
* `target_section` (neu: Keyword-Index für Section-basierte Filterung)
|
||||
* `kind`
|
||||
* `scope`
|
||||
* `note_id`
|
||||
|
||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
||||
audience: developer, frontend_architect
|
||||
scope: architecture, graph_viz, state_management
|
||||
status: active
|
||||
version: 2.7.0
|
||||
version: 2.9.1
|
||||
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
||||
---
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
||||
audience: developer, devops
|
||||
scope: backend, ingestion, smart_edges, edge_registry, modularization
|
||||
status: active
|
||||
version: 2.9.0
|
||||
version: 2.13.12
|
||||
context: "Detaillierte technische Beschreibung der Import-Pipeline, Two-Pass-Workflow (WP-15b) und modularer Datenbank-Architektur (WP-14). Integriert Mistral-safe Parsing und Deep Fallback."
|
||||
---
|
||||
|
||||
@@ -31,9 +31,10 @@ Der Prozess ist **asynchron**, **idempotent** und wird nun in zwei logische Durc
|
||||
4. **Edge Registry Initialisierung (WP-22):**
|
||||
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
||||
* Validierung der Vokabular-Datei unter `MINDNET_VOCAB_PATH`.
|
||||
5. **Config Resolution (WP-14):**
|
||||
5. **Config Resolution (WP-14 / v2.13.12):**
|
||||
* Bestimmung von `chunking_profile` und `retriever_weight` via zentraler `TypeRegistry`.
|
||||
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Global Default.
|
||||
* **Registry-First Profiling:** Automatische Anwendung der korrekten Profile basierend auf dem Note-Typ (z.B. `value` nutzt automatisch `structured_smart_edges_strict`).
|
||||
6. **LocalBatchCache & Summary Generation (WP-15b):**
|
||||
* Erstellung von Kurz-Zusammenfassungen für jede Note.
|
||||
* Speicherung im `batch_cache` als Referenzrahmen für die spätere Kantenvalidierung.
|
||||
@@ -66,7 +67,24 @@ Der Prozess ist **asynchron**, **idempotent** und wird nun in zwei logische Durc
|
||||
|
||||
## 2. Betrieb & CLI Befehle
|
||||
|
||||
### 2.1 Standard-Betrieb (Inkrementell)
|
||||
### 2.1 API-Endpunkt: `/ingest/save` (Background Tasks)
|
||||
|
||||
Seit WP-14 nutzt der `/ingest/save` Endpunkt **Background Tasks** für non-blocking Ingestion:
|
||||
|
||||
**Workflow:**
|
||||
1. **Request:** Frontend sendet Markdown an `/ingest/save`
|
||||
2. **Sofortige Antwort:** API antwortet mit `status: "queued"` und `note_id: "pending"`
|
||||
3. **Datei-Persistenz:** Markdown wird sofort auf Festplatte geschrieben
|
||||
4. **Background Task:** Ingestion läuft asynchron im Hintergrund
|
||||
- Chunking
|
||||
- Embedding-Generierung
|
||||
- Smart Edge Allocation (WP-15)
|
||||
- Hybrid-Cloud-Analyse (WP-20)
|
||||
5. **Vorteil:** Keine Timeouts bei großen Dateien oder langsamen LLM-Calls
|
||||
|
||||
**Hinweis:** Die tatsächliche `note_id` steht erst nach dem Parsing fest. Das Frontend sollte den `file_path` für Tracking nutzen.
|
||||
|
||||
### 2.2 CLI-Betrieb (Inkrementell)
|
||||
Erkennt Änderungen via Multi-Hash.
|
||||
|
||||
```bash
|
||||
@@ -109,19 +127,44 @@ Das Chunking ist profilbasiert und bezieht seine Konfiguration dynamisch aus der
|
||||
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte (Projekte). |
|
||||
| `structured_smart_edges` | `by_heading` | `strict: false` | Strukturierte Texte. |
|
||||
|
||||
### 3.2 Die `by_heading` Logik (v2.9 Hybrid)
|
||||
### 3.2 Die `by_heading` Logik (v3.9.9 Atomic Section Logic)
|
||||
|
||||
Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften). Sie unterstützt ein "Safety Net" gegen zu große Chunks.
|
||||
Die Strategie `by_heading` implementiert seit v3.9.9 das **"Pack-and-Carry-Over"** Verfahren (Regel 1-3), um Sektions-Überschriften und deren Inhalte atomar in Chunks zu halten.
|
||||
|
||||
* **Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||
* **Modus "Strict" (`strict_heading_split: true`):**
|
||||
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt.
|
||||
* *Safety Net:* Wird ein Abschnitt zu lang (> `max` Token), wird auch ohne Überschrift getrennt.
|
||||
* **Modus "Soft" (`strict_heading_split: false`):**
|
||||
* **Hierarchie-Check:** Überschriften *oberhalb* des Split-Levels erzwingen **immer** einen Split.
|
||||
* **Füll-Logik:** Überschriften *auf* dem Split-Level lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||
**Kernprinzipien:**
|
||||
* **Atomic Section Logic:** Überschriften und deren Inhalte werden als atomare Einheiten behandelt und nicht über Chunk-Grenzen hinweg getrennt.
|
||||
* **H1-Context Preservation:** Der Dokumenttitel (H1) wird zuverlässig als Breadcrumb in das Embedding-Fenster (`window`) aller Chunks injiziert.
|
||||
* **Signature Alignment:** Parameter-Synchronisierung zwischen Orchestrator und Strategien (`context_prefix` statt `doc_title`).
|
||||
|
||||
**Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||
|
||||
**Modus "Strict" (`strict_heading_split: true`):**
|
||||
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt.
|
||||
* *Safety Net:* Wird ein Abschnitt zu lang (> `max` Token), wird auch ohne Überschrift getrennt.
|
||||
|
||||
**Modus "Soft" (`strict_heading_split: false`):**
|
||||
* **Hierarchie-Check:** Überschriften *oberhalb* des Split-Levels erzwingen **immer** einen Split.
|
||||
* **Füll-Logik:** Überschriften *auf* dem Split-Level lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||
* **Pack-and-Carry-Over:** Wenn ein Abschnitt zu groß ist, wird er intelligent zerlegt, wobei der Rest (mit Überschrift) zurück in die Queue gelegt wird.
|
||||
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||
|
||||
### 3.3 Registry-First Profiling (v2.13.12)
|
||||
|
||||
Seit v2.13.12 nutzt der `IngestionService` die korrekte Hierarchie zur Ermittlung des Chunking-Profils:
|
||||
|
||||
**Priorität:**
|
||||
1. **Frontmatter** (Override) - Explizite `chunking_profile` Angabe
|
||||
2. **`types.yaml` Typ-Config** - Profil basierend auf `type`
|
||||
3. **Global Defaults** - Fallback auf `sliding_standard`
|
||||
|
||||
**Wichtig:** Ein Hard-Fallback auf `sliding_standard` erfolgt nur noch, wenn keine Konfiguration existiert. Dies stellt sicher, dass Note-Typen wie `value` automatisch das korrekte Profil (z.B. `structured_smart_edges_strict`) erhalten.
|
||||
|
||||
### 3.4 Deterministic Hashing (v2.13.12)
|
||||
|
||||
Der `full`-Hash inkludiert nun alle strategischen Parameter (z.B. `split_level`, `strict_heading_split`), sodass Konfigurationsänderungen im Frontmatter zwingend einen Re-Import auslösen.
|
||||
|
||||
**Impact:** Änderungen an Chunking-Parametern werden zuverlässig erkannt, auch wenn der Text unverändert bleibt.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -131,30 +131,131 @@ Administratoren sollten regelmäßig das Log für unbekannte Kanten-Typen prüfe
|
||||
|
||||
### 3.3 Troubleshooting Guide
|
||||
|
||||
Dieser Abschnitt hilft bei häufigen Problemen und deren Lösung.
|
||||
|
||||
#### Allgemeine Diagnose-Schritte
|
||||
|
||||
Bevor du spezifische Fehler behebst, führe diese Checks durch:
|
||||
|
||||
1. **Service-Status prüfen:**
|
||||
```bash
|
||||
systemctl status mindnet-prod
|
||||
systemctl status mindnet-ui-prod
|
||||
docker ps | grep qdrant
|
||||
```
|
||||
|
||||
2. **Logs analysieren:**
|
||||
```bash
|
||||
journalctl -u mindnet-prod -n 50 --no-pager
|
||||
journalctl -u mindnet-ui-prod -n 50 --no-pager
|
||||
docker logs qdrant --tail 50
|
||||
```
|
||||
|
||||
3. **API-Verfügbarkeit testen:**
|
||||
```bash
|
||||
curl http://localhost:8001/health
|
||||
curl http://localhost:8001/query -X POST -H "Content-Type: application/json" -d '{"query": "test", "top_k": 1}'
|
||||
```
|
||||
|
||||
#### Häufige Fehler & Lösungen
|
||||
|
||||
**Fehler: "Registry Initialization Failure" (Neu in v2.7)**
|
||||
* **Symptom:** API startet, aber Kanten werden nicht gewichtet oder Fehlermeldung im Log.
|
||||
* **Lösung:** Prüfen Sie `MINDNET_VOCAB_PATH` in der `.env`. Der Pfad muss absolut sein und auf eine existierende Markdown-Tabelle zeigen.
|
||||
* **Diagnose:** Prüfe die Logs auf `EdgeRegistry`-Fehler.
|
||||
* **Lösung:**
|
||||
1. Prüfe `MINDNET_VOCAB_PATH` in der `.env`. Der Pfad muss absolut sein.
|
||||
2. Stelle sicher, dass die Datei `01_edge_vocabulary.md` existiert und eine gültige Markdown-Tabelle enthält.
|
||||
3. Prüfe Dateiberechtigungen: `ls -l $MINDNET_VOCAB_PATH`
|
||||
|
||||
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
||||
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
||||
* Lösung: Environment aktualisieren.
|
||||
* **Ursache:** Alte Dependencies oder falsches Paket installiert.
|
||||
* **Lösung:** Environment aktualisieren.
|
||||
```bash
|
||||
source .venv/bin/activate
|
||||
pip uninstall streamlit-cytoscapejs
|
||||
pip install st-cytoscape
|
||||
pip install -r requirements.txt # Vollständige Synchronisation
|
||||
```
|
||||
|
||||
**Fehler: "Vector dimension error: expected 768, got 384"**
|
||||
* Ursache: Alte DB (v2.2), neues Modell (v2.4).
|
||||
* Lösung: **Full Reset** (siehe Kap. 4.2).
|
||||
* **Ursache:** Alte DB (v2.2), neues Modell (v2.4) oder falsches Embedding-Modell.
|
||||
* **Diagnose:** Prüfe die Collection-Konfiguration in Qdrant.
|
||||
* **Lösung:** **Full Reset** (siehe Kap. 4.2) oder Collection neu erstellen:
|
||||
```bash
|
||||
python3 -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply --force
|
||||
```
|
||||
|
||||
**Fehler: Import sehr langsam**
|
||||
* Ursache: Smart Edges sind aktiv und analysieren jeden Chunk.
|
||||
* Lösung: `MINDNET_LLM_BACKGROUND_LIMIT` prüfen oder Feature in `types.yaml` deaktivieren.
|
||||
* **Ursache:** Smart Edges sind aktiv und analysieren jeden Chunk mit LLM-Calls.
|
||||
* **Diagnose:** Prüfe `MINDNET_LLM_BACKGROUND_LIMIT` und LLM-Provider-Status.
|
||||
* **Lösung:**
|
||||
1. Erhöhe `MINDNET_LLM_BACKGROUND_LIMIT` in `.env` (Standard: 2)
|
||||
2. Oder deaktiviere Smart Edges temporär in `types.yaml` für bestimmte Typen
|
||||
3. Prüfe, ob Ollama/Cloud-Provider erreichbar ist
|
||||
|
||||
**Fehler: UI "Read timed out"**
|
||||
* Ursache: Backend braucht für Smart Edges länger als 60s.
|
||||
* Lösung: `MINDNET_API_TIMEOUT=300.0` in `.env` setzen (oder im Systemd Service).
|
||||
* **Ursache:** Backend braucht für Smart Edges länger als das Timeout-Limit.
|
||||
* **Diagnose:** Prüfe Backend-Logs auf langsame LLM-Calls.
|
||||
* **Lösung:**
|
||||
1. Erhöhe `MINDNET_API_TIMEOUT=300.0` in `.env` (oder im Systemd Service)
|
||||
2. Prüfe `MINDNET_LLM_TIMEOUT` für einzelne LLM-Requests
|
||||
3. Erwäge, Smart Edges für große Imports zu deaktivieren
|
||||
|
||||
**Fehler: "Qdrant connection refused"**
|
||||
* **Ursache:** Qdrant-Container läuft nicht oder falsche URL.
|
||||
* **Lösung:**
|
||||
```bash
|
||||
docker ps | grep qdrant # Prüfe Container-Status
|
||||
docker start qdrant # Starte Container falls gestoppt
|
||||
docker logs qdrant # Prüfe Container-Logs
|
||||
# Prüfe QDRANT_URL in .env
|
||||
```
|
||||
|
||||
**Fehler: "Ollama model not found"**
|
||||
* **Ursache:** Modell nicht geladen oder falscher Modellname.
|
||||
* **Lösung:**
|
||||
```bash
|
||||
ollama list # Zeige geladene Modelle
|
||||
ollama pull phi3:mini # Lade fehlendes Modell
|
||||
ollama pull nomic-embed-text
|
||||
# Prüfe MINDNET_LLM_MODEL und MINDNET_EMBEDDING_MODEL in .env
|
||||
```
|
||||
|
||||
**Fehler: "Too many open files" (Qdrant)**
|
||||
* **Ursache:** System-Limit für offene Dateien zu niedrig (besonders bei vielen Collections).
|
||||
* **Lösung:** Erhöhe `ulimits` im Docker-Compose (siehe Kap. 1.2) oder systemweit:
|
||||
```bash
|
||||
# Temporär
|
||||
ulimit -n 65535
|
||||
# Permanently: /etc/security/limits.conf
|
||||
```
|
||||
|
||||
**Fehler: "Unknown edge type" in Logs**
|
||||
* **Ursache:** Neue Kanten-Typen im Vault, die nicht in `edge_vocabulary.md` definiert sind.
|
||||
* **Diagnose:** Prüfe `data/logs/unknown_edges.jsonl`.
|
||||
* **Lösung:**
|
||||
1. Füge fehlende Typen als Aliase in `01_edge_vocabulary.md` hinzu
|
||||
2. Oder verwende kanonische Typen aus der Registry
|
||||
|
||||
#### Performance-Optimierung
|
||||
|
||||
**Problem: Langsame Chat-Antworten**
|
||||
* Prüfe LLM-Provider (Cloud vs. lokal)
|
||||
* Reduziere `top_k` in Query-Requests
|
||||
* Prüfe Qdrant-Performance (Anzahl Collections, Index-Größe)
|
||||
|
||||
**Problem: Hoher Speicherverbrauch**
|
||||
* Reduziere `MINDNET_LLM_BACKGROUND_LIMIT`
|
||||
* Prüfe Qdrant-Speicherverbrauch: `docker stats qdrant`
|
||||
* Erwäge, alte Collections zu archivieren
|
||||
|
||||
#### Weitere Hilfe
|
||||
|
||||
Für detaillierte Informationen zu:
|
||||
- **Server-Betrieb:** Siehe [Server Operations Manual](04_server_operation_manual.md)
|
||||
- **Entwicklung:** Siehe [Developer Guide](../05_Development/05_developer_guide.md#10-troubleshooting--one-liners)
|
||||
- **Konfiguration:** Siehe [Configuration Reference](../03_Technical_References/03_tech_configuration.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -178,4 +279,11 @@ python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||
|
||||
# 2. Neu importieren (Force Hash recalculation)
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||
```
|
||||
```
|
||||
|
||||
**Wichtig (v2.9.1 Migration):**
|
||||
Nach dem Update auf v2.9.1 (Section-basierte Links, Multigraph-Support) ist ein vollständiger Re-Import erforderlich, um "Phantom-Knoten" zu beheben und die neue Edge-Struktur zu konsolidieren:
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||
```
|
||||
Dies stellt sicher, dass alle bestehenden Links korrekt in `target_id` und `target_section` aufgeteilt werden.
|
||||
@@ -0,0 +1,474 @@
|
||||
---
|
||||
doc_type: operations_manual
|
||||
audience: devops, deployment_engineer
|
||||
scope: deployment, ci_cd, rollout, versioning
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Vollständiger Deployment-Guide für Mindnet: CI/CD, Rollout-Strategien, Versionierung und Rollback."
|
||||
---
|
||||
|
||||
# Deployment Guide
|
||||
|
||||
Dieses Dokument beschreibt die Deployment-Prozesse, CI/CD-Pipelines und Rollout-Strategien für Mindnet.
|
||||
|
||||
## 1. Deployment-Architektur
|
||||
|
||||
Mindnet läuft in einer **Multi-Environment-Architektur**:
|
||||
|
||||
| Environment | Ports | Zweck | User |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Production** | 8001 (API), 8501 (UI) | Live-System | `llmadmin` |
|
||||
| **Development** | 8002 (API), 8502 (UI) | Test & Entwicklung | `llmadmin` |
|
||||
|
||||
**Wichtig:** Beide Environments teilen sich die gleiche Qdrant-Instanz, nutzen aber unterschiedliche Collection-Prefixes.
|
||||
|
||||
---
|
||||
|
||||
## 2. Deployment-Methoden
|
||||
|
||||
### 2.1 Automatisches Deployment (CI/CD)
|
||||
|
||||
**Tool:** Gitea Actions (`.gitea/workflows/deploy.yml`)
|
||||
|
||||
**Trigger:** Push auf `main` Branch
|
||||
|
||||
**Prozess:**
|
||||
1. **Checkout:** Code wird ausgecheckt
|
||||
2. **Stop API:** Graceful Stop des API-Services
|
||||
3. **Deploy:** Rsync der whitelisted Verzeichnisse
|
||||
4. **Dependencies:** Python venv & requirements aktualisieren
|
||||
5. **Restart:** API-Service neu starten
|
||||
|
||||
**Deployierte Verzeichnisse:**
|
||||
- `app/` - Backend-Code
|
||||
- `scripts/` - Admin-Tools
|
||||
- `config/` - Konfigurationsdateien
|
||||
- `tests/` - Test-Suite
|
||||
- `requirements.txt` - Dependencies
|
||||
|
||||
**Ausgeschlossen:**
|
||||
- `.env*` - Umgebungsvariablen (bleiben auf Server)
|
||||
- `.venv` - Virtuelle Umgebung (wird neu erstellt)
|
||||
- `vault/` - Content (bleibt auf Server)
|
||||
|
||||
### 2.2 Manuelles Deployment
|
||||
|
||||
**Für:** Hotfixes, manuelle Rollouts, Debugging
|
||||
|
||||
**Prozess:**
|
||||
```bash
|
||||
# 1. Auf Server einloggen
|
||||
ssh llmadmin@llm-node
|
||||
|
||||
# 2. In Produktions-Verzeichnis wechseln
|
||||
cd ~/mindnet
|
||||
|
||||
# 3. Code aktualisieren
|
||||
git fetch origin
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# 4. Dependencies aktualisieren
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 5. Services neu starten
|
||||
sudo systemctl restart mindnet-prod
|
||||
sudo systemctl restart mindnet-ui-prod
|
||||
|
||||
# 6. Status prüfen
|
||||
sudo systemctl status mindnet-prod
|
||||
sudo systemctl status mindnet-ui-prod
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Systemd Services
|
||||
|
||||
### 3.1 Backend Service (API)
|
||||
|
||||
**Datei:** `/etc/systemd/system/mindnet-prod.service`
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Mindnet API Prod (8001)
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=llmadmin
|
||||
Group=llmadmin
|
||||
WorkingDirectory=/home/llmadmin/mindnet
|
||||
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
Environment="MINDNET_VOCAB_PATH=/home/llmadmin/mindnet/vault/_system/dictionary/edge_vocabulary.md"
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
**Wichtig:**
|
||||
- `--env-file .env` lädt Umgebungsvariablen
|
||||
- `MINDNET_VOCAB_PATH` muss absolut sein (für Edge Registry)
|
||||
|
||||
### 3.2 Frontend Service (UI)
|
||||
|
||||
**Datei:** `/etc/systemd/system/mindnet-ui-prod.service`
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Mindnet UI Prod (8501)
|
||||
After=mindnet-prod.service
|
||||
|
||||
[Service]
|
||||
User=llmadmin
|
||||
Group=llmadmin
|
||||
WorkingDirectory=/home/llmadmin/mindnet
|
||||
Environment="MINDNET_API_URL=http://localhost:8001"
|
||||
Environment="MINDNET_API_TIMEOUT=300"
|
||||
Environment="STREAMLIT_SERVER_PORT=8501"
|
||||
Environment="STREAMLIT_SERVER_ADDRESS=0.0.0.0"
|
||||
Environment="STREAMLIT_SERVER_HEADLESS=true"
|
||||
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
### 3.3 Service-Management
|
||||
|
||||
**Befehle:**
|
||||
```bash
|
||||
# Status prüfen
|
||||
sudo systemctl status mindnet-prod
|
||||
sudo systemctl status mindnet-ui-prod
|
||||
|
||||
# Starten
|
||||
sudo systemctl start mindnet-prod
|
||||
sudo systemctl start mindnet-ui-prod
|
||||
|
||||
# Stoppen
|
||||
sudo systemctl stop mindnet-prod
|
||||
sudo systemctl stop mindnet-ui-prod
|
||||
|
||||
# Neustart
|
||||
sudo systemctl restart mindnet-prod
|
||||
sudo systemctl restart mindnet-ui-prod
|
||||
|
||||
# Logs anzeigen
|
||||
sudo journalctl -u mindnet-prod -f
|
||||
sudo journalctl -u mindnet-ui-prod -f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Rollout-Strategien
|
||||
|
||||
### 4.1 Blue-Green Deployment (Empfohlen)
|
||||
|
||||
**Konzept:** Zwei identische Environments, Switch zwischen ihnen.
|
||||
|
||||
**Aktuell:** Prod/Dev als Blue-Green Setup
|
||||
|
||||
**Vorgehen:**
|
||||
1. Deploy auf Dev (Port 8002/8502)
|
||||
2. Tests auf Dev durchführen
|
||||
3. Wenn erfolgreich: Deploy auf Prod (Port 8001/8501)
|
||||
4. Switch erfolgt durch Service-Restart
|
||||
|
||||
**Vorteile:**
|
||||
- Schneller Rollback (alte Version läuft noch)
|
||||
- Keine Downtime
|
||||
- Test vor Produktion
|
||||
|
||||
### 4.2 Canary Deployment (Zukünftig)
|
||||
|
||||
**Konzept:** Schrittweise Rollout an einen Teil der Nutzer.
|
||||
|
||||
**Umsetzung:**
|
||||
- Load Balancer mit Traffic-Splitting
|
||||
- Monitoring der Fehlerrate
|
||||
- Automatischer Rollback bei Fehlern
|
||||
|
||||
**Status:** Noch nicht implementiert (Single-User-Szenario)
|
||||
|
||||
---
|
||||
|
||||
## 5. Versionierung & Releases
|
||||
|
||||
### 5.1 Version-Schema
|
||||
|
||||
**Format:** `v2.9.1`
|
||||
|
||||
- **Major (2):** Breaking Changes
|
||||
- **Minor (9):** Neue Features, Backward Compatible
|
||||
- **Patch (1):** Bugfixes, kleine Verbesserungen
|
||||
|
||||
### 5.2 Release-Prozess
|
||||
|
||||
**1. Feature-Entwicklung:**
|
||||
```bash
|
||||
git checkout -b feature/neue-funktion
|
||||
# ... Entwicklung ...
|
||||
git push origin feature/neue-funktion
|
||||
```
|
||||
|
||||
**2. Testing:**
|
||||
- Unit Tests
|
||||
- Integration Tests
|
||||
- Smoke Tests auf Dev
|
||||
|
||||
**3. Merge:**
|
||||
```bash
|
||||
# Pull Request in Gitea
|
||||
# Review & Merge nach main
|
||||
```
|
||||
|
||||
**4. Deployment:**
|
||||
- Automatisch via CI/CD (bei Push auf main)
|
||||
- Oder manuell (siehe 2.2)
|
||||
|
||||
**5. Tagging (Optional):**
|
||||
```bash
|
||||
git tag -a v2.9.2 -m "Release v2.9.2: Neue Funktion X"
|
||||
git push origin v2.9.2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Rollback-Strategien
|
||||
|
||||
### 6.1 Code-Rollback
|
||||
|
||||
**Methode 1: Git Revert**
|
||||
```bash
|
||||
cd ~/mindnet
|
||||
git log --oneline -10 # Finde letzten guten Commit
|
||||
git checkout <commit-hash>
|
||||
sudo systemctl restart mindnet-prod
|
||||
```
|
||||
|
||||
**Methode 2: Git Reset (Vorsicht!)**
|
||||
```bash
|
||||
cd ~/mindnet
|
||||
git reset --hard <commit-hash>
|
||||
sudo systemctl restart mindnet-prod
|
||||
```
|
||||
|
||||
### 6.2 Datenbank-Rollback
|
||||
|
||||
**Problem:** Code-Rollback hilft nicht bei Schema-Änderungen.
|
||||
|
||||
**Lösung:**
|
||||
- **Qdrant-Snapshots:** Regelmäßige Backups (siehe [Server Operations Manual](04_server_operation_manual.md))
|
||||
- **Collection-Versionierung:** Separate Collections pro Version (nicht empfohlen)
|
||||
|
||||
**Vorgehen bei Schema-Änderung:**
|
||||
1. Snapshot vor Deployment erstellen
|
||||
2. Deployment durchführen
|
||||
3. Bei Problemen: Snapshot wiederherstellen
|
||||
|
||||
---
|
||||
|
||||
## 7. Pre-Deployment Checkliste
|
||||
|
||||
Vor jedem Deployment sollten folgende Punkte geprüft werden:
|
||||
|
||||
- [ ] **Code-Qualität:**
|
||||
- [ ] Unit Tests bestehen
|
||||
- [ ] Integration Tests bestehen
|
||||
- [ ] Linting bestanden
|
||||
|
||||
- [ ] **Dependencies:**
|
||||
- [ ] `requirements.txt` aktualisiert
|
||||
- [ ] Neue Dependencies dokumentiert
|
||||
- [ ] Breaking Changes in Dependencies geprüft
|
||||
|
||||
- [ ] **Konfiguration:**
|
||||
- [ ] `.env` Variablen dokumentiert (falls neu)
|
||||
- [ ] Config-Dateien (`types.yaml`, etc.) kompatibel
|
||||
- [ ] Edge Registry Pfad korrekt
|
||||
|
||||
- [ ] **Datenbank:**
|
||||
- [ ] Schema-Änderungen dokumentiert
|
||||
- [ ] Migration-Skripte vorhanden (falls nötig)
|
||||
- [ ] Backup erstellt
|
||||
|
||||
- [ ] **Dokumentation:**
|
||||
- [ ] Changelog aktualisiert
|
||||
- [ ] Dokumentation synchronisiert
|
||||
- [ ] Breaking Changes dokumentiert
|
||||
|
||||
---
|
||||
|
||||
## 8. Post-Deployment Validierung
|
||||
|
||||
Nach jedem Deployment sollten folgende Checks durchgeführt werden:
|
||||
|
||||
### 8.1 Service-Status
|
||||
|
||||
```bash
|
||||
# Services laufen
|
||||
sudo systemctl status mindnet-prod
|
||||
sudo systemctl status mindnet-ui-prod
|
||||
|
||||
# Health Check
|
||||
curl http://localhost:8001/healthz
|
||||
```
|
||||
|
||||
### 8.2 Funktionalität
|
||||
|
||||
```bash
|
||||
# API-Test
|
||||
curl -X POST http://localhost:8001/query \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"query": "test", "top_k": 1}'
|
||||
|
||||
# UI-Test (Manuell)
|
||||
# Öffne http://localhost:8501 im Browser
|
||||
```
|
||||
|
||||
### 8.3 Logs prüfen
|
||||
|
||||
```bash
|
||||
# Fehler in Logs
|
||||
sudo journalctl -u mindnet-prod --since "5 minutes ago" | grep -i error
|
||||
|
||||
# Warnings
|
||||
sudo journalctl -u mindnet-prod --since "5 minutes ago" | grep -i warning
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. CI/CD Pipeline Details
|
||||
|
||||
### 9.1 Gitea Actions Workflow
|
||||
|
||||
**Datei:** `.gitea/workflows/deploy.yml`
|
||||
|
||||
**Trigger:**
|
||||
- Push auf `main` Branch
|
||||
- Concurrency: Nur ein Deployment gleichzeitig
|
||||
|
||||
**Schritte:**
|
||||
1. **Checkout:** Code aus Repository
|
||||
2. **Stop API:** Graceful Stop (continue-on-error)
|
||||
3. **Deploy:** Rsync der Verzeichnisse
|
||||
4. **Python Setup:** Venv & Requirements
|
||||
5. **Start API:** Service neu starten
|
||||
|
||||
**Wichtig:**
|
||||
- `.env` wird **nicht** deployed (bleibt auf Server)
|
||||
- Vault wird **nicht** deployed (bleibt auf Server)
|
||||
|
||||
### 9.2 Deployment-Verzeichnisse
|
||||
|
||||
**Whitelist:**
|
||||
```
|
||||
app scripts schemas docker tests config requirements.txt README.md
|
||||
```
|
||||
|
||||
**Excluded:**
|
||||
- `.git/`
|
||||
- `.env*`
|
||||
- `.venv/`
|
||||
- `vault/`
|
||||
- `hf_cache/`
|
||||
|
||||
---
|
||||
|
||||
## 10. Monitoring & Alerting
|
||||
|
||||
### 10.1 Health Checks
|
||||
|
||||
**API Health Endpoint:**
|
||||
```bash
|
||||
curl http://localhost:8001/healthz
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"qdrant": "http://localhost:6333",
|
||||
"prefix": "mindnet"
|
||||
}
|
||||
```
|
||||
|
||||
**Monitoring-Script:**
|
||||
```bash
|
||||
python3 -m scripts.health_check_mindnet --url http://localhost:8001 --strict
|
||||
```
|
||||
|
||||
### 10.2 Log-Monitoring
|
||||
|
||||
**Systemd Journal:**
|
||||
```bash
|
||||
# Live-Logs
|
||||
sudo journalctl -u mindnet-prod -f
|
||||
|
||||
# Letzte 100 Zeilen
|
||||
sudo journalctl -u mindnet-prod -n 100
|
||||
|
||||
# Seit gestern
|
||||
sudo journalctl -u mindnet-prod --since "yesterday"
|
||||
```
|
||||
|
||||
### 10.3 Metriken (Zukünftig)
|
||||
|
||||
**Geplante Metriken:**
|
||||
- Request-Rate
|
||||
- Response-Zeiten
|
||||
- Fehler-Rate
|
||||
- LLM-Call-Dauer
|
||||
- Qdrant-Performance
|
||||
|
||||
**Tools:** Prometheus + Grafana (noch nicht implementiert)
|
||||
|
||||
---
|
||||
|
||||
## 11. Disaster Recovery
|
||||
|
||||
Siehe [Server Operations Manual](04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr) für detaillierte Disaster-Recovery-Prozeduren.
|
||||
|
||||
**Kurzfassung:**
|
||||
1. **Stage 1:** Basis-Image Restore (Bare Metal)
|
||||
2. **Stage 2:** Daten-Update via Borgmatic
|
||||
3. **Dienste:** Gitea, Qdrant, Ollama spezifisch wiederherstellen
|
||||
|
||||
---
|
||||
|
||||
## 12. Best Practices
|
||||
|
||||
### 12.1 Deployment-Zeiten
|
||||
|
||||
- **Produktion:** Während Wartungsfenstern (nachts, Wochenenden)
|
||||
- **Development:** Jederzeit (ist Test-Umgebung)
|
||||
|
||||
### 12.2 Kommunikation
|
||||
|
||||
- **Breaking Changes:** Vorher ankündigen
|
||||
- **Downtime:** Bei größeren Deployments kommunizieren
|
||||
- **Rollback-Plan:** Immer bereit haben
|
||||
|
||||
### 12.3 Testing
|
||||
|
||||
- **Immer zuerst auf Dev testen**
|
||||
- **Smoke Tests nach Deployment**
|
||||
- **Monitoring für erste Stunden nach Deployment**
|
||||
|
||||
---
|
||||
|
||||
## 13. Weitere Informationen
|
||||
|
||||
- **Admin Operations:** Siehe [Admin Operations Guide](04_admin_operations.md)
|
||||
- **Server Operations:** Siehe [Server Operations Manual](04_server_operation_manual.md)
|
||||
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](04_admin_operations.md#33-troubleshooting-guide)
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2025-01-XX
|
||||
**Version:** 2.9.1
|
||||
|
||||
@@ -216,6 +216,22 @@ Das Frontend ist eine Streamlit-App, die sich wie eine Single-Page-Application (
|
||||
|
||||
Das Backend ist das Herzstück. Es stellt die Logik via REST-API bereit.
|
||||
|
||||
**Wichtig:** Seit WP-14 ist die Core-Logik in spezialisierte Pakete unterteilt:
|
||||
|
||||
#### Core-Pakete (Modularisierung WP-14)
|
||||
|
||||
| Paket | Zweck | Wichtige Module |
|
||||
| :--- | :--- | :--- |
|
||||
| **`app/core/chunking/`** | Text-Segmentierung | `chunking_strategies.py` (Sliding/Heading), `chunking_processor.py` (Orchestrierung) |
|
||||
| **`app/core/database/`** | Qdrant-Infrastruktur | `qdrant.py` (Client), `qdrant_points.py` (Point-Mapping) |
|
||||
| **`app/core/graph/`** | Graph-Logik | `graph_subgraph.py` (Expansion), `graph_weights.py` (Scoring) |
|
||||
| **`app/core/ingestion/`** | Import-Pipeline | `ingestion_processor.py` (Two-Pass), `ingestion_validation.py` (Mistral-safe Parsing) |
|
||||
| **`app/core/parser/`** | Markdown-Parsing | `parsing_markdown.py` (Frontmatter/Body), `parsing_scanner.py` (File-Scan) |
|
||||
| **`app/core/retrieval/`** | Suche & Scoring | `retriever.py` (Orchestrator), `retriever_scoring.py` (Mathematik) |
|
||||
| **`app/core/registry.py`** | SSOT & Utilities | Text-Bereinigung, Circular-Import-Fix |
|
||||
|
||||
**Legacy-Bridges:** Die alten Dateien (`app/core/retriever.py`, `app/core/qdrant.py`) existieren noch als Proxy-Adapter für Abwärtskompatibilität, delegieren aber an die neuen Pakete.
|
||||
|
||||
| Layer | Datei | Status | Verantwortung |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Entry** | `app/main.py` | 🟢 **Core** | **Entrypoint.** Initialisiert FastAPI, CORS, und bindet alle Router ein. |
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
---
|
||||
doc_type: developer_guide
|
||||
audience: developer, tester
|
||||
scope: testing, quality_assurance, test_strategies
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Umfassender Test-Guide für Mindnet: Test-Strategien, Test-Frameworks, Test-Daten und Best Practices."
|
||||
---
|
||||
|
||||
# Testing Guide
|
||||
|
||||
Dieses Dokument beschreibt die Test-Strategien, Test-Frameworks und Best Practices für die Qualitätssicherung von Mindnet.
|
||||
|
||||
## 1. Test-Strategie & Ebenen
|
||||
|
||||
Mindnet nutzt eine **dreistufige Test-Pyramide**:
|
||||
|
||||
```
|
||||
/\
|
||||
/E2E\ ← Wenige, langsame, teure Tests
|
||||
/------\
|
||||
/Integration\ ← Mittlere Anzahl, mittlere Geschwindigkeit
|
||||
/------------\
|
||||
/ Unit Tests \ ← Viele, schnelle, isolierte Tests
|
||||
/----------------\
|
||||
```
|
||||
|
||||
### 1.1 Unit Tests (Pytest)
|
||||
|
||||
**Zweck:** Isolierte Logik-Tests ohne externe Abhängigkeiten.
|
||||
|
||||
**Framework:** `pytest`
|
||||
|
||||
**Beispiele:**
|
||||
- `tests/test_retriever_basic.py` - Scoring-Logik
|
||||
- `tests/test_chunking.py` - Chunking-Strategien
|
||||
- `tests/test_edges_all.py` - Edge-Logik
|
||||
- `tests/test_type_registry.py` - Registry-Funktionen
|
||||
|
||||
**Ausführung:**
|
||||
```bash
|
||||
# Einzelner Test
|
||||
pytest tests/test_retriever_basic.py -v
|
||||
|
||||
# Alle Unit Tests
|
||||
pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py
|
||||
|
||||
# Mit Coverage
|
||||
pytest tests/ --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
**Best Practices:**
|
||||
- Tests sollten isoliert sein (keine Abhängigkeiten zu Qdrant/Ollama)
|
||||
- Mock externe Services (LLM, Qdrant)
|
||||
- Schnelle Ausführung (< 1 Sekunde pro Test)
|
||||
|
||||
### 1.2 Integration Tests
|
||||
|
||||
**Zweck:** Prüfen den Datenfluss von Markdown bis Qdrant.
|
||||
|
||||
**Tools:**
|
||||
- `scripts/payload_dryrun.py` - JSON-Schema-Konformität
|
||||
- `scripts/edges_full_check.py` - Graph-Integrität
|
||||
- `scripts/make_test_vault.py` - Test-Daten-Generierung
|
||||
|
||||
**Ausführung:**
|
||||
```bash
|
||||
# Payload-Validierung
|
||||
python3 -m scripts.payload_dryrun --vault ./test_vault --with-edges
|
||||
|
||||
# Graph-Integrität
|
||||
python3 -m scripts.edges_full_check
|
||||
|
||||
# Test-Vault erstellen
|
||||
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||
```
|
||||
|
||||
**Was wird geprüft:**
|
||||
- Frontmatter-Parsing
|
||||
- Chunk-Generierung
|
||||
- Edge-Erstellung
|
||||
- Payload-Schema-Konformität
|
||||
- Graph-Invarianten (keine Dangling Edges)
|
||||
|
||||
### 1.3 E2E / Smoke Tests
|
||||
|
||||
**Zweck:** Prüfen das laufende System gegen echte Infrastruktur (Qdrant, Ollama).
|
||||
|
||||
**Framework:** Python `unittest` + Shell-Skripte
|
||||
|
||||
**Beispiele:**
|
||||
- `tests/test_wp06_decision.py` - Decision Engine
|
||||
- `tests/test_feedback_smoke.py` - Feedback-Loop
|
||||
- `tests/test_dialog_full_flow.py` - Vollständiger Dialog-Flow
|
||||
- `tests/run_e2e_roundtrip.sh` - Kompletter Roundtrip (Import → Export)
|
||||
|
||||
**Ausführung:**
|
||||
```bash
|
||||
# Decision Engine Test
|
||||
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||
|
||||
# Feedback Test
|
||||
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||
|
||||
# E2E Roundtrip
|
||||
./tests/run_e2e_roundtrip.sh --vault ./test_vault --prefix mindnet_test
|
||||
```
|
||||
|
||||
**Voraussetzungen:**
|
||||
- Qdrant läuft auf `localhost:6333`
|
||||
- Ollama läuft auf `localhost:11434`
|
||||
- API läuft auf Port 8002 (Dev)
|
||||
|
||||
---
|
||||
|
||||
## 2. Test-Daten & Vaults
|
||||
|
||||
### 2.1 Test-Vault erstellen
|
||||
|
||||
**Tool:** `scripts/make_test_vault.py`
|
||||
|
||||
**Zweck:** Erstellt einen minimalen, nachvollziehbaren Test-Vault.
|
||||
|
||||
**Inhalt:**
|
||||
- Verschiedene Note-Typen (`concept`, `experience`, `project`)
|
||||
- Verschiedene Edge-Szenarien (explicit, implicit, missing links)
|
||||
- Externe Links für Edge-Tests
|
||||
|
||||
**Verwendung:**
|
||||
```bash
|
||||
# Standard
|
||||
python3 -m scripts.make_test_vault --out ./test_vault
|
||||
|
||||
# Mit fehlenden Links (für Link-Auflösungs-Tests)
|
||||
python3 -m scripts.make_test_vault --out ./test_vault --with-missing
|
||||
|
||||
# Überschreiben bestehenden Vault
|
||||
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||
```
|
||||
|
||||
### 2.2 Test-Collection Prefix
|
||||
|
||||
**Wichtig:** Nutze separate Prefixes für Tests, um Produktionsdaten nicht zu beeinflussen.
|
||||
|
||||
```bash
|
||||
export COLLECTION_PREFIX="mindnet_test"
|
||||
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet_test --apply
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Test-Frameworks & Tools
|
||||
|
||||
### 3.1 Pytest (Unit Tests)
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
pip install pytest pytest-asyncio pytest-cov
|
||||
```
|
||||
|
||||
**Konfiguration:** `pytest.ini` oder `pyproject.toml`
|
||||
|
||||
**Async Tests:**
|
||||
```python
|
||||
import pytest
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_function():
|
||||
result = await async_function()
|
||||
assert result == expected
|
||||
```
|
||||
|
||||
### 3.2 Unittest (E2E Tests)
|
||||
|
||||
**Framework:** Python `unittest`
|
||||
|
||||
**Beispiel:**
|
||||
```python
|
||||
import unittest
|
||||
from app.routers.ingest import save_note, SaveRequest
|
||||
|
||||
class TestIngest(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_save_note(self):
|
||||
req = SaveRequest(markdown_content="...", filename="test.md")
|
||||
response = await save_note(req)
|
||||
self.assertEqual(response.status, "queued")
|
||||
```
|
||||
|
||||
### 3.3 Shell-Skripte (E2E Roundtrip)
|
||||
|
||||
**Tool:** `tests/run_e2e_roundtrip.sh`
|
||||
|
||||
**Zweck:** Vollständiger Test-Zyklus (Import → Export → Vergleich)
|
||||
|
||||
**Schritte:**
|
||||
1. Qdrant truncate
|
||||
2. Import (Create-Fall)
|
||||
3. Import (Idempotenz-Test)
|
||||
4. Hash-Reporter
|
||||
5. Export
|
||||
6. Vergleich Vault vs. Export
|
||||
7. Sync-Deletes Test
|
||||
|
||||
---
|
||||
|
||||
## 4. Test-Szenarien
|
||||
|
||||
### 4.1 Chunking-Tests
|
||||
|
||||
**Was wird getestet:**
|
||||
- Sliding Window Strategie
|
||||
- Heading-basierte Strategie
|
||||
- Edge-Vererbung
|
||||
- Chunk-Größen-Limits
|
||||
|
||||
**Tests:**
|
||||
- `tests/test_smart_chunking_integration.py`
|
||||
- `scripts/preview_chunks.py` (Manuelle Inspektion)
|
||||
|
||||
### 4.2 Retrieval-Tests
|
||||
|
||||
**Was wird getestet:**
|
||||
- Semantic Search
|
||||
- Hybrid Search (Semantik + Graph)
|
||||
- Scoring-Formel
|
||||
- Explanation Layer
|
||||
|
||||
**Tests:**
|
||||
- `tests/test_retriever_basic.py`
|
||||
- `tests/test_retriever_edges.py`
|
||||
- `tests/test_retriever_weight.py`
|
||||
- `tests/test_explanation_smoke.py`
|
||||
|
||||
### 4.3 Edge-Tests
|
||||
|
||||
**Was wird getestet:**
|
||||
- Edge-Erstellung (explicit, smart, rule)
|
||||
- Edge-Validierung (Registry)
|
||||
- Edge-Vererbung
|
||||
- Unresolved References
|
||||
|
||||
**Tests:**
|
||||
- `tests/test_edges_all.py`
|
||||
- `tests/test_edges_smoke.py`
|
||||
- `tests/test_edges_defaults_smoke.py`
|
||||
- `scripts/edges_full_check.py`
|
||||
|
||||
### 4.4 Chat & Intent-Tests
|
||||
|
||||
**Was wird getestet:**
|
||||
- Intent-Erkennung (FACT, DECISION, EMPATHY, INTERVIEW)
|
||||
- Decision Engine
|
||||
- Interview-Modus
|
||||
- Feedback-Loop
|
||||
|
||||
**Tests:**
|
||||
- `tests/test_wp06_decision.py`
|
||||
- `tests/test_interview_intent.py`
|
||||
- `tests/test_chat_wp05.py`
|
||||
- `tests/test_feedback_smoke.py`
|
||||
|
||||
### 4.5 Ingestion-Tests
|
||||
|
||||
**Was wird getestet:**
|
||||
- Two-Pass Workflow
|
||||
- Change Detection (Hash-basiert)
|
||||
- Background Tasks
|
||||
- Smart Edge Allocation
|
||||
|
||||
**Tests:**
|
||||
- `tests/test_dialog_full_flow.py`
|
||||
- `tests/test_WP22_intelligence.py`
|
||||
- `scripts/import_markdown.py` (mit `--dry-run`)
|
||||
|
||||
---
|
||||
|
||||
## 5. Continuous Integration
|
||||
|
||||
### 5.1 Pre-Commit Checks
|
||||
|
||||
**Empfohlene Checks:**
|
||||
```bash
|
||||
# Linting
|
||||
flake8 app/ scripts/
|
||||
|
||||
# Type Checking (optional)
|
||||
mypy app/
|
||||
|
||||
# Unit Tests
|
||||
pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py
|
||||
```
|
||||
|
||||
### 5.2 CI/CD Pipeline
|
||||
|
||||
**Gitea Actions:** `.gitea/workflows/`
|
||||
|
||||
**Typische Pipeline:**
|
||||
1. Checkout
|
||||
2. Python Setup
|
||||
3. Dependencies installieren
|
||||
4. Unit Tests
|
||||
5. Integration Tests (optional)
|
||||
6. Deployment (bei main branch)
|
||||
|
||||
---
|
||||
|
||||
## 6. Test-Best Practices
|
||||
|
||||
### 6.1 Isolation
|
||||
|
||||
- **Unit Tests:** Keine externen Abhängigkeiten (Mock alles)
|
||||
- **Integration Tests:** Echte Qdrant, aber isolierte Collections
|
||||
- **E2E Tests:** Separate Test-Umgebung (Port 8002)
|
||||
|
||||
### 6.2 Test-Daten
|
||||
|
||||
- Nutze `make_test_vault.py` für konsistente Test-Daten
|
||||
- Separate Collection-Prefixes für Tests
|
||||
- Cleanup nach Tests (oder isolierte Collections)
|
||||
|
||||
### 6.3 Performance
|
||||
|
||||
- Unit Tests sollten < 1 Sekunde dauern
|
||||
- Integration Tests können länger dauern (10-30 Sekunden)
|
||||
- E2E Tests sind langsam (1-5 Minuten)
|
||||
|
||||
### 6.4 Wartbarkeit
|
||||
|
||||
- Klare Test-Namen (`test_<functionality>_<scenario>`)
|
||||
- Dokumentation in Test-Docstrings
|
||||
- Keine Hardcoded-Pfade (nutze `os.path`)
|
||||
|
||||
---
|
||||
|
||||
## 7. Debugging & Diagnose
|
||||
|
||||
### 7.1 Test-Debugging
|
||||
|
||||
**Pytest Debug-Modus:**
|
||||
```bash
|
||||
pytest tests/test_retriever_basic.py -v --pdb
|
||||
```
|
||||
|
||||
**Einzelnen Test inspizieren:**
|
||||
```bash
|
||||
python3 -m scripts.payload_dryrun --vault ./test_vault --note-id "test-note"
|
||||
```
|
||||
|
||||
### 7.2 Qdrant-State prüfen
|
||||
|
||||
```bash
|
||||
# Collection-Status
|
||||
python3 -m scripts.debug_qdrant_state --prefix mindnet_test
|
||||
|
||||
# Payload-Indexe prüfen
|
||||
python3 -m scripts.diag_payload_indexes --prefix mindnet_test
|
||||
```
|
||||
|
||||
### 7.3 Chunk-Inspektion
|
||||
|
||||
```bash
|
||||
# Chunks für eine Note anzeigen
|
||||
python3 -m scripts.dump_note_chunks --note-id "test-note" --prefix mindnet_test
|
||||
|
||||
# Chunk-Text-Verifikation
|
||||
python3 -m scripts.verify_chunk_texts --prefix mindnet_test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Test-Checkliste für Pull Requests
|
||||
|
||||
Vor jedem PR sollten folgende Tests durchlaufen:
|
||||
|
||||
- [ ] Unit Tests: `pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py`
|
||||
- [ ] Payload-Validierung: `python3 -m scripts.payload_dryrun --vault ./test_vault`
|
||||
- [ ] Graph-Integrität: `python3 -m scripts.edges_full_check`
|
||||
- [ ] Smoke Test (wenn API läuft): `python tests/test_wp06_decision.py -p 8002`
|
||||
|
||||
---
|
||||
|
||||
## 9. Weitere Informationen
|
||||
|
||||
- **Developer Guide:** Siehe [Developer Guide](05_developer_guide.md)
|
||||
- **Scripts-Übersicht:** Siehe [Developer Guide - Scripts](05_developer_guide.md#44-scripts--tooling-die-admin-toolbox)
|
||||
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2025-01-XX
|
||||
**Version:** 2.9.1
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Branch Merge Commit Message: WP4d
|
||||
|
||||
```
|
||||
feat: Section-basierte Links, Atomic Section Chunking & Registry-First Profiling (v2.9.1)
|
||||
|
||||
## Graph Topology & Edge Management
|
||||
|
||||
### Section-basierte Links (Multigraph-Support)
|
||||
- Split `[[Note#Section]]` Links in `target_id="Note"` und `target_section="Section"`
|
||||
- Edge-ID enthält nun `variant` (Section), ermöglicht mehrere Kanten zwischen denselben Knoten
|
||||
- Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key
|
||||
- Behebt "Phantom-Knoten" durch korrekte Trennung von Note-Name und Abschnitt
|
||||
|
||||
**Geänderte Dateien:**
|
||||
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion
|
||||
- `app/core/graph/graph_derive_edges.py`: `target_section` in Edge-Payload
|
||||
- `app/core/database/qdrant.py`: Keyword-Index für `target_section`
|
||||
- `app/core/database/qdrant_points.py`: Explizites Durchreichen von `target_section`
|
||||
- `app/models/dto.py`: `EdgeDTO` mit `target_section` Feld
|
||||
|
||||
### Extraction & Parsing Verbesserungen
|
||||
- Multi-line Callout-Blocks korrekt verarbeitet (stop-check logic)
|
||||
- Robuster Fallback für "headless" Blocks (split chunks)
|
||||
- Liberalisierte Regex für Umlaute und Sonderzeichen in Targets
|
||||
|
||||
**Geänderte Dateien:**
|
||||
- `app/core/graph/graph_extractors.py`: Multi-line Callout-Parser, erweiterte Regex
|
||||
|
||||
## Chunking & Ingestion (v3.9.9 / v2.13.12)
|
||||
|
||||
### Atomic Section Logic (v3.9.9)
|
||||
- Vollständige Implementierung des "Pack-and-Carry-Over" Verfahrens (Regel 1-3)
|
||||
- Sektions-Überschriften und Inhalte bleiben atomar in Chunks
|
||||
- H1-Context Preservation: Dokumenttitel als Breadcrumb in Embedding-Fenster
|
||||
- Signature Alignment: Parameter-Synchronisierung (`context_prefix` statt `doc_title`)
|
||||
|
||||
**Geänderte Dateien:**
|
||||
- `app/core/chunking/chunking_strategies.py`: Atomic Section Logic implementiert
|
||||
|
||||
### Format-agnostische De-Duplizierung
|
||||
- Prüfung auf vorhandene Kanten basiert auf Ziel (`target`), nicht String-Match
|
||||
- Verhindert Dopplung von Kanten, die bereits via `[!edge]` Callout vorhanden sind
|
||||
- Global Pool Integration für unzugeordnete Kanten
|
||||
|
||||
**Geänderte Dateien:**
|
||||
- `app/core/chunking/chunking_propagation.py`: Ziel-basierte Prüfung
|
||||
|
||||
### Registry-First Profiling (v2.13.12)
|
||||
- Korrekte Hierarchie: Frontmatter > types.yaml Typ-Config > Global Defaults
|
||||
- Hard-Fallback auf `sliding_standard` nur wenn keine Konfiguration existiert
|
||||
- Automatische Anwendung korrekter Profile basierend auf Note-Typ
|
||||
|
||||
### Deterministic Hashing
|
||||
- `full`-Hash inkludiert strategische Parameter (`split_level`, `strict_heading_split`)
|
||||
- Konfigurationsänderungen im Frontmatter lösen zwingend Re-Import aus
|
||||
|
||||
**Geänderte Dateien:**
|
||||
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling, Deterministic Hashing
|
||||
|
||||
## Impact & Breaking Changes
|
||||
|
||||
### Migration erforderlich
|
||||
**WICHTIG:** Vollständiger Re-Import erforderlich für bestehende Vaults:
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||
```
|
||||
|
||||
**Grund:**
|
||||
- Behebt "Phantom-Knoten" durch korrekte Aufteilung von `[[Note#Section]]` Links
|
||||
- Konsolidiert Edge-Struktur mit `target_section` Feld
|
||||
- Aktualisiert Chunking basierend auf neuen Strategien
|
||||
|
||||
### Fixes
|
||||
- ✅ Resolves: Mehrere Links zur gleichen Note in einem Callout-Block wurden zu einer Kante gemergt
|
||||
- ✅ Resolves: "Phantom-Knoten" durch Einbeziehung des Anchors in `target_id`
|
||||
- ✅ Resolves: Redundante `[[rel:...]]` Links in Chunks
|
||||
- ✅ Resolves: Inkonsistente Metadaten in Qdrant durch Registry-First Profiling
|
||||
|
||||
## Dokumentation
|
||||
|
||||
Alle relevanten Dokumente aktualisiert:
|
||||
- `03_tech_data_model.md`: Edge Payload Schema mit `target_section`
|
||||
- `02_concept_graph_logic.md`: Section-basierte Links & Multigraph-Support
|
||||
- `03_tech_ingestion_pipeline.md`: Chunking-Strategien, Registry-First Profiling
|
||||
- `03_tech_api_reference.md`: EdgeDTO mit `target_section`
|
||||
- `01_knowledge_design.md`: Deep-Links dokumentiert
|
||||
- `00_glossary.md`: Neue Begriffe ergänzt
|
||||
- `04_admin_operations.md`: Migration-Hinweis
|
||||
|
||||
## Versionen
|
||||
|
||||
- Graph Topology: v2.9.1
|
||||
- Chunking Strategies: v3.9.9
|
||||
- Ingestion Processor: v2.13.12
|
||||
- API DTO: v0.6.7
|
||||
|
||||
Closes #[issue-number]
|
||||
```
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
# Release Notes: Mindnet v2.9.1 (WP4d)
|
||||
|
||||
**Release Date:** 2025-01-XX
|
||||
**Type:** Feature Release mit Breaking Changes
|
||||
**Branch:** WP4d
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Übersicht
|
||||
|
||||
Diese Version führt **Section-basierte Links** ein, verbessert das Chunking durch **Atomic Section Logic** und implementiert **Registry-First Profiling** für konsistentere Konfigurationsauflösung. Die Änderungen erfordern einen **vollständigen Re-Import** bestehender Vaults.
|
||||
|
||||
---
|
||||
|
||||
## ✨ Neue Features
|
||||
|
||||
### Section-basierte Links (Deep-Links)
|
||||
|
||||
Mindnet unterstützt nun **Deep-Links** zu spezifischen Abschnitten innerhalb einer Note:
|
||||
|
||||
```markdown
|
||||
[[rel:based_on Mein Leitbild#P3 – Disziplin]]
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- Mehrere Links zur gleichen Note möglich (verschiedene Sections)
|
||||
- Präzise Kontext-Ladung (nur relevanter Abschnitt)
|
||||
- Keine "Phantom-Knoten" mehr durch korrekte Trennung von Note-Name und Abschnitt
|
||||
|
||||
**Technische Details:**
|
||||
- Links werden in `target_id="Note"` und `target_section="Section"` aufgeteilt
|
||||
- Edge-ID enthält `variant` (Section) für Multigraph-Support
|
||||
- Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key
|
||||
|
||||
### Atomic Section Logic (Chunking v3.9.9)
|
||||
|
||||
Das Chunking hält nun Sektions-Überschriften und deren Inhalte **atomar** zusammen:
|
||||
|
||||
**"Pack-and-Carry-Over" Verfahren:**
|
||||
- Regel 1 & 2: Sektionen werden zusammengepackt, wenn sie in den Token-Limit passen
|
||||
- Regel 3: Zu große Sektionen werden intelligent zerlegt, Rest wird zurück in Queue gelegt
|
||||
- H1-Context Preservation: Dokumenttitel wird als Breadcrumb in alle Chunks injiziert
|
||||
|
||||
**Vorteile:**
|
||||
- Keine getrennten Überschriften mehr
|
||||
- Bessere semantische Kohärenz in Chunks
|
||||
- Verbesserte Retrieval-Qualität durch vollständigen Kontext
|
||||
|
||||
### Registry-First Profiling (v2.13.12)
|
||||
|
||||
Die Konfigurationsauflösung folgt nun einer klaren Hierarchie:
|
||||
|
||||
1. **Frontmatter** (höchste Priorität)
|
||||
2. **types.yaml Typ-Config**
|
||||
3. **Global Defaults**
|
||||
|
||||
**Impact:**
|
||||
- Note-Typen wie `value` erhalten automatisch das korrekte Profil (`structured_smart_edges_strict`)
|
||||
- Keine manuellen Overrides mehr nötig für Standard-Typen
|
||||
- Konsistente Metadaten in Qdrant
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Verbesserungen
|
||||
|
||||
### Extraction & Parsing
|
||||
|
||||
- **Multi-line Callout-Blocks:** Korrekte Verarbeitung von mehrzeiligen `[!edge]` Callouts
|
||||
- **Robuste Fallbacks:** "Headless" Blocks werden korrekt behandelt
|
||||
- **Liberalisierte Regex:** Unterstützung für Umlaute und Sonderzeichen in Link-Targets
|
||||
|
||||
### Format-agnostische De-Duplizierung
|
||||
|
||||
- Kanten werden unabhängig vom Format (Inline, Callout, Wikilink) erkannt
|
||||
- Verhindert Dopplungen, wenn Kanten bereits via `[!edge]` Callout vorhanden sind
|
||||
- Ziel-basierte Prüfung statt String-Match
|
||||
|
||||
### Deterministic Hashing
|
||||
|
||||
- `full`-Hash inkludiert strategische Parameter (`split_level`, `strict_heading_split`)
|
||||
- Konfigurationsänderungen im Frontmatter lösen zwingend Re-Import aus
|
||||
- Zuverlässigere Change Detection
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Bugfixes
|
||||
|
||||
- ✅ **Behoben:** Mehrere Links zur gleichen Note in einem Callout-Block wurden zu einer Kante gemergt
|
||||
- ✅ **Behoben:** "Phantom-Knoten" durch Einbeziehung des Anchors in `target_id`
|
||||
- ✅ **Behoben:** Redundante `[[rel:...]]` Links in Chunks
|
||||
- ✅ **Behoben:** Inkonsistente Metadaten in Qdrant durch fehlerhafte Profil-Auflösung
|
||||
- ✅ **Behoben:** `TypeError` durch Parameter-Mismatch zwischen Orchestrator und Strategien
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Breaking Changes & Migration
|
||||
|
||||
### Migration erforderlich
|
||||
|
||||
**WICHTIG:** Nach dem Update auf v2.9.1 ist ein **vollständiger Re-Import** erforderlich:
|
||||
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||
```
|
||||
|
||||
**Warum?**
|
||||
- Behebt "Phantom-Knoten" durch korrekte Aufteilung von `[[Note#Section]]` Links
|
||||
- Konsolidiert Edge-Struktur mit neuem `target_section` Feld
|
||||
- Aktualisiert Chunking basierend auf Atomic Section Logic
|
||||
|
||||
**Was passiert beim Re-Import?**
|
||||
- Alle bestehenden Links werden neu geparst und in `target_id` + `target_section` aufgeteilt
|
||||
- Chunks werden mit neuer Atomic Section Logic neu generiert
|
||||
- Edge-Struktur wird konsolidiert (Multigraph-Support)
|
||||
|
||||
**Dauer:** Abhängig von Vault-Größe (typischerweise 5-30 Minuten)
|
||||
|
||||
---
|
||||
|
||||
## 📚 API-Änderungen
|
||||
|
||||
### EdgeDTO erweitert
|
||||
|
||||
```python
|
||||
class EdgeDTO(BaseModel):
|
||||
# ... bestehende Felder ...
|
||||
target_section: Optional[str] = None # Neu: Abschnitts-Name
|
||||
```
|
||||
|
||||
**Impact für API-Consumer:**
|
||||
- Graph-Endpunkte (`/graph/{note_id}`) enthalten nun `target_section` in Edge-Objekten
|
||||
- Frontend kann Section-Informationen für präzisere Visualisierung nutzen
|
||||
|
||||
---
|
||||
|
||||
## 📖 Dokumentation
|
||||
|
||||
Alle relevanten Dokumente wurden aktualisiert:
|
||||
|
||||
- ✅ `03_tech_data_model.md`: Edge Payload Schema mit `target_section`
|
||||
- ✅ `02_concept_graph_logic.md`: Section-basierte Links & Multigraph-Support
|
||||
- ✅ `03_tech_ingestion_pipeline.md`: Chunking-Strategien, Registry-First Profiling
|
||||
- ✅ `03_tech_api_reference.md`: EdgeDTO mit `target_section`
|
||||
- ✅ `01_knowledge_design.md`: Deep-Links dokumentiert
|
||||
- ✅ `00_glossary.md`: Neue Begriffe ergänzt
|
||||
- ✅ `04_admin_operations.md`: Migration-Hinweis
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Technische Details
|
||||
|
||||
### Geänderte Module
|
||||
|
||||
**Graph Topology:**
|
||||
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion
|
||||
- `app/core/graph/graph_derive_edges.py`: `target_section` in Edge-Payload
|
||||
- `app/core/graph/graph_extractors.py`: Multi-line Callout-Parser
|
||||
|
||||
**Chunking:**
|
||||
- `app/core/chunking/chunking_strategies.py`: Atomic Section Logic (v3.9.9)
|
||||
- `app/core/chunking/chunking_propagation.py`: Format-agnostische De-Duplizierung
|
||||
|
||||
**Ingestion:**
|
||||
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling (v2.13.12), Deterministic Hashing
|
||||
|
||||
**Database:**
|
||||
- `app/core/database/qdrant.py`: Keyword-Index für `target_section`
|
||||
- `app/core/database/qdrant_points.py`: Explizites Durchreichen von `target_section`
|
||||
|
||||
**API:**
|
||||
- `app/models/dto.py`: `EdgeDTO` mit `target_section` Feld (v0.6.7)
|
||||
|
||||
### Versionsnummern
|
||||
|
||||
- Graph Topology: **v2.9.1**
|
||||
- Chunking Strategies: **v3.9.9**
|
||||
- Ingestion Processor: **v2.13.12**
|
||||
- API DTO: **v0.6.7**
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Upgrade-Pfad
|
||||
|
||||
### Für Administratoren
|
||||
|
||||
1. **Backup erstellen:**
|
||||
```bash
|
||||
docker stop qdrant
|
||||
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_data
|
||||
docker start qdrant
|
||||
```
|
||||
|
||||
2. **Code aktualisieren:**
|
||||
```bash
|
||||
git pull origin main
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. **Re-Import durchführen:**
|
||||
```bash
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||
```
|
||||
|
||||
4. **Services neu starten:**
|
||||
```bash
|
||||
sudo systemctl restart mindnet-prod
|
||||
sudo systemctl restart mindnet-ui-prod
|
||||
```
|
||||
|
||||
### Für Entwickler
|
||||
|
||||
- Keine Code-Änderungen erforderlich, wenn nur API genutzt wird
|
||||
- Frontend kann `target_section` Feld in Edge-Objekten nutzen (optional)
|
||||
|
||||
---
|
||||
|
||||
## 📝 Bekannte Einschränkungen
|
||||
|
||||
- **Migration-Dauer:** Große Vaults (>10.000 Notizen) können 30+ Minuten benötigen
|
||||
- **Temporärer Speicher:** Während des Re-Imports kann Qdrant-Speicher temporär ansteigen
|
||||
|
||||
---
|
||||
|
||||
## 🙏 Danksagungen
|
||||
|
||||
Diese Version wurde durch umfangreiche Code-Analyse und Dokumentationsprüfung ermöglicht. Besonderer Fokus lag auf:
|
||||
- Konsistenz zwischen Code und Dokumentation
|
||||
- Vollständige Abdeckung aller Rollen (Entwickler, Administratoren, Anwender, Tester, Deployment)
|
||||
- Klare Migration-Pfade
|
||||
|
||||
---
|
||||
|
||||
**Vollständige Changelog:** Siehe Git-Commits für detaillierte Änderungen
|
||||
**Support:** Bei Fragen zur Migration siehe [Admin Operations Guide](../04_Operations/04_admin_operations.md)
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
---
|
||||
doc_type: documentation_index
|
||||
audience: all
|
||||
status: active
|
||||
version: 2.9.1
|
||||
context: "Zentraler Einstiegspunkt für die Mindnet-Dokumentation"
|
||||
---
|
||||
|
||||
# Mindnet Dokumentation
|
||||
|
||||
Willkommen in der Dokumentation von Mindnet v2.9.1! Diese Dokumentation hilft dir dabei, das System zu verstehen, zu nutzen und weiterzuentwickeln.
|
||||
|
||||
## 🚀 Schnellstart
|
||||
|
||||
**Neu hier?** Beginne mit diesen Dokumenten:
|
||||
|
||||
1. **[Vision & Strategie](00_General/00_vision_and_strategy.md)** - Verstehe die Ziele und Prinzipien von Mindnet
|
||||
2. **[Glossar](00_General/00_glossary.md)** - Lerne die wichtigsten Begriffe kennen
|
||||
3. **[Dokumentationskarte](00_General/00_documentation_map.md)** - Finde schnell die richtige Dokumentation
|
||||
|
||||
**Je nach Rolle:**
|
||||
|
||||
- **👤 Benutzer/Autor:** Starte mit [Chat Usage Guide](01_User_Manual/01_chat_usage_guide.md) und [Knowledge Design](01_User_Manual/01_knowledge_design.md)
|
||||
- **👨💻 Entwickler:** Beginne mit [Developer Guide](05_Development/05_developer_guide.md)
|
||||
- **🔧 Administrator:** Siehe [Admin Operations](04_Operations/04_admin_operations.md)
|
||||
|
||||
## 📚 Dokumentationsstruktur
|
||||
|
||||
Die Dokumentation ist in logische Bereiche unterteilt:
|
||||
|
||||
### 00_General (Grundlagen)
|
||||
Grundlegende Informationen für alle Zielgruppen:
|
||||
- Vision & Strategie
|
||||
- Glossar
|
||||
- Dokumentationskarte (Navigation)
|
||||
|
||||
### 01_User_Manual (Anwendung)
|
||||
Anleitungen für Endbenutzer und Autoren:
|
||||
- Chat-Bedienung
|
||||
- Knowledge Design (Content-Regeln)
|
||||
- Authoring Guidelines
|
||||
- Obsidian-Integration
|
||||
|
||||
### 02_Concepts (Fachliche Logik)
|
||||
Konzeptionelle Erklärungen für Architekten:
|
||||
- Graph-Logik
|
||||
- KI-Persönlichkeit & Router
|
||||
|
||||
### 03_Technical_Reference (Technik & Code)
|
||||
Detaillierte technische Referenzen für Entwickler:
|
||||
- Datenmodell
|
||||
- Ingestion-Pipeline
|
||||
- Retrieval & Scoring
|
||||
- Chat-Backend
|
||||
- Frontend-Architektur
|
||||
- Konfiguration
|
||||
|
||||
### 04_Operations (Betrieb)
|
||||
Betriebsanleitungen für Administratoren:
|
||||
- Admin Operations (Installation, Backup, Troubleshooting)
|
||||
- Server Operations Manual (Systemd, Disaster Recovery)
|
||||
|
||||
### 05_Development (Entwicklung)
|
||||
Entwickler-Ressourcen:
|
||||
- Developer Guide (Workflow, Architektur, Module)
|
||||
- GenAI Best Practices (Prompt-Library)
|
||||
|
||||
### 06_Roadmap (Planung)
|
||||
Projektplanung und Roadmap:
|
||||
- Active Roadmap (aktuelle Workpackages)
|
||||
- Handover Prompts (Übergabe-Prompts für neue Entwickler)
|
||||
|
||||
### 99_Archive (Archiv)
|
||||
Historische Dokumentation:
|
||||
- Legacy Workpackages (abgeschlossene WPs)
|
||||
|
||||
## 🔍 Navigation nach Rolle
|
||||
|
||||
### 👨💻 Entwickler
|
||||
| Frage | Dokument |
|
||||
|-------|----------|
|
||||
| Wie richte ich meine Entwicklungsumgebung ein? | [Developer Guide](05_Development/05_developer_guide.md#6-lokales-setup-development) |
|
||||
| Wie ist die Architektur aufgebaut? | [Architektur-Patterns](02_concepts/02_concept_architecture_patterns.md) |
|
||||
| Wie erweitere ich das System? | [Developer Guide - Teach-the-AI](05_Development/05_developer_guide.md#8-erweiterungs-guide-teach-the-ai) |
|
||||
| Wie teste ich meine Änderungen? | [Testing Guide](05_Development/05_testing_guide.md) |
|
||||
| Welche API-Endpunkte gibt es? | [API Reference](03_Technical_References/03_tech_api_reference.md) |
|
||||
|
||||
### 🔧 Administratoren
|
||||
| Frage | Dokument |
|
||||
|-------|----------|
|
||||
| Wie installiere ich Mindnet? | [Admin Operations](04_Operations/04_admin_operations.md#1-installation--setup) |
|
||||
| Wie konfiguriere ich die Services? | [Admin Operations - Deployment](04_Operations/04_admin_operations.md#2-deployment-systemd-services) |
|
||||
| Wie führe ich Backups durch? | [Admin Operations - Backup](04_Operations/04_admin_operations.md#4-backup--restore) |
|
||||
| Was tun bei Problemen? | [Admin Operations - Troubleshooting](04_Operations/04_admin_operations.md#33-troubleshooting-guide) |
|
||||
| Wie betreibe ich den Server? | [Server Operations Manual](04_Operations/04_server_operation_manual.md) |
|
||||
|
||||
### 👤 Anwender
|
||||
| Frage | Dokument |
|
||||
|-------|----------|
|
||||
| Wie starte ich mit Mindnet? | [Schnellstart](00_General/00_quickstart.md) |
|
||||
| Wie nutze ich den Chat? | [Chat Usage Guide](01_User_Manual/01_chat_usage_guide.md) |
|
||||
| Wie strukturiere ich meine Notizen? | [Knowledge Design](01_User_Manual/01_knowledge_design.md) |
|
||||
| Wie schreibe ich für den Digitalen Zwilling? | [Authoring Guidelines](01_User_Manual/01_authoring_guidelines.md) |
|
||||
| Wie integriere ich Obsidian? | [Obsidian Integration](01_User_Manual/01_obsidian_integration_guide.md) |
|
||||
|
||||
### 🧪 Tester
|
||||
| Frage | Dokument |
|
||||
|-------|----------|
|
||||
| Welche Test-Strategien gibt es? | [Testing Guide - Strategien](05_Development/05_testing_guide.md#1-test-strategie--ebenen) |
|
||||
| Wie führe ich Tests aus? | [Testing Guide - Frameworks](05_Development/05_testing_guide.md#3-test-frameworks--tools) |
|
||||
| Wie erstelle ich Test-Daten? | [Testing Guide - Test-Daten](05_Development/05_testing_guide.md#2-test-daten--vaults) |
|
||||
| Was ist die Test-Checkliste? | [Testing Guide - Checkliste](05_Development/05_testing_guide.md#8-test-checkliste-für-pull-requests) |
|
||||
|
||||
### 🚀 Deployment
|
||||
| Frage | Dokument |
|
||||
|-------|----------|
|
||||
| Wie deploye ich automatisch? | [Deployment Guide - CI/CD](04_Operations/04_deployment_guide.md#9-cicd-pipeline-details) |
|
||||
| Welche Rollout-Strategien gibt es? | [Deployment Guide - Rollout](04_Operations/04_deployment_guide.md#4-rollout-strategien) |
|
||||
| Wie führe ich einen Rollback durch? | [Deployment Guide - Rollback](04_Operations/04_deployment_guide.md#6-rollback-strategien) |
|
||||
| Was muss vor dem Deployment geprüft werden? | [Deployment Guide - Checkliste](04_Operations/04_deployment_guide.md#7-pre-deployment-checkliste) |
|
||||
|
||||
## 📖 Dokumentationsprinzipien
|
||||
|
||||
Diese Dokumentation folgt klaren Prinzipien:
|
||||
|
||||
1. **Single Source of Truth:** Informationen werden nicht dupliziert, sondern referenziert
|
||||
2. **Konkrete Beispiele:** Technische Dokumente enthalten immer Code-Snippets
|
||||
3. **Human Readable:** Benutzerhandbücher enthalten Narrative und Szenarien
|
||||
4. **KI-Optimiert:** Jede Datei hat YAML-Frontmatter für bessere RAG-Integration
|
||||
|
||||
## 🔄 Dokumentation aktualisieren
|
||||
|
||||
Wenn du an einem Feature arbeitest, nutze die [Maintenance Matrix](00_General/00_documentation_map.md#3-maintenance-guide-welche-datei-muss-ich-ändern) in der Dokumentationskarte, um zu sehen, welche Dateien aktualisiert werden müssen.
|
||||
|
||||
## ✅ Qualitätsprüfung
|
||||
|
||||
Die Dokumentation wurde systematisch für alle Rollen geprüft:
|
||||
- **Entwickler:** Setup, Architektur, Code, Testing, Debugging ✅
|
||||
- **Administratoren:** Installation, Betrieb, Wartung, Backup, DR ✅
|
||||
- **Anwender:** Nutzung, Content-Erstellung, Workflows ✅
|
||||
- **Tester:** Test-Strategien, Frameworks, Tools ✅
|
||||
- **Deployment:** CI/CD, Rollout, Versionierung, Rollback ✅
|
||||
|
||||
Siehe [Qualitäts-Checkliste](00_General/00_quality_checklist.md) für Details.
|
||||
|
||||
## 💡 Feedback
|
||||
|
||||
Falls du Verbesserungsvorschläge für die Dokumentation hast oder Fehler findest, melde diese bitte im Repository.
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2025-01-XX
|
||||
**Version:** 2.9.1
|
||||
|
||||
@@ -1,18 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests/assert_payload_schema.py (compat v1.1)
|
||||
FILE: scripts/assert_payload_schema.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Prüft, ob die erwarteten Payload-Indizes (payload_schema) auf den drei Collections vorhanden sind.
|
||||
Kompatibel mit älteren qdrant-client Versionen (ohne with_payload_schema im Wrapper).
|
||||
Zweck:
|
||||
-------
|
||||
Prüft, ob die erwarteten Payload-Indizes auf allen Collections vorhanden sind.
|
||||
Validiert Schema-Integrität für CI/CD und Wartung.
|
||||
|
||||
Collections & Pflichtfelder:
|
||||
- mindnet_notes : note_id, type, title, updated, tags
|
||||
- mindnet_chunks : note_id, chunk_id, index, type, tags
|
||||
- mindnet_edges : note_id, kind, scope, source_id, target_id, chunk_id
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Ermittelt Collections für das Präfix (notes, chunks, edges)
|
||||
2. Lädt Payload-Schema für jede Collection
|
||||
3. Prüft, ob alle Pflichtfelder indiziert sind:
|
||||
- notes: note_id, type, title, updated, tags
|
||||
- chunks: note_id, chunk_id, index, type, tags
|
||||
- edges: note_id, kind, scope, source_id, target_id, chunk_id
|
||||
4. Gibt Validierungs-Ergebnis aus
|
||||
|
||||
Nutzung:
|
||||
python3 -m tests.assert_payload_schema
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Validierungs-Ergebnissen
|
||||
* collections: Schema-Status pro Collection
|
||||
* missing: Fehlende Indizes
|
||||
* valid: true/false
|
||||
- Exit-Code 0: Alle Indizes vorhanden
|
||||
- Exit-Code 1: Fehlende Indizes gefunden
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- CI/CD-Validierung nach ensure_payload_indexes
|
||||
- Diagnose von Index-Problemen
|
||||
- Wartung und Audit
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Kompatibel mit verschiedenen qdrant-client Versionen
|
||||
- Nutzt Fallback-Strategie für Schema-Abfrage
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.assert_payload_schema --prefix mindnet
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.1.0: Kompatibilität mit verschiedenen qdrant-client Versionen
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,7 +64,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
REQUIRED = {
|
||||
"notes": ["note_id", "type", "title", "updated", "tags"],
|
||||
|
||||
@@ -1,4 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/audit_chunks.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Audit-Tool zur Analyse der Chunk-Qualität im Vault.
|
||||
Erkennt Probleme wie überdimensionierte Chunks, leere Chunks und defekte Nachbarschafts-Links.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle Markdown-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Erzeugt Chunks via assemble_chunks
|
||||
- Prüft Token-Anzahl pro Chunk
|
||||
- Validiert Nachbarschafts-Links (prev/next)
|
||||
3. Aggregiert Statistiken und identifiziert Probleme
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Zusammenfassung
|
||||
* notes: Anzahl verarbeiteter Notizen
|
||||
* chunks_total: Gesamtanzahl Chunks
|
||||
* chunks_per_note_avg: Durchschnittliche Chunks pro Note
|
||||
* tokens_avg: Durchschnittliche Token pro Chunk
|
||||
* tokens_p95: 95. Perzentil der Token-Verteilung
|
||||
* issues_counts: Anzahl gefundener Probleme
|
||||
- Zusätzlich: Liste der ersten 20 Probleme pro Kategorie
|
||||
* oversize: Chunks > 600 Tokens
|
||||
* broken_neighbors: Defekte prev/next Links
|
||||
* empty: Leere Chunks (0 Tokens)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Qualitätskontrolle nach Chunking-Änderungen
|
||||
- Identifikation von Problemen vor dem Import
|
||||
- Monitoring der Chunk-Verteilung
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt synchrones assemble_chunks (kann async sein)
|
||||
- Heuristik für Oversize: > 600 Tokens
|
||||
- Prüft nur strukturelle Integrität, keine semantische Qualität
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.audit_chunks --vault ./vault
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, json, glob, statistics as stats
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
||||
|
||||
@@ -1,34 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script: audit_edges_vs_expectations.py — Prüfe Kanten in Qdrant gegen Vault-Erwartungen
|
||||
Version: 1.0.0
|
||||
Datum: 2025-09-09
|
||||
FILE: scripts/audit_edges_vs_expectations.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck
|
||||
-----
|
||||
- Liest Edges/Chunks/Notes aus Qdrant.
|
||||
- Ermittelt erwartete Kanten-Anzahlen aus dem Vault:
|
||||
* belongs_to : sollte == #Chunks
|
||||
* next / prev : je Note (#Chunks_in_Note - 1)
|
||||
* references : Summe aller Chunk-Wikilinks
|
||||
* backlink : Summe einzigartiger Wikilinks pro Note (Note-Level)
|
||||
- Vergleicht IST vs. SOLL und meldet Abweichungen.
|
||||
|
||||
ENV/Qdrant
|
||||
----------
|
||||
QDRANT_URL, QDRANT_API_KEY (optional), COLLECTION_PREFIX (Default: mindnet)
|
||||
|
||||
Aufrufe
|
||||
Zweck:
|
||||
-------
|
||||
# Gesamtaudit
|
||||
python3 -m scripts.audit_edges_vs_expectations --vault ./test_vault
|
||||
Prüft Edge-Anzahlen in Qdrant gegen erwartete Werte aus dem Vault.
|
||||
Validiert strukturelle Integrität des Graphen.
|
||||
|
||||
# Mit anderem Prefix
|
||||
python3 -m scripts.audit_edges_vs_expectations --vault ./test_vault --prefix mindnet_dev
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Liest Edges/Chunks/Notes aus Qdrant
|
||||
2. Ermittelt erwartete Edge-Anzahlen aus Vault:
|
||||
- belongs_to: sollte == #Chunks pro Note
|
||||
- next/prev: je Note (#Chunks - 1)
|
||||
- references: Summe aller Chunk-Wikilinks
|
||||
- backlink: Summe einzigartiger Wikilinks (Note-Level)
|
||||
3. Vergleicht IST vs. SOLL
|
||||
4. Meldet Abweichungen
|
||||
|
||||
# Details anzeigen
|
||||
python3 -m scripts.audit_edges_vs_expectations --vault ./test_vault --details
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Vergleichs-Ergebnissen
|
||||
* expected: Erwartete Edge-Anzahlen
|
||||
* actual: Tatsächliche Edge-Anzahlen
|
||||
* discrepancies: Abweichungen
|
||||
* per_note: Details pro Note (mit --details)
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Validierung nach Importen
|
||||
- Debugging von Edge-Problemen
|
||||
- Qualitätskontrolle
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Prüft strukturelle, nicht semantische Korrektheit
|
||||
- Kann bei großen Vaults langsam sein
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.audit_edges_vs_expectations --vault ./vault
|
||||
python3 -m scripts.audit_edges_vs_expectations --vault ./vault --prefix mindnet_dev --details
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--prefix TEXT Collection-Präfix (Default: mindnet)
|
||||
--details Zeigt Details pro Note
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
QDRANT_URL, QDRANT_API_KEY (optional), COLLECTION_PREFIX
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0 (2025-09-09): Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,38 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: scripts/audit_vault_vs_qdrant.py
|
||||
Version: v1.0.0 (2025-09-05)
|
||||
Kurzbeschreibung:
|
||||
Prüft die Konsistenz zwischen Obsidian-Vault und Qdrant:
|
||||
- Zählt Markdown-Dateien mit gültiger Frontmatter (title, id, type, status, created).
|
||||
- Zählt Wikilink-Vorkommen im Vault (regex wie in derive_edges.py).
|
||||
- Liest Zählungen aus Qdrant (Notes/Chunks/Edges je kind).
|
||||
- Vergleicht erwartete Wikilink-Anzahl (Vault) vs. tatsächlich importierte Edges (Qdrant).
|
||||
- Listet Auffälligkeiten pro Note (z. B. Wikilinks im Vault, aber keine references in Qdrant).
|
||||
FILE: scripts/audit_vault_vs_qdrant.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Aufruf (aus Projekt-Root, im venv):
|
||||
python3 -m scripts.audit_vault_vs_qdrant --vault ./vault --prefix mindnet
|
||||
Zweck:
|
||||
-------
|
||||
Prüft Konsistenz zwischen Vault und Qdrant.
|
||||
Vergleicht erwartete vs. tatsächliche Edge-Anzahlen.
|
||||
|
||||
Parameter:
|
||||
--vault Pfad zum Vault (z. B. ./vault)
|
||||
--prefix Collection-Prefix in Qdrant (Default: mindnet)
|
||||
--limit Max. Punkte pro Scroll-Seite aus Qdrant (Default: 1000)
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt Vault:
|
||||
- Zählt Markdown-Dateien mit gültiger Frontmatter
|
||||
- Zählt Wikilink-Vorkommen (regex wie in derive_edges.py)
|
||||
2. Liest Qdrant:
|
||||
- Zählt Notes/Chunks/Edges
|
||||
- Gruppiert Edges nach kind
|
||||
3. Vergleicht:
|
||||
- Erwartete Wikilink-Anzahl (Vault) vs. references (Qdrant)
|
||||
- Listet Auffälligkeiten pro Note
|
||||
|
||||
Voraussetzungen:
|
||||
- Aktives Python venv mit installiertem qdrant-client.
|
||||
- Zugriff auf Qdrant per ENV (QDRANT_URL, QDRANT_API_KEY optional).
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Vergleichs-Ergebnissen
|
||||
* vault_stats: Zählungen aus Vault
|
||||
* qdrant_stats: Zählungen aus Qdrant
|
||||
* discrepancies: Abweichungen und Auffälligkeiten
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Konsistenz-Check nach Importen
|
||||
- Validierung der Edge-Erzeugung
|
||||
- Debugging von fehlenden Links
|
||||
|
||||
Hinweise:
|
||||
- Der Wikilink-Regex entspricht dem in app/core/derive_edges.py verwendeten Muster. (Quelle: derive_edges.py) # :contentReference[oaicite:3]{index=3}
|
||||
- Pflicht-Frontmatter wird wie in app/core/parser.py geprüft. (Quelle: parser.py) # :contentReference[oaicite:4]{index=4}
|
||||
- Collection-Namen & 1D-Edge-Vektoren folgen app/core/qdrant.py / qdrant_points.py. (Quellen: qdrant.py, qdrant_points.py) #
|
||||
---------
|
||||
- Wikilink-Regex entspricht derive_edges.py
|
||||
- Prüft strukturelle, nicht semantische Korrektheit
|
||||
|
||||
Changelog:
|
||||
v1.0.0: Erste Version.
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.audit_vault_vs_qdrant --vault ./vault --prefix mindnet
|
||||
|
||||
Autor:
|
||||
mindnet – Datenimporte & Sync
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--prefix TEXT Collection-Präfix (Default: mindnet)
|
||||
--limit INT Max. Punkte pro Scroll-Seite (Default: 1000)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0 (2025-09-05): Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, glob, re, json
|
||||
|
||||
@@ -1,12 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/backfill_edges.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Füllt fehlende Edges nach, indem es Wikilinks aus dem Vault extrahiert
|
||||
und in Qdrant schreibt. Nützlich nach Migrationen oder wenn Edges verloren gingen.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle Markdown-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Erstellt Note-Stub (minimaler Payload)
|
||||
- Erstellt einen Chunk mit dem gesamten Body
|
||||
- Extrahiert Wikilinks via derive_wikilink_edges
|
||||
3. Baut Lookup-Index (Titel/Alias -> note_id)
|
||||
4. Löst Wikilinks auf und erzeugt Edges
|
||||
5. Schreibt Edges in Qdrant
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Statistiken
|
||||
* notes_scanned: Anzahl verarbeiteter Notizen
|
||||
* edges_upserted: Anzahl geschriebener Edges
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Nach Migrationen oder Datenverlust
|
||||
- Wenn Edges fehlen oder unvollständig sind
|
||||
- Zur Reparatur des Graphen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Überschreibt existierende Edges (kein Merge)
|
||||
- Nutzt vereinfachtes Chunking (1 Chunk = gesamter Body)
|
||||
- Erzeugt nur Wikilink-Edges, keine anderen Edge-Typen
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.backfill_edges --vault ./vault
|
||||
python3 -m scripts.backfill_edges --vault ./vault --exclude /.obsidian/ /_backup/
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--exclude PATH Pfade zum Ausschließen (Default: /.obsidian/, /_backup_frontmatter/)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, glob, json, os
|
||||
from typing import List, Tuple
|
||||
|
||||
from app.core.parser import read_markdown # gibt je nach Implementierung ein Objekt ODER ein (fm, body)-Tuple
|
||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections
|
||||
from app.core.qdrant_points import points_for_edges, upsert_batch
|
||||
from app.core.derive_edges import build_note_index, derive_wikilink_edges
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, ensure_collections
|
||||
from app.core.database.qdrant_points import points_for_edges, upsert_batch
|
||||
# TODO: build_note_index und derive_wikilink_edges müssen noch implementiert werden
|
||||
# from app.core.graph.graph_derive_edges import build_note_index, derive_wikilink_edges
|
||||
|
||||
|
||||
def _coerce_parsed(note_or_tuple):
|
||||
|
||||
@@ -1,3 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/debug_edge_loss.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Debug-Tool)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Debug-Tool zur Analyse von Edge-Verlust-Problemen bei der Chunk-Verarbeitung.
|
||||
Hilft zu verstehen, warum bestimmte Edges nicht erkannt oder verloren gehen.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Analysiert eine einzelne Markdown-Datei
|
||||
2. Führt zwei Analyseschritte durch:
|
||||
a) Pre-Scan: Extrahiert alle Edge-Kandidaten aus dem rohen Text
|
||||
- Wikilinks
|
||||
- Typed Relations
|
||||
- Callout Relations
|
||||
b) Chunk-Analyse:
|
||||
- Erstellt Chunks mit konfigurierbarem Profil
|
||||
- Prüft, welche Edges in jedem Chunk gefunden werden
|
||||
- Vergleicht mit Pre-Scan-Ergebnissen
|
||||
3. Gibt detaillierte Analyse pro Chunk aus
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- [1] Globale Kandidaten: Alle Edge-Kandidaten, die im Text vorhanden sind
|
||||
- [2] Chunk-Struktur: Für jeden Chunk:
|
||||
* Section-Pfad
|
||||
* Text-Snippet
|
||||
* Gefundene explizite Kanten (callout:edge, inline:rel)
|
||||
* Warnung, falls Callout im Text vorhanden, aber nicht erkannt
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Debugging von Edge-Verlust bei Chunk-Grenzen
|
||||
- Validierung der Edge-Extraktion in verschiedenen Chunk-Kontexten
|
||||
- Analyse von Problemen mit Callout-Erkennung
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Asynchrones Skript (nutzt assemble_chunks async API)
|
||||
- Konfigurierbares Chunking-Profil (Standard: sliding_window, 400/600 chars)
|
||||
- Smart Edge Allocation ist standardmäßig deaktiviert für klare Analyse
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 scripts/debug_edge_loss.py [PFAD_ZUR_DATEI.md]
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
Keine CLI-Parameter. Dateipfad als erstes Argument oder Standard-Pfad.
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Entfernt: _extract_all_edges_from_md (nicht mehr vorhanden)
|
||||
- Ersetzt durch: extract_wikilinks, extract_typed_relations, extract_callout_relations
|
||||
- Chunk-Payload-Struktur angepasst (window, type hinzugefügt)
|
||||
v1.0.0: Erster Release
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
@@ -6,8 +70,10 @@ from pathlib import Path
|
||||
# Pfad-Setup
|
||||
sys.path.insert(0, os.path.abspath("."))
|
||||
|
||||
from app.core.chunking import assemble_chunks, _extract_all_edges_from_md
|
||||
from app.core.derive_edges import build_edges_for_note
|
||||
from app.core.chunking import assemble_chunks
|
||||
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||
from app.core.parser import extract_wikilinks
|
||||
from app.core.graph.graph_extractors import extract_typed_relations, extract_callout_relations
|
||||
|
||||
# Mock für Settings, falls nötig
|
||||
os.environ["MINDNET_LLM_MODEL"] = "phi3:mini"
|
||||
@@ -19,9 +85,25 @@ async def analyze_file(file_path: str):
|
||||
text = f.read()
|
||||
|
||||
# 1. Globale Kandidaten (Was sieht der Pre-Scan?)
|
||||
# Wir simulieren den Aufruf, den der Chunker macht
|
||||
# Wir extrahieren alle Edge-Kandidaten aus dem Text
|
||||
note_id = Path(file_path).stem
|
||||
candidates = _extract_all_edges_from_md(text, note_id, "concept")
|
||||
candidates = []
|
||||
|
||||
# Wikilinks extrahieren
|
||||
wikilinks = extract_wikilinks(text)
|
||||
for wl in wikilinks:
|
||||
candidates.append(f"wikilink:{wl}")
|
||||
|
||||
# Typed Relations extrahieren
|
||||
typed_rels, _ = extract_typed_relations(text)
|
||||
for kind, target in typed_rels:
|
||||
candidates.append(f"typed:{kind}:{target}")
|
||||
|
||||
# Callout Relations extrahieren
|
||||
callout_rels, _ = extract_callout_relations(text)
|
||||
for kind, target in callout_rels:
|
||||
candidates.append(f"callout:{kind}:{target}")
|
||||
|
||||
print(f"\n[1] Globale Kandidaten (Pre-Scan):")
|
||||
for c in candidates:
|
||||
print(f" - {c}")
|
||||
@@ -45,7 +127,12 @@ async def analyze_file(file_path: str):
|
||||
|
||||
# Was findet derive_edges in diesem rohen Chunk?
|
||||
# Wir simulieren das Payload-Dict, das derive_edges erwartet
|
||||
chunk_pl = {"text": chunk.text, "window": chunk.window, "chunk_id": chunk.id}
|
||||
chunk_pl = {
|
||||
"text": chunk.text,
|
||||
"window": chunk.window or chunk.text,
|
||||
"chunk_id": chunk.id,
|
||||
"type": "concept"
|
||||
}
|
||||
edges = build_edges_for_note(note_id, [chunk_pl])
|
||||
|
||||
found_explicitly = [f"{e['kind']}:{e.get('target_id')}" for e in edges if e['rule_id'] in ['callout:edge', 'inline:rel']]
|
||||
|
||||
@@ -1,15 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/debug_note_payload.py
|
||||
Zeigt, welche app.core.note_payload geladen wird, ruft make_note_payload auf
|
||||
und druckt Typ/Preview der Rückgabe.
|
||||
FILE: scripts/debug_note_payload.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Debug-Tool)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Debug-Tool zur Analyse der Note-Payload-Erzeugung.
|
||||
Zeigt, welches Modul geladen wird und die erzeugte Payload-Struktur.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Lädt Note-Payload-Modul
|
||||
2. Liest Markdown-Datei
|
||||
3. Ruft make_note_payload auf
|
||||
4. Zeigt Modul-Pfad, Rückgabe-Typ und Payload-Inhalt
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Debug-Informationen
|
||||
* module_path: Pfad zum geladenen Modul
|
||||
* return_type: Typ der Rückgabe
|
||||
* keys: Liste der Payload-Keys (falls Dict)
|
||||
* JSON: Vollständige Payload (falls Dict)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Debugging von Payload-Erzeugungsproblemen
|
||||
- Validierung der Modul-Ladung
|
||||
- Analyse der Payload-Struktur
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt app.core.ingestion.ingestion_note_payload (nicht mehr app.core.note_payload)
|
||||
- Zeigt vollständige Payload-Struktur
|
||||
|
||||
Aufruf:
|
||||
python3 -m scripts.debug_note_payload --file ./test_vault/40_concepts/concept-alpha.md --vault-root ./test_vault
|
||||
-------
|
||||
python3 -m scripts.debug_note_payload --file ./vault/note.md --vault-root ./vault
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--file PATH Pfad zur Markdown-Datei (erforderlich)
|
||||
--vault-root PATH Vault-Root für relative Pfade (optional)
|
||||
--hash-mode MODE Hash-Modus (optional)
|
||||
--hash-normalize N Hash-Normalisierung (optional)
|
||||
--hash-source SRC Hash-Quelle (optional)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Geändert: app.core.note_payload → app.core.ingestion.ingestion_note_payload
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
import argparse, json, os, pprint
|
||||
from app.core import note_payload as np
|
||||
from app.core.ingestion import ingestion_note_payload as np
|
||||
from app.core.parser import read_markdown
|
||||
|
||||
def main():
|
||||
@@ -24,7 +71,6 @@ def main():
|
||||
print("module_path:", getattr(np, "__file__", "<unknown>"))
|
||||
parsed = read_markdown(args.file)
|
||||
res = np.make_note_payload(parsed, vault_root=args.vault_root,
|
||||
hash_mode=args.hash_mode,
|
||||
hash_normalize=args.hash_normalize,
|
||||
hash_source=args.hash_source,
|
||||
file_path=args.file)
|
||||
|
||||
@@ -1,18 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/debug_qdrant_state.py
|
||||
Zeigt Prefix, Collections und einfache Counts (notes/chunks/edges) + sample note_ids.
|
||||
FILE: scripts/debug_qdrant_state.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Debug-Tool)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Zeigt schnelle Übersicht über den Qdrant-Zustand.
|
||||
Gibt Prefix, Collections, Punkt-Anzahlen und Beispiel-IDs aus.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Verbindet mit Qdrant
|
||||
2. Ermittelt Collections für das Präfix
|
||||
3. Zählt Points in jeder Collection
|
||||
4. Extrahiert Beispiel-IDs (erste 5)
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Zustands-Übersicht
|
||||
* prefix: Collection-Präfix
|
||||
* collections: Namen der Collections
|
||||
* counts: Punkt-Anzahlen pro Collection
|
||||
* samples: Beispiel-IDs pro Collection
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Schnelle Status-Prüfung
|
||||
- Debugging von Verbindungsproblemen
|
||||
- Validierung der Collection-Struktur
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt count() für exakte Zählung (falls verfügbar)
|
||||
- Fallback auf scroll() bei Problemen
|
||||
|
||||
Aufruf:
|
||||
export COLLECTION_PREFIX="mindnet"
|
||||
python3 -m scripts.debug_qdrant_state
|
||||
# oder:
|
||||
python3 -m scripts.debug_qdrant_state --prefix mindnet
|
||||
-------
|
||||
python3 -m scripts.debug_qdrant_state
|
||||
python3 -m scripts.debug_qdrant_state --prefix mindnet_dev
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, json
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
def count_points(client, collection: str) -> int:
|
||||
try:
|
||||
|
||||
@@ -1,13 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/diag_payload_indexes.py (compat v1.2)
|
||||
FILE: scripts/diag_payload_indexes.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zeigt payload_schema je Collection; kompatibel mit älteren qdrant-client Versionen.
|
||||
Strategie (in dieser Reihenfolge):
|
||||
1) openapi_client.collections_api.get_collection(..., with_payload_schema=True)
|
||||
2) client.get_collection(...)
|
||||
3) HTTP GET /collections/{name}?with_payload_schema=true
|
||||
Zweck:
|
||||
-------
|
||||
Zeigt das Payload-Schema (Indizes) für alle Collections eines Präfixes.
|
||||
Nützlich zur Diagnose von Index-Problemen oder Validierung der Schema-Struktur.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Ermittelt Collections für das Präfix (notes, chunks, edges)
|
||||
2. Für jede Collection:
|
||||
- Versucht Payload-Schema über verschiedene Methoden zu laden:
|
||||
* qdrant-client API (get_collection)
|
||||
* HTTP GET direkt (Fallback)
|
||||
- Zeigt Schema als JSON
|
||||
3. Gibt Schema-Übersicht aus
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON pro Collection mit payload_schema
|
||||
- Zeigt vorhandene Indizes (keyword, text) und deren Konfiguration
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Diagnose von Index-Problemen
|
||||
- Validierung nach ensure_payload_indexes
|
||||
- Dokumentation der Schema-Struktur
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Kompatibel mit verschiedenen qdrant-client Versionen
|
||||
- Nutzt Fallback-Strategie für maximale Kompatibilität
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.diag_payload_indexes --prefix mindnet
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.2.0: Kompatibilität mit verschiedenen qdrant-client Versionen
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,7 +60,7 @@ import urllib.request
|
||||
import urllib.error
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
|
||||
@@ -1,4 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/dump_note_chunks.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Gibt die Chunks einer bestimmten Note in lesbarer Form aus.
|
||||
Nützlich zur Analyse der Chunk-Struktur und -Inhalte.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Sucht Note nach note-id im Vault
|
||||
2. Erzeugt Chunks via assemble_chunks
|
||||
3. Gibt Chunks formatiert aus:
|
||||
- Chunk-ID, Token-Anzahl, Section-Pfad
|
||||
- Vollständiger Chunk-Text
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Formatierter Text
|
||||
* Header: "# Titel (note-id) — X chunks"
|
||||
* Pro Chunk: "--- chunk_id | tokens | section_path ---"
|
||||
* Gefolgt vom Chunk-Text
|
||||
- Exit-Code 0: Erfolgreich
|
||||
- Fehlermeldung, wenn Note nicht gefunden
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Analyse der Chunk-Struktur einer spezifischen Note
|
||||
- Debugging von Chunking-Problemen
|
||||
- Validierung der Chunk-Inhalte
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt synchrones assemble_chunks (kann async sein)
|
||||
- Gibt nur erste gefundene Note aus (bei Duplikaten)
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.dump_note_chunks --vault ./vault --note-id my-note-id
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--note-id ID Note-ID zum Dumpen (erforderlich)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, glob
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
||||
|
||||
+63
-15
@@ -1,22 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# scripts/edges_dryrun.py
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Dry-Run: Erzeuge Edges aus einem Vault **ohne** Qdrant-Upsert.
|
||||
- Liest Markdown mit YAML-Frontmatter
|
||||
- Chunking: einfacher Absatz-Chunker (Index + text)
|
||||
- Kanten: nutzt app.core.edges.build_edges_for_note()
|
||||
- Ausgabe: JSON pro Note mit Edge-Counts und 3 Beispiel-Payloads
|
||||
FILE: scripts/edges_dryrun.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Simuliert die Edge-Erzeugung aus Markdown-Dateien ohne Datenbank-Upsert.
|
||||
Nützlich zur Analyse, welche Kanten aus einem Vault generiert würden.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle .md-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Parst Markdown mit Frontmatter
|
||||
- Erstellt einfache Absatz-basierte Chunks (vereinfachtes Chunking)
|
||||
- Extrahiert Edge-Kandidaten via build_edges_for_note():
|
||||
* Wikilinks [[...]]
|
||||
* Typed Relations [[rel:KIND|Target]]
|
||||
* Callout Relations [!edge] KIND: [[Target]]
|
||||
* Struktur-Kanten (belongs_to, next, prev)
|
||||
- Zählt Edges nach Typ (kind/relation)
|
||||
3. Gibt JSON-Report aus mit Edge-Statistiken pro Note
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON-Array mit einem Objekt pro Note
|
||||
- Jedes Objekt enthält:
|
||||
* path: Dateipfad
|
||||
* note_id: Note-Identifier
|
||||
* type: Note-Typ
|
||||
* chunks: Anzahl der Chunks
|
||||
* edges_total: Gesamtanzahl der Edges
|
||||
* edges_by_kind: Dictionary mit Edge-Anzahl pro Typ
|
||||
* samples: Erste 3 Edges als Beispiele
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Analyse der Graph-Struktur vor dem Import
|
||||
- Debugging von fehlenden oder unerwarteten Edges
|
||||
- Validierung der Edge-Extraktion-Logik
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Verwendet vereinfachtes Chunking (Absatz-basiert), nicht das vollständige Chunking-System
|
||||
- Edge-Extraktion entspricht der Produktions-Logik (app.core.derive_edges)
|
||||
- Keine Datenbank-Operationen, rein analytisch
|
||||
|
||||
Aufruf:
|
||||
python3 -m scripts.edges_dryrun --vault ./vault
|
||||
-------
|
||||
python3 -m scripts.edges_dryrun --vault ./vault
|
||||
python3 -m scripts.edges_dryrun --vault ./vault --include-note-scope-refs
|
||||
|
||||
Optional:
|
||||
--include-note-scope-refs # auch Frontmatter-Links (links[].target_id) als Note-Scope-Referenzen
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--include-note-scope-refs Berücksichtigt auch Frontmatter-Links (links[].target_id)
|
||||
|
||||
Voraussetzungen:
|
||||
- app/core/parser.py (read_markdown, normalize_frontmatter)
|
||||
- app/core/edges.py (dieses Modul forwardet zur v2-Implementierung)
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Geändert: app.core.edges → app.core.derive_edges
|
||||
- Parameter korrigiert: chunk_payloads → chunks, note_level_refs → note_level_references
|
||||
v1.0.0: Erster Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -28,7 +76,7 @@ from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from app.core.parser import read_markdown, normalize_frontmatter
|
||||
from app.core.edges import build_edges_for_note
|
||||
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||
|
||||
def _iter_markdown(vault: str):
|
||||
for p in Path(vault).rglob("*.md"):
|
||||
@@ -83,8 +131,8 @@ def main():
|
||||
|
||||
edges = build_edges_for_note(
|
||||
note_id=note_id,
|
||||
chunk_payloads=chunks,
|
||||
note_level_refs=note_refs,
|
||||
chunks=chunks,
|
||||
note_level_references=note_refs,
|
||||
include_note_scope_refs=include_note_scope,
|
||||
)
|
||||
kinds = {}
|
||||
|
||||
+58
-13
@@ -1,19 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/edges_full_check.py
|
||||
Zählt und validiert Kanten in Qdrant. Erkennt folgende Rule-Gruppen:
|
||||
- explicit_total: rule_id startswith "explicit:" (z.B. explicit:wikilink, explicit:note_scope)
|
||||
- callout_total: rule_id == "callout:edge"
|
||||
- inline_total: rule_id startswith "inline:" (z.B. inline:rel)
|
||||
- defaults_total: rule_id startswith "edge_defaults:"
|
||||
- structure: rule_id in {"structure:belongs_to","structure:order"}
|
||||
FILE: scripts/edges_full_check.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Gibt zusätzlich:
|
||||
- edges_by_kind (aggregiert)
|
||||
- notes/chunks/edges Anzahlen
|
||||
- multi_callout_detected: True, falls ein Chunk mehrere Callout-Ziele der gleichen Relation enthält
|
||||
- per_note_checks: belongs_to == chunks, next == prev == (chunks-1)
|
||||
Zweck:
|
||||
-------
|
||||
Umfassende Validierung der Edge-Struktur in Qdrant.
|
||||
Analysiert Edge-Typen, Rule-Gruppen und strukturelle Integrität.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Lädt alle Edges aus {prefix}_edges
|
||||
2. Gruppiert Edges nach rule_id:
|
||||
- explicit: rule_id startswith "explicit:" (wikilink, note_scope)
|
||||
- callout: rule_id == "callout:edge"
|
||||
- inline: rule_id startswith "inline:" (rel)
|
||||
- defaults: rule_id startswith "edge_defaults:"
|
||||
- structure: rule_id in {"structure:belongs_to", "structure:order"}
|
||||
3. Prüft strukturelle Integrität:
|
||||
- belongs_to == chunks pro Note
|
||||
- next == prev == (chunks-1) pro Note
|
||||
- Multi-Callout-Erkennung
|
||||
4. Aggregiert Statistiken
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit umfassender Analyse
|
||||
* counts: notes/chunks/edges Anzahlen
|
||||
* edges_by_kind: Aggregierte Edge-Anzahl pro Typ
|
||||
* rule_groups: Zählung nach Rule-Gruppen
|
||||
* per_note_checks: Strukturelle Validierung pro Note
|
||||
* multi_callout_detected: Boolean
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Umfassende Graph-Analyse
|
||||
- Validierung nach größeren Änderungen
|
||||
- Debugging von Edge-Problemen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Kann bei großen Graphen langsam sein
|
||||
- Prüft strukturelle, nicht semantische Korrektheit
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.edges_full_check --prefix mindnet
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,7 +67,7 @@ import json
|
||||
from collections import Counter, defaultdict
|
||||
from typing import Dict, Any, List, Tuple
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
|
||||
|
||||
+64
-30
@@ -1,39 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script: scripts/export_markdown.py — Qdrant → Markdown (Vault)
|
||||
Version: 1.4.1
|
||||
Datum: 2025-09-10
|
||||
FILE: scripts/export_markdown.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Funktion
|
||||
--------
|
||||
Exportiert Notes (Frontmatter + Body) aus Qdrant in einen Zielordner. Der Body wird
|
||||
bevorzugt aus dem Feld `fulltext` rekonstruiert; falls leer/nicht vorhanden, aus Chunks
|
||||
(Sortierung: seq → chunk_index → Nummer in chunk_id). Pfade werden **relativ** geschrieben.
|
||||
Zweck:
|
||||
-------
|
||||
Exportiert Notes (Frontmatter + Body) aus Qdrant zurück in Markdown-Dateien.
|
||||
Nützlich für Backup, Migration oder Notfall-Wiederherstellung.
|
||||
|
||||
Optionen
|
||||
--------
|
||||
--out PATH Zielordner (erforderlich)
|
||||
--prefix TEXT Collection-Prefix (CLI überschreibt ENV COLLECTION_PREFIX)
|
||||
--note-id ID Nur eine Note exportieren
|
||||
--overwrite Existierende Dateien überschreiben
|
||||
--include-edges MODE none|yaml|footer (Default: none)
|
||||
--flatten-paths Alle Dateien flach schreiben; Originalpfad in FM: orig_path
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Liest alle Notes aus Qdrant (Collection: {prefix}_notes)
|
||||
2. Für jede Note:
|
||||
- Rekonstruiert Frontmatter aus Payload-Feldern
|
||||
- Rekonstruiert Body:
|
||||
* Primär: aus `fulltext` Feld (falls vorhanden)
|
||||
* Fallback: aus Chunks (sortiert nach seq → chunk_index → chunk_id)
|
||||
- Optional: Fügt Edges als Links hinzu (yaml/footer)
|
||||
3. Schreibt Markdown-Dateien mit relativen Pfaden
|
||||
|
||||
ENV
|
||||
---
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON pro Datei mit note_id, path, decision (write/skip-exists)
|
||||
- Abschluss: "Done. Exported notes: X"
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Backup vor größeren Änderungen
|
||||
- Migration zwischen Instanzen
|
||||
- Notfall-Wiederherstellung bei Vault-Verlust
|
||||
- Analyse der in Qdrant gespeicherten Daten
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Pfade werden relativ geschrieben (wie im Original-Vault)
|
||||
- --flatten-paths: Alle Dateien in einen Ordner (orig_path in Frontmatter)
|
||||
- Body-Rekonstruktion aus Chunks kann bei sehr langen Dokumenten unvollständig sein
|
||||
- Edge-Export optional (none/yaml/footer)
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.export_markdown --out ./_exportVault
|
||||
python3 -m scripts.export_markdown --out ./_exportVault --note-id concept-alpha --include-edges yaml
|
||||
python3 -m scripts.export_markdown --out ./_exportVault --flatten-paths --overwrite
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--out PATH Zielordner für exportierte Markdown-Dateien (erforderlich)
|
||||
--prefix TEXT Collection-Präfix (überschreibt ENV COLLECTION_PREFIX)
|
||||
--note-id ID Nur eine bestimmte Note-ID exportieren (optional)
|
||||
--overwrite Existierende Dateien überschreiben (sonst skip)
|
||||
--include-edges MODE none|yaml|footer (Default: none)
|
||||
- none: Keine Edges
|
||||
- yaml: Als YAML-Feld 'references' im Frontmatter
|
||||
- footer: Als Markdown-Links am Ende
|
||||
--flatten-paths Alle Dateien flach schreiben (orig_path in Frontmatter)
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
COLLECTION_PREFIX, QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
|
||||
|
||||
Beispiele
|
||||
---------
|
||||
export COLLECTION_PREFIX="mindnet"
|
||||
python3 -m scripts.export_markdown --out ./_exportVault
|
||||
|
||||
# Nur eine Note, Edges als YAML-Feld 'references'
|
||||
python3 -m scripts.export_markdown --out ./_exportVault --note-id concept-alpha --include-edges yaml
|
||||
|
||||
# Flach schreiben mit Überschreiben
|
||||
python3 -m scripts.export_markdown --out ./_exportVault --flatten-paths --overwrite
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Aktualisiert: Import-Pfade für neue Struktur
|
||||
v1.4.1 (2025-09-10): Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,8 +80,7 @@ from typing import Dict, List, Optional, Tuple, Any
|
||||
import yaml
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.qdrant import ensure_collections # safety
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, ensure_collections
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Helpers
|
||||
|
||||
@@ -1,4 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/fix_frontmatter.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Repariert oder ergänzt fehlende Frontmatter-Felder in Markdown-Dateien.
|
||||
Erzeugt stabile IDs, erkennt Typen und erstellt vollständige Frontmatter-Struktur.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle Markdown-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Liest vorhandenes Frontmatter
|
||||
- Erkennt fehlende Felder (id, title, type, created)
|
||||
- Generiert fehlende Werte:
|
||||
* id: Stabile ID aus Pfad, Titel und Datum
|
||||
* title: Aus H1, Dateiname oder "Untitled"
|
||||
* type: Aus Pfad/Tags (journal, task, project, etc.)
|
||||
* created: Aus Dateiname oder mtime
|
||||
- Validiert Payload (optional)
|
||||
- Schreibt korrigiertes Frontmatter zurück
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON pro Datei mit Änderungen
|
||||
* path: Dateipfad
|
||||
* changes: Dict mit alten/neuen Werten
|
||||
* backup_path: Pfad zur Backup-Datei (falls --backup)
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Migration von Legacy-Vaults ohne Frontmatter
|
||||
- Reparatur beschädigter Frontmatter
|
||||
- Standardisierung von Frontmatter-Strukturen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Erstellt Backups vor Änderungen (mit --backup)
|
||||
- Idempotent: Überspringt bereits vollständige Frontmatter
|
||||
- Nutzt Heuristiken für Typ-Erkennung (Pfad/Tags)
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.fix_frontmatter --vault ./vault --apply
|
||||
python3 -m scripts.fix_frontmatter --vault ./vault --backup --apply
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--backup Erstellt Backup-Dateien vor Änderungen
|
||||
--apply Führt tatsächliche Änderungen durch (sonst Dry-Run)
|
||||
--validate Validiert Note-Payload nach Fix
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
- Hinweis: validate_note_payload existiert nicht mehr (wird entfernt)
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, re, sys, json, shutil, time, hashlib
|
||||
from dataclasses import dataclass
|
||||
@@ -6,7 +70,7 @@ from typing import Dict, Tuple, Optional, List
|
||||
from slugify import slugify
|
||||
from app.core.parser import read_markdown, normalize_frontmatter
|
||||
from app.core.parser import FRONTMATTER_RE # für Re-Inject
|
||||
from app.core.validate_note import validate_note_payload
|
||||
# NOTE: validate_note_payload existiert nicht mehr - entfernt
|
||||
from app.core.ingestion.ingestion_note_payload import make_note_payload
|
||||
|
||||
DATE_IN_NAME = re.compile(r"(?P<y>\d{4})[-_\.]?(?P<m>\d{2})[-_\.]?(?P<d>\d{2})")
|
||||
|
||||
@@ -1,50 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
# scripts/gc_qdrant_after_vault_scan.py
|
||||
# Version: 1.0.0 (2025-09-05)
|
||||
#
|
||||
# Zweck
|
||||
# -----
|
||||
# Garbage-Collector für Qdrant: löscht Einträge (Edges, Chunks, Notes), deren Note-ID
|
||||
# nicht mehr im Obsidian-Vault vorhanden ist. So bleiben Vektorindex/Graph mit dem Vault konsistent.
|
||||
#
|
||||
# Aufrufparameter
|
||||
# ---------------
|
||||
# --vault PATH Pfad zum Obsidian-Vault (z. B. ./vault) [erforderlich]
|
||||
# --mode {edges,content,all}
|
||||
# edges -> nur Kanten mit source_id/target_id ∉ Vault-Notes löschen
|
||||
# content -> Chunks & Notes löschen, deren note_id ∉ Vault-Notes (keine Edges)
|
||||
# all -> zuerst edges, dann content
|
||||
# --prefix PREFIX Collection-Präfix (Default: aus ENV COLLECTION_PREFIX oder "mindnet")
|
||||
# --apply Ohne diesen Schalter: Dry-Run (nur Vorschau). Mit Schalter: ausführen.
|
||||
# --yes Sicherheitsabfrage überspringen (non-interaktiv)
|
||||
# --batch-size N Größe für In-Filter (Default: 1000)
|
||||
#
|
||||
# Hinweise
|
||||
# --------
|
||||
# - Benötigt funktionierendes Python-venv mit allen Abhängigkeiten von mindnet (qdrant-client usw.).
|
||||
# - Läuft gegen die drei Collections {prefix}_notes, {prefix}_chunks, {prefix}_edges (keine anderen Projekte).
|
||||
# - Nutzt OR-Filter (Filter.should) korrekt, keine minimum_should (Pydantic v2 lässt die Option nicht zu).
|
||||
#
|
||||
# Änderungen ggü. vorher
|
||||
# ----------------------
|
||||
# - Neu: eigenes GC-Tool; berührt ausschließlich das übergebene Projekt-Präfix.
|
||||
# - Sichere Dry-Run-Vorschau mit Zählung pro Collection; interaktive Bestätigung.
|
||||
# - Löscht Edges mittels Filter auf (source_id ∈ MISSING) ODER (target_id ∈ MISSING).
|
||||
# - Löscht Chunks/Notes mittels Filter auf note_id ∈ MISSING.
|
||||
#
|
||||
# Beispiele
|
||||
# ---------
|
||||
# DRY RUN: python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode all
|
||||
# APPLY: python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode all --apply
|
||||
# CI-Modus: python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode edges --apply --yes
|
||||
#
|
||||
# Kompatibilität / Kontext
|
||||
# ------------------------
|
||||
# - Frontmatter-Validierung & Parsing wie im Projekt (parser.read_markdown, validate_required_frontmatter). :contentReference[oaicite:0]{index=0}
|
||||
# - Note-Payload-Schema (u. a. note_id, hash_fulltext) wie spezifiziert. :contentReference[oaicite:1]{index=1}
|
||||
# - Collection-Namen & Anlage-Logik über app.core.qdrant (notes/chunks = dim, edges = 1D). :contentReference[oaicite:2]{index=2}
|
||||
# - Edges nutzen Felder source_id/target_id; Chunks/Notes tragen note_id in payload. :contentReference[oaicite:3]{index=3} :contentReference[oaicite:4]{index=4}
|
||||
#
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/gc_qdrant_after_vault_scan.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Garbage-Collector für Qdrant: löscht Einträge, deren Note-ID nicht mehr
|
||||
im Vault vorhanden ist. Hält Vektorindex/Graph mit dem Vault konsistent.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt Vault und sammelt alle note_ids
|
||||
2. Lädt note_ids aus Qdrant
|
||||
3. Berechnet Differenz (verwaiste IDs)
|
||||
4. Löscht verwaiste Einträge:
|
||||
- mode=edges: Nur Edges mit source_id/target_id ∉ Vault
|
||||
- mode=content: Chunks & Notes mit note_id ∉ Vault
|
||||
- mode=all: Zuerst edges, dann content
|
||||
5. Nutzt Batch-Filter für effiziente Löschung
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Preview und Statistiken
|
||||
* mode: DRY-RUN oder APPLY
|
||||
* vault_note_ids: Anzahl Notizen im Vault
|
||||
* qdrant_note_ids: Anzahl Notizen in Qdrant
|
||||
* orphans: Anzahl verwaister Notizen
|
||||
* deleted: Anzahl gelöschter Einträge (nach --apply)
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Regelmäßige Wartung nach Vault-Bereinigung
|
||||
- Konsistenz-Check zwischen Vault und Datenbank
|
||||
- Vor Migrationen
|
||||
|
||||
Sicherheitsmerkmale:
|
||||
-------------------
|
||||
- Dry-Run standardmäßig (keine Änderungen ohne --apply)
|
||||
- Interaktive Bestätigung (außer mit --yes)
|
||||
- Nur betroffene Collections werden geändert
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode all
|
||||
python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode all --apply
|
||||
python3 -m scripts.gc_qdrant_after_vault_scan --vault ./vault --mode edges --apply --yes
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--mode MODE edges | content | all (Default: all)
|
||||
- edges: Nur Edges löschen
|
||||
- content: Nur Chunks & Notes löschen
|
||||
- all: Beides (zuerst edges, dann content)
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
--apply Führt tatsächliches Löschen durch (sonst Dry-Run)
|
||||
--yes Keine interaktive Bestätigung
|
||||
--batch-size N Batch-Größe für Filter (Default: 1000)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Aktualisiert: Import-Pfade für neue Struktur
|
||||
v1.0.0 (2025-09-05): Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, glob, json, sys
|
||||
from typing import Iterable, Set, Tuple, List
|
||||
@@ -54,7 +77,7 @@ from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter # :contentReference[oaicite:5]{index=5}
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names # :contentReference[oaicite:6]{index=6}
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names # :contentReference[oaicite:6]{index=6}
|
||||
|
||||
def iter_note_ids_from_vault(vault_root: str) -> Set[str]:
|
||||
"""Liest alle Markdown-Dateien im Vault und sammelt valide Frontmatter-IDs."""
|
||||
|
||||
@@ -1,40 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/health_check_mindnet.py
|
||||
FILE: scripts/health_check_mindnet.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Health-Check für den mindnet-Retriever-/Query-Endpoint.
|
||||
Zweck:
|
||||
-------
|
||||
Health-Check für den mindnet /query-Retriever-Endpoint.
|
||||
Prüft Verfügbarkeit, Antwortzeit und Ergebnisqualität.
|
||||
|
||||
Funktion:
|
||||
- Führt POST-Requests auf /query in verschiedenen Modi aus (standard: semantic + hybrid).
|
||||
- Prüft Status-Code, JSON-Struktur und Anzahl der Treffer.
|
||||
- Kennzeichnet Probleme als:
|
||||
- status="ok"
|
||||
- status="warning" (z.B. Timeout)
|
||||
- status="error" (harte Fehler wie HTTP-Fehler, JSON-Fehler etc.)
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Führt POST-Requests auf /query in verschiedenen Modi aus
|
||||
2. Prüft für jeden Modus:
|
||||
- HTTP-Status-Code (erwartet 200)
|
||||
- JSON-Struktur (erwartet Objekt mit results-Array)
|
||||
- Anzahl der Treffer (mindestens min-results)
|
||||
- Antwortzeit (Latency)
|
||||
3. Klassifiziert Ergebnisse:
|
||||
- ok: Alles in Ordnung
|
||||
- warning: Timeout oder unerwartetes Verhalten
|
||||
- error: HTTP-Fehler, JSON-Fehler, zu wenige Ergebnisse
|
||||
|
||||
Exit-Code:
|
||||
- Default (tolerant):
|
||||
- overall_status = "ok" (inkl. warnings) → Exit-Code 0
|
||||
- overall_status = "error" → Exit-Code 1
|
||||
- Mit --strict:
|
||||
- warnings werden wie errors behandelt → Exit-Code 1
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Menschlich lesbare Zusammenfassung + JSON-Report
|
||||
- overall_status: ok | warning | error
|
||||
- Exit-Code 0: ok (tolerant) oder ok/warning (strict)
|
||||
- Exit-Code 1: error (tolerant) oder warning/error (strict)
|
||||
|
||||
Beispiele:
|
||||
Verwendung:
|
||||
-----------
|
||||
- Monitoring und Alerting (z.B. cronjob)
|
||||
- CI/CD-Pipelines (Validierung nach Deployment)
|
||||
- Debugging von Performance-Problemen
|
||||
- Integration in externe Monitoring-Tools (n8n, etc.)
|
||||
|
||||
python scripts/health_check_mindnet.py \
|
||||
--url http://127.0.0.1:8001/query \
|
||||
--query "embeddings" \
|
||||
--top-k 3
|
||||
Hinweise:
|
||||
---------
|
||||
- Standard: Prüft semantic und hybrid Modi
|
||||
- Tolerant: Warnings führen nicht zu Exit-Code 1
|
||||
- Strict: Warnings werden wie Errors behandelt
|
||||
- JSON-Ausgabe für maschinelle Weiterverarbeitung
|
||||
|
||||
python scripts/health_check_mindnet.py \
|
||||
--url http://127.0.0.1:8001/query \
|
||||
--query "embeddings" \
|
||||
--top-k 3 \
|
||||
--timeout 15 \
|
||||
--modes hybrid
|
||||
Aufruf:
|
||||
-------
|
||||
python3 scripts/health_check_mindnet.py --url http://127.0.0.1:8001/query
|
||||
python3 scripts/health_check_mindnet.py --query "test" --top-k 5 --modes semantic hybrid
|
||||
python3 scripts/health_check_mindnet.py --strict
|
||||
|
||||
# Strenger Modus (warnings → Exit-Code 1)
|
||||
python scripts/health_check_mindnet.py --strict
|
||||
Parameter:
|
||||
----------
|
||||
--url URL Vollständige URL des /query-Endpunkts (Default: http://127.0.0.1:8001/query)
|
||||
--query TEXT Test-Query (Default: embeddings)
|
||||
--top-k INT Anzahl der erwarteten Ergebnisse (Default: 3)
|
||||
--timeout FLOAT Timeout in Sekunden pro Request (Default: 5.0)
|
||||
--modes LIST Zu prüfende Modi (Default: semantic hybrid)
|
||||
--min-results INT Minimale Anzahl erwarteter Ergebnisse (Default: 1)
|
||||
--strict Warnings als Fehler behandeln (Exit-Code 1 bei warnings)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,11 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/import_markdown.py
|
||||
CLI-Tool zum Importieren von Markdown-Dateien in Qdrant.
|
||||
WP-15b: Implementiert den Two-Pass Workflow (Pre-Scan + Processing).
|
||||
Sorgt dafür, dass der LocalBatchCache vor der Verarbeitung robust gefüllt wird.
|
||||
Indiziert Notizen nach ID, Titel und Dateiname für maximale Link-Kompatibilität.
|
||||
VERSION: 2.4.1
|
||||
FILE: scripts/import_markdown.py
|
||||
VERSION: 2.4.1 (2025-12-15)
|
||||
STATUS: Active (Core)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Hauptwerkzeug zum Importieren von Markdown-Dateien aus einem Vault in Qdrant.
|
||||
Implementiert den Two-Pass Workflow (WP-15b) für robuste Edge-Validierung.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. PASS 1: Global Pre-Scan
|
||||
- Scannt alle Markdown-Dateien im Vault
|
||||
- Extrahiert Note-Kontext (ID, Titel, Dateiname)
|
||||
- Füllt LocalBatchCache für semantische Edge-Validierung
|
||||
- Indiziert nach ID, Titel und Dateiname für Link-Auflösung
|
||||
|
||||
2. PASS 2: Semantic Processing
|
||||
- Verarbeitet Dateien in Batches (20 Dateien, max. 5 parallel)
|
||||
- Nutzt gefüllten Cache für binäre Edge-Validierung
|
||||
- Erzeugt Notes, Chunks und Edges in Qdrant
|
||||
- Respektiert Hash-basierte Change Detection
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Log-Ausgabe: Fortschritt und Statistiken
|
||||
- Stats: processed, skipped, errors
|
||||
- Exit-Code 0: Erfolgreich (auch wenn einzelne Dateien Fehler haben)
|
||||
- Ohne --apply: Dry-Run (keine DB-Änderungen)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Regelmäßiger Import nach Vault-Änderungen
|
||||
- Initial-Import eines neuen Vaults
|
||||
- Re-Indexierung mit --force
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Two-Pass Workflow sorgt für robuste Edge-Validierung
|
||||
- Change Detection verhindert unnötige Re-Indexierung
|
||||
- Parallele Verarbeitung für Performance (max. 5 gleichzeitig)
|
||||
- Cloud-Resilienz durch Semaphore-Limits
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.import_markdown --vault ./vault --apply
|
||||
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet_dev --force --apply
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (Default: ./vault)
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
--force Erzwingt Re-Indexierung aller Dateien (ignoriert Hashes)
|
||||
--apply Führt tatsächliche DB-Schreibvorgänge durch (sonst Dry-Run)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.4.1 (2025-12-15): WP-15b Two-Pass Workflow
|
||||
- Implementiert Pre-Scan für LocalBatchCache
|
||||
- Indizierung nach ID, Titel und Dateiname
|
||||
- Batch-Verarbeitung mit Semaphore-Limits
|
||||
v2.0.0: Initial Release
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
+46
-31
@@ -1,45 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
make_test_vault.py — erzeugt einen minimalen, nachvollziehbaren Test-Vault
|
||||
FILE: scripts/make_test_vault.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Test-Tool)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Version: 1.2 (2025-09-09)
|
||||
Änderungen ggü. 1.1:
|
||||
- Fügt **externe Links** (http/mailto) in `exp-two.md` hinzu, damit der Chunk-Payload-Exporter
|
||||
`external_links` realistisch testen kann.
|
||||
- Kleine Textanpassungen zur stabilen Chunk-Bildung (Absatzstruktur).
|
||||
Zweck:
|
||||
-------
|
||||
Erzeugt einen minimalen, nachvollziehbaren Test-Vault für Entwicklung und Tests.
|
||||
Enthält verschiedene Szenarien: leere Links, externe Links, verschiedene Note-Typen.
|
||||
|
||||
Zweck
|
||||
- Kleiner Obsidian-ähnlicher Vault zum Durchspielen des Importers (Chunks/Edges).
|
||||
- Szenarien: leere Links, spätere Anlage fehlender Noten, Chunk-Neuaufteilung, externe Links.
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Erstellt Verzeichnisstruktur (concepts, experiences, projects)
|
||||
2. Generiert Test-Notizen mit vollständigem Frontmatter:
|
||||
- concept-alpha.md (Basis-Concept)
|
||||
- exp-one.md (verlinkt auf concept-alpha und missing-note)
|
||||
- exp-two.md (verlinkt auf concept-alpha + externe Links)
|
||||
- project-demo.md (verlinkt auf concept-alpha und exp-one)
|
||||
3. Optional: Erstellt missing-note (mit --with-missing)
|
||||
|
||||
Struktur (Default: ./test_vault)
|
||||
- 40_concepts/concept-alpha.md
|
||||
- 20_experiences/exp-one.md (verlinkt auf [[concept-alpha]] und [[missing-note]])
|
||||
- 20_experiences/exp-two.md (verlinkt auf [[concept-alpha]] + externe Links)
|
||||
- 30_projects/project-demo.md (verlinkt auf [[concept-alpha]] und [[exp-one]])
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Erfolgsmeldung mit erstellten Dateien
|
||||
- Exit-Code 0: Erfolgreich
|
||||
- Exit-Code 1: Fehler (z.B. Verzeichnis existiert bereits ohne --force)
|
||||
|
||||
Voraussetzungen
|
||||
- Keine. Rein Dateigenerierung.
|
||||
Verwendung:
|
||||
-----------
|
||||
- Entwicklung und Testing
|
||||
- Demo und Dokumentation
|
||||
- CI/CD-Tests
|
||||
|
||||
Aufruf
|
||||
python3 -m scripts.make_test_vault [--out ./test_vault] [--force] [--with-missing]
|
||||
Hinweise:
|
||||
---------
|
||||
- Erstellt realistische Test-Daten mit verschiedenen Edge-Szenarien
|
||||
- Enthält "Red Links" (missing-note) für Link-Auflösungs-Tests
|
||||
- Externe Links für Chunk-Payload-Tests
|
||||
|
||||
Parameter
|
||||
--out Zielverzeichnis (Standard: ./test_vault)
|
||||
--force Bestehenden Ordner löschen und neu anlegen.
|
||||
--with-missing Auch die 'missing-note' direkt anlegen (Standard: erst im 2. Lauf)
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.make_test_vault --out ./test_vault
|
||||
python3 -m scripts.make_test_vault --out ./test_vault --force --with-missing
|
||||
|
||||
Hinweise für Tests
|
||||
1) Erster Import (dry-run oder --apply): Es gibt einen „leeren“ Link [[missing-note]].
|
||||
2) Lege danach eine Datei für „missing-note“ an (mit gleicher ID im YAML) und importiere erneut:
|
||||
-> Erwartung: Edges für ehemals leeren Link werden korrekt nachgezogen (references + backlink).
|
||||
3) Ändere den Body von exp-one.md so, dass andere Chunk-Grenzen entstehen und importiere erneut:
|
||||
-> Erwartung: Chunks/Edges/Note werden für betroffene Noten aktualisiert.
|
||||
4) Prüfe externe Links (verify_chunk_texts.py betrifft nur Text; externe Links siehst du in chunk_payloads).
|
||||
Parameter:
|
||||
----------
|
||||
--out PATH Zielverzeichnis (Default: ./test_vault)
|
||||
--force Löscht bestehenden Ordner und legt neu an
|
||||
--with-missing Erstellt auch missing-note direkt (Standard: erst im 2. Lauf)
|
||||
|
||||
Kompatibel mit:
|
||||
- note.schema.json: 'created'/'updated' müssen strings sein. (Wichtig!)
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.2 (2025-09-09): Externe Links hinzugefügt
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,21 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/ollama_tool_runner.py — Minimaler Tool-Caller für Ollama + mindnet
|
||||
FILE: scripts/ollama_tool_runner.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
Führt den Tool-Call-Loop für mindnet_query / mindnet_subgraph aus.
|
||||
Nutzt /tools/ollama (Schema) und deine FastAPI (/query, /graph).
|
||||
ENV:
|
||||
OLLAMA=http://127.0.0.1:11434
|
||||
API_BASE=http://127.0.0.1:8000
|
||||
MODEL=llama3.1
|
||||
Nutzung:
|
||||
python3 scripts/ollama_tool_runner.py "Frage an den Agenten"
|
||||
Version:
|
||||
0.1.0 (Erstanlage)
|
||||
Stand:
|
||||
2025-10-07
|
||||
-------
|
||||
Minimaler Tool-Caller für Ollama mit mindnet-Tools.
|
||||
Führt Tool-Call-Loop für mindnet_query und mindnet_subgraph aus.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Lädt Tool-Schema von /tools/ollama Endpoint
|
||||
2. Sendet Query an Ollama mit Tool-Definitionen
|
||||
3. Ollama entscheidet, welche Tools aufzurufen sind
|
||||
4. Führt Tool-Calls aus:
|
||||
- mindnet_query: Ruft /query Endpoint auf
|
||||
- mindnet_subgraph: Ruft /graph Endpoint auf
|
||||
5. Wiederholt bis keine weiteren Tool-Calls nötig sind
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Konversations-Verlauf mit Tool-Calls und Antworten
|
||||
- Exit-Code 0: Erfolgreich
|
||||
- Exit-Code 1: Fehler (z.B. API nicht erreichbar)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Testing von Tool-Integration
|
||||
- Demo der Agent-Funktionalität
|
||||
- Entwicklung neuer Tools
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt Ollama als LLM-Backend
|
||||
- Tool-Schema wird von mindnet API bereitgestellt
|
||||
- Unterstützt mehrere Tool-Calls in einer Konversation
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 scripts/ollama_tool_runner.py "Frage an den Agenten"
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
Keine CLI-Parameter. Query als erstes Argument.
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
OLLAMA (Default: http://127.0.0.1:11434)
|
||||
API_BASE (Default: http://127.0.0.1:8000)
|
||||
MODEL (Default: llama3.1)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v0.1.0 (2025-10-07): Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,13 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/parse_validate_notes.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Validiert alle Markdown-Dateien in einem Vault auf strukturelle Korrektheit.
|
||||
Prüft Frontmatter-Validität und Note-Payload-Erzeugung ohne Datenbank-Upsert.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt rekursiv alle .md-Dateien im angegebenen Vault-Verzeichnis
|
||||
2. Für jede Datei:
|
||||
- Liest und parst Markdown mit Frontmatter
|
||||
- Validiert erforderliche Frontmatter-Felder (id, title, type)
|
||||
- Erzeugt Note-Payload (validiert durch JSON-Serialisierung)
|
||||
3. Gibt Statistik aus: Anzahl valider vs. invalider Dateien
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Exit-Code 0: Alle Dateien sind valide
|
||||
- Exit-Code 1: Mindestens eine Datei ist invalide
|
||||
- Ausgabe: "✅ Valid: X | ❌ Invalid: Y"
|
||||
- Fehlerdetails werden auf stderr ausgegeben
|
||||
|
||||
Häufige Fehler:
|
||||
--------------
|
||||
- Fehlende oder ungültige Frontmatter-Felder (id, title, type)
|
||||
- JSON-Serialisierungsfehler im Payload (z.B. ungültige Datentypen)
|
||||
- Encoding-Probleme beim Lesen der Datei
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.parse_validate_notes --vault ./vault
|
||||
python3 -m scripts.parse_validate_notes --vault ./vault --include "**/*.md" --exclude /.obsidian/ /_imported/
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--include PATTERN Glob-Pattern für Dateien (Default: "**/*.md")
|
||||
--exclude PATH Pfade zum Ausschließen (Default: /.obsidian/, /_imported/)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Entfernt: app.core.note_payload (ersetzt durch ingestion_note_payload)
|
||||
- Entfernt: app.core.validate_note (Validierung in make_note_payload integriert)
|
||||
- Entfernt: jsonschema.ValidationError (nicht mehr benötigt)
|
||||
v1.0.0: Erster Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import glob
|
||||
from jsonschema import ValidationError
|
||||
from app.core.parser import read_markdown, validate_required_frontmatter, normalize_frontmatter
|
||||
from app.core.note_payload import make_note_payload
|
||||
from app.core.validate_note import validate_note_payload
|
||||
from app.core.ingestion.ingestion_note_payload import make_note_payload
|
||||
|
||||
|
||||
@@ -39,11 +89,10 @@ def main():
|
||||
parsed = read_markdown(path)
|
||||
fm = normalize_frontmatter(parsed.frontmatter)
|
||||
validate_required_frontmatter(fm)
|
||||
# Note-Payload gemäß note.schema.json validieren
|
||||
payload = make_note_payload(parsed, vault_root=root)
|
||||
validate_note_payload(payload)
|
||||
# Note-Payload wird in make_note_payload bereits validiert (JSON-Serialisierung)
|
||||
payload = make_note_payload(parsed, vault_root=root, file_path=path)
|
||||
ok += 1
|
||||
except (ValidationError, ValueError) as e:
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as e:
|
||||
failed += 1
|
||||
print(f"❌ {os.path.relpath(path, root)} :: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
+148
-83
@@ -1,24 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/payload_dryrun.py (zeigt, was VOR dem Upsert tatsächlich in den Payloads steht)
|
||||
- KEIN Überschreiben der Note-Payload mehr
|
||||
- types.yaml ist maßgeblich (gemäß app/core/note_payload.py & chunk_payload.py)
|
||||
FILE: scripts/payload_dryrun.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Zeigt die Payload-Struktur, die vor dem Datenbank-Upsert erzeugt würde.
|
||||
Nützlich zur Validierung der Payload-Erzeugung und Konfiguration (types.yaml).
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle Markdown-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Parst Markdown mit Frontmatter
|
||||
- Erzeugt Note-Payload (wie in make_note_payload)
|
||||
- Erstellt Chunks via assemble_chunks
|
||||
- Erzeugt Chunk-Payloads (wie in make_chunk_payloads)
|
||||
- Optional: Erzeugt Edges (mit --with-edges)
|
||||
3. Gibt JSON pro Note aus mit Payload-Zusammenfassung
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON-Objekte (ein Objekt pro Note, eine Zeile pro Objekt)
|
||||
- Jedes Objekt enthält:
|
||||
* note_id, title, type, path
|
||||
* note_payload: retriever_weight, chunk_profile
|
||||
* chunks_summary: count, first (erste 3 Chunks mit Metadaten)
|
||||
* edges_summary (nur mit --with-edges): total, by_kind
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Validierung der types.yaml Konfiguration
|
||||
- Debugging von Payload-Erzeugungsproblemen
|
||||
- Analyse der Chunk-Struktur vor dem Import
|
||||
- Prüfung von retriever_weight und chunk_profile Zuweisungen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- types.yaml ist maßgeblich für Payload-Erzeugung
|
||||
- Frontmatter-Überschreibungen werden berücksichtigt
|
||||
- Keine Datenbank-Operationen, rein analytisch
|
||||
- Chunking nutzt vollständiges assemble_chunks (nicht vereinfacht)
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.payload_dryrun --vault ./vault
|
||||
python3 -m scripts.payload_dryrun --vault ./vault --note-id my-note-id
|
||||
python3 -m scripts.payload_dryrun --vault ./vault --with-edges
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--note-id ID Nur eine bestimmte Note verarbeiten (optional)
|
||||
--with-edges Edge-Erzeugung einschließen (optional)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Entfernt: Fallback für app.core.edges
|
||||
- Verwendet direkt: app.core.derive_edges
|
||||
- Parameter korrigiert: chunk_payloads → chunks, note_level_refs → note_level_references
|
||||
v1.0.0: Erster Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, json
|
||||
import argparse, os, json, asyncio
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
||||
from app.core.chunking import assemble_chunks
|
||||
from app.core.ingestion.ingestion_note_payload import make_note_payload
|
||||
from app.core.ingestion.ingestion_chunk_payload import make_chunk_payloads
|
||||
try:
|
||||
from app.core.derive_edges import build_edges_for_note
|
||||
except Exception:
|
||||
from app.core.edges import build_edges_for_note # type: ignore
|
||||
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||
|
||||
def main():
|
||||
async def process_file(path: str, root: str, args):
|
||||
"""Verarbeitet eine einzelne Datei asynchron."""
|
||||
parsed = read_markdown(path)
|
||||
if not parsed:
|
||||
return None
|
||||
fm = normalize_frontmatter(parsed.frontmatter)
|
||||
try:
|
||||
validate_required_frontmatter(fm)
|
||||
except Exception as e:
|
||||
print(json.dumps({"path": path, "error": f"invalid frontmatter: {e}"}))
|
||||
return None
|
||||
|
||||
if args.note_id and fm.get("id") != args.note_id:
|
||||
return None
|
||||
|
||||
# Note-Payload exakt so, wie der Importer ihn baut (types.yaml maßgeblich)
|
||||
note_pl = make_note_payload(parsed,
|
||||
vault_root=root,
|
||||
hash_source="parsed",
|
||||
hash_normalize="canonical",
|
||||
file_path=path)
|
||||
|
||||
body_text = getattr(parsed, "body", "") or ""
|
||||
chunks = await assemble_chunks(fm["id"], body_text, fm.get("type","concept"))
|
||||
|
||||
chunk_note = {
|
||||
"frontmatter": fm,
|
||||
"id": fm.get("id"),
|
||||
"type": fm.get("type"),
|
||||
"title": fm.get("title"),
|
||||
"path": note_pl.get("path") or path,
|
||||
"note_id": note_pl.get("note_id"),
|
||||
"tags": fm.get("tags"),
|
||||
}
|
||||
# make_chunk_payloads bestimmt Werte ebenfalls aus types.yaml (Frontmatter wird ignoriert)
|
||||
chunk_pls = make_chunk_payloads(
|
||||
chunk_note,
|
||||
note_pl["path"],
|
||||
chunks,
|
||||
note_text=body_text,
|
||||
types_cfg=None, # Loader aus Datei; kein Override von außen
|
||||
file_path=path,
|
||||
)
|
||||
|
||||
out = {
|
||||
"note_id": note_pl.get("note_id") or fm.get("id"),
|
||||
"title": fm.get("title"),
|
||||
"type": fm.get("type"),
|
||||
"note_payload": {
|
||||
"retriever_weight": note_pl.get("retriever_weight"),
|
||||
"chunk_profile": note_pl.get("chunk_profile")
|
||||
},
|
||||
"chunks_summary": {
|
||||
"count": len(chunk_pls),
|
||||
"first": [
|
||||
{k: chunk_pls[i].get(k) for k in ("chunk_id","index","ord","retriever_weight","chunk_profile","neighbors_prev","neighbors_next")}
|
||||
for i in range(min(3, len(chunk_pls)))
|
||||
]
|
||||
},
|
||||
"path": note_pl.get("path")
|
||||
}
|
||||
|
||||
if args.with_edges:
|
||||
edges = build_edges_for_note(
|
||||
note_id=note_pl.get("note_id") or fm.get("id"),
|
||||
chunks=chunk_pls,
|
||||
note_level_references=note_pl.get("references") or [],
|
||||
include_note_scope_refs=False,
|
||||
)
|
||||
kinds = {}
|
||||
for e in edges:
|
||||
k = (e.get("relation") or e.get("kind") or "edge")
|
||||
kinds[k] = kinds.get(k, 0) + 1
|
||||
out["edges_summary"] = {"total": len(edges), "by_kind": kinds}
|
||||
|
||||
return out
|
||||
|
||||
async def main_async():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--vault", required=True)
|
||||
ap.add_argument("--note-id")
|
||||
@@ -35,81 +169,12 @@ def main():
|
||||
files.sort()
|
||||
|
||||
for path in files:
|
||||
parsed = read_markdown(path)
|
||||
if not parsed:
|
||||
continue
|
||||
fm = normalize_frontmatter(parsed.frontmatter)
|
||||
try:
|
||||
validate_required_frontmatter(fm)
|
||||
except Exception as e:
|
||||
print(json.dumps({"path": path, "error": f"invalid frontmatter: {e}"}))
|
||||
continue
|
||||
result = await process_file(path, root, args)
|
||||
if result:
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
if args.note_id and fm.get("id") != args.note_id:
|
||||
continue
|
||||
|
||||
# Note-Payload exakt so, wie der Importer ihn baut (types.yaml maßgeblich)
|
||||
note_pl = make_note_payload(parsed,
|
||||
vault_root=root,
|
||||
hash_mode="body",
|
||||
hash_normalize="canonical",
|
||||
hash_source="parsed",
|
||||
file_path=path)
|
||||
|
||||
body_text = getattr(parsed, "body", "") or ""
|
||||
chunks = assemble_chunks(fm["id"], body_text, fm.get("type","concept"))
|
||||
|
||||
chunk_note = {
|
||||
"frontmatter": fm,
|
||||
"id": fm.get("id"),
|
||||
"type": fm.get("type"),
|
||||
"title": fm.get("title"),
|
||||
"path": note_pl.get("path") or path,
|
||||
"note_id": note_pl.get("note_id"),
|
||||
"tags": fm.get("tags"),
|
||||
}
|
||||
# make_chunk_payloads bestimmt Werte ebenfalls aus types.yaml (Frontmatter wird ignoriert)
|
||||
chunk_pls = make_chunk_payloads(
|
||||
chunk_note,
|
||||
note_pl["path"],
|
||||
chunks,
|
||||
note_text=body_text,
|
||||
types_cfg=None, # Loader aus Datei; kein Override von außen
|
||||
file_path=path,
|
||||
)
|
||||
|
||||
out = {
|
||||
"note_id": note_pl.get("note_id") or fm.get("id"),
|
||||
"title": fm.get("title"),
|
||||
"type": fm.get("type"),
|
||||
"note_payload": {
|
||||
"retriever_weight": note_pl.get("retriever_weight"),
|
||||
"chunk_profile": note_pl.get("chunk_profile")
|
||||
},
|
||||
"chunks_summary": {
|
||||
"count": len(chunk_pls),
|
||||
"first": [
|
||||
{k: chunk_pls[i].get(k) for k in ("chunk_id","index","ord","retriever_weight","chunk_profile","neighbors_prev","neighbors_next")}
|
||||
for i in range(min(3, len(chunk_pls)))
|
||||
]
|
||||
},
|
||||
"path": note_pl.get("path")
|
||||
}
|
||||
|
||||
if args.with_edges:
|
||||
edges = build_edges_for_note(
|
||||
note_id=note_pl.get("note_id") or fm.get("id"),
|
||||
chunk_payloads=chunk_pls,
|
||||
note_level_refs=note_pl.get("references") or [],
|
||||
include_note_scope_refs=False,
|
||||
)
|
||||
kinds = {}
|
||||
for e in edges:
|
||||
k = (e.get("relation") or e.get("kind") or "edge")
|
||||
kinds[k] = kinds.get(k, 0) + 1
|
||||
out["edges_summary"] = {"total": len(edges), "by_kind": kinds}
|
||||
|
||||
print(json.dumps(out, ensure_ascii=False))
|
||||
def main():
|
||||
asyncio.run(main_async())
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,4 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/preview_chunks.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Zeigt eine Vorschau der Chunk-Struktur für Notizen im Vault.
|
||||
Nützlich zur Analyse der Chunking-Strategie und Nachbarschafts-Links.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Scannt alle Markdown-Dateien im Vault
|
||||
2. Für jede Datei:
|
||||
- Erzeugt Note-Payload
|
||||
- Erstellt Chunks via assemble_chunks
|
||||
- Erzeugt Chunk-Payloads
|
||||
3. Gibt JSON pro Note aus mit Chunk-Details
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON-Objekte (ein Objekt pro Note, eine Zeile pro Objekt)
|
||||
- Jedes Objekt enthält:
|
||||
* note_id, title
|
||||
* num_chunks: Anzahl der Chunks
|
||||
* avg_tokens: Durchschnittliche Token pro Chunk
|
||||
* chunks: Array mit Chunk-Details (id, tokens, section, prev, next)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Analyse der Chunk-Verteilung
|
||||
- Validierung der Nachbarschafts-Links
|
||||
- Debugging von Chunking-Problemen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Nutzt synchrones assemble_chunks (kann async sein)
|
||||
- Zeigt nur Struktur, keine Inhalte
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.preview_chunks --vault ./vault
|
||||
python3 -m scripts.preview_chunks --vault ./vault --note-id my-note-id
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--note-id ID Nur eine bestimmte Note verarbeiten (optional)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, glob, json
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
||||
|
||||
@@ -1,38 +1,79 @@
|
||||
# scripts/prune_qdrant_vs_vault.py
|
||||
# -----------------------------------------------------------------------------
|
||||
# Name: prune_qdrant_vs_vault.py
|
||||
# Version: 1.0.0 (2025-09-08)
|
||||
# Zweck: Entfernt verwaiste Qdrant-Einträge (notes/chunks/edges), wenn
|
||||
# die zugehörigen Markdown-Dateien im Vault nicht mehr existieren.
|
||||
#
|
||||
# Was es macht:
|
||||
# - Liest alle note_id aus dem Vault (Frontmatter: id / note_id).
|
||||
# - Liest alle note_id aus Qdrant (mindnet_notes).
|
||||
# - Bildet die Differenz (nur in Qdrant vorhandene, im Vault fehlende).
|
||||
# - Löscht für jede verwaiste note_id:
|
||||
# * Notes-Point(s)
|
||||
# * Alle Chunks der Note
|
||||
# * Alle Edges, die auf diese Note referenzieren
|
||||
# (source_id == note_id ODER target_id == note_id ODER
|
||||
# source_note_id == note_id ODER target_note_id == note_id)
|
||||
#
|
||||
# Hinweise:
|
||||
# - Kein globaler Delete. Nur betroffene note_id.
|
||||
# - Dry-Run standardmäßig; tatsächliches Löschen erst mit --apply.
|
||||
# - Interaktive Bestätigung (abschaltbar mit --yes).
|
||||
#
|
||||
# Aufruf:
|
||||
# python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet
|
||||
# python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet --apply
|
||||
# python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet --apply --yes
|
||||
#
|
||||
# Voraussetzungen:
|
||||
# - Ausführung im aktivierten venv empfohlen: source .venv/bin/activate
|
||||
# - Qdrant läuft lokal (oder URL/API-Key in ENV), siehe app/core/qdrant.py
|
||||
#
|
||||
# Änderungen:
|
||||
# - 1.0.0: Erster Release.
|
||||
# -----------------------------------------------------------------------------
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/prune_qdrant_vs_vault.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Bereinigt verwaiste Einträge in Qdrant, wenn die zugehörigen Markdown-Dateien
|
||||
im Vault nicht mehr existieren. Stellt Konsistenz zwischen Vault und Datenbank her.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Liest alle note_id aus dem Vault (aus Frontmatter: id / note_id)
|
||||
2. Liest alle note_id aus Qdrant (Collection: {prefix}_notes)
|
||||
3. Berechnet Differenz: note_ids nur in Qdrant vorhanden (verwaist)
|
||||
4. Für jede verwaiste note_id (nur mit --apply):
|
||||
- Löscht Note-Point(s) aus {prefix}_notes
|
||||
- Löscht alle Chunks der Note aus {prefix}_chunks
|
||||
- Löscht alle Edges, die auf diese Note referenzieren:
|
||||
* source_id == note_id
|
||||
* target_id == note_id
|
||||
* source_note_id == note_id
|
||||
* target_note_id == note_id
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Preview-Informationen
|
||||
* mode: "DRY-RUN" oder "APPLY"
|
||||
* counts: Statistiken (vault_note_ids, qdrant_note_ids, orphans)
|
||||
* orphans_sample: Erste 20 verwaiste note_ids
|
||||
- Bei --apply: Zusätzlich JSON mit deleted-Statistiken
|
||||
* deleted.notes: Anzahl gelöschter Note-Points
|
||||
* deleted.chunks: Anzahl gelöschter Chunks
|
||||
* deleted.edges: Anzahl gelöschter Edges
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Regelmäßige Wartung nach Vault-Bereinigung
|
||||
- Vor Migrationen oder größeren Umstrukturierungen
|
||||
- Konsistenz-Check zwischen Vault und Datenbank
|
||||
|
||||
Sicherheitsmerkmale:
|
||||
-------------------
|
||||
- Dry-Run standardmäßig (keine Änderungen ohne --apply)
|
||||
- Interaktive Bestätigung (außer mit --yes)
|
||||
- Nur betroffene note_ids werden gelöscht (kein globaler Delete)
|
||||
- Zeigt Preview vor Ausführung
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
# Dry-Run (nur Analyse)
|
||||
python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet
|
||||
|
||||
# Tatsächliches Löschen
|
||||
python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet --apply
|
||||
|
||||
# Ohne Rückfrage
|
||||
python3 -m scripts.prune_qdrant_vs_vault --vault ./vault --prefix mindnet --apply --yes
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--vault PATH Pfad zum Vault-Verzeichnis (erforderlich)
|
||||
--prefix TEXT Collection-Präfix (Default: mindnet)
|
||||
--apply Führt tatsächliches Löschen durch (sonst nur Dry-Run)
|
||||
--yes Keine interaktive Bestätigung
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Geändert: parse_markdown_file → read_markdown + normalize_frontmatter
|
||||
- Parsing-Logik an neue API angepasst
|
||||
v1.0.0 (2025-09-08): Erster Release
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
@@ -44,19 +85,20 @@ from typing import Dict, List, Set, Tuple
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.parser import parse_markdown_file # nutzt euer bestehendes Parsing/Schema
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.parser import read_markdown, normalize_frontmatter
|
||||
|
||||
|
||||
def read_vault_note_ids(vault_dir: Path) -> Set[str]:
|
||||
note_ids: Set[str] = set()
|
||||
for p in vault_dir.rglob("*.md"):
|
||||
try:
|
||||
parsed = parse_markdown_file(str(p))
|
||||
fm = parsed.frontmatter if hasattr(parsed, "frontmatter") else (parsed.get("frontmatter") or {})
|
||||
nid = fm.get("id") or fm.get("note_id")
|
||||
if nid:
|
||||
note_ids.add(str(nid))
|
||||
parsed = read_markdown(str(p))
|
||||
if parsed:
|
||||
fm = normalize_frontmatter(parsed.frontmatter) if parsed.frontmatter else {}
|
||||
nid = fm.get("id") or fm.get("note_id")
|
||||
if nid:
|
||||
note_ids.add(str(nid))
|
||||
except Exception:
|
||||
# still und leise weiter – wir wollen robust sein
|
||||
continue
|
||||
|
||||
+50
-16
@@ -1,25 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script: scripts/report_hashes.py — Übersicht & Lücken bei Mehrfach-Hashes
|
||||
Version: 1.0.0
|
||||
Datum: 2025-09-10
|
||||
FILE: scripts/report_hashes.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Funktion
|
||||
--------
|
||||
Listet je Note die vorhandenen Einträge im Feld `hashes` (Signaturen: <mode>:<source>:<normalize>)
|
||||
und meldet fehlende Soll-Keys. Eignet sich als CI-Check.
|
||||
Zweck:
|
||||
-------
|
||||
Erstellt Übersicht über Hash-Signaturen in Note-Payloads.
|
||||
Meldet fehlende Soll-Keys für Multi-Hash Change Detection.
|
||||
|
||||
Optionen
|
||||
--------
|
||||
--prefix TEXT Collection-Prefix (CLI überschreibt ENV)
|
||||
--require K [K ...] Zusätzliche Soll-Keys (Default: body|frontmatter|full:parsed:canonical)
|
||||
--fail-on-missing Exitcode 2, wenn fehlende Keys gefunden werden
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Lädt alle Notes aus {prefix}_notes
|
||||
2. Prüft für jede Note das `hashes` Feld
|
||||
3. Vergleicht vorhandene Keys mit Soll-Keys
|
||||
4. Meldet fehlende Keys pro Note
|
||||
|
||||
Beispiele
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Hash-Übersicht
|
||||
* notes_total: Anzahl geprüfter Notizen
|
||||
* notes_with_missing: Anzahl Notizen mit fehlenden Keys
|
||||
* missing_keys: Liste fehlender Keys pro Note
|
||||
- Exit-Code 0: Keine fehlenden Keys (oder --fail-on-missing nicht gesetzt)
|
||||
- Exit-Code 2: Fehlende Keys gefunden (nur mit --fail-on-missing)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- CI/CD-Validierung der Hash-Integrität
|
||||
- Audit nach Migrationen
|
||||
- Prüfung der Change Detection Funktionalität
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
python3 -m scripts.report_hashes --prefix mindnet
|
||||
python3 -m scripts.report_hashes --require frontmatter:raw:none --fail-on-missing
|
||||
- Multi-Hash Format: <mode>:<source>:<normalize>
|
||||
- Standard Soll-Keys: body:parsed:canonical, full:parsed:canonical
|
||||
- Kann zusätzliche Keys via --require anfordern
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.report_hashes --prefix mindnet
|
||||
python3 -m scripts.report_hashes --require frontmatter:raw:none --fail-on-missing
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (überschreibt ENV COLLECTION_PREFIX)
|
||||
--require KEY ... Zusätzliche Soll-Keys (Default: body:parsed:canonical, full:parsed:canonical)
|
||||
--fail-on-missing Exit-Code 2, wenn fehlende Keys gefunden werden
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0 (2025-09-10): Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -29,7 +63,7 @@ import os
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from qdrant_client.http import models as rest
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
def collections(prefix: str):
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
+62
-36
@@ -1,49 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: scripts/reset_qdrant.py
|
||||
Version: v1.2.1 (2025-12-11)
|
||||
Kurzbeschreibung:
|
||||
Sicheres Zurücksetzen der Qdrant-Collections für EIN Projektpräfix. Das Skript
|
||||
ermittelt zunächst die tatsächlich betroffenen Collections und zeigt eine
|
||||
Übersicht an. Anschließend wird der User um Bestätigung gebeten (interaktive
|
||||
Abfrage), bevor eine der Aktionen ausgeführt wird:
|
||||
FILE: scripts/reset_qdrant.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Core)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
- wipe: Löscht die Collections komplett und legt sie gemäß Projekt-Defaults neu an.
|
||||
**Neu**: Danach werden *immer* die Payload-Indizes & Schema-Ergänzungen
|
||||
über ensure_payload_indexes() idempotent eingerichtet (falls nicht mit --no-indexes deaktiviert).
|
||||
- truncate: Löscht nur alle Points (Inhalte), behält die Collection-Settings.
|
||||
**Neu**: Optional (Default) werden im Anschluss die Payload-Indizes geprüft/ergänzt.
|
||||
Zweck:
|
||||
-------
|
||||
Sicheres Zurücksetzen der Qdrant-Collections für ein Projektpräfix.
|
||||
Ermöglicht vollständigen Neustart (wipe) oder Löschen nur der Inhalte (truncate).
|
||||
|
||||
Aufruf (aus Projekt-Root, im venv):
|
||||
python3 -m scripts.reset_qdrant --mode wipe [--prefix PREFIX] [--yes] [--dry-run]
|
||||
python3 -m scripts.reset_qdrant --mode truncate [--prefix PREFIX] [--yes] [--dry-run]
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Ermittelt betroffene Collections (notes, chunks, edges für Präfix)
|
||||
2. Zeigt Preview der existierenden Collections
|
||||
3. Interaktive Bestätigung (außer mit --yes)
|
||||
4. Führt Aktion aus:
|
||||
- wipe: Löscht Collections komplett, legt neu an, richtet Indizes ein
|
||||
- truncate: Löscht nur Points, behält Collection-Settings, prüft Indizes
|
||||
5. Richtet Payload-Indizes idempotent ein (außer mit --no-indexes)
|
||||
|
||||
Parameter:
|
||||
--mode wipe | truncate (Pflicht)
|
||||
--prefix Collection-Prefix (Default: env COLLECTION_PREFIX oder 'mindnet')
|
||||
--yes Keine Rückfrage, direkt ausführen (CI/CD geeignet)
|
||||
--dry-run Nur anzeigen, was passieren würde; nichts ändern
|
||||
--no-indexes Überspringt den Schritt ensure_payload_indexes() (Standard: Indizes/Schema werden geprüft/ergänzt)
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Preview: Zeigt betroffene Collections vor Ausführung
|
||||
- Exit-Code 0: Erfolgreich
|
||||
- Exit-Code 1: Abgebrochen oder keine Aktion
|
||||
- Exit-Code 2: Verbindungs- oder Konfigurationsfehler
|
||||
|
||||
Umgebungsvariablen (optional):
|
||||
QDRANT_URL, QDRANT_API_KEY, COLLECTION_PREFIX, VECTOR_DIM (Default 384)
|
||||
(Zusätzliche ENV für Named Vectors etc. werden innerhalb ensure_collections/ensure_payload_indexes berücksichtigt.)
|
||||
Verwendung:
|
||||
-----------
|
||||
- Vor größeren Migrationen oder Schema-Änderungen
|
||||
- Bei Inkonsistenzen in der Datenbank
|
||||
- Für Entwicklung/Testing (schneller Reset)
|
||||
- CI/CD-Pipelines (mit --yes)
|
||||
|
||||
Sicherheitsmerkmale:
|
||||
- Betrachtet ausschließlich Collections des angegebenen Präfixes.
|
||||
- Listet vor Ausführung die tatsächlich existierenden Ziel-Collections auf.
|
||||
- Fragt interaktiv nach Bestätigung (es sei denn --yes ist gesetzt).
|
||||
-------------------
|
||||
- Betrachtet nur Collections des angegebenen Präfixes
|
||||
- Listet betroffene Collections vor Ausführung auf
|
||||
- Interaktive Bestätigung (außer mit --yes)
|
||||
- Dry-Run Modus verfügbar
|
||||
|
||||
Exitcodes:
|
||||
0 = OK, 1 = abgebrochen/keine Aktion, 2 = Verbindungs-/Konfigurationsfehler
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.reset_qdrant --mode wipe --prefix mindnet
|
||||
python3 -m scripts.reset_qdrant --mode truncate --prefix mindnet --yes
|
||||
python3 -m scripts.reset_qdrant --mode wipe --dry-run
|
||||
|
||||
Changelog:
|
||||
v1.2.1: Fix: load_dotenv() hinzugefügt, damit VECTOR_DIM aus .env gelesen wird.
|
||||
v1.2.0: ensure_payload_indexes() nach wipe/truncate standardmäßig ausführen (idempotent); --no-indexes Flag ergänzt.
|
||||
v1.1.1: Stabilisierung & Preview (2025-09-05).
|
||||
v1.1.0: Interaktive Bestätigung, --yes/--dry-run hinzugefügt, Preview der betroffenen Collections.
|
||||
v1.0.0: Wipe/Truncate ohne Bestätigungsabfrage.
|
||||
Parameter:
|
||||
----------
|
||||
--mode MODE wipe | truncate (Pflicht)
|
||||
- wipe: Collections löschen & neu anlegen
|
||||
- truncate: Nur Points löschen, Settings behalten
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
--yes Keine Rückfrage, direkt ausführen (CI/CD)
|
||||
--dry-run Nur anzeigen, was passieren würde
|
||||
--no-indexes Überspringt ensure_payload_indexes() (Standard: Indizes werden geprüft/ergänzt)
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
QDRANT_URL, QDRANT_API_KEY, COLLECTION_PREFIX, VECTOR_DIM (Default: 768)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Aktualisiert: Import-Pfade für neue Struktur
|
||||
v1.2.1 (2025-12-11): Fix load_dotenv() für VECTOR_DIM
|
||||
v1.2.0: ensure_payload_indexes() standardmäßig nach wipe/truncate
|
||||
v1.1.0: Interaktive Bestätigung, --yes/--dry-run
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
@@ -57,7 +83,7 @@ from dotenv import load_dotenv
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import (
|
||||
from app.core.database.qdrant import (
|
||||
QdrantConfig,
|
||||
get_client,
|
||||
ensure_collections,
|
||||
|
||||
@@ -1,20 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
# scripts/resolve_unresolved_references.py
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
resolve_unresolved_references.py — Unaufgelöste Wikilinks in Qdrant nachträglich auflösen
|
||||
FILE: scripts/resolve_unresolved_references.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Version: 1.1.0 (Fixed for v2.6 Architecture)
|
||||
Zweck:
|
||||
-------
|
||||
Löst unaufgelöste Wikilinks in Qdrant nachträglich auf.
|
||||
Findet Edges mit status=="unresolved" und versucht sie über Titel/Alias aufzulösen.
|
||||
|
||||
Zweck
|
||||
------
|
||||
- Findet Edges in {prefix}_edges mit payload.status=="unresolved".
|
||||
- Baut einen In-Memory Index aller Notizen (Titel/Alias -> ID).
|
||||
- Aktualisiert die Edges (setzt target_id, entfernt status).
|
||||
- Erzeugt symmetrische 'backlink'-Kanten für 'references'.
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Baut Lookup-Index aus allen Notizen:
|
||||
- Mapping: lower(title) -> note_id
|
||||
- Mapping: lower(alias) -> note_id
|
||||
2. Findet alle Edges mit status=="unresolved"
|
||||
3. Versucht Auflösung über Lookup-Index
|
||||
4. Aktualisiert erfolgreich aufgelöste Edges:
|
||||
- Setzt target_id
|
||||
- Entfernt status
|
||||
- Fügt resolution="healed_by_script" hinzu
|
||||
5. Erzeugt Backlinks für erfolgreich aufgelöste references-Edges
|
||||
|
||||
Aufruf
|
||||
------
|
||||
python3 -m scripts.resolve_unresolved_references --apply
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Log-Ausgabe: Fortschritt und Statistiken
|
||||
- "Resolvable: X/Y": Anzahl aufgelösbarer Edges
|
||||
- Ohne --apply: Dry-Run (keine DB-Änderungen)
|
||||
- Exit-Code 0: Erfolgreich
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Nach Import von neuen Notizen, die bestehende Links auflösen
|
||||
- Reparatur von "Red Links" (Links auf noch nicht existierende Notizen)
|
||||
- Wartung des Graphen nach größeren Änderungen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Sucht nach status=="unresolved" in Edge-Payloads
|
||||
- Auflösung erfolgt über Titel und Aliases (case-insensitive)
|
||||
- Erzeugt automatisch Backlinks für references-Edges
|
||||
- Batch-Verarbeitung für Performance
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.resolve_unresolved_references --apply
|
||||
python3 -m scripts.resolve_unresolved_references --prefix mindnet --limit 1000 --apply
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX)
|
||||
--apply Führt tatsächliche DB-Änderungen durch (sonst Dry-Run)
|
||||
--limit INT Maximale Anzahl zu verarbeitender Edges (0=alle, Default: 0)
|
||||
--batch INT Batch-Größe für Upserts (Default: 100)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.1.0: Fixed for v2.6 Architecture
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -24,8 +70,8 @@ import uuid
|
||||
from typing import List, Dict, Any, Iterable
|
||||
|
||||
from qdrant_client import models
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.qdrant_points import points_for_edges
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant_points import points_for_edges
|
||||
|
||||
# Logging Setup
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
|
||||
@@ -1,23 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FILE: scripts/setup_mindnet_collections.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
-------
|
||||
Richtet die Qdrant-Collections für das mindnet-Projekt ein.
|
||||
Legt Collections und Payload-Indizes an (idempotent).
|
||||
|
||||
Collections:
|
||||
- mindnet_chunks : semantische Suche über Markdown-Text-Chunks (Vektor: dim/Cosine)
|
||||
- mindnet_notes : 1 Punkt pro Notiz (Metadaten, optional Titel-Embedding)
|
||||
- mindnet_edges : explizite Link-Kanten (Dummy-Vektor size=1; Filter über Payload)
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Prüft Qdrant-Verfügbarkeit (optional /ready Endpoint)
|
||||
2. Legt drei Collections an:
|
||||
- {prefix}_chunks: Semantische Suche über Text-Chunks (Vektor: dim/Cosine)
|
||||
- {prefix}_notes: Metadaten pro Notiz (Vektor: dim/Cosine)
|
||||
- {prefix}_edges: Link-Kanten (Dummy-Vektor size=1, Filter über Payload)
|
||||
3. Richtet Payload-Indizes ein:
|
||||
- Keyword-Indizes für häufige Filter-Felder
|
||||
- Text-Index für Volltextsuche (chunks.text)
|
||||
|
||||
Eigenschaften:
|
||||
- Idempotent: legt nur an, wenn eine Collection noch nicht existiert
|
||||
- Legt sinnvolle Payload-Indizes an (keyword/text)
|
||||
- Ohne "global"-Seiteneffekte; Qdrant-URL wird sauber übergeben
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Status pro Collection ([+] angelegt, [=] existiert bereits)
|
||||
- Abschluss: JSON-Liste aller vorhandenen Collections
|
||||
- Exit-Code 0: Erfolgreich
|
||||
- Exit-Code 1: Fehler (z.B. Qdrant nicht erreichbar)
|
||||
|
||||
Aufrufbeispiel:
|
||||
python3 setup_mindnet_collections.py \
|
||||
--qdrant-url http://127.0.0.1:6333 \
|
||||
--prefix mindnet \
|
||||
--dim 384 \
|
||||
--distance Cosine
|
||||
Verwendung:
|
||||
-----------
|
||||
- Initial-Setup einer neuen mindnet-Instanz
|
||||
- Nach Qdrant-Reset oder Migration
|
||||
- Validierung der Collection-Struktur
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Idempotent: Überspringt existierende Collections
|
||||
- Nutzt HTTP-API direkt (kein qdrant-client)
|
||||
- Legt nur Basis-Indizes an (erweiterte Indizes via ensure_payload_indexes)
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.setup_mindnet_collections --qdrant-url http://127.0.0.1:6333 --prefix mindnet --dim 768
|
||||
python3 -m scripts.setup_mindnet_collections --prefix mindnet_dev --dim 768 --distance Cosine
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--qdrant-url URL Qdrant-URL (Default: http://127.0.0.1:6333)
|
||||
--prefix TEXT Collection-Präfix (Default: mindnet)
|
||||
--dim INT Vektor-Dimension (Default: 384, empfohlen: 768 für nomic)
|
||||
--distance METRIC Cosine | Euclid | Dot (Default: Cosine)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Kompatibilität mit WP-14 Modularisierung
|
||||
- Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
+58
-15
@@ -1,23 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/validate_edges.py
|
||||
FILE: scripts/validate_edges.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Validiert die von WP-03 erzeugten Edges in Qdrant:
|
||||
- Zählt Kanten je Typ (references, backlink, references_at)
|
||||
- Prüft: Für jede "references" (resolved) existiert eine "backlink"-Gegenkante
|
||||
- Prüft: "backlink" darf nicht "unresolved" sein
|
||||
- Prüft: "references_at".source_id existiert in {prefix}_chunks
|
||||
- Prüft: "references"/"backlink" source/target existieren in {prefix}_notes
|
||||
- Prüft: doppelte edge_id (sollte 0 sein, da UUIDv5 aus edge_id)
|
||||
Gibt ein kompaktes JSON-Resultat + optionale Detail-Listen aus.
|
||||
Zweck:
|
||||
-------
|
||||
Validiert die Integrität der Edges in Qdrant.
|
||||
Prüft strukturelle Korrektheit, Referenz-Integrität und Konsistenz.
|
||||
|
||||
Umgebung/Parameter:
|
||||
- QDRANT_URL (Default: http://127.0.0.1:6333)
|
||||
- QDRANT_API_KEY (optional)
|
||||
- COLLECTION_PREFIX (Default: mindnet)
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Lädt alle Edges aus {prefix}_edges
|
||||
2. Führt mehrere Validierungen durch:
|
||||
- Zählt Edges nach Typ (references, backlink, etc.)
|
||||
- Prüft: Für jede "references" existiert "backlink"-Gegenkante
|
||||
- Prüft: "backlink" darf nicht "unresolved" sein
|
||||
- Prüft: "references_at".source_id existiert in chunks
|
||||
- Prüft: source/target existieren in notes
|
||||
- Prüft: doppelte edge_id (sollte 0 sein)
|
||||
3. Gibt kompaktes JSON-Resultat + optionale Detail-Listen aus
|
||||
|
||||
Beispiel:
|
||||
python scripts/validate_edges.py --prefix mindnet
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Validierungs-Ergebnissen
|
||||
* counts_by_kind: Anzahl Edges pro Typ
|
||||
* validation_results: Ergebnisse der einzelnen Prüfungen
|
||||
* issues: Liste gefundener Probleme (optional mit --verbose)
|
||||
- Exit-Code 0: Alle Validierungen bestanden
|
||||
- Exit-Code 1: Validierungsfehler gefunden
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Qualitätskontrolle nach Importen
|
||||
- Debugging von Graph-Problemen
|
||||
- CI/CD-Validierung
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Prüft strukturelle Integrität, nicht semantische Korrektheit
|
||||
- Kann bei großen Graphen langsam sein
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.validate_edges --prefix mindnet
|
||||
python3 -m scripts.validate_edges --prefix mindnet --verbose
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX oder mindnet)
|
||||
--verbose Zeigt detaillierte Problem-Listen
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
QDRANT_URL (Default: http://127.0.0.1:6333), QDRANT_API_KEY, COLLECTION_PREFIX
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0: Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
|
||||
@@ -1,58 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script: scripts/verify_chunk_texts.py
|
||||
Version: 1.0.0
|
||||
Datum: 2025-09-09
|
||||
FILE: scripts/verify_chunk_texts.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Kurzbeschreibung
|
||||
Zweck:
|
||||
-------
|
||||
Verifiziert, dass Chunk-Texte in Qdrant korrekt gespeichert sind und
|
||||
der Note-Body aus Chunks rekonstruiert werden kann.
|
||||
|
||||
Funktionsweise:
|
||||
---------------
|
||||
Verifiziert, dass in Qdrant für jede Note die zugehörigen Chunks ein Textfeld
|
||||
enthalten und der Body (notes.payload.fulltext) aus den Chunk-Texten sinnvoll
|
||||
rekonstruiert werden kann.
|
||||
1. Lädt alle Notes aus {prefix}_notes
|
||||
2. Für jede Note:
|
||||
- Lädt zugehörige Chunks
|
||||
- Prüft, dass alle Chunks Text enthalten (text/content/raw)
|
||||
- Rekonstruiert Body aus Chunks (sortiert nach chunk_index/chunk_id)
|
||||
- Berechnet Coverage: gefundene Textsegmente / Fulltext-Länge
|
||||
3. Validiert gegen notes.payload.fulltext
|
||||
|
||||
Prüfungen pro Note:
|
||||
- Alle Chunks vorhanden (>=1).
|
||||
- Jedes Chunk-Payload hat einen nutzbaren Textschlüssel: "text" (bevorzugt), sonst "content", sonst "raw".
|
||||
- Reihenfolge der Chunks wird stabil bestimmt (payload.chunk_index -> Nummer aus chunk_id).
|
||||
- Coverage: Summe der im Fulltext gefundenen Chunk-Textsegmente / len(Fulltext) (Toleranz für Overlaps).
|
||||
-> OK wenn coverage >= 0.90 (konfigurierbar via --min-coverage)
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: JSON mit Validierungs-Ergebnissen
|
||||
* summary: Gesamtstatistiken
|
||||
* per_note: Details pro Note
|
||||
* coverage: Durchschnittliche Coverage
|
||||
- Exit-Code 0: Alle Prüfungen bestanden
|
||||
- Exit-Code 1: Probleme gefunden
|
||||
|
||||
Ausgabe:
|
||||
- JSON mit Gesamtsummen und Details je Note.
|
||||
Verwendung:
|
||||
-----------
|
||||
- Validierung nach Importen
|
||||
- Diagnose von Text-Rekonstruktionsproblemen
|
||||
- Qualitätskontrolle
|
||||
|
||||
ENV:
|
||||
- QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
|
||||
- COLLECTION_PREFIX (Fallback, wenn --prefix fehlt)
|
||||
Hinweise:
|
||||
---------
|
||||
- Coverage-Toleranz für Overlaps (Standard: >= 0.90)
|
||||
- Prüft Text-Felder: text (bevorzugt), content, raw
|
||||
|
||||
Beispiele:
|
||||
# Alle Notes prüfen (Prefix aus ENV)
|
||||
python3 -m scripts.verify_chunk_texts
|
||||
Aufruf:
|
||||
-------
|
||||
python3 -m scripts.verify_chunk_texts --prefix mindnet
|
||||
python3 -m scripts.verify_chunk_texts --note-id concept-alpha --min-coverage 0.95
|
||||
|
||||
# Nur eine Note prüfen
|
||||
python3 -m scripts.verify_chunk_texts --note-id concept-alpha
|
||||
Parameter:
|
||||
----------
|
||||
--prefix TEXT Collection-Präfix (Default: ENV COLLECTION_PREFIX)
|
||||
--note-id ID Nur eine bestimmte Note prüfen (optional)
|
||||
--min-coverage F Minimale Coverage (Default: 0.90)
|
||||
|
||||
# Prefix explizit setzen und strengere Coverage verlangen
|
||||
python3 -m scripts.verify_chunk_texts --prefix mindnet --min-coverage 0.95
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY, COLLECTION_PREFIX
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v1.0.0 (2025-09-09): Initial Release
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, json, os, re, sys
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
def _names(prefix: str) -> Tuple[str,str,str]:
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
def _client() -> QdrantClient:
|
||||
url = os.getenv("QDRANT_URL")
|
||||
if not url:
|
||||
host = os.getenv("QDRANT_HOST", "127.0.0.1")
|
||||
port = int(os.getenv("QDRANT_PORT", "6333"))
|
||||
url = f"http://{host}:{port}"
|
||||
api_key = os.getenv("QDRANT_API_KEY") or None
|
||||
return QdrantClient(url=url, api_key=api_key)
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
def _chunk_sort_key(p: Dict, pid: str) -> Tuple[int,int,str]:
|
||||
# Primär: payload.chunk_index, sekundär: Nummer am Ende der ID (#cNN oder #NN), sonst 0
|
||||
@@ -104,9 +119,11 @@ def main() -> None:
|
||||
ap.add_argument("--min-coverage", type=float, default=0.90, help="Mindestabdeckung durch Chunks (Default: 0.90)")
|
||||
args = ap.parse_args()
|
||||
|
||||
prefix = args.prefix or os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||
notes_col, chunks_col, _ = _names(prefix)
|
||||
cli = _client()
|
||||
cfg = QdrantConfig.from_env()
|
||||
if args.prefix:
|
||||
cfg.prefix = args.prefix
|
||||
notes_col, chunks_col, _ = collection_names(cfg.prefix)
|
||||
cli = get_client(cfg)
|
||||
|
||||
# Notes abrufen (optional filter by note_id)
|
||||
notes_filter = None
|
||||
@@ -125,7 +142,7 @@ def main() -> None:
|
||||
if off is None:
|
||||
break
|
||||
|
||||
results = []
|
||||
results: List[Dict] = []
|
||||
total_missing_text = 0
|
||||
total_notes_ok = 0
|
||||
for n in notes:
|
||||
|
||||
+51
-19
@@ -1,28 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/wp04_smoketest.py — E2E-Schnelltest der WP-04 Endpunkte
|
||||
FILE: scripts/wp04_smoketest.py
|
||||
VERSION: 2.1.0 (2025-12-15)
|
||||
STATUS: Active (Test-Tool)
|
||||
COMPATIBILITY: v2.9.1 (Post-WP14/WP-15b)
|
||||
|
||||
Zweck:
|
||||
- Holt exemplarisch einen Vektor aus {prefix}_chunks (falls verfügbar),
|
||||
- ruft POST /query mit diesem Vektor auf,
|
||||
- ruft GET /graph/<note_id> für die Top-Note auf,
|
||||
- druckt Kurzresultate auf STDOUT.
|
||||
-------
|
||||
E2E-Schnelltest der WP-04 Endpunkte (/query und /graph).
|
||||
Validiert grundlegende Funktionalität der Retrieval- und Graph-APIs.
|
||||
|
||||
Kompatibilität:
|
||||
Python 3.12+, requests, qdrant-client
|
||||
Version:
|
||||
0.1.0 (Erstanlage)
|
||||
Stand:
|
||||
2025-10-07
|
||||
Bezug:
|
||||
WP-04 /query & /graph
|
||||
Nutzung:
|
||||
export QDRANT_URL="http://localhost:6333"
|
||||
export MINDNET_PREFIX="mindnet"
|
||||
python3 scripts/wp04_smoketest.py --api http://localhost:8000
|
||||
Änderungsverlauf:
|
||||
0.1.0 (2025-10-07) – Erstanlage.
|
||||
Funktionsweise:
|
||||
---------------
|
||||
1. Holt exemplarischen Chunk-Vektor aus Qdrant
|
||||
2. Ruft POST /query mit Test-Query auf
|
||||
3. Ruft GET /graph/<note_id> für Top-Note auf
|
||||
4. Gibt Kurzresultate aus
|
||||
|
||||
Ergebnis-Interpretation:
|
||||
------------------------
|
||||
- Ausgabe: Test-Ergebnisse
|
||||
* query_result: Ergebnis des /query Aufrufs
|
||||
* graph_result: Ergebnis des /graph Aufrufs
|
||||
* status: ok/error
|
||||
- Exit-Code 0: Alle Tests bestanden
|
||||
- Exit-Code 1: Fehler (z.B. API nicht erreichbar, keine Daten)
|
||||
|
||||
Verwendung:
|
||||
-----------
|
||||
- Schnelle Validierung nach Deployment
|
||||
- CI/CD-Tests
|
||||
- Debugging von API-Problemen
|
||||
|
||||
Hinweise:
|
||||
---------
|
||||
- Benötigt vorhandene Daten in Qdrant
|
||||
- Testet nur grundlegende Funktionalität
|
||||
|
||||
Aufruf:
|
||||
-------
|
||||
python3 scripts/wp04_smoketest.py --api http://localhost:8000
|
||||
|
||||
Parameter:
|
||||
----------
|
||||
--api URL Base-URL der mindnet API (Default: http://localhost:8000)
|
||||
|
||||
Umgebungsvariablen:
|
||||
-------------------
|
||||
QDRANT_URL (Default: http://localhost:6333)
|
||||
MINDNET_PREFIX (Default: mindnet)
|
||||
|
||||
Änderungen:
|
||||
-----------
|
||||
v2.1.0 (2025-12-15): Dokumentation aktualisiert
|
||||
v0.1.0 (2025-10-07): Initial Release
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,7 +23,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
REQUIRED = {
|
||||
"notes": ["note_id", "type", "title", "updated", "tags"],
|
||||
|
||||
@@ -9,7 +9,7 @@ if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from qdrant_client.http import models as rest
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
def scroll_all(c, col, flt=None):
|
||||
out, nextp = [], None
|
||||
|
||||
@@ -18,7 +18,7 @@ PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
|
||||
@@ -18,7 +18,7 @@ PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Diagnose-Script: Prüft welche Kanten für eine Note gefunden werden.
|
||||
Hilft beim Debugging der Graph-Anzeige.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Projekt-Root zum sys.path hinzufügen
|
||||
PROJECT_ROOT = Path(__file__).parent.parent
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
def find_edges_for_note(note_id: str, prefix: str = "mindnet"):
|
||||
"""Findet alle Kanten für eine Note und zeigt sie an."""
|
||||
cfg = QdrantConfig.from_env()
|
||||
if prefix:
|
||||
cfg.prefix = prefix
|
||||
|
||||
client = get_client(cfg)
|
||||
_, _, edges_col = collection_names(cfg.prefix)
|
||||
notes_col = f"{cfg.prefix}_notes"
|
||||
|
||||
# 1. Lade Note, um Titel zu bekommen
|
||||
note_res, _ = client.scroll(
|
||||
collection_name=notes_col,
|
||||
scroll_filter=rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))]),
|
||||
limit=1, with_payload=True
|
||||
)
|
||||
|
||||
if not note_res:
|
||||
print(f"❌ Note '{note_id}' nicht gefunden!")
|
||||
return
|
||||
|
||||
note = note_res[0].payload
|
||||
note_title = note.get("title", "")
|
||||
print(f"📄 Note: {note_id}")
|
||||
print(f" Titel: {note_title}\n")
|
||||
|
||||
# 2. Ausgehende Kanten (note_id = unsere Note)
|
||||
print("🔍 AUSGEHENDE KANTEN (note_id = unsere Note):")
|
||||
out_filter = rest.Filter(must=[
|
||||
rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id)),
|
||||
rest.FieldCondition(key="kind", match=rest.MatchExcept(**{"except": ["prev", "next", "belongs_to"]}))
|
||||
])
|
||||
out_edges, _ = client.scroll(edges_col, scroll_filter=out_filter, limit=2000, with_payload=True)
|
||||
print(f" Gefunden: {len(out_edges)} Kanten")
|
||||
for i, e in enumerate(out_edges[:10], 1): # Zeige erste 10
|
||||
pl = e.payload
|
||||
print(f" {i}. {pl.get('kind')}: {pl.get('source_id')} -> {pl.get('target_id')}")
|
||||
if len(out_edges) > 10:
|
||||
print(f" ... und {len(out_edges) - 10} weitere\n")
|
||||
else:
|
||||
print()
|
||||
|
||||
# 3. Eingehende Kanten - exakte Titel-Suche
|
||||
print("🔍 EINGEHENDE KANTEN (target_id = exakter Titel):")
|
||||
if note_title:
|
||||
in_filter_exact = rest.Filter(
|
||||
must=[rest.FieldCondition(key="kind", match=rest.MatchExcept(**{"except": ["prev", "next", "belongs_to"]}))],
|
||||
should=[rest.FieldCondition(key="target_id", match=rest.MatchValue(value=note_title))]
|
||||
)
|
||||
in_edges_exact, _ = client.scroll(edges_col, scroll_filter=in_filter_exact, limit=2000, with_payload=True)
|
||||
print(f" Gefunden: {len(in_edges_exact)} Kanten (exakter Titel)")
|
||||
for i, e in enumerate(in_edges_exact[:10], 1):
|
||||
pl = e.payload
|
||||
print(f" {i}. {pl.get('kind')}: {pl.get('source_id')} -> {pl.get('target_id')}")
|
||||
if len(in_edges_exact) > 10:
|
||||
print(f" ... und {len(in_edges_exact) - 10} weitere\n")
|
||||
else:
|
||||
print()
|
||||
|
||||
# 4. Eingehende Kanten - Titel#Abschnitt Varianten mit Fuzzy-Matching
|
||||
print("🔍 EINGEHENDE KANTEN (target_id beginnt mit 'Titel#' + Fuzzy-Matching):")
|
||||
if note_title:
|
||||
import re
|
||||
# Lade alle Kanten und filtere clientseitig (wie Case D in ui_graph_service.py)
|
||||
all_filter = rest.Filter(
|
||||
must=[rest.FieldCondition(key="kind", match=rest.MatchExcept(**{"except": ["prev", "next", "belongs_to"]}))]
|
||||
)
|
||||
all_edges, _ = client.scroll(edges_col, scroll_filter=all_filter, limit=10000, with_payload=True)
|
||||
print(f" Gesamt geladen: {len(all_edges)} Kanten aus der Datenbank")
|
||||
|
||||
# Normalisierungs-Funktion (wie in ui_graph_service.py)
|
||||
def normalize_title(t):
|
||||
if not t:
|
||||
return ""
|
||||
t = re.sub(r'\s*\([^)]*\)', '', t)
|
||||
t = re.sub(r'\s*\d{4}[\s–\-]*\d{0,4}', '', t)
|
||||
t = re.sub(r'^(Mein|Meine)\s+', '', t, flags=re.IGNORECASE)
|
||||
t = re.sub(r'\s+', ' ', t).strip()
|
||||
return t.lower()
|
||||
|
||||
note_title_norm = normalize_title(note_title)
|
||||
print(f" Normalisierter Note-Titel: '{note_title_norm}'")
|
||||
|
||||
# Clientseitige Filterung: Exakte Matches
|
||||
matched_exact = []
|
||||
for e in all_edges:
|
||||
tgt_id = e.payload.get("target_id", "")
|
||||
if tgt_id and (tgt_id == note_title or tgt_id.startswith(note_title + "#")):
|
||||
matched_exact.append(e)
|
||||
|
||||
# Clientseitige Filterung: Fuzzy-Matches
|
||||
matched_fuzzy = []
|
||||
for e in all_edges:
|
||||
tgt_id = e.payload.get("target_id", "")
|
||||
if not tgt_id or e in matched_exact:
|
||||
continue
|
||||
tgt_base = tgt_id.split("#")[0].strip()
|
||||
tgt_norm = normalize_title(tgt_base)
|
||||
if tgt_norm and note_title_norm and len(note_title_norm) > 5:
|
||||
if (tgt_norm == note_title_norm or
|
||||
tgt_norm.startswith(note_title_norm) or
|
||||
note_title_norm.startswith(tgt_norm)):
|
||||
matched_fuzzy.append((e, tgt_norm))
|
||||
|
||||
matched = matched_exact + [e for e, _ in matched_fuzzy]
|
||||
print(f" Gefunden: {len(matched_exact)} exakte Matches, {len(matched_fuzzy)} Fuzzy-Matches")
|
||||
print(f" Gesamt: {len(matched)} Kanten")
|
||||
for i, e in enumerate(matched[:10], 1):
|
||||
pl = e.payload
|
||||
match_type = "EXAKT" if e in matched_exact else "FUZZY"
|
||||
print(f" {i}. [{match_type}] {pl.get('kind')}: {pl.get('source_id')} -> {pl.get('target_id')}")
|
||||
if len(matched) > 10:
|
||||
print(f" ... und {len(matched) - 10} weitere\n")
|
||||
else:
|
||||
print()
|
||||
|
||||
# Zeige auch einige Beispiele von target_ids, die NICHT matchen
|
||||
print(" 🔍 DEBUG: Beispiel target_ids die NICHT matchen (erste 10):")
|
||||
non_matched = []
|
||||
for e in all_edges[:200]: # Erste 200 prüfen
|
||||
tgt_id = e.payload.get("target_id", "")
|
||||
if not tgt_id or e in matched:
|
||||
continue
|
||||
tgt_base = tgt_id.split("#")[0].strip()
|
||||
tgt_norm = normalize_title(tgt_base)
|
||||
non_matched.append((tgt_id, tgt_norm))
|
||||
if len(non_matched) >= 10:
|
||||
break
|
||||
for i, (tgt, tgt_norm) in enumerate(non_matched, 1):
|
||||
print(f" {i}. '{tgt}' (normalisiert: '{tgt_norm}')")
|
||||
print()
|
||||
|
||||
# 5. Zeige Beispiel target_ids aus der Datenbank
|
||||
print("📊 BEISPIEL target_ids aus der Datenbank (erste 20 mit #):")
|
||||
sample_filter = rest.Filter(
|
||||
must=[rest.FieldCondition(key="kind", match=rest.MatchExcept(**{"except": ["prev", "next", "belongs_to"]}))]
|
||||
)
|
||||
sample_edges, _ = client.scroll(edges_col, scroll_filter=sample_filter, limit=100, with_payload=True)
|
||||
hash_edges = [e for e in sample_edges if "#" in str(e.payload.get("target_id", ""))]
|
||||
for i, e in enumerate(hash_edges[:20], 1):
|
||||
pl = e.payload
|
||||
print(f" {i}. target_id: '{pl.get('target_id')}' (kind: {pl.get('kind')})")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--note-id", required=True, help="Note-ID zum Testen")
|
||||
parser.add_argument("--prefix", default="mindnet", help="Collection-Prefix")
|
||||
args = parser.parse_args()
|
||||
|
||||
find_edges_for_note(args.note_id, args.prefix)
|
||||
|
||||
@@ -37,7 +37,7 @@ if PROJECT_ROOT not in sys.path:
|
||||
|
||||
from qdrant_client.http import models as rest # type: ignore
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
|
||||
def fetch_edges_for_note(note_id: str, prefix: str | None, limit: int = 512) -> List[dict]:
|
||||
|
||||
@@ -10,7 +10,7 @@ WICHTIG: Einige Qdrant-Versionen liefern payload_schema nur, wenn
|
||||
from __future__ import annotations
|
||||
import argparse, json
|
||||
from qdrant_client.http import models as rest
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
def compact_schema(ps: dict | None) -> dict:
|
||||
if not isinstance(ps, dict):
|
||||
|
||||
@@ -33,8 +33,8 @@ PROJECT_ROOT = os.path.dirname(THIS_DIR)
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client # type: ignore
|
||||
import app.core.graph_adapter as ga # type: ignore
|
||||
from app.core.database.qdrant import QdrantConfig, get_client # type: ignore
|
||||
import app.core.graph.graph_subgraph as ga # type: ignore
|
||||
|
||||
|
||||
def build_subgraph_for_note(
|
||||
|
||||
@@ -14,7 +14,7 @@ import urllib.request
|
||||
import urllib.error
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, ensure_payload_indexes, collection_names
|
||||
from app.core.database.qdrant import QdrantConfig, get_client, ensure_payload_indexes, collection_names
|
||||
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.core.parser import read_markdown, normalize_frontmatter, validate_requi
|
||||
from app.core.chunker import assemble_chunks
|
||||
from app.core.chunk_payload import make_chunk_payloads
|
||||
try:
|
||||
from app.core.derive_edges import build_edges_for_note
|
||||
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||
except Exception:
|
||||
from app.core.edges import build_edges_for_note # type: ignore
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import argparse, json, os, sys
|
||||
from typing import Dict, Any, List, Tuple
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
@@ -14,7 +14,7 @@ from unittest.mock import MagicMock, patch, AsyncMock
|
||||
import app.routers.chat
|
||||
from app.models.dto import ChatRequest, QueryHit, QueryRequest
|
||||
from app.services.edge_registry import EdgeRegistry
|
||||
from app.core.retriever import _compute_total_score, _get_status_multiplier
|
||||
from app.core.retrieval.retriever_scoring import compute_wp22_score, get_status_multiplier
|
||||
from app.routers.chat import _classify_intent, get_decision_strategy, chat_endpoint
|
||||
|
||||
class TestWP22Integration(unittest.IsolatedAsyncioTestCase):
|
||||
@@ -93,19 +93,19 @@ class TestWP22Integration(unittest.IsolatedAsyncioTestCase):
|
||||
|
||||
def test_scoring_math(self):
|
||||
print("\n🔵 TEST 2: Scoring Math (Lifecycle)")
|
||||
with patch("app.core.retriever._get_scoring_weights", return_value=(1.0, 1.0, 0.0)):
|
||||
with patch("app.core.retrieval.retriever_scoring.get_weights", return_value=(1.0, 1.0, 0.0)):
|
||||
# Stable (1.2)
|
||||
self.assertEqual(_get_status_multiplier({"status": "stable"}), 1.2)
|
||||
self.assertEqual(get_status_multiplier({"status": "stable"}), 1.2)
|
||||
# Draft (0.5)
|
||||
self.assertEqual(_get_status_multiplier({"status": "draft"}), 0.5)
|
||||
self.assertEqual(get_status_multiplier({"status": "draft"}), 0.5)
|
||||
|
||||
# Scoring Formel Test: BaseScore * (1 + ConfigWeight + DynamicBoost)
|
||||
# BaseScore = 0.5 (sem) * 1.2 (stable) = 0.6
|
||||
# ConfigWeight = 1.0 (neutral) - 1.0 = 0.0
|
||||
# DynamicBoost = (1.0 * 0.5) = 0.5
|
||||
# Total = 0.6 * (1 + 0 + 0.5) = 0.9
|
||||
total, _, _ = _compute_total_score(0.5, {"status": "stable", "retriever_weight": 1.0}, edge_bonus_raw=0.5)
|
||||
self.assertAlmostEqual(total, 0.9)
|
||||
result = compute_wp22_score(0.5, {"status": "stable", "retriever_weight": 1.0}, edge_bonus_raw=0.5)
|
||||
self.assertAlmostEqual(result["total"], 0.9)
|
||||
print("✅ Scoring OK.")
|
||||
|
||||
async def test_router_intent(self):
|
||||
|
||||
@@ -16,7 +16,7 @@ import json
|
||||
from collections import Counter, defaultdict
|
||||
from typing import Dict, Any, List, Tuple
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
|
||||
def _scroll_all(client, collection: str):
|
||||
|
||||
@@ -8,7 +8,7 @@ Zeigt, ob typenbasierte edge_defaults-Relationen (z. B. depends_on/related_to) a
|
||||
from __future__ import annotations
|
||||
from collections import Counter
|
||||
import json
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
def main():
|
||||
cfg = QdrantConfig.from_env()
|
||||
|
||||
@@ -7,7 +7,7 @@ import os
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
from qdrant_client.http import models as rest
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
|
||||
def _rel(pl: dict) -> str:
|
||||
|
||||
@@ -13,7 +13,7 @@ import argparse, json
|
||||
from typing import Dict, Any, List, Tuple
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
from app.core.database.qdrant import QdrantConfig, get_client
|
||||
|
||||
KINDS = ["belongs_to", "next", "prev", "references", "backlink"]
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import create_app
|
||||
import app.core.graph_adapter as ga
|
||||
import app.core.graph.graph_subgraph as ga
|
||||
|
||||
def _fake_get_edges_for_sources(client, prefix, source_ids, edge_types=None, limit=2048):
|
||||
note_id = source_ids[0]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import create_app
|
||||
import app.services.embeddings_client as ec
|
||||
import app.core.qdrant_points as qp
|
||||
import app.core.graph_adapter as ga
|
||||
import app.core.database.qdrant_points as qp
|
||||
import app.core.graph.graph_subgraph as ga
|
||||
|
||||
def _fake_embed_text(text: str):
|
||||
# Liefert stabilen 384-d Vektor ohne echtes Modell
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import create_app
|
||||
import app.core.qdrant_points as qp
|
||||
import app.core.graph_adapter as ga
|
||||
import app.core.database.qdrant_points as qp
|
||||
import app.core.graph.graph_subgraph as ga
|
||||
|
||||
def _fake_search_chunks_by_vector(client, prefix, vector, top=10, filters=None):
|
||||
return [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from app.core import retriever as r
|
||||
from app.core.retrieval import retriever as r
|
||||
from app.models.dto import QueryRequest
|
||||
import app.core.qdrant as qdr
|
||||
import app.core.qdrant_points as qp
|
||||
import app.core.database.qdrant as qdr
|
||||
import app.core.database.qdrant_points as qp
|
||||
import app.services.embeddings_client as ec
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from app.core import retriever as r
|
||||
from app.core.retrieval import retriever as r
|
||||
from app.models.dto import QueryRequest
|
||||
import app.core.qdrant as qdr
|
||||
import app.core.qdrant_points as qp
|
||||
import app.core.graph_adapter as ga
|
||||
import app.core.database.qdrant as qdr
|
||||
import app.core.database.qdrant_points as qp
|
||||
import app.core.graph.graph_subgraph as ga
|
||||
import app.services.embeddings_client as ec
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from app.core import retriever as r
|
||||
from app.core.retrieval import retriever as r
|
||||
from app.models.dto import QueryRequest
|
||||
import app.core.qdrant as qdr
|
||||
import app.core.qdrant_points as qp
|
||||
import app.core.database.qdrant as qdr
|
||||
import app.core.database.qdrant_points as qp
|
||||
import app.services.embeddings_client as ec
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ sys.path.insert(0, str(ROOT_DIR))
|
||||
|
||||
# Import der Kernkomponenten
|
||||
from app.core import chunker
|
||||
from app.core import derive_edges
|
||||
from app.core.graph import graph_derive_edges as derive_edges
|
||||
from app.services.semantic_analyzer import SemanticAnalyzer
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user