"""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") # Bump this when the ingestion document shape changes (fields Onyx displays or # indexes) so every already-synced file is re-upserted once, even though its # bytes are unchanged. v2: semantic_identifier is the file name, not the path. DOC_FORMAT_VERSION = 2 def _source_slug(source_name: str) -> str: return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src" def _fs_safe(value: str, fallback_encoding: str) -> str: """Return a UTF-8/JSON-safe version of a filesystem string. Filenames whose bytes are not valid UTF-8 arrive from os.walk as surrogate- escaped strings (e.g. '\\udce4' for the Latin-1/CP1252 byte 0xE4 = 'ä'). Encoding those to UTF-8 — for the id hash, the ingestion JSON, or the manifest — raises UnicodeEncodeError and crashes the cycle. Recover the original bytes and decode them with the share's codepage so the real character comes through. """ try: value.encode("utf-8") return value # already clean UTF-8 except UnicodeEncodeError: raw = os.fsencode(value) # reverse surrogateescape → original on-disk bytes for enc in (fallback_encoding, "utf-8", "latin-1"): try: return raw.decode(enc) except (UnicodeDecodeError, LookupError): continue return raw.decode("utf-8", "replace") 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) filename = os.path.basename(rel_path) updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat() return { "id": doc_id, "source": "file", # semantic_identifier is the label Onyx shows in the citation view. Use the # file name so the citation stays short; the full network path is still in # `link` and metadata, and the UI overlay copies it on click. "semantic_identifier": filename, "title": filename, # The full logical network path. smb://Z:\... won't open in a browser; the # AIDO UI overlay copies this to the clipboard on click instead. "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, "from_ingestion_api": True, } def _index_document_id(source_name: str) -> str: # Shares the source prefix so it is recognised as this connector's document, # but has a fixed suffix so it is never treated as a file. The reconcile pass # must whitelist this id (see sync_source) or it would be deleted as an orphan. return f"{_source_id_prefix(source_name)}index" def _build_index_text(source: SourceConfig, files: dict[str, "FileRecord"]) -> str: """A human/LLM-readable table of contents: every file grouped by folder.""" by_folder: dict[str, list[str]] = {} for rel, rec in files.items(): folder = os.path.dirname(rec.logical_path) or source.normalized_logical() by_folder.setdefault(folder, []).append(rec.logical_path) lines = [ f"Index of all documents synced from {source.name}.", f"Total files: {len(files)}.", "", "This document lists every file available on this share, grouped by folder,", "so the assistant knows the full set of documents even when a search only", "returns some of them.", "", ] for folder in sorted(by_folder): lines.append(f"{folder}") for path in sorted(by_folder[folder]): lines.append(f" - {os.path.basename(path)}\t{path}") lines.append("") return "\n".join(lines) def _build_index_document(source: SourceConfig, files: dict[str, "FileRecord"]) -> dict: text = _build_index_text(source, files) label = f"{source.name} — Index ({len(files)} Dateien)" return { "id": _index_document_id(source.name), "source": "file", "semantic_identifier": label, "title": label, # No file:// link: the index is a generated document, not a file on the # share, so clicking it should not try to copy a path. "link": None, "sections": [{"text": text, "link": None}], "metadata": { "smb_source": source.name, "smb_index": "true", }, "doc_updated_at": datetime.now(tz=timezone.utc).isoformat(), "from_ingestion_api": True, } 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"{cfg.connector_name_prefix} - {source.name}", group_ids=source.group_ids, ) 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, "/") # Normalise non-UTF-8 filenames (surrogate-escaped) so the id hash, # the ingestion payload and the manifest are all UTF-8/JSON-safe. rel = _fs_safe(rel, cfg.filename_encoding) 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 and prev.doc_format_version == DOC_FORMAT_VERSION ): 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), doc_format_version=DOC_FORMAT_VERSION, ) 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() # Index (table-of-contents) document: one per source, re-upserted only when # the file set changed. Written after deletes so it reflects the current set. index_id = _index_document_id(source.name) if cfg.write_index and ss.files: index_doc = _build_index_document(source, ss.files) index_hash = hashlib.sha256( index_doc["sections"][0]["text"].encode("utf-8") ).hexdigest() if ss.index_hash != index_hash: try: client.upsert_document(index_doc, cc_pair_id) ss.index_hash = index_hash state.save() logger.info("wrote index document (%d files)", len(ss.files)) except OnyxError as exc: logger.error("Index upsert failed for '%s': %s", source.name, exc) elif not cfg.write_index and ss.index_hash is not None: # Feature turned off after an index was written — remove it. try: client.delete_document(index_id) ss.index_hash = None state.save() logger.info("removed index document (SMB_WRITE_INDEX disabled)") except OnyxError as exc: logger.warning("Index delete for '%s' skipped: %s", source.name, exc) # 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()} # The index document shares the source prefix but is not a file, so it # must be whitelisted here or the reconcile would delete it every cycle. if cfg.write_index and ss.files: live_ids.add(index_id) 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)