Compare commits

...
Author SHA1 Message Date
Lars 58bce0ea19 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 19:57:32 +02:00
Lars 3e888cc669 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 19:47:16 +02:00
Lars 78446c74d3 schemas/note.schema.json aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 19:43:12 +02:00
Lars 51f08f193c scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 19:42:35 +02:00
Lars 4872374a6e app/core/note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 19:42:09 +02:00
Lars 81c1400ef4 app/core/note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:55:36 +02:00
Lars 298c1fb180 scripts/debug_note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:55:12 +02:00
Lars f8108bd724 scripts/debug_note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:52:25 +02:00
Lars 65c40b287f scripts/debug_note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:48:41 +02:00
Lars 13e50d4695 scripts/debug_note_payload.py hinzugefügt
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:47:13 +02:00
Lars 791cda23af scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:44:59 +02:00
Lars 466ea64e63 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:39:48 +02:00
Lars f5e6fcc097 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:36:27 +02:00
Lars 9ef2e8d397 app/core/note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:33:38 +02:00
Lars 4637091125 app/core/note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:31:25 +02:00
Lars 43a8c80508 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:31:00 +02:00
Lars 9362064ad1 scripts/make_test_vault.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:17:27 +02:00
Lars 23952aa3c5 app/core/chunk_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:16:34 +02:00
Lars 79e19c85eb schemas/note.schema.json aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:15:53 +02:00
Lars 62d8299480 schemas/edge.schema.json aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:15:22 +02:00
Lars 8f342ea2d3 schemas/chunk.schema.json aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 16:15:05 +02:00
Lars 5d5de06290 scripts/verify_chunk_texts.py hinzugefügt
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 15:58:12 +02:00
Lars d7e5f398f0 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 12:40:54 +02:00
Lars 5bf5316af5 app/core/note_payload.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 12:40:23 +02:00
Lars d9fd6d8a8f docs/knowledge_design.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 12:29:55 +02:00
Lars e672eade8b docs/knowledge_design.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 12:22:26 +02:00
Lars ec346905ed docs/chunking_strategy.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 12:22:04 +02:00
Lars c9cbbbfcb9 docs/knowledge_design.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:57:34 +02:00
Lars 93739935b7 docs/knowledge_design.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:56:54 +02:00
Lars 6a293e842e docs/chunking_strategy.md aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:56:26 +02:00
Lars f4abb1d873 scripts/import_markdown.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:52:16 +02:00
Lars 8f48701ea0 app/core/qdrant.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:51:52 +02:00
Lars 6f32c60c47 app/core/edges.py aktualisiert
Deploy mindnet to llm-node / deploy (push) Failing after 2s
2025-09-09 11:51:28 +02:00
13 changed files with 1553 additions and 916 deletions

No files matched your search

+185 -91
View File
@@ -2,157 +2,251 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Modul: app/core/chunk_payload.py Modul: app/core/chunk_payload.py
Version: 1.1.3 Version: 2.0.0
Datum: 2025-09-09 Datum: 2025-09-09
Kurzbeschreibung Kurzbeschreibung
---------------- ----------------
Erzeugt Qdrant-Payloads für Text-Chunks einer Note. Jeder Chunk enthält Erzeugt **Chunk-Payloads** für die Qdrant-Collection `<prefix>_chunks` auf Basis der
den tatsächlichen Text unter dem Schlüssel ``text``. Dadurch kann der vom Chunker gelieferten `Chunk`-Objekte. Ziel:
Exporter den vollständigen Body verlässlich aus Chunks rekonstruieren, - *Verlustfreie Rekonstruktion*: Jeder Chunk enthält seinen **Text** (payload["text"]).
falls ``notes.payload.fulltext`` fehlt. - *Schnelle Abfragen*: Wichtige Note-Metadaten werden gespiegelt, um Filter ohne Join zu erlauben.
- *Graph-Kompatibilität*: Wikilinks und externe Links werden extrahiert; Nachbarschaften werden übernommen.
- *Monitoring*: Token- und Längenmetriken sowie Text-Hash erleichtern Audits und Re-Embeddings.
Wesentliche Features Kompatibilität
--------------------
- Stabile, idempotente Payload-Struktur für Chunks
- Persistenter Chunk-Text (``text``)
- Extraktion von Wikilinks pro Chunk (``wikilinks`` & ``references``)
- Pfadübernahme (relativ zum Vault, wird vom Aufrufer geliefert)
- Bereinigung leerer Felder (keine ``None``/leere Collections im Payload)
Abhängigkeiten
-------------- --------------
- ``app.core.chunker.Chunk`` und ``assemble_chunks`` (nur für CLI-Demo) - **Abwärtskompatibel** zur bisherigen `make_chunk_payloads`-Signatur.
- ``app.core.parser.extract_wikilinks`` und ``read_markdown`` (nur CLI-Demo) - Zusätzliche Felder stören bestehende Upserts nicht (Payload ist schema-flexibel).
- Erwartet, dass `Chunk` u. a. die Attribute `id`, `index`, `text`, `char_start`, `char_end`,
`section_title`, `section_path`, `neighbors_prev`, `neighbors_next` liefert.
Beispiele (CLI – Sichtprüfung) CLI (Schnelltest)
------------------------------ -----------------
python3 -m app.core.chunk_payload --from-file ./vault/demo.md --print # Preview aus einer Markdown-Datei
python3 -m app.core.chunk_payload --from-file ./test_vault/20_experiences/exp-two.md --vault-root ./test_vault
# Nur IDs & Tokenmengen
python3 -m app.core.chunk_payload --from-file ./test_vault/20_experiences/exp-two.md --vault-root ./test_vault --summary
Felder (Auszug)
---------------
id : "<note_id>#cNN"
scope : "chunk"
note_id : "<note_id>"
note_title : str
note_type : str
note_status : str
area, project : optional
tags : list[str]
note_path : str (relativ, Slashes normalisiert)
chunk_index : int
section_title : str | None
section_path : str | None
char_start : int | None
char_end : int | None
char_len : int
token_est : int (≈ len(text)/4)
neighbors : {"prev": str|None, "next": str|None}
text : str (Chunk-Text, **Pflicht**)
text_sha256 : str "sha256:<hex>"
lang : optional
wikilinks : list[str]
external_links : list[{"href": str, "label": str|None}]
references : list[{"target_id": str, "kind": "wikilink"}]
embed_model : optional (durchreichbar)
embed_dim : optional
embed_version : optional
""" """
from __future__ import annotations from __future__ import annotations
from typing import Dict, List, Any
import argparse import argparse
import hashlib
import json import json
import os import os
import re
from typing import Dict, List, Optional, Tuple
# WICHTIG: Keine direkten Selbst- oder Kreuz-Imports, die Zyklen erzeugen!
# Für die Kernfunktion reicht extract_wikilinks als Typ-unabhängige Hilfsfunktion.
try: try:
from app.core.parser import extract_wikilinks # nur Funktion, erzeugt keine Zyklen # Paket-Import (normaler Betrieb)
from app.core.chunker import Chunk
from app.core.parser import extract_wikilinks, read_markdown, normalize_frontmatter, validate_required_frontmatter
except Exception: # pragma: no cover except Exception: # pragma: no cover
from .parser import extract_wikilinks # type: ignore # Relativ (lokale Tests)
from .chunker import Chunk # type: ignore
# Typ-Hinweis für Chunk (zur Laufzeit nicht notwendig) from .parser import extract_wikilinks, read_markdown, normalize_frontmatter, validate_required_frontmatter # type: ignore
try:
from app.core.chunker import Chunk # nur Typ-Annotation / Nutzung im CLI
except Exception: # pragma: no cover
class Chunk: # type: ignore
pass
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Utils # Utilities
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _drop_empty(d: Dict[str, Any]) -> Dict[str, Any]: RE_MD_LINK = re.compile(r"\[([^\]]*)\]\(([^)\s]+)(?:\s+\"([^\"]+)\")?\)")
"""Entfernt leere/None-Felder aus einem Dict (für saubere Payloads).""" RE_HTTP_SCHEMES = ("http://", "https://", "mailto:", "obsidian://", "tel:")
return {k: v for k, v in d.items() if v not in (None, [], {}, "")}
def _estimate_tokens(text: str) -> int:
"""Grobe Token-Schätzung (≈ 1 Token pro 4 Zeichen)."""
return max(0, int(round(len((text or '').strip()) / 4)))
def _sha256_text(text: str) -> str:
h = hashlib.sha256()
h.update((text or "").encode("utf-8"))
return "sha256:" + h.hexdigest()
def _normalize_rel_path(path: Optional[str], vault_root: Optional[str]) -> Optional[str]:
if not path:
return None
p = str(path)
p = p.replace("\\", "/")
if vault_root and os.path.isabs(p):
try:
p = os.path.relpath(p, vault_root)
except Exception:
pass
p = p.replace("\\", "/").lstrip("/")
return p
def _extract_external_links(text: str) -> List[Dict[str, Optional[str]]]:
"""Findet Markdown-Links [label](href "title") mit erlaubten Schemes."""
out: List[Dict[str, Optional[str]]] = []
if not text:
return out
for m in RE_MD_LINK.finditer(text):
label = (m.group(1) or "").strip() or None
href = (m.group(2) or "").strip()
title = (m.group(3) or "").strip() or None
if any(href.startswith(s) for s in RE_HTTP_SCHEMES):
out.append({"href": href, "label": label or title})
return out
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Kernfunktion # Public API
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def make_chunk_payloads(note_meta: Dict[str, Any], path: str, chunks: List[Chunk]) -> List[Dict[str, Any]]: def make_chunk_payloads(note_meta: Dict, path: str, chunks: List[Chunk]) -> List[Dict]:
""" """
Baut Payloads für alle ``chunks`` der gegebenen Note. Erzeugt Payload-Dicts für alle Chunks einer Note.
Parameters Parameters
---------- ----------
note_meta : Dict[str, Any] note_meta : Dict
Minimale Metadaten der Note (mind. ``id``, ``title``; optional ``type``, Normalisierte Frontmatter der Note (mind.: id, title, type, status, tags, [area, project, lang]).
``area``, ``project``, ``tags``, ``lang``).
path : str path : str
Relativer Pfad der Note innerhalb des Vaults (z. B. "area/topic/file.md"). Pfad zur Note (sollte relativ zum Vault sein; wird hier zur Sicherheit normalisiert).
chunks : List[Chunk] chunks : List[Chunk]
Liste vorsegmentierter Chunks (vgl. app.core.chunker.Chunk). Vom Chunker erzeugte Chunks.
Returns Returns
------- -------
List[Dict[str, Any]] List[Dict]
Payload-Objekte, bereit für Qdrant-Upserts. Liste von Payloads (ein Eintrag pro Chunk).
""" """
res: List[Dict[str, Any]] = [] res: List[Dict] = []
rel_path = _normalize_rel_path(path, vault_root=None)
for ch in chunks: for ch in chunks:
# 'text' kann bei leerem Abschnitt None/'' sein → robust behandeln text: str = getattr(ch, "text", "") or ""
text_val = getattr(ch, "text", "") or "" wikilinks = extract_wikilinks(text)
wikilinks = extract_wikilinks(text_val) ext_links = _extract_external_links(text)
payload = {
payload: Dict = {
"id": getattr(ch, "id", None), "id": getattr(ch, "id", None),
"scope": "chunk",
"note_id": note_meta.get("id"), "note_id": note_meta.get("id"),
"note_title": note_meta.get("title"), "note_title": note_meta.get("title"),
# gespiegelt für schnelle Filter:
"note_type": note_meta.get("type"),
"note_status": note_meta.get("status"),
"area": note_meta.get("area"),
"project": note_meta.get("project"),
"tags": note_meta.get("tags"),
# Pfad
"note_path": rel_path,
"path": rel_path, # Back-compat
# Reihenfolge & Section
"chunk_index": getattr(ch, "index", None), "chunk_index": getattr(ch, "index", None),
"char_start": getattr(ch, "char_start", None),
"char_end": getattr(ch, "char_end", None),
"token_count": getattr(ch, "token_count", None),
"section_title": getattr(ch, "section_title", None), "section_title": getattr(ch, "section_title", None),
"section_path": getattr(ch, "section_path", None), "section_path": getattr(ch, "section_path", None),
"lang": note_meta.get("lang"), # Position
"wikilinks": wikilinks, "char_start": getattr(ch, "char_start", None),
"external_links": [], "char_end": getattr(ch, "char_end", None),
"references": [{"target_id": w, "kind": "wikilink"} for w in wikilinks], "char_len": max(0, int(getattr(ch, "char_end", 0) or 0) - int(getattr(ch, "char_start", 0) or 0)) or len(text),
# Nachbarn
"neighbors": { "neighbors": {
"prev": getattr(ch, "neighbors_prev", None), "prev": getattr(ch, "neighbors_prev", None),
"next": getattr(ch, "neighbors_next", None), "next": getattr(ch, "neighbors_next", None),
}, },
"path": path, # vom Aufrufer relativ geliefert # Inhalt & Metrik
"text": text_val, # WICHTIG für Export/Rekonstruktion "text": text,
"text_sha256": _sha256_text(text),
"token_est": _estimate_tokens(text),
# Sprache
"lang": note_meta.get("lang"),
# Links
"wikilinks": wikilinks,
"external_links": ext_links,
"references": [{"target_id": w, "kind": "wikilink"} for w in wikilinks],
} }
res.append(_drop_empty(payload))
# Entferne Nones/Leeres, aber **text** bleibt (darf leer sein z. B. bei Bild-Only-Chunks)
cleaned = {}
for k, v in payload.items():
if v in (None, [], {}):
# immer behalten:
if k in ("text", "neighbors"):
cleaned[k] = v
else:
continue
else:
cleaned[k] = v
res.append(cleaned)
return res return res
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# CLI – nur zur Sichtprüfung / Debug # CLI zum schnellen Testen
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _cli() -> None: def _cli() -> None:
# CLI lädt hier *lazy* die schweren Abhängigkeiten, ap = argparse.ArgumentParser(description="Chunk-Payloads aus einer einzelnen Markdown-Datei erzeugen")
# damit die Modul-Initialisierung zirkularfrei bleibt. ap.add_argument("--from-file", required=True, help="Pfad zur Markdown-Datei")
try: ap.add_argument("--vault-root", default=None, help="Vault-Wurzel (zur Pfad-Relativierung)")
from app.core.parser import read_markdown ap.add_argument("--summary", action="store_true", help="Nur kurze Übersicht je Chunk ausgeben")
from app.core.chunker import assemble_chunks
except Exception: # pragma: no cover
from .parser import read_markdown # type: ignore
from .chunker import assemble_chunks # type: ignore
ap = argparse.ArgumentParser(description="Vorschau: Chunk-Payloads erzeugen und anzeigen")
ap.add_argument("--from-file", dest="src", required=True, help="Pfad zu einer Markdown-Datei")
ap.add_argument("--print", dest="do_print", action="store_true", help="Payload auf stdout ausgeben")
args = ap.parse_args() args = ap.parse_args()
note = read_markdown(args.src) parsed = read_markdown(args.from_file)
note_meta = { fm = normalize_frontmatter(parsed.frontmatter)
"id": note.frontmatter.get("id") or note.frontmatter.get("note_id"), validate_required_frontmatter(fm)
"title": note.frontmatter.get("title"),
"type": note.frontmatter.get("type"),
"area": note.frontmatter.get("area"),
"project": note.frontmatter.get("project"),
"tags": note.frontmatter.get("tags", []),
"lang": note.frontmatter.get("lang"),
}
chunks = assemble_chunks(note.frontmatter.get("id"), note.body or "", note.frontmatter.get("type", "concept")) # lazy import, um Zyklen zu vermeiden
try:
from app.core.chunker import assemble_chunks
except Exception:
from .chunker import assemble_chunks # type: ignore
# Vault-Root heuristisch relativieren (nur für Demo) chunks = assemble_chunks(fm["id"], parsed.body, fm.get("type", "concept"))
vault_root = os.path.dirname(os.path.dirname(args.src)) # heuristisch rel = _normalize_rel_path(parsed.path, args.vault_root)
rel_path = os.path.relpath(args.src, vault_root).replace("\\", "/").lstrip("/")
payloads = make_chunk_payloads(note_meta, rel_path, chunks) pls = make_chunk_payloads(fm, rel or parsed.path, chunks)
if args.do_print: if args.summary:
print(json.dumps(payloads, ensure_ascii=False, indent=2)) out = []
for p in pls:
out.append({
"id": p.get("id"),
"chunk_index": p.get("chunk_index"),
"token_est": p.get("token_est"),
"wikilinks": p.get("wikilinks"),
"ext_links": [e.get("href") for e in p.get("external_links", [])],
"prev": (p.get("neighbors") or {}).get("prev"),
"next": (p.get("neighbors") or {}).get("next"),
})
print(json.dumps(out, ensure_ascii=False, indent=2))
else:
print(json.dumps(pls, ensure_ascii=False, indent=2))
if __name__ == "__main__": # pragma: no cover if __name__ == "__main__": # pragma: no cover
+108 -33
View File
@@ -1,45 +1,120 @@
from __future__ import annotations #!/usr/bin/env python3
from typing import List, Dict # -*- coding: utf-8 -*-
"""
Modul: app/core/edges.py
Version: 1.0.0
Datum: 2025-09-09
def deriv_edges_for_note(note_meta: Dict, chunk_payloads: List[Dict]) -> List[Dict]: 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)
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.
"""
from __future__ import annotations
from typing import Dict, List
def build_edges_for_note(
note_id: str,
chunk_payloads: List[Dict],
note_level_refs: List[str] | None,
*,
include_note_scope_refs: bool = False,
) -> List[Dict]:
edges: List[Dict] = [] edges: List[Dict] = []
# Chunk → Note (belongs_to) + prev/next # Chunk-Scope: belongs_to / prev / next / references
for idx, ch in enumerate(chunk_payloads): for ch in chunk_payloads:
cid = ch["id"]
owner = ch.get("note_id") or note_id
# belongs_to
edges.append({ edges.append({
"src_id": ch["id"], "dst_id": note_meta["id"], "kind": "belongs_to",
"edge_type": "belongs_to", "scope": "chunk" "source_id": cid,
"target_id": note_id,
"scope": "chunk",
"note_id": owner,
}) })
prev_id = ch.get("neighbors",{}).get("prev") # Nachbarn
next_id = ch.get("neighbors",{}).get("next") nb = ch.get("neighbors") or {}
prev_id = nb.get("prev")
next_id = nb.get("next")
if prev_id: if prev_id:
edges.append({"src_id": ch["id"], "dst_id": prev_id, "edge_type": "next", "scope": "chunk"}) edges.append({
edges.append({"src_id": prev_id, "dst_id": ch["id"], "edge_type": "prev", "scope": "chunk"}) "kind": "prev",
"source_id": cid,
"target_id": prev_id,
"scope": "chunk",
"note_id": owner,
})
edges.append({
"kind": "next",
"source_id": prev_id,
"target_id": cid,
"scope": "chunk",
"note_id": owner,
})
if next_id: if next_id:
edges.append({"src_id": ch["id"], "dst_id": next_id, "edge_type": "next", "scope": "chunk"}) edges.append({
edges.append({"src_id": next_id, "dst_id": ch["id"], "edge_type": "prev", "scope": "chunk"}) "kind": "next",
"source_id": cid,
# references aus wikilinks (Chunk-Scope) "target_id": next_id,
for ref in ch.get("references", []): "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") tid = ref.get("target_id")
if not tid: continue if not tid:
edges.append({"src_id": ch["id"], "dst_id": tid, "edge_type": "references", "scope": "chunk"}) continue
edges.append({"src_id": tid, "dst_id": ch["id"], "edge_type": "backlink", "scope": "chunk"}) edges.append({
"kind": "references",
"source_id": cid,
"target_id": tid,
"scope": "chunk",
"note_id": owner,
})
# depends_on / assigned_to (Note-Scope, aus Frontmatter) # Note-Scope: backlink (immer); references (optional)
for dep in note_meta.get("depends_on", []) or []: unique_refs = list(dict.fromkeys(note_level_refs or []))
edges.append({"src_id": note_meta["id"], "dst_id": dep, "edge_type": "depends_on", "scope": "note"}) for tid in unique_refs:
for ass in note_meta.get("assigned_to", []) or []: if include_note_scope_refs:
edges.append({"src_id": note_meta["id"], "dst_id": ass, "edge_type": "assigned_to", "scope": "note"}) edges.append({
"kind": "references",
# Note-Level references (optional: falls du im Note-Payload `references` sammelst) "source_id": note_id,
for tid in note_meta.get("references", []) or []: "target_id": tid,
edges.append({"src_id": note_meta["id"], "dst_id": tid, "edge_type": "references", "scope": "note"}) "scope": "note",
edges.append({"src_id": tid, "dst_id": note_meta["id"], "edge_type": "backlink", "scope": "note"}) "note_id": note_id,
})
edges.append({
"kind": "backlink",
"source_id": tid,
"target_id": note_id,
"scope": "note",
"note_id": note_id,
})
# Dedupe # Dedupe
uniq = {} dedup = {}
for e in edges: for e in edges:
k = (e["src_id"], e["edge_type"], e["dst_id"], e.get("scope","note")) k = (e["kind"], e["source_id"], e["target_id"], e.get("scope", ""))
uniq[k] = e dedup[k] = e
return list(uniq.values()) return list(dedup.values())
+145 -114
View File
@@ -1,98 +1,85 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" # Modul: app/core/note_payload.py
Modul: app/core/note_payload.py # Version: 1.7.0
Version: 1.4.0 # Datum: 2025-09-09
Datum: 2025-09-09
Kurzbeschreibung
----------------
Erzeugt den Qdrant-Payload für **Notes**. Neben stabiler Hash-Bildung zur
Idempotenz wird der vollständige Body unter ``fulltext`` persistiert und
der Dateipfad relativ zum Vault gespeichert. Das erlaubt eine verlustfreie
Rekonstruktion im Export (erst ``fulltext``, sonst Chunks).
Hash-Steuerung
--------------
- Modus: ``body`` (Default) | ``frontmatter`` | ``body+frontmatter``
* per Funktionsparameter ``hash_mode`` (prio 1)
* oder ENV ``MINDNET_HASH_MODE`` (prio 2)
- Normalisierung: ``canonical`` (Default) | ``none``
* per Funktionsparameter ``hash_normalize`` (prio 1)
* oder ENV ``MINDNET_HASH_NORMALIZE`` (prio 2)
Beispiele (CLI – Sichtprüfung)
------------------------------
python3 -m app.core.note_payload --from-file ./vault/demo.md --vault-root ./vault --print
"""
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import hashlib import hashlib
import json import json
import os import os
from typing import Any, Dict, Optional from typing import Any, Dict, Optional, Tuple
try: try:
from app.core.parser import read_markdown, extract_wikilinks from app.core.parser import read_markdown, extract_wikilinks, FRONTMATTER_RE
except Exception: # pragma: no cover except Exception: # pragma: no cover
from .parser import read_markdown, extract_wikilinks # type: ignore from .parser import read_markdown, extract_wikilinks, FRONTMATTER_RE # type: ignore
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Hashing # Helpers
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _canon_frontmatter(fm: Dict[str, Any]) -> str: def _canon_frontmatter(fm: Dict[str, Any]) -> str:
"""Kanonische, stabile JSON-Serialisierung der Frontmatter für Hashbildung."""
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True) return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
def _normalize_body(body: str, mode: str) -> str: def _normalize_body(body: str, mode: str) -> str:
"""Normalisiert den Body für reproduzierbare Hashes (oder nicht)."""
if mode == "none": if mode == "none":
return body if body is not None else "" return body if body is not None else ""
# canonical: \r\n→\n, trailing spaces, mehrfach-blankzeilen trimmen
text = (body or "").replace("\r\n", "\n").replace("\r", "\n") text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
# trailing whitespace am Zeilenende entfernen
text = "\n".join(line.rstrip() for line in text.split("\n")) text = "\n".join(line.rstrip() for line in text.split("\n"))
# keine aggressivere Logik (keine inhaltliche Änderung)
return text return text
def compute_hash( def _resolve_hash_mode(explicit: Optional[str]) -> str:
*, if explicit:
body: Optional[str], val = explicit.strip().lower()
frontmatter: Optional[Dict[str, Any]], else:
mode: Optional[str] = None, val = (os.environ.get("MINDNET_HASH_MODE")
normalize: Optional[str] = None, or os.environ.get("MINDNET_HASH_COMPARE")
) -> str: or "body").strip().lower()
""" if val in ("full", "fulltext", "body+frontmatter", "bodyplusfrontmatter"):
Berechnet einen Hex-Hash gemäß ``mode`` und ``normalize``. return "full"
if val in ("frontmatter", "fm"):
return "frontmatter"
return "body"
mode: def _read_raw_body_from_file(file_path: Optional[str]) -> Tuple[str, Dict[str, Any]]:
- "body" (Default) if not file_path or not os.path.exists(file_path):
- "frontmatter" return "", {}
- "body+frontmatter" try:
normalize: with open(file_path, "r", encoding="utf-8") as f:
- "canonical" (Default) raw = f.read()
- "none" except Exception:
""" return "", {}
mode = (mode or os.environ.get("MINDNET_HASH_MODE", "body")).strip().lower() m = FRONTMATTER_RE.match(raw)
normalize = (normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower() fm = {}
if m:
body = _normalize_body(body or "", normalize) fm_txt = m.group(1)
fm_s = _canon_frontmatter(frontmatter or {}) try:
import yaml # lazy
fm = yaml.safe_load(fm_txt) or {}
except Exception:
fm = {}
body = raw[m.end():]
else:
body = raw
return body, fm
def _sha256(s: str) -> str:
h = hashlib.sha256() h = hashlib.sha256()
if mode == "frontmatter": h.update(s.encode("utf-8"))
h.update(fm_s.encode("utf-8"))
elif mode == "body+frontmatter":
h.update(body.encode("utf-8"))
h.update(b"\n--FM--\n")
h.update(fm_s.encode("utf-8"))
else: # body
h.update(body.encode("utf-8"))
return h.hexdigest() return h.hexdigest()
def _hash_for(mode: str, *, body: str, fm: Dict[str, Any], normalize: str) -> str:
body_n = _normalize_body(body or "", normalize)
fm_s = _canon_frontmatter(fm or {})
if mode == "frontmatter":
return _sha256(fm_s)
if mode == "full":
return _sha256(body_n + "\n--FM--\n" + fm_s)
# default: body
return _sha256(body_n)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Kernfunktion # Kernfunktion
@@ -104,51 +91,84 @@ def make_note_payload(
*, *,
hash_mode: Optional[str] = None, hash_mode: Optional[str] = None,
hash_normalize: Optional[str] = None, hash_normalize: Optional[str] = None,
hash_source: Optional[str] = None,
file_path: Optional[str] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
Erzeugt den Payload für eine geparste Note. Liefert den Note-Payload inkl. Mehrfach-Hashes.
- Es werden IMMER die drei Hashes für (body|frontmatter|full) unter
Parameters 'parsed:canonical' erzeugt (Schlüssel: z. B. 'body:parsed:canonical').
---------- - Zusätzlich werden – falls die aktuelle Konfig (source/normalize) davon
parsed : Any abweicht – die drei Hashes unter den entsprechenden Schlüsseln erzeugt,
Objekt mit Attributen/Keys ``frontmatter``, ``body``, ``path``. z. B. 'frontmatter:raw:none'.
vault_root : Optional[str] - 'hash_fulltext' und 'hash_signature' repräsentieren den *aktuellen* Modus.
Vault-Wurzel (für Pfad-Relativierung). Wenn ``None``, wird ``path`` unverändert übernommen.
hash_mode : Optional[str]
"body" | "frontmatter" | "body+frontmatter" (überschreibt ENV).
hash_normalize : Optional[str]
"canonical" | "none" (überschreibt ENV).
Returns
-------
Dict[str, Any]
Qdrant-Payload für die Notes-Collection.
""" """
# "Duck typing": dict oder Objekt akzeptieren # dict oder Objekt akzeptieren
fm = ( if isinstance(parsed, dict):
getattr(parsed, "frontmatter", None) fm = parsed.get("frontmatter") or {}
or getattr(parsed, "fm", None) body_parsed = parsed.get("body") or ""
or getattr(parsed, "front_matter", None) path = parsed.get("path") or ""
or (parsed.get("frontmatter") if isinstance(parsed, dict) else {}) else:
) or {} fm = getattr(parsed, "frontmatter", {}) or {}
body = getattr(parsed, "body", None) or (parsed.get("body") if isinstance(parsed, dict) else "") or "" body_parsed = getattr(parsed, "body", "") or ""
path = getattr(parsed, "path", None) or (parsed.get("path") if isinstance(parsed, dict) else "") or "" path = getattr(parsed, "path", "") or ""
# Hash gem. Modus bilden # Zielpfad relativieren
hash_fulltext = compute_hash(body=body, frontmatter=fm, mode=hash_mode, normalize=hash_normalize)
# Pfad relativieren
rel_path = path rel_path = path
try: try:
if vault_root: if vault_root:
rel = os.path.relpath(path, vault_root) rel = os.path.relpath(path, vault_root)
rel = rel.replace("\\", "/").lstrip("/") # normalisieren rel = rel.replace("\\", "/").lstrip("/")
rel_path = rel rel_path = rel
except Exception: except Exception:
pass # Pfad nicht kritisch für Hash/ID pass
# Optionale Note-Level-Wikilinks (Fallback, wenn Chunks nicht geliefert werden) # Konfiguration auflösen
note_level_refs = list(dict.fromkeys(extract_wikilinks(body))) if body else [] mode_resolved = _resolve_hash_mode(hash_mode) # body|frontmatter|full
src = (hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed")).strip().lower() # parsed|raw
norm = (hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower() # canonical|none
# Body-Quelle laden
raw_body, raw_fm = ("", {})
if src == "raw":
raw_body, raw_fm = _read_raw_body_from_file(file_path or path)
if isinstance(raw_fm, dict) and raw_fm:
merged_fm = dict(fm)
for k, v in raw_fm.items():
merged_fm.setdefault(k, v)
fm = merged_fm
body_for_hash = raw_body
else:
body_for_hash = body_parsed
# --- 1) Standard-Tripel (parsed:canonical) immer erzeugen ---
std_src = "parsed"
std_norm = "canonical"
std_hashes: Dict[str, str] = {}
for m in ("body", "frontmatter", "full"):
std_hashes[f"{m}:{std_src}:{std_norm}"] = _hash_for(
m, body=body_parsed, fm=fm, normalize=std_norm
)
# Convenience-Felder (für Tools)
hash_body = std_hashes["body:parsed:canonical"]
hash_frontmatter = std_hashes["frontmatter:parsed:canonical"]
hash_full = std_hashes["full:parsed:canonical"]
# --- 2) Hashes für die *aktuelle* Konfiguration (falls abweichend) ---
cur_hashes: Dict[str, str] = {}
if not (src == std_src and norm == std_norm):
for m in ("body", "frontmatter", "full"):
cur_hashes[f"{m}:{src}:{norm}"] = _hash_for(
m, body=body_for_hash, fm=fm, normalize=norm
)
# --- 3) Aktueller Modus für Backwards-Compat Felder ---
current_hash = _hash_for(mode_resolved, body=body_for_hash, fm=fm, normalize=norm)
hash_signature = f"{mode_resolved}:{src}:{norm}:{current_hash}"
# Wikilinks (Note-Ebene)
refs = list(dict.fromkeys(extract_wikilinks(body_parsed))) if body_parsed else []
payload: Dict[str, Any] = { payload: Dict[str, Any] = {
"note_id": fm.get("id") or fm.get("note_id"), "note_id": fm.get("id") or fm.get("note_id"),
@@ -159,40 +179,51 @@ def make_note_payload(
"updated": fm.get("updated"), "updated": fm.get("updated"),
"path": rel_path or fm.get("path"), "path": rel_path or fm.get("path"),
"tags": fm.get("tags"), "tags": fm.get("tags"),
"hash_fulltext": hash_fulltext, # Volltext für verlustfreien Export
# Volltext persistieren (verlustfreie Rekonstruktion) "fulltext": body_parsed,
"fulltext": body, # Backwards-Compat:
# Fallback-Refs auf Note-Ebene "hash_fulltext": current_hash,
"references": note_level_refs, "hash_signature": hash_signature,
# Option C: Mehrfach-Hashes
"hashes": {**std_hashes, **cur_hashes},
"hash_body": hash_body,
"hash_frontmatter": hash_frontmatter,
"hash_full": hash_full,
# Fallback-Refs
"references": refs,
} }
for k in ("area", "project", "source", "lang", "slug"): for k in ("area", "project", "source", "lang", "slug", "aliases"):
if k in fm: if k in fm:
payload[k] = fm[k] payload[k] = fm[k]
return payload return payload
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# CLI – Sichtprüfung # CLI – Sichtprüfung
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _cli() -> None: def _cli() -> None:
ap = argparse.ArgumentParser(description="Note-Payload aus Markdown erzeugen und anzeigen") ap = argparse.ArgumentParser(description="Note-Payload aus Markdown erzeugen und anzeigen")
ap.add_argument("--from-file", dest="src", required=True, help="Pfad zur Markdown-Datei") ap.add_argument("--from-file", dest="src", required=True)
ap.add_argument("--vault-root", dest="vault_root", default=None, help="Vault-Wurzel zur Pfad-Relativierung") ap.add_argument("--vault-root", dest="vault_root", default=None)
ap.add_argument("--print", dest="do_print", action="store_true", help="Payload auf stdout ausgeben") ap.add_argument("--print", dest="do_print", action="store_true")
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter"], default=None) ap.add_argument("--hash-mode", choices=["body", "frontmatter", "full"], default=None)
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None) ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
ap.add_argument("--hash-source", choices=["parsed", "raw"], default=None)
args = ap.parse_args() args = ap.parse_args()
parsed = read_markdown(args.src) parsed = read_markdown(args.src)
payload = make_note_payload(parsed, vault_root=args.vault_root, payload = make_note_payload(
hash_mode=args.hash_mode, hash_normalize=args.hash_normalize) parsed,
vault_root=args.vault_root,
hash_mode=args.hash_mode,
hash_normalize=args.hash_normalize,
hash_source=args.hash_source,
file_path=args.src,
)
if args.do_print: if args.do_print:
print(json.dumps(payload, ensure_ascii=False, indent=2)) print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__": # pragma: no cover if __name__ == "__main__": # pragma: no cover
_cli() _cli()
+31 -59
View File
@@ -2,30 +2,16 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Name: app/core/qdrant.py Name: app/core/qdrant.py
Version: v1.3.1 (2025-09-05) Version: v1.4.0 (2025-09-09)
Kurzbeschreibung: Kurzbeschreibung:
Qdrant-Client & Collection-Setup für mindnet. Qdrant-Client & Collection-Setup für mindnet.
- Stellt sicher, dass {prefix}_notes / {prefix}_chunks / {prefix}_edges existieren. - Stellt sicher, dass {prefix}_notes / {prefix}_chunks / {prefix}_edges existieren.
- Edges-Collection nutzt 1D Dummy-Vektor (Workaround für Python-Client). - Edges-Collection nutzt 1D Dummy-Vektor.
- **Nicht-destruktiv per Default**: ensure_collections(..., destructive=False). - NEW: ensure_payload_indexes(...) legt sinnvolle Payload-Indizes an.
- **Abwärtskompatibel**: collection_names(prefix) wieder verfügbar.
Aufruf/Verwendung: Aufruf:
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
Umgebungsvariablen (optional):
QDRANT_URL | QDRANT_HOST/QDRANT_PORT, QDRANT_API_KEY,
COLLECTION_PREFIX (Default "mindnet"), VECTOR_DIM (Default 384)
Änderungen:
v1.3.1: Helper collection_names(prefix) wiederhergestellt (für reset_qdrant usw.).
v1.3.0: ensure_collections(..., destructive=False) – keine stillen Drops im Dry-Run.
Edges-Collection nur bei explicit destructive=True neu anlegen.
≤v1.2.x: Konnte {prefix}_edges bei fehlender VectorConfig automatisch neu erstellen (riskant).
Bezug/Quelle:
Alte Core-Variante enthielt collection_names(prefix); diverse Scripts nutzen das weiterhin. :contentReference[oaicite:1]{index=1}
""" """
from __future__ import annotations from __future__ import annotations
import os import os
@@ -36,10 +22,6 @@ from qdrant_client import QdrantClient
from qdrant_client.http import models as rest from qdrant_client.http import models as rest
# -------------------------------
# Konfiguration
# -------------------------------
@dataclass @dataclass
class QdrantConfig: class QdrantConfig:
url: str url: str
@@ -60,18 +42,10 @@ class QdrantConfig:
return QdrantConfig(url=url, api_key=api_key, prefix=prefix, dim=dim) return QdrantConfig(url=url, api_key=api_key, prefix=prefix, dim=dim)
# -------------------------------
# Client
# -------------------------------
def get_client(cfg: QdrantConfig) -> QdrantClient: def get_client(cfg: QdrantConfig) -> QdrantClient:
return QdrantClient(url=cfg.url, api_key=cfg.api_key) return QdrantClient(url=cfg.url, api_key=cfg.api_key)
# -------------------------------
# Collection-Erzeuger (Hilfsfunktionen)
# -------------------------------
def _create_notes(client: QdrantClient, name: str, dim: int) -> None: def _create_notes(client: QdrantClient, name: str, dim: int) -> None:
if not client.collection_exists(name): if not client.collection_exists(name):
client.create_collection( client.create_collection(
@@ -94,16 +68,7 @@ def _create_edges(client: QdrantClient, name: str) -> None:
) )
# -------------------------------
# Public API
# -------------------------------
def ensure_collections(client: QdrantClient, prefix: str, dim: int, destructive: bool = False) -> None: def ensure_collections(client: QdrantClient, prefix: str, dim: int, destructive: bool = False) -> None:
"""
Stellt sicher, dass die drei Collections existieren.
- Default **nicht destruktiv**: vorhandene Collections bleiben unangetastet.
- Nur wenn 'destructive=True', wird eine ungeeignete Edges-Collection gelöscht und neu angelegt.
"""
notes = f"{prefix}_notes" notes = f"{prefix}_notes"
chunks = f"{prefix}_chunks" chunks = f"{prefix}_chunks"
edges = f"{prefix}_edges" edges = f"{prefix}_edges"
@@ -112,41 +77,48 @@ def ensure_collections(client: QdrantClient, prefix: str, dim: int, destructive:
_create_chunks(client, chunks, dim) _create_chunks(client, chunks, dim)
if client.collection_exists(edges): if client.collection_exists(edges):
# Prüfen, ob die Edges-Collection bereits eine Vektorkonfig hat
try: try:
info = client.get_collection(edges) info = client.get_collection(edges)
vectors_cfg = getattr(getattr(info.result, "config", None), "params", None) vectors_cfg = getattr(getattr(info.result, "config", None), "params", None)
has_vectors = getattr(vectors_cfg, "vectors", None) is not None has_vectors = getattr(vectors_cfg, "vectors", None) is not None
except Exception: except Exception:
# konservativ: nichts anfassen, um Datenverlust zu vermeiden
has_vectors = True has_vectors = True
if not has_vectors: if not has_vectors:
if destructive: if destructive:
client.delete_collection(edges) client.delete_collection(edges)
_create_edges(client, edges) _create_edges(client, edges)
else: else:
print( print(f"[ensure_collections] WARN: '{edges}' ohne VectorConfig; destructive=False.", flush=True)
f"[ensure_collections] WARN: '{edges}' ohne VectorConfig gefunden; "
f"keine destruktive Änderung (destructive=False).",
flush=True,
)
else: else:
_create_edges(client, edges) _create_edges(client, edges)
def collection_names(prefix: str) -> Tuple[str, str, str]: def collection_names(prefix: str) -> Tuple[str, str, str]:
"""
Abwärtskompatibler Helper für Scripts:
returns (f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges")
"""
return (f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges") return (f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges")
def wipe_collections(client: QdrantClient, prefix: str) -> None: # -------------------------------
""" # NEW: Payload-Indexing
Löscht alle drei Collections – nur verwenden, wenn bewusst ein Clean-Rebuild gewünscht ist. # -------------------------------
"""
for name in collection_names(prefix): def _safe_create_index(client: QdrantClient, col: str, field: str, schema: rest.PayloadSchemaType):
if client.collection_exists(name): try:
client.delete_collection(name) client.create_payload_index(
collection_name=col,
field_name=field,
field_schema=schema,
)
except Exception:
# bereits vorhanden oder nicht unterstütztes Schema → ignorieren
pass
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
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)
+106 -116
View File
@@ -13,74 +13,67 @@ Entwickle eine robuste, parser-freundliche **Chunking-Strategie** für Markdown-
--- ---
## 2) Annahmen aus `knowledge_design.md` ## 2) Annahmen aus `knowledge_design.md`
- **Stabile IDs** & Dateinamen-Schema (z. B. `YYYYMMDD-HHMM-type-slug` bzw. `type-slug`). - **IDs**: deterministische, stabile `id` pro Note (Slug / semantischer Identifier), ggf. `aliases`.
- **Pflichtfelder** in YAML: `title`, `id`, `type`, `status`, `created`, `tags` (empfohlene Felder ggf. mehr). - **Dateinamen**: entweder `YYYY-MM-DD_title.md` oder `slug.md`; Pfade sind **relativ** zum Vault.
- **Abschnitts-Konventionen** je `type` (z. B. `## Zusammenfassung`, `## Kontext` …) → ideale **Chunk-Grenzen**. - **Frontmatter-Pflichtfelder**: `id`, `title`, `type`, `created`, `updated` (Details in `knowledge_design.md`).
- **Edge-Typen**: `belongs_to`, `references`, `backlink`, `depends_on`, `assigned_to`, `discussed_in`, `authored_by`, `related`. Für Chunking primär `belongs_to` & `references` (+ optionale `prev`/`next`). - **Backlink-/Link-Regeln**: Wikilinks `[[id]]` im Body; am Ende optional redaktionelle Sektion „Mögliche Verbindungen“ (erzeugt **keine** Kanten).
--- ---
## 3) Chunking-Prinzipien ## 3) Chunking-Prinzipien
1. **Frontmatter extrahieren** → als strukturiertes `metadata` (nicht in `text` des Chunks). - **Semantische Schnitte**: Chunks enden an Absätzen, Überschriften, Listenpunkten, Codeblöcken, Zitaten.
2. **Markdown AST** (oder strukturierter Parser) nutzen: - **Frontmatter**: YAML **nicht** embedden; stattdessen komplett im Note-Payload speichern.
- Primäre Grenzen: **Überschriftenebene H2/H3** (H1 = Dokumenttitel). - **Verlustfreiheit**:
- Sekundär: **Absätze**, **nummerierte/unnummerierte Listen** als atomare Einheiten, **Codeblöcke** als zusammenhängender Block (nicht splitten). - Note-Payload: `fulltext` (gesamter Body).
3. **Längensteuerung**: Semantik vor harter Länge. Wenn Abschnitt > Zielgröße, **weich segmentieren** entlang von Absätzen/Listenpunkten. - Chunk-Payload: `text` (Originalchunk).
4. **Referenz-Extraktion**: `[[Wikilinks]]` + Markdown-Links → `references`. Backlinks werden downstream generiert. Damit kann der Export den Body **verlustfrei** rekonstruieren (erst `fulltext`, sonst Chunks).
5. **Kontext-Overlap**: Chunks erhalten **Überlappung** über Satz-/Absatzgrenzen, um Kohärenz beim Retrieval zu erhöhen.
--- ---
## 4) Optimale Chunkgrößen & Overlaps ## 4) Optimale Chunkgrößen & Overlaps
> Ziel: gutes Recall@k, wenig Fragmentierung, stabile Antwortqualität. - **Zielgröße**: 250–400 Tokens (Richtwert, abhängig vom `type`).
- **Maxgröße**: 600–800 Tokens (nur in Ausnahmen).
- **Mingröße**: 80–120 Tokens (sonst mit Nachbar verschmelzen).
- **Overlap**: 40–60 Tokens, um Kontextverlust zu vermeiden.
- **Kontextabhängig**:
- `concept`, `thought`, `experience`: 250–350 Tokens
- `task`, `project`: eher 200–300 Tokens (mehr Bullet-Struktur)
- `journal`: 300–400 Tokens (tagesabschnittsweise)
| Notiz-Typ (`type`) | Inhalt | Zielgröße (Tokens) | Max. Größe (Tokens) | Overlap (Tokens) | Hinweise | ---
|---|---|---:|---:|---:|---|
| `thought` | kurze Thesen/Ideen | 150–250 | 300 | 30–40 | meist 1–2 Chunks |
| `experience` | Kontext/Beobachtung/Interpretation | 250–350 | 450 | 40–60 | Trenne entlang der Template-Sektionen |
| `journal` | Tagebuch, episodisch | 200–300 | 400 | 30–50 | Tagesabschnitte bündeln |
| `task` | knapp, Checklisten | 120–200 | 250 | 20–30 | Listen nicht splitten |
| `project` | Scope/WPs/Risiken/Status | 300–450 | 600 | 50–70 | Pro Hauptsektion ein Chunk |
| `concept` | definierte Begriffe, Erklärungen | 250–400 | 550 | 40–60 | Definition separat halten |
| `source` | Metadaten + Auszüge/Notizen | 200–350 | 500 | 30–50 | Zitate als eigene Chunks (Urheberrecht) |
## 4.1 Overlap-Regeln ## 4.1 Overlap-Regeln
- Overlap **nie mitten im Satz** beenden → mindestens **ein kompletter Satz** wandert in den nächsten Chunk. - Overlap betrifft **nur den Body**; die YAML-Frontmatter bleibt **außerhalb**.
- An **Absatzgrenzen** ausrichten, wenn möglich. - Keine Overlaps, die Codeblöcke oder Tabellen „aufreißen“. Falls nötig: Chunk-Grenze an Blockgrenze ziehen.
- Bei **Listen** ggf. den vorherigen Punkt als Overlap mitführen (falls < 50 Tokens). - Bei reinen Listen: zusammenhängende Bullets gruppieren, ggf. kleinere Overlaps.
- Codeblöcke und Tabellen **nicht splitten**; wenn sie größer als `Max-Tokens` sind, als **eigener Chunk** belassen (Ausnahmefall zulassen).
**Daumenregel (zeichenzentriert):** ~4 Zeichen ≈ 1 Token → 800–1600 Zeichen Ziel; Overlap ~120–240 Zeichen (≈ 30–60 Tokens).
**Mindestanforderung:** Keine Trennung innerhalb von Sätzen. Sicherstellung, dass immer an Satzenden gechunct wird
**Default für mindnet:** **~300 Tokens** + **~50 Tokens Overlap**; per `type` feinjustieren (siehe Tabelle).
--- ---
## 5) Semantische Regeln je Strukturelement ## 5) Semantische Regeln je Strukturelement
- **Überschriften (H2/H3)**: new chunk start; speichere `section_path` (z. B. `/Kontext/Beobachtung`). - **Überschriften**: vorzugsweise an H2/H3 trennen; H1 meist Dokumenttitel → Teil der Frontmatter.
- **Absätze**: Primäre Untereinheiten; wenn Zusammenfassung + Beispiel direkt folgen, zusammen lassen. - **Absätze**: primäre Trennkandidaten.
- **Listen**: Jeder **Listeneintrag** bleibt zusammen mit seinem einleitenden Satz (falls vorhanden). Große Listen → in **logische Blöcke** (5–8 Items) splitten. - **Listen**: zusammenhängende Gruppe als ein Chunk, wenn sie einen semantischen Block bilden.
- **Codeblöcke**: Nicht splitten; ggf. separater Chunk, **aber** im Retrieval **downweighten** (optional). - **Codeblöcke**: niemals splitten; Code bleibt in einem Chunk.
- **Zitate/Blockquotes**: zusammenhalten; Quelle im `references_meta` anreichern (falls Link vorhanden). - **Zitate**: ab 2+ Zeilen als eigener Chunk.
- **Tabellen**: als ein Chunk; zusätzlich **Plain-Text-Extrakt** (Header + 1–2 Zeilen) in `summary` für Retriever, falls Modelle Tabellen schlechter verarbeiten. - **Bilder/Anhänge**: Referenzen im Text belassen; Pfade relativ halten.
--- ---
## 6) Normalisierung & Preprocessing ## 6) Normalisierung & Preprocessing
- **Nicht embedden:** YAML-Frontmatter (aber spezifische Felder als `metadata.*` mitschreiben: `type`, `tags`, `area`, `project`, `priority`, `people`, `aliases`). - **Zeilenenden**: `\r\n` → `\n`, trailing spaces trimmen (nur für Hashing, nicht für Anzeige).
- **Bereinigen:** führende/trailing Spaces, Mehrfach-Leerzeilen → 1; Unicode-NFKC; Zeilenenden normalisieren. - **Whitespace**: mehrfach-Blankzeilen reduzieren (optional, Hash-Modus beachten).
- **Bewahren:** Markdown-Semantik (Überschriften-Hashes, Listenpräfixe, Codefences) **im Text beibehalten**, damit RAG-Antworten sauber zitieren können. - **Links**: `[[Titel|id]]` zu `(display="Titel", target_id="id")` normalisieren.
- **Sprachhinweis:** `lang` heuristisch bestimmen (DE/EN/…); in `metadata.lang` ablegen → später für sprachspezifische Embeddings nützlich. - **Pfade**: `path` im Payload **zwingend relativ** (Backslashes → Slashes).
- **Stop-Abschnitte:** „Mögliche Verbindungen“ am Ende **separat** chunken (nur Links), um Link-Graph sauber zu extrahieren.
--- ---
## 7) Edge-Modell (Graph) ## 7) Edge-Modell (Graph)
- **Chunk → Note:** `belongs_to(note_id)` (obligatorisch). - **Chunk → Note:** `belongs_to(note_id)` (obligatorisch; Edge-Payload enthält zusätzlich `note_id` als Owner-Note).
- **Chunk → Chunk (gleiche Note):** `prev`, `next` (lineare Leserichtung). - **Chunk → Chunk (gleiche Note):** `prev`, `next` (symmetrisch für lineare Navigation; beide Richtungen werden erzeugt).
- **Note/Chunk → Note:** `references(target_id)` aus `[[Wikilinks]]` & Markdown-Links; optional `related` (schwach). - **Chunk → Note:** `references(target_id)` aus `[[Wikilinks]]` oder Markdown-Links im Chunk-Text (Standard; *Chunk-Scope*).
- **Backlink:** systemisch generiert: inverse Kante `backlink`. - **Note → Note:** `backlink(target_id)` automatisch generiert, dedupliziert pro Note (*Note-Scope*).
- **Sektionen:** `has_section(note_id, section_path)` (optional, für Navigations-UI). - **Optional:** `references:note` (Note-Scope-References) per Flag/ENV aktivierbar; **Default = aus**, um Doppelzählungen zu vermeiden.
- **Task-Spezialfälle:** `depends_on`, `assigned_to(person-id)` bleiben **Note-Level** (nicht Chunk-Level). - **Unresolved:** Wenn `target_id` nicht existiert, wird eine Kante mit `status: "unresolved"` angelegt (später durch Resolver/Agent heilbar).
--- ---
@@ -100,26 +93,49 @@ Entwickle eine robuste, parser-freundliche **Chunking-Strategie** für Markdown-
"project": "project-mindnet", "project": "project-mindnet",
"tags": ["area/mindnet","type/thought","topic/yaml"], "tags": ["area/mindnet","type/thought","topic/yaml"],
"chunk_index": 2, "chunk_index": 2,
"char_start": 1240, "char_start": 1024,
"char_end": 2012, "char_end": 1789,
"token_count": 305,
"section_title": "Begründung / Details", "section_title": "Begründung / Details",
"section_path": "/Begründung / Details", "section_path": "Begründung / Details",
"lang": "de", "neighbors": {"prev": "…#c01", "next": "…#c03"},
"wikilinks": ["concept-vektorsuche-qdrant","source-obsidian-properties"], "wikilinks": ["concept-yaml-styleguide"],
"external_links": [], "references": [{"kind":"wikilink", "target_id":"concept-yaml-styleguide"}],
"references": [ "text": "… ursprünglicher Chunk-Text …"
{"target_id": "concept-vektorsuche-qdrant", "kind": "wikilink"}
],
"neighbors": {"prev": "#c01", "next": "#c03"},
"created_at": "2025-09-02T18:35:00+02:00"
} }
} }
**Collection-Einstellungen (Empfehlung)** **Point (Note)**
- `distance`: `Cosine` (gemischte Textlängen)
- `vectors`: 384–1024 Dim (abh. Embedding-Modell) {
- `hnsw_ef_construct`: 128–256; `m`: 16–32 (Workload-abhängig) "id": "20250902-1830-thought-yaml-recall",
"vector": [/* optional Nullvektor oder Zentroid */],
"payload": {
"note_id": "20250902-1830-thought-yaml-recall",
"title": "Gedanke: Einheitliche YAML-Standards steigern Recall",
"type": "thought",
"status": "draft",
"created": "2025-09-02",
"updated": "2025-09-02",
"path": "10_thoughts/20250902-1830-thought-yaml-recall.md",
"tags": ["area/mindnet","type/thought","topic/yaml"],
"hash_fulltext": "sha256:…",
"fulltext": "… gesamter Body für verlustfreie Rekonstruktion …",
"references": ["concept-yaml-styleguide"] // Fallback für Note-Level-Backlinks
}
}
**Edges (Payload; neues Schema)**
{
"kind": "references" | "backlink" | "belongs_to" | "prev" | "next",
"source_id": "<chunk_id|note_id>",
"target_id": "<note_id|chunk_id>",
"scope": "chunk" | "note",
"note_id": "<owner-note-id>", // neu: für schnelles Filtern/Purge
"status": "ok" | "unresolved" // optional
}
**Performance-Hinweis (Qdrant):** Für schnelle Filter/Deletes Payload-Indizes anlegen: **edges** → `kind`, `scope`, `source_id`, `target_id`, `note_id`; **chunks** → `note_id`, `chunk_index`; **notes** → `note_id`.
--- ---
@@ -136,79 +152,53 @@ Entwickle eine robuste, parser-freundliche **Chunking-Strategie** für Markdown-
blocks = group_blocks(sec, keep_code=True, keep_lists=True) blocks = group_blocks(sec, keep_code=True, keep_lists=True)
for group in soft_wrap(blocks, target_tokens=target_size(meta["type"]), for group in soft_wrap(blocks, target_tokens=target_size(meta["type"]),
max_tokens=max_size(meta["type"])): max_tokens=max_size(meta["type"])):
raw_chunks.append(render_markdown(group)) raw_chunks.append(render_md(group))
chunks = apply_overlap(raw_chunks, overlap_tokens=overlap_size(meta["type"])) chunks = apply_overlap(raw_chunks, overlap_tokens=overlap(meta["type"]))
chunks = trim_whitespace(chunks) chunks = normalize_chunks(chunks) # trim, fix code fences, etc.
# link extraction # IDs & Nachbarn
for i, ch in enumerate(chunks): for i, ch in enumerate(chunks, start=1):
ch.payload.update({ ch.id = f"{meta['id']}#c{i:02d}"
"wikilinks": extract_wikilinks(ch.text), ch.index = i
"external_links": extract_md_links(ch.text), ch.neighbors_prev = chunks[i-2].id if i > 1 else None
"references": [{"target_id": t, "kind": "wikilink"} for t in extract_wikilinks(ch.text)], ch.neighbors_next = chunks[i].id if i < len(chunks) else None
"neighbors": {"prev": f"#c{i-1}" if i>0 else None,
"next": f"#c{i+1}" if i<len(chunks)-1 else None}
})
# attach metadata # Wikilinks je Chunk
for idx, ch in enumerate(chunks): for ch in chunks:
ch.id = f'{meta["id"]}#c{idx:02d}' ch.wikilinks = extract_wikilinks(ch.text)
ch.payload |= minimal_payload_from_meta(meta, file_path, idx, ch)
return chunks return chunks
**Hinweise zur Implementierung**
- **Tokenizer**: gleiche Tokenizer-Funktion für **Längensteuerung** und **Embedding** nutzen (Leak vermeiden).
- **Overlap** implementieren auf **Satz-/Absatzebene**; notfalls anhand Token-Fenster (kein Wort-Cut).
- **Heuristik** für `target_size`/`overlap_size` per `type` (siehe Tabelle).
- **Später**: Re-Chunking ermöglichen (idempotente Re-Runs), Chunk-IDs stabil halten (Index + Hash über `section_path + first_64_tokens`).
--- ---
## 10) Einbettung (Embeddings) ## 10) Einbettung (Embeddings)
- **Standard:** nur `chunk.text` embedden (ohne YAML), **aber**: - Modell: MiniLM/all-MiniLM-L6-v2 (384d) oder E5 (besseres Retrieval, ggf. multilingual).
- `aliases`, `title` können als **synthetischer Kontext** *vorangestellt* werden (konkateniert, durch Trennzeichen), falls Recall für Synonyme wichtig ist. - **Note-Embeddings** optional (Zentroid der Chunks).
- **Mehrsprachigkeit:** pro Chunk die Sprache detektieren; ggf. **mehrsprachige Modelle**/Pipelines verwenden. - **Hashing für Change-Detection** (Importer):
- **Code-Gewichtung:** optional zweite Vektor-Spur für Code (separate Collection) falls viel Technik. - `MINDNET_HASH_MODE = body|frontmatter|body+frontmatter` (Default: `body`)
- `MINDNET_HASH_NORMALIZE = canonical|none` (Default: `canonical`)
--- ---
## 11) Qualitätssicherung ## 11) Qualitätssicherung
- **Unit-Tests**: Gold-Notes mit erwarteten Section-Splits und Link-Graph. - **Zähler**: `notes/chunks/edges` je Lauf prüfen.
- **Metrics**: Retrieval-Eval (nDCG@k, Recall@k) auf internen QA-Fragen. - **Edge-Invarianten**:
- **Linting**: Pre-commit prüft Pflichtfelder & Link-Integrität (IDs, Dateinamen, Wikilinks). - `belongs_to == #Chunks`
- `next == prev == Σ(max(chunks_in_note-1, 0))`
- `references (chunk) == Σ(Chunk-Wikilinks)`
- `backlink == Σ(eindeutige Wikilinks je Note)`
- **Unresolved**: sollten durch Resolver-Jobs über Zeit abnehmen.
- **Roundtrip-Test**: Import → Export → Diff; exakt rekonstruierbare Bodies.
--- ---
## 12) Deliverables ## 12) Deliverables
1. **Python-Modul** `mindnet_chunker/` (Parser, Chunker, Link-Extractor, Qdrant-Client). - Code: Parser, Chunker, Importer, Exporter, Edges.
2. **CLI** `mindnet-chunk` (stdin→stdout, oder Datei→NDJSON). - Schemas: `note.schema.json`, Payload-Layouts.
3. **Docs**: README mit Schema & Beispielen; Tests + Fixtures. - Tests: Mini-Vault (`scripts/make_test_vault.py`), Audit/Validate.
--- ---
## 13) Prompt für neues Chatfenster (kopieren & einfügen) ## 13) Prompt für neues Chatfenster (kopieren & einfügen)
*(Unverändert)*
**Projekt:** mindnet Wissensnetzwerk
**Rolle:** Du bist mein Assistent für NLP-Strategien.
**Ziel:** Hilf mir, eine robuste Chunking-Strategie für Markdown-Notizen zu entwickeln, die später in Qdrant gespeichert werden.
**Anforderungen:**
- Nutze das YAML-Frontmatter-Schema und die Strukturregeln aus `knowledge_design.md`. (Pflichtfelder, Abschnitts-Konventionen, Edge-Typen)
- Definiere optimale Chunkgrößen (Tokens) nach Notiz-Typ, inkl. **Overlap-Empfehlungen**.
- Beschreibe, wie **logische Abschnitte** (Überschriften/Absätze/Listen/Code) als Grenzen dienen.
- Erkläre das **Edge-Modell** zwischen **Chunks** und **Notizen** (`belongs_to`, `references`, `backlink`, `prev/next`).
- Ergebnis: ein **konkretes Konzept + Python-Outline**, das ich direkt implementieren kann (inkl. Datenmodell für Qdrant).
**Kontext zum System:**
- IDs/Dateinamen/Tags gemäß `knowledge_design.md`.
- Zielgröße pro Chunk ~**300 Tokens**, **Overlap ~50 Tokens** als Default; per `type` feinjustiert (Tabelle).
- YAML wird **nicht** in die Embeddings gemischt; ausgewählte Felder als `payload`.
Bitte liefere:
1) Zusammenfassung der Strategie,
2) Tabelle mit Größen/Overlaps,
3) Python-Pseudocode für Chunker,
4) Qdrant-Payload-Beispiel,
5) Test-Plan kurz.
+367 -299
View File
@@ -3,9 +3,9 @@ title: "mindnet – Knowledge Design"
id: "design-knowledge-architecture" id: "design-knowledge-architecture"
type: "guide" type: "guide"
status: "active" status: "active"
version: "1.2.0" version: "1.3.0"
created: 2025-09-02 created: 2025-09-02
updated: 2025-09-02 updated: 2025-09-09
tags: ["type/guide","area/mindnet","topic/obsidian","topic/knowledge-architecture"] tags: ["type/guide","area/mindnet","topic/obsidian","topic/knowledge-architecture"]
owner: "Ich" owner: "Ich"
--- ---
@@ -15,422 +15,490 @@ owner: "Ich"
## 1. Gesamtziel, Anspruch & Nutzen ## 1. Gesamtziel, Anspruch & Nutzen
**Ziel:** **Ziel:**
*mindnet* ist ein persönliches Wissensnetzwerk, das **alle** relevanten Inhalte – Gedanken, Erfahrungen, Aufgaben, Projekte, Quellen, Personen, Meetings, Tagebuch/Journal, Wendepunkte und Leitbilder – **einheitlich** in Markdown + YAML ablegt. Es bildet einen **Spiegel der Persönlichkeit** (Werte, Überzeugungen, Erlebnisse) und ist zugleich so strukturiert, dass Tools (Dataview, Embeddings, Vektorsuche/Qdrant, Agenten) es **maschinenlesbar** nutzen können. *mindnet* ist ein persönliches Wissensnetzwerk, das **alle** relevanten Informationen über mein Leben, meine Werte, Projekte, Erfahrungen, Pläne und Erkenntnisse **strukturiert** erfasst. Es bleibt **portabel** (Markdown + YAML), ist **parser-freundlich**, und so gestaltet, dass Tools (Obsidian + Dataview, Embeddings/Vektorsuche via Qdrant, Agenten) es **maschinenlesbar** nutzen können.
**Anspruch an die Struktur:** **Anspruch an die Struktur:**
- **Stabil**: robuste IDs, deterministische Dateinamen, konsistente Feldnamen - **Stabil**: robuste IDs, deterministische Dateinamen, konsistente Feldnamen
- **Atomar**: ein Kerninhalt pro Datei (keine Sammelcontainer) - **Atomar**: eine Kernaussage/ein zentrales Thema pro Datei (keine Sammelcontainer)
- **Erweiterbar**: neue Typen (z. B. `milestone`, `manifesto`) jederzeit möglich - **Erweiterbar**: neue Typen jederzeit möglich (ohne Migrationsschmerz)
- **Portabel**: reines Markdown + YAML → funktioniert in Obsidian, Git und Parsern - **Portabel**: pures Markdown + YAML → funktioniert in Obsidian, Git, Parsern
- **Vernetzbar**: systematische Links/Backlinks erzeugen ein sinnvoll navigierbares Netz - **Vernetzbar**: systematische Links/Backlinks bilden ein navigierbares Wissensnetz
- **Parser-freundlich**: wiederkehrende Abschnittsüberschriften; Felder/Enums klar definiert - **Parser-freundlich**: wiederkehrende Abschnittsüberschriften, klare Enums
**Späterer Nutzen / Einsatzzwecke:** **Nutzen / Einsatzzwecke:**
- **Schnelles Wiederfinden**: Dataview-Abfragen, Filter, Dashboards - **Schnelles Wiederfinden**: Dataview-Abfragen, Filter, Dashboards
- **Selbstreflexion & Entwicklung**: persönliche Werte, Wendepunkte, Kinderentwicklung, Lernpfade - **LLM-gestütztes Arbeiten**: Q&A mit Kontext-Zitaten aus Chunks (RAG)
- **Agenten**: Vorschläge für Verbindungen/Struktur; Auflösen von „unresolved links“
- **Projektnavigation**: Aufgabenbeziehungen, Abhängigkeiten
- **Langfristiges Gedächtnis**: Lebens-/Projektchronik (rückblickend und planend)
- **Automatisierung**: Vektor-Index (Qdrant), Embeddings, LLM-Q&A, Agenten-Workflows - **Automatisierung**: Vektor-Index (Qdrant), Embeddings, LLM-Q&A, Agenten-Workflows
- **Langfristiges Gedächtnis**: eigene Lebens-/Projektchronik reproduzierbar pflegen
- **Aufgaben-/Projektsteuerung**: im selben System, vernetzt mit Kontextwissen
--- ---
## 2. YAML-Frontmatter-Schema ## 2. YAML-Frontmatter-Schema
> **Pflichtfelder:** `title`, `id`, `type`, `status`, `created`, `tags` > **Pflichtfelder:** `title`, `id`, `type`, `status`, `created`, `tags`
> **Empfohlen:** `updated`, `area`, `project`, `priority`, `aliases` (u. a.) > **Empfohlen:** `updated`, `area`, `project`, `priority`, `aliases`, `lang`, `people`, `depends_on`, `source` u. a.
### 2.1 Feldübersicht ### 2.1 Feldübersicht
| Feld | Typ | Bedeutung | Beispiel(e) | | Feld | Typ | Bedeutung |
|---------------------|-------------------------------|---------------------------------------------------------------------------|------------------------------------------------------------------------------| |--------------------|-------------------------------|---------------------------------------------------------------------------|
| `title` | string | Menschlich lesbarer Titel | `"Vektorsuche in Qdrant"` | | `title` | string | Menschlich lesbarer Titel |
| `id` | string (slug/identifier) | **Stabile** technische ID (nie umbenennen) | `"20250902-1710-thought-obsidian-struktur"`, `"concept-persoenliches-leitbild"` | | `id` | string (slug/identifier) | **Stabile** ID; referenzierbar über Wikilinks |
| `type` | enum | Notiz-Typ | `thought`, `experience`, `task`, `project`, `source`, `concept`, `person`, `meeting`, `journal`, `milestone` | | `type` | enum | `concept`, `thought`, `experience`, `task`, `project`, `journal`, `person`, `meeting`, `milestone`, … |
| `status` | enum | Lebenszyklus | `idea`, `draft`, `active`, `paused`, `blocked`, `done`, `archived` | | `status` | enum | `draft` \| `active` \| `done` \| `archived` |
| `created` | date/datetime | Erstellzeitpunkt | `2025-09-02` oder `2025-09-02T17:10:00+02:00` | | `created` | date | Erstellungsdatum (ISO) |
| `updated` | date/datetime | Letzte inhaltliche Änderung | `2025-09-02T18:05:00+02:00` | | `updated` | date | Letzte Änderung (ISO) |
| `tags` | string[] | Schlagwörter gemäß Taxonomie | `["area/mindnet","topic/obsidian","type/thought"]` | | `area` | string | Themen-/Lebensbereich (z. B. „mindnet“, „gesundheit“, „familie“) |
| `area` | enum/string | Lebens-/Arbeitsbereich | `mindnet`, `family`, `karate`, `travel`, `health`, `home-automation`, … | | `project` | string | Projekt-/Arbeitskontext |
| `role` | string | Rolle/Hut (Filter) | `"father"`, `"researcher"`, `"project-owner"` | | `tags` | list<string> | Taxonomische Tags (präfixiert, s. Abschnitt 4) |
| `project` | string | Zugehöriges Projekt (ID oder sprechend) | `"project-mindnet"` | | `aliases` | list<string> | Alternative IDs/Titel (Slug-Resolver) |
| `priority` | int (1–5) | 1 = hoch, 5 = niedrig | `2` | | `lang` | string | Sprache, optional (z. B. `de`, `en`) |
| `effort_min` | int | Aufwand in Minuten (für `task`) | `90` | | `priority` | enum/int | Priorität, optional (`low`/`med`/`high` oder 1–5) |
| `due` | date | Fälligkeit (Task/Projekt) | `2025-09-10` | | `due`, `effort_min`| date/int | Für Aufgaben/Projekte (Fälligkeit, Aufwand in Minuten) |
| `start` | date | geplanter Start (Task/Projekt) | `2025-09-05` | | `people` | list<string> | Beteiligte Personen/IDs |
| `people` | string[] (Wikilinks erlaubt) | Beteiligte Personen | `["Ich","[[person-kathie]]"]` | | `depends_on` | list<string> | Abhängigkeiten auf andere IDs |
| `location` | string | Ort/Platz | `"Home Office"`, `"München"` | | `source` | string | Quelle (Artikel, Buch, Video, …) |
| `source_url` | url | Kanonische URL (für `source`) | `"https://qdrant.tech/docs/"` | | `slug` | string | Stabiler Pfad-/Dateiname, falls abweichend |
| `authors` | string[] | Autoren (für `source`) | `["Jane Doe"]` |
| `published` | date | Veröffentlichungsdatum (für `source`) | `2024-11-20` |
| `accessed` | date | Zugriffsdatum (für `source`) | `2025-09-02` |
| `aliases` | string[] | Alternative Namen/Titel | `["Manifest","Leitbild"]` |
| `related_ids` | string[] | ID-basierte Verknüpfungen | `["concept-persoenliches-leitbild"]` |
| `embedding_exclude` | boolean | Von Embeddings/Index ausschließen | `false` |
### 2.2 Konventionen ### 2.2 Konventionen
- **IDs:** entweder Zeitstempel-basiert (`YYYYMMDD-HHMM-type-slug`) **oder** stabile, sprechende (`concept-*`, `project-*`, `person-*`). - `id` ist **menschenlesbar** (Slug), eindeutig im Vault; `aliases` dienen als Fallback-IDs.
- **Datums-/Zeitformat:** ISO 8601, Zeiten möglichst mit TZ (z. B. `+02:00`). - Datumsformat: ISO `YYYY-MM-DD`.
- **Felder:** klein geschrieben; zusammengesetzte Felder in `snake_case`. - Keine duplizierten Tags; Präfixe nutzen (`area/…`, `type/…`, `topic/…`).
- Frontmatter nur Fakten/Metadaten, **keine** ausufernden Inhalte (die stehen in den Body-Abschnitten).
### 2.3 Minimalbeispiel Frontmatter ### 2.3 Minimalbeispiel Frontmatter
---
title: "Kurzer, klarer Gedanke"
id: "20250902-1715-thought-klarer-gedanke"
type: "thought"
status: "idea"
created: 2025-09-02T17:15:00+02:00
updated: 2025-09-02T17:15:00+02:00
tags: ["area/mindnet","type/thought","topic/obsidian"]
---
## 2.4 Enum-Werte title: "Gedanke: YAML-Standards"
id: thought-yaml-standards
type: thought
status: draft
created: 2025-09-02
updated: 2025-09-09
area: mindnet
project: project-mindnet
tags: [area/mindnet, type/thought, topic/yaml]
aliases: [yaml-gedanken]
lang: de
Zur Sicherstellung der Konsistenz werden für bestimmte Felder feste Wertemengen (Enums) verwendet: ### 2.4 Enum-Werte (Beispiele)
- `type`: `concept`, `thought`, `experience`, `task`, `project`, `journal`, `person`, `meeting`, `milestone`, `manifesto`
- **type** - `status`: `draft`, `active`, `done`, `archived`
- `idea` – spontane Gedanken, Inspirationen - `priority`: `low`, `med`, `high` oder 1–5
- `experience` – persönliche Erfahrungen, Reflexionen
- `task` – konkrete Aufgaben
- `project` – Projekte, bestehend aus mehreren Tasks
- `concept` – abstrakte Konzepte, Modelle, Methoden
- `milestone` – wichtige Ereignisse oder Wendepunkte
- `person` – Personen (z. B. Kontakte, Vorbilder)
- `meeting` – Besprechungen, Treffen, Gespräche
- `resource` – externe Quellen (Artikel, Bücher, Links)
- `journal` – Tagebuchnotizen
- **status**
- `open`
- `in-progress`
- `done`
- `blocked`
- `canceled`
- **priority**
- `low`
- `medium`
- `high`
- **area** (Beispiele – erweiterbar)
- `personal`
- `work`
- `family`
- `karate`
- `health`
- `finance`
--- ---
## 3. Dateinamen-Konventionen ## 3. Dateinamen-Konventionen
- `YYYY-MM-DD_title.md` oder `slug.md`.
> Keine Sonderzeichen wie `: / \` im Dateinamen. - Pfade **relativ** zum Vault; keine absoluten Pfade (einheitliche Slashes `/`).
- Verzeichnisse nach eigener Ordnung, empfohlen: `10_thoughts/`, `20_concepts/`, `30_projects/`, `40_journal/`, …
- **Zeitbasierte Notizen (Gedanken, Journal, tagesgebundene Einträge):**
`YYYYMMDD-HHMM-<type>-<slug>.md`
Beispiel: `20250902-1710-thought-obsidian-struktur.md`
- **Zeitunabhängige Wissensknoten (Konzepte, Personen, Projekte, Leitbild):**
`<type>-<slug>.md`
Beispiele: `concept-vektorsuche-qdrant.md`, `project-mindnet.md`, `person-kathie.md`, `concept-persoenliches-leitbild.md`
- **Ordnerstruktur (Empfehlung):**
00_inbox/
10_thoughts/
20_experiences/
30_projects/
31_tasks/
40_concepts/
50_sources/
60_people/
70_meetings/
80_journal/
90_templates/
_attachments/
_meta/
--- ---
## 4. Tagging-Regeln & Taxonomie ## 4. Tagging-Regeln & Taxonomie
- Präfixe verwenden: `area/…`, `type/…`, `topic/…`, `status/…`.
- **Hierarchische Tags:** - Möglichst **keine** losen Ein-Wort-Tags ohne Präfix (verhindert Wildwuchs).
- `area/*` – Lebens-/Arbeitsbereiche: `area/mindnet`, `area/family`, `area/karate`, `area/health`, … - Für Dataview konsistente Namespaces beibehalten (z. B. `topic/llm`, `topic/lernen`).
- `type/*` – optionaler Spiegel von `type`: `type/thought`, `type/experience`, …
- `topic/*` – thematische Schwerpunkte: `topic/obsidian`, `topic/yaml`, `topic/qdrant`, `topic/werte`, …
- optional: `place/*`, `person/*`, `level/*` (z. B. `person/rouven`, `person/rohan`)
- **Regeln:**
- Jede Notiz hat **mindestens ein** `area/*`.
- `topic/*` sparsam, aber konsistent; ein Mapping in `_meta/tags.md` pflegen.
- Möglichst **keine** losen Ein-Wort-Tags ohne Präfix (verhindert Wildwuchs).
--- ---
## 5. Backlink- & Link-Regeln ## 5. Backlink- & Link-Regeln
- **Wikilinks** verwenden: `[[stabile-id-oder-dateiname]]` - **Wikilinks**: `[[stabile-id]]` oder `[[Titel|stabile-id]]`
- Im **Fließtext** bei erster Nennung verlinken; am **Ende** die Sektion **„Mögliche Verbindungen“** pflegen: - Im **Fließtext** verlinken (Forwardlinks); am **Ende** optional **„Mögliche Verbindungen“** redaktionell pflegen:
## Mögliche Verbindungen ## Mögliche Verbindungen
- [[concept-persoenliches-leitbild]] - [[concept-persoenliches-leitbild]]
- [[project-mindnet]] - [[project-mindnet]]
- **Linkrichtung:** „aufwärts“ (Detail → Konzept/Leitbild) und „seitwärts“ (verwandte Knoten). - **Linkrichtung:** „aufwärts“ (Detail → Konzept/Leitbild) und „seitwärts“ (verwandte Knoten).
- Optional zusätzlich **ID-Relationen** im YAML (`related_ids`) für Parser. - Optional zusätzliche **ID-Relationen** im YAML (`related_ids`) für Parser.
- **Unresolved Links:** Links auf noch nicht existierende Ziele sind zulässig; der Importer schreibt `status: unresolved`-Edges (später durch Resolver/Agent heilbar).
## 5.1 Edge-Typen ---
Beziehungen zwischen Notizen, Chunks und Objekten werden als **Edges** gespeichert. Jeder Edge erhält einen `type` und optionale `meta`-Informationen (z. B. Gewichtung, Richtung). ## 5.1 Edge-Typen & Semantik (Graph)
- **belongs_to** Beziehungen werden als **Edges** mit neuem Payload-Schema gespeichert:
Chunk → Note (ein Chunk gehört zu genau einer Note)
- **references** kind : "belongs_to" | "next" | "prev" | "references" | "backlink" | "unresolved"
Note → Note (eine Notiz verweist auf eine andere) source_id : ID des Quellknotens (Chunk- oder Note-ID)
target_id : ID des Zielknotens (Note- oder Chunk-ID)
scope : "chunk" | "note"
note_id : Owner-Note des Edges (für schnelles Filtern/Purge)
status : optional, z. B. "unresolved"
- **backlink** **Kantenarten**
Automatisch generiert: Gegenkante von `references` - **belongs_to** — *Chunk → Note*
Jeder Chunk gehört zu **genau einer** Note. *Scope:* `chunk`.
- **depends_on** - **prev / next** — *Chunk → Chunk*
Task → Task oder Task → Project (Aufgabe hängt von anderer ab) Lineare Reihenfolge innerhalb derselben Note; **symmetrisch** angelegt (d. h. `prev` und `next` konsistent). *Scope:* `chunk`.
- **assigned_to** - **references** — *Chunk → Note*
Task → Person (eine Aufgabe ist einer Person zugeordnet) Aus `[[Wikilinks]]` oder Markdown-Links im **Chunk-Text** (präzise Herkunft). *Scope:* `chunk`.
- **discussed_in** - **backlink** — *Note → Note*
Note/Concept → Meeting (ein Thema wurde in einem Meeting behandelt) Automatisch generierte Gegenkante zu `references` (pro Note **dedupliziert**). *Scope:* `note`.
- **authored_by** - **unresolved**
Note → Person (z. B. externer Autor oder eigene Urheberschaft) Edge mit `status: "unresolved"`, wenn `target_id` (noch) nicht existiert. Wird später vom Resolver/Agent ersetzt.
- **related** - **Optional:** `references:note` — *Note → Note*
Generische Relation für schwache Assoziationen Zusätzliche Forwardlinks auf Note-Ebene; standardmäßig **deaktiviert**, um Doppelzählungen mit `references` (Chunk-Scope) zu vermeiden. Aktivierung per ENV/Flag möglich.
**Performanzhinweise (Qdrant)**
- Edges werden dedupliziert über `(kind, source_id, target_id, scope)`.
- `note_id` ist Pflichtfeld im Edge-Payload (Owner-Note).
- Payload-Indizes für Qdrant anlegen:
edges : kind (KEYWORD), scope (KEYWORD), source_id (KEYWORD), target_id (KEYWORD), note_id (KEYWORD)
chunks : note_id (KEYWORD), chunk_index (INTEGER)
notes : note_id (KEYWORD)
--- ---
## 6. Abschnitts-Konventionen im Body ## 6. Abschnitts-Konventionen im Body
Einheitliche Überschriften erleichtern spätere Parser und Abfragen. Einheitliche Überschriften erleichtern Parser, Chunking und Abfragen. Typ-spezifische Empfehlungen:
- **Gedanke (`thought`)** - **Gedanke (`thought`)**
`## Zusammenfassung` · `## Begründung / Details` · `## Belege / Quellen` · `## Nächste Schritte` · `## Mögliche Verbindungen` `## Zusammenfassung` · `## Begründung / Details` · `## Belege / Quellen` · `## Nächste Schritte` · `## Mögliche Verbindungen`
- **Erfahrung (`experience`)** - **Erfahrung (`experience`)**
`## Kontext` · `## Beobachtung` · `## Interpretation` · `## Implikationen` · `## Mögliche Verbindungen` `## Kontext` · `## Beobachtung` · `## Interpretation` · `## Implikationen` · `## Mögliche Verbindungen`
- **Aufgabe (`task`)** - **Aufgabe (`task`)**
`## Checkliste` · `## Notizen` · `## Mögliche Verbindungen` `## Checkliste` · `## Notizen` · `## Nächste Schritte` · `## Mögliche Verbindungen`
- **Projekt (`project`)** - **Projekt (`project`)**
`## Scope` · `## Arbeitspakete` · `## Risiken & Gegenmaßnahmen` · `## Status / Fortschritt` · `## Mögliche Verbindungen` `## Scope` · `## Arbeitspakete` · `## Risiken & Gegenmaßnahmen` · `## Status / Fortschritt` · `## Mögliche Verbindungen`
- **Journal (`journal`)** - **Journal (`journal`)**
`## Tageszusammenfassung` · `## Highlights` · `## Gelernt / Notizen` · `## Mögliche Verbindungen` `## Tageszusammenfassung` · `## Highlights` · `## Learnings` · `## Mögliche Verbindungen`
- **Meeting (`meeting`)**
`## Agenda` · `## Notizen` · `## Entscheidungen` · `## Aufgaben` · `## Mögliche Verbindungen`
--- ---
## 7. Abbildung persönlicher Inhalte auf Typen ## 7. Abbildung persönlicher Inhalte auf Typen
- **Persönliches Leitbild** → `type: "concept"` (oder optional neuer Typ `manifesto`) **Richtlinien:**
Datei: `concept-persoenliches-leitbild.md` (zeitunabhängig) - Wähle den Typ nach **Hauptintention** (Definition, Gedanke, Beobachtung, Aufgabe, Projekt, …).
Verlinkt zu prägenden Erfahrungen und Wendepunkten. - **Konzepte** (`concept`): langlebige Definitionen, Prinzipien, Leitbilder.
- **Erfahrungen, die dich geprägt haben** → `type: "experience"` - **Gedanken** (`thought`): explorative Ideen, noch nicht stabil (können später bei Reife in `concept` überführt werden).
Je **eine** prägende Erfahrung pro Datei; klarer Kontext + Interpretation. - **Erfahrungen** (`experience`): Beobachtungen & Learnings aus der Praxis.
- **Wendepunkte im Leben** → `type: "milestone"` - **Aufgaben** (`task`): konkrete, umsetzbare To-dos mit `due`/`effort_min`.
Je Wendepunkt ein Knoten; verlinkt zu den auslösenden Erfahrungen. - **Projekte** (`project`): Ziele, Deliverables, Arbeitspakete, Abhängigkeiten.
- **Aktuelle Erfahrungen** → `type: "experience"`, `status: "active"` - **Journal** (`journal`): tagesbasierte Notizen, Reflexionen, Reiseberichte.
Bei Bedarf später in „prägende“ Erfahrungen überführen. - **Personen** (`person`): Kontakte, Profile, Bezüge, Gespräche.
- **Entwicklungsschritte der Kinder** → `type: "journal"` (chronologisch) **oder** `experience` (wenn es prägend ist); Tags `person/<name>`. - **Meetings** (`meeting`): Agenda, Notizen, Entscheidungen, Folgeaufgaben.
- **Tagebucheinträge** → `type: "journal"`; ein Eintrag pro Tag; tagesbasierte Dateinamen. - **Meilensteine** (`milestone`): wichtige Wendepunkte im Lebens-/Projektverlauf.
Damit entsteht ein **netzartiges Persönlichkeitsprofil** mit klaren Pfaden zwischen Werten (Leitbild), Ereignissen (Erfahrungen), Wendepunkten und fortlaufenden Beobachtungen (Journal).
--- ---
## 8. Beispiel-Notizen ## 8. Beispiel-Notizen
### 8.1 Gedanke (`thought`) ### 8.1 Gedanke (`thought`) – Beispiel
---
title: "Gedanke: Einheitliche YAML-Standards steigern Recall" **Frontmatter**
id: "20250902-1830-thought-yaml-recall"
type: "thought" title: "Gedanke: Übungen für tiefe Arbeit"
status: "idea" id: thought-deep-work-uebungen
created: 2025-09-02T18:30:00+02:00 type: thought
updated: 2025-09-02T18:30:00+02:00 status: active
tags: ["area/mindnet","type/thought","topic/yaml","topic/recall"] created: 2025-08-21
area: "mindnet" updated: 2025-09-05
project: "project-mindnet" area: lernen
aliases: [] project: project-self-improvement
--- tags: [area/lernen, type/thought, topic/fokus]
aliases: [deep-work-ideen]
lang: de
**Body (Ausschnitt)**
## Zusammenfassung ## Zusammenfassung
Konsistente YAML-Felder verbessern Filter, Dataview-Queries und Vektor-Retrieval. Kurze tägliche Routinen (z. B. Timer-Blöcke, Ablenkungslog) erhöhen meinen Fokus.
## Begründung / Details ## Begründung / Details
- Parser benötigen stabile Feldnamen (z. B. `type`, `status`). - 25–45 Min Timerblöcke mit 5 Min Pause
- Einheitliche Werte erleichtern Dashboards und Automationen. - Ablenkungen sofort notieren
- Abschluss-Log am Ende des Tages
## Mögliche Verbindungen
- [[concept-deep-work]]
- [[project-productivity-week]]
### 8.2 Konzept (`concept`) – Beispiel
**Frontmatter**
title: "Konzept: Deep Work"
id: concept-deep-work
type: concept
status: active
created: 2024-05-14
updated: 2025-08-01
area: lernen
tags: [area/lernen, type/concept, topic/fokus]
aliases: [konzept-tiefe-arbeit]
lang: de
**Body (Ausschnitt)**
## Definition
Tiefe Arbeit = kognitiv anspruchsvolle Arbeit ohne Ablenkung.
## Belege / Quellen ## Belege / Quellen
- [[source-obsidian-properties]] - Buch: Cal Newport – Deep Work
- [[concept-vektorsuche-qdrant]]
## Nächste Schritte
- [ ] `tags`-Mapping in `_meta/tags.md` erstellen
- [ ] Beispiel-Queries für Dataview hinterlegen
## Mögliche Verbindungen ## Mögliche Verbindungen
- [[project-mindnet]] - [[thought-deep-work-uebungen]]
- [[20250902-1730-task-yaml-standard-migration]]
### 8.2 Erfahrung (`experience`) ### 8.3 Aufgabe (`task`) – Beispiel
---
title: "Erfahrung: Journal → Erfahrung extrahieren erhöht Klarheit"
id: "20250902-1840-experience-journal-extraktion"
type: "experience"
status: "active"
created: 2025-09-02T18:40:00+02:00
updated: 2025-09-02T18:40:00+02:00
tags: ["area/personal","type/experience","topic/journal","topic/reflexion"]
area: "personal"
project: "project-mindnet"
---
## Kontext **Frontmatter**
Wiederkehrende Journaleinträge enthalten Rohmaterial für prägende Einsichten.
## Beobachtung title: "Task: Wochenplanung erstellen"
Wird Material regelmäßig zu `experience`-Knoten verdichtet, sind spätere Bezüge einfacher. id: task-week-planning
type: task
status: active
created: 2025-09-07
updated: 2025-09-07
due: 2025-09-11
effort_min: 45
area: organisation
project: project-productivity-week
tags: [area/organisation, type/task, topic/planung]
lang: de
## Interpretation **Body (Ausschnitt)**
Abstraktion + Verlinkung (z. B. auf [[concept-persoenliches-leitbild]]) erhöhen Nutzen und Wiederfindbarkeit.
## Implikationen
Pro Woche 15–30 Minuten „Verdichtungs-Review“ einplanen.
## Mögliche Verbindungen
- [[journal-20250902]]
- [[concept-persoenliches-leitbild]]
### 8.3 Aufgabe (`task`)
---
title: "Task: YAML-Standard in Altbeständen ergänzen"
id: "20250902-1850-task-yaml-migration"
type: "task"
status: "active"
created: 2025-09-02
updated: 2025-09-02
due: 2025-09-10
start: 2025-09-03
priority: 2
effort_min: 120
area: "mindnet"
project: "project-mindnet"
tags: ["area/mindnet","type/task","topic/migration"]
depends_on: []
---
## Checkliste ## Checkliste
- [ ] Triage: Notiz-Typ bestimmen - Ziele der Woche definieren
- [ ] Minimal-YAML ergänzen (Pflichtfelder) - 5 Fokusblöcke eintragen
- [ ] Dateinamen vereinheitlichen - 2 Lerneinheiten terminieren
- [ ] „Mögliche Verbindungen“ pflegen
## Notizen
Beginne mit zuletzt genutzten Notizen (Pareto 20/80).
## Mögliche Verbindungen ## Mögliche Verbindungen
- [[project-mindnet]] - [[project-productivity-week]]
- [[20250902-1830-thought-yaml-recall]] - [[thought-deep-work-uebungen]]
--- ---
## 9. Schrittweise Migration bestehender freier Notizen ## 9. Schrittweise Migration bestehender freier Notizen
**Phase A – Triage (schnell)** 1. **Frontmatter ergänzen** (min. `id`, `title`, `type`, `status`, `created`, `tags`).
1. Sichtung & **Typ** bestimmen (`type`). 2. **Abschnittsstruktur** an Typ anpassen (Konventionen s. Abschnitt 6).
2. **Minimal-YAML** einfügen (`title`, `id`, `type`, `status=draft`, `created≈Dateidatum`, `tags`). 3. **Wikilinks** im Body setzen (statt bloßer Erwähnungen).
3. **Dateiname** grob anpassen (Schema + Slug). 4. **Tags normalisieren** (Präfixe, Kleinschreibung, keine Dubletten).
5. **Aliases** angeben, falls Notiz zuvor unter anderem Namen existierte.
**Phase B – Strukturieren (fokussiert)** 6. **Testlauf**: Import (Dry-Run), danach Apply, Audit/Validate prüfen.
1. **Abschnitte** nach Typ-Template ergänzen.
2. **Zerlegen**: mehrere Gedanken/Ereignisse → je **eigene Datei**, ursprüngliche Datei wird zum **Index** mit Links.
3. **Verlinken**: relevante `[[Knoten]]` + **„Mögliche Verbindungen“** pflegen.
**Phase C – Verfeinern (bei Bedarf)**
1. **Status & Felder** pflegen (`status`, `priority`, `due`, `effort_min`).
2. **Tag-Harmonisierung**: Mapping-Tabelle pflegen (`_meta/tags.md`).
3. **Aliases** ergänzen (Such-/Linkvarianten).
**Priorisierung:** Starte mit **aktuellen & häufig genutzten** Notizen (Pareto-Prinzip), Altbestände nachziehen, wenn sie wieder gebraucht werden.
--- ---
## 10. Dataview-Beispiele (direkt nutzbar) ## 10. Dataview-Beispiele (direkt nutzbar)
**Offene Aufgaben dieser Woche (nach Priorität):** **Aktive Gedanken der letzten 30 Tage**
TABLE due, priority, effort_min TABLE title, created, updated, area
FROM "31_tasks"
WHERE type = "task" AND status != "done"
AND due >= date(today) - dur(1 week)
AND due <= date(today) + dur(1 week)
SORT priority ASC, due ASC
**Aktive Projekte mit Meilensteinen:**
LIST
FROM "30_projects"
WHERE type = "project" AND status = "active"
SORT priority ASC, file.ctime DESC
**Gedanken im Bereich mindnet, jüngste zuerst:**
TABLE created, status
FROM "10_thoughts" FROM "10_thoughts"
WHERE type = "thought" AND area = "mindnet" WHERE type = "thought" AND status = "active" AND created >= date(today) - dur(30 days)
SORT created DESC SORT updated DESC
LIMIT 50
**Quellen ohne `source_url` (Pflegebedarf):** **Offene Tasks mit Fälligkeit**
TABLE title, created TABLE title, due, effort_min, project, area
FROM "50_sources" FROM "30_tasks"
WHERE type = "source" AND (source_url = "" OR !source_url) WHERE type = "task" AND status = "active" AND due
SORT due ASC
**Konzepte je Topic**
TABLE title, area, tags
FROM "20_concepts"
WHERE contains(tags, "type/concept")
GROUP BY choice(regexreplace(join(filter(tags, (t) => startswith(t, "topic/")), ", "), "^topic/", ""))
**Verknüpfungskandidaten (redaktionell, nicht automatisch)**
*(Liste am Ende der jeweiligen Notiz in „Mögliche Verbindungen“)*
--- ---
## 11. Validierung & Pflege ## 11. Validierung & Pflege
- **Wöchentlicher Review-Slot (15–30 Min.):** - **Linter/Validator** prüfen Pflichtfelder und Wertebereiche (Enums, ISO-Datum).
- Neue Notizen triagieren (`type`, `status`, `area`) - **Resolver** löst `unresolved`-Edges, wenn neue Notizen/Aliases entstehen.
- 5 Alt-Notizen migrieren (YAML + Dateiname + Verlinkung) - **Idempotente Re-Imports**: Hash-Steuerung konfigurierbar:
- **Dataview-Checks:** fehlende `source_url`, offene Tasks, aktive Projekte, veraltete `status`. - `MINDNET_HASH_MODE`: `body` \| `frontmatter` \| `body+frontmatter` (Default: `body`)
- **Optional (technisch):** - `MINDNET_HASH_NORMALIZE`: `canonical` \| `none` (Default: `canonical`)
- **Pre-commit Hook**: prüft Pflichtfelder (`title`, `id`, `type`, `status`, `created`, `tags`) - **Edge-Invarianten** (Audit):
- **ID-Generator**: `YYYYMMDD-HHMM-type-slug` bei Neuanlage - `belongs_to == #Chunks`
- **Link-Linter**: prüft tote `[[Links]]` - `next == prev == Σ(max(chunks_in_note−1, 0))`
- `references (chunk) == Σ(Chunk-Wikilinks)`
- `backlink == Σ(eindeutige Wikilinks je Note)`
- **Roundtrip-Test**: Import → Export → Diff muss Body verlustfrei rekonstruieren.
--- ---
## 12. Versions- & Änderungsrichtlinien ## 12. Qdrant-Ablage & Indizes
- Dieses Dokument pflegt `version` & `updated`. **Collections**
- **Breaking Changes** (z. B. Feldumbenennungen) in `_meta/changelog.md` dokumentieren. - `{prefix}_notes` – Vektor optional (Nullvektor oder Zentroid), Payload inkl. Frontmatter & `fulltext`
- **Migrationen** (Tag-Refactorings, Typänderungen) als Skript oder Batch-Checkliste planen. - `{prefix}_chunks` – 384d Embedding je Chunk, Payload inkl. `text`, `chunk_index`, `note_id`
- `{prefix}_edges` – 1d Dummy-Vektor, Payload im neuen Schema (s. 5.1)
**IDs & Idempotenz**
- Deterministisch/UUIDv5 über stabile Schlüssel (`note_id`, `chunk_id = note_id#cNN`, `edge_id` aus `(kind, source_id, target_id, scope)`)
- Re-Imports erzeugen keine Duplikate (Upsert)
**Payload-Indizes (Performance)**
notes : note_id (KEYWORD)
chunks : note_id (KEYWORD), chunk_index (INTEGER)
edges : kind (KEYWORD), scope (KEYWORD), source_id (KEYWORD), target_id (KEYWORD), note_id (KEYWORD)
**Delete/Purge**
- Selektives Löschen in Edges/Chunks per `note_id`-Filter (schnell, sicher).
- `--sync-deletes` (geplant): Qdrant→Vault Diffs gezielt entfernen (mit Dry-Run).
--- ---
## 13. Typen-Kurzreferenz ## 13. LLM/RAG & Agenten – Arbeitsweise (Überblick)
- `thought` – Gedanke/These **Retriever (Hybrid)**
- `experience` – Beobachtung/Erfahrung mit Interpretation & Implikationen 1) **kNN (Chunks)** in Qdrant → Top-k Kandidaten (Semantik).
- `task` – umsetzbare Arbeitseinheit (mit `due`, `effort_min`, `priority`) 2) **Nachbarschafts-Expand** (1 Hop) über Edges (`belongs_to`, `references`, `backlink`) → zusätzliche Kontexte.
- `project` – Container für Ziele/Tasks/Meilensteine 3) **Rerank** (optional BM25/LLM-score).
- `source` – externe Quelle (Artikel, Buch, Video) 4) **Prompt** mit Zitaten/Belegen (Verweis auf `path` + Abschnittstitel).
- `concept` – definierter Begriff / Prinzip / Leitbild
- `person` – Bezugsperson/Kontakt **Agentisches Einordnen (neue Inputs)**
- `meeting` – Termin mit Agenda, Notizen, erzeugten Aufgaben - **Chunking + Embedding** → **kNN-Kandidaten**
- `journal` – Tagebuch-/Reiseeintrag (tagesbasiert) - Klassifikation (`type`, `area`, `project`) via Heuristik/LLM
- `milestone` – Wendepunkt / Meilenstein im Lebens-/Projektverlauf - Edge-Vorschläge: `references` (Semantik + geteilte Tags/Area), `belongs_to` (beste Einordnung)
- Falls kein Ziel existiert → `unresolved` erzeugen oder **Stub-Note** anlegen
- **Human-in-the-loop**: Vorschläge bestätigen, dann Commit via Importer
**Graph-Layer (optional, empfohlen)**
- Zusätzliche SQLite/Postgres-Tabellen `nodes/edges/aliases` für 2–3-Hop-Queries, Pfadsuche, Zählungen.
- Importer pflegt Qdrant **und** SQL (UPSERT).
- Graph-Features (Degree, Communities, optional PageRank) regelmäßig berechnen und als Felder in `notes.payload` speichern.
--- ---
## 14 Erweiterungen ## 14. Versions- & Änderungsrichtlinien
Zukünftige Typen möglich (z. B. decision, recommendation). - **Kleine Änderungen** direkt in der bestehenden Notiz (Frontmatter `updated` anpassen).
- **Große Strukturänderungen** (z. B. neuer Typ) als neue Notiz mit Verweis; alte Note verlinken/archivieren (`status: archived`).
- **IDs nie recyceln** (Konstanz für Referenzen und Edges).
- **Aliases** nutzen, wenn sich Titel/Slug ändert (Resolver kann beides auflösen).
- **Commit-Meldungen** im Git prägnant strukturieren:
- `feat(note): …` · `fix(frontmatter): …` · `chore(tags): …` · `refactor(structure): …`
Personalisierung durch zusätzliche Properties (values, goals) ---
## 15. Typen-Kurzreferenz
- **concept** — Definitionen, Leitbilder, Prinzipien
Empfohlene Abschnitte: *Definition*, *Beispiele*, *Belege*, *Mögliche Verbindungen*
- **thought** — Ideen, Entwürfe, Skizzen
Abschnitte: *Zusammenfassung*, *Details*, *Nächste Schritte*, *Mögliche Verbindungen*
- **experience** — Beobachtungen, Learnings
Abschnitte: *Kontext*, *Beobachtung*, *Interpretation*, *Implikationen*, *Mögliche Verbindungen*
- **task** — konkrete To-dos
Felder: `due`, `effort_min`; Abschnitte: *Checkliste*, *Notizen*, *Mögliche Verbindungen*
- **project** — Ziele, Deliverables, Arbeitspakete
Abschnitte: *Scope*, *Arbeitspakete*, *Risiken*, *Status*, *Mögliche Verbindungen*
- **journal** — tagesbasierte Einträge
Abschnitte: *Tageszusammenfassung*, *Highlights*, *Learnings*, *Mögliche Verbindungen*
- **person** — Kontakte, Profile
Felder: `people` (Selbst-/Fremd-ID), *Notizen*, *Mögliche Verbindungen*
- **meeting** — Termine, Protokolle
Abschnitte: *Agenda*, *Notizen*, *Entscheidungen*, *Aufgaben*, *Mögliche Verbindungen*
- **milestone** — Wendepunkte
Abschnitte: *Kontext*, *Bedeutung*, *Verknüpfungen*
---
## 16. Erweiterungen
- Neue Typen (z. B. `decision`, `recommendation`, `resource`) können ohne Bruch ergänzt werden.
- Personalisierung durch zusätzliche Properties (`values`, `goals`) in Frontmatter.
- Internationale Inhalte: `lang` pflegen, optional **mehrsprachige** Embeddings (z. B. mE5).
---
## 17. Anhang – Beispiele & Snippets
**Beispiel: YAML-Frontmatter für Projekt**
title: "Projekt: Produktivität Woche 37"
id: project-productivity-week
type: project
status: active
created: 2025-09-08
updated: 2025-09-09
area: organisation
tags: [area/organisation, type/project, topic/planung]
people: [ich]
depends_on: [concept-deep-work]
lang: de
**Beispiel: Redaktions-Sektion (keine Kanten-Erzeugung)**
## Mögliche Verbindungen
- [[concept-wochenplanung]]
- [[thought-deep-work-uebungen]]
- [[journal-2025-09-08]]
**CLI: Import & Audit**
# Dry-Run Import
python3 -m scripts.import_markdown --vault ./vault
# Apply mit strenger Hash-Erkennung (jede Änderung zählt)
python3 -m scripts.import_markdown --vault ./vault --apply --hash-normalize none
# Audit Edges vs. Erwartungen
python3 -m scripts.audit_edges_vs_expectations --vault ./vault
---
## 18. Glossar
- **Alias**: alternativer Name/Slug, der auf dieselbe Note verweist
- **Backlink**: automatisch erzeugte Gegenkante zu `references` (Note-Scope)
- **Chunk**: semantisch sinnvoller Textabschnitt einer Note, inkl. Embedding
- **Owner-Note**: Note, zu der ein Edge gehört (`note_id` im Edge-Payload)
- **Resolver**: Prozess/Script, das `unresolved`-Edges bei späterer Ziel-Existenz heilt
---
## 19. Verweise
- `chunking_strategy.md` – Details zu Chunkgrößen, Overlaps, Abschnittsregeln
- `schemas/note.schema.json` – Validierung von Frontmatter‐Feldern
- Import/Export-Skripte: `scripts/import_markdown.py`, `scripts/export_markdown.py`
- Qdrant-Client/Setup: `app/core/qdrant.py`, `app/core/qdrant_points.py`
---
## 20. Änderungsverlauf
- **1.3.0 (2025-09-09)**
- Edge-Politik präzisiert: `references` (Chunk-Scope), `backlink` (Note-Scope), `references:note` optional.
- `note_id` als Pflichtfeld im Edge-Payload (Owner).
- Qdrant-Payload-Indizes ergänzt (Performanz).
- Beispiele & Dataview-Snippets erweitert.
- **1.2.0 (2025-09-02)**
- Erstfassung des Knowledge-Designs.
+79 -27
View File
@@ -2,37 +2,89 @@
"$schema": "https://json-schema.org/draft/2020-12/schema", "$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "mindnet_chunk", "title": "mindnet_chunk",
"type": "object", "type": "object",
"required": ["id", "note_id", "chunk_index", "type", "path", "token_count", "lang"], "description": "Chunk-Payload (Qdrant). Kompatibel mit Alt-Feldern und neuen Feldern für Export/Roundtrip.",
"required": ["id", "note_id", "chunk_index", "path"],
"properties": { "properties": {
"id": {"type": "string"}, "id": { "type": "string" },
"note_id": {"type": "string"}, "scope": { "type": "string", "enum": ["chunk"] },
"note_title": {"type": "string"}, "note_id": { "type": "string" },
"chunk_index": {"type": "integer"}, "note_title": { "type": "string" },
"char_start": {"type": "integer"}, "note_type": { "type": "string" },
"char_end": {"type": "integer"}, "note_status": { "type": "string" },
"token_count": {"type": "integer"}, "type": { "type": "string", "description": "Legacy: früherer Chunk-Typ; kann dem Note-Typ entsprechen" },
"type": {"type": "string"}, "area": { "type": "string" },
"area": {"type": "string"}, "project": { "type": "string" },
"project": {"type": "string"}, "tags": { "type": "array", "items": { "type": "string" } },
"tags": {"type": "array", "items": {"type": "string"}},
"section_title": {"type": "string"}, "note_path": { "type": "string" },
"section_path": {"type": "string"}, "path": { "type": "string" },
"lang": {"type": "string"},
"wikilinks": {"type": "array", "items": {"type": "string"}}, "chunk_index": { "type": "integer" },
"external_links": {"type": "array", "items": {"type": "string"}}, "section_title":{ "type": ["string","null"] },
"section_path": { "type": ["string","null"] },
"char_start": { "type": ["integer","null"] },
"char_end": { "type": ["integer","null"] },
"char_len": { "type": "integer" },
"token_count": { "type": "integer", "description": "Legacy: frühere Token-Zahl" },
"token_est": { "type": "integer", "description": "Neue grobe Token-Schätzung (≈ len(text)/4)" },
"neighbors": {
"type": "object",
"properties": {
"prev": { "type": ["string","null"] },
"next": { "type": ["string","null"] }
},
"additionalProperties": false
},
"text": { "type": "string" },
"text_sha256": { "type": "string", "pattern": "^sha256:[0-9a-fA-F]{64}$" },
"lang": { "type": "string" },
"wikilinks": { "type": "array", "items": { "type": "string" } },
"external_links": {
"type": "array",
"items": {
"anyOf": [
{ "type": "string" },
{
"type": "object",
"properties": {
"href": { "type": "string" },
"label": { "type": ["string","null"] }
},
"required": ["href"],
"additionalProperties": false
}
]
}
},
"references": { "references": {
"type": "array", "type": "array",
"items": {"type": "object", "properties": { "items": {
"target_id": {"type": "string"}, "type": "object",
"kind": {"type": "string"} "properties": {
}, "required": ["target_id", "kind"]} "target_id": { "type": "string" },
"kind": { "type": "string" }
},
"required": ["target_id","kind"],
"additionalProperties": true
}
}, },
"neighbors": {"type": "object", "properties": {
"prev": {"type": ["string","null"]}, "embed_model": { "type": "string" },
"next": {"type": ["string","null"]} "embed_dim": { "type": "integer" },
}}, "embed_version": { "type": "integer" },
"path": {"type": "string"},
"created_at": {"type": "string"} "created_at": { "type": "string" }
}, },
"allOf": [
{ "anyOf": [ { "required": ["token_count"] }, { "required": ["token_est"] } ] },
{ "anyOf": [ { "required": ["type"] }, { "required": ["note_type"] } ] }
],
"additionalProperties": true "additionalProperties": true
} }
+23 -8
View File
@@ -2,15 +2,30 @@
"$schema": "https://json-schema.org/draft/2020-12/schema", "$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "mindnet_edge", "title": "mindnet_edge",
"type": "object", "type": "object",
"required": ["src_id", "dst_id", "edge_type", "scope"], "description": "Edge-Payload (Qdrant). Unterstützt Legacy (edge_type/src_id/dst_id) und neues Schema (kind/source_id/target_id/note_id/status).",
"properties": { "properties": {
"src_id": {"type": "string"}, "scope": { "type": "string", "enum": ["note","chunk"] },
"dst_id": {"type": "string"},
"edge_type": {"type": "string"}, "edge_type": { "type": "string", "description": "Legacy: z. B. references/backlink/belongs_to/prev/next" },
"scope": {"type": "string", "enum": ["note","chunk"]}, "src_id": { "type": "string", "description": "Legacy: source_id" },
"weight": {"type": "number"}, "dst_id": { "type": "string", "description": "Legacy: target_id" },
"meta": {"type": "object"},
"created_at": {"type": "string"} "kind": { "type": "string", "description": "Neu: z. B. references/backlink/belongs_to/prev/next" },
"source_id": { "type": "string" },
"target_id": { "type": "string" },
"note_id": { "type": "string", "description": "Owner-Note für diesen Edge (Filter/Purge)" },
"status": { "type": "string", "description": "optional, z. B. 'unresolved'" },
"weight": { "type": "number" },
"meta": { "type": "object" },
"created_at":{ "type": "string" }
}, },
"anyOf": [
{ "required": ["src_id", "dst_id", "edge_type", "scope"] },
{ "required": ["source_id", "target_id", "kind", "scope"] }
],
"additionalProperties": true "additionalProperties": true
} }
+38 -40
View File
@@ -1,47 +1,45 @@
{ {
"$schema": "https://json-schema.org/draft/2020-12/schema", "$schema": "http://json-schema.org/draft-07/schema#",
"title": "mindnet_note", "title": "mindnet note payload",
"type": "object", "type": "object",
"required": ["note_id", "title", "type", "status", "created", "path"],
"properties": { "properties": {
"note_id": { "type": "string" }, "note_id": { "type": "string" },
"title": { "type": "string" }, "title": { "type": ["string","null"] },
"type": { "type": "string" }, "type": { "type": ["string","null"] },
"status": { "type": "string" }, "status": { "type": ["string","null"] },
"created": { "type": "string" }, "created": { "type": ["string","null"] },
"updated": { "type": "string" }, "updated": { "type": ["string","null"] },
"tags": { "path": { "type": ["string","null"] },
"type": "array", "tags": { "type": ["array","null"], "items": { "type": "string" } },
"items": { "type": "string" } "area": { "type": ["string","null"] },
}, "project": { "type": ["string","null"] },
"area": { "type": "string" }, "source": { "type": ["string","null"] },
"project": { "type": "string" }, "lang": { "type": ["string","null"] },
"priority": { "type": "number" }, "slug": { "type": ["string","null"] },
"effort_min": { "type": "number" }, "aliases": { "type": ["array","null"], "items": { "type": "string" } },
"due": { "type": "string" },
"people": { "fulltext": { "type": ["string","null"] },
"type": "array", "references": { "type": ["array","null"], "items": { "type": "string" } },
"items": { "type": "string" }
}, "hash_fulltext": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
"aliases": { "hash_signature": { "type": ["string","null"] },
"type": "array",
"items": { "type": "string" } "hash_body": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
}, "hash_frontmatter": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
"references": { "hash_full": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
"type": "array",
"items": { "type": "string" } "hashes": {
}, "type": ["object","null"],
"depends_on": { "description": "Mapping: <mode>:<source>:<normalize> -> sha256 hex",
"type": "array", "patternProperties": {
"items": { "type": "string" } "^(body|frontmatter|full):(parsed|raw):(canonical|none)$": {
}, "type": "string",
"assigned_to": { "pattern": "^[a-f0-9]{64}$"
"type": "array", }
"items": { "type": "string" } },
}, "additionalProperties": false
"lang": { "type": "string" }, }
"path": { "type": "string" },
"hash_fulltext": { "type": "string" }
}, },
"required": ["note_id"],
"additionalProperties": true "additionalProperties": true
} }
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
scripts/debug_note_payload.py
Zeigt, welche app.core.note_payload geladen wird, ruft make_note_payload auf
und druckt Typ/Preview der Rückgabe.
Aufruf:
python3 -m scripts.debug_note_payload --file ./test_vault/40_concepts/concept-alpha.md --vault-root ./test_vault
"""
import argparse, json, os, pprint
from app.core import note_payload as np
from app.core.parser import read_markdown
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--file", required=True)
ap.add_argument("--vault-root", default=None)
ap.add_argument("--hash-mode", default=None)
ap.add_argument("--hash-normalize", default=None)
ap.add_argument("--hash-source", default=None)
args = ap.parse_args()
print("module_path:", getattr(np, "__file__", "<unknown>"))
parsed = read_markdown(args.file)
res = np.make_note_payload(parsed, vault_root=args.vault_root,
hash_mode=args.hash_mode,
hash_normalize=args.hash_normalize,
hash_source=args.hash_source,
file_path=args.file)
print("return_type:", type(res).__name__)
if isinstance(res, dict):
print("keys:", list(res.keys()))
print(json.dumps(res, ensure_ascii=False, indent=2))
else:
preview = repr(res)
if len(preview) > 600: preview = preview[:600] + "…"
print("preview:", preview)
if __name__ == "__main__":
main()
+227 -115
View File
@@ -1,48 +1,61 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Script: import_markdown.py — Markdown → Qdrant (Notes, Chunks, Edges) Script: scripts/import_markdown.py — Markdown → Qdrant (Notes, Chunks, Edges)
Version: 3.2.0 Version: 3.6.2
Datum: 2025-09-09 Datum: 2025-09-09
Kurzbeschreibung Kurzbeschreibung
---------------- ----------------
Liest Markdown-Dateien aus einem Vault ein und schreibt Notes, Chunks und Edges - Liest Markdown-Dateien ein und erzeugt Notes/Chunks/Edges **idempotent**.
idempotent nach Qdrant. Change-Detection basiert standardmäßig auf dem **Body-Hash**. - Robuste Änderungserkennung: Mehrfach-Hashes werden parallel in der Note gespeichert
Neu: Hash-Modus und Normalisierung sind auch per **CLI** steuerbar. (Option C). Vergleich erfolgt **modusgenau** anhand von `hashes[<mode>:<source>:<normalize>]`.
Ein Wechsel des Vergleichsmodus führt so **nicht** zu Massenänderungen.
- **Fix (v3.6.2):** Bei **erstem Import** (kein Alt-Payload) wird die Note als **geändert**
behandelt → Create (Notes/Chunks/Edges) findet zuverlässig statt.
- Baseline-Modus: Mit `--baseline-modes` werden **fehlende** Hash-Varianten
im Feld `hashes` „still“ nachgetragen (Upsert NUR Notes; Legacy-Hashfelder bleiben unangetastet).
ENV / Qdrant Konfiguration Hash/Compare
------------ --------------------------
- QDRANT_URL (oder QDRANT_HOST/QDRANT_PORT) - Vergleichsmodus: `--hash-mode body|frontmatter|full`
- QDRANT_API_KEY (optional) - oder ENV: `MINDNET_HASH_MODE` / `MINDNET_HASH_COMPARE` (Body|Frontmatter|Full)
- Quelle: `--hash-source parsed|raw` (ENV: `MINDNET_HASH_SOURCE`, Default parsed)
- Normalisierung: `--hash-normalize canonical|none` (ENV: `MINDNET_HASH_NORMALIZE`, Default canonical)
- Optional: `--compare-text` (oder `MINDNET_COMPARE_TEXT=true`) vergleicht zusätzlich den parsed Body-Text direkt.
Weitere ENV / Qdrant
--------------------
- QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
- COLLECTION_PREFIX (Default: mindnet) - COLLECTION_PREFIX (Default: mindnet)
- VECTOR_DIM (Default: 384) - VECTOR_DIM (Default: 384)
- MINDNET_HASH_MODE: "body" (Default) | "frontmatter" | "body+frontmatter" - MINDNET_NOTE_SCOPE_REFS: true|false (Default: false)
- MINDNET_HASH_NORMALIZE: "canonical" (Default) | "none"
CLI (übersteuert ENV) Aufruf-Beispiele
--------------------- ----------------
--hash-mode body|frontmatter|body+frontmatter # Standard (Body, parsed, canonical)
--hash-normalize canonical|none
Aufruf
------
python3 -m scripts.import_markdown --vault ./vault python3 -m scripts.import_markdown --vault ./vault
python3 -m scripts.import_markdown --vault ./vault --apply
python3 -m scripts.import_markdown --vault ./vault --apply --purge-before-upsert
python3 -m scripts.import_markdown --vault ./vault --note-id 20250821-foo --apply
python3 -m scripts.import_markdown --vault ./vault --apply --embed-note
# Feingranulare Erkennung (jede Kleinigkeit im Body zählt):
python3 -m scripts.import_markdown --vault ./vault --hash-normalize none
"""
# Baseline (füllt hashes für parsed:canonical Tripel „still“ auf)
MINDNET_HASH_SOURCE=parsed MINDNET_HASH_NORMALIZE=canonical \
python3 -m scripts.import_markdown --vault ./vault --apply --baseline-modes
# Frontmatter-Vergleich ohne Massenänderungen (nach Baseline)
MINDNET_HASH_COMPARE=Frontmatter \
python3 -m scripts.import_markdown --vault ./vault
# Sehr sensibel (raw + none) und direkten Textvergleich
python3 -m scripts.import_markdown --vault ./vault --apply --hash-source raw --hash-normalize none --compare-text
"""
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import difflib
import json import json
import os import os
import sys import sys
from typing import Dict, List, Optional, Tuple from typing import Dict, List, Optional, Tuple, Any
from collections.abc import Mapping
from dotenv import load_dotenv from dotenv import load_dotenv
from qdrant_client.http import models as rest from qdrant_client.http import models as rest
@@ -51,12 +64,17 @@ from app.core.parser import (
read_markdown, read_markdown,
normalize_frontmatter, normalize_frontmatter,
validate_required_frontmatter, validate_required_frontmatter,
extract_wikilinks,
) )
from app.core.note_payload import make_note_payload from app.core.note_payload import make_note_payload
from app.core.chunker import assemble_chunks from app.core.chunker import assemble_chunks
from app.core.chunk_payload import make_chunk_payloads from app.core.chunk_payload import make_chunk_payloads
from app.core.qdrant import QdrantConfig, get_client, ensure_collections from app.core.edges import build_edges_for_note
from app.core.qdrant import (
QdrantConfig,
get_client,
ensure_collections,
ensure_payload_indexes,
)
from app.core.qdrant_points import ( from app.core.qdrant_points import (
points_for_chunks, points_for_chunks,
points_for_note, points_for_note,
@@ -65,15 +83,14 @@ from app.core.qdrant_points import (
) )
try: try:
from app.core.embed import embed_texts, embed_one # optional from app.core.embed import embed_texts # optional
except Exception: except Exception:
embed_texts = None embed_texts = None
embed_one = None
# ----------------------------------------------------------------------------- # ---------------------------------------------------------------------
# Hilfsfunktionen # Helpers
# ----------------------------------------------------------------------------- # ---------------------------------------------------------------------
def iter_md(root: str) -> List[str]: def iter_md(root: str) -> List[str]:
out: List[str] = [] out: List[str] = []
@@ -91,12 +108,9 @@ def iter_md(root: str) -> List[str]:
def collections(prefix: str) -> Tuple[str, str, str]: def collections(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"
def fetch_existing_note_hash(client, prefix: str, note_id: str) -> Optional[str]: def fetch_existing_note_payload(client, prefix: str, note_id: str) -> Optional[Dict]:
notes_col, _, _ = collections(prefix) notes_col, _, _ = collections(prefix)
f = rest.Filter(must=[rest.FieldCondition( f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
key="note_id",
match=rest.MatchValue(value=note_id),
)])
points, _ = client.scroll( points, _ = client.scroll(
collection_name=notes_col, collection_name=notes_col,
scroll_filter=f, scroll_filter=f,
@@ -106,21 +120,32 @@ def fetch_existing_note_hash(client, prefix: str, note_id: str) -> Optional[str]
) )
if not points: if not points:
return None return None
pl = points[0].payload or {} return points[0].payload or {}
return pl.get("hash_fulltext")
def purge_note_artifacts(client, prefix: str, note_id: str) -> None: def purge_note_artifacts(client, prefix: str, note_id: str) -> None:
"""
Löscht alle Chunks & Edges zu einer Note mittels Filter-Selector (kompatibel mit aktuellen Qdrant-Clients).
"""
_, chunks_col, edges_col = collections(prefix) _, chunks_col, edges_col = collections(prefix)
f_chunks = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))]) filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
client.delete(collection_name=chunks_col, points_selector=f_chunks, wait=True)
should = [ try:
rest.FieldCondition(key="source_id", match=rest.MatchText(text=f"{note_id}#")), client.delete(
rest.FieldCondition(key="target_id", match=rest.MatchText(text=f"{note_id}#")), collection_name=chunks_col,
rest.FieldCondition(key="source_id", match=rest.MatchValue(value=note_id)), points_selector=rest.FilterSelector(filter=filt),
rest.FieldCondition(key="target_id", match=rest.MatchValue(value=note_id)), wait=True
] )
f_edges = rest.Filter(should=should) except Exception as e:
client.delete(collection_name=edges_col, points_selector=f_edges, wait=True) print(json.dumps({"note_id": note_id, "warn": f"delete chunks via filter failed: {e}"}))
try:
client.delete(
collection_name=edges_col,
points_selector=rest.FilterSelector(filter=filt),
wait=True
)
except Exception as e:
print(json.dumps({"note_id": note_id, "warn": f"delete edges via filter failed: {e}"}))
def _normalize_rel_path(abs_path: str, vault_root: str) -> str: def _normalize_rel_path(abs_path: str, vault_root: str) -> str:
try: try:
@@ -129,10 +154,21 @@ def _normalize_rel_path(abs_path: str, vault_root: str) -> str:
rel = abs_path rel = abs_path
return rel.replace("\\", "/").lstrip("/") return rel.replace("\\", "/").lstrip("/")
def _resolve_mode(val: Optional[str]) -> str:
v = (val or os.environ.get("MINDNET_HASH_MODE") or os.environ.get("MINDNET_HASH_COMPARE") or "body").strip().lower()
if v in ("full", "fulltext", "body+frontmatter", "bodyplusfrontmatter"):
return "full"
if v in ("frontmatter", "fm"):
return "frontmatter"
return "body"
# ----------------------------------------------------------------------------- def _env(key: str, default: str) -> str:
return (os.environ.get(key) or default).strip().lower()
# ---------------------------------------------------------------------
# Main # Main
# ----------------------------------------------------------------------------- # ---------------------------------------------------------------------
def main() -> None: def main() -> None:
load_dotenv() load_dotenv()
@@ -145,15 +181,32 @@ def main() -> None:
ap.add_argument("--embed-note", action="store_true", help="Optional: Note-Volltext einbetten") ap.add_argument("--embed-note", action="store_true", help="Optional: Note-Volltext einbetten")
ap.add_argument("--force-replace", action="store_true", ap.add_argument("--force-replace", action="store_true",
help="Änderungserkennung ignorieren und immer upserten (+ optional Purge)") help="Änderungserkennung ignorieren und immer upserten (+ optional Purge)")
# NEU: Hash-Steuerung per CLI ap.add_argument("--hash-mode", choices=["body", "frontmatter", "full"], default=None,
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter"], default=None) help="Vergleichsmodus (Body | Frontmatter | Full)")
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None) ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
ap.add_argument("--hash-source", choices=["parsed", "raw"], default=None,
help="Quelle für die Hash-Berechnung (Default: parsed)")
ap.add_argument("--note-scope-refs", action="store_true",
help="(Optional) erzeugt zusätzlich references:note (Default: aus)")
ap.add_argument("--debug-hash-diff", action="store_true",
help="Zeigt einen kurzen Diff zwischen altem und neuem Body")
ap.add_argument("--compare-text", action="store_true",
help="Parsed fulltext zusätzlich direkt vergleichen (über Hash hinaus)")
ap.add_argument("--baseline-modes", action="store_true",
help="Fehlende Hash-Varianten im Feld 'hashes' still nachtragen (Upsert NUR Notes)")
args = ap.parse_args() args = ap.parse_args()
mode = _resolve_mode(args.hash_mode) # body|frontmatter|full
src = _env("MINDNET_HASH_SOURCE", args.hash_source or "parsed") # parsed|raw
norm = _env("MINDNET_HASH_NORMALIZE", args.hash_normalize or "canonical") # canonical|none
note_scope_refs_env = (_env("MINDNET_NOTE_SCOPE_REFS", "false") == "true")
note_scope_refs = args.note_scope_refs or note_scope_refs_env
compare_text = args.compare_text or (_env("MINDNET_COMPARE_TEXT", "false") == "true")
cfg = QdrantConfig.from_env() cfg = QdrantConfig.from_env()
client = get_client(cfg) client = get_client(cfg)
ensure_collections(client, cfg.prefix, cfg.dim) ensure_collections(client, cfg.prefix, cfg.dim)
notes_col, chunks_col, edges_col = collections(cfg.prefix) ensure_payload_indexes(client, cfg.prefix)
root = os.path.abspath(args.vault) root = os.path.abspath(args.vault)
files = iter_md(root) files = iter_md(root)
@@ -161,12 +214,22 @@ def main() -> None:
print("Keine Markdown-Dateien gefunden.", file=sys.stderr) print("Keine Markdown-Dateien gefunden.", file=sys.stderr)
sys.exit(2) sys.exit(2)
key_current = f"{mode}:{src}:{norm}"
processed = 0 processed = 0
for path in files: for path in files:
parsed = read_markdown(path) # -------- Parse & Validate --------
fm = normalize_frontmatter(parsed.frontmatter) try:
parsed = read_markdown(path)
except Exception as e:
print(json.dumps({"path": path, "error": f"read_markdown failed: {e}"}))
continue
if parsed is None:
print(json.dumps({"path": path, "error": "read_markdown returned None"}))
continue
try: try:
fm = normalize_frontmatter(parsed.frontmatter)
validate_required_frontmatter(fm) validate_required_frontmatter(fm)
except Exception as e: except Exception as e:
print(json.dumps({"path": path, "error": f"Frontmatter invalid: {e}"})) print(json.dumps({"path": path, "error": f"Frontmatter invalid: {e}"}))
@@ -177,89 +240,138 @@ def main() -> None:
processed += 1 processed += 1
# Note-Payload (mit expliziten Hash-Parametern) # -------- Build new payload (includes 'hashes') --------
note_pl = make_note_payload(parsed, vault_root=root, note_pl = make_note_payload(
hash_mode=args.hash_mode, hash_normalize=args.hash_normalize) parsed,
if "fulltext" not in (note_pl or {}): vault_root=root,
note_pl["fulltext"] = parsed.body or "" hash_mode=mode,
if note_pl.get("path"): hash_normalize=norm,
note_pl["path"] = _normalize_rel_path( hash_source=src,
os.path.join(root, note_pl["path"]) if not os.path.isabs(note_pl["path"]) else note_pl["path"], root file_path=path,
) )
else: if not note_pl.get("fulltext"):
note_pl["path"] = _normalize_rel_path(parsed.path, root) note_pl["fulltext"] = getattr(parsed, "body", "") or ""
note_id = note_pl["note_id"] note_id = note_pl.get("note_id") or fm.get("id")
if not note_id:
print(json.dumps({"path": path, "error": "Missing note_id after payload build"}))
continue
# Change-Detection # -------- Fetch old payload --------
new_hash = note_pl.get("hash_fulltext") old_payload = None if args.force_replace else fetch_existing_note_payload(client, cfg.prefix, note_id)
old_hash = None if args.force_replace else fetch_existing_note_hash(client, cfg.prefix, note_id) has_old = old_payload is not None
changed = args.force_replace or (old_hash != new_hash)
# Chunks + Embeddings (Nullvektor-Fallback) old_hashes = (old_payload or {}).get("hashes") or {}
chunks = assemble_chunks(fm["id"], parsed.body, fm.get("type", "concept")) old_hash_exact = old_hashes.get(key_current)
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks)
if embed_texts:
vecs = embed_texts([getattr(c, "text", "") for c in chunks])
else:
vecs = [[0.0] * cfg.dim for _ in chunks]
# Edges (leichtgewichtig direkt hier ableiten) # Neu-Hash (aktueller Modus) aus neuem Payload
# belongs_to / prev/next aus Chunk-Nachbarschaften + Wikilinks als references new_hash_exact = (note_pl.get("hashes") or {}).get(key_current)
edges: List[Dict] = []
for ch in chunk_pls:
cid = ch["id"]
edges.append({"src_id": cid, "dst_id": note_id, "edge_type": "belongs_to", "scope": "chunk"})
nb = ch.get("neighbors") or {}
if nb.get("prev"):
edges.append({"src_id": nb["prev"], "dst_id": cid, "edge_type": "next", "scope": "chunk"})
edges.append({"src_id": cid, "dst_id": nb["prev"], "edge_type": "prev", "scope": "chunk"})
if nb.get("next"):
edges.append({"src_id": cid, "dst_id": nb["next"], "edge_type": "next", "scope": "chunk"})
edges.append({"src_id": nb["next"], "dst_id": cid, "edge_type": "prev", "scope": "chunk"})
for ref in (ch.get("references") or []):
tid = ref.get("target_id")
if tid:
edges.append({"src_id": cid, "dst_id": tid, "edge_type": "references", "scope": "chunk"})
for tid in (note_pl.get("references") or []):
edges.append({"src_id": note_id, "dst_id": tid, "edge_type": "references", "scope": "note"})
edges.append({"src_id": tid, "dst_id": note_id, "edge_type": "backlink", "scope": "note"})
# Dedupe
_uniq = {}
for e in edges:
_uniq[(e["src_id"], e["dst_id"], e["edge_type"], e.get("scope", ""))] = e
edges = list(_uniq.values())
# Zusammenfassung needs_baseline = (old_hash_exact is None)
# Change-Detection:
# - CREATE: wenn es KEIN Alt-Payload gibt -> changed=True
# - UPDATE: baseline existiert UND Hash differiert
# - force/text_changed wie gehabt
hash_changed = (old_hash_exact is not None and new_hash_exact is not None and old_hash_exact != new_hash_exact)
text_changed = False
if compare_text:
old_text = (old_payload or {}).get("fulltext") or ""
new_text = note_pl.get("fulltext") or ""
text_changed = (old_text != new_text)
changed = args.force_replace or (not has_old) or hash_changed or text_changed
# Baseline-only nur, wenn Alt-Payload existiert UND Key fehlt UND keine sonstige Änderung
do_baseline_only = (args.baseline_modes and has_old and needs_baseline and not changed)
# -------- Optional: Chunks / Embeddings / Edges vorbereiten --------
# CREATE/UPDATE: wir brauchen Chunks/Edges; Baseline-only: nein
chunks = []
chunk_pls = []
edges = []
vecs = []
if (args.apply and (changed and (not do_baseline_only))):
try:
chunks = assemble_chunks(fm["id"], getattr(parsed, "body", "") or "", fm.get("type", "concept"))
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks)
except Exception as e:
print(json.dumps({"path": path, "note_id": note_id, "error": f"chunk build failed: {e}"}))
continue
if embed_texts:
try:
vecs = embed_texts([getattr(c, "text", "") for c in chunks]) # type: ignore[attr-defined]
except Exception as e:
print(json.dumps({"path": path, "note_id": note_id, "warn": f"embed_texts failed, using zeros: {e}"}))
vecs = [[0.0] * cfg.dim for _ in chunks]
else:
vecs = [[0.0] * cfg.dim for _ in chunks]
try:
note_refs = note_pl.get("references") or []
edges = build_edges_for_note(
note_id,
chunk_pls,
note_refs,
include_note_scope_refs=note_scope_refs,
)
except Exception as e:
print(json.dumps({"path": path, "note_id": note_id, "error": f"build_edges_for_note failed: {e}"}))
continue
# -------- Summary --------
summary = { summary = {
"note_id": note_id, "note_id": note_id,
"title": fm.get("title"), "title": fm.get("title"),
"chunks": len(chunk_pls), "chunks": len(chunk_pls),
"edges": len(edges), "edges": len(edges),
"changed": changed, "changed": changed,
"decision": ("apply" if args.apply and changed else "needs_baseline_for_mode": needs_baseline,
"decision": ("baseline-only" if args.apply and do_baseline_only else
"apply" if args.apply and changed else
"apply-skip-unchanged" if args.apply and not changed else "apply-skip-unchanged" if args.apply and not changed else
"dry-run"), "dry-run"),
"path": note_pl["path"], "path": note_pl["path"],
"hash_mode": args.hash_mode or os.environ.get("MINDNET_HASH_MODE", "body"), "hash_mode": mode,
"hash_normalize": args.hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical"), "hash_normalize": norm,
"hash_old": old_hash, "hash_source": src,
"hash_new": new_hash,
} }
print(json.dumps(summary, ensure_ascii=False)) print(json.dumps(summary, ensure_ascii=False))
# -------- Writes --------
if not args.apply: if not args.apply:
continue continue
if changed and args.purge_before_upsert: # BASELINE-ONLY: fehlenden Key nachtragen, ohne legacy Felder anzutasten
purge_note_artifacts(client, cfg.prefix, note_id) if do_baseline_only:
merged_hashes = {}
merged_hashes.update(old_hashes)
merged_hashes.update(note_pl.get("hashes") or {})
# Legacy-Hashfelder unverändert lassen, falls vorhanden
if old_payload:
note_pl["hash_fulltext"] = old_payload.get("hash_fulltext", note_pl.get("hash_fulltext"))
note_pl["hash_signature"] = old_payload.get("hash_signature", note_pl.get("hash_signature"))
note_pl["hashes"] = merged_hashes
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
upsert_batch(client, notes_name, note_pts)
continue
# Normale CREATE/UPDATE
if not changed:
continue
if args.purge_before_upsert and has_old:
try:
purge_note_artifacts(client, cfg.prefix, note_id)
except Exception as e:
print(json.dumps({"path": path, "note_id": note_id, "warn": f"purge failed: {e}"}))
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim) notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
upsert_batch(client, notes_name, note_pts) upsert_batch(client, notes_name, note_pts)
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs) chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
upsert_batch(client, chunks_name, chunk_pts) upsert_batch(client, chunks_name, chunk_pts)
edges_name, edge_pts = points_for_edges(cfg.prefix, edges) edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
upsert_batch(client, edges_name, edge_pts) upsert_batch(client, edges_name, edge_pts)
+18 -14
View File
@@ -3,31 +3,32 @@
""" """
make_test_vault.py — erzeugt einen minimalen, nachvollziehbaren Test-Vault make_test_vault.py — erzeugt einen minimalen, nachvollziehbaren Test-Vault
Version: 1.1 (2025-09-05) Version: 1.2 (2025-09-09)
Änderungen ggü. 1.0: Änderungen ggü. 1.1:
- created/updated werden als QUOTED ISO-Strings geschrieben, damit der YAML-Parser - Fügt **externe Links** (http/mailto) in `exp-two.md` hinzu, damit der Chunk-Payload-Exporter
sie nicht in datetime-Objekte konvertiert (Schema verlangt strings). `external_links` realistisch testen kann.
- Kommentare/Output gestrafft. - Kleine Textanpassungen zur stabilen Chunk-Bildung (Absatzstruktur).
Zweck Zweck
- Kleiner Obsidian-ähnlicher Vault zum Durchspielen des Importers (Chunks/Edges). - Kleiner Obsidian-ähnlicher Vault zum Durchspielen des Importers (Chunks/Edges).
- Szenarien: leere Links, spätere Anlage fehlender Noten, Chunk-Neuaufteilung. - Szenarien: leere Links, spätere Anlage fehlender Noten, Chunk-Neuaufteilung, externe Links.
Struktur (Default: ./test_vault) Struktur (Default: ./test_vault)
- 40_concepts/concept-alpha.md - 40_concepts/concept-alpha.md
- 20_experiences/exp-one.md (verlinkt auf [[concept-alpha]] und [[missing-note]]) - 20_experiences/exp-one.md (verlinkt auf [[concept-alpha]] und [[missing-note]])
- 20_experiences/exp-two.md (verlinkt auf [[concept-alpha]]) - 20_experiences/exp-two.md (verlinkt auf [[concept-alpha]] + externe Links)
- 30_projects/project-demo.md (verlinkt auf [[concept-alpha]] und [[exp-one]]) - 30_projects/project-demo.md (verlinkt auf [[concept-alpha]] und [[exp-one]])
Voraussetzungen Voraussetzungen
- Keine. Rein Dateigenerierung. - Keine. Rein Dateigenerierung.
Aufruf Aufruf
python3 -m scripts.make_test_vault [--out ./test_vault] [--force] python3 -m scripts.make_test_vault [--out ./test_vault] [--force] [--with-missing]
Parameter Parameter
--out Zielverzeichnis (Standard: ./test_vault) --out Zielverzeichnis (Standard: ./test_vault)
--force Bestehenden Ordner löschen und neu anlegen. --force Bestehenden Ordner löschen und neu anlegen.
--with-missing Auch die 'missing-note' direkt anlegen (Standard: erst im 2. Lauf)
Hinweise für Tests Hinweise für Tests
1) Erster Import (dry-run oder --apply): Es gibt einen „leeren“ Link [[missing-note]]. 1) Erster Import (dry-run oder --apply): Es gibt einen „leeren“ Link [[missing-note]].
@@ -35,6 +36,7 @@ Hinweise für Tests
-> Erwartung: Edges für ehemals leeren Link werden korrekt nachgezogen (references + backlink). -> Erwartung: Edges für ehemals leeren Link werden korrekt nachgezogen (references + backlink).
3) Ändere den Body von exp-one.md so, dass andere Chunk-Grenzen entstehen und importiere erneut: 3) Ändere den Body von exp-one.md so, dass andere Chunk-Grenzen entstehen und importiere erneut:
-> Erwartung: Chunks/Edges/Note werden für betroffene Noten aktualisiert. -> Erwartung: Chunks/Edges/Note werden für betroffene Noten aktualisiert.
4) Prüfe externe Links (verify_chunk_texts.py betrifft nur Text; externe Links siehst du in chunk_payloads).
Kompatibel mit: Kompatibel mit:
- note.schema.json: 'created'/'updated' müssen strings sein. (Wichtig!) - note.schema.json: 'created'/'updated' müssen strings sein. (Wichtig!)
@@ -52,7 +54,6 @@ def iso_now() -> str:
def q(s: str) -> str: def q(s: str) -> str:
# Sicheres Quoten für YAML-Frontmatter # Sicheres Quoten für YAML-Frontmatter
# (einfaches doppelt-Quoten reicht hier, da wir keine eingebetteten """ verwenden)
return f"\"{s}\"" return f"\"{s}\""
TEMPLATE_CONCEPT = """--- TEMPLATE_CONCEPT = """---
@@ -66,7 +67,7 @@ tags: ["area/mindnet","type/concept","topic/test"]
--- ---
## Beschreibung ## Beschreibung
Dies ist ein einfaches Konzept für Testzwecke. Dies ist ein einfaches Konzept für Testzwecke. Es wird von anderen Notizen referenziert.
## Mögliche Verbindungen ## Mögliche Verbindungen
- [[exp-one]] - [[exp-one]]
@@ -109,10 +110,12 @@ tags: ["area/mindnet","type/experience","topic/test"]
--- ---
## Kontext ## Kontext
Zweite Experience, die auf dasselbe Konzept verweist. Zweite Experience, die auf dasselbe Konzept verweist, ergänzt um **externe Links**.
## Beobachtung ## Beobachtung
Verweis auf [[concept-alpha]]. Verweis auf [[concept-alpha]]. Zusätzliche Ressourcen:
- Link: [Beispielseite](https://example.com "Referenz")
- Kontakt: [E-Mail](mailto:info@example.com)
## Mögliche Verbindungen ## Mögliche Verbindungen
- [[concept-alpha]] - [[concept-alpha]]
@@ -218,6 +221,7 @@ def main():
print(" 1) Zuerst ohne missing-note anlegen (Standard), importieren, Edges prüfen.") print(" 1) Zuerst ohne missing-note anlegen (Standard), importieren, Edges prüfen.")
print(" 2) Dann erneut ausführen mit --force --with-missing (missing-note wird erzeugt),") print(" 2) Dann erneut ausführen mit --force --with-missing (missing-note wird erzeugt),")
print(" und Import wiederholen → Edges/Backlinks sollten nachgezogen werden.") print(" und Import wiederholen → Edges/Backlinks sollten nachgezogen werden.")
print(" 3) In exp-two.md sind **externe Links** enthalten → prüfe `external_links` in Chunk-Payloads.")
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script: scripts/verify_chunk_texts.py
Version: 1.0.0
Datum: 2025-09-09
Kurzbeschreibung
---------------
Verifiziert, dass in Qdrant für jede Note die zugehörigen Chunks ein Textfeld
enthalten und der Body (notes.payload.fulltext) aus den Chunk-Texten sinnvoll
rekonstruiert werden kann.
Prüfungen pro Note:
- Alle Chunks vorhanden (>=1).
- Jedes Chunk-Payload hat einen nutzbaren Textschlüssel: "text" (bevorzugt), sonst "content", sonst "raw".
- Reihenfolge der Chunks wird stabil bestimmt (payload.chunk_index -> Nummer aus chunk_id).
- Coverage: Summe der im Fulltext gefundenen Chunk-Textsegmente / len(Fulltext) (Toleranz für Overlaps).
-> OK wenn coverage >= 0.90 (konfigurierbar via --min-coverage)
Ausgabe:
- JSON mit Gesamtsummen und Details je Note.
ENV:
- QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
- COLLECTION_PREFIX (Fallback, wenn --prefix fehlt)
Beispiele:
# Alle Notes prüfen (Prefix aus ENV)
python3 -m scripts.verify_chunk_texts
# Nur eine Note prüfen
python3 -m scripts.verify_chunk_texts --note-id concept-alpha
# Prefix explizit setzen und strengere Coverage verlangen
python3 -m scripts.verify_chunk_texts --prefix mindnet --min-coverage 0.95
"""
from __future__ import annotations
import argparse, json, os, re, sys
from typing import Dict, List, Tuple, Optional
from qdrant_client import QdrantClient
from qdrant_client.http import models as rest
def _names(prefix: str) -> Tuple[str,str,str]:
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
def _client() -> QdrantClient:
url = os.getenv("QDRANT_URL")
if not url:
host = os.getenv("QDRANT_HOST", "127.0.0.1")
port = int(os.getenv("QDRANT_PORT", "6333"))
url = f"http://{host}:{port}"
api_key = os.getenv("QDRANT_API_KEY") or None
return QdrantClient(url=url, api_key=api_key)
def _chunk_sort_key(p: Dict, pid: str) -> Tuple[int,int,str]:
# Primär: payload.chunk_index, sekundär: Nummer am Ende der ID (#cNN oder #NN), sonst 0
ci = p.get("chunk_index")
n = 0
m = re.search(r'#c?(\d+)$', pid or "")
if m:
try:
n = int(m.group(1))
except Exception:
n = 0
return (ci if isinstance(ci, int) else 1_000_000 + n, n, pid)
def _choose_text(payload: Dict) -> Optional[str]:
for k in ("text", "content", "raw"):
v = payload.get(k)
if isinstance(v, str) and v.strip():
return v
return None
def _coverage(fulltext: str, pieces: List[str]) -> float:
"""Berechnet die Abdeckungsquote der Stücke im Fulltext (sequenzielles Matching)."""
if not fulltext:
return 0.0 if pieces else 1.0
cursor = 0
covered = 0
ft = fulltext
for piece in pieces:
if not piece:
continue
# Tolerant gegen Whitespace-Unterschiede: normalisieren nur \r\n→\n
p = piece.replace("\r\n", "\n").replace("\r", "\n")
idx = ft.find(p, cursor)
if idx == -1:
# Versuche ein paar Heuristiken: trimmen
p2 = p.strip()
if p2 and len(p2) > 8:
idx = ft.find(p2, cursor)
if idx != -1:
covered += len(p)
cursor = idx + len(p)
# sonst: nicht abgedeckt
return covered / max(1, len(ft))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--prefix", help="Collection-Prefix (Default: ENV COLLECTION_PREFIX oder 'mindnet')")
ap.add_argument("--note-id", help="Nur eine bestimmte Note prüfen")
ap.add_argument("--min-coverage", type=float, default=0.90, help="Mindestabdeckung durch Chunks (Default: 0.90)")
args = ap.parse_args()
prefix = args.prefix or os.getenv("COLLECTION_PREFIX", "mindnet")
notes_col, chunks_col, _ = _names(prefix)
cli = _client()
# Notes abrufen (optional filter by note_id)
notes_filter = None
if args.note_id:
notes_filter = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=args.note_id))])
notes: List[Dict] = []
off = None
while True:
pts, off = cli.scroll(collection_name=notes_col, scroll_filter=notes_filter,
with_payload=True, with_vectors=False, limit=256, offset=off)
if not pts:
break
for p in pts:
notes.append({"id": p.id, "payload": p.payload or {}})
if off is None:
break
results = []
total_missing_text = 0
total_notes_ok = 0
for n in notes:
pl = n["payload"]
nid = pl.get("note_id") or pl.get("id") or n.get("id")
fulltext = pl.get("fulltext") or ""
# Chunks der Note holen
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=nid))])
chunks = []
off = None
while True:
pts, off = cli.scroll(collection_name=chunks_col, scroll_filter=f,
with_payload=True, with_vectors=False, limit=256, offset=off)
if not pts:
break
for p in pts:
chunks.append({"id": p.id, "payload": p.payload or {}})
if off is None:
break
# sortieren
chunks.sort(key=lambda c: _chunk_sort_key(c["payload"], c["id"]))
texts = []
missing_text = 0
for c in chunks:
t = _choose_text(c["payload"])
if t is None:
missing_text += 1
texts.append("")
else:
texts.append(t)
cov = _coverage(fulltext, texts)
ok = (missing_text == 0) and (cov >= args.min_coverage or not fulltext)
if ok:
total_notes_ok += 1
total_missing_text += missing_text
results.append({
"note_id": nid,
"title": pl.get("title"),
"chunks": len(chunks),
"missing_chunk_texts": missing_text,
"coverage": round(cov, 4),
"has_fulltext": bool(fulltext),
"ok": ok
})
out = {
"collections": {"notes": notes_col, "chunks": chunks_col},
"notes_checked": len(notes),
"notes_ok": total_notes_ok,
"total_missing_chunk_texts": total_missing_text,
"min_coverage": args.min_coverage,
"details": results
}
print(json.dumps(out, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()