Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
300086fc83 | ||
|
|
688eb262a9 | ||
|
|
bfb6f5dede | ||
|
|
88c0fbe56b | ||
|
|
3d74eff224 | ||
|
|
22d08afe2d | ||
|
|
a97f757e34 | ||
|
|
bbc8f13944 | ||
|
|
f18a40d76c | ||
|
|
c7644a36aa | ||
|
|
f394f31c12 | ||
|
|
0513673c2a | ||
|
|
a73542a391 | ||
|
|
c465797654 | ||
|
|
7ce3f982f2 | ||
|
|
6311456917 | ||
|
|
3c06559c5d | ||
|
|
5c9f2e8c83 | ||
|
|
62902faaca | ||
|
|
d22fd77b22 | ||
|
|
2f86f493d6 | ||
|
|
eafa0fad85 | ||
|
|
2e7c497b69 | ||
|
|
79dcfdcf9a | ||
|
|
487e28a904 | ||
|
|
c492f97a67 | ||
|
|
ec2ff74514 | ||
|
|
c501f8d6e6 | ||
|
|
b4287cbfda | ||
|
|
26724a1db1 | ||
|
|
d6368ee709 | ||
|
|
ea211a5c0b | ||
|
|
9e8b433c95 | ||
|
|
2a1c62aeed | ||
|
|
948d6f4b47 | ||
|
|
725271a7da | ||
|
|
4ea62e6886 | ||
|
|
c01cf3b078 | ||
|
|
c67777a6b9 | ||
|
|
e5e5e7560c | ||
|
|
6e1cd5fbbc | ||
|
|
8bd8f7c0bb | ||
|
|
1c42cd1f78 | ||
|
|
be090a43f2 |
No files matched your search
+111
-162
@@ -1,180 +1,129 @@
|
||||
# chunk_payload.py
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
app/core/chunk_payload.py (Mindnet V2 — types.yaml authoritative)
|
||||
- neighbors_prev / neighbors_next sind Listen ([], [id]).
|
||||
- retriever_weight / chunk_profile kommen aus types.yaml (Frontmatter wird ignoriert).
|
||||
- Fallbacks: defaults.* in types.yaml; sonst 1.0 / "default".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
import os, json, pathlib, re, yaml, hashlib
|
||||
from typing import Any, Dict, List, Optional
|
||||
import os, yaml
|
||||
|
||||
FRONTMATTER_RE = re.compile(r"^---\s*\n.*?\n---\s*\n?", re.DOTALL)
|
||||
def _env(n: str, d: Optional[str]=None) -> str:
|
||||
v = os.getenv(n)
|
||||
return v if v is not None else (d or "")
|
||||
|
||||
def _as_dict(note: Any) -> Dict[str, Any]:
|
||||
if isinstance(note, dict):
|
||||
return note
|
||||
d: Dict[str, Any] = {}
|
||||
for attr in ("id","note_id","title","path","frontmatter","meta","metadata","body","text","content","raw","markdown","type","chunks"):
|
||||
if hasattr(note, attr):
|
||||
d[attr] = getattr(note, attr)
|
||||
fm = d.get("frontmatter") or d.get("meta") or d.get("metadata") or {}
|
||||
d["frontmatter"] = fm if isinstance(fm, dict) else {}
|
||||
return d
|
||||
def _load_types() -> dict:
|
||||
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||
try:
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[Dict[str,Any]]]:
|
||||
path = kwargs.get("path")
|
||||
types_cfg = kwargs.get("types_config")
|
||||
for a in args:
|
||||
if path is None and isinstance(a, (str, pathlib.Path)):
|
||||
path = str(a)
|
||||
if types_cfg is None and isinstance(a, dict):
|
||||
types_cfg = a
|
||||
return path, types_cfg
|
||||
def _get_types_map(reg: dict) -> dict:
|
||||
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
||||
return reg["types"]
|
||||
return reg if isinstance(reg, dict) else {}
|
||||
|
||||
def _load_types_config(explicit: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
if isinstance(explicit, dict):
|
||||
return explicit
|
||||
for rel in ("config/config.yaml", "config/types.yaml"):
|
||||
p = pathlib.Path(rel)
|
||||
if p.exists():
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
if isinstance(data, dict) and "types" in data and isinstance(data["types"], dict):
|
||||
return data["types"]
|
||||
return data if isinstance(data, dict) else {}
|
||||
def _get_defaults(reg: dict) -> dict:
|
||||
if isinstance(reg, dict) and isinstance(reg.get("defaults"), dict):
|
||||
return reg["defaults"]
|
||||
if isinstance(reg, dict) and isinstance(reg.get("global"), dict):
|
||||
return reg["global"]
|
||||
return {}
|
||||
|
||||
def _coalesce(*vals):
|
||||
for v in vals:
|
||||
def _as_float(x: Any):
|
||||
try:
|
||||
return float(x)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _resolve_chunk_profile(note_type: str, reg: dict) -> str:
|
||||
types = _get_types_map(reg)
|
||||
if isinstance(types, dict):
|
||||
t = types.get(note_type, {})
|
||||
if isinstance(t, dict) and isinstance(t.get("chunk_profile"), str):
|
||||
return t["chunk_profile"]
|
||||
defs = _get_defaults(reg)
|
||||
if isinstance(defs, dict) and isinstance(defs.get("chunk_profile"), str):
|
||||
return defs["chunk_profile"]
|
||||
return "default"
|
||||
|
||||
def _resolve_retriever_weight(note_type: str, reg: dict) -> float:
|
||||
types = _get_types_map(reg)
|
||||
if isinstance(types, dict):
|
||||
t = types.get(note_type, {})
|
||||
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
||||
v = _as_float(t.get("retriever_weight"))
|
||||
if v is not None:
|
||||
return float(v)
|
||||
defs = _get_defaults(reg)
|
||||
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
||||
v = _as_float(defs.get("retriever_weight"))
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
return float(v)
|
||||
return 1.0
|
||||
|
||||
def _text_from_note(n: Dict[str, Any], path_hint: Optional[str]) -> str:
|
||||
# häufige Felder
|
||||
cand = [
|
||||
n.get("body"),
|
||||
n.get("text"),
|
||||
n.get("markdown"),
|
||||
n.get("raw"),
|
||||
]
|
||||
content = n.get("content")
|
||||
if isinstance(content, str):
|
||||
cand.append(content)
|
||||
elif isinstance(content, dict):
|
||||
for k in ("text","body","raw","markdown","content"):
|
||||
v = content.get(k)
|
||||
if isinstance(v, str):
|
||||
cand.append(v)
|
||||
for t in cand:
|
||||
if isinstance(t, str) and t.strip():
|
||||
return t
|
||||
|
||||
# Fallback: Datei lesen und Frontmatter entfernen
|
||||
p = n.get("path") or path_hint
|
||||
if p:
|
||||
try:
|
||||
pth = pathlib.Path(p)
|
||||
if pth.exists():
|
||||
txt = pth.read_text(encoding="utf-8", errors="ignore")
|
||||
if txt:
|
||||
return FRONTMATTER_RE.sub("", txt).strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
def _iter_chunks(n: Dict[str, Any], profile: str, fulltext: str) -> List[Dict[str, Any]]:
|
||||
# 1) vorhandene Chunks nehmen, wenn sinnvoll
|
||||
existing = n.get("chunks")
|
||||
out: List[Dict[str, Any]] = []
|
||||
if isinstance(existing, list) and existing:
|
||||
for i, c in enumerate(existing):
|
||||
text = ""
|
||||
if isinstance(c, dict):
|
||||
text = c.get("text") or c.get("body") or c.get("raw") or ""
|
||||
elif isinstance(c, str):
|
||||
text = c
|
||||
if text and text.strip():
|
||||
out.append({"index": i, "text": text})
|
||||
if out:
|
||||
return out
|
||||
|
||||
# 2) Fallback: profilabhängige Bündelung
|
||||
if not isinstance(profile, str):
|
||||
profile = "medium"
|
||||
size = {"short": 600, "medium": 1200, "long": 2400}.get(profile, 1200)
|
||||
if not fulltext:
|
||||
def _as_list(x):
|
||||
if x is None:
|
||||
return []
|
||||
paras = re.split(r"\n{2,}", fulltext)
|
||||
buf = ""
|
||||
chunks: List[str] = []
|
||||
for p in paras:
|
||||
p = (p or "").strip()
|
||||
if not p:
|
||||
continue
|
||||
if len(buf) + (2 if buf else 0) + len(p) <= size:
|
||||
buf = (buf + "\n\n" + p).strip() if buf else p
|
||||
else:
|
||||
if buf: chunks.append(buf)
|
||||
if len(p) <= size:
|
||||
buf = p
|
||||
else:
|
||||
for i in range(0, len(p), size):
|
||||
chunks.append(p[i:i+size])
|
||||
buf = ""
|
||||
if buf: chunks.append(buf)
|
||||
return [{"index": i, "text": c} for i, c in enumerate(chunks)]
|
||||
if isinstance(x, list):
|
||||
return x
|
||||
return [x]
|
||||
|
||||
def make_chunk_payloads(note: Any, *args, **kwargs) -> List[Dict[str, Any]]:
|
||||
n = _as_dict(note)
|
||||
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
||||
types_cfg = _load_types_config(types_cfg_explicit)
|
||||
def make_chunk_payloads(note: Dict[str, Any],
|
||||
note_path: str,
|
||||
chunks_from_chunker: List[Any],
|
||||
*,
|
||||
note_text: str = "",
|
||||
types_cfg: Optional[dict] = None,
|
||||
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
fm = (note or {}).get("frontmatter", {}) or {}
|
||||
note_type = fm.get("type") or note.get("type") or "concept"
|
||||
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
||||
|
||||
fm = n.get("frontmatter") or {}
|
||||
note_type = str(fm.get("type") or n.get("type") or "note")
|
||||
cfg_for_type = types_cfg.get(note_type, {}) if isinstance(types_cfg, dict) else {}
|
||||
# types.yaml authoritative
|
||||
cp = _resolve_chunk_profile(note_type, reg)
|
||||
rw = _resolve_retriever_weight(note_type, reg)
|
||||
|
||||
try:
|
||||
default_rw = float(os.environ.get("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0))
|
||||
except Exception:
|
||||
default_rw = 1.0
|
||||
tags = fm.get("tags") or []
|
||||
if isinstance(tags, str):
|
||||
tags = [tags]
|
||||
|
||||
retriever_weight = _coalesce(fm.get("retriever_weight"), cfg_for_type.get("retriever_weight"), default_rw)
|
||||
try:
|
||||
retriever_weight = float(retriever_weight)
|
||||
except Exception:
|
||||
retriever_weight = default_rw
|
||||
out: List[Dict[str, Any]] = []
|
||||
for idx, ch in enumerate(chunks_from_chunker):
|
||||
# Attribute oder Keys (Chunk-Objekt oder Dict)
|
||||
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
|
||||
nid = getattr(ch, "note_id", None) or (ch.get("note_id") if isinstance(ch, dict) else fm.get("id"))
|
||||
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
||||
text = getattr(ch, "text", None) or (ch.get("text") if isinstance(ch, dict) else "")
|
||||
window = getattr(ch, "window", None) or (ch.get("window") if isinstance(ch, dict) else text)
|
||||
prev_id = getattr(ch, "neighbors_prev", None) or (ch.get("neighbors_prev") if isinstance(ch, dict) else None)
|
||||
next_id = getattr(ch, "neighbors_next", None) or (ch.get("neighbors_next") if isinstance(ch, dict) else None)
|
||||
|
||||
chunk_profile = _coalesce(fm.get("chunk_profile"), cfg_for_type.get("chunk_profile"), os.environ.get("MINDNET_DEFAULT_CHUNK_PROFILE","medium"))
|
||||
chunk_profile = chunk_profile if isinstance(chunk_profile, str) else "medium"
|
||||
|
||||
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||
title = n.get("title") or fm.get("title") or ""
|
||||
path = n.get("path") or path_arg
|
||||
if isinstance(path, pathlib.Path):
|
||||
path = str(path)
|
||||
path = path or "" # immer vorhanden
|
||||
|
||||
fulltext = _text_from_note(n, path)
|
||||
chunks = _iter_chunks(n, chunk_profile, fulltext)
|
||||
|
||||
payloads: List[Dict[str, Any]] = []
|
||||
for c in chunks:
|
||||
idx = c.get("index", len(payloads))
|
||||
text = c.get("text") if isinstance(c, dict) else (str(c) if c is not None else "")
|
||||
text = text if isinstance(text, str) else str(text or "")
|
||||
|
||||
key = f"{note_id}|{idx}"
|
||||
h = hashlib.sha1(key.encode("utf-8")).hexdigest()[:12] if note_id else hashlib.sha1(f"{path}|{idx}".encode("utf-8")).hexdigest()[:12]
|
||||
chunk_id = f"{note_id}-{idx:03d}-{h}" if note_id else f"{h}"
|
||||
|
||||
payload = {
|
||||
"note_id": note_id,
|
||||
"chunk_id": chunk_id,
|
||||
"index": idx,
|
||||
"title": title,
|
||||
pl: Dict[str, Any] = {
|
||||
"note_id": nid,
|
||||
"chunk_id": cid,
|
||||
"index": int(index),
|
||||
"ord": int(index) + 1,
|
||||
"type": note_type,
|
||||
"path": path, # <- garantiert vorhanden
|
||||
"text": text, # <- nie leer, sonst werden keine Chunks erzeugt
|
||||
"retriever_weight": retriever_weight,
|
||||
"chunk_profile": chunk_profile,
|
||||
"tags": tags,
|
||||
"text": text,
|
||||
"window": window,
|
||||
"neighbors_prev": _as_list(prev_id),
|
||||
"neighbors_next": _as_list(next_id),
|
||||
"section": getattr(ch, "section", None) or (ch.get("section") if isinstance(ch, dict) else ""),
|
||||
"path": note_path,
|
||||
"source_path": file_path or note_path,
|
||||
"retriever_weight": float(rw),
|
||||
"chunk_profile": cp,
|
||||
}
|
||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||
payloads.append(payload)
|
||||
# Aufräumen von Alt-Feldern
|
||||
for alias in ("chunk_num", "Chunk_Number"):
|
||||
pl.pop(alias, None)
|
||||
|
||||
return payloads
|
||||
out.append(pl)
|
||||
|
||||
return out
|
||||
@@ -3,10 +3,7 @@
|
||||
"""
|
||||
Modul: app/core/derive_edges.py
|
||||
Version: 1.4.0
|
||||
Datum: 2025-10-01
|
||||
|
||||
Zweck
|
||||
-----
|
||||
Robuste Kantenbildung für mindnet (Notes/Chunks):
|
||||
- belongs_to (chunk -> note)
|
||||
- next / prev (chunk-Kette)
|
||||
@@ -15,25 +12,12 @@ Robuste Kantenbildung für mindnet (Notes/Chunks):
|
||||
|
||||
Wichtig: Wikilinks werden mit der Parser-Funktion `extract_wikilinks` extrahiert,
|
||||
damit Varianten wie [[id#anchor]] oder [[id|label]] korrekt auf 'id' reduziert werden.
|
||||
|
||||
Erwartete Chunk-Payload-Felder:
|
||||
{
|
||||
"note_id": "...",
|
||||
"chunk_id": "...", # Alias "id" ist zulässig
|
||||
"id": "...",
|
||||
"chunk_index": int,
|
||||
"seq": int,
|
||||
"window": str,
|
||||
"text": str,
|
||||
"path": "rel/path.md",
|
||||
...
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List, Optional, Iterable
|
||||
|
||||
# WICHTIG: benutze die Parser-Extraktion für saubere Wikilinks
|
||||
# Parser-Extraktion für saubere Wikilinks
|
||||
from app.core.parser import extract_wikilinks
|
||||
|
||||
def _get(d: dict, *keys, default=None):
|
||||
@@ -113,7 +97,7 @@ def build_edges_for_note(
|
||||
if not cid:
|
||||
continue
|
||||
txt = _chunk_text_for_refs(ch)
|
||||
refs = extract_wikilinks(txt) # <— Parser-Logik, kompatibel zu deinem System
|
||||
refs = extract_wikilinks(txt) # Parser-Logik
|
||||
for r in refs:
|
||||
edges.append(_edge("references", "chunk", cid, r, note_id, {"chunk_id": cid, "ref_text": r}))
|
||||
refs_all.extend(refs)
|
||||
@@ -128,4 +112,9 @@ def build_edges_for_note(
|
||||
edges.append(_edge("references", "note", note_id, r, note_id))
|
||||
edges.append(_edge("backlink", "note", r, note_id, note_id))
|
||||
|
||||
return edges
|
||||
# Dedupe (Schlüssel: kind,source_id,target_id,scope)
|
||||
dedup = {}
|
||||
for e in edges:
|
||||
k = (e["kind"], e["source_id"], e["target_id"], e.get("scope", ""))
|
||||
dedup[k] = e
|
||||
return list(dedup.values())
|
||||
+257
-81
@@ -2,119 +2,295 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Modul: app/core/edges.py
|
||||
Version: 1.0.0
|
||||
Datum: 2025-09-09
|
||||
Version: 2.0.0 (V2‑superset, rückwärtskompatibel zu v1 vom 2025‑09‑09)
|
||||
|
||||
Zweck
|
||||
-----
|
||||
Zentrale, konsistente Erzeugung von Edge-Payloads im **neuen Schema**:
|
||||
- kind : "belongs_to" | "next" | "prev" | "references" | "backlink"
|
||||
- source_id : ID des Quellknotens (Chunk- oder Note-ID)
|
||||
- target_id : ID des Zielknotens
|
||||
- scope : "chunk" | "note"
|
||||
- note_id : Owner-Note (für performantes Filtern/Löschen)
|
||||
- seq : optional (z. B. Reihenfolge von Vorkommen)
|
||||
Bewahrt die bestehende Edgelogik (belongs_to, prev/next, references, backlink)
|
||||
und ergänzt V2‑Felder + Typ‑Default‑Kanten gemäß config/types.yaml (edge_defaults).
|
||||
Die Funktion ist **idempotent** und **rückwärtskompatibel** zur bisherigen Signatur.
|
||||
|
||||
Hinweise
|
||||
--------
|
||||
- Edges werden dedupliziert (key=(kind,source_id,target_id,scope)).
|
||||
- Für Chunk-Edges wird `note_id` aus dem Chunk-Payload entnommen.
|
||||
- Für Note-Scope-Edges ist `note_id` die Quell-Note-ID.
|
||||
Kompatibilitätsgarantien (gegenüber v1):
|
||||
- **Input**: akzeptiert identische Chunk‑Payloads wie v1:
|
||||
* `id` (Chunk‑ID), `note_id` (Owner), `neighbors.prev|next` (optional),
|
||||
`references: [{target_id: ...}]` (optional),
|
||||
alternativ: `chunk_id`, `chunk_index|ord`, `window|text`
|
||||
- **Output (v1‑Felder)**: `kind`, `source_id`, `target_id`, `scope`, `note_id`, `edge_id`
|
||||
- **Neu (v2‑Felder)**: `relation`, `src_note_id`, `src_chunk_id?`, `dst_note_id`, `dst_chunk_id?`,
|
||||
`provenance` (`explicit|rule`), `rule_id?`, `confidence?`
|
||||
|
||||
Regeln
|
||||
------
|
||||
- Deduplizierungsschlüssel: (source_id, target_id, relation, rule_id)
|
||||
- Strukturkanten:
|
||||
* belongs_to: 1× pro Chunk
|
||||
* next/prev: Sequenz der Chunks; nutzt bevorzugt neighbors; sonst ord/chunk_index
|
||||
- Explizite Referenzen:
|
||||
* aus Chunk: `references[].target_id` (falls vorhanden)
|
||||
* Fallback: Wikilinks in `window|text`: [[Some Title|some-id]] oder [[some-id]]
|
||||
- Note‑Scope:
|
||||
* backlink immer; references nur, wenn include_note_scope_refs=True
|
||||
- Typ‑Defaults (edge_defaults aus config/types.yaml des **Quell‑Notiztyps**):
|
||||
* Für jede explizite Referenz wird je default‑Relation eine Regel‑Kante erzeugt
|
||||
* rule_id: "type_default:{note_type}:{relation}:v1", provenance="rule"
|
||||
|
||||
Konfiguration
|
||||
-------------
|
||||
- ENV MINDNET_TYPES_FILE (Default: ./config/types.yaml)
|
||||
|
||||
Lizenz/Autor
|
||||
------------
|
||||
- Erstimplementierung v1 (2025‑09‑09) — Projekt Mindnet
|
||||
- Erweiterung v2 (2025‑11‑11) — kompatible Superset‑Implementierung
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Dict, List
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Dict, Iterable, List, Optional, Tuple, Set
|
||||
|
||||
try:
|
||||
import yaml # optional, nur für types.yaml
|
||||
except Exception: # pragma: no cover
|
||||
yaml = None
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Hilfen: types.yaml laden (edge_defaults)
|
||||
# ------------------------------------------------------------
|
||||
|
||||
def _types_path() -> str:
|
||||
return os.getenv("MINDNET_TYPES_FILE") or "./config/types.yaml"
|
||||
|
||||
def _load_types() -> Dict[str, dict]:
|
||||
p = _types_path()
|
||||
if not os.path.isfile(p) or yaml is None:
|
||||
return {}
|
||||
try:
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
if isinstance(data, dict) and "types" in data and isinstance(data["types"], dict):
|
||||
return data["types"]
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _edge_defaults_for(note_type: Optional[str]) -> List[str]:
|
||||
types = _load_types()
|
||||
t = (note_type or "").strip().lower()
|
||||
cfg = types.get(t) or {}
|
||||
defaults = cfg.get("edge_defaults") or []
|
||||
if isinstance(defaults, str):
|
||||
defaults = [defaults]
|
||||
return [str(x) for x in defaults if isinstance(x, (str, int, float))]
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Wikilink‑Parser (Fallback, wenn ch["references"] fehlt)
|
||||
# ------------------------------------------------------------
|
||||
|
||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
||||
|
||||
def _extract_wikilinks(text: str) -> List[str]:
|
||||
ids: List[str] = []
|
||||
for m in _WIKILINK_RE.finditer(text or ""):
|
||||
ids.append(m.group(1).strip())
|
||||
return ids
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Utility
|
||||
# ------------------------------------------------------------
|
||||
|
||||
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None) -> str:
|
||||
base = f"{kind}:{s}->{t}#{scope}"
|
||||
if rule_id:
|
||||
base += f"|{rule_id}"
|
||||
try:
|
||||
import hashlib
|
||||
return hashlib.blake2s(base.encode("utf-8"), digest_size=12).hexdigest()
|
||||
except Exception: # pragma: no cover
|
||||
return base
|
||||
|
||||
def _dedupe(edges: List[Dict]) -> List[Dict]:
|
||||
seen: Set[Tuple[str,str,str,str]] = set()
|
||||
out: List[Dict] = []
|
||||
for e in edges:
|
||||
s = str(e.get("source_id") or "")
|
||||
t = str(e.get("target_id") or "")
|
||||
rel = str(e.get("relation") or e.get("kind") or "edge")
|
||||
rule = str(e.get("rule_id") or "")
|
||||
key = (s, t, rel, rule)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
def _first(v: dict, *keys, default=None):
|
||||
for k in keys:
|
||||
if k in v and v[k] is not None:
|
||||
return v[k]
|
||||
return default
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Hauptfunktion
|
||||
# ------------------------------------------------------------
|
||||
|
||||
def build_edges_for_note(
|
||||
note_id: str,
|
||||
chunk_payloads: List[Dict],
|
||||
note_level_refs: List[str] | None,
|
||||
note_level_refs: Optional[List[str]] = None,
|
||||
*,
|
||||
include_note_scope_refs: bool = False,
|
||||
) -> List[Dict]:
|
||||
edges: List[Dict] = []
|
||||
chunks = list(chunk_payloads or [])
|
||||
# Notiztyp aus erstem Chunk ableiten (kompatibel zu existierenden Payloads)
|
||||
note_type = (chunks[0].get("type") if chunks else None) or (chunks[0].get("note_type") if chunks else None)
|
||||
|
||||
# Chunk-Scope: belongs_to / prev / next / references
|
||||
for ch in chunk_payloads:
|
||||
cid = ch["id"]
|
||||
# --- Strukturkanten ------------------------------------------------------
|
||||
# belongs_to
|
||||
for ch in chunks:
|
||||
cid = _first(ch, "id", "chunk_id")
|
||||
if not cid:
|
||||
continue
|
||||
owner = ch.get("note_id") or note_id
|
||||
# belongs_to
|
||||
edges.append({
|
||||
e = {
|
||||
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to:v1"),
|
||||
"kind": "belongs_to",
|
||||
"relation": "belongs_to",
|
||||
"scope": "chunk",
|
||||
"source_id": cid,
|
||||
"target_id": note_id,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
})
|
||||
# Nachbarn
|
||||
"note_id": owner, # v1-Kompat
|
||||
# v2
|
||||
"src_note_id": owner,
|
||||
"src_chunk_id": cid,
|
||||
"dst_note_id": note_id,
|
||||
"provenance": "rule",
|
||||
"rule_id": "structure:belongs_to:v1",
|
||||
"confidence": 1.0,
|
||||
}
|
||||
edges.append(e)
|
||||
|
||||
# next/prev — bevorzugt neighbors.prev/next; sonst via ord/chunk_index
|
||||
# Map der Chunks nach Index
|
||||
ordered = list(chunks)
|
||||
def _idx(c):
|
||||
return _first(c, "chunk_index", "ord", default=0)
|
||||
ordered.sort(key=_idx)
|
||||
|
||||
for i, ch in enumerate(ordered):
|
||||
cid = _first(ch, "id", "chunk_id")
|
||||
if not cid:
|
||||
continue
|
||||
owner = ch.get("note_id") or note_id
|
||||
nb = ch.get("neighbors") or {}
|
||||
prev_id = nb.get("prev")
|
||||
next_id = nb.get("next")
|
||||
# Fallback-Reihenfolge
|
||||
if prev_id is None and i > 0:
|
||||
prev_id = _first(ordered[i-1], "id", "chunk_id")
|
||||
if next_id is None and i+1 < len(ordered):
|
||||
next_id = _first(ordered[i+1], "id", "chunk_id")
|
||||
|
||||
if prev_id:
|
||||
edges.append({
|
||||
"kind": "prev",
|
||||
"source_id": cid,
|
||||
"target_id": prev_id,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
"edge_id": _mk_edge_id("prev", cid, prev_id, "chunk", "structure:order:v1"),
|
||||
"kind": "prev", "relation": "prev", "scope": "chunk",
|
||||
"source_id": cid, "target_id": prev_id, "note_id": owner,
|
||||
"src_note_id": owner, "src_chunk_id": cid,
|
||||
"dst_note_id": owner, "dst_chunk_id": prev_id,
|
||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
||||
})
|
||||
edges.append({
|
||||
"kind": "next",
|
||||
"source_id": prev_id,
|
||||
"target_id": cid,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
})
|
||||
if next_id:
|
||||
edges.append({
|
||||
"kind": "next",
|
||||
"source_id": cid,
|
||||
"target_id": next_id,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
})
|
||||
edges.append({
|
||||
"kind": "prev",
|
||||
"source_id": next_id,
|
||||
"target_id": cid,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
})
|
||||
# references aus Chunk
|
||||
for ref in (ch.get("references") or []):
|
||||
tid = ref.get("target_id")
|
||||
if not tid:
|
||||
continue
|
||||
edges.append({
|
||||
"kind": "references",
|
||||
"source_id": cid,
|
||||
"target_id": tid,
|
||||
"scope": "chunk",
|
||||
"note_id": owner,
|
||||
"edge_id": _mk_edge_id("next", prev_id, cid, "chunk", "structure:order:v1"),
|
||||
"kind": "next", "relation": "next", "scope": "chunk",
|
||||
"source_id": prev_id, "target_id": cid, "note_id": owner,
|
||||
"src_note_id": owner, "src_chunk_id": prev_id,
|
||||
"dst_note_id": owner, "dst_chunk_id": cid,
|
||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
||||
})
|
||||
|
||||
# Note-Scope: backlink (immer); references (optional)
|
||||
unique_refs = list(dict.fromkeys(note_level_refs or []))
|
||||
# --- Explizite Referenzen (Chunk‑Scope) ---------------------------------
|
||||
explicit_refs: List[Dict] = []
|
||||
for ch in chunks:
|
||||
cid = _first(ch, "id", "chunk_id")
|
||||
if not cid:
|
||||
continue
|
||||
owner = ch.get("note_id") or note_id
|
||||
# 1) bevorzugt vorhandene ch["references"]
|
||||
refs = ch.get("references") or []
|
||||
targets = [r.get("target_id") for r in refs if isinstance(r, dict) and r.get("target_id")]
|
||||
# 2) Fallback: Wikilinks aus Text
|
||||
if not targets:
|
||||
text = _first(ch, "window", "text", default="") or ""
|
||||
targets = _extract_wikilinks(text)
|
||||
for tid in targets:
|
||||
if not isinstance(tid, str) or not tid.strip():
|
||||
continue
|
||||
e = {
|
||||
"edge_id": _mk_edge_id("references", cid, tid, "chunk"),
|
||||
"kind": "references",
|
||||
"relation": "references",
|
||||
"scope": "chunk",
|
||||
"source_id": cid,
|
||||
"target_id": tid,
|
||||
"note_id": owner,
|
||||
# v2
|
||||
"src_note_id": owner,
|
||||
"src_chunk_id": cid,
|
||||
"dst_note_id": tid,
|
||||
"provenance": "explicit",
|
||||
"rule_id": "",
|
||||
"confidence": 1.0,
|
||||
}
|
||||
edges.append(e)
|
||||
explicit_refs.append(e)
|
||||
|
||||
# --- Note‑Scope: references (optional) + backlink (immer) ----------------
|
||||
unique_refs = []
|
||||
if note_level_refs:
|
||||
seen = set()
|
||||
for tid in note_level_refs:
|
||||
if isinstance(tid, str) and tid.strip() and tid not in seen:
|
||||
unique_refs.append(tid); seen.add(tid)
|
||||
|
||||
for tid in unique_refs:
|
||||
if include_note_scope_refs:
|
||||
edges.append({
|
||||
"kind": "references",
|
||||
"source_id": note_id,
|
||||
"target_id": tid,
|
||||
"scope": "note",
|
||||
"note_id": note_id,
|
||||
"edge_id": _mk_edge_id("references", note_id, tid, "note"),
|
||||
"kind": "references", "relation": "references", "scope": "note",
|
||||
"source_id": note_id, "target_id": tid, "note_id": note_id,
|
||||
"src_note_id": note_id, "dst_note_id": tid,
|
||||
"provenance": "explicit", "rule_id": "", "confidence": 1.0,
|
||||
})
|
||||
edges.append({
|
||||
"kind": "backlink",
|
||||
"source_id": tid,
|
||||
"target_id": note_id,
|
||||
"scope": "note",
|
||||
"note_id": note_id,
|
||||
"edge_id": _mk_edge_id("backlink", tid, note_id, "note", "derived:backlink:v1"),
|
||||
"kind": "backlink", "relation": "backlink", "scope": "note",
|
||||
"source_id": tid, "target_id": note_id, "note_id": note_id,
|
||||
"src_note_id": tid, "dst_note_id": note_id,
|
||||
"provenance": "rule", "rule_id": "derived:backlink:v1", "confidence": 0.9,
|
||||
})
|
||||
|
||||
# Dedupe
|
||||
dedup = {}
|
||||
for e in edges:
|
||||
k = (e["kind"], e["source_id"], e["target_id"], e.get("scope", ""))
|
||||
dedup[k] = e
|
||||
return list(dedup.values())
|
||||
# --- Type‑Defaults je expliziter Referenz --------------------------------
|
||||
defaults = [d for d in _edge_defaults_for(note_type) if d and d != "references"]
|
||||
if defaults:
|
||||
for e in explicit_refs + ([ ] if not include_note_scope_refs else []):
|
||||
# wir nutzen die bereits erzeugten explicit‑Edges als Vorlage
|
||||
src = e["source_id"]; tgt = e["target_id"]
|
||||
scope = e.get("scope", "chunk")
|
||||
s_note = e.get("src_note_id") or note_id
|
||||
s_chunk = e.get("src_chunk_id")
|
||||
t_note = e.get("dst_note_id") or tgt
|
||||
for rel in defaults:
|
||||
rule_id = f"type_default:{(note_type or 'unknown')}:{rel}:v1"
|
||||
edges.append({
|
||||
"edge_id": _mk_edge_id(rel, src, tgt, scope, rule_id),
|
||||
"kind": rel, "relation": rel, "scope": scope,
|
||||
"source_id": src, "target_id": tgt, "note_id": s_note,
|
||||
"src_note_id": s_note, "src_chunk_id": s_chunk,
|
||||
"dst_note_id": t_note,
|
||||
"provenance": "rule", "rule_id": rule_id, "confidence": 0.7,
|
||||
})
|
||||
|
||||
# --- Dedupe & Return -----------------------------------------------------
|
||||
return _dedupe(edges)
|
||||
+141
-86
@@ -1,104 +1,159 @@
|
||||
# note_payload.py
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
app/core/note_payload.py (Mindnet V2 — types.yaml authoritative)
|
||||
- retriever_weight und chunk_profile werden aus config/types.yaml gelesen.
|
||||
- Reihenfolge: types.<type> > defaults.* > Fallbacks (1.0 / "default").
|
||||
- Frontmatter-Overrides für diese beiden Felder werden bewusst IGNORIERT.
|
||||
- edge_defaults (falls in types.yaml definiert) werden in die Note-Payload gespiegelt.
|
||||
- MINDNET_TYPES_FILE kann absoluten Pfad liefern, sonst ./config/types.yaml.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
import os, json, pathlib, yaml
|
||||
from typing import Any, Dict, Optional, List
|
||||
import os, yaml, hashlib, datetime
|
||||
|
||||
def _as_dict(note: Any) -> Dict[str, Any]:
|
||||
if isinstance(note, dict):
|
||||
return note
|
||||
d: Dict[str, Any] = {}
|
||||
for attr in ("id","note_id","title","path","frontmatter","meta","metadata","type","created","modified","date","tags"):
|
||||
if hasattr(note, attr):
|
||||
d[attr] = getattr(note, attr)
|
||||
# Normalisiere Frontmatter
|
||||
fm = d.get("frontmatter") or d.get("meta") or d.get("metadata") or {}
|
||||
d["frontmatter"] = fm if isinstance(fm, dict) else {}
|
||||
return d
|
||||
# ----------------------- helpers -----------------------
|
||||
|
||||
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[Dict[str,Any]]]:
|
||||
path = kwargs.get("path")
|
||||
types_cfg = kwargs.get("types_config")
|
||||
# legacy positional: (path, types_config) oder (types_config, ...)
|
||||
for a in args:
|
||||
if path is None and isinstance(a, (str, pathlib.Path)):
|
||||
path = str(a)
|
||||
if types_cfg is None and isinstance(a, dict):
|
||||
types_cfg = a
|
||||
return path, types_cfg
|
||||
def _env(n: str, d: Optional[str]=None) -> str:
|
||||
v = os.getenv(n)
|
||||
return v if v is not None else (d or "")
|
||||
|
||||
def _load_types_config(explicit: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
if isinstance(explicit, dict):
|
||||
return explicit
|
||||
for rel in ("config/config.yaml", "config/types.yaml"):
|
||||
p = pathlib.Path(rel)
|
||||
if p.exists():
|
||||
with p.open("r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
if isinstance(data, dict) and "types" in data and isinstance(data["types"], dict):
|
||||
return data["types"]
|
||||
return data if isinstance(data, dict) else {}
|
||||
def _load_types() -> dict:
|
||||
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||
try:
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _get_types_map(reg: dict) -> dict:
|
||||
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
||||
return reg["types"]
|
||||
return reg if isinstance(reg, dict) else {}
|
||||
|
||||
def _get_defaults(reg: dict) -> dict:
|
||||
if isinstance(reg, dict) and isinstance(reg.get("defaults"), dict):
|
||||
return reg["defaults"]
|
||||
# alias "global" erlaubt
|
||||
if isinstance(reg, dict) and isinstance(reg.get("global"), dict):
|
||||
return reg["global"]
|
||||
return {}
|
||||
|
||||
def _coalesce(*vals):
|
||||
for v in vals:
|
||||
def _resolve_chunk_profile(note_type: str, reg: dict) -> str:
|
||||
types = _get_types_map(reg)
|
||||
if isinstance(types, dict):
|
||||
t = types.get(note_type, {})
|
||||
if isinstance(t, dict) and isinstance(t.get("chunk_profile"), str):
|
||||
return t["chunk_profile"]
|
||||
defs = _get_defaults(reg)
|
||||
if isinstance(defs, dict) and isinstance(defs.get("chunk_profile"), str):
|
||||
return defs["chunk_profile"]
|
||||
return "default"
|
||||
|
||||
def _as_float(x: Any) -> Optional[float]:
|
||||
try:
|
||||
return float(x)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _resolve_retriever_weight(note_type: str, reg: dict) -> float:
|
||||
types = _get_types_map(reg)
|
||||
if isinstance(types, dict):
|
||||
t = types.get(note_type, {})
|
||||
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
||||
v = _as_float(t.get("retriever_weight"))
|
||||
if v is not None:
|
||||
return float(v)
|
||||
defs = _get_defaults(reg)
|
||||
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
||||
v = _as_float(defs.get("retriever_weight"))
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
return float(v)
|
||||
return 1.0
|
||||
|
||||
def _env_float(name: str, default: float) -> float:
|
||||
try:
|
||||
return float(os.environ.get(name, default))
|
||||
except Exception:
|
||||
return default
|
||||
# ------------------- public API -------------------
|
||||
|
||||
def _ensure_list(x) -> list:
|
||||
if x is None: return []
|
||||
if isinstance(x, list): return [str(i) for i in x]
|
||||
if isinstance(x, (set, tuple)): return [str(i) for i in x]
|
||||
return [str(x)]
|
||||
def make_note_payload(parsed_note: Any,
|
||||
*,
|
||||
vault_root: str,
|
||||
hash_mode: str = "body",
|
||||
hash_normalize: str = "canonical",
|
||||
hash_source: str = "parsed",
|
||||
file_path: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Erwartet ein Parsed-Objekt mit Attributen:
|
||||
- frontmatter (dict)
|
||||
- body (str)
|
||||
- path (optional)
|
||||
Liefert Note-Payload mit deterministischer note_id und Typ-Werten aus types.yaml.
|
||||
"""
|
||||
fm = (getattr(parsed_note, "frontmatter", None) or {}) if parsed_note else {}
|
||||
title = fm.get("title") or ""
|
||||
note_type = fm.get("type") or "concept"
|
||||
note_id = fm.get("id") or _stable_id_from_path_or_title(file_path or "", title)
|
||||
tags = fm.get("tags") or []
|
||||
if isinstance(tags, str):
|
||||
tags = [tags]
|
||||
|
||||
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||
n = _as_dict(note)
|
||||
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
||||
types_cfg = _load_types_config(types_cfg_explicit)
|
||||
# types.yaml authoritative:
|
||||
reg = _load_types()
|
||||
chunk_profile = _resolve_chunk_profile(note_type, reg)
|
||||
retriever_weight = _resolve_retriever_weight(note_type, reg)
|
||||
# edge_defaults (falls vorhanden)
|
||||
edge_defaults = None
|
||||
types = _get_types_map(reg)
|
||||
if isinstance(types, dict):
|
||||
t = types.get(note_type, {})
|
||||
if isinstance(t, dict) and isinstance(t.get("edge_defaults"), list):
|
||||
edge_defaults = t["edge_defaults"]
|
||||
|
||||
fm = n.get("frontmatter") or {}
|
||||
note_type = str(fm.get("type") or n.get("type") or "note")
|
||||
cfg_for_type = types_cfg.get(note_type, {}) if isinstance(types_cfg, dict) else {}
|
||||
updated = _ts_to_int(fm.get("updated"))
|
||||
|
||||
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
||||
retriever_weight = _coalesce(fm.get("retriever_weight"), cfg_for_type.get("retriever_weight"), default_rw)
|
||||
try:
|
||||
retriever_weight = float(retriever_weight)
|
||||
except Exception:
|
||||
retriever_weight = default_rw
|
||||
|
||||
chunk_profile = _coalesce(fm.get("chunk_profile"), cfg_for_type.get("chunk_profile"), os.environ.get("MINDNET_DEFAULT_CHUNK_PROFILE","medium"))
|
||||
chunk_profile = chunk_profile if isinstance(chunk_profile, str) else "medium"
|
||||
|
||||
edge_defaults = _ensure_list(_coalesce(fm.get("edge_defaults"), cfg_for_type.get("edge_defaults"), []))
|
||||
|
||||
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||
title = n.get("title") or fm.get("title") or ""
|
||||
path = n.get("path") or path_arg
|
||||
if isinstance(path, pathlib.Path):
|
||||
path = str(path)
|
||||
|
||||
payload = {
|
||||
payload: Dict[str, Any] = {
|
||||
"note_id": note_id,
|
||||
"title": title,
|
||||
"type": note_type,
|
||||
"path": path or "", # immer vorhanden
|
||||
"retriever_weight": retriever_weight,
|
||||
"title": title,
|
||||
"tags": tags,
|
||||
"updated": updated if updated is not None else 0,
|
||||
"path": file_path or "",
|
||||
"chunk_profile": chunk_profile,
|
||||
"edge_defaults": edge_defaults,
|
||||
"retriever_weight": float(retriever_weight),
|
||||
}
|
||||
if edge_defaults is not None:
|
||||
payload["edge_defaults"] = edge_defaults
|
||||
|
||||
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||
if tags: payload["tags"] = _ensure_list(tags)
|
||||
for k in ("created","modified","date"):
|
||||
v = fm.get(k) or n.get(k)
|
||||
if v: payload[k] = str(v)
|
||||
|
||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||
return payload
|
||||
|
||||
# ------------------- internal utilities -------------------
|
||||
|
||||
def _stable_id_from_path_or_title(path: str, title: str) -> str:
|
||||
base = path or title or ""
|
||||
if not base:
|
||||
base = "note"
|
||||
h = hashlib.sha1(base.encode("utf-8")).hexdigest()[:6]
|
||||
# title-sourced; in V2 typischerweise durch Frontmatter id ersetzt
|
||||
return f"auto-{h}"
|
||||
|
||||
def _ts_to_int(val: Any) -> Optional[int]:
|
||||
# akzeptiert YYYY-MM-DD oder epoch int; None bei Fehler
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, int):
|
||||
return val
|
||||
if isinstance(val, float):
|
||||
return int(val)
|
||||
if isinstance(val, str):
|
||||
val = val.strip()
|
||||
# YYYY-MM-DD
|
||||
try:
|
||||
dt = datetime.date.fromisoformat(val)
|
||||
return int(datetime.datetime(dt.year, dt.month, dt.day).timestamp())
|
||||
except Exception:
|
||||
pass
|
||||
# epoch string
|
||||
try:
|
||||
return int(val)
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
+147
-92
@@ -1,124 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: app/core/qdrant.py
|
||||
Version: v1.4.0 (2025-09-09)
|
||||
app/core/qdrant.py
|
||||
Version: 2.2.0 (2025-11-11)
|
||||
|
||||
Kurzbeschreibung:
|
||||
Qdrant-Client & Collection-Setup für mindnet.
|
||||
- Stellt sicher, dass {prefix}_notes / {prefix}_chunks / {prefix}_edges existieren.
|
||||
- Edges-Collection nutzt 1D Dummy-Vektor.
|
||||
- NEW: ensure_payload_indexes(...) legt sinnvolle Payload-Indizes an.
|
||||
Aufgabe
|
||||
-------
|
||||
- Zentraler Qdrant-Zugriff (Client, Config)
|
||||
- Collection-Anlage (notes/chunks/edges)
|
||||
- **Payload-Indizes sicherstellen** (idempotent)
|
||||
|
||||
Aufruf:
|
||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
||||
Hinweis
|
||||
-------
|
||||
Diese Datei ist als Drop-in-Ersatz gedacht, falls in deinem Projekt noch keine
|
||||
robuste ensure_payload_indexes()-Implementierung vorliegt. Die Signaturen
|
||||
bleiben kompatibel zu scripts.import_markdown und scripts.reset_qdrant.
|
||||
|
||||
API-Notizen
|
||||
-----------
|
||||
- Payload-Indizes werden mit `create_payload_index` angelegt.
|
||||
- Typen stammen aus `qdrant_client.http.models.PayloadSchemaType`:
|
||||
KEYWORD | TEXT | INTEGER | FLOAT | BOOL | GEO | DATETIME
|
||||
- Für häufige Filterfelder (note_id, kind, scope, type, tags, ...) legen wir
|
||||
Indizes an. Das ist laut Qdrant-Doku Best Practice für performante Filter.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Tuple
|
||||
from typing import Optional, Tuple, Dict, List
|
||||
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Konfiguration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class QdrantConfig:
|
||||
url: str
|
||||
api_key: Optional[str]
|
||||
prefix: str
|
||||
dim: int
|
||||
host: Optional[str] = None
|
||||
port: Optional[int] = None
|
||||
url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
prefix: str = "mindnet"
|
||||
dim: int = 384
|
||||
distance: str = "Cosine" # Cosine | Dot | Euclid
|
||||
on_disk_payload: bool = True
|
||||
|
||||
@staticmethod
|
||||
def from_env() -> "QdrantConfig":
|
||||
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}"
|
||||
@classmethod
|
||||
def from_env(cls) -> "QdrantConfig":
|
||||
# Entweder URL ODER Host/Port, API-Key optional
|
||||
url = os.getenv("QDRANT_URL") or None
|
||||
host = os.getenv("QDRANT_HOST") or None
|
||||
port = os.getenv("QDRANT_PORT")
|
||||
port = int(port) if port else None
|
||||
api_key = os.getenv("QDRANT_API_KEY") or None
|
||||
prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||
dim = int(os.getenv("VECTOR_DIM", "384"))
|
||||
return QdrantConfig(url=url, api_key=api_key, prefix=prefix, dim=dim)
|
||||
prefix = os.getenv("COLLECTION_PREFIX") or "mindnet"
|
||||
dim = int(os.getenv("VECTOR_DIM") or 384)
|
||||
distance = os.getenv("DISTANCE", "Cosine")
|
||||
on_disk_payload = (os.getenv("ON_DISK_PAYLOAD", "true").lower() == "true")
|
||||
return cls(
|
||||
host=host, port=port, url=url, api_key=api_key,
|
||||
prefix=prefix, dim=dim, distance=distance, on_disk_payload=on_disk_payload
|
||||
)
|
||||
|
||||
|
||||
def get_client(cfg: QdrantConfig) -> QdrantClient:
|
||||
return QdrantClient(url=cfg.url, api_key=cfg.api_key)
|
||||
# QdrantClient akzeptiert entweder url=... oder host/port
|
||||
if cfg.url:
|
||||
return QdrantClient(url=cfg.url, api_key=cfg.api_key, timeout=60.0)
|
||||
return QdrantClient(host=cfg.host or "127.0.0.1", port=cfg.port or 6333, api_key=cfg.api_key, timeout=60.0)
|
||||
|
||||
|
||||
def _create_notes(client: QdrantClient, name: str, dim: int) -> None:
|
||||
if not client.collection_exists(name):
|
||||
client.create_collection(
|
||||
collection_name=name,
|
||||
vectors_config=rest.VectorParams(size=dim, distance=rest.Distance.COSINE),
|
||||
)
|
||||
|
||||
def _create_chunks(client: QdrantClient, name: str, dim: int) -> None:
|
||||
if not client.collection_exists(name):
|
||||
client.create_collection(
|
||||
collection_name=name,
|
||||
vectors_config=rest.VectorParams(size=dim, distance=rest.Distance.COSINE),
|
||||
)
|
||||
|
||||
def _create_edges(client: QdrantClient, name: str) -> None:
|
||||
if not client.collection_exists(name):
|
||||
client.create_collection(
|
||||
collection_name=name,
|
||||
vectors_config=rest.VectorParams(size=1, distance=rest.Distance.DOT), # 1D-Dummy
|
||||
)
|
||||
|
||||
|
||||
def ensure_collections(client: QdrantClient, prefix: str, dim: int, destructive: bool = False) -> None:
|
||||
notes = f"{prefix}_notes"
|
||||
chunks = f"{prefix}_chunks"
|
||||
edges = f"{prefix}_edges"
|
||||
|
||||
_create_notes(client, notes, dim)
|
||||
_create_chunks(client, chunks, dim)
|
||||
|
||||
if client.collection_exists(edges):
|
||||
try:
|
||||
info = client.get_collection(edges)
|
||||
vectors_cfg = getattr(getattr(info.result, "config", None), "params", None)
|
||||
has_vectors = getattr(vectors_cfg, "vectors", None) is not None
|
||||
except Exception:
|
||||
has_vectors = True
|
||||
if not has_vectors:
|
||||
if destructive:
|
||||
client.delete_collection(edges)
|
||||
_create_edges(client, edges)
|
||||
else:
|
||||
print(f"[ensure_collections] WARN: '{edges}' ohne VectorConfig; destructive=False.", flush=True)
|
||||
else:
|
||||
_create_edges(client, edges)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Collections
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def collection_names(prefix: str) -> Tuple[str, str, str]:
|
||||
return (f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges")
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
|
||||
# -------------------------------
|
||||
# NEW: Payload-Indexing
|
||||
# -------------------------------
|
||||
def _vector_params(dim: int, distance: str) -> rest.VectorParams:
|
||||
# Distance: "Cosine" | "Dot" | "Euclid"
|
||||
dist = getattr(rest.Distance, distance.capitalize(), rest.Distance.COSINE)
|
||||
return rest.VectorParams(size=dim, distance=dist)
|
||||
|
||||
def _safe_create_index(client: QdrantClient, col: str, field: str, schema: rest.PayloadSchemaType):
|
||||
try:
|
||||
client.create_payload_index(
|
||||
collection_name=col,
|
||||
field_name=field,
|
||||
field_schema=schema,
|
||||
|
||||
def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
||||
"""Legt mindnet_notes, mindnet_chunks, mindnet_edges an (falls nicht vorhanden)."""
|
||||
notes, chunks, edges = collection_names(prefix)
|
||||
|
||||
# notes
|
||||
if not client.collection_exists(notes):
|
||||
client.create_collection(
|
||||
collection_name=notes,
|
||||
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
||||
on_disk_payload=True,
|
||||
)
|
||||
except Exception:
|
||||
# bereits vorhanden oder nicht unterstütztes Schema → ignorieren
|
||||
pass
|
||||
# chunks
|
||||
if not client.collection_exists(chunks):
|
||||
client.create_collection(
|
||||
collection_name=chunks,
|
||||
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
||||
on_disk_payload=True,
|
||||
)
|
||||
# edges (Dummy-Vektor, Filter via Payload)
|
||||
if not client.collection_exists(edges):
|
||||
client.create_collection(
|
||||
collection_name=edges,
|
||||
vectors_config=_vector_params(1, "Dot"),
|
||||
on_disk_payload=True,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Payload-Indizes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _ensure_index(client: QdrantClient, collection: str, field: str, schema: rest.PayloadSchemaType) -> None:
|
||||
"""Idempotentes Anlegen eines Payload-Indexes für ein Feld."""
|
||||
try:
|
||||
client.create_payload_index(collection_name=collection, field_name=field, field_schema=schema, wait=True)
|
||||
except Exception as e:
|
||||
# Fehler ignorieren, falls Index bereits existiert oder Server "already indexed" meldet.
|
||||
# Für Debugging ggf. Logging ergänzen.
|
||||
_ = e
|
||||
|
||||
|
||||
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
||||
"""
|
||||
Stellt sicher, dass alle benötigten Payload-Indizes existieren.
|
||||
- notes: note_id(KEYWORD), type(KEYWORD), title(TEXT), updated(INTEGER), tags(KEYWORD)
|
||||
- chunks: note_id(KEYWORD), chunk_id(KEYWORD), index(INTEGER), type(KEYWORD), tags(KEYWORD)
|
||||
- edges: note_id(KEYWORD), kind(KEYWORD), scope(KEYWORD), source_id(KEYWORD), target_id(KEYWORD), chunk_id(KEYWORD)
|
||||
"""
|
||||
notes, chunks, edges = collection_names(prefix)
|
||||
# Notes
|
||||
_safe_create_index(client, notes, "note_id", rest.PayloadSchemaType.KEYWORD)
|
||||
# Chunks
|
||||
_safe_create_index(client, chunks, "note_id", rest.PayloadSchemaType.KEYWORD)
|
||||
_safe_create_index(client, chunks, "chunk_index", rest.PayloadSchemaType.INTEGER)
|
||||
# Edges
|
||||
for f in ("kind", "scope", "source_id", "target_id", "note_id"):
|
||||
_safe_create_index(client, edges, f, rest.PayloadSchemaType.KEYWORD)
|
||||
|
||||
# NOTES
|
||||
for field, schema in [
|
||||
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("type", rest.PayloadSchemaType.KEYWORD),
|
||||
("title", rest.PayloadSchemaType.TEXT),
|
||||
("updated", rest.PayloadSchemaType.INTEGER),
|
||||
("tags", rest.PayloadSchemaType.KEYWORD),
|
||||
]:
|
||||
_ensure_index(client, notes, field, schema)
|
||||
|
||||
# CHUNKS
|
||||
for field, schema in [
|
||||
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("index", rest.PayloadSchemaType.INTEGER),
|
||||
("type", rest.PayloadSchemaType.KEYWORD),
|
||||
("tags", rest.PayloadSchemaType.KEYWORD),
|
||||
]:
|
||||
_ensure_index(client, chunks, field, schema)
|
||||
|
||||
# EDGES
|
||||
for field, schema in [
|
||||
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("kind", rest.PayloadSchemaType.KEYWORD),
|
||||
("scope", rest.PayloadSchemaType.KEYWORD),
|
||||
("source_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("target_id", rest.PayloadSchemaType.KEYWORD),
|
||||
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||
]:
|
||||
_ensure_index(client, edges, field, schema)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QdrantConfig",
|
||||
"get_client",
|
||||
"ensure_collections",
|
||||
"ensure_payload_indexes",
|
||||
"collection_names",
|
||||
]
|
||||
+9
-2
@@ -1,9 +1,12 @@
|
||||
version: 1.0
|
||||
defaults:
|
||||
retriever_weight: 0.1
|
||||
chunk_profile: default
|
||||
types:
|
||||
concept:
|
||||
chunk_profile: medium
|
||||
edge_defaults: ["references", "related_to"]
|
||||
retriever_weight: 0.33
|
||||
retriever_weight: 0.35
|
||||
task:
|
||||
chunk_profile: short
|
||||
edge_defaults: ["depends_on", "belongs_to"]
|
||||
@@ -15,4 +18,8 @@ types:
|
||||
project:
|
||||
chunk_profile: long
|
||||
edge_defaults: ["references", "depends_on"]
|
||||
retriever_weight: 0.95
|
||||
retriever_weight: 0.97
|
||||
profile:
|
||||
chunk_profile: long
|
||||
edge_defaults: ["references", "depends_on"]
|
||||
retriever_weight: 0.66
|
||||
+155
-188
@@ -1,249 +1,216 @@
|
||||
# mindnet – Knowledge Design
|
||||
**Version:** 1.4.0 (aktualisiert 2025-10-06)
|
||||
**Version:** 1.5.0 (aktualisiert 2025-11-09)
|
||||
|
||||
## 1. Gesamtziel und Systemverständnis
|
||||
|
||||
**mindnet** ist ein lokales Wissensnetzwerk, das alle meine Notizen, Projekte, Gedanken, Erfahrungen und Pläne als Markdown-Dateien speichert, automatisch importiert, semantisch in **Chunks** zerlegt und als **Graph-Struktur in Qdrant** ablegt.
|
||||
Es ist die Grundlage für ein agentenfähiges, lokal betriebenes LLM-System, das meine Daten verknüpft, abfragt und erweitert.
|
||||
|
||||
**Zentrale Ziele**
|
||||
- Vollständige Repräsentation persönlichen Wissens in strukturierter, maschinenlesbarer Form
|
||||
- Reproduzierbare Verarbeitung: Import → Chunking → Embedding → Edges → Graph
|
||||
- Verlustfreie Roundtrip-Fähigkeit (Import ⇄ Export)
|
||||
- Erweiterbarkeit für Agenten, RAG-Retriever und semantische Suche
|
||||
|
||||
**Prinzipien**
|
||||
- **Deterministisch:** IDs, Hashes und Edges wiederholbar
|
||||
- **Portabel:** Markdown + YAML
|
||||
- **Robust:** fehlertoleranter Parser
|
||||
- **Idempotent:** keine Duplikate bei Re-Import
|
||||
- **Erweiterbar:** neue Typen und Edge-Arten ohne Migration
|
||||
> Dieses Dokument beschreibt das Ziel, die Architektur, die Datenmodelle sowie die Regeln und Prozesse für den Aufbau von **mindnet** – einem persönlichen, lokal betriebenen Wissensnetz, das auf Markdown-Quellen, Graph-Beziehungen und Vektor-Suche basiert. Es soll die Persönlichkeit, Werte und Erfahrungen des Besitzers widerspiegeln und künftig Antworten generieren, die diese Perspektive authentisch berücksichtigen.
|
||||
|
||||
---
|
||||
|
||||
## 2. YAML-Frontmatter-Schema
|
||||
## 1. Ziel von mindnet
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
|-------|-----|--------------|
|
||||
| `title` | string | Menschlich lesbarer Titel |
|
||||
| `id` | string | Eindeutige Note-ID (Slug) |
|
||||
| `type` | enum | `concept`, `thought`, `experience`, `task`, `project`, `journal`, `person`, `meeting`, `milestone` |
|
||||
| `status` | enum | `draft`, `active`, `done`, `archived` |
|
||||
| `created` | date | ISO-Datum |
|
||||
| `updated` | date | Letzte Änderung |
|
||||
| `area` | string | Themen- oder Lebensbereich |
|
||||
| `project` | string | Zugehöriges Projekt |
|
||||
| `tags` | list | Strukturierte Tags (`area/…`, `topic/…`) |
|
||||
| `depends_on` | list | IDs anderer Notizen |
|
||||
| `assigned_to` | list | Beteiligte Personen |
|
||||
| `embedding_exclude` | bool | Falls `true`, keine Embeddings |
|
||||
| `hash_mode` | enum | Hash-Modus beim Import (`body`, `frontmatter`, `full`) |
|
||||
| `priority` | enum/int | 1–5 oder `low` / `med` / `high` |
|
||||
| `effort_min`, `due` | int/date | Aufwand / Termin |
|
||||
| `aliases` | list | Alternative IDs |
|
||||
| `lang` | string | ISO-Sprachcode |
|
||||
| `source` | string | Herkunft / Referenzquelle |
|
||||
**1.1 Zweck**
|
||||
- mindnet dient als persönliches Wissensnetz, das Erfahrungen, Werte, Prinzipien, Ziele und prägenden Ereignisse langfristig strukturiert.
|
||||
- Es ermöglicht spätere Einsichten in Entscheidungen und Entwicklungen und kann in Zukunft für die Familie (z. B. Kinder) eine nachvollziehbare Quelle sein.
|
||||
|
||||
**Pflichtfelder:** `title`, `id`, `type`, `status`, `created`
|
||||
**Optionale Felder:** alle übrigen
|
||||
**1.2 Leitidee**
|
||||
- Statt einer reinen Dokumentablage wird Wissen durch **Knoten (Notes/Chunks)** und **Kanten (Edges)** vernetzt.
|
||||
- Antworten sollen **persönlich** kontextualisiert werden (Perspektive, Konditionierung, Persönlichkeit).
|
||||
|
||||
**1.3 Langfristigkeit**
|
||||
- Stabiler, zukunftsfähiger Entwurf; spätere Massenmigrationen sollen vermieden werden.
|
||||
- Architektur unterstützt schrittweise Erweiterung (neue Quellen, neue Agenten, neue Regeln).
|
||||
|
||||
---
|
||||
|
||||
## 3. Dateinamen und Ordner
|
||||
## 2. Zielarchitektur (High Level)
|
||||
|
||||
- Format: `YYYY-MM-DD_title.md` oder `slug.md`
|
||||
- Strukturierte Ordner:
|
||||
- `10_thoughts/`, `20_concepts/`, `30_projects/`, `40_experiences/`, …
|
||||
- Alle Pfade relativ; Unterstriche statt Leerzeichen
|
||||
- **Datenquellen:** Markdown-Vault (Obsidian-kompatibel), perspektivisch weitere Quellen (MediaWiki, PDFs, Web-Exporte, E-Mail-Auszüge).
|
||||
- **Import-Pipeline:** Parser → Frontmatter/Body → Chunking → Embedding → Qdrant (Notes/Chunks/Edges).
|
||||
- **Speicher:** Qdrant (Vektoren + Payload + Textindex), Dateien bleiben im Filesystem (Quelle ist Referenz).
|
||||
- **Graph-Schicht:** Edges explizit modelliert (Typ, Richtung, Evidenz, Confidence); optionale abgeleitete Edges per Batch-Job.
|
||||
- **Retriever/Composer:** Hybrid-Retrieval (Vektor + Filter + optional Volltext), Komposition zu Antwortkandidaten.
|
||||
- **Erklärbarkeit:** Begründungspfade (Top-Chunks, Graph-Kette, Provenienz).
|
||||
- **Schnittstellen:** REST/CLI, n8n-Glue, lokale LLM-Anbindung (Ollama).
|
||||
|
||||
---
|
||||
|
||||
## 4. Link- und Edge-Design
|
||||
## 3. Collections in Qdrant
|
||||
|
||||
**Verlinkungen**
|
||||
- Wikilinks: `[[note-id]]` oder `[[Titel|note-id]]`
|
||||
- Automatische Edges aus Text und Frontmatter
|
||||
|
||||
**Edge-Typen in Qdrant**
|
||||
|
||||
| Typ | Bedeutung | Quelle | Scope |
|
||||
|------|------------|--------|--------|
|
||||
| `belongs_to` | Chunk → Note | intern | chunk |
|
||||
| `prev` / `next` | Reihenfolge | intern | chunk |
|
||||
| `references` | explizite Wikilinks | Text | chunk |
|
||||
| `backlink` | Gegenkante zu `references` | abgeleitet | note |
|
||||
| `depends_on` | YAML-Abhängigkeiten | YAML | note |
|
||||
| `assigned_to` | YAML-Zuweisung | YAML | note |
|
||||
| `unresolved` | Ziel fehlt (Stub) | abgeleitet | chunk |
|
||||
|
||||
**Edge-Schlüssel**
|
||||
- `source_id`, `target_id`, `kind`, `scope`, `note_id`
|
||||
- Dedup-Schlüssel: Kombination aus `(kind, source_id, target_id, scope)`
|
||||
- `mindnet_notes` – Note-Metadaten (id, title, type, path, timestamps, tags, …).
|
||||
- `mindnet_chunks` – inhaltstragende Segmente inkl. Vektoren und Textindex.
|
||||
- `mindnet_edges` – Beziehungen (src/dst, relation, direction, evidence, confidence, …).
|
||||
- (optional) `mindnet_people` – strukturierte Personenobjekte (Eigen-/Fremdbezug).
|
||||
|
||||
---
|
||||
|
||||
## 5. Chunking-Modell
|
||||
## 4. Identitäten & IDs
|
||||
|
||||
**Chunk-Datenstruktur**
|
||||
| Feld | Beschreibung |
|
||||
|-------|---------------|
|
||||
| `note_id` | Zugehörige Note |
|
||||
| `chunk_index` | Laufende Nummer |
|
||||
| `text` | Originalabschnitt |
|
||||
| `window` | Text + Overlap links/rechts |
|
||||
| `overlap_left` | Länge des linken Overlaps |
|
||||
| `overlap_right` | Länge des rechten Overlaps |
|
||||
| `embedding` | 384-dimensionaler Vektor |
|
||||
| `tokens` | Tokenanzahl (optional) |
|
||||
|
||||
**Chunking-Regeln (aus `chunking_strategy.md`)**
|
||||
- Trennung nach Absätzen, Überschriften, Listen, Tabellen
|
||||
- Token-Zielgröße 350–500 (max 600)
|
||||
- Overlap: 30–40 % für semantische Kohärenz
|
||||
- Overlap wird in `window` integriert, sodass `text ≠ window`
|
||||
- **Deterministische IDs** für Notes (z. B. Namespace-basierte UUIDv5) und stabile, ableitbare IDs für Chunks/Edges.
|
||||
- ID-Stabilität ist Voraussetzung für Idempotenz (Re-Imports ohne Duplikate).
|
||||
|
||||
---
|
||||
|
||||
## 6. Hash-Strategie und Änderungsverfolgung
|
||||
## 5. Frontmatter & Typen
|
||||
|
||||
**Zweck:** Nur bei realer Inhaltsänderung re-indexieren
|
||||
|
||||
| Umgebungsvariable | Beschreibung |
|
||||
|--------------------|--------------|
|
||||
| `MINDNET_HASH_COMPARE` | Vergleichsquelle (`Body`, `Full`, `Frontmatter`) |
|
||||
| `MINDNET_HASH_SOURCE` | Rohtext vs. geparst (`raw` / `parsed`) |
|
||||
| `MINDNET_HASH_NORMALIZE` | Normalisierung (`canonical` / `none`) |
|
||||
|
||||
**Basismodi**
|
||||
- `body` → Nur Textkörper
|
||||
- `frontmatter` → Nur Metadaten
|
||||
- `full` → Kombination
|
||||
- Hash = SHA-256(canonicalized_input)
|
||||
|
||||
Bei Änderung: Re-Import, neue Embeddings, Edges werden aktualisiert.
|
||||
- Pflichtfelder: `id`, `title`, `type`, `created`, `updated`, `tags`, `source_path`.
|
||||
- Note-Typen (Auszug): `experience`, `principle`, `value`, `goal`, `role`, `persona`, `plan`, `project`, `journal`, `reference`, `translation`.
|
||||
- **types.yaml** definiert Regeln/Defaults je Typ und für Relationstypen (siehe Abschnitt 10).
|
||||
|
||||
---
|
||||
|
||||
## 7. Qdrant-Speicherstruktur
|
||||
## 6. Chunking-Strategie
|
||||
|
||||
| Collection | Inhalt | Primärfelder | Embedding |
|
||||
|-------------|---------|---------------|------------|
|
||||
| `mindnet_notes` | Notes mit Fulltext & Hash | `note_id` | optional |
|
||||
| `mindnet_chunks` | Chunks mit Text, Window, Embedding | `chunk_id`, `note_id` | 384 d |
|
||||
| `mindnet_edges` | Graphkanten | `edge_id`, `source_id`, `target_id` | — |
|
||||
|
||||
**Upsert-Strategie**
|
||||
- Idempotente UUIDv5-IDs
|
||||
- Keine Duplikate durch deterministische Signaturen
|
||||
- `purge-before-upsert` zur Bereinigung
|
||||
|
||||
**Indizes**
|
||||
- notes: `note_id`, `hash_signature`
|
||||
- chunks: `note_id`, `chunk_index`
|
||||
- edges: `(kind, source_id, target_id, scope)`
|
||||
- Satz- bis Absatz-Chunks, moderate Überlappung; Meta-Felder verweisen auf Note/Quelle.
|
||||
- Named Vectors (z. B. `content`, optional `title`, `tags`) ermöglichen hybride Scores.
|
||||
|
||||
---
|
||||
|
||||
## 8. Fehler-Toleranz und Parser-Robustheit
|
||||
## 7. Embeddings & Vektoren
|
||||
|
||||
- UTF-8 mit Fallback: ersetzt ungültige Bytes (`errors="replace"`)
|
||||
- Ignoriert Nullbytes, BOM, exotische Zeilenenden
|
||||
- Erkennt defekte oder leere YAML-Header und überspringt sie
|
||||
- Logt Problemfälle (`read_markdown failed`, `make_note_payload returned non-dict`)
|
||||
- Bei Fehlern: Import → warn → continue
|
||||
- Einheitliche Metrik (cosine), reproduzierbares Embedding-Setup.
|
||||
- Konsistenz über Zeit durch Versionsfeld (`embedding_model`, `embedding_version`).
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests & Validierung
|
||||
## 8. Volltext & Filter
|
||||
|
||||
**Integrationstests**
|
||||
- Roundtrip: Import → Export → Compare (`compare_vaults.py`)
|
||||
- Chunk-Integrität: `verify_chunks_integrity.py`
|
||||
- Hash-Audit: `hash_reporter.py`
|
||||
- Window-Vergleich: `check_chunks_window_vs_text.py`
|
||||
|
||||
**Erwartete Ergebnisse**
|
||||
- Alle Notes werden erkannt
|
||||
- `window ≠ text` bei > 60 % der Chunks
|
||||
- Roundtrip-Vergleich liefert „OK“
|
||||
- Edge-Anzahl entspricht Modell (belongs_to = #Chunks, next/prev ≈ #Chunks – 1)
|
||||
- Textindex auf `mindnet_chunks.body` für exakte Term/Operator-Queries.
|
||||
- Payload-Filter zur schnellen Einschränkung (tags, types, time-buckets, visibility u. a.).
|
||||
|
||||
---
|
||||
|
||||
## 10. Export & Roundtrip-Verhalten
|
||||
## 9. Edges – Beziehungen
|
||||
|
||||
- `export_markdown.py` erzeugt identische Markdown-Dateien
|
||||
- Schreibt YAML + Body in korrekter Reihenfolge
|
||||
- Roundtrip-Prüfung (`compare_vaults.py`) validiert:
|
||||
- vollständigen Body
|
||||
- unveränderte Hash-Signatur
|
||||
- gleiche Chunkzahl
|
||||
- **Explizit**: Jede tatsächliche Beziehung wird als Kante gespeichert (kein Workaround).
|
||||
- Felder u. a.: `src_id`, `dst_id`, `relation`, `direction`, `confidence (0–1)`, `evidence` (Chunk-IDs), `created_at`, `updated_at`.
|
||||
- **edge_defaults** liefern **Interpretations-Hints** (Gewichte, Symmetrie, Transitivität) und parametrisieren abgeleitete Edges; sie **ersetzen** keine Originalkanten.
|
||||
|
||||
---
|
||||
|
||||
## 11. Graph-Schicht und WP-04-Integration
|
||||
## 10. Regeln & Policies (types.yaml)
|
||||
|
||||
- Qdrant fungiert als Graph-Backend
|
||||
- `graph/service.py` (WP-04): stellt API für Mehrhop-Abfragen bereit
|
||||
- Unterstützt:
|
||||
- `expand(note_id, hops=2)`
|
||||
- `resolve_unresolved()`
|
||||
- `neighbors(kind=…)`
|
||||
- Grundlage für spätere **Retriever-Funktionen** (LLM / Agenten)
|
||||
- Per Typ/Relation:
|
||||
- Default-Eigenschaften (Gewicht, Directedness, Symmetrie, Transitivität).
|
||||
- Scoring-Hooks für Graph-Kontext im Retriever.
|
||||
- (später) Privacy-Hooks je Relation (Mindest-Visibility).
|
||||
|
||||
---
|
||||
|
||||
## 12. Agenten- und LLM-Integration
|
||||
## 11. Retrieval & Ranking (Komposition)
|
||||
|
||||
**Retriever-Pipeline**
|
||||
1. Suche top-k Chunks (cosine distance)
|
||||
2. Erweiterung um Edges (`references`, `backlinks`)
|
||||
3. Kontext-Assembling via `window`-Text
|
||||
4. Prompt-Generierung
|
||||
|
||||
**Agent-Use-Cases**
|
||||
- Automatisches Tagging (`type`, `status`)
|
||||
- Vorschläge für neue Edges
|
||||
- Auflösen von `unresolved`-Referenzen
|
||||
- Auto-Import externer Quellen (MediaWiki, PDFs, Webseiten)
|
||||
- Hybrid: Vektor-Score + Filter + optional BM25/Volltext.
|
||||
- Zeitgewicht (Decays) und Graph-Kontext werden komponiert (Formel siehe 16.3).
|
||||
- Konfiguration über `.env`/`config.yaml` (gewichts- und halbwertszeit-basiert).
|
||||
|
||||
---
|
||||
|
||||
## 13. Erweiterbarkeit
|
||||
## 12. Erklärbarkeit
|
||||
|
||||
- Neue Edge-Typen: `inspired_by`, `relates_to`, `contradicts`
|
||||
- Neue Note-Typen: `decision`, `resource`, `recommendation`
|
||||
- Embedding-Engines austauschbar (MiniLM → LaBSE → E5)
|
||||
- Versionierte Chunking-Strategien (`chunk_config.py`)
|
||||
- „Warum-Pfad“: Top-Chunks mit Score-Zerlegung (Vektor/Time/Graph), Graph-Kette, Provenienz.
|
||||
- Mehrschichtige Narrative (Kindheit/Erlebnisse, Werte/Prinzipien, Ziele/Leitbild, Gegenwart).
|
||||
|
||||
---
|
||||
|
||||
## 14. Qualitätssicherung und Best Practices
|
||||
## 13. Betrieb & Sicherheit
|
||||
|
||||
- Validierung vor Upsert
|
||||
- Keine Leer-Chunks
|
||||
- Vollständige Metadaten in Notes
|
||||
- Tests in `tests/` automatisch ausführbar (`run_e2e_roundtrip.sh`)
|
||||
- Ergebnis: „Roundtrip OK“ und `verify_chunks_integrity` = OK
|
||||
- Lokal auf Single-Node starten (Backups via Snapshots).
|
||||
- Zugriff nur intern/Reverse-Proxy; Festplattenverschlüsselung OS-seitig.
|
||||
- Migrationspfad zu Qdrant-Distributed (Shards, Replikation) einplanen.
|
||||
|
||||
---
|
||||
|
||||
## 15. Änderungsverlauf
|
||||
## 14. Qualität & Monitoring
|
||||
|
||||
**v1.4.0 (2025-10-06)**
|
||||
- Neu: `window` vs `text` Feld in `mindnet_chunks`
|
||||
- Neu: Hash-Modi (`body`, `frontmatter`, `full`) mit Env-Steuerung
|
||||
- Neu: Baseline-Modus für Vergleich
|
||||
- Parser → fehlertolerant (UTF-8 replace)
|
||||
- Roundtrip-Test vollständig integriert
|
||||
- Graph-Service und Mehrhop-Abfragen (WP-04-Vorbereitung)
|
||||
- `purge-before-upsert` und `--note-scope-refs` Parameter ergänzt
|
||||
|
||||
**v1.3.0 (2025-09-09)**
|
||||
- Hash-Normalisierung und Edge-Scope
|
||||
- Roundtrip-Tests, Agenten-Integration
|
||||
|
||||
**v1.2.0 (2025-09-02)**
|
||||
- Grundstruktur des Knowledge-Designs
|
||||
- Offline-Eval-Sets, Telemetrie (lokal), Drift-Checks, manuelle Reviews.
|
||||
- Kennzahlen: Hit-Rate, Overlap, Quellen-Alter, Erklärungspfad-Nutzung.
|
||||
|
||||
---
|
||||
|
||||
## 15. Offene Punkte
|
||||
|
||||
- Ausdetaillierung `types.yaml` (Relationen, Hooks).
|
||||
- UI-Oberfläche für Erklärpfade und Provenienz.
|
||||
- Batch-Jobs für abgeleitete Edges.
|
||||
|
||||
---
|
||||
|
||||
## 16. Ergänzungen 2025-11-09 (v1.5.0)
|
||||
|
||||
**Kontext:** Basierend auf den neuen Rahmenbedingungen (nur Deutsch; perspektivische externe Abfragen; einheitliche Vertraulichkeit mit Option auf feinere Stufen; Recency-Priorisierung als Default; Regeln später konfigurierbar; zunächst lokale Speicherung mit optionaler Migration; heutige Hardware, später skalierbar; hohe Erklärbarkeit mit mehreren Erklärungsebenen) werden folgende Entscheidungen und Erweiterungen getroffen. Alle bisherigen Inhalte bleiben gültig und werden **nicht** verändert.
|
||||
|
||||
### 16.1 Sprach- und Inhaltsrichtlinie (nur Deutsch)
|
||||
- `lang: "de"` als verpflichtendes Feld in allen Note-, Chunk- und Edge-Payloads.
|
||||
- Für spätere Mehrsprachigkeit **nicht** die Collection splitten, sondern ein Feld `lang` + optional `lang_original` behalten; Translation-Artefakte als eigener `type: translation` (verweisend auf `source_id`).
|
||||
|
||||
### 16.2 Vertraulichkeit & Sichtbarkeit
|
||||
- Heute: einheitliche Stufe `visibility: "internal"`.
|
||||
- Vorausschauend: reservierte Felder in allen Payloads
|
||||
- `visibility`: `"public" | "internal" | "restricted"`
|
||||
- `sensitivity`: Integer 0–3 (0 = unkritisch, 3 = hochsensibel)
|
||||
- `acl`: Liste erlaubter Rollen/Personen-IDs (App-Layer erzwingt Filter vor Query).
|
||||
- Access-Control erfolgt **im Applikations-Layer** mittels Qdrant-Payload-Filtern (`must: [ { key: "visibility", match: { any: [...] }}, ... ]`); Qdrant bleibt „dumm“ in Bezug auf ACL.
|
||||
|
||||
### 16.3 Recency-Modell & Ranking (konfigurierbar)
|
||||
- Default: **Zeitnähe** priorisieren (sanfte Abwertung älterer Inhalte).
|
||||
- Im Retrieval kombinieren wir:
|
||||
1) Vektor-Score (cosine) aus Qdrant
|
||||
2) Zeitgewicht `time_decay = exp( - ln(2) * age_days / half_life_days )`
|
||||
3) Graph-Kontext aus Edges (z. B. Degree, Path-Hops zum Anker „Ich/Persona“)
|
||||
- Konfigurierbare Gewichte (per `.env` oder `config.yaml`):
|
||||
```text
|
||||
FINAL_SCORE = w_vec * norm(vec_score)
|
||||
+ w_time * time_decay
|
||||
+ w_graph * graph_context_score
|
||||
# Vorschlag: w_vec=0.70, w_time=0.20, w_graph=0.10; half_life_days=365
|
||||
```
|
||||
- Für Fragen, die „zeitlos“ sind, kann `half_life_days = inf` gesetzt werden (kein Decay).
|
||||
|
||||
### 16.4 Erklärbarkeit („Warum diese Antwort?“)
|
||||
- Jeder Antwort wird ein **Erklärpfad** mitgegeben (optional im UI):
|
||||
- Top-Chunks (mit Score-Zerlegung w_vec/w_time/w_graph)
|
||||
- **Kausalpfad** im Graphen: `Note → Edge(relation, confidence) → Note …`
|
||||
- **Provenienz** (Quelle, Erstellungszeit, letzte Änderung).
|
||||
- Ein **Multi-Layer-Explanations**-Modul ordnet Beiträge zu: Kindheit/Erlebnisse, Werte & Prinzipien, aktuelle Ziele/Leitbild, Gegenwartskontext.
|
||||
|
||||
### 16.5 Qdrant-Schemata (Ergänzungen, rückwärtskompatibel)
|
||||
- **Collections** bleiben: `mindnet_notes`, `mindnet_chunks`, `mindnet_edges` (+ `mindnet_people` falls noch nicht vorhanden).
|
||||
- Gemeinsame Zusatzfelder (alle Payloads):
|
||||
- `lang: "de"`
|
||||
- `visibility`/`sensitivity`/`acl` (s. 16.2)
|
||||
- `created_at` (ISO-8601), `updated_at` (ISO-8601), `age_days` (App-seitig berechnet)
|
||||
- **Chunks**:
|
||||
- Named-Vectors (z. B. `"content"`, optional `"title"`, `"tags"` für Hybrid-Scores).
|
||||
- `text_index` auf `body` für BM25-ähnliche Volltextsuche (Qdrant-Textindex).
|
||||
- `recency_group`: Jahr-Monat `YYYY-MM` (ermöglicht Pre-Filter für „letzte N Monate“).
|
||||
- **Edges** (explizit, keine Workarounds):
|
||||
- Felder: `src_id`, `dst_id`, `relation`, `direction`, `confidence` (0–1), `evidence` (Chunk-IDs), `created_at`, `updated_at`.
|
||||
- **edge_defaults** bleiben als **Interpretations-Hints**: z. B. `default_weight`, `symmetry`, `transitivity`. Sie ersetzen **nicht** echte Kanten, sondern parametrisieren abgeleitete/zusätzliche Kantenbildung.
|
||||
- Abgeleitete Edges: optionaler Batch-Job erzeugt *ergänzende* Kanten entlang `types.yaml`-Regeln (z. B. Backlinks, „inspired_by“ aus Zitaten), niemals statt der Originalkanten.
|
||||
|
||||
### 16.6 Regeln & Typen (konfigurierbar)
|
||||
- `types.yaml` erweitert um:
|
||||
- Relationstypen mit Default-Eigenschaften (`weight`, `directed`, `symmetric`, `transitive`).
|
||||
- **Scoring-Hooks**: pro Relation optionaler Einfluss auf `graph_context_score`.
|
||||
- **Privacy-Hooks**: pro Relation Minimal-Visibility (z. B. Beziehungen zu Personen sind mindestens `internal`).
|
||||
|
||||
### 16.7 Speicher- & Betriebsstrategie (heute lokal, später skalierbar)
|
||||
- **Heute**: Single-Node Qdrant mit HNSW-Index, Text-Index und Payload-Filtern; regelmäßiges Backup (Snapshots).
|
||||
- **Morgen**: Migrationspfad in **Qdrant-Distributed** (Shards, ggf. Replikation) bei Bedarf; Parameter-Gleichheit sichern (named-vectors, Metrik, HNSW-Param).
|
||||
- **Sicherheit**: Zugriff nur über internes Netz/Reverse-Proxy, Auth vor Qdrant; Festplatten-Verschlüsselung auf OS-Ebene (z. B. LUKS).
|
||||
|
||||
### 16.8 Persona-Layer („meine Essenz“)
|
||||
- Eigenständiger **Persona-Knoten** (z. B. Note `person/lars`), verbunden mit:
|
||||
- Werten/Prinzipien, Leitbild, prägenden Erlebnissen, Zielen, Rollen.
|
||||
- Jede Antwort kann gegen diesen Knoten **kontextualisiert** werden (Graph-Pfadnähe).
|
||||
- Feld `persona_weight` in Chunks/Notes zur Priorisierung persönlicher Relevanz.
|
||||
|
||||
### 16.9 Evaluierung & Qualitätssicherung
|
||||
- **Offline-Sets** aus echten Fragen (inkl. gewünschter Perspektiven) mit erwarteten Top-Quellen.
|
||||
- **Telemetrie** (lokal): Query-Arten, Treffer-Overlaps, Zeitgewicht-Effekte, „Warum-Pfad“ genutzt/ignoriert.
|
||||
- **Drift-Checks**: Anteil sehr alter vs. neuer Quellen in Antworten; manuelle Reviews.
|
||||
|
||||
### 16.10 Offene Punkte / Nächste Schritte
|
||||
1) `types.yaml` um Relationseigenschaften erweitern (s. 16.6).
|
||||
2) Retriever-Komposition inkl. Zeitgewicht (s. 16.3) implementieren.
|
||||
3) Explanations-Pfad inkl. Provenienzoberfläche (s. 16.4) im UI.
|
||||
4) Feld-Erweiterungen in Import-Pipelines (`lang`, `visibility`, Zeitfelder).
|
||||
5) Optional: Batch-Job für abgeleitete Edges nach Regeln (ergänzend, nicht ersetzend).
|
||||
@@ -0,0 +1,192 @@
|
||||
# Mindnet – Fachliche Architektur
|
||||
**Version:** 2.0 • **Datum:** 2025-11-09 • **Autor:** Fachkonzept (gemeinsam mit Owner)
|
||||
|
||||
---
|
||||
|
||||
## 0. Zweck dieses Dokuments
|
||||
Dieses Dokument beschreibt **Fachdomäne, Funktionsräume, Prozesse und Regeln** von *mindnet*. Es ergänzt die technische Architektur und macht die ursprünglichen Ziele, Designentscheidungen, Anti‑Patterns und Umsetzungsstrategien explizit nachvollziehbar.
|
||||
|
||||
---
|
||||
|
||||
## 1. Vision & Leitplanken
|
||||
- **Essenz bewahren:** Entscheidungen, Erlebnisse, Werte, Prinzipien und Konditionierungen so strukturieren, dass sie später erklärbar rekonstruiert werden können.
|
||||
- **Antworten im eigenen Stil:** Ergebnisse sollen die Persönlichkeit des Owners widerspiegeln (Sprache: **Deutsch**).
|
||||
- **Vertraulichkeit:** Aktuell einheitlich, aber mit **Stufen** (public/internal/sensitive) erweiterbar.
|
||||
- **Zeitliche Priorisierung:** Standard: jüngere Inhalte leichter gewichten; Ausnahmen konfigurierbar.
|
||||
- **Lokal zuerst**, später skalierbar.
|
||||
|
||||
---
|
||||
|
||||
## 2. Fachliches Datenmodell
|
||||
### 2.1 Kernobjekte
|
||||
- **Note**: Eintrag im Wissensnetz (z. B. Konzept, Projekt, Erfahrung, Ereignis, Aufgabe).
|
||||
- **Chunk**: semantischer Abschnitt einer Note (Antwortbaustein).
|
||||
- **Edge**: gerichtete Beziehung zwischen Notes/Chunks (mit Typ, Gewicht, Quelle).
|
||||
- **Run**: Importlauf (Audit).
|
||||
- **Config**: aktive Regel‑ und Typkonfigurationen.
|
||||
|
||||
### 2.2 Typen & Semantik (Auszug)
|
||||
- `concept`: Begriff/These/Prinzip.
|
||||
- `experience`: Erlebnis/Beobachtung (zeitlich verankert).
|
||||
- `project`: Vorhaben mit Zielen/Abhängigkeiten.
|
||||
- `task`: Arbeitseinheit.
|
||||
- (erweiterbar: `event`, `decision`, `person`, `place`, `quote` …)
|
||||
|
||||
### 2.3 Relationen (fachlich)
|
||||
- `references`: verweist inhaltlich auf …
|
||||
- `related_to`: thematische Nähe/Assoziation.
|
||||
- `depends_on`: fachliche/kausale Abhängigkeit.
|
||||
- `belongs_to`: Zugehörigkeit (Teil‑von, Kapitel‑zu).
|
||||
- `derived_from`: abgeleitet (z. B. Schluss aus Erfahrung).
|
||||
- `inspired_by`: Impuls/Idee aus Quelle.
|
||||
- `supports` / `contradicts`: argumentative Beziehung.
|
||||
|
||||
---
|
||||
|
||||
## 3. Funktionsräume
|
||||
1. **Kurativer Raum**
|
||||
- Schreiben/Überarbeiten von Notizen (Obsidian Templates, Frontmatter‑Guides).
|
||||
- Plausibilisierung: Pflichtfelder, Dublettencheck, Warnungen (z. B. fehlende Relationen).
|
||||
|
||||
2. **Graphischer Raum**
|
||||
- Relationen setzen (declared), Vorschläge prüfen (inferred).
|
||||
- Subgraph‑Explorer je Frage/Entscheidung.
|
||||
|
||||
3. **Antwort‑Raum**
|
||||
- Query‑Typen: *Faktenabruf*, *Erlebnisbasiert erklären*, *Planung/Entscheidung begründen*.
|
||||
- Erklärpfad: Chunks → Kanten → Zeitfaktoren → Typgewichte.
|
||||
|
||||
4. **Governance‑Raum**
|
||||
- Sichtbarkeit/ACL, Qualitätsflags, Review‑Queues.
|
||||
- Versionsjournal, Import‑Runs, Config‑Historie.
|
||||
|
||||
---
|
||||
|
||||
## 4. Fachliche Regeln
|
||||
### 4.1 Frontmatter‑Schema (Mindeststandard)
|
||||
```yaml
|
||||
id: "{deterministic}"
|
||||
title: "…"
|
||||
type: "concept|experience|project|task|…"
|
||||
created: "YYYY-MM-DD"
|
||||
modified: "YYYY-MM-DD"
|
||||
visibility: "internal" # default
|
||||
retriever_weight: null # optional override
|
||||
chunk_profile: null # optional override
|
||||
tags: ["…"]
|
||||
edge_hints:
|
||||
- relation: references
|
||||
target: "note-id-or-path"
|
||||
- relation: depends_on
|
||||
target: "…"
|
||||
```
|
||||
|
||||
### 4.2 Typregeln (aus types.yaml)
|
||||
- `chunk_profile`, `retriever_weight`, `edge_defaults` werden je Typ **automatisch** angewandt.
|
||||
- Aus `edge_defaults` abgeleitete Kanten werden **persistiert** (`source='rule'`).
|
||||
|
||||
### 4.3 Zeitgewichtung
|
||||
- Default: **Exponential Decay** mit globalem λ; Override per `time_weight_override` möglich.
|
||||
- Erlebnisse (`experience`) erhalten standardmäßig leicht höheren **Base‑Impact** im Score, um Persönlichkeit abzubilden.
|
||||
|
||||
### 4.4 Qualitätsregeln
|
||||
- Jede Note soll **mind. eine Relation** besitzen.
|
||||
- **Konflikte** (contradicts) werden nicht gefiltert, sondern sichtbar gemacht (mit Hinweis).
|
||||
- **Sichtbarkeit**: Antworten aus `sensitive` nur bei expliziter Freigabe.
|
||||
|
||||
---
|
||||
|
||||
## 5. Use Cases (repräsentativ)
|
||||
1. **„Warum habe ich 2019 X entschieden?“**
|
||||
- Abfrage auf `decision` + temporale Nachbarschaft zu `experience`/`principle`.
|
||||
- Ausgabe mit Erklärpfad: *Erlebnis → Prinzip → Projekt → Entscheidung*.
|
||||
|
||||
2. **„Plane ein Trainingsprogramm“**
|
||||
- Query kombiniert Konzepte/Erfahrungen/Projekte → Graph‑Walk + Typgewichtung, priorisiert jüngere Erkenntnisse.
|
||||
|
||||
3. **„Welche Ereignisse haben mein Leitbild geprägt?“**
|
||||
- Subgraph über `derived_from`/`inspired_by` Ketten + Zeitachsen‑Visualisierung.
|
||||
|
||||
---
|
||||
|
||||
## 6. Anti‑Patterns (vermeiden)
|
||||
- **Edges ohne Relation** („Dot‑Kanten“) – verhindern jede sinnvolle Auswertung.
|
||||
- **Nur Vektor‑Suche** ohne Graph / Zeitfaktor – verfälscht Persönlichkeit.
|
||||
- **Freies Tag‑Chaos** ohne Typregeln – mindert Reproduzierbarkeit.
|
||||
- **Heimliche Workarounds** (z. B. Felder mit Mehrdeutigkeit) – erschweren spätere Automatisierung.
|
||||
|
||||
---
|
||||
|
||||
## 7. Umsetzungsstrategie & Roadmap
|
||||
### Phase 1 (Jetzt)
|
||||
- Pflicht‑Frontmatter, deterministische IDs, Ingestion v2 (Chunks/Edges **persistiert**).
|
||||
- types.yaml + retrieval.yaml live‑fähig; Import‑Run‑Audit.
|
||||
- Tests (Parser/Chunker/Edge‑Rules), Regression auf Chunk‑Mengen.
|
||||
|
||||
### Phase 2
|
||||
- Hybrid‑Retrieval mit Graph‑Boosts, Explain‑Traces in API.
|
||||
- Subgraph‑Explorer, Governance‑Views (Review‑Queues).
|
||||
|
||||
### Phase 3
|
||||
- ML‑gestützte Edge‑Vorschläge, temporale Graphanalysen, Reasoning‑Chains.
|
||||
- ACL/Sharing‑Modelle, Export/Archiv‑Pipelines.
|
||||
|
||||
---
|
||||
|
||||
## 8. Beispiel‑Konfigurationen
|
||||
### 8.1 types.yaml (Beispiel – wie technisch)
|
||||
```yaml
|
||||
version: 1.0
|
||||
types:
|
||||
concept:
|
||||
chunk_profile: medium
|
||||
edge_defaults: ["references", "related_to"]
|
||||
retriever_weight: 0.33
|
||||
task:
|
||||
chunk_profile: short
|
||||
edge_defaults: ["depends_on", "belongs_to"]
|
||||
retriever_weight: 0.8
|
||||
experience:
|
||||
chunk_profile: medium
|
||||
edge_defaults: ["derived_from", "inspired_by"]
|
||||
retriever_weight: 0.9
|
||||
project:
|
||||
chunk_profile: long
|
||||
edge_defaults: ["references", "depends_on"]
|
||||
retriever_weight: 0.95
|
||||
```
|
||||
|
||||
### 8.2 retrieval.yaml
|
||||
```yaml
|
||||
relation_weights:
|
||||
references: 1.0
|
||||
related_to: 0.6
|
||||
depends_on: 1.2
|
||||
belongs_to: 0.8
|
||||
derived_from: 1.1
|
||||
inspired_by: 0.8
|
||||
supports: 1.0
|
||||
contradicts: -0.9
|
||||
mixing:
|
||||
alpha: 0.45
|
||||
beta: 0.25
|
||||
gamma: 0.20
|
||||
delta: 0.07
|
||||
epsilon: 0.03
|
||||
time_decay:
|
||||
lambda: 0.0025
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Governance & Nachvollziehbarkeit
|
||||
- **Decision Log** (ADR‑ähnlich): jedes Regel‑/Schema‑Update mit Begründung.
|
||||
- **Import‑Protokolle** versioniert, inkl. geänderter Dateien, Chunk‑/Edge‑Zahlen.
|
||||
- **Explainability Standard** in jeder Antwort.
|
||||
|
||||
---
|
||||
|
||||
## Anhang A: Glossar
|
||||
- **Chunk‑Profil**: Regelset zur Textteilung.
|
||||
- **Rule‑Edge**: automatisch erzeugte Kante auf Basis von Typregeln.
|
||||
- **Declared Edge**: explizit gesetzte Kante aus der Quelle.
|
||||
@@ -0,0 +1,474 @@
|
||||
# Mindnet – Technische Architektur
|
||||
**Version:** 2.0 • **Datum:** 2025-11-09 • **Autor:** Systemarchitektur (gemeinsam mit Owner)
|
||||
|
||||
---
|
||||
|
||||
## 0. Zweck dieses Dokuments
|
||||
Dieses Dokument beschreibt die **technische Architektur** von *mindnet* so präzise, dass ein erfahrener Engineer sie 1:1 implementieren kann. Es konsolidiert die bisherigen Überlegungen, eliminiert redundante/unklare Passagen und ergänzt fehlende Details (Datenmodell, Indizes, Import‑Pipelines, Scoring, Erklärbarkeit, Skalierung, Betrieb). Gültige Inhalte aus früheren Fassungen bleiben erhalten (siehe **Anhang A: Originalinhalt**).
|
||||
|
||||
> **Kernziele:**
|
||||
> - Persönliches Wissensnetz mit langlebiger Semantik (Notizen, Erlebnisse, Entscheidungen).
|
||||
> - Antworten, die **erklärbar** auf Erfahrungen, Konditionierung und Persönlichkeit beruhen.
|
||||
> - **Konfigurierbare Regeln** (Zeitgewichtung, Relationstypen, Typ‑Profile).
|
||||
> - **Lokal** betreibbar, später **skalierbar** (on‑prem → Rechenzentrum/Cloud).
|
||||
> - **Deterministisch**, idempotent, auditierbar.
|
||||
|
||||
---
|
||||
|
||||
## 1. Systemkontext (High Level)
|
||||
- **Quellen:** Obsidian‑Vault (Markdown + Frontmatter), künftig MediaWiki/HTML/PDF/E-Mail/Images.
|
||||
- **Ingestion:** Validator → Parser → Chunker (Profile) → Embedding → Graph‑& Payload‑Indexierung.
|
||||
- **Speicher:** Qdrant als Vektorstore + Payload (JSON), ergänzt um Dateimetadaten.
|
||||
- **APIs:** FastAPI (Read/Write), Tools (mindnet_query, mindnet_subgraph), n8n‑Glue.
|
||||
- **Retrieval/Reasoning:** Hybrid (Vektor + Keyword + Graph‑Walk) mit konfigurierbaren Scoring‑Regeln und **Erklärpfad**.
|
||||
- **Ops:** Deterministische IDs, Versions/Provenance‑Felder, Observability, Tests.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielarchitektur (Komponenten)
|
||||
### 2.1 Ingestion Layer
|
||||
1. **Frontmatter‑Validator**
|
||||
- Erzwingt Pflichtfelder: `id`, `title`, `type`, `created`, `modified`
|
||||
- Optionale Felder: `tags`, `visibility`, `relevance`, `time_weight_override`, `retriever_weight`, `chunk_profile`, `sources`, `aliases`, `edge_hints`.
|
||||
- Validiert `type` gegen **types.yaml** (Konfiguration).
|
||||
|
||||
2. **Parser**
|
||||
- Extrahiert: reinen Text, Überschriften, Querverweise (`[[Note]]`, Markdown‑Links), Zitate/Quellen.
|
||||
- Normalisiert Unicode, trennt Codeblöcke, Zitate, Aufzählungen.
|
||||
|
||||
3. **Chunker** (profilgesteuert)
|
||||
- Profile: `short` (~300–500 Token), `medium` (~700–1000), `long` (~1200–1600).
|
||||
- Regeln: Absatz‑, Überschriften‑, semantische Grenzen, Überschneidung ~10–15% für Kontextkohärenz.
|
||||
- Chunk‑Header speichert: `{note_id, path, type, idx, section_hierarchy, tokens, chunk_profile}`.
|
||||
|
||||
4. **Embedding**
|
||||
- Standard: MiniLM‑384d (lokal über Ollama/TEI), konfigurierbar (`embedding.model`, `dim`).
|
||||
- Persistiert Vektor + **Payload**.
|
||||
|
||||
5. **Edge‑Builder**
|
||||
- **Declared Edges**: aus expliziten Links/Referenzen in der Quelle.
|
||||
- **Inferred Edges (Rules)**: aus `types.yaml.edge_defaults` **und** Heuristiken (z. B. Abschnittstitel „Bezug“, „siehe auch“).
|
||||
- Beide Ebenen als **Edges** persistiert mit `source='declared' | 'rule'`, **kein bloßer Dot‑Marker**.
|
||||
|
||||
### 2.2 Storage Layer (Qdrant)
|
||||
**Collections (empfohlen):**
|
||||
- `mindnet_notes` (1 Vektor je Note, optional)
|
||||
- `mindnet_chunks` (**primärer Suchraum**)
|
||||
- `mindnet_edges` (Graph als Payload‑Dokumente)
|
||||
- `mindnet_runs` (Import‑Läufe, Audit/Provenance)
|
||||
- `mindnet_configs` (aktive Konfigurationen, z. B. `types.yaml` Schnappschuss)
|
||||
|
||||
**Beispiel‑Schemas:**
|
||||
|
||||
```yaml
|
||||
# mindnet_chunks.payload
|
||||
id: string # deterministic (UUIDv5 über prefix+path+idx)
|
||||
note_id: string # FK mindnet_notes.id
|
||||
type: string # z. B. concept|task|experience|project|event …
|
||||
title: string
|
||||
path: string # Pfad im Vault
|
||||
collection: string # Präfix/Namespace
|
||||
created: string # ISO‑Datum
|
||||
modified: string # ISO‑Datum
|
||||
chunk_idx: int
|
||||
chunk_profile: string # short|medium|long
|
||||
retriever_weight: float # aus types.yaml oder Note‑Override
|
||||
time_weight: float # berechnet (Decay) oder Override
|
||||
section: string # Überschrift/Gliederung
|
||||
text: string # Rohtext des Chunks
|
||||
tokens: int
|
||||
hash: string # content_hash (idempotent)
|
||||
visibility: string # public|internal|sensitive
|
||||
source: { # Provenance
|
||||
repo: string|null,
|
||||
path: string,
|
||||
commit: string|null,
|
||||
import_run_id: string
|
||||
}
|
||||
```
|
||||
|
||||
```yaml
|
||||
# mindnet_edges.payload
|
||||
id: string # deterministic (UUIDv5 über src_id + dst_id + relation + source)
|
||||
src_id: string # id (Note ODER Chunk)
|
||||
dst_id: string # id (Note ODER Chunk)
|
||||
src_kind: string # note|chunk
|
||||
dst_kind: string # note|chunk
|
||||
relation: string # references|related_to|depends_on|belongs_to|derived_from|inspired_by|mentions|contradicts|supports …
|
||||
weight: float # Standard 1.0; typenspezifische Offsets möglich
|
||||
source: string # declared|rule|ml
|
||||
evidence: string|null # Textausschnitt/Link der Ableitung
|
||||
created: string
|
||||
import_run_id: string
|
||||
visibility: string
|
||||
```
|
||||
|
||||
**Indizes (Qdrant):**
|
||||
- Vektorindex auf `mindnet_chunks` (HNSW)
|
||||
- Payload‑Indizes:
|
||||
- `type` (keyword), `visibility` (keyword), `created/modified` (datetime), `note_id` (keyword)
|
||||
- optional: **Full‑Text** auf `text` (Qdrant payload text index) für Hybrid‑Suche
|
||||
|
||||
### 2.3 Retrieval & Scoring
|
||||
**Hybrid‑Pipeline (empfohlen):**
|
||||
1. **Lexikalische Kandidaten** (FTS auf `text`, `title`, `aliases`) – k_l.
|
||||
2. **Vektor‑Kandidaten** (ANN auf Embeddings) – k_v.
|
||||
3. **Graph‑Expansion**: 1–2 Hops über `mindnet_edges` mit relation‑spezifischen Boosts.
|
||||
4. **Re‑Ranking** (finale Score):
|
||||
- `S = α·sim + β·kw + γ·G + δ·time_decay + ε·type_weight + ζ·recency_boost_overrides`
|
||||
- `type_weight` = `retriever_weight` aus **types.yaml** oder Note‑Override.
|
||||
- `time_decay` = `exp(−λ·age_days)`; λ global/konfigurierbar; Override per Frontmatter möglich.
|
||||
- **Erklärbarkeit:** Speichere die Summanden + Top‑Edges als **evidence** im Query‑Log.
|
||||
|
||||
**Relation‑Gewichte (Defaultvorschlag):**
|
||||
```yaml
|
||||
relation_weights:
|
||||
references: 1.0
|
||||
related_to: 0.6
|
||||
depends_on: 1.2
|
||||
belongs_to: 0.8
|
||||
derived_from: 1.1
|
||||
inspired_by: 0.8
|
||||
supports: 1.0
|
||||
contradicts: -0.9
|
||||
```
|
||||
|
||||
### 2.4 Konfiguration (types.yaml + config.yaml)
|
||||
```yaml
|
||||
version: 1.0
|
||||
types:
|
||||
concept: { chunk_profile: medium, edge_defaults: [references, related_to], retriever_weight: 0.33 }
|
||||
task: { chunk_profile: short, edge_defaults: [depends_on, belongs_to], retriever_weight: 0.80 }
|
||||
experience: { chunk_profile: medium, edge_defaults: [derived_from, inspired_by],retriever_weight: 0.90 }
|
||||
project: { chunk_profile: long, edge_defaults: [references, depends_on], retriever_weight: 0.95 }
|
||||
retrieval:
|
||||
alpha: 0.45 # sim
|
||||
beta: 0.25 # keyword
|
||||
gamma: 0.20 # graph
|
||||
delta: 0.07 # time decay
|
||||
epsilon: 0.03 # type weight
|
||||
time_decay:
|
||||
lambda: 0.0025 # ~ Halbwertzeit ≈ 277 Tage
|
||||
visibility_defaults: public
|
||||
```
|
||||
|
||||
### 2.5 Determinismus, Versionierung, Idempotenz
|
||||
- **IDs:** UUIDv5 über `{collection_prefix}:{path}:{chunk_idx}` (Chunks) bzw. `{collection_prefix}:{path}` (Notes).
|
||||
- **content_hash:** SHA256 über normalisierte Inhalte (Unicode NFC, Whitespace‑Policy, Überschriften‑Normalisierung).
|
||||
- **Import‑Lauf (`mindnet_runs`)**: `{run_id, started_at, finished_at, config_hash, files_seen, files_changed, errors}`.
|
||||
- **Idempotenz:** nur `changed` bei `content_hash`‑Abweichung.
|
||||
|
||||
### 2.6 Erklärbarkeit (Audit Trail)
|
||||
- Jede Antwort liefert: Top‑Chunks, Summanden des Scores, **angetretene Kanten** inkl. Relation & Gewicht, Zeitfaktor.
|
||||
- Persistiere Query‑Logs (optional): `{query, filters, topk, decision_trace, timestamp}`.
|
||||
|
||||
### 2.7 Sicherheit & Datenschutz
|
||||
- **visibility**: `public|internal|sensitive`, Query‑Filter standardmäßig `internal`.
|
||||
- Optionale **ACL**‑Schicht: Nutzer/Gruppen, Freigabe je Note/Chunk/Edge.
|
||||
- **Redaktions‑Flags**: `needs_review`, `draft`, `private_journal` (werden standardmäßig ausgeschlossen).
|
||||
|
||||
### 2.8 Skalierung & Betrieb
|
||||
- **Shards/Replicas** (Qdrant): 1/1 lokal; 2/2 in DC/Cloud.
|
||||
- **Snapshots/Backups**: Qdrant Snapshot + Vault‑Repo Snapshot (rsync/borg).
|
||||
- **Observability**: Prometheus‑Exporter (API Latenz, Import‑Dauer, Chunks/Edges pro Lauf), strukturierte Logs (JSON).
|
||||
- **Tests**: deterministische Golden‑Files für Parser/Chunker; Contract‑Tests für API; Offline‑Eval für Retrieval.
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementierungsleitfaden (konkret)
|
||||
### 3.1 Collections anlegen (Qdrant)
|
||||
- `mindnet_chunks(dim=384, distance=cosine)`
|
||||
- `mindnet_notes(dim=384, distance=cosine)` (optional, falls Note‑Level‑Suche gewünscht)
|
||||
- `mindnet_edges(dim=0)` (reiner Payload‑Store; kein Vektor)
|
||||
- Payload‑Indizes: siehe 2.2
|
||||
|
||||
### 3.2 Import‑Pipeline (CLI)
|
||||
1. **Scan** Vault → valide Dateien.
|
||||
2. **Make Note Payload** (inkl. Typ‑Regeln; `retriever_weight`/`chunk_profile` aus **types.yaml**, Override per Frontmatter).
|
||||
3. **Chunken** gemäß Profil + `chunk_idx`.
|
||||
4. **Edges bauen**: declared + rule‑inferred (duplizierte Kanten per ID‑Determinismus verhindern).
|
||||
5. **Upsert**: Notes → Chunks → Edges (in dieser Reihenfolge).
|
||||
6. **Run‑Record** und **Config‑Schnappschuss** persistieren.
|
||||
|
||||
### 3.3 Query‑API (FastAPI)
|
||||
- `POST /query`: text, filters({visibility, types, date_range}), topk, graph_hops, `explain=true`.
|
||||
- `GET /subgraph/{id}`: Nachbarschaft, Relation‑Filter, Depth.
|
||||
- `POST /admin/reindex` / `POST /admin/import`.
|
||||
|
||||
### 3.4 Konfigurierbarkeit
|
||||
- `types.yaml` heiß ladbar (mit Versionsstempel); bei Änderung → `config_hash` & reimport optional.
|
||||
- `retrieval.yaml` für Gewichte, Relation‑Boosts, Zeitdecay.
|
||||
|
||||
---
|
||||
|
||||
## 4. Migrations‑ und Qualitätsregeln
|
||||
- **Keine Workarounds**, die Semantik zerstören (z. B. „Dot‑Edge“ ohne Relation).
|
||||
- **Explizite Kantenpersistenz**: *jede* Regelkante wird als `source='rule'` gespeichert.
|
||||
- **Chunk‑Zahl**: Profiltreue sicherstellen; Regressionstest (z. B. 171 ➝ 59 = **Fehler** oder Profiländerung dokumentieren).
|
||||
- **Provenance Pflicht**: `import_run_id` in Chunks/Edges setzen.
|
||||
|
||||
---
|
||||
|
||||
## 5. Offene Erweiterungen (vordenken)
|
||||
- **ML‑Edge‑Inference** (NER, Coref, TEI‑Reranking).
|
||||
- **Reasoning‑Graph** (Motivationsketten: Kindheitserlebnis → Prinzip → Entscheidung).
|
||||
- **Citations‑Fabric** (autom. Quellenkonsolidierung).
|
||||
- **Temporale Graphabfragen** (Edges mit Zeitintervallen).
|
||||
|
||||
---
|
||||
|
||||
## Anhang A: Originalinhalt (unverändert, falls vorhanden)
|
||||
Der vollständige Originaltext aus `knowledge_design.md` bleibt hier als Referenz erhalten, damit keine implizite Aussage verloren geht.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# mindnet – Knowledge Design
|
||||
**Version:** 1.4.0 (aktualisiert 2025-10-06)
|
||||
|
||||
## 1. Gesamtziel und Systemverständnis
|
||||
|
||||
**mindnet** ist ein lokales Wissensnetzwerk, das alle meine Notizen, Projekte, Gedanken, Erfahrungen und Pläne als Markdown-Dateien speichert, automatisch importiert, semantisch in **Chunks** zerlegt und als **Graph-Struktur in Qdrant** ablegt.
|
||||
Es ist die Grundlage für ein agentenfähiges, lokal betriebenes LLM-System, das meine Daten verknüpft, abfragt und erweitert.
|
||||
|
||||
**Zentrale Ziele**
|
||||
- Vollständige Repräsentation persönlichen Wissens in strukturierter, maschinenlesbarer Form
|
||||
- Reproduzierbare Verarbeitung: Import → Chunking → Embedding → Edges → Graph
|
||||
- Verlustfreie Roundtrip-Fähigkeit (Import ⇄ Export)
|
||||
- Erweiterbarkeit für Agenten, RAG-Retriever und semantische Suche
|
||||
|
||||
**Prinzipien**
|
||||
- **Deterministisch:** IDs, Hashes und Edges wiederholbar
|
||||
- **Portabel:** Markdown + YAML
|
||||
- **Robust:** fehlertoleranter Parser
|
||||
- **Idempotent:** keine Duplikate bei Re-Import
|
||||
- **Erweiterbar:** neue Typen und Edge-Arten ohne Migration
|
||||
|
||||
---
|
||||
|
||||
## 2. YAML-Frontmatter-Schema
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
|-------|-----|--------------|
|
||||
| `title` | string | Menschlich lesbarer Titel |
|
||||
| `id` | string | Eindeutige Note-ID (Slug) |
|
||||
| `type` | enum | `concept`, `thought`, `experience`, `task`, `project`, `journal`, `person`, `meeting`, `milestone` |
|
||||
| `status` | enum | `draft`, `active`, `done`, `archived` |
|
||||
| `created` | date | ISO-Datum |
|
||||
| `updated` | date | Letzte Änderung |
|
||||
| `area` | string | Themen- oder Lebensbereich |
|
||||
| `project` | string | Zugehöriges Projekt |
|
||||
| `tags` | list | Strukturierte Tags (`area/…`, `topic/…`) |
|
||||
| `depends_on` | list | IDs anderer Notizen |
|
||||
| `assigned_to` | list | Beteiligte Personen |
|
||||
| `embedding_exclude` | bool | Falls `true`, keine Embeddings |
|
||||
| `hash_mode` | enum | Hash-Modus beim Import (`body`, `frontmatter`, `full`) |
|
||||
| `priority` | enum/int | 1–5 oder `low` / `med` / `high` |
|
||||
| `effort_min`, `due` | int/date | Aufwand / Termin |
|
||||
| `aliases` | list | Alternative IDs |
|
||||
| `lang` | string | ISO-Sprachcode |
|
||||
| `source` | string | Herkunft / Referenzquelle |
|
||||
|
||||
**Pflichtfelder:** `title`, `id`, `type`, `status`, `created`
|
||||
**Optionale Felder:** alle übrigen
|
||||
|
||||
---
|
||||
|
||||
## 3. Dateinamen und Ordner
|
||||
|
||||
- Format: `YYYY-MM-DD_title.md` oder `slug.md`
|
||||
- Strukturierte Ordner:
|
||||
- `10_thoughts/`, `20_concepts/`, `30_projects/`, `40_experiences/`, …
|
||||
- Alle Pfade relativ; Unterstriche statt Leerzeichen
|
||||
|
||||
---
|
||||
|
||||
## 4. Link- und Edge-Design
|
||||
|
||||
**Verlinkungen**
|
||||
- Wikilinks: `[[note-id]]` oder `[[Titel|note-id]]`
|
||||
- Automatische Edges aus Text und Frontmatter
|
||||
|
||||
**Edge-Typen in Qdrant**
|
||||
|
||||
| Typ | Bedeutung | Quelle | Scope |
|
||||
|------|------------|--------|--------|
|
||||
| `belongs_to` | Chunk → Note | intern | chunk |
|
||||
| `prev` / `next` | Reihenfolge | intern | chunk |
|
||||
| `references` | explizite Wikilinks | Text | chunk |
|
||||
| `backlink` | Gegenkante zu `references` | abgeleitet | note |
|
||||
| `depends_on` | YAML-Abhängigkeiten | YAML | note |
|
||||
| `assigned_to` | YAML-Zuweisung | YAML | note |
|
||||
| `unresolved` | Ziel fehlt (Stub) | abgeleitet | chunk |
|
||||
|
||||
**Edge-Schlüssel**
|
||||
- `source_id`, `target_id`, `kind`, `scope`, `note_id`
|
||||
- Dedup-Schlüssel: Kombination aus `(kind, source_id, target_id, scope)`
|
||||
|
||||
---
|
||||
|
||||
## 5. Chunking-Modell
|
||||
|
||||
**Chunk-Datenstruktur**
|
||||
| Feld | Beschreibung |
|
||||
|-------|---------------|
|
||||
| `note_id` | Zugehörige Note |
|
||||
| `chunk_index` | Laufende Nummer |
|
||||
| `text` | Originalabschnitt |
|
||||
| `window` | Text + Overlap links/rechts |
|
||||
| `overlap_left` | Länge des linken Overlaps |
|
||||
| `overlap_right` | Länge des rechten Overlaps |
|
||||
| `embedding` | 384-dimensionaler Vektor |
|
||||
| `tokens` | Tokenanzahl (optional) |
|
||||
|
||||
**Chunking-Regeln (aus `chunking_strategy.md`)**
|
||||
- Trennung nach Absätzen, Überschriften, Listen, Tabellen
|
||||
- Token-Zielgröße 350–500 (max 600)
|
||||
- Overlap: 30–40 % für semantische Kohärenz
|
||||
- Overlap wird in `window` integriert, sodass `text ≠ window`
|
||||
|
||||
---
|
||||
|
||||
## 6. Hash-Strategie und Änderungsverfolgung
|
||||
|
||||
**Zweck:** Nur bei realer Inhaltsänderung re-indexieren
|
||||
|
||||
| Umgebungsvariable | Beschreibung |
|
||||
|--------------------|--------------|
|
||||
| `MINDNET_HASH_COMPARE` | Vergleichsquelle (`Body`, `Full`, `Frontmatter`) |
|
||||
| `MINDNET_HASH_SOURCE` | Rohtext vs. geparst (`raw` / `parsed`) |
|
||||
| `MINDNET_HASH_NORMALIZE` | Normalisierung (`canonical` / `none`) |
|
||||
|
||||
**Basismodi**
|
||||
- `body` → Nur Textkörper
|
||||
- `frontmatter` → Nur Metadaten
|
||||
- `full` → Kombination
|
||||
- Hash = SHA-256(canonicalized_input)
|
||||
|
||||
Bei Änderung: Re-Import, neue Embeddings, Edges werden aktualisiert.
|
||||
|
||||
---
|
||||
|
||||
## 7. Qdrant-Speicherstruktur
|
||||
|
||||
| Collection | Inhalt | Primärfelder | Embedding |
|
||||
|-------------|---------|---------------|------------|
|
||||
| `mindnet_notes` | Notes mit Fulltext & Hash | `note_id` | optional |
|
||||
| `mindnet_chunks` | Chunks mit Text, Window, Embedding | `chunk_id`, `note_id` | 384 d |
|
||||
| `mindnet_edges` | Graphkanten | `edge_id`, `source_id`, `target_id` | — |
|
||||
|
||||
**Upsert-Strategie**
|
||||
- Idempotente UUIDv5-IDs
|
||||
- Keine Duplikate durch deterministische Signaturen
|
||||
- `purge-before-upsert` zur Bereinigung
|
||||
|
||||
**Indizes**
|
||||
- notes: `note_id`, `hash_signature`
|
||||
- chunks: `note_id`, `chunk_index`
|
||||
- edges: `(kind, source_id, target_id, scope)`
|
||||
|
||||
---
|
||||
|
||||
## 8. Fehler-Toleranz und Parser-Robustheit
|
||||
|
||||
- UTF-8 mit Fallback: ersetzt ungültige Bytes (`errors="replace"`)
|
||||
- Ignoriert Nullbytes, BOM, exotische Zeilenenden
|
||||
- Erkennt defekte oder leere YAML-Header und überspringt sie
|
||||
- Logt Problemfälle (`read_markdown failed`, `make_note_payload returned non-dict`)
|
||||
- Bei Fehlern: Import → warn → continue
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests & Validierung
|
||||
|
||||
**Integrationstests**
|
||||
- Roundtrip: Import → Export → Compare (`compare_vaults.py`)
|
||||
- Chunk-Integrität: `verify_chunks_integrity.py`
|
||||
- Hash-Audit: `hash_reporter.py`
|
||||
- Window-Vergleich: `check_chunks_window_vs_text.py`
|
||||
|
||||
**Erwartete Ergebnisse**
|
||||
- Alle Notes werden erkannt
|
||||
- `window ≠ text` bei > 60 % der Chunks
|
||||
- Roundtrip-Vergleich liefert „OK“
|
||||
- Edge-Anzahl entspricht Modell (belongs_to = #Chunks, next/prev ≈ #Chunks – 1)
|
||||
|
||||
---
|
||||
|
||||
## 10. Export & Roundtrip-Verhalten
|
||||
|
||||
- `export_markdown.py` erzeugt identische Markdown-Dateien
|
||||
- Schreibt YAML + Body in korrekter Reihenfolge
|
||||
- Roundtrip-Prüfung (`compare_vaults.py`) validiert:
|
||||
- vollständigen Body
|
||||
- unveränderte Hash-Signatur
|
||||
- gleiche Chunkzahl
|
||||
|
||||
---
|
||||
|
||||
## 11. Graph-Schicht und WP-04-Integration
|
||||
|
||||
- Qdrant fungiert als Graph-Backend
|
||||
- `graph/service.py` (WP-04): stellt API für Mehrhop-Abfragen bereit
|
||||
- Unterstützt:
|
||||
- `expand(note_id, hops=2)`
|
||||
- `resolve_unresolved()`
|
||||
- `neighbors(kind=…)`
|
||||
- Grundlage für spätere **Retriever-Funktionen** (LLM / Agenten)
|
||||
|
||||
---
|
||||
|
||||
## 12. Agenten- und LLM-Integration
|
||||
|
||||
**Retriever-Pipeline**
|
||||
1. Suche top-k Chunks (cosine distance)
|
||||
2. Erweiterung um Edges (`references`, `backlinks`)
|
||||
3. Kontext-Assembling via `window`-Text
|
||||
4. Prompt-Generierung
|
||||
|
||||
**Agent-Use-Cases**
|
||||
- Automatisches Tagging (`type`, `status`)
|
||||
- Vorschläge für neue Edges
|
||||
- Auflösen von `unresolved`-Referenzen
|
||||
- Auto-Import externer Quellen (MediaWiki, PDFs, Webseiten)
|
||||
|
||||
---
|
||||
|
||||
## 13. Erweiterbarkeit
|
||||
|
||||
- Neue Edge-Typen: `inspired_by`, `relates_to`, `contradicts`
|
||||
- Neue Note-Typen: `decision`, `resource`, `recommendation`
|
||||
- Embedding-Engines austauschbar (MiniLM → LaBSE → E5)
|
||||
- Versionierte Chunking-Strategien (`chunk_config.py`)
|
||||
|
||||
---
|
||||
|
||||
## 14. Qualitätssicherung und Best Practices
|
||||
|
||||
- Validierung vor Upsert
|
||||
- Keine Leer-Chunks
|
||||
- Vollständige Metadaten in Notes
|
||||
- Tests in `tests/` automatisch ausführbar (`run_e2e_roundtrip.sh`)
|
||||
- Ergebnis: „Roundtrip OK“ und `verify_chunks_integrity` = OK
|
||||
|
||||
---
|
||||
|
||||
## 15. Änderungsverlauf
|
||||
|
||||
**v1.4.0 (2025-10-06)**
|
||||
- Neu: `window` vs `text` Feld in `mindnet_chunks`
|
||||
- Neu: Hash-Modi (`body`, `frontmatter`, `full`) mit Env-Steuerung
|
||||
- Neu: Baseline-Modus für Vergleich
|
||||
- Parser → fehlertolerant (UTF-8 replace)
|
||||
- Roundtrip-Test vollständig integriert
|
||||
- Graph-Service und Mehrhop-Abfragen (WP-04-Vorbereitung)
|
||||
- `purge-before-upsert` und `--note-scope-refs` Parameter ergänzt
|
||||
|
||||
**v1.3.0 (2025-09-09)**
|
||||
- Hash-Normalisierung und Edge-Scope
|
||||
- Roundtrip-Tests, Agenten-Integration
|
||||
|
||||
**v1.2.0 (2025-09-02)**
|
||||
- Grundstruktur des Knowledge-Designs
|
||||
|
||||
---
|
||||
@@ -0,0 +1,324 @@
|
||||
# mindnet v2 – Implementierungs-Playbook & Handover (Side‑by‑Side zu v1)
|
||||
*Stand:* 2025-11-10 08:03
|
||||
*Autor:* ChatGPT (Projekt‑Handover)
|
||||
*Zweck:* Vollständige, ausführbare Anleitung zur Weiterentwicklung von **mindnet** auf eine versionierte, testbare v2‑Architektur (neben v1), inklusive Prompt für den Folgethread, Akzeptanzkriterien, Dateiliste, Test‑ und Rollback‑Pläne.
|
||||
|
||||
---
|
||||
|
||||
## 0) Kontext & Zielbild (kurz)
|
||||
- **Mission:** Persönliches Wissensnetz, das langfristig die eigene Persönlichkeit, Erfahrungen und Entscheidungslogik abbildet; später nachvollziehbare Erklärungen für Familie/Nachwelt.
|
||||
- **Heutiger Stand (v1):** `mindnet_notes` in Qdrant vorhanden; **Chunks** und **Edges** bisher nur teilweise/nicht konsistent; Edge‑Defaults („1 Dot“) vorhanden, aber Ziele teils nicht materialisiert. Importskripte: `import_markdown.py`, `edges.py` (historisch).
|
||||
- **Ziel (v2):**
|
||||
- **Collections:** `mindnet_notes_v2`, `mindnet_chunks_v2`, `mindnet_edges_v2` (saubere Payload‑Schemata + Indizes).
|
||||
- **Chunker v2:** Block/Heading‑aware, Ziel 900–1200 Zeichen, Überlappung 120–180, deterministische `chunk_id`s.
|
||||
- **Edge‑Builder v2:** Reihenfolge: **explicit → rule → default_resolved → default**; saubere `provenance`.
|
||||
- **Importer‑Pipeline v2:** Parse → Chunk → Edge → Embeddings → Batch‑Upsert + Payload‑Indexpflege + Snapshots.
|
||||
- **Policies:** Privacy/Recency/Type‑Gewichte als **Konfiguration** (YAML + JSON‑Schema), nicht hart im Code.
|
||||
- **Observability:** FastAPI + OpenTelemetry (Tracing/Metrics); Import‑Reports (CSV/JSON).
|
||||
- **Side‑by‑Side:** v2 **parallel** zu v1; kein Big‑Bang.
|
||||
|
||||
> **Warum so?** Qdrant‑Payload‑Indizes/Filter → schnelle, erklärbare Selektionen; Snapshots → betriebssicheres Rollback; OTel → Nachvollziehbarkeit; YAML/JSON‑Schema → Validierbarkeit & Stabilität.
|
||||
|
||||
---
|
||||
|
||||
## 1) Datenmodelle (Schemata, v2)
|
||||
Die tatsächlichen JSON‑Schemata (2020‑12) werden im Repo abgelegt und in CI validiert.
|
||||
|
||||
### 1.1 note.schema.json
|
||||
```json
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://example.org/mindnet/note.schema.json",
|
||||
"type": "object",
|
||||
"required": ["id", "title", "type", "privacy", "created", "hash_body"],
|
||||
"properties": {
|
||||
"id": { "type": "string", "pattern": "^[a-zA-Z0-9_-]+$" },
|
||||
"title": { "type": "string", "minLength": 1 },
|
||||
"type": { "type": "string" },
|
||||
"privacy": { "type": "string", "enum": ["public","internal","private"] },
|
||||
"created": { "type": "string", "format": "date-time" },
|
||||
"modified": { "type": "string", "format": "date-time" },
|
||||
"tags": { "type": "array", "items": { "type": "string" } },
|
||||
"lang": { "type": "string", "default": "de" },
|
||||
"source_path": { "type": "string" },
|
||||
"source_collection": { "type": "string" },
|
||||
"hash_body": { "type": "string" },
|
||||
"hash_frontmatter": { "type": "string" },
|
||||
"token_count": { "type": "integer", "minimum": 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 chunk.schema.json
|
||||
```json
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://example.org/mindnet/chunk.schema.json",
|
||||
"type": "object",
|
||||
"required": ["chunk_id","note_id","text","ord"],
|
||||
"properties": {
|
||||
"chunk_id": { "type": "string", "pattern": "^[a-zA-Z0-9_-]+#c\d{4}$" },
|
||||
"note_id": { "type": "string" },
|
||||
"text": { "type": "string" },
|
||||
"ord": { "type": "integer", "minimum": 0 },
|
||||
"span_char_start": { "type": "integer", "minimum": 0 },
|
||||
"span_char_end": { "type": "integer", "minimum": 0 },
|
||||
"heading_path": { "type": "array", "items": { "type": "string" } },
|
||||
"section_title": { "type": "string" },
|
||||
"tokens_start": { "type": "integer", "minimum": 0 },
|
||||
"tokens_end": { "type": "integer", "minimum": 0 },
|
||||
"embeddings_version": { "type": "string" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 edge.schema.json
|
||||
```json
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://example.org/mindnet/edge.schema.json",
|
||||
"type": "object",
|
||||
"required": ["edge_id","src_note_id","relation","provenance"],
|
||||
"properties": {
|
||||
"edge_id": { "type": "string" },
|
||||
"src_note_id": { "type": "string" },
|
||||
"src_chunk_id": { "type": "string" },
|
||||
"dst_note_id": { "type": "string" },
|
||||
"dst_chunk_id": { "type": "string" },
|
||||
"relation": { "type": "string" },
|
||||
"evidence_spans":{ "type": "array", "items": {"type":"object","properties":{"chunk_id":{"type":"string"},"span":[{"type":"integer"},{"type":"integer"}]]} },
|
||||
"provenance": { "type": "string", "enum": ["explicit","rule","default_resolved","default"] },
|
||||
"rule_id": { "type": "string" },
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.4 default_edge.schema.json
|
||||
```json
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://example.org/mindnet/default_edge.schema.json",
|
||||
"type": "object",
|
||||
"required": ["src_note_id","relation","target_kind"],
|
||||
"properties": {
|
||||
"src_note_id": { "type": "string" },
|
||||
"relation": { "type": "string" },
|
||||
"target_kind": { "type": "string" },
|
||||
"when": { "type": "string" },
|
||||
"strength_hint":{ "type": "number", "minimum": 0, "maximum": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2) Qdrant: Collections & Indizes (v2)
|
||||
Anlegen **neben** v1:
|
||||
- `mindnet_notes_v2` (Payload‑Index: `type, privacy, created, modified, tags, source_path`)
|
||||
- `mindnet_chunks_v2` (Payload‑Index: `note_id, ord, heading_path`)
|
||||
- `mindnet_edges_v2` (Payload‑Index: `src_note_id, dst_note_id, relation, provenance`)
|
||||
|
||||
> Snapshots für Backups/Restore einplanen (Runbook siehe unten).
|
||||
|
||||
---
|
||||
|
||||
## 3) Import‑Pipeline v2 – Module & Flags
|
||||
- **Chunker v2** (`chunking/block_chunker.py`): `target_len=1000`, `overlap=150`, `respect_headings=True`, `min_chunk_len=600`, `max_chunk_len=1400`, `chunk_id = f\"{note_id}#c{ordinal:04d}\"`
|
||||
- **Edge‑Builder v2** (`graph/edge_builder_v2.py`): Reihenfolge **explicit → rule → default_resolved → default**, `provenance` korrekt setzen.
|
||||
- **Importer** (`scripts/import_markdown.py` erweitern oder `scripts/import_markdown_v2.py`):
|
||||
Flags: `--schema v2`, `--chunker v2`, `--edges v2`, `--dry-run`, `--apply`, `--prefix "$COLLECTION_PREFIX"`.
|
||||
|
||||
**Beispiel‑Run (dry‑run):**
|
||||
```bash
|
||||
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --dry-run --prefix "$COLLECTION_PREFIX"
|
||||
```
|
||||
|
||||
**Apply:**
|
||||
```bash
|
||||
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --apply --prefix "$COLLECTION_PREFIX"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4) Policies (konfigurierbar, kein Hard‑Code)
|
||||
- `policies/retrieval.schema.json` (JSON‑Schema) und `policies/retrieval.yaml`, z. B.:
|
||||
```yaml
|
||||
privacy_order: [private, internal, public]
|
||||
recency_boost_half_life_days: 90
|
||||
type_priority:
|
||||
person: 1.2
|
||||
event: 1.1
|
||||
concept: 1.0
|
||||
max_chunks_per_note: 8
|
||||
edge_provenance_weights:
|
||||
explicit: 1.0
|
||||
rule: 0.8
|
||||
default_resolved: 0.6
|
||||
default: 0.2
|
||||
rule_sets:
|
||||
- id: "rules:types-v1"
|
||||
enabled: true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5) Observability & Reports
|
||||
- **FastAPI + OpenTelemetry**: Traces um Phasen *parse/chunk/edge/upsert*; Metriken (Counter/Histogramme) pro Phase.
|
||||
- **Import‑Report** je Lauf (CSV/JSON): counts für Notes/Chunks/Edges, Fehler, Dauer, Embedding‑Version.
|
||||
|
||||
---
|
||||
|
||||
## 6) Teststrategie
|
||||
- **Gold‑Notizen** (3–5 repräsentative .md) mit erwarteten *Chunk‑Counts* und *Edge‑Sets*.
|
||||
- **Regression:** fixer Soll‑Count (z. B. 171 ± 15 %) über Gesamt‑Vault; keine Duplikate `(src,relation,dst)`.
|
||||
- **Dry‑Run vs Apply**: identische Counts, nur ohne Upserts.
|
||||
- **Filter‑Smoke‑Tests:** Qdrant‑Filter nach `privacy`, `type`, `tags`, `created` funktionieren performant.
|
||||
|
||||
---
|
||||
|
||||
## 7) Akzeptanzkriterien (KPI)
|
||||
1. **Chunk‑Qualität:** ≥ 90 % der Chunks enden an semantischen Grenzen; Ziel‑Länge 900–1200 Zeichen; deterministische IDs.
|
||||
2. **Edge‑Kohärenz:** Keine Duplikate gleicher `(src,relation,dst)`; ≥ 95 % der expliziten Links materialisiert; `default` nur, wenn kein Ziel existiert.
|
||||
3. **Filterbarkeit:** Queries nach `privacy/type/tags/created` performant (Payload‑Index vorhanden).
|
||||
4. **Betriebsfestigkeit:** Telemetrie aktiv; fehlertoleranter Import; Qdrant‑Snapshot nach erfolgreichem Lauf.
|
||||
|
||||
---
|
||||
|
||||
## 8) Roadmap in kleinen, testbaren Schritten
|
||||
|
||||
### Step 0 – Safeguards
|
||||
- Qdrant‑Snapshot v1 erstellen + Restore‑Probe.
|
||||
- ENV: `MINDNET_SCHEMA_VERSION=2` (Importer wird v2 schreiben, v1 bleibt unberührt).
|
||||
|
||||
### Step 1 – Schemata (nur Dateien)
|
||||
- Ablage: `/schemas/note.schema.json`, `/schemas/chunk.schema.json`, `/schemas/edge.schema.json`, `/schemas/default_edge.schema.json`
|
||||
- CI‑Job: `make schema-validate` (jsonschema).
|
||||
- **Abnahme:** Validator grün auf 3 Gold‑Notizen.
|
||||
|
||||
### Step 2 – Qdrant v2‑Collections
|
||||
- Anlegen der 3 v2‑Collections + Payload‑Indizes.
|
||||
- **Abnahme:** Filter‑Query liefert erwartbare Ergebnisse.
|
||||
|
||||
### Step 3 – Chunker v2
|
||||
- Implementierung & Flag `--chunker v2`.
|
||||
- **Abnahme:** Chunk‑Counts ~ alt (≈171 ± 15 %), semantische Schnitte.
|
||||
|
||||
### Step 4 – Edge‑Builder v2
|
||||
- Reihenfolge & `provenance` strikt umsetzen, `default_resolved` integrieren.
|
||||
- **Abnahme:** erwartete Relationensätze auf Gold‑Notizen, keine Duplikate.
|
||||
|
||||
### Step 5 – Importer‑Pipeline v2
|
||||
- `--schema v2` Side‑by‑Side; Batch‑Upserts; vollständige Payloads; Recency‑Boost Konfig **nur** in Policy.
|
||||
- **Abnahme:** Dry‑Run/Apply‑Parität, Reports, Telemetrie‑Ereignisse sichtbar.
|
||||
|
||||
### Step 6 – Observability
|
||||
- OTel‑Instrumentierung + `/import/status` + Reports.
|
||||
- **Abnahme:** Traces & Metriken vorhanden.
|
||||
|
||||
### Step 7 – Snapshots & Runbook
|
||||
- Snapshot nach Erfolg; Restore‑Dokument.
|
||||
- **Abnahme:** Restore‑Probe erfolgreich.
|
||||
|
||||
### Step 8 – Policies
|
||||
- `policies/retrieval.yaml` + JSON‑Schema; A/B‑Test (Policy ändern → Retrieval ändert sich ohne Reimport).
|
||||
- **Abnahme:** Sichtbarer Effekt laut Testfall.
|
||||
|
||||
### Step 9 – Umschalten
|
||||
- Abnahme‑Doku, KPI‑Delta dokumentiert; Alias/Flag‑Switch auf v2.
|
||||
- **Abnahme:** Funktionale Gleichwertigkeit + Qualitätsgewinn.
|
||||
|
||||
---
|
||||
|
||||
## 9) Dateien (neu/ändern)
|
||||
**Neu:**
|
||||
- `schemas/note.schema.json`
|
||||
- `schemas/chunk.schema.json`
|
||||
- `schemas/edge.schema.json`
|
||||
- `schemas/default_edge.schema.json`
|
||||
- `policies/retrieval.schema.json`
|
||||
- `policies/retrieval.yaml`
|
||||
- `chunking/block_chunker.py`
|
||||
- `graph/edge_builder_v2.py`
|
||||
- `docs/OPERATIONS.md` (Snapshots/Restore/Runbook)
|
||||
- `tests/gold_notes/manifest.yaml` (+ 3–5 Notizen Kopien)
|
||||
|
||||
**Änderungen:**
|
||||
- `scripts/import_markdown.py` **oder** `scripts/import_markdown_v2.py` neu (Flags `--schema/--chunker/--edges`).
|
||||
- `edges.py` (falls weiterverwendet): auf **v2‑Edge‑Builder** migrieren oder auslaufen lassen.
|
||||
- `types.yaml`: Regel‑Definitionen klarisieren (IDs, Bedingungen), **nicht** hart in Code.
|
||||
|
||||
---
|
||||
|
||||
## 10) Beispiel‑Kommandos
|
||||
```bash
|
||||
# Step 2: Collections prüfen
|
||||
curl -s http://127.0.0.1:6333/collections | jq
|
||||
|
||||
# Step 3: Chunker v2 (dry-run)
|
||||
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --dry-run --prefix "$COLLECTION_PREFIX"
|
||||
|
||||
# Step 5: Apply + Report
|
||||
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --apply --prefix "$COLLECTION_PREFIX" --report ./reports/import_$(date +%F_%H%M).json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11) Rollback
|
||||
- v2‑Collections droppen (wenn Side‑by‑Side).
|
||||
- Aus Snapshot wiederherstellen (v1).
|
||||
- Flags zurück auf v1.
|
||||
|
||||
---
|
||||
|
||||
## 12) Referenzen (offizielle Quellen)
|
||||
- Qdrant – Collections, Payload‑Index, Filter: <https://qdrant.tech/documentation/>
|
||||
- Qdrant – Snapshots/Backup: <https://qdrant.tech/documentation/guides/backup/>
|
||||
- OpenTelemetry (Python/FastAPI): <https://opentelemetry.io/docs/instrumentation/python/>
|
||||
- JSON‑Schema 2020‑12: <https://json-schema.org/>
|
||||
- YAML 1.2: <https://yaml.org/spec/1.2.2/>
|
||||
- Obsidian Frontmatter: <https://help.obsidian.md/Editing+and+formatting/Properties>
|
||||
- Ollama CLI/API (lokale Modelle): <https://github.com/ollama/ollama>
|
||||
|
||||
---
|
||||
|
||||
## 13) **PROMPT für den neuen Chat (bitte exakt so einfügen)**
|
||||
```
|
||||
Rolle: Du bist mein Senior‑Entwickler & Architekt für mindnet. Arbeite strikt in kleinen, testbaren Schritten (Side‑by‑Side v2 neben v1). Liefere komplette Dateien als Downloads. Frage immer zuerst nach den **aktuellsten** Projektdateien, wenn du sie brauchst (z. B. import_markdown.py, edges.py, types.yaml), ändere keine Systemfunktion „workaround‑artig“ ohne die Gesamtwirkung zu prüfen.
|
||||
|
||||
Kontext (Kurzfassung):
|
||||
- v1 hat nur mindnet_notes zuverlässig. Chunks/Edges sind inkonsistent/teilweise leer. Ziel: v2 mit drei Collections (notes/chunks/edges), neuem Chunker v2, Edge‑Builder v2 (explicit → rule → default_resolved → default), Policies (YAML), Observability (OTel), Snapshots. Kein Big‑Bang; v2 parallel zu v1.
|
||||
- Siehe angehängte Datei **mindnet_v2_implementation_playbook.md** (Pfad/Download im Chat). Alles daraus ist verbindlich.
|
||||
|
||||
Deine ersten Aufgaben (Step‑by‑Step):
|
||||
1) **Schemata anlegen (Step 1)**
|
||||
- Erstelle die Dateien:
|
||||
- schemas/note.schema.json
|
||||
- schemas/chunk.schema.json
|
||||
- schemas/edge.schema.json
|
||||
- schemas/default_edge.schema.json
|
||||
- Nutze die in der Playbook‑Datei vorgegebenen Strukturen als Basis.
|
||||
- Liefere zusätzlich ein einfaches `Makefile`‑Ziel `schema-validate` (jsonschema via Python), plus `requirements.txt`.
|
||||
- Output: komplette Dateien als Downloads + kurze Testanleitung.
|
||||
|
||||
2) **Qdrant v2‑Collections (Step 2)**
|
||||
- Erzeuge die Collections + Payload‑Indizes.
|
||||
- Liefere ein kleines Python‑Skript `tools/qdrant_bootstrap_v2.py`, das diese Anlage idempotent durchführt (inkl. Prüf‑Output).
|
||||
|
||||
3) **Chunker v2 (Step 3)**
|
||||
- Implementiere `chunking/block_chunker.py` mit den im Playbook genannten Parametern.
|
||||
- Teste gegen 3 Gold‑Notizen (liefere mini Test‑Harness in `tests/gold_notes/…`).
|
||||
|
||||
Arbeitsweise:
|
||||
- Jede Aufgabe einzeln, mit klaren Akzeptanzkriterien (aus Playbook) und Download‑Artefakten.
|
||||
- Keine parallelen Großumbauten.
|
||||
- Immer deterministische IDs, idempotente Upserts.
|
||||
|
||||
Dateien, die ich dir anfänglich bereitstelle:
|
||||
- **mindnet_v2_implementation_playbook.md** (diese Datei)
|
||||
- **import_markdown.py** (aktuelle Version aus dem Projekt)
|
||||
- **edges.py** (aktuelle Version aus dem Projekt)
|
||||
- **types.yaml** (aktuelle Version)
|
||||
|
||||
Sage mir jeweils, welche Datei du als Nächstes brauchst. Beginne jetzt mit Aufgabe 1 (Schemata).
|
||||
```
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests/assert_payload_schema.py (compat v1.1)
|
||||
|
||||
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).
|
||||
|
||||
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
|
||||
|
||||
Nutzung:
|
||||
python3 -m tests.assert_payload_schema
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
REQUIRED = {
|
||||
"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"],
|
||||
}
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
if hasattr(obj, "model_dump"):
|
||||
return obj.model_dump()
|
||||
if hasattr(obj, "dict"):
|
||||
return obj.dict()
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
|
||||
def _cfg_base_url(cfg) -> str:
|
||||
if getattr(cfg, "url", None):
|
||||
return cfg.url.rstrip('/')
|
||||
host = getattr(cfg, "host", None) or os.getenv("QDRANT_HOST") or "127.0.0.1"
|
||||
port = getattr(cfg, "port", None) or os.getenv("QDRANT_PORT") or "6333"
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
def _http_get(url: str, api_key: str | None) -> Dict[str, Any]:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
if api_key:
|
||||
req.add_header("api-key", api_key)
|
||||
req.add_header("Authorization", f"Bearer {api_key}")
|
||||
req.add_header("Accept", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
def get_collection_payload_schema(client, cfg, name: str) -> Dict[str, Any] | None:
|
||||
# 1) OpenAPI client mit Flag
|
||||
try:
|
||||
oc = getattr(client, "openapi_client", None)
|
||||
if oc is not None and hasattr(oc, "collections_api"):
|
||||
api = oc.collections_api
|
||||
info = api.get_collection(collection_name=name, with_payload_schema=True)
|
||||
d = _safe_model_dump(info)
|
||||
return (d.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
pass
|
||||
# 2) Wrapper (manche Versionen liefern Schema auch ohne Flag)
|
||||
try:
|
||||
info = client.get_collection(collection_name=name)
|
||||
d = _safe_model_dump(info)
|
||||
ps = (d.get("result") or {}).get("payload_schema")
|
||||
if ps is not None:
|
||||
return ps
|
||||
except Exception:
|
||||
pass
|
||||
# 3) Direkter HTTP-Call
|
||||
try:
|
||||
base = _cfg_base_url(cfg)
|
||||
url = f"{base}/collections/{name}?with_payload_schema=true"
|
||||
raw = _http_get(url, getattr(cfg, "api_key", None))
|
||||
return (raw.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def ensure_fields(schema: Dict[str, dict] | None, required: List[str]) -> Dict[str, bool]:
|
||||
ks = set((schema or {}).keys())
|
||||
return {k: (k in ks) for k in required}
|
||||
|
||||
def main():
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
notes, chunks, edges = collection_names(cfg.prefix)
|
||||
names = {"notes": notes, "chunks": chunks, "edges": edges}
|
||||
|
||||
report = {}
|
||||
ok_all = True
|
||||
for kind, col in names.items():
|
||||
sch = get_collection_payload_schema(client, cfg, col)
|
||||
checks = ensure_fields(sch, REQUIRED[kind])
|
||||
ok = all(checks.values())
|
||||
ok_all = ok_all and ok
|
||||
report[kind] = {
|
||||
"collection": col,
|
||||
"ok": ok,
|
||||
"missing": [k for k,v in checks.items() if not v],
|
||||
"present": [k for k,v in checks.items() if v],
|
||||
}
|
||||
|
||||
print(json.dumps({"prefix": cfg.prefix, "ok": ok_all, "report": report}, ensure_ascii=False, indent=2))
|
||||
if not ok_all:
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/diag_payload_indexes.py (compat v1.2)
|
||||
|
||||
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
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
if hasattr(obj, "model_dump"):
|
||||
return obj.model_dump()
|
||||
if hasattr(obj, "dict"):
|
||||
return obj.dict()
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
|
||||
|
||||
def _cfg_base_url(cfg) -> str:
|
||||
if getattr(cfg, "url", None):
|
||||
return cfg.url.rstrip("/")
|
||||
host = getattr(cfg, "host", None) or os.getenv("QDRANT_HOST") or "127.0.0.1"
|
||||
port = getattr(cfg, "port", None) or os.getenv("QDRANT_PORT") or "6333"
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
|
||||
def _http_get(url: str, api_key: str | None) -> Dict[str, Any]:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
if api_key:
|
||||
req.add_header("api-key", api_key)
|
||||
req.add_header("Authorization", f"Bearer {api_key}")
|
||||
req.add_header("Accept", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
|
||||
def get_collection_payload_schema(client, cfg, name: str) -> Dict[str, Any] | None:
|
||||
# Strategy 1: OpenAPI client with flag
|
||||
try:
|
||||
oc = getattr(client, "openapi_client", None)
|
||||
if oc is not None and hasattr(oc, "collections_api"):
|
||||
api = oc.collections_api
|
||||
info = api.get_collection(collection_name=name, with_payload_schema=True)
|
||||
d = _safe_model_dump(info)
|
||||
return (d.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
pass
|
||||
# Strategy 2: wrapper (manche Versionen liefern Schema auch ohne Flag)
|
||||
try:
|
||||
info = client.get_collection(collection_name=name) # kein with_payload_schema kwarg!
|
||||
d = _safe_model_dump(info)
|
||||
ps = (d.get("result") or {}).get("payload_schema")
|
||||
if ps is not None:
|
||||
return ps
|
||||
except Exception:
|
||||
pass
|
||||
# Strategy 3: direkter HTTP Call
|
||||
try:
|
||||
base = _cfg_base_url(cfg)
|
||||
url = f"{base}/collections/{name}?with_payload_schema=true"
|
||||
raw = _http_get(url, getattr(cfg, "api_key", None))
|
||||
return (raw.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
notes, chunks, edges = collection_names(cfg.prefix)
|
||||
cols = [notes, chunks, edges]
|
||||
out = []
|
||||
for name in cols:
|
||||
ps = get_collection_payload_schema(client, cfg, name)
|
||||
# Vektorinfos (optional)
|
||||
try:
|
||||
info = client.get_collection(collection_name=name)
|
||||
d = _safe_model_dump(info)
|
||||
vectors = (d.get("result") or {}).get("vectors")
|
||||
if isinstance(vectors, dict) and "config" in vectors:
|
||||
vectors = vectors["config"]
|
||||
except Exception:
|
||||
vectors = None
|
||||
out.append({"name": name, "vectors": vectors, "payload_schema": ps})
|
||||
print(json.dumps({"prefix": cfg.prefix, "collections": out}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/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
|
||||
|
||||
Aufruf:
|
||||
python3 -m scripts.edges_dryrun --vault ./vault
|
||||
|
||||
Optional:
|
||||
--include-note-scope-refs # auch Frontmatter-Links (links[].target_id) als Note-Scope-Referenzen
|
||||
|
||||
Voraussetzungen:
|
||||
- app/core/parser.py (read_markdown, normalize_frontmatter)
|
||||
- app/core/edges.py (dieses Modul forwardet zur v2-Implementierung)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
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
|
||||
|
||||
def _iter_markdown(vault: str):
|
||||
for p in Path(vault).rglob("*.md"):
|
||||
if p.name.startswith("."): # ignore hidden
|
||||
continue
|
||||
yield p
|
||||
|
||||
def _simple_chunker(body: str, note_id: str, note_type: str) -> List[Dict]:
|
||||
# Absatzbasiert, minimal ausreichend für Edges (window/text, chunk_id, ord, note_id, type)
|
||||
paras = [s.strip() for s in re.split(r"\n{2,}", body or "") if s.strip()]
|
||||
chunks = []
|
||||
for i, t in enumerate(paras):
|
||||
chunks.append({
|
||||
"chunk_id": f"{note_id}#c{i:04d}",
|
||||
"ord": i,
|
||||
"text": t,
|
||||
"note_id": note_id,
|
||||
"type": note_type,
|
||||
})
|
||||
return chunks
|
||||
|
||||
def _fm_note_refs(fm: Dict) -> List[str]:
|
||||
out = []
|
||||
links = fm.get("links") or []
|
||||
if isinstance(links, list):
|
||||
for e in links:
|
||||
if isinstance(e, dict):
|
||||
tid = e.get("target_id")
|
||||
if isinstance(tid, str) and tid.strip():
|
||||
out.append(tid.strip())
|
||||
return out
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--vault", required=True)
|
||||
ap.add_argument("--include-note-scope-refs", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
vault = args.vault
|
||||
include_note_scope = args.include_note_scope_refs
|
||||
|
||||
report = []
|
||||
for p in _iter_markdown(vault):
|
||||
parsed = read_markdown(str(p))
|
||||
if not parsed:
|
||||
continue
|
||||
fm = normalize_frontmatter(parsed.frontmatter or {})
|
||||
note_id = fm.get("id") or p.stem
|
||||
note_type = (fm.get("type") or "concept").lower()
|
||||
chunks = _simple_chunker(parsed.body, note_id, note_type)
|
||||
note_refs = _fm_note_refs(fm)
|
||||
|
||||
edges = build_edges_for_note(
|
||||
note_id=note_id,
|
||||
chunk_payloads=chunks,
|
||||
note_level_refs=note_refs,
|
||||
include_note_scope_refs=include_note_scope,
|
||||
)
|
||||
kinds = {}
|
||||
for e in edges:
|
||||
key = (e.get("relation") or e.get("kind") or "edge")
|
||||
kinds[key] = kinds.get(key, 0) + 1
|
||||
report.append({
|
||||
"path": str(p),
|
||||
"note_id": note_id,
|
||||
"type": note_type,
|
||||
"chunks": len(chunks),
|
||||
"edges_total": len(edges),
|
||||
"edges_by_kind": kinds,
|
||||
"samples": edges[:3],
|
||||
})
|
||||
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -124,7 +124,7 @@ def load_type_registry() -> dict:
|
||||
p = _env("MINDNET_TYPES_FILE", None)
|
||||
if p and os.path.exists(p):
|
||||
return _load_json_or_yaml(p)
|
||||
fallback = os.path.abspath("./types.yaml")
|
||||
fallback = os.path.abspath("./config/types.yaml") if os.path.exists("./config/types.yaml") else os.path.abspath("./types.yaml")
|
||||
return _load_json_or_yaml(fallback)
|
||||
|
||||
def get_type_config(note_type: Optional[str], reg: dict) -> dict:
|
||||
@@ -144,19 +144,43 @@ def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
||||
return "concept" if "concept" in types else (requested or "concept")
|
||||
|
||||
def effective_chunk_profile(note_type: str, reg: dict) -> Optional[str]:
|
||||
"""Resolve chunk_profile for type or from defaults/global.
|
||||
Accepts symbolic profiles: short|medium|long|default.
|
||||
"""
|
||||
cfg = get_type_config(note_type, reg)
|
||||
prof = cfg.get("chunk_profile")
|
||||
if isinstance(prof, str) and prof in {"short", "medium", "long"}:
|
||||
prof = (cfg.get("chunk_profile") if isinstance(cfg, dict) else None)
|
||||
if isinstance(prof, str) and prof:
|
||||
return prof
|
||||
return None
|
||||
# defaults fallbacks
|
||||
for key in ("defaults", "default", "global"):
|
||||
dcfg = reg.get(key) if isinstance(reg, dict) else None
|
||||
if isinstance(dcfg, dict):
|
||||
dprof = dcfg.get("chunk_profile")
|
||||
if isinstance(dprof, str) and dprof:
|
||||
return dprof
|
||||
return "default"
|
||||
|
||||
def effective_retriever_weight(note_type: str, reg: dict) -> Optional[float]:
|
||||
"""Resolve retriever_weight for type or defaults; returns float.
|
||||
"""
|
||||
cfg = get_type_config(note_type, reg)
|
||||
w = cfg.get("retriever_weight")
|
||||
w = (cfg.get("retriever_weight") if isinstance(cfg, dict) else None)
|
||||
try:
|
||||
return float(w) if w is not None else None
|
||||
if w is not None:
|
||||
return float(w)
|
||||
except Exception:
|
||||
return None
|
||||
pass
|
||||
# defaults fallbacks
|
||||
for key in ("defaults", "default", "global"):
|
||||
dcfg = reg.get(key) if isinstance(reg, dict) else None
|
||||
if isinstance(dcfg, dict):
|
||||
dw = dcfg.get("retriever_weight")
|
||||
try:
|
||||
if dw is not None:
|
||||
return float(dw)
|
||||
except Exception:
|
||||
pass
|
||||
return 1.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/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)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os, json
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
||||
from app.core.note_payload import make_note_payload
|
||||
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
|
||||
except Exception:
|
||||
from app.core.edges import build_edges_for_note # type: ignore
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--vault", required=True)
|
||||
ap.add_argument("--note-id")
|
||||
ap.add_argument("--with-edges", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
root = os.path.abspath(args.vault)
|
||||
|
||||
files: List[str] = []
|
||||
for dp, _, fns in os.walk(root):
|
||||
for fn in fns:
|
||||
if fn.lower().endswith(".md"):
|
||||
files.append(os.path.join(dp, fn))
|
||||
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
|
||||
|
||||
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))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+33
-10
@@ -2,28 +2,33 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: scripts/reset_qdrant.py
|
||||
Version: v1.1.1 (2025-09-05)
|
||||
Version: v1.2.0 (2025-11-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 beiden Aktionen ausgeführt wird:
|
||||
Abfrage), bevor eine der Aktionen ausgeführt wird:
|
||||
|
||||
- wipe: Löscht die Collections komplett und legt sie gemäß Projekt-Defaults neu an
|
||||
- truncate: Löscht nur alle Points (Inhalte), behält die Collection-Settings
|
||||
- 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.
|
||||
|
||||
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]
|
||||
|
||||
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
|
||||
--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)
|
||||
|
||||
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.)
|
||||
|
||||
Sicherheitsmerkmale:
|
||||
- Betrachtet ausschließlich Collections des angegebenen Präfixes.
|
||||
@@ -34,6 +39,8 @@ Exitcodes:
|
||||
0 = OK, 1 = abgebrochen/keine Aktion, 2 = Verbindungs-/Konfigurationsfehler
|
||||
|
||||
Changelog:
|
||||
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.
|
||||
"""
|
||||
@@ -46,7 +53,13 @@ from typing import List
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.http import models as rest
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, collection_names
|
||||
from app.core.qdrant import (
|
||||
QdrantConfig,
|
||||
get_client,
|
||||
ensure_collections,
|
||||
ensure_payload_indexes,
|
||||
collection_names,
|
||||
)
|
||||
|
||||
|
||||
def resolve_existing_collections(client: QdrantClient, prefix: str) -> List[str]:
|
||||
@@ -111,12 +124,13 @@ def wipe_collections(client: QdrantClient, all_col_names: List[str], existing: L
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Wipe oder truncate mindnet-Collections in Qdrant (mit Bestätigung).")
|
||||
ap = argparse.ArgumentParser(description="Wipe oder truncate mindnet-Collections in Qdrant (mit Bestätigung & Index-Setup).")
|
||||
ap.add_argument("--mode", choices=["wipe", "truncate"], required=True,
|
||||
help="wipe = Collections löschen & neu anlegen; truncate = nur Inhalte löschen")
|
||||
ap.add_argument("--prefix", help="Collection-Prefix (Default: env COLLECTION_PREFIX oder 'mindnet')")
|
||||
ap.add_argument("--yes", action="store_true", help="Ohne Rückfrage ausführen (CI/CD)")
|
||||
ap.add_argument("--dry-run", action="store_true", help="Nur anzeigen, was passieren würde; nichts ändern")
|
||||
ap.add_argument("--no-indexes", action="store_true", help="Überspringt ensure_payload_indexes()")
|
||||
args = ap.parse_args()
|
||||
|
||||
# Qdrant-Konfiguration
|
||||
@@ -155,13 +169,22 @@ def main():
|
||||
if args.mode == "wipe":
|
||||
wipe_collections(client, all_col_names, existing)
|
||||
ensure_collections(client, cfg.prefix, cfg.dim)
|
||||
if not args.no_indexes:
|
||||
ensure_payload_indexes(client, cfg.prefix)
|
||||
print(f"Wiped & recreated (Prefix={cfg.prefix}): {all_col_names}")
|
||||
if not args.no_indexes:
|
||||
print("Payload-Indizes & Schema-Ergänzungen geprüft/ergänzt (ensure_payload_indexes).")
|
||||
else:
|
||||
if not existing:
|
||||
print("Keine existierenden Collections zum Truncaten gefunden. Beende ohne Aktion.")
|
||||
sys.exit(0)
|
||||
delete_all_points(client, existing)
|
||||
if not args.no_indexes:
|
||||
# Auch nach truncate sicherstellen, dass neue/fehlende Indizes ergänzt werden
|
||||
ensure_payload_indexes(client, cfg.prefix)
|
||||
print(f"Truncated (deleted all points in): {existing}")
|
||||
if not args.no_indexes:
|
||||
print("Payload-Indizes & Schema-Ergänzungen geprüft/ergänzt (ensure_payload_indexes).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests/assert_payload_schema.py (compat v1.1)
|
||||
|
||||
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).
|
||||
|
||||
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
|
||||
|
||||
Nutzung:
|
||||
python3 -m tests.assert_payload_schema
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, collection_names
|
||||
|
||||
REQUIRED = {
|
||||
"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"],
|
||||
}
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
if hasattr(obj, "model_dump"):
|
||||
return obj.model_dump()
|
||||
if hasattr(obj, "dict"):
|
||||
return obj.dict()
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
|
||||
def _cfg_base_url(cfg) -> str:
|
||||
if getattr(cfg, "url", None):
|
||||
return cfg.url.rstrip('/')
|
||||
host = getattr(cfg, "host", None) or os.getenv("QDRANT_HOST") or "127.0.0.1"
|
||||
port = getattr(cfg, "port", None) or os.getenv("QDRANT_PORT") or "6333"
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
def _http_get(url: str, api_key: str | None) -> Dict[str, Any]:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
if api_key:
|
||||
req.add_header("api-key", api_key)
|
||||
req.add_header("Authorization", f"Bearer {api_key}")
|
||||
req.add_header("Accept", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
def get_collection_payload_schema(client, cfg, name: str) -> Dict[str, Any] | None:
|
||||
# 1) OpenAPI client mit Flag
|
||||
try:
|
||||
oc = getattr(client, "openapi_client", None)
|
||||
if oc is not None and hasattr(oc, "collections_api"):
|
||||
api = oc.collections_api
|
||||
info = api.get_collection(collection_name=name, with_payload_schema=True)
|
||||
d = _safe_model_dump(info)
|
||||
return (d.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
pass
|
||||
# 2) Wrapper (manche Versionen liefern Schema auch ohne Flag)
|
||||
try:
|
||||
info = client.get_collection(collection_name=name)
|
||||
d = _safe_model_dump(info)
|
||||
ps = (d.get("result") or {}).get("payload_schema")
|
||||
if ps is not None:
|
||||
return ps
|
||||
except Exception:
|
||||
pass
|
||||
# 3) Direkter HTTP-Call
|
||||
try:
|
||||
base = _cfg_base_url(cfg)
|
||||
url = f"{base}/collections/{name}?with_payload_schema=true"
|
||||
raw = _http_get(url, getattr(cfg, "api_key", None))
|
||||
return (raw.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def ensure_fields(schema: Dict[str, dict] | None, required: List[str]) -> Dict[str, bool]:
|
||||
ks = set((schema or {}).keys())
|
||||
return {k: (k in ks) for k in required}
|
||||
|
||||
def main():
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
notes, chunks, edges = collection_names(cfg.prefix)
|
||||
names = {"notes": notes, "chunks": chunks, "edges": edges}
|
||||
|
||||
report = {}
|
||||
ok_all = True
|
||||
for kind, col in names.items():
|
||||
sch = get_collection_payload_schema(client, cfg, col)
|
||||
checks = ensure_fields(sch, REQUIRED[kind])
|
||||
ok = all(checks.values())
|
||||
ok_all = ok_all and ok
|
||||
report[kind] = {
|
||||
"collection": col,
|
||||
"ok": ok,
|
||||
"missing": [k for k,v in checks.items() if not v],
|
||||
"present": [k for k,v in checks.items() if v],
|
||||
}
|
||||
|
||||
print(json.dumps({"prefix": cfg.prefix, "ok": ok_all, "report": report}, ensure_ascii=False, indent=2))
|
||||
if not ok_all:
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/diag_payload_indexes.py (v1.1)
|
||||
|
||||
Zeigt payload_schema (Indizes) je Collection.
|
||||
WICHTIG: Einige Qdrant-Versionen liefern payload_schema nur, wenn
|
||||
`with_payload_schema=true` gesetzt wird. Daher setzen wir das Flag explizit.
|
||||
"""
|
||||
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
|
||||
|
||||
def compact_schema(ps: dict | None) -> dict:
|
||||
if not isinstance(ps, dict):
|
||||
return {}
|
||||
out = {}
|
||||
for k, v in ps.items():
|
||||
if isinstance(v, dict) and "type" in v:
|
||||
out[k] = v["type"]
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--raw", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
notes, chunks, edges = collection_names(cfg.prefix)
|
||||
|
||||
cols = [notes, chunks, edges]
|
||||
result = []
|
||||
for name in cols:
|
||||
info = client.get_collection(collection_name=name, with_payload_schema=True)
|
||||
d = info.model_dump() if hasattr(info, "model_dump") else (info.dict() if hasattr(info, "dict") else info)
|
||||
payload_schema = (d.get("result") or {}).get("payload_schema")
|
||||
vectors = (d.get("result") or {}).get("vectors")
|
||||
if isinstance(vectors, dict) and "config" in vectors:
|
||||
vectors = vectors.get("config")
|
||||
if args.raw:
|
||||
result.append({"collection": name, "raw": d})
|
||||
else:
|
||||
result.append({
|
||||
"name": name,
|
||||
"vectors": vectors,
|
||||
"payload_schema": compact_schema(payload_schema),
|
||||
"segments_count": (d.get("result") or {}).get("segments_count"),
|
||||
})
|
||||
print(json.dumps({"prefix": cfg.prefix, "collections": result}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests/ensure_indexes_and_show.py (compat v1.0.1)
|
||||
|
||||
Erzwingt ensure_payload_indexes(...) und zeigt danach payload_schema je Collection.
|
||||
Kompatibel mit qdrant-client Versionen ohne 'with_payload_schema' im Wrapper.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.core.qdrant import QdrantConfig, get_client, ensure_payload_indexes, collection_names
|
||||
|
||||
|
||||
def _safe_model_dump(obj: Any) -> Dict[str, Any]:
|
||||
if hasattr(obj, "model_dump"):
|
||||
return obj.model_dump()
|
||||
if hasattr(obj, "dict"):
|
||||
return obj.dict()
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
|
||||
|
||||
def _cfg_base_url(cfg) -> str:
|
||||
if getattr(cfg, "url", None):
|
||||
return cfg.url.rstrip("/")
|
||||
host = getattr(cfg, "host", None) or os.getenv("QDRANT_HOST") or "127.0.0.1"
|
||||
port = getattr(cfg, "port", None) or os.getenv("QDRANT_PORT") or "6333"
|
||||
return f"http://{host}:{port}"
|
||||
|
||||
|
||||
def _http_get(url: str, api_key: str | None) -> Dict[str, Any]:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
if api_key:
|
||||
req.add_header("api-key", api_key)
|
||||
req.add_header("Authorization", f"Bearer {api_key}")
|
||||
req.add_header("Accept", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
|
||||
def get_collection_payload_schema(client, cfg, name: str) -> Dict[str, Any] | None:
|
||||
# Strategy 1: OpenAPI client with flag
|
||||
try:
|
||||
oc = getattr(client, "openapi_client", None)
|
||||
if oc is not None and hasattr(oc, "collections_api"):
|
||||
api = oc.collections_api
|
||||
info = api.get_collection(collection_name=name, with_payload_schema=True)
|
||||
d = _safe_model_dump(info)
|
||||
return (d.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
pass
|
||||
# Strategy 2: wrapper
|
||||
try:
|
||||
info = client.get_collection(collection_name=name)
|
||||
d = _safe_model_dump(info)
|
||||
ps = (d.get("result") or {}).get("payload_schema")
|
||||
if ps is not None:
|
||||
return ps
|
||||
except Exception:
|
||||
pass
|
||||
# Strategy 3: direct HTTP
|
||||
try:
|
||||
base = _cfg_base_url(cfg)
|
||||
url = f"{base}/collections/{name}?with_payload_schema=true"
|
||||
raw = _http_get(url, getattr(cfg, "api_key", None))
|
||||
return (raw.get("result") or {}).get("payload_schema")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
ensure_payload_indexes(client, cfg.prefix)
|
||||
notes, chunks, edges = collection_names(cfg.prefix)
|
||||
res = {}
|
||||
for name in (notes, chunks, edges):
|
||||
res[name] = get_collection_payload_schema(client, cfg, name)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/show_edges_for_note.py
|
||||
|
||||
Zeigt Kanten einer Note (gefiltert nach kind/scope) in einer kompakten Form.
|
||||
Aufrufbeispiele:
|
||||
python3 -m scripts.show_edges_for_note --note-id 20251110-ollama-llm-9f0a12 --kinds references,next,prev --limit 10
|
||||
python3 -m scripts.show_edges_for_note --title "Qdrant Vektordatenbank" --scope note
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
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
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
def find_note_by_title(client, prefix: str, title: str) -> str | None:
|
||||
notes_col, _, _ = collections(prefix)
|
||||
f = rest.Filter(must=[rest.FieldCondition(key="title", match=rest.MatchText(text=title))])
|
||||
pts, _ = client.scroll(collection_name=notes_col, scroll_filter=f, with_payload=True, with_vectors=False, limit=1)
|
||||
if not pts:
|
||||
return None
|
||||
return pts[0].payload.get("note_id")
|
||||
|
||||
def fetch_edges_for_note(client, prefix: str, note_id: str, kinds: List[str] | None, scope: str | None, limit: int) -> List[Dict[str, Any]]:
|
||||
_, _, edges_col = collections(prefix)
|
||||
must = [rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))]
|
||||
if scope:
|
||||
must.append(rest.FieldCondition(key="scope", match=rest.MatchValue(value=scope)))
|
||||
if kinds:
|
||||
must.append(rest.FieldCondition(key="kind", match=rest.MatchAny(any=kinds)))
|
||||
f = rest.Filter(must=must)
|
||||
pts, _ = client.scroll(collection_name=edges_col, scroll_filter=f, with_payload=True, with_vectors=False, limit=limit)
|
||||
return [p.payload for p in pts]
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--note-id")
|
||||
ap.add_argument("--title")
|
||||
ap.add_argument("--kinds", help="CSV: references,next,prev,belongs_to,backlink")
|
||||
ap.add_argument("--scope", choices=["note","chunk"])
|
||||
ap.add_argument("--limit", type=int, default=25)
|
||||
args = ap.parse_args()
|
||||
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
|
||||
nid = args.note_id
|
||||
if not nid and args.title:
|
||||
nid = find_note_by_title(client, cfg.prefix, args.title)
|
||||
if not nid:
|
||||
print(json.dumps({"error": f"note with title '{args.title}' not found"}))
|
||||
sys.exit(2)
|
||||
if not nid:
|
||||
print(json.dumps({"error": "please provide --note-id or --title"}))
|
||||
sys.exit(2)
|
||||
|
||||
kinds = None
|
||||
if args.kinds:
|
||||
kinds = [s.strip() for s in args.kinds.split(",") if s.strip()]
|
||||
|
||||
edges = fetch_edges_for_note(client, cfg.prefix, nid, kinds, args.scope, args.limit)
|
||||
print(json.dumps({"note_id": nid, "count": len(edges), "edges": edges}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/test_edges_smoke.py — Progressive Ausgabe
|
||||
|
||||
Prüft edge-Integrität je Note mit Live-Ausgabe:
|
||||
- belongs_to == #Chunks
|
||||
- next == prev == max(#Chunks-1,0)
|
||||
- Duplikat-Edges (Key: (kind,source_id,target_id,scope)) == 0
|
||||
- Zählt references (chunk/note), backlink
|
||||
|
||||
Optionen:
|
||||
--max-notes N : prüft nur die ersten N Notizen
|
||||
--limit L : Scroll-Limit pro Anfrage (Default 256)
|
||||
--flush : jede Zeile sofort flushen
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import os, sys, json, argparse
|
||||
from typing import Dict, Any, List, Tuple, Set
|
||||
from qdrant_client.http import models as rest
|
||||
from app.core.qdrant import QdrantConfig, get_client
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
def scroll_iter(client, collection: str, filt: rest.Filter | None, with_payload: bool, limit: int):
|
||||
next_page = None
|
||||
while True:
|
||||
pts, next_page = client.scroll(
|
||||
collection_name=collection,
|
||||
scroll_filter=filt,
|
||||
with_payload=with_payload,
|
||||
with_vectors=False,
|
||||
limit=limit,
|
||||
offset=next_page,
|
||||
)
|
||||
if not pts:
|
||||
break
|
||||
for p in pts:
|
||||
yield p
|
||||
if next_page is None:
|
||||
break
|
||||
|
||||
def list_notes(client, prefix: str, limit: int, max_notes: int | None) -> List[Dict[str, Any]]:
|
||||
notes_col, _, _ = collections(prefix)
|
||||
out: List[Dict[str, Any]] = []
|
||||
for p in scroll_iter(client, notes_col, None, True, limit):
|
||||
pl = p.payload or {}
|
||||
nid = pl.get("note_id") or pl.get("id")
|
||||
if nid:
|
||||
out.append({"note_id": nid, "title": pl.get("title"), "type": pl.get("type")})
|
||||
if max_notes is not None and len(out) >= max_notes:
|
||||
break
|
||||
return out
|
||||
|
||||
def count_chunks_for_note(client, prefix: str, note_id: str, limit: int) -> int:
|
||||
_, chunks_col, _ = collections(prefix)
|
||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||
return sum(1 for _ in scroll_iter(client, chunks_col, f, False, limit))
|
||||
|
||||
def fetch_edges_for_note(client, prefix: str, note_id: str, limit: int) -> List[Dict[str, Any]]:
|
||||
_, _, edges_col = collections(prefix)
|
||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||
return [p.payload or {} for p in scroll_iter(client, edges_col, f, True, limit)]
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--max-notes", type=int)
|
||||
ap.add_argument("--limit", type=int, default=256)
|
||||
ap.add_argument("--flush", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
|
||||
notes = list_notes(client, cfg.prefix, args.limit, args.max_notes)
|
||||
total = {"notes": 0, "chunks": 0, "belongs_to": 0, "next": 0, "prev": 0, "refs_chunk": 0, "refs_note": 0, "backlink": 0, "dup_edges": 0}
|
||||
|
||||
for n in notes:
|
||||
nid = n["note_id"]
|
||||
total["notes"] += 1
|
||||
chunk_count = count_chunks_for_note(client, cfg.prefix, nid, args.limit)
|
||||
total["chunks"] += chunk_count
|
||||
|
||||
edges = fetch_edges_for_note(client, cfg.prefix, nid, args.limit)
|
||||
by_kind = {}
|
||||
keys: Set[tuple] = set()
|
||||
dup_count = 0
|
||||
refs_chunk = 0
|
||||
refs_note = 0
|
||||
backlink = 0
|
||||
|
||||
for e in edges:
|
||||
k = e.get("kind")
|
||||
by_kind[k] = by_kind.get(k, 0) + 1
|
||||
t = (e.get("kind"), e.get("source_id"), e.get("target_id"), e.get("scope"))
|
||||
if t in keys:
|
||||
dup_count += 1
|
||||
else:
|
||||
keys.add(t)
|
||||
if k == "references" and e.get("scope") == "chunk":
|
||||
refs_chunk += 1
|
||||
if k == "references" and e.get("scope") == "note":
|
||||
refs_note += 1
|
||||
if k == "backlink":
|
||||
backlink += 1
|
||||
|
||||
total["belongs_to"] += by_kind.get("belongs_to", 0)
|
||||
total["next"] += by_kind.get("next", 0)
|
||||
total["prev"] += by_kind.get("prev", 0)
|
||||
total["refs_chunk"] += refs_chunk
|
||||
total["refs_note"] += refs_note
|
||||
total["backlink"] += backlink
|
||||
total["dup_edges"] += dup_count
|
||||
|
||||
ok_bt = (by_kind.get("belongs_to", 0) == chunk_count)
|
||||
ok_seq = (by_kind.get("next", 0) == max(chunk_count - 1, 0) and by_kind.get("prev", 0) == max(chunk_count - 1, 0))
|
||||
ok_dup = (dup_count == 0)
|
||||
|
||||
line = {
|
||||
"note_id": nid,
|
||||
"title": n.get("title"),
|
||||
"type": n.get("type"),
|
||||
"chunks": chunk_count,
|
||||
"edges_by_kind": by_kind,
|
||||
"checks": {
|
||||
"belongs_to_equals_chunks": ok_bt,
|
||||
"next_prev_match": ok_seq,
|
||||
"no_duplicate_edges": ok_dup,
|
||||
}
|
||||
}
|
||||
print(json.dumps(line, ensure_ascii=False))
|
||||
if args.flush:
|
||||
sys.stdout.flush()
|
||||
|
||||
print(json.dumps({"prefix": cfg.prefix, "summary": total}, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
scripts/test_edges_smoke_fast.py — Zählung über /count (sehr schnell)
|
||||
|
||||
Verwendet Qdrant 'count' API je Note/Kind (anstatt scroll), dadurch sehr schnelle Ausführung.
|
||||
Optionen:
|
||||
--max-notes N : prüft nur die ersten N Notizen
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
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
|
||||
|
||||
KINDS = ["belongs_to", "next", "prev", "references", "backlink"]
|
||||
|
||||
def collections(prefix: str) -> Tuple[str, str, str]:
|
||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||
|
||||
def list_note_ids(client, notes_col: str, max_notes: int | None) -> List[Dict[str, Any]]:
|
||||
pts, _ = client.scroll(collection_name=notes_col, with_payload=True, with_vectors=False, limit=max_notes or 1024)
|
||||
out = []
|
||||
for p in pts or []:
|
||||
pl = p.payload or {}
|
||||
nid = pl.get("note_id") or pl.get("id")
|
||||
if nid:
|
||||
out.append({"note_id": nid, "title": pl.get("title"), "type": pl.get("type")})
|
||||
return out
|
||||
|
||||
def count_points(client, col: str, filt: rest.Filter) -> int:
|
||||
res = client.count(collection_name=col, count_filter=filt, exact=True)
|
||||
return int(getattr(res, "count", 0))
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--max-notes", type=int)
|
||||
args = ap.parse_args()
|
||||
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
notes_col, chunks_col, edges_col = collections(cfg.prefix)
|
||||
notes = list_note_ids(client, notes_col, args.max_notes)
|
||||
|
||||
summary = {"notes": 0, "chunks": 0, "edges": 0}
|
||||
for n in notes:
|
||||
nid = n["note_id"]
|
||||
summary["notes"] += 1
|
||||
|
||||
filt_note = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=nid))])
|
||||
chunk_cnt = count_points(client, chunks_col, filt_note)
|
||||
summary["chunks"] += chunk_cnt
|
||||
|
||||
# counts per kind (edges)
|
||||
by_kind: Dict[str, int] = {}
|
||||
for k in KINDS:
|
||||
f = rest.Filter(must=[
|
||||
rest.FieldCondition(key="note_id", match=rest.MatchValue(value=nid)),
|
||||
rest.FieldCondition(key="kind", match=rest.MatchValue(value=k)),
|
||||
])
|
||||
c = count_points(client, edges_col, f)
|
||||
if c:
|
||||
by_kind[k] = c
|
||||
|
||||
summary["edges"] += sum(by_kind.values())
|
||||
line = {"note_id": nid, "title": n.get("title"), "type": n.get("type"), "chunks": chunk_cnt, "edges_by_kind": by_kind}
|
||||
print(json.dumps(line, ensure_ascii=False))
|
||||
|
||||
print(json.dumps({"prefix": cfg.prefix, "summary": summary}, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user