"""The reconciliation engine: the production functionality the POC was missing. For each source, one cycle: 1. Walk the mounted share, hashing each eligible file's content. 2. NEW / CHANGED (hash differs from the manifest) → upsert into Onyx. 3. GONE (in the manifest but no longer on disk) → delete from Onyx. 4. Reconcile against Onyx's own doc list so deletes still happen even if the local manifest was lost (e.g. fresh volume). Document ids are stable (derived from source name + relative path), so re-ingesting a changed file updates it in place instead of creating a duplicate. """ from __future__ import annotations import hashlib import logging import os import re from datetime import datetime, timezone from .config import Config, SourceConfig from .extract import extract_text from .onyx_client import OnyxClient, OnyxError from .state import FileRecord, State logger = logging.getLogger("smb.sync") def _source_slug(source_name: str) -> str: return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src" def _stable_document_id(source_name: str, rel_path: str) -> str: # URL-safe id (no ':' etc.) so it is NOT re-encoded by Onyx — keeps the id we # send, store and later delete/reconcile byte-for-byte identical. digest = hashlib.sha256(f"{source_name}\x00{rel_path}".encode("utf-8")).hexdigest()[:20] return f"smb_{_source_slug(source_name)}_{digest}" def _source_id_prefix(source_name: str) -> str: return f"smb_{_source_slug(source_name)}_" def _logical_path(source: SourceConfig, rel_path: str) -> str: # Present the Windows-style path the user recognises, mapped from the mount. sep = "\\" if "\\" in source.normalized_logical() else "/" joined = rel_path.replace("/", sep) return f"{source.normalized_logical()}{sep}{joined}" def _eligible(path: str, cfg: Config) -> bool: ext = os.path.splitext(path)[1].lower().lstrip(".") if cfg.include_ext and ext not in cfg.include_ext: return False try: if os.path.getsize(path) > cfg.max_file_mb * 1024 * 1024: logger.info("Skipping %s (> %d MB)", path, cfg.max_file_mb) return False except OSError: return False return not os.path.basename(path).startswith(".") def _build_document( source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float ) -> dict: logical = _logical_path(source, rel_path) updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat() return { "id": doc_id, "source": "ingestion_api", # semantic_identifier is the main label Onyx shows in the citation view. "semantic_identifier": logical, "title": os.path.basename(rel_path), # A link is kept for reference; smb:// won't open in a browser (Phase 2 # replaces the broken preview with this path shown as copyable text). "link": f"file://{logical}", "sections": [{"text": text, "link": None}], "metadata": { "smb_source": source.name, "logical_path": logical, "relative_path": rel_path, }, "doc_updated_at": updated, } def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: State) -> None: if not os.path.isdir(source.mount): logger.error("Source '%s': mount %s is not accessible — skipping", source.name, source.mount) return ss = state.source(source.name) cc_pair_id = source.cc_pair_id or ss.cc_pair_id if not cc_pair_id: cc_pair_id = client.provision_cc_pair(f"AIDO SMB - {source.name}") ss.cc_pair_id = cc_pair_id state.save() seen: set[str] = set() upserts = deletes = unchanged = 0 for root, _dirs, files in os.walk(source.mount): for fname in files: abspath = os.path.join(root, fname) if not _eligible(abspath, cfg): continue rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/") seen.add(rel) try: data = open(abspath, "rb").read() except OSError as exc: logger.warning("Cannot read %s: %s", abspath, exc) continue content_hash = hashlib.sha256(data).hexdigest() prev = ss.files.get(rel) if prev and prev.content_hash == content_hash: unchanged += 1 continue text = extract_text(abspath, data) if not text.strip(): # Nothing extractable — don't ingest an empty document. continue doc_id = _stable_document_id(source.name, rel) document = _build_document(source, rel, doc_id, text, os.path.getmtime(abspath)) try: result = client.upsert_document(document, cc_pair_id) except OnyxError as exc: logger.error("Upsert failed for %s: %s", rel, exc) continue # Store the id Onyx actually persisted (it may normalise/encode the id), # so later delete + reconcile match byte-for-byte. canonical_id = result.get("document_id", doc_id) if isinstance(result, dict) else doc_id ss.files[rel] = FileRecord( document_id=canonical_id, content_hash=content_hash, logical_path=_logical_path(source, rel), size=len(data), mtime=os.path.getmtime(abspath), ) upserts += 1 logger.info("%s %s", "updated" if prev else "indexed", rel) # Deletes: files in the manifest but no longer on disk. for rel in list(ss.files.keys()): if rel in seen: continue rec = ss.files.pop(rel) try: client.delete_document(rec.document_id) deletes += 1 logger.info("deleted %s (removed from share)", rel) except OnyxError as exc: logger.error("Delete failed for %s: %s", rel, exc) ss.files[rel] = rec # keep it; retry next cycle state.save() # Manifest-independent reconcile: remove Onyx docs for this cc_pair that we # no longer track (covers a lost manifest / externally-added docs). try: live_ids = {r.document_id for r in ss.files.values()} for doc in client.list_cc_pair_documents(cc_pair_id): did = doc.get("document_id") if did and did.startswith(_source_id_prefix(source.name)) and did not in live_ids: client.delete_document(did) deletes += 1 logger.info("reconciled orphan delete %s", did) except OnyxError as exc: logger.warning("Reconcile pass for '%s' skipped: %s", source.name, exc) logger.info( "Source '%s' done: %d upserted, %d deleted, %d unchanged (cc_pair_id=%s)", source.name, upserts, deletes, unchanged, cc_pair_id, ) def sync_all(client: OnyxClient, cfg: Config, state: State) -> None: for source in cfg.sources: try: sync_source(client, cfg, source, state) except Exception as exc: # isolate a failing source from the rest logger.exception("Source '%s' failed this cycle: %s", source.name, exc)