Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58bce0ea19 | ||
|
|
3e888cc669 | ||
|
|
78446c74d3 | ||
|
|
51f08f193c | ||
|
|
4872374a6e |
No files matched your search
+71
-151
@@ -1,36 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# Modul: app/core/note_payload.py
|
||||
# Version: 1.6.3
|
||||
# Version: 1.7.0
|
||||
# Datum: 2025-09-09
|
||||
#
|
||||
# Zweck
|
||||
# -----
|
||||
# Erzeugt den Qdrant-Payload für Notes inkl. robuster Hash-Bildung zur
|
||||
# Änderungserkennung. Der vollständige (parsed) Body wird unter "fulltext"
|
||||
# persistiert; der Pfad ist relativ (für verlustfreien Export).
|
||||
#
|
||||
# Steuerung (CLI/ENV, vom Importer durchgereicht)
|
||||
# -----------------------------------------------
|
||||
# - Vergleichsmodus:
|
||||
# --hash-mode body|frontmatter|full
|
||||
# ENV: MINDNET_HASH_MODE oder MINDNET_HASH_COMPARE (Body|Frontmatter|Full)
|
||||
# "full" ist Alias für "body+frontmatter".
|
||||
# - Hash-Quelle:
|
||||
# --hash-source parsed|raw (ENV: MINDNET_HASH_SOURCE)
|
||||
# - Normalisierung:
|
||||
# --hash-normalize canonical|none (ENV: MINDNET_HASH_NORMALIZE)
|
||||
#
|
||||
# Payload-Felder (Auszug)
|
||||
# -----------------------
|
||||
# note_id, title, type, status, created, updated, path, tags,
|
||||
# fulltext, references (Note-Level-Wikilinks),
|
||||
# hash_fulltext (Primärhash), hash_signature (z. B. "body:raw:none:<hex>")
|
||||
#
|
||||
# Hinweise
|
||||
# --------
|
||||
# - Keine Abhängigkeit von FS-Zeitstempeln; nur Inhalte fließen in den Hash ein.
|
||||
# - Abwärtskompatibel: Feldernamen bleiben stabil; zusätzliche Felder stören nicht.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,17 +17,14 @@ try:
|
||||
except Exception: # pragma: no cover
|
||||
from .parser import read_markdown, extract_wikilinks, FRONTMATTER_RE # type: ignore
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _canon_frontmatter(fm: Dict[str, Any]) -> str:
|
||||
"""Kanonische JSON-Serialisierung der Frontmatter für Hashbildung."""
|
||||
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
||||
|
||||
def _normalize_body(body: str, mode: str) -> str:
|
||||
"""Normalisiert den Body für reproduzierbare Hashes (oder nicht)."""
|
||||
if mode == "none":
|
||||
return body if body is not None else ""
|
||||
text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
|
||||
@@ -63,12 +32,6 @@ def _normalize_body(body: str, mode: str) -> str:
|
||||
return text
|
||||
|
||||
def _resolve_hash_mode(explicit: Optional[str]) -> str:
|
||||
"""
|
||||
Normalisiert den Hash-Modus auf:
|
||||
'body' | 'frontmatter' | 'body+frontmatter'
|
||||
Akzeptiert 'full' als Alias.
|
||||
Berücksichtigt ENV: MINDNET_HASH_MODE oder MINDNET_HASH_COMPARE.
|
||||
"""
|
||||
if explicit:
|
||||
val = explicit.strip().lower()
|
||||
else:
|
||||
@@ -76,17 +39,12 @@ def _resolve_hash_mode(explicit: Optional[str]) -> str:
|
||||
or os.environ.get("MINDNET_HASH_COMPARE")
|
||||
or "body").strip().lower()
|
||||
if val in ("full", "fulltext", "body+frontmatter", "bodyplusfrontmatter"):
|
||||
return "body+frontmatter"
|
||||
return "full"
|
||||
if val in ("frontmatter", "fm"):
|
||||
return "frontmatter"
|
||||
return "body"
|
||||
|
||||
def _read_raw_body_from_file(file_path: Optional[str]) -> Tuple[str, Dict[str, Any]]:
|
||||
"""Liest die Rohdatei und extrahiert Body & Frontmatter ohne Parser-Logik.
|
||||
|
||||
Rückgabe:
|
||||
(body_text, frontmatter_dict)
|
||||
"""
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
return "", {}
|
||||
try:
|
||||
@@ -94,7 +52,6 @@ def _read_raw_body_from_file(file_path: Optional[str]) -> Tuple[str, Dict[str, A
|
||||
raw = f.read()
|
||||
except Exception:
|
||||
return "", {}
|
||||
# Frontmatter per Regex entfernen
|
||||
m = FRONTMATTER_RE.match(raw)
|
||||
fm = {}
|
||||
if m:
|
||||
@@ -109,55 +66,21 @@ def _read_raw_body_from_file(file_path: Optional[str]) -> Tuple[str, Dict[str, A
|
||||
body = raw
|
||||
return body, fm
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hashing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _sha256(s: str) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(s.encode("utf-8"))
|
||||
return h.hexdigest()
|
||||
|
||||
def compute_hash(
|
||||
*,
|
||||
body: Optional[str],
|
||||
frontmatter: Optional[Dict[str, Any]],
|
||||
mode: Optional[str] = None,
|
||||
normalize: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Berechnet einen Hex-Hash gemäß 'mode' und 'normalize'.
|
||||
|
||||
mode: "body" | "frontmatter" | "body+frontmatter"
|
||||
normalize: "canonical" | "none"
|
||||
"""
|
||||
mode = _resolve_hash_mode(mode)
|
||||
normalize = (normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower()
|
||||
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(frontmatter or {})
|
||||
|
||||
fm_s = _canon_frontmatter(fm or {})
|
||||
if mode == "frontmatter":
|
||||
return _sha256(fm_s)
|
||||
if mode == "body+frontmatter":
|
||||
if mode == "full":
|
||||
return _sha256(body_n + "\n--FM--\n" + fm_s)
|
||||
# default: body
|
||||
return _sha256(body_n)
|
||||
|
||||
def compute_hash_set(*, body_parsed: str, body_raw: str, fm: Dict[str, Any], normalize: str) -> Dict[str, str]:
|
||||
"""Berechnet ein Set an Hashes für Monitoring/Debug."""
|
||||
fm_s = _canon_frontmatter(fm or {})
|
||||
bp = _normalize_body(body_parsed or "", normalize)
|
||||
br = _normalize_body(body_raw or "", normalize)
|
||||
return {
|
||||
"frontmatter": _sha256(fm_s),
|
||||
"body_parsed": _sha256(bp),
|
||||
"body_raw": _sha256(br),
|
||||
"full_parsed": _sha256(bp + "\n--FM--\n" + fm_s),
|
||||
"full_raw": _sha256(br + "\n--FM--\n" + fm_s),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Kernfunktion
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -172,27 +95,13 @@ def make_note_payload(
|
||||
file_path: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Erzeugt den Payload für eine geparste Note.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
parsed : Any
|
||||
Objekt mit Attributen/Keys 'frontmatter', 'body', 'path'.
|
||||
vault_root : Optional[str]
|
||||
Vault-Wurzel (für Pfad-Relativierung).
|
||||
hash_mode : Optional[str]
|
||||
"body" | "frontmatter" | "body+frontmatter" | "full" (Alias; überschreibt ENV).
|
||||
hash_normalize : Optional[str]
|
||||
"canonical" | "none" (überschreibt ENV).
|
||||
hash_source : Optional[str]
|
||||
"parsed" (Default) oder "raw". Wenn "raw", wird der Body aus der Rohdatei gelesen.
|
||||
file_path : Optional[str]
|
||||
Pfad zur Markdown-Datei, erforderlich für 'hash_source=raw'.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Dict[str, Any]
|
||||
Qdrant-Payload für die Notes-Collection.
|
||||
Liefert den Note-Payload inkl. Mehrfach-Hashes.
|
||||
- Es werden IMMER die drei Hashes für (body|frontmatter|full) unter
|
||||
'parsed:canonical' erzeugt (Schlüssel: z. B. 'body:parsed:canonical').
|
||||
- Zusätzlich werden – falls die aktuelle Konfig (source/normalize) davon
|
||||
abweicht – die drei Hashes unter den entsprechenden Schlüsseln erzeugt,
|
||||
z. B. 'frontmatter:raw:none'.
|
||||
- 'hash_fulltext' und 'hash_signature' repräsentieren den *aktuellen* Modus.
|
||||
"""
|
||||
# dict oder Objekt akzeptieren
|
||||
if isinstance(parsed, dict):
|
||||
@@ -204,38 +113,62 @@ def make_note_payload(
|
||||
body_parsed = getattr(parsed, "body", "") or ""
|
||||
path = getattr(parsed, "path", "") or ""
|
||||
|
||||
# Hash-Quelle bestimmen
|
||||
src = (hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed")).strip().lower()
|
||||
# Zielpfad relativieren
|
||||
rel_path = path
|
||||
try:
|
||||
if vault_root:
|
||||
rel = os.path.relpath(path, vault_root)
|
||||
rel = rel.replace("\\", "/").lstrip("/")
|
||||
rel_path = rel
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Konfiguration auflösen
|
||||
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)
|
||||
# Roh-FM ergänzen (nicht überschreiben)
|
||||
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
|
||||
|
||||
normalize = (hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower()
|
||||
mode_resolved = _resolve_hash_mode(hash_mode)
|
||||
# --- 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
|
||||
)
|
||||
|
||||
# Hash gemäß Modus/Quelle bilden
|
||||
body_for_hash = raw_body if src == "raw" else body_parsed
|
||||
primary_hash = compute_hash(body=body_for_hash, frontmatter=fm, mode=mode_resolved, normalize=normalize)
|
||||
hash_signature = f"{'full' if mode_resolved=='body+frontmatter' else mode_resolved}:{src}:{normalize}:{primary_hash}"
|
||||
# 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"]
|
||||
|
||||
# Pfad relativieren
|
||||
rel_path = path
|
||||
try:
|
||||
if vault_root:
|
||||
rel = os.path.relpath(path, vault_root)
|
||||
rel = rel.replace("\\", "/").lstrip("/") # normalisieren
|
||||
rel_path = rel
|
||||
except Exception:
|
||||
pass
|
||||
# --- 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
|
||||
)
|
||||
|
||||
# Note-Level-Wikilinks (Fallback, wenn Chunks nicht geliefert werden)
|
||||
note_level_refs = list(dict.fromkeys(extract_wikilinks(body_parsed))) if body_parsed else []
|
||||
# --- 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] = {
|
||||
"note_id": fm.get("id") or fm.get("note_id"),
|
||||
@@ -246,47 +179,36 @@ def make_note_payload(
|
||||
"updated": fm.get("updated"),
|
||||
"path": rel_path or fm.get("path"),
|
||||
"tags": fm.get("tags"),
|
||||
# Primärer Hash + Signatur (für Vergleich)
|
||||
"hash_fulltext": primary_hash,
|
||||
"hash_signature": hash_signature,
|
||||
# Volltext persistieren (verlustfreie Rekonstruktion) – parsed Body
|
||||
# Volltext für verlustfreien Export
|
||||
"fulltext": body_parsed,
|
||||
# Fallback-Refs auf Note-Ebene
|
||||
"references": note_level_refs,
|
||||
# Backwards-Compat:
|
||||
"hash_fulltext": current_hash,
|
||||
"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", "aliases"):
|
||||
if k in fm:
|
||||
payload[k] = fm[k]
|
||||
|
||||
# Optional: gesamtes Hash-Set persistieren (Debug/Monitoring)
|
||||
if os.environ.get("MINDNET_HASH_RECORD_ALL", "false").strip().lower() == "true":
|
||||
payload["hashes"] = compute_hash_set(
|
||||
body_parsed=body_parsed, body_raw=raw_body, fm=fm, normalize=normalize
|
||||
)
|
||||
|
||||
# Optional: Roh-Body-Hash separat (historische Kompatibilität)
|
||||
if os.environ.get("MINDNET_HASH_STORE_RAW", "false").strip().lower() == "true" and src == "raw":
|
||||
try:
|
||||
payload["hash_raw_body"] = compute_hash(
|
||||
body=raw_body, frontmatter=fm, mode="body", normalize="none"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI – Sichtprüfung
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cli() -> None:
|
||||
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("--vault-root", dest="vault_root", default=None, help="Vault-Wurzel zur Pfad-Relativierung")
|
||||
ap.add_argument("--print", dest="do_print", action="store_true", help="Payload auf stdout ausgeben")
|
||||
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter", "full"], default=None)
|
||||
ap.add_argument("--from-file", dest="src", required=True)
|
||||
ap.add_argument("--vault-root", dest="vault_root", default=None)
|
||||
ap.add_argument("--print", dest="do_print", action="store_true")
|
||||
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-source", choices=["parsed", "raw"], default=None)
|
||||
args = ap.parse_args()
|
||||
@@ -300,10 +222,8 @@ def _cli() -> None:
|
||||
hash_source=args.hash_source,
|
||||
file_path=args.src,
|
||||
)
|
||||
|
||||
if args.do_print:
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
_cli()
|
||||
+35
-29
@@ -1,39 +1,45 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "mindnet_note",
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "mindnet note payload",
|
||||
"type": "object",
|
||||
"description": "Note-Payload (Qdrant). Erweitert um fulltext/hash_raw_body für verlustfreien Export.",
|
||||
|
||||
"required": ["note_id", "title", "type", "status", "created", "path"],
|
||||
|
||||
"properties": {
|
||||
"note_id": { "type": "string" },
|
||||
"title": { "type": "string" },
|
||||
"type": { "type": "string" },
|
||||
"status": { "type": "string" },
|
||||
"created": { "type": "string" },
|
||||
"updated": { "type": "string" },
|
||||
"note_id": { "type": "string" },
|
||||
"title": { "type": ["string","null"] },
|
||||
"type": { "type": ["string","null"] },
|
||||
"status": { "type": ["string","null"] },
|
||||
"created": { "type": ["string","null"] },
|
||||
"updated": { "type": ["string","null"] },
|
||||
"path": { "type": ["string","null"] },
|
||||
"tags": { "type": ["array","null"], "items": { "type": "string" } },
|
||||
"area": { "type": ["string","null"] },
|
||||
"project": { "type": ["string","null"] },
|
||||
"source": { "type": ["string","null"] },
|
||||
"lang": { "type": ["string","null"] },
|
||||
"slug": { "type": ["string","null"] },
|
||||
"aliases": { "type": ["array","null"], "items": { "type": "string" } },
|
||||
|
||||
"tags": { "type": "array", "items": { "type": "string" } },
|
||||
"area": { "type": "string" },
|
||||
"project": { "type": "string" },
|
||||
"priority": { "type": "number" },
|
||||
"effort_min": { "type": "number" },
|
||||
"due": { "type": "string" },
|
||||
"people": { "type": "array", "items": { "type": "string" } },
|
||||
"aliases": { "type": "array", "items": { "type": "string" } },
|
||||
"lang": { "type": "string" },
|
||||
"fulltext": { "type": ["string","null"] },
|
||||
"references": { "type": ["array","null"], "items": { "type": "string" } },
|
||||
|
||||
"path": { "type": "string" },
|
||||
"hash_fulltext": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
||||
"hash_signature": { "type": ["string","null"] },
|
||||
|
||||
"references": { "type": "array", "items": { "type": "string" } },
|
||||
"depends_on": { "type": "array", "items": { "type": "string" } },
|
||||
"assigned_to": { "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}$" },
|
||||
"hash_full": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
||||
|
||||
"hash_fulltext":{ "type": "string" },
|
||||
"hash_raw_body":{ "type": "string" },
|
||||
"fulltext": { "type": "string" }
|
||||
"hashes": {
|
||||
"type": ["object","null"],
|
||||
"description": "Mapping: <mode>:<source>:<normalize> -> sha256 hex",
|
||||
"patternProperties": {
|
||||
"^(body|frontmatter|full):(parsed|raw):(canonical|none)$": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-f0-9]{64}$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
|
||||
"required": ["note_id"],
|
||||
"additionalProperties": true
|
||||
}
|
||||
+171
-247
@@ -2,42 +2,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script: scripts/import_markdown.py — Markdown → Qdrant (Notes, Chunks, Edges)
|
||||
Version: 3.5.3
|
||||
Version: 3.6.2
|
||||
Datum: 2025-09-09
|
||||
|
||||
Neu in 3.5.3
|
||||
------------
|
||||
- **Fallback**, falls app.core.note_payload.make_note_payload(None) / non-dict zurückgibt:
|
||||
Der Importer baut einen minimalen, korrekten Note-Payload selbst (inkl. Hash
|
||||
gemäß --hash-mode/--hash-source/--hash-normalize) und läuft weiter.
|
||||
- Detaillierte Debug-Ausgaben mit Typ/Preview, falls die Rückgabeform abweicht.
|
||||
|
||||
Kurzbeschreibung
|
||||
----------------
|
||||
- Liest Markdown-Dateien ein, erzeugt Notes/Chunks/Edges **idempotent**.
|
||||
- Änderungserkennung (nur Inhalte, keine FS-Zeitstempel) konfigurierbar:
|
||||
* --hash-mode: body | frontmatter | body+frontmatter | full (Alias)
|
||||
- Env: MINDNET_HASH_MODE oder MINDNET_HASH_COMPARE (Body/Frontmatter/Full)
|
||||
* --hash-normalize: canonical | none (Default: canonical)
|
||||
* --hash-source: parsed (Default) | raw
|
||||
* Optional: --compare-text (oder ENV MINDNET_COMPARE_TEXT=true)
|
||||
* Signaturabgleich: Wechselt die Signatur (z. B. body→full, parsed→raw, canonical→none),
|
||||
gilt die Note einmalig als geändert.
|
||||
- Liest Markdown-Dateien ein und erzeugt Notes/Chunks/Edges **idempotent**.
|
||||
- Robuste Änderungserkennung: Mehrfach-Hashes werden parallel in der Note gespeichert
|
||||
(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
|
||||
--------------------------
|
||||
- Vergleichsmodus: `--hash-mode body|frontmatter|full`
|
||||
- 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)
|
||||
- VECTOR_DIM (Default: 384)
|
||||
- MINDNET_NOTE_SCOPE_REFS: true|false (Default: false)
|
||||
- MINDNET_COMPARE_TEXT: true|false (Default: false)
|
||||
|
||||
Aufruf-Beispiele
|
||||
----------------
|
||||
# Standard (Body, parsed, canonical)
|
||||
python3 -m scripts.import_markdown --vault ./vault
|
||||
python3 -m scripts.import_markdown --vault ./vault --apply --hash-source raw --hash-normalize none
|
||||
MINDNET_HASH_COMPARE=Full python3 -m scripts.import_markdown --vault ./vault --apply
|
||||
python3 -m scripts.import_markdown --vault ./vault --apply --compare-text
|
||||
|
||||
# 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
|
||||
|
||||
@@ -56,8 +64,6 @@ from app.core.parser import (
|
||||
read_markdown,
|
||||
normalize_frontmatter,
|
||||
validate_required_frontmatter,
|
||||
extract_wikilinks,
|
||||
FRONTMATTER_RE,
|
||||
)
|
||||
from app.core.note_payload import make_note_payload
|
||||
from app.core.chunker import assemble_chunks
|
||||
@@ -117,11 +123,29 @@ def fetch_existing_note_payload(client, prefix: str, note_id: str) -> Optional[D
|
||||
return points[0].payload or {}
|
||||
|
||||
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)
|
||||
f_chunks = 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)
|
||||
f_edges = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||
client.delete(collection_name=edges_col, points_selector=f_edges, wait=True)
|
||||
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||
|
||||
try:
|
||||
client.delete(
|
||||
collection_name=chunks_col,
|
||||
points_selector=rest.FilterSelector(filter=filt),
|
||||
wait=True
|
||||
)
|
||||
except Exception as e:
|
||||
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:
|
||||
try:
|
||||
@@ -130,127 +154,16 @@ def _normalize_rel_path(abs_path: str, vault_root: str) -> str:
|
||||
rel = abs_path
|
||||
return rel.replace("\\", "/").lstrip("/")
|
||||
|
||||
def _resolve_hash_mode(val: Optional[str]) -> str:
|
||||
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 "body+frontmatter"
|
||||
return "full"
|
||||
if v in ("frontmatter", "fm"):
|
||||
return "frontmatter"
|
||||
return "body"
|
||||
|
||||
def _normalize_body(body: str, mode: str) -> str:
|
||||
if mode == "none":
|
||||
return body if body is not None else ""
|
||||
text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
|
||||
text = "\n".join(line.rstrip() for line in text.split("\n"))
|
||||
return text
|
||||
|
||||
def _canon_fm(fm: Dict[str, Any]) -> str:
|
||||
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
||||
|
||||
def _read_raw_body(file_path: str) -> tuple[str, Dict[str, Any]]:
|
||||
if not os.path.exists(file_path):
|
||||
return "", {}
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
raw = f.read()
|
||||
m = FRONTMATTER_RE.match(raw)
|
||||
fm = {}
|
||||
if m:
|
||||
import yaml
|
||||
try:
|
||||
fm = yaml.safe_load(m.group(1)) or {}
|
||||
except Exception:
|
||||
fm = {}
|
||||
body = raw[m.end():]
|
||||
else:
|
||||
body = raw
|
||||
return body, fm
|
||||
|
||||
def _fallback_note_payload(parsed: Any, vault_root: str, *, hash_mode: Optional[str], hash_normalize: Optional[str],
|
||||
hash_source: Optional[str], file_path: str) -> Dict[str, Any]:
|
||||
"""Baut einen minimalen Note-Payload, falls make_note_payload None liefert."""
|
||||
fm = normalize_frontmatter(parsed.frontmatter)
|
||||
path = getattr(parsed, "path", file_path)
|
||||
rel_path = _normalize_rel_path(path, vault_root)
|
||||
src = (hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed")).strip().lower()
|
||||
norm = (hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower()
|
||||
mode = _resolve_hash_mode(hash_mode)
|
||||
|
||||
if src == "raw":
|
||||
body_raw, fm_raw = _read_raw_body(file_path)
|
||||
# Roh-FM ergänzen (nicht überschreiben)
|
||||
if fm_raw:
|
||||
merged = dict(fm)
|
||||
for k, v in fm_raw.items():
|
||||
merged.setdefault(k, v)
|
||||
fm = merged
|
||||
body_for_hash = body_raw
|
||||
else:
|
||||
body_for_hash = getattr(parsed, "body", "") or ""
|
||||
|
||||
body_n = _normalize_body(body_for_hash, norm)
|
||||
fm_s = _canon_fm(fm)
|
||||
|
||||
import hashlib
|
||||
def h(s: str) -> str:
|
||||
x = hashlib.sha256()
|
||||
x.update(s.encode("utf-8"))
|
||||
return x.hexdigest()
|
||||
|
||||
if mode == "frontmatter":
|
||||
primary_hash = h(fm_s)
|
||||
elif mode == "body+frontmatter":
|
||||
primary_hash = h(body_n + "\n--FM--\n" + fm_s)
|
||||
else:
|
||||
primary_hash = h(body_n)
|
||||
|
||||
sig = f"{'full' if mode=='body+frontmatter' else mode}:{src}:{norm}:{primary_hash}"
|
||||
|
||||
refs = extract_wikilinks(getattr(parsed, "body", "") or "")
|
||||
|
||||
return {
|
||||
"note_id": fm.get("id") or fm.get("note_id"),
|
||||
"title": fm.get("title"),
|
||||
"type": fm.get("type"),
|
||||
"status": fm.get("status"),
|
||||
"created": fm.get("created"),
|
||||
"updated": fm.get("updated"),
|
||||
"path": rel_path or fm.get("path"),
|
||||
"tags": fm.get("tags"),
|
||||
"hash_fulltext": primary_hash,
|
||||
"hash_signature": sig,
|
||||
"fulltext": getattr(parsed, "body", "") or "",
|
||||
"references": list(dict.fromkeys(refs)),
|
||||
}
|
||||
|
||||
def _coerce_to_dict(obj: Any) -> Optional[Dict[str, Any]]:
|
||||
if obj is None:
|
||||
return None
|
||||
if isinstance(obj, dict):
|
||||
return obj
|
||||
if isinstance(obj, Mapping):
|
||||
try:
|
||||
return dict(obj)
|
||||
except Exception:
|
||||
pass
|
||||
if isinstance(obj, (list, tuple)):
|
||||
for it in obj:
|
||||
d = _coerce_to_dict(it)
|
||||
if isinstance(d, dict):
|
||||
return d
|
||||
return None
|
||||
md = getattr(obj, "model_dump", None)
|
||||
if callable(md):
|
||||
try: return md()
|
||||
except Exception: pass
|
||||
dd = getattr(obj, "dict", None)
|
||||
if callable(dd):
|
||||
try: return dd()
|
||||
except Exception: pass
|
||||
dct = getattr(obj, "__dict__", None)
|
||||
if isinstance(dct, dict):
|
||||
return dict(dct)
|
||||
return None
|
||||
def _env(key: str, default: str) -> str:
|
||||
return (os.environ.get(key) or default).strip().lower()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -268,17 +181,27 @@ def main() -> None:
|
||||
ap.add_argument("--embed-note", action="store_true", help="Optional: Note-Volltext einbetten")
|
||||
ap.add_argument("--force-replace", action="store_true",
|
||||
help="Änderungserkennung ignorieren und immer upserten (+ optional Purge)")
|
||||
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter", "full"], default=None)
|
||||
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "full"], default=None,
|
||||
help="Vergleichsmodus (Body | Frontmatter | Full)")
|
||||
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
|
||||
ap.add_argument("--hash-source", choices=["parsed", "raw"], default=None)
|
||||
ap.add_argument("--note-scope-refs", action="store_true")
|
||||
ap.add_argument("--debug-hash-diff", action="store_true")
|
||||
ap.add_argument("--compare-text", action="store_true")
|
||||
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()
|
||||
|
||||
note_scope_refs_env = (os.environ.get("MINDNET_NOTE_SCOPE_REFS", "false").strip().lower() == "true")
|
||||
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 (os.environ.get("MINDNET_COMPARE_TEXT", "false").strip().lower() == "true")
|
||||
compare_text = args.compare_text or (_env("MINDNET_COMPARE_TEXT", "false") == "true")
|
||||
|
||||
cfg = QdrantConfig.from_env()
|
||||
client = get_client(cfg)
|
||||
@@ -291,9 +214,11 @@ def main() -> None:
|
||||
print("Keine Markdown-Dateien gefunden.", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
key_current = f"{mode}:{src}:{norm}"
|
||||
|
||||
processed = 0
|
||||
for path in files:
|
||||
# ------------- Parsing -------------
|
||||
# -------- Parse & Validate --------
|
||||
try:
|
||||
parsed = read_markdown(path)
|
||||
except Exception as e:
|
||||
@@ -315,63 +240,40 @@ def main() -> None:
|
||||
|
||||
processed += 1
|
||||
|
||||
# ------------- Note-Payload -------------
|
||||
try:
|
||||
note_pl_raw = make_note_payload(
|
||||
parsed,
|
||||
vault_root=root,
|
||||
hash_mode=args.hash_mode,
|
||||
hash_normalize=args.hash_normalize,
|
||||
hash_source=args.hash_source,
|
||||
file_path=path,
|
||||
)
|
||||
except Exception as e:
|
||||
print(json.dumps({"path": path, "note_id": fm.get("id"), "error": f"make_note_payload failed: {e}"}))
|
||||
note_pl_raw = None
|
||||
|
||||
note_pl = _coerce_to_dict(note_pl_raw)
|
||||
if not isinstance(note_pl, dict):
|
||||
# Fallback: baue minimalen Payload
|
||||
note_pl = _fallback_note_payload(
|
||||
parsed,
|
||||
root,
|
||||
hash_mode=args.hash_mode,
|
||||
hash_normalize=args.hash_normalize,
|
||||
hash_source=args.hash_source,
|
||||
file_path=path,
|
||||
)
|
||||
print(json.dumps({
|
||||
"path": path,
|
||||
"note_id": fm.get("id"),
|
||||
"warn": "make_note_payload returned non-dict; used fallback",
|
||||
"returned_type": type(note_pl_raw).__name__ if note_pl_raw is not None else "NoneType"
|
||||
}))
|
||||
|
||||
# fulltext + path Sicherheit
|
||||
# -------- Build new payload (includes 'hashes') --------
|
||||
note_pl = make_note_payload(
|
||||
parsed,
|
||||
vault_root=root,
|
||||
hash_mode=mode,
|
||||
hash_normalize=norm,
|
||||
hash_source=src,
|
||||
file_path=path,
|
||||
)
|
||||
if not note_pl.get("fulltext"):
|
||||
note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
||||
if note_pl.get("path"):
|
||||
note_pl["path"] = _normalize_rel_path(
|
||||
os.path.join(root, note_pl["path"]) if not os.path.isabs(note_pl["path"]) else note_pl["path"], root
|
||||
)
|
||||
else:
|
||||
p_path = getattr(parsed, "path", None) or path
|
||||
note_pl["path"] = _normalize_rel_path(p_path, root)
|
||||
|
||||
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 (even in fallback)"}))
|
||||
print(json.dumps({"path": path, "error": "Missing note_id after payload build"}))
|
||||
continue
|
||||
|
||||
# ------------- Change-Detection -------------
|
||||
# -------- Fetch old payload --------
|
||||
old_payload = None if args.force_replace else fetch_existing_note_payload(client, cfg.prefix, note_id)
|
||||
old_hash = None if not old_payload else old_payload.get("hash_fulltext")
|
||||
old_sig = (old_payload or {}).get("hash_signature")
|
||||
new_hash = note_pl.get("hash_fulltext")
|
||||
new_sig = note_pl.get("hash_signature")
|
||||
has_old = old_payload is not None
|
||||
|
||||
sig_changed = bool(old_sig) and bool(new_sig) and (old_sig.split(":")[:3] != new_sig.split(":")[:3])
|
||||
hash_changed = (old_hash != new_hash)
|
||||
old_hashes = (old_payload or {}).get("hashes") or {}
|
||||
old_hash_exact = old_hashes.get(key_current)
|
||||
|
||||
# Neu-Hash (aktueller Modus) aus neuem Payload
|
||||
new_hash_exact = (note_pl.get("hashes") or {}).get(key_current)
|
||||
|
||||
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:
|
||||
@@ -379,77 +281,99 @@ def main() -> None:
|
||||
new_text = note_pl.get("fulltext") or ""
|
||||
text_changed = (old_text != new_text)
|
||||
|
||||
changed = args.force_replace or sig_changed or hash_changed or text_changed
|
||||
changed = args.force_replace or (not has_old) or hash_changed or text_changed
|
||||
|
||||
# ------------- Chunks / Embeddings / Edges -------------
|
||||
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
|
||||
# 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)
|
||||
|
||||
if embed_texts:
|
||||
# -------- 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:
|
||||
vecs = embed_texts([getattr(c, "text", "") for c in chunks]) # type: ignore[attr-defined]
|
||||
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, "warn": f"embed_texts failed, using zeros: {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]
|
||||
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
|
||||
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,
|
||||
"title": fm.get("title"),
|
||||
"chunks": len(chunk_pls),
|
||||
"edges": len(edges),
|
||||
"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
|
||||
"dry-run"),
|
||||
"path": note_pl["path"],
|
||||
"hash_mode": args.hash_mode or os.environ.get("MINDNET_HASH_MODE") or os.environ.get("MINDNET_HASH_COMPARE", "body"),
|
||||
"hash_normalize": args.hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical"),
|
||||
"hash_source": args.hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed"),
|
||||
"hash_signature": note_pl.get("hash_signature"),
|
||||
"sig_changed": sig_changed,
|
||||
"hash_changed": hash_changed,
|
||||
"text_changed": text_changed,
|
||||
"hash_mode": mode,
|
||||
"hash_normalize": norm,
|
||||
"hash_source": src,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
# ------------- Upserts -------------
|
||||
# -------- Writes --------
|
||||
if not args.apply:
|
||||
continue
|
||||
|
||||
try:
|
||||
if changed and args.purge_before_upsert:
|
||||
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}"}))
|
||||
|
||||
try:
|
||||
# BASELINE-ONLY: fehlenden Key nachtragen, ohne legacy Felder anzutasten
|
||||
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)
|
||||
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
|
||||
upsert_batch(client, chunks_name, chunk_pts)
|
||||
edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
|
||||
upsert_batch(client, edges_name, edge_pts)
|
||||
except Exception as e:
|
||||
print(json.dumps({"path": path, "note_id": note_id, "error": f"upsert failed: {e}"}))
|
||||
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)
|
||||
upsert_batch(client, notes_name, note_pts)
|
||||
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
|
||||
upsert_batch(client, chunks_name, chunk_pts)
|
||||
edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
|
||||
upsert_batch(client, edges_name, edge_pts)
|
||||
|
||||
print(f"Done. Processed notes: {processed}")
|
||||
|
||||
|
||||
Reference in new issue
Block a user