Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

164 KB
Raw Blame
"""
Note Service - CRUD operations for notes stored as Documents.

Notes are Documents with source_type='note'. This service provides
note-specific operations while leveraging the Document infrastructure.
"""

import atexit
import hashlib
import json
import random
import re
import threading
import time
import unicodedata
import uuid
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List, Optional

from loguru import logger
from sqlalchemy import delete, func, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload

from ....database.models import (
    Collection,
    Document,
    DocumentChunk,
    DocumentCollection,
    NoteChangeType,
    NoteLink,
    NoteReference,
    NoteResearch,
    NoteVersion,
    RagDocumentStatus,
    SourceType,
)
from ....database.session_context import get_user_db_session, safe_rollback
from ....database.thread_local_session import thread_cleanup
from ...utils import escape_like


def escape_markdown_link_label(label: str) -> str:
    """Escape a string so it is safe as the LABEL of a ``[label](url)``
    markdown link.

    Provenance/comment notes embed untrusted text — a research query, or a
    library document's title (which for downloaded documents comes from
    third-party HTML/PDF metadata) — as the label of an auto-generated
    link. Without escaping, a label like ``evil](https://attacker/x`` ends
    the label at its first ``]`` and lets the rest re-target the rendered
    link at an attacker URL (a phishing/content-integrity issue when the
    note is later rendered as markdown, and a syntax-injection risk in the
    PDF/LaTeX/Quarto exporters). Escape the four link-structural
    metacharacters (backslash first) and neutralise newlines so the label
    can never break out of the brackets.
    """
    return (
        str(label)
        .replace("\\", "\\\\")
        .replace("[", "\\[")
        .replace("]", "\\]")
        .replace("(", "\\(")
        .replace(")", "\\)")
        .replace("\r", " ")
        .replace("\n", " ")
    )


def _capture_request_db_password(username: str) -> Optional[str]:
    """Capture the encrypted-DB password from the request thread.

    Thin wrapper over the shared
    ``database.session_passwords.capture_request_db_password`` (kept as a
    module-local name so the many call sites in this file stay unchanged).
    Needed because ``ThreadPoolExecutor.submit`` does not copy the calling
    thread's ``ContextVar`` snapshot, so background workers otherwise lose
    the password and every encrypted-DB write is swallowed.
    """
    from ....database.session_passwords import capture_request_db_password

    return capture_request_db_password(username)


# Bounded thread pool for AI change-summary generation. The change summary is
# the only call inside update_note that hits a remote LLM, so leaving it on
# the request thread pays a full round-trip on every content-changing save.
# We persist the version snapshot synchronously with change_summary=None,
# then enqueue an UPDATE that fills the summary once the LLM returns. Users
# see their save reflected in history immediately; the summary populates
# moments later when they open the version panel.
_summary_executor: ThreadPoolExecutor | None = None
_summary_executor_lock = threading.Lock()


def _get_summary_executor() -> ThreadPoolExecutor:
    global _summary_executor
    with _summary_executor_lock:
        if _summary_executor is None:
            _summary_executor = ThreadPoolExecutor(
                max_workers=4,
                thread_name_prefix="note_summary_",
            )
    return _summary_executor


# Soft cap on pending change-summary tasks. ThreadPoolExecutor's
# internal queue is unbounded; combined with the per-task (old_content,
# new_content) capture (up to 50 MB each), a scripted burst of saves
# could pile up hundreds of MB before the 4 workers drain it. Drop the
# task with a log line once the queue exceeds the cap — losing the AI
# change summary is a non-essential degradation; the snapshot row
# itself already landed at update_note commit time. Per-user write
# rate-limit (``_notes_write_limit`` at 60/min) provides the primary
# defence; this is belt-and-suspenders for unexpected hot paths.
_SUMMARY_QUEUE_SOFT_CAP = 100


def _submit_summary_task(fn, *args, **kwargs) -> None:
    """Submit a change-summary task with queue-depth backpressure.

    On overload, drops the task and logs at WARNING level — better than
    silent unbounded queue growth. The snapshot row is unaffected;
    change_summary stays NULL until the next save fills it.
    """
    executor = _get_summary_executor()
    # ThreadPoolExecutor exposes its work queue via the private
    # ``_work_queue`` attribute. The qsize() reading is approximate
    # (queue is concurrent-safe but the value can be stale by the
    # time we read it) but the soft cap intentionally tolerates drift.
    try:
        qsize = executor._work_queue.qsize()
    except Exception:
        qsize = 0
    if qsize >= _SUMMARY_QUEUE_SOFT_CAP:
        logger.warning(
            "Summary executor queue at {} items (cap {}); dropping task. "
            "NoteVersion.change_summary will stay NULL for this save.",
            qsize,
            _SUMMARY_QUEUE_SOFT_CAP,
        )
        return
    # Wrap in thread_cleanup so the worker clears its thread-local DB
    # session AND the cached (username, password) entry in
    # _thread_credentials when it returns. The summary pool's threads are
    # long-lived (they never die), so cleanup_dead_threads never sweeps
    # them — without this the plaintext SQLCipher password the worker
    # captured would sit in the pool thread's dict for the whole process
    # lifetime (the #4182 credential-hygiene class). Mirrors the idiom
    # every other executor in the codebase uses (e.g. news_strategy).
    try:
        executor.submit(thread_cleanup(fn), *args, **kwargs)
    except RuntimeError:
        # The pool was shut down (graceful restart / atexit) between the
        # _get_summary_executor() read above and this submit. change_summary is
        # best-effort, so drop it rather than let the RuntimeError bubble up and
        # 500 a note save whose content already committed durably.
        logger.warning(
            "Summary executor shut down before task submit; "
            "NoteVersion.change_summary will stay NULL for this save."
        )


def _shutdown_summary_executor() -> None:
    # Race fix: the matching getter at _get_summary_executor holds the
    # lock for its read-modify-write of _summary_executor; the shutdown
    # path must hold the same lock or a request thread can observe a
    # half-replaced reference (e.g. submit() into an already-shut-down
    # executor → RuntimeError) during gunicorn graceful shutdown.
    global _summary_executor
    with _summary_executor_lock:
        if _summary_executor is not None:
            _summary_executor.shutdown(wait=True)
            _summary_executor = None


atexit.register(_shutdown_summary_executor)


def _populate_change_summary_async(
    username: str,
    dbpw: Optional[str],
    version_id: str,
    old_content: str,
    new_content: str,
) -> None:
    """Background worker: ask the LLM for a change summary and UPDATE the
    already-persisted NoteVersion row.

    ``dbpw`` is the encrypted-DB password captured on the request thread by
    ``_capture_request_db_password`` and threaded in explicitly because
    stdlib ``ThreadPoolExecutor`` does not propagate the request's
    ``ContextVar`` snapshot — without it, ``get_user_db_session`` raises
    ``DatabaseSessionError`` on every encrypted-DB install. It's named
    ``dbpw`` rather than ``db_password`` to avoid a gitleaks generic-secret
    false positive (that rule matches a ``password=<8+ char literal>`` shape);
    the value is a passthrough credential, never a hardcoded secret.

    Exceptions are logged but never raised — this runs on a thread pool and
    a failure here must not crash the worker.
    """
    try:
        from .note_ai_service import NoteAIService

        # Pass dbpw so the LLM-settings lookup inside
        # summarize_changes_sync -> _get_llm() can open the encrypted DB on
        # this worker thread (no request context to resolve the password
        # from).
        ai_service = NoteAIService(username, dbpw=dbpw)
        # summarize_changes_sync, NOT asyncio.run(summarize_changes(...)):
        # bridging the async core on a throwaway loop per summary is the
        # #6293 hazard, not a safe bridge. The langchain OpenAI/Anthropic
        # async client is cached once per process with no loop in its
        # cache key, so a second loop reusing a keep-alive connection
        # opened by the uvicorn request loop fails with "Event loop is
        # closed" after the request was already sent (the openai SDK
        # silently re-sends it), and the closed loop can leave an orphaned
        # transport fd behind. (_close_base_llm in utilities/llm_utils.py
        # may still run asyncio.run(async_httpx.aclose()) on this thread
        # for a freshly built per-instance Ollama client; that's safe
        # because that client was never driven on any loop.)
        # The sync path shares its prompt, shortcuts and teardown with the
        # async core; only the LLM call differs. The executor thread
        # blocks for this one task, exactly as it did before.
        summary = ai_service.summarize_changes_sync(old_content, new_content)
        if not summary:
            return

        with get_user_db_session(username, password=dbpw) as session:
            row = session.query(NoteVersion).filter_by(id=version_id).first()
            if row is None:
                logger.debug(
                    "Version {} disappeared before summary landed; skipping",
                    version_id[:8],
                )
                return
            # Fill-only guard: this worker is only ever scheduled for a
            # freshly inserted snapshot (change_summary=None). Refuse to
            # overwrite an existing summary so a caller bug (e.g. passing
            # a dedup-absorbed historical version id) can't corrupt the
            # audit trail.
            if row.change_summary is not None:
                logger.warning(
                    "Version {} already has a change summary; refusing to "
                    "overwrite it",
                    version_id[:8],
                )
                return
            row.change_summary = summary
            session.commit()
            logger.debug(
                "Filled change summary for note version {}", version_id[:8]
            )
    except Exception:
        logger.exception(
            "Async change-summary worker failed for version {}",
            version_id[:8] if version_id else "<none>",
        )


# Regex for parsing [[wiki-style links]]. The negated class is bounded by
# MAX_LINK_TEXT_LENGTH so an unclosed ``[[`` doesn't capture multi-MB of
# body and ship it as a SQL parameter twice (exact + startswith) against
# the unindexed LOWER(title) column. It also excludes newlines (``\n``): a
# note title is a single-line String(500), so a ``[[`` whose closing
# ``]]`` is on a later line is an unclosed bracket, not a link. This
# mirrors the frontend's ``WIKILINK_TARGET = [^\]\n]+`` in
# web/static/js/services/formatting.js so parse (which creates NoteLink
# rows) and render (which draws the link) agree — previously the backend
# admitted newlines and created links the UI never rendered.
MAX_LINK_TEXT_LENGTH = 500
LINK_PATTERN = re.compile(r"\[\[([^\]\n]{1,500})\]\]")

# Cap on parsed wiki-links per note. Without this, a pathological note
# (e.g. 50 MB of `[[A]]\n` lines = millions of matches) would spawn
# millions of NoteLink rows on save and have each one trigger 2-3
# database queries through ``_resolve_link_internal``. 1000 covers any
# realistic note (Roam/Obsidian power users typically have <100 links
# per note); anything beyond is silently truncated and a warning logged
# rather than failing the save.
MAX_LINKS_PER_NOTE = 1000

# Mirrors SQLite's built-in lower(): ASCII-only case folding. Link
# resolution folds titles in SQL, and the batched exact-title lookup has
# to match lower(title) values computed BY THE DATABASE back to
# Python-side link texts — so the Python fold must be the database's.
# str.lower() folds full Unicode ('Ü' → 'ü') and would diverge.
_SQLITE_LOWER_TABLE = str.maketrans(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"
)


def _fold_title_ascii(text: str) -> str:
    return (text or "").translate(_SQLITE_LOWER_TABLE)


# SQLITE_MAX_VARIABLE_NUMBER is 999 on older SQLite builds; chunk IN()
# lists well below it so a 1000-link note can't overflow the bind-param
# limit.
_IN_CLAUSE_CHUNK = 500

# Caps on per-note many-to-many list params accepted by the route
# layer. Mirror MAX_TAGS_PER_NOTE in spirit: bound how many DocumentCollection
# / NoteResearch rows a single create or reorder request can spawn.
MAX_COLLECTIONS_PER_NOTE = 50
MAX_RESEARCH_PER_NOTE = 200

# Mirrors BaseExporter.MAX_CONTENT_SIZE at exporters/base.py:63. Kept inline
# rather than imported because exporters/__init__.py unconditionally pulls in
# weasyprint via all 5 exporter modules — importing BaseExporter would drag a
# heavy dependency into note CRUD. Extract to a dep-light constants module if
# sharing ever becomes worthwhile.
NOTE_CONTENT_MAX_BYTES = 50 * 1024 * 1024  # 50 MB

# Cap on version-history rows per note. Auto-save can otherwise grow
# note_versions unboundedly — a near-50 MB note with small changes x 100 saves
# = ~5 GB. Pure FIFO: simplest rule with useful value; the `initial` version
# can be pruned, but the user still has 100 recent snapshots to fall back on.
MAX_VERSIONS_PER_NOTE = 100
# Audit bookends (PRE_RESTORE / RESTORE) are excluded from the normal version
# prune so the "restored here" trail survives heavy editing — but they still
# need a ceiling, or repeated restores grow note_versions without bound. Keep
# the most recent N bookends.
MAX_BOOKEND_VERSIONS = 40

# PRE_RESTORE / RESTORE are the audit bookends excluded from version-dedup
# (their hashes are salted) and from the prune pool (the "restored here" trail
# survives heavy editing).
_AUDIT_BOOKEND_TYPES = (
    NoteChangeType.PRE_RESTORE.value,
    NoteChangeType.RESTORE.value,
)


def _assert_content_size(content: str) -> None:
    """Raise ValueError if content isn't a string or exceeds
    NOTE_CONTENT_MAX_BYTES.

    The type check matters for direct API callers: a truthy non-string
    body value (e.g. ``{"content": 123}``) passes the route layer's
    ``if not content`` guard, and without this check ``.encode()`` raised
    an AttributeError that surfaced as an opaque 500 instead of the 400
    the routes' ``except ValueError`` mapping produces.
    """
    if not isinstance(content, str):
        raise ValueError("content must be a string")
    if content and len(content.encode("utf-8")) > NOTE_CONTENT_MAX_BYTES:
        raise ValueError(
            f"Note content exceeds maximum size "
            f"({NOTE_CONTENT_MAX_BYTES // (1024 * 1024)} MB)"
        )


# Mirrors MAX_TAG_LENGTH in note-detail.js. The frontend caps the input
# field, but direct API callers can still submit arbitrary tag strings.
# Backend validation is the only stop against a 10MB tag landing in the
# JSON ``tags`` column.
MAX_TAG_LENGTH = 50

# Cap the number of tags per note. Without this, ``_validate_tags`` accepts
# an unbounded list — the 50-char per-tag limit then permits multi-MB of
# tag JSON per note, and snapshots store the tag list per version, so the
# 100-version cap multiplies the bloat.
MAX_TAGS_PER_NOTE = 50


def _validate_tags(tags: Optional[List[str]]) -> None:
    """Raise ValueError if ``tags`` isn't a list of short strings.

    None passes (callers may pass None to mean "don't update tags"). An
    empty list passes. Anything else: must be a list, every entry must
    be a string, and each string must be ``<= MAX_TAG_LENGTH`` chars.
    """
    if tags is None:
        return
    if not isinstance(tags, list):
        raise ValueError("tags must be a list")
    if len(tags) > MAX_TAGS_PER_NOTE:
        raise ValueError(f"too many tags (max {MAX_TAGS_PER_NOTE})")
    for tag in tags:
        if not isinstance(tag, str):
            raise ValueError("each tag must be a string")
        if len(tag) > MAX_TAG_LENGTH:
            raise ValueError(
                f"tag exceeds maximum length ({MAX_TAG_LENGTH} chars)"
            )


# Cap on note title length. ``Document.title`` is a plain ``Text`` column
# (unbounded), but the title is interpolated raw into LLM synthesis prompts
# (note_ai_service.py:729) and into ``LOWER(title) == ?`` wiki-link lookups
# (note_service._resolve_link_internal) on every save. Without a cap a
# direct API caller could send a 50 MB title and DoS both paths.
MAX_TITLE_LENGTH = 500


def _validate_title(title: Optional[str]) -> None:
    """Raise ValueError if ``title`` isn't a short non-blank string.

    None passes (callers may pass None to "don't update title"). Empty
    string passes (the route layer's own ``if not title`` check still
    rejects it on create). Whitespace-only strings (``"   "``,
    ``"\\t\\n"``) are explicitly rejected so the slug generator does not
    produce an empty slug and the wiki-link resolver doesn't match an
    invisible title via ``[[ ]]``. Anything else: must be a string and
    at most ``MAX_TITLE_LENGTH`` characters.
    """
    if title is None:
        return
    if not isinstance(title, str):
        raise ValueError("title must be a string")
    # Reject whitespace-only titles. Empty string falls through to the
    # route-layer guard; whitespace-only is truthy and would slip past
    # ``if not title`` checks.
    if title and not title.strip():
        raise ValueError("title must not be blank or whitespace-only")
    if len(title) > MAX_TITLE_LENGTH:
        raise ValueError(
            f"title exceeds maximum length ({MAX_TITLE_LENGTH} chars)"
        )


class NoteService:
    """Service for managing notes (Documents with source_type='note')."""

    DEFAULT_NOTES_COLLECTION_NAME = "Notes"
    SOURCE_TYPE_NAME = "note"

    def __init__(self, username: str):
        """Initialize note service for a user."""
        self.username = username

    @staticmethod
    def _generate_slug(title: str) -> str:
        """Generate a URL-friendly slug from a title.

        Folds Latin accents to ASCII via stdlib NFKD normalization
        (``café`` → ``cafe``). Scripts with no ASCII form (CJK, Cyrillic,
        Arabic) and emoji drop out at the ``encode("ascii", "ignore")`` step.
        A real transliterator is avoided on purpose: the licensed options
        (text-unidecode / python-slugify) are copyleft/GPL, and the slug is a
        non-critical convenience field.

        A title that reduces to nothing gets ``note-<12 hex>`` derived from
        the title itself, NOT the bare ``"note"`` placeholder: that constant
        gave every CJK-, Cyrillic-, Arabic- or emoji-titled note the same
        slug, so two differently titled notes were indistinguishable in the
        autocomplete payload that carries it. Same shape as the fallback
        ``security.filename_sanitizer`` uses for an upload stem werkzeug drops
        (#6108). Whitespace is collapsed first so the fallback treats padding
        and runs the way the ASCII branch above already does.

        Only a title with no content at all still returns ``"note"``.
        """
        ascii_title = (
            unicodedata.normalize("NFKD", title or "")
            .encode("ascii", "ignore")
            .decode("ascii")
        )
        slug = ascii_title.lower()
        slug = re.sub(r"\s+", "-", slug)
        slug = re.sub(r"[^a-z0-9\-]", "", slug)
        slug = re.sub(r"-+", "-", slug)
        slug = slug.strip("-")
        if slug:
            return slug[:500]

        collapsed = re.sub(r"\s+", " ", title or "").strip()
        if not collapsed:
            return "note"
        # Normalized and case-folded first, so the fallback answers the way the
        # ASCII branch above does. That one lowercases and NFKD-folds, so
        # ``Hello`` and ``hello`` share a slug; hashing the raw text would give
        # ``Привет`` and ``привет`` two, and a precomposed vs decomposed
        # spelling of one title two more, for a title that never changed.
        # ``casefold`` on a lone surrogate is a no-op, so the guard below still
        # does its job.
        #
        # surrogatepass: a title round-tripped through a filesystem or a
        # lenient client can carry a lone surrogate, which plain UTF-8
        # encoding raises on. It only feeds the digest — the slug stays ASCII.
        #
        # 12 hex characters is 48 bits, deliberately truncated: this is a
        # convenience label recomputed per request, never stored and never a
        # lookup key, so a collision costs a duplicate label, not a wrong note.
        digest = hashlib.sha256(
            unicodedata.normalize("NFKC", collapsed)
            .casefold()
            .encode("utf-8", errors="surrogatepass")
        ).hexdigest()[:12]
        return f"note-{digest}"

    @staticmethod
    def _compute_content_hash(content: str) -> str:
        """Compute SHA-256 hash of content."""
        return hashlib.sha256(content.encode("utf-8")).hexdigest()

    @staticmethod
    def _compute_version_hash(
        title: Optional[str],
        content: Optional[str],
        tags: Optional[List[str]],
    ) -> str:
        """Compute the dedup hash for a NoteVersion snapshot.

        JSON-encodes the whole ``[title, content, sorted-tags]`` triple and
        hashes that, so title-only / content-only / tag-only edits each get a
        distinct hash and aren't silently deduped against an existing snapshot.
        Tags are sorted first so reordering alone doesn't churn the hash.

        Why JSON the WHOLE triple rather than a NUL-joined string: title and
        content can each contain a literal NUL byte — a JSON ``\\u0000`` in the
        request body decodes to ``\\x00`` and survives SQLite TEXT storage
        untouched (SQLite is length-prefixed, not NUL-terminated), and nothing
        validates it away — so a NUL separator is NOT injection-proof. Pre-fix,
        ``title="MyTitle", content="Hello\\x00World"`` and
        ``title="MyTitle\\x00Hello", content="World"`` produced the identical
        NUL-joined payload and hash, silently dedup-absorbing a genuinely
        different save out of version history. JSON escapes every control
        character (NUL included) as ``\\uXXXX`` and quotes/escapes each element,
        making the encoding injective across all three fields.

        Hash-format note: this serialization differs from older builds', so the
        hash changes for previously-written snapshots. The only consumer is the
        (document_id, content_hash) dedup check, so the sole effect is a
        one-time extra version row the first time a note is re-saved in a state
        that already has an old-format snapshot — benign.
        """
        title_s = "" if title is None else title
        content_s = "" if content is None else content
        sorted_tags = sorted(t for t in (tags or []) if isinstance(t, str))
        payload = json.dumps(
            [title_s, content_s, sorted_tags], ensure_ascii=False
        )
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()

    def _get_note_source_type_id(self, session: Session) -> str:
        """Get the source_type ID for notes, creating it if needed."""
        from . import get_note_source_type_id

        source_type_id = get_note_source_type_id(session)
        if source_type_id:
            return source_type_id

        # Create it if it doesn't exist (shouldn't happen normally)
        source_type = SourceType(
            id=str(uuid.uuid4()),
            name=self.SOURCE_TYPE_NAME,
            display_name="Note",
            description="User-created notes with AI-enhanced features",
            icon="sticky-note",
        )
        session.add(source_type)
        session.flush()
        return source_type.id

    def _get_or_create_notes_collection(self, session: Session) -> str:
        """Get or create the default Notes collection.

        Serialised by the per-user init lock to prevent two concurrent
        first-note creations (e.g. two browser tabs both creating their
        first note simultaneously) from each seeing no ``collection_type='notes'``
        row and inserting a duplicate. Matches the locking pattern used
        by ``ensure_default_library_collection`` and
        ``ensure_research_history_collection`` in ``database/library_init.py``;
        there is no UNIQUE constraint at the schema level that would
        catch the race otherwise.

        The create path COMMITS inside the lock, for two reasons (both
        matching the ``library_init`` reference pattern):

        1. Lock scope: a flush-only insert leaves the row invisible to
           other sessions until the caller commits — after the lock is
           released — so a second request entering the lock in that window
           would still see no row and insert a duplicate.
        2. Read-only callers: routes like ask-context reach this via
           ``get_notes_collection_id`` and never commit; the request
           teardown ROLLS BACK the shared session, discarding the row
           after its id was already returned to the client.

        Because the commit flushes the caller's whole session, callers
        must resolve the collection BEFORE staging unrelated writes on
        the same session (create_note does).
        """
        from ....database.library_init import _get_user_init_lock

        with _get_user_init_lock(self.username):
            collection = (
                session.query(Collection)
                .filter_by(collection_type="notes")
                .first()
            )

            if collection:
                return collection.id

            collection_id = str(uuid.uuid4())
            collection = Collection(
                id=collection_id,
                name=self.DEFAULT_NOTES_COLLECTION_NAME,
                description="Default collection for notes",
                collection_type="notes",
            )
            session.add(collection)
            try:
                session.commit()
            except Exception:
                session.rollback()
                raise
            # The collection-engine cache may hold this user's pre-creation
            # (empty) engine list from a search within the TTL; drop it so
            # the next research offers the Notes collection as a tool (#6609).
            from ....web_search_engines.search_engines_config import (
                invalidate_collection_engines_cache,
            )

            invalidate_collection_engines_cache(self.username)
            logger.info("Created default Notes collection: {}", collection_id)
            return collection_id

    def get_notes_collection_id(self) -> Optional[str]:
        """Get the default Notes collection ID.

        Returns the collection ID or None if it cannot be determined.
        """
        try:
            with get_user_db_session(self.username) as session:
                return self._get_or_create_notes_collection(session)
        except Exception:
            logger.exception("Error getting notes collection ID")
            return None

    def get_notes_index_status(self) -> Dict[str, Any]:
        """Pre-flight context for "Ask your notes": the Notes collection id,
        the total note count, and how many notes are indexed into it.

        The UI uses this to warn when there is nothing to search — no notes
        at all, or notes that haven't been embedded yet — before kicking off
        a research run pinned to the Notes collection.
        """
        collection_id = self.get_notes_collection_id()
        note_count = self.count_notes()
        indexed_count = 0
        if collection_id:
            with get_user_db_session(self.username) as session:
                indexed_count = (
                    session.query(DocumentCollection)
                    .filter_by(collection_id=collection_id, indexed=True)
                    .count()
                )
        return {
            "collection_id": collection_id,
            "note_count": note_count,
            "indexed_count": indexed_count,
        }

    def _is_note(self, session: Session, document: Document) -> bool:
        """Check if a document is a note."""
        source_type = (
            session.query(SourceType)
            .filter_by(id=document.source_type_id)
            .first()
        )
        return source_type and source_type.name == self.SOURCE_TYPE_NAME

    def _get_note_in_session(
        self, session: Session, note_id: str
    ) -> Optional[Document]:
        """Fetch a Document by id and return it only if it is a note.

        Centralizes the fetch + ``_is_note`` guard prelude that every
        mutating note method hand-copied — and which was half-copied as a
        bug on the collection helpers (they originally skipped the
        ``_is_note`` check, letting a non-note Document acquire note rows).
        Returns ``None`` when the id doesn't exist or the Document isn't a
        note; callers map that to their own bail value.

        Still routes through ``self._is_note`` so the existing
        ``patch.object(NoteService, '_is_note')`` monkeypatches keep firing.
        """
        document = session.query(Document).filter_by(id=note_id).first()
        if document is None or not self._is_note(session, document):
            return None
        return document

    @staticmethod
    def _escape_like(text: str) -> str:
        """Escape LIKE/ILIKE wildcards so user input matches literally.

        Thin alias for the shared :func:`escape_like` so every notes query
        path uses the one canonical escaping rule.
        """
        return escape_like(text)

    @staticmethod
    def _rollback_quietly(session) -> None:
        """Roll back a session after a failed flush/commit, swallowing any
        rollback error. The per-user request session is shared and is NOT
        rolled back by get_user_db_session on exception, so callers that catch
        IntegrityError (and want to retry or surface a clean error) must roll
        back explicitly or the next statement reuses a poisoned session.

        Keeps the None-guard (call sites pass ``locals().get("session")``,
        which may be None) and delegates the actual rollback/log to the
        shared :func:`safe_rollback` helper.
        """
        if session is None:
            return
        safe_rollback(session, "note_service")

    def create_note(
        self,
        title: str,
        content: str,
        tags: Optional[List[str]] = None,
        collection_ids: Optional[List[str]] = None,
    ) -> str:
        """
        Create a new note (stored as a Document).

        Args:
            title: Note title
            content: Note content (markdown)
            tags: Optional list of tags
            collection_ids: Optional list of collection IDs

        Returns:
            The created note/document ID
        """
        _validate_title(title)
        _assert_content_size(content)
        _validate_tags(tags)
        if collection_ids is not None:
            if not isinstance(collection_ids, list):
                raise ValueError("collection_ids must be a list")
            if len(collection_ids) > MAX_COLLECTIONS_PER_NOTE:
                raise ValueError(
                    f"too many collection_ids (max {MAX_COLLECTIONS_PER_NOTE})"
                )
            # Element type check: an unhashable element (dict/list) would
            # otherwise raise TypeError in the de-dupe set comprehension
            # below — an opaque 500 instead of the routes' ValueError→400.
            for cid in collection_ids:
                if not isinstance(cid, str):
                    raise ValueError("each collection_id must be a string")
        try:
            with get_user_db_session(self.username) as session:
                note_id = str(uuid.uuid4())
                source_type_id = self._get_note_source_type_id(session)
                content_hash = self._compute_content_hash(
                    f"{note_id}:{content}"
                )

                # Resolve the default Notes collection BEFORE staging the
                # note: the get-or-create commits when it has to create the
                # collection (see its docstring), and committing after
                # session.add(document) would break this method's
                # one-transaction atomicity for the note itself. A lazily
                # created SourceType (flushed above) riding along on that
                # commit is fine — it's the same kind of idempotent init
                # row as the collection.
                default_collection_id = self._get_or_create_notes_collection(
                    session
                )

                # Create Document with source_type='note'
                document = Document(
                    id=note_id,
                    source_type_id=source_type_id,
                    document_hash=content_hash,
                    file_size=len(content.encode("utf-8")),
                    file_type="note",
                    title=title,
                    text_content=content,
                    tags=tags or [],
                    # DB column stays `favorite` (the flag is shared with the
                    # Document model); the notes API/UI vocabulary for it is
                    # `pinned` (see the `"pinned": document.favorite` response
                    # mapping). One column, two names by design.
                    favorite=False,
                    character_count=len(content),
                    word_count=len(content.split()),
                )
                session.add(document)

                # Add to default Notes collection
                doc_coll = DocumentCollection(
                    document_id=note_id,
                    collection_id=default_collection_id,
                    indexed=False,
                )
                session.add(doc_coll)

                # Add to additional collections. De-dupe and skip ids that
                # don't exist: a repeated id would violate the
                # (document_id, collection_id) UNIQUE and a bogus id would
                # FK-violate — either one aborting the entire note creation
                # with an opaque error.
                if collection_ids:
                    requested = {cid for cid in collection_ids if cid} - {
                        default_collection_id
                    }
                    valid_ids = {
                        row[0]
                        for row in session.query(Collection.id).filter(
                            Collection.id.in_(requested)
                        )
                    }
                    for coll_id in valid_ids:
                        session.add(
                            DocumentCollection(
                                document_id=note_id,
                                collection_id=coll_id,
                                indexed=False,
                            )
                        )

                # Atomicity: Document + DocumentCollection + INITIAL
                # version snapshot + outgoing links all land in one
                # transaction. Pre-fix, the document committed first and
                # the snapshot + link reparse ran in fresh sessions, so a
                # crash between writes left a note with no INITIAL audit
                # row and no parsed [[wiki-links]] — same shape as the
                # bug that update_note already fixed.
                self._create_version_snapshot_in_session(
                    session,
                    note_id=note_id,
                    title=title,
                    content=content,
                    tags=tags,
                    change_type=NoteChangeType.INITIAL.value,
                    change_summary="Initial version",
                )
                self._parse_and_update_links_in_session(
                    session, note_id, content
                )

                try:
                    session.commit()
                except Exception:
                    session.rollback()
                    raise

                # Don't log the title — note titles can carry sensitive
                # content (e.g. medical, personal). Note id alone is
                # enough to correlate with surrounding events.
                logger.info("Created note {}", note_id)

                return note_id

        except Exception:
            # Same atomicity guarantee as update_note: the cached
            # request/thread session does NOT auto-rollback. The
            # in-session helpers (snapshot, link reparse) call
            # session.flush() at the end, so a downstream failure leaves
            # the document INSERT durably flushed without ever committing
            # properly. Rollback explicitly so create_note is atomic.
            # locals().get avoids NameError when the failure happens before
            # `with ... as session` binds; _rollback_quietly no-ops on None.
            self._rollback_quietly(locals().get("session"))
            logger.exception("Error creating note")
            raise

    def note_exists(self, note_id: str) -> bool:
        """Cheap existence + is-note guard for route-level 404 checks.

        Projects only ``Document.id`` filtered by the note source type —
        no ``text_content`` hydration (a plain non-deferred column, up to
        50 MB per row via ``get_note``) and none of ``get_note``'s
        aggregate side queries. Use this wherever the caller only needs
        to know the note is real; ``get_note`` stays for handlers that
        consume the payload.
        """
        if not note_id:
            return False
        with get_user_db_session(self.username) as session:
            note_source_type_id = self._get_note_source_type_id(session)
            if note_source_type_id is None:
                return False
            return (
                session.query(Document.id)
                .filter(
                    Document.id == note_id,
                    Document.source_type_id == note_source_type_id,
                )
                .first()
                is not None
            )

    def get_note(self, note_id: str) -> Optional[Dict[str, Any]]:
        """Get a note by ID.

        The response includes an ``outgoing_links`` map (link_text →
        target_id, target_title) so the frontend can resolve
        ``[[wiki-links]]`` to the correct target Document at render
        time, regardless of whether the target has since been renamed.
        Pre-fix the frontend resolved by title text alone via
        ``navigateToNoteByTitle``, so renaming a linked note silently
        broke every existing ``[[OldTitle]]`` in other notes' content.
        """
        try:
            with get_user_db_session(self.username) as session:
                document = self._get_note_in_session(session, note_id)
                if document is None:
                    return None

                result = self._document_to_note_dict(document, session)

                # Outgoing-link resolution table for the frontend wiki-link
                # renderer. Keep this lean (only the link_text and the
                # target_id/title) — the full backlinks payload is served
                # by GET /api/notes/<id>/outgoing-links on demand.
                outgoing_links = (
                    session.query(
                        NoteLink.link_text,
                        Document.id,
                        Document.title,
                    )
                    .join(NoteLink, Document.id == NoteLink.target_document_id)
                    .filter(NoteLink.source_document_id == note_id)
                    .all()
                )
                result["outgoing_links"] = [
                    {
                        "link_text": row.link_text,
                        "target_id": row.id,
                        "target_title": row.title,
                    }
                    for row in outgoing_links
                ]
                return result

        except Exception:
            logger.exception("Error getting note {}", note_id)
            raise

    def update_note(
        self,
        note_id: str,
        title: Optional[str] = None,
        content: Optional[str] = None,
        tags: Optional[List[str]] = None,
        favorite: Optional[bool] = None,
        _link_overrides: Optional[Dict[str, str]] = None,
        _append_link_title: Optional[str] = None,
    ) -> bool:
        """Update a note.

        Naming note: ``favorite`` matches ``Document.favorite`` (the column
        backing this state). The user-facing UI vocabulary is "pin"; the
        wire format keeps ``pinned`` for that reason and the route layer
        translates. Don't rename the kwarg back without also updating the
        Document column.

        ``_append_link_title`` (internal, used by ``accept_suggested_link``):
        when set, the new body is derived from the note's CURRENT content —
        loaded fresh inside this method's write transaction — by appending a
        ``[[title]]`` wiki-link, rather than being passed in precomputed by the
        caller. This keeps the read-modify-write atomic and closes the
        lost-update window where a concurrent save committed after the caller's
        precondition read would otherwise be clobbered. Mutually exclusive with
        ``content``.
        """
        _validate_title(title)
        # Empty title is allowed on create's route-level guard, but here on
        # update an explicit empty string would erase a previously valid
        # title with no semantic meaning. Reject it.
        if title is not None and not title:
            raise ValueError("title must not be empty")
        if content is not None:
            _assert_content_size(content)
        _validate_tags(tags)
        try:
            with get_user_db_session(self.username) as session:
                document = self._get_note_in_session(session, note_id)
                if document is None:
                    return False

                # Append-mode (accept_suggested_link): derive the new body from
                # the FRESHLY loaded row inside this write transaction, rather
                # than from a value the caller read in an earlier, now-closed
                # session. Doing the read-modify-write in one transaction closes
                # the lost-update window where a concurrent save committed
                # between the caller's precondition read and this write would
                # otherwise be silently clobbered.
                _append_reparse_only = False
                if _append_link_title is not None:
                    current = document.text_content or ""
                    # If the exact wiki-link text is already in the body, don't
                    # DUPLICATE the line — but STILL reparse links so the target
                    # NoteLink is created/updated. This covers two cases:
                    #  (a) a concurrent second accept of the SAME suggestion
                    #      (double-submit / two tabs / a retry after a
                    #      processed-but-timed-out response) whose first accept
                    #      already appended the line and created the NoteLink —
                    #      the reparse is then an idempotent no-op; and
                    #  (b) accepting a suggestion for a link the user had TYPED
                    #      while it was still unresolved (no NoteLink row exists
                    #      yet, e.g. the target note was created later). Skipping
                    #      the reparse here would make the user's explicit accept
                    #      a silent no-op that never creates the link.
                    if f"[[{_append_link_title}]]" in current:
                        content = None
                        _append_reparse_only = True
                    else:
                        content = (
                            current.rstrip() + f"\n\n[[{_append_link_title}]]\n"
                        )
                        _assert_content_size(content)

                content_changed = (
                    content is not None and content != document.text_content
                )
                title_changed = title is not None and title != document.title
                # Tags are part of the version state (they participate in
                # _compute_version_hash). A tag-only edit must produce a
                # snapshot — otherwise the hash improvement is dead code on
                # this path and the user's version history silently misses
                # tag-only changes.
                #
                # Use sorted() so reordering the same tag set
                # (e.g. ["b","a"] vs ["a","b"]) doesn't flip the trigger.
                # _compute_version_hash already sorts before hashing, so an
                # order-only "change" would just create a dedup-absorbed
                # snapshot trigger, wasting work; aligning the comparison
                # keeps trigger and hash consistent.
                tags_changed = tags is not None and sorted(
                    t for t in tags if isinstance(t, str)
                ) != sorted(
                    t for t in (document.tags or []) if isinstance(t, str)
                )
                old_content = document.text_content

                if title is not None:
                    document.title = title
                if content is not None:
                    document.text_content = content
                    document.character_count = len(content)
                    document.word_count = len(content.split())
                    document.document_hash = self._compute_content_hash(
                        f"{note_id}:{content}"
                    )
                    document.file_size = len(content.encode("utf-8"))
                if tags is not None:
                    document.tags = tags
                if favorite is not None:
                    document.favorite = favorite

                # Atomicity: document update + version snapshot + link
                # rewrite all share the same transaction. Pre-fix, each
                # ran in its own session, so a crash between them left a
                # committed content change with no MANUAL_SAVE row
                # or with zero outgoing links. The AI change-summary
                # generation still runs off-thread — it's enqueued AFTER
                # commit so a failed transaction won't leave a stranded
                # background task.
                version_id: Optional[str] = None
                version_created = False
                # (0, 0) means "prune wasn't run this call" as well as "ran
                # but nothing was over cap" — both cases skip the post-commit
                # log the same way, so a single sentinel default covers both.
                prune_counts: "tuple[int, int]" = (0, 0)
                # The version-snapshot INSERT is flushed inside
                # _create_version_snapshot_in_session, so a concurrent
                # identical-content save's UNIQUE(uix_note_version_content)
                # collision can fire at THAT flush, not only at the commit
                # below. Wrap the whole snapshot + link-reparse + commit block
                # so it is caught and recovered in one place — previously the
                # recovery guarded only commit(), so a flush-time collision
                # 500'd a benign concurrent save (the recovery was dead code).
                try:
                    if content_changed or title_changed or tags_changed:
                        (
                            version_id,
                            version_created,
                        ) = self._create_version_snapshot_in_session(
                            session,
                            note_id=note_id,
                            title=document.title,
                            content=document.text_content,
                            tags=document.tags,
                            change_type=NoteChangeType.MANUAL_SAVE.value,
                            change_summary=None,
                        )
                        # Counts are only bound here, not logged — the
                        # delete is merely flushed, and this whole block can
                        # still roll back below (IntegrityError recovery) or
                        # in the outer handler. Logging happens after
                        # session.commit() succeeds, so the log never claims
                        # a prune a rollback undid.
                        prune_counts = self._prune_versions_in_session(
                            session, note_id
                        )

                    if content_changed or _append_reparse_only:
                        # In append-reparse-only mode `content` is None (the body
                        # already held the link text); reparse the CURRENT body
                        # so the override still binds the NoteLink to the target.
                        self._parse_and_update_links_in_session(
                            session,
                            note_id,
                            content
                            if content is not None
                            else (document.text_content or ""),
                            link_overrides=_link_overrides,
                        )

                    # Stale-vector fix: when the note's content or title
                    # changes, mark its embeddings stale (both indexed-state
                    # sources) so the auto-index worker re-embeds AND the RAG
                    # status report doesn't keep showing it as indexed. See
                    # _mark_note_stale_for_reindex_in_session.
                    if content_changed or title_changed:
                        self._mark_note_stale_for_reindex_in_session(
                            session, note_id
                        )

                    session.commit()
                    # Only reachable once the transaction holding the prune
                    # deletes has actually committed — see
                    # _prune_versions_in_session for why this can't log
                    # from inside the prune itself.
                    self._log_version_prune(note_id, prune_counts)
                except IntegrityError as exc:
                    # Concurrency: two same-note saves carrying byte-identical
                    # content both pass the in-session dedup pre-check in
                    # _create_version_snapshot_in_session (neither sees the
                    # other's uncommitted row), then race to INSERT the same
                    # (document_id, content_hash). The winner commits; the
                    # loser hits UNIQUE(uix_note_version_content) — at the
                    # snapshot flush above or at the commit. That
                    # collision means the identical version already exists and
                    # the winner already persisted the identical document
                    # content — so the user's save IS reflected. Recover
                    # (rollback + return success) instead of 500'ing.
                    #
                    # Discriminator: only the version-dedup constraint carries
                    # "content_hash" (SQLite reports the offending columns,
                    # Postgres the constraint name uix_note_version_content —
                    # both contain "content_hash"). Any other IntegrityError
                    # (e.g. a NoteLink uix_note_link violation from the link
                    # reparse) must still surface, so re-raise it.
                    self._rollback_quietly(session)
                    err = (
                        str(exc.orig).lower() if exc.orig else str(exc).lower()
                    )
                    if "content_hash" not in err:
                        raise
                    logger.debug(
                        "Concurrent identical-content save of note {} "
                        "collided on the version-dedup UNIQUE; the existing "
                        "version already represents this content. Treating as "
                        "success.",
                        note_id,
                    )
                    # The winner persisted the identical VERSIONED state
                    # (title/content/tags — the fields in the version
                    # hash), but ``favorite`` is not hashed: a loser that
                    # also carried a pin change had it rolled back with
                    # the rest of its transaction, so returning success
                    # here would silently drop the pin. Re-apply it in a
                    # fresh transaction — a favorite-only UPDATE cannot
                    # collide on the version constraint. A failure here
                    # propagates (outer handler) rather than reporting a
                    # success the DB doesn't reflect.
                    if favorite is not None:
                        refetched = self._get_note_in_session(session, note_id)
                        if (
                            refetched is not None
                            and refetched.favorite != favorite
                        ):
                            refetched.favorite = favorite
                            session.commit()
                    return True

                logger.info("Updated note {}", note_id)

                # Post-commit: enqueue the LLM change-summary worker. The
                # snapshot row already exists with change_summary=None; the
                # worker UPDATEs it when the LLM returns. Only schedule it
                # for a genuinely NEW row: when the dedup check absorbed
                # the snapshot into an existing version (e.g. the user
                # reverted to an exact prior state), version_id points at a
                # HISTORICAL row whose change_summary the worker would
                # overwrite with a description of this much later edit.
                if (
                    version_id
                    and version_created
                    and content_changed
                    and content is not None
                ):
                    # NB: intentionally NOT gated on `old_content` being
                    # truthy. A first-content edit of a previously blank/NULL
                    # note (old_content "" or None) is still worth summarizing
                    # — the change-summary path handles it cheaply (`if not
                    # old_content: return "Note created"`, no LLM call). Gating
                    # on truthy old_content left that MANUAL_SAVE version's
                    # change_summary NULL forever.
                    # Capture the DB password from the request thread now;
                    # the worker runs on a stdlib ThreadPoolExecutor which
                    # does NOT copy ContextVar state, so the worker cannot
                    # locate the password itself.
                    dbpw = _capture_request_db_password(self.username)
                    if dbpw is None:
                        # Without the password the worker can't open the
                        # encrypted DB to write the summary. Pre-fix this
                        # was silently dropped by the worker itself; log
                        # explicitly and skip the submit so operators can
                        # see WHY summaries are missing.
                        logger.warning(
                            "Skipping AI change-summary for version {}: "
                            "DB password not available in request thread.",
                            version_id,
                        )
                    else:
                        _submit_summary_task(
                            _populate_change_summary_async,
                            self.username,
                            dbpw,
                            version_id,
                            old_content,
                            content,
                        )

                return True

        except Exception:
            # ``get_user_db_session``'s context manager does NOT rollback
            # on exception (it returns a cached request- or thread-scoped
            # session whose lifecycle is managed elsewhere). Helpers like
            # ``_create_version_snapshot_in_session`` call ``session.flush()``
            # at the end so a downstream failure (e.g. in link reparse)
            # would otherwise leave the document UPDATE durably flushed
            # without ever committing properly. Rollback explicitly here
            # so the atomicity guarantee holds.
            # ``session`` is bound iff we entered the with block; locals().get
            # avoids NameError when the failure happens before then, and
            # _rollback_quietly no-ops on None.
            self._rollback_quietly(locals().get("session"))
            logger.exception("Error updating note {}", note_id)
            raise

    def delete_note(self, note_id: str) -> bool:
        """Delete a note.

        Before the row is removed we collect the set of collections this note
        was indexed into, because the ``Document → DocumentCollection``
        cascade fires on delete and would otherwise hide them. After the
        delete commits we purge the corresponding ``DocumentChunk`` rows for
        each indexed collection via
        ``LibraryRAGService.purge_document_chunks`` — NOT
        ``remove_document_from_rag``, which looks the document up by its
        (now cascade-deleted) ``DocumentCollection`` join row and would
        silently no-op.

        Both halves of the RAG state are purged: the FAISS vectors first
        (``purge_document_vectors`` — replace-on-reindex can never fire
        again for a deleted document id, and the shared search flows
        rehydrate snippets straight from the ``DocumentChunk`` rows in the
        (encrypted) DB by id, with no Document-existence check, so
        lingering vectors would serve the deleted note's text
        indefinitely), then the ``DocumentChunk`` rows
        (``purge_document_chunks``). The ghost-hit filter in
        ``NoteAIService.semantic_search`` / ``find_similar_passages``
        remains as the safety net for cleanup failures and pre-fix
        leftovers.
        """
        try:
            indexed_collection_ids: List[str] = []
            with get_user_db_session(self.username) as session:
                document = self._get_note_in_session(session, note_id)
                if document is None:
                    return False

                # Capture (before the cascade destroys them) every collection
                # where this note might have vectors to purge: the UNION of
                # DocumentCollection.indexed=True AND collections that actually
                # have chunk rows. The chunk-row half is essential — an edited
                # note has indexed=False during the edit->reindex window while
                # its pre-edit chunks/vectors still exist, so gating on the
                # indexed flag alone would strand orphaned vectors.
                indexed_rows = (
                    session.query(DocumentCollection.collection_id)
                    .filter_by(document_id=note_id, indexed=True)
                    .all()
                )
                chunk_rows = (
                    session.query(DocumentChunk.collection_name)
                    .filter_by(source_type="document", source_id=note_id)
                    .distinct()
                    .all()
                )
                indexed_collection_ids = list(
                    {row[0] for row in indexed_rows}
                    | {
                        row[0].removeprefix("collection_")
                        for row in chunk_rows
                        if row[0]
                    }
                )

                session.delete(document)
                session.commit()
                logger.info("Deleted note {}", note_id)

            # Best-effort FAISS / chunk cleanup. Failures must not surface
            # to the user (the DB delete already committed) but should be
            # logged for ops visibility.
            if indexed_collection_ids:
                dbpw = _capture_request_db_password(self.username)
                from ...services.rag_service_factory import get_rag_service

                for collection_id in indexed_collection_ids:
                    try:
                        # A FRESH service per collection, built via the
                        # factory so it resolves THAT collection's stored
                        # embedding model/provider (get_rag_service reads
                        # Collection settings; a hardcoded-default
                        # LibraryRAGService would compute the wrong index
                        # hash and silently purge nothing for any
                        # non-default-embedding collection). Per-collection
                        # instances also avoid one collection's cached
                        # ``rag_index_record`` / loaded vector index
                        # carrying over into another collection's
                        # ``purge_document_vectors`` call.
                        with get_rag_service(
                            self.username,
                            collection_id=collection_id,
                            db_password=dbpw,
                        ) as rag:
                            # Vectors BEFORE chunk rows: purge_document_vectors
                            # -> VectorIndex.delete looks up the DocumentChunk
                            # rows by (source_type, source_id, collection_name)
                            # to learn which FAISS int ids to remove, and
                            # deletes those matching rows itself. The rows
                            # must still exist when this runs, or the lookup
                            # finds nothing and the vectors (and their
                            # persisted text) are stranded in the FAISS store
                            # forever. purge_document_chunks below then only
                            # has to catch whatever purge_document_vectors
                            # didn't match (e.g. no current FAISS index).
                            rag.purge_document_vectors(note_id, collection_id)
                            # purge_document_chunks, not
                            # remove_document_from_rag: the Document (and
                            # its DocumentCollection join row) is already
                            # cascade-deleted, so the join-row lookup in
                            # remove_document_from_rag would no-op and
                            # leave the chunks orphaned.
                            rag.purge_document_chunks(note_id, collection_id)
                    except Exception:
                        # exception=True keeps the stack trace. `dbpw` is a
                        # live local, but frame-local values render only under
                        # the opt-in LDR_LOGURU_DIAGNOSE dev flag — every
                        # persistent sink sets diagnose=False — so the password
                        # cannot leak into logs in normal operation.
                        logger.opt(exception=True).error(
                            "Failed to remove RAG entries for note {} "
                            "from collection {}",
                            note_id,
                            collection_id,
                        )

            # Guaranteed backstop: delete any DocumentChunk rows the per-
            # collection purge above could not reach (get_rag_service failing
            # because the request-thread password is unavailable, a transient
            # FAISS/DB error, a stored-config mismatch). chunk_text holds the
            # note's content and collection search rehydrates hits purely by
            # DocumentChunk.id — a surviving row would keep serving the deleted
            # note's text. The matching orphaned vector then resolves to no row
            # and is filtered out. Mirrors DocumentDeletionService's backstop.
            try:
                with get_user_db_session(self.username) as sweep_session:
                    sweep_session.query(DocumentChunk).filter_by(
                        source_type="document", source_id=note_id
                    ).delete(synchronize_session=False)
                    sweep_session.commit()
            except Exception:
                logger.opt(exception=True).error(
                    "Failed to sweep residual chunk rows for note {}", note_id
                )

            return True

        except Exception:
            logger.exception("Error deleting note {}", note_id)
            raise

    def _build_filtered_notes_query(
        self,
        session: Session,
        collection_id: Optional[str],
        search: Optional[str],
        pinned_only: bool,
    ):
        """Build the filtered Document query used by both ``list_notes``
        and ``count_notes``. Centralising the filter shape keeps the
        list response and its ``total`` count in lockstep.
        """
        source_type_id = self._get_note_source_type_id(session)
        query = session.query(Document).filter(
            Document.source_type_id == source_type_id
        )

        if collection_id:
            query = query.join(DocumentCollection).filter(
                DocumentCollection.collection_id == collection_id
            )

        if search:
            search_pattern = f"%{self._escape_like(search)}%"
            query = query.filter(
                or_(
                    Document.title.ilike(search_pattern, escape="\\"),
                    Document.text_content.ilike(search_pattern, escape="\\"),
                )
            )

        if pinned_only:
            query = query.filter(Document.favorite.is_(True))

        return query

    def count_notes(
        self,
        collection_id: Optional[str] = None,
        search: Optional[str] = None,
        pinned_only: bool = False,
    ) -> int:
        """Count notes matching the same filter as ``list_notes``.

        Used by the list endpoint so the frontend can render real
        pagination controls (page-N-of-M, "load more" with bounded
        progress, etc.) without having to call ``list_notes`` with a
        huge limit just to compute the size.
        """
        with get_user_db_session(self.username) as session:
            return self._build_filtered_notes_query(
                session, collection_id, search, pinned_only
            ).count()

    def list_notes(
        self,
        collection_id: Optional[str] = None,
        search: Optional[str] = None,
        pinned_only: bool = False,
        limit: int = 100,
        offset: int = 0,
    ) -> List[Dict[str, Any]]:
        """List notes with optional filtering."""
        try:
            with get_user_db_session(self.username) as session:
                query = self._build_filtered_notes_query(
                    session, collection_id, search, pinned_only
                )

                query = query.order_by(
                    Document.favorite.desc(),
                    Document.updated_at.desc(),
                    # Stable tiebreaker: without it, notes sharing an
                    # updated_at (bulk-created) have no guaranteed order, so
                    # offset pagination ("Load more") could repeat or skip
                    # rows between pages; mirrors the mention/link panels.
                    Document.id.desc(),
                )

                query = query.offset(offset).limit(limit)
                documents = query.all()

                if not documents:
                    return []

                doc_ids = [d.id for d in documents]

                # Batched aggregates: replaces 3 per-row sub-queries inside
                # _document_to_note_dict with 3 grouped queries total. Default
                # limit=100 went from 300 extra queries/page to 3.
                collection_counts = dict(
                    session.query(
                        DocumentCollection.document_id,
                        func.count(DocumentCollection.id),
                    )
                    .filter(DocumentCollection.document_id.in_(doc_ids))
                    .group_by(DocumentCollection.document_id)
                    .all()
                )
                research_counts = dict(
                    session.query(
                        NoteResearch.document_id,
                        func.count(NoteResearch.id),
                    )
                    .filter(NoteResearch.document_id.in_(doc_ids))
                    .group_by(NoteResearch.document_id)
                    .all()
                )
                indexed_rows = (
                    session.query(DocumentCollection)
                    .filter(
                        DocumentCollection.document_id.in_(doc_ids),
                        DocumentCollection.indexed.is_(True),
                    )
                    .all()
                )
                indexed_by_doc: Dict[str, DocumentCollection] = {}
                for row in indexed_rows:
                    # Mirror prior .first() semantics: first indexed row wins
                    indexed_by_doc.setdefault(row.document_id, row)

                return [
                    self._document_to_note_dict(
                        doc,
                        session,
                        _collection_count=collection_counts.get(doc.id, 0),
                        _research_count=research_counts.get(doc.id, 0),
                        _indexed_coll=indexed_by_doc.get(doc.id),
                        include_full_content=False,
                    )
                    for doc in documents
                ]

        except Exception:
            logger.exception("Error listing notes")
            raise

    def add_to_collection(self, note_id: str, collection_id: str) -> bool:
        """Add a note to a collection."""
        try:
            with get_user_db_session(self.username) as session:
                # Only operate on notes — every other mutating method guards
                # with _is_note, but these collection helpers did not, so a
                # non-note Document id could get note-collection rows attached.
                doc = self._get_note_in_session(session, note_id)
                if doc is None:
                    return False

                # Validate the target collection exists before inserting the
                # join row. Otherwise a stale/bogus collection_id trips the FK
                # constraint and surfaces as a generic 500 instead of a clean
                # 404 (mirrors create_note, which filters to valid ids).
                collection = (
                    session.query(Collection)
                    .filter_by(id=collection_id)
                    .first()
                )
                if collection is None:
                    raise LookupError(  # noqa: TRY301 — except logs and re-raises to the route as a 404
                        f"Collection {collection_id} not found"
                    )

                existing = (
                    session.query(DocumentCollection)
                    .filter_by(document_id=note_id, collection_id=collection_id)
                    .first()
                )

                if existing:
                    return False

                doc_coll = DocumentCollection(
                    document_id=note_id,
                    collection_id=collection_id,
                    indexed=False,
                )
                session.add(doc_coll)
                session.commit()
                logger.info(
                    f"Added note {note_id} to collection {collection_id}"
                )
                return True

        except IntegrityError:
            # TOCTOU on UNIQUE(document_id, collection_id): a concurrent add of
            # the same note+collection raced past the existing-row check above.
            # get_user_db_session already rolled the shared session back; return
            # the idempotent "already a member" outcome (route → 409) instead of
            # letting the constraint violation surface as a 500.
            return False
        except Exception:
            logger.exception("Error adding note {} to collection", note_id)
            raise

    def remove_from_collection(self, note_id: str, collection_id: str) -> bool:
        """Remove a note from a collection.

        Raises ValueError when ``collection_id`` is the system Notes
        collection: it is the persistent home of every note (see
        ``_get_or_create_notes_collection``), and the deletion services
        rely on that invariant — a note unlinked from Notes but still in
        a user collection would be hard-deleted as an "orphan" when that
        collection is deleted.
        """
        try:
            was_indexed = False
            with get_user_db_session(self.username) as session:
                doc = self._get_note_in_session(session, note_id)
                if doc is None:
                    return False

                collection = (
                    session.query(Collection)
                    .filter_by(id=collection_id)
                    .first()
                )
                if (
                    collection is not None
                    and collection.collection_type == "notes"
                ):
                    raise ValueError(  # noqa: TRY301 — needs the db session; except logs and re-raises
                        "Cannot remove a note from the Notes collection — "
                        "it is the permanent home of every note"
                    )

                doc_coll = (
                    session.query(DocumentCollection)
                    .filter_by(document_id=note_id, collection_id=collection_id)
                    .first()
                )

                link_existed = doc_coll is not None
                if doc_coll:
                    # Purge if this collection is flagged indexed OR the note
                    # still has chunk rows here — the chunk-row half catches the
                    # edit->reindex window where indexed=False but the pre-edit
                    # chunks/vectors still exist. Captured before the link is
                    # deleted.
                    was_indexed = bool(doc_coll.indexed) or (
                        session.query(DocumentChunk.id)
                        .filter_by(
                            source_type="document",
                            source_id=note_id,
                            collection_name=f"collection_{collection_id}",
                        )
                        .first()
                        is not None
                    )
                    session.delete(doc_coll)
                    session.commit()
                    logger.info(
                        f"Removed note {note_id} from collection {collection_id}"
                    )
                else:
                    # The link is already gone (a concurrent removal). Do NOT
                    # return early: a racing index_document could have (re)created
                    # chunk rows for this (note, collection) AFTER the link was
                    # deleted, and there is no other route-level retry for that
                    # pair — an early return would leave the removed note's
                    # plaintext searchable here forever. Fall through to the
                    # unconditional backstop chunk sweep below (which removes the
                    # plaintext rows); the full RAG vector purge is skipped since
                    # there is no link to unlink.
                    was_indexed = False

            # Best-effort FAISS + chunk cleanup for the collection the note was
            # unlinked from — mirrors delete_note. Without it, the note's chunk
            # rows and vectors linger in that collection's index, so the removed
            # note stays fully searchable there. Vectors BEFORE chunk rows (the
            # int-id lookup needs the rows to still exist). Uses get_rag_service
            # so THAT collection's stored embedding model resolves the right
            # index hash. Failures are logged, not surfaced (the unlink already
            # committed).
            if was_indexed:
                dbpw = _capture_request_db_password(self.username)
                from ...services.rag_service_factory import get_rag_service

                try:
                    with get_rag_service(
                        self.username,
                        collection_id=collection_id,
                        db_password=dbpw,
                    ) as rag:
                        rag.purge_document_vectors(note_id, collection_id)
                        rag.purge_document_chunks(note_id, collection_id)
                except Exception:
                    # exception=True keeps the stack trace. `dbpw` (the DB
                    # password) is a live local, but frame-local values render
                    # only under the opt-in LDR_LOGURU_DIAGNOSE dev flag — every
                    # persistent sink sets diagnose=False — so it cannot leak.
                    logger.opt(exception=True).error(
                        "Failed to purge RAG entries for note {} removed from "
                        "collection {}",
                        note_id,
                        collection_id,
                    )

            # Guaranteed backstop, scoped to THIS collection only (the note
            # survives in its other collections): delete any DocumentChunk rows
            # the purge above could not reach, so the unlinked note's text stops
            # surfacing in this collection's search even when the RAG purge
            # failed. Mirrors DocumentDeletionService's scoped backstop.
            try:
                with get_user_db_session(self.username) as sweep_session:
                    sweep_session.query(DocumentChunk).filter_by(
                        source_type="document",
                        source_id=note_id,
                        collection_name=f"collection_{collection_id}",
                    ).delete(synchronize_session=False)
                    sweep_session.commit()
            except Exception:
                logger.opt(exception=True).error(
                    "Failed to sweep residual chunk rows for note {} in "
                    "collection {}",
                    note_id,
                    collection_id,
                )
            # False when the link was already gone (nothing to unlink), True when
            # this call performed the removal — preserves the prior contract.
            return link_existed

        except Exception:
            logger.exception("Error removing note {} from collection", note_id)
            raise

    def get_note_collections(self, note_id: str) -> List[Dict[str, Any]]:
        """Get collections a note belongs to."""
        try:
            with get_user_db_session(self.username) as session:
                # Use JOIN to avoid N+1 query issue
                results = (
                    session.query(Collection, DocumentCollection)
                    .join(
                        DocumentCollection,
                        Collection.id == DocumentCollection.collection_id,
                    )
                    .filter(DocumentCollection.document_id == note_id)
                    .all()
                )

                return [
                    {
                        "id": coll.id,
                        "name": coll.name,
                        # The UI hides the remove control for the system
                        # Notes collection (every note's persistent home;
                        # remove_from_collection refuses it server-side).
                        "collection_type": coll.collection_type,
                        "indexed": dc.indexed,
                        "chunk_count": dc.chunk_count or 0,
                    }
                    for coll, dc in results
                ]

        except Exception:
            logger.exception("Error getting collections for note {}", note_id)
            raise

    def get_note_research(self, note_id: str) -> List[Dict[str, Any]]:
        """Get research runs triggered from a note."""
        try:
            with get_user_db_session(self.username) as session:
                note_research = (
                    session.query(NoteResearch)
                    .options(joinedload(NoteResearch.research))
                    .filter_by(document_id=note_id)
                    .order_by(NoteResearch.display_order.asc())
                    .all()
                )

                return [
                    {
                        "id": nr.id,
                        "research_id": nr.research_id,
                        "search_engine": (nr.research.research_meta or {})
                        .get("submission", {})
                        .get("search_engine")
                        if nr.research
                        else None,
                        "research_mode": nr.research.mode
                        if nr.research
                        else None,
                        "query_used": nr.research.query
                        if nr.research
                        else None,
                        "display_order": nr.display_order,
                        "is_collapsed": nr.is_collapsed,
                        "created_at": nr.created_at.isoformat()
                        if nr.created_at
                        else None,
                    }
                    for nr in note_research
                ]

        except Exception:
            logger.exception("Error getting research for note {}", note_id)
            raise

    # Max retries on display_order UNIQUE collision. The old value of 5
    # was contention-fragile: colliding threads re-read MAX(display_order)
    # in lockstep, so under 6+ concurrent same-note links one thread could
    # lose all 5 races and 500 the user (dropping the link). Each retry can
    # only fail because another writer landed at the same display_order, and
    # the number of concurrent NoteResearch inserts is itself bounded by
    # MAX_RESEARCH_PER_NOTE — so a budget comfortably above that, combined
    # with the randomized jitter below, makes losing every race effectively
    # impossible while never masking a non-retryable error.
    _LINK_RESEARCH_MAX_RETRIES = MAX_RESEARCH_PER_NOTE + 10

    def link_research_to_note(
        self,
        note_id: str,
        research_id: str,
    ) -> int:
        """Link a research run to a note.

        Concurrency: two same-user requests (e.g. double-click or two
        tabs) can both observe the same MAX(display_order) and try to
        insert with the same display_order. The UNIQUE constraint on
        (document_id, display_order) added in migration 0021 turns the
        race into an IntegrityError; we catch it, rollback, recompute
        MAX, and retry up to a small bound. The
        (document_id, research_id) UniqueConstraint is separate — that
        one signals "research already linked", which surfaces as
        IntegrityError too. We distinguish the two by looking for the
        ``display_order`` token in the error: SQLite reports the offending
        COLUMNS (not the constraint name) and Postgres reports the constraint
        name ``uix_note_research_display_order`` — both contain
        ``display_order``, while the duplicate-link and FK errors do not. Only
        the display_order collision is retryable; everything else surfaces
        immediately so a legitimate duplicate link (or an FK violation) isn't
        masked by burning retries.
        """
        for attempt in range(self._LINK_RESEARCH_MAX_RETRIES):
            session = None
            try:
                with get_user_db_session(self.username) as session:
                    # Every other mutating method guards with _is_note;
                    # without this, a NoteResearch row can be attached to
                    # any Document (e.g. an uploaded PDF) — orphaned rows
                    # the notes UI never renders.
                    doc = self._get_note_in_session(session, note_id)
                    if doc is None:
                        raise ValueError(  # noqa: TRY301 — needs the db session; except rolls back and re-raises
                            f"Note {note_id} not found"
                        )

                    # Enforce MAX_RESEARCH_PER_NOTE where rows are created
                    # (this is the only NoteResearch creation site). The
                    # cap previously existed only in reorder_note_research,
                    # so a note could grow past it and then every reorder
                    # of the (necessarily full) list failed on the same
                    # cap — permanently un-reorderable.
                    existing_count = (
                        session.query(func.count(NoteResearch.id))
                        .filter_by(document_id=note_id)
                        .scalar()
                    )
                    if existing_count >= MAX_RESEARCH_PER_NOTE:
                        raise ValueError(  # noqa: TRY301 — needs the db session; except rolls back and re-raises
                            f"too many linked researches "
                            f"(max {MAX_RESEARCH_PER_NOTE})"
                        )

                    # Use MAX(display_order) + 1, not COUNT, so deleting an
                    # earlier link can't make the next insert reuse an
                    # existing display_order. Research runs CASCADE-delete
                    # NoteResearch rows when a ResearchHistory is removed,
                    # so COUNT < MAX+1 is a real possibility.
                    max_order = (
                        session.query(
                            func.coalesce(
                                func.max(NoteResearch.display_order), -1
                            )
                        )
                        .filter_by(document_id=note_id)
                        .scalar()
                    )

                    note_research = NoteResearch(
                        document_id=note_id,
                        research_id=research_id,
                        display_order=max_order + 1,
                    )
                    session.add(note_research)
                    session.commit()
                    logger.info(
                        "Linked research {} to note {}", research_id, note_id
                    )
                    return note_research.id

            except IntegrityError as exc:
                # The shared per-user request session is NOT rolled back by the
                # context manager on exception (it only closes a session it
                # created), so without an explicit rollback the next retry reuses
                # a poisoned session and fails identically.
                self._rollback_quietly(session)
                msg = str(exc.orig).lower() if exc.orig else str(exc).lower()
                # Only a (document_id, display_order) collision is retryable.
                # The duplicate (document_id, research_id) link and FK violations
                # contain no "display_order" token → surface immediately.
                if "display_order" not in msg:
                    raise
                if attempt + 1 == self._LINK_RESEARCH_MAX_RETRIES:
                    logger.exception(
                        "Giving up linking research {} to note {} after "
                        "{} display_order collisions",
                        research_id,
                        note_id,
                        self._LINK_RESEARCH_MAX_RETRIES,
                    )
                    raise
                logger.debug(
                    "display_order collision linking research {} to note "
                    "{} (attempt {}); retrying",
                    research_id,
                    note_id,
                    attempt + 1,
                )
                # Backoff with randomized jitter so colliding threads
                # don't re-read MAX(display_order) in perfect lockstep and
                # collide again on the very next attempt. Spreading the
                # retries breaks the synchronized contention that made a
                # fixed, no-backoff budget exhaustible under load.
                # noqa S311: jitter for retry-backoff scheduling, not a
                # security/crypto context — non-CSPRNG randomness is fine.
                time.sleep(random.uniform(0, 0.01 * (attempt + 1)))  # noqa: S311
                continue
            except Exception:
                self._rollback_quietly(session)
                logger.exception("Error linking research to note {}", note_id)
                raise

        # Unreachable — the loop either returns or raises.
        raise RuntimeError("link_research_to_note exhausted retries")

    def get_notes_for_research(
        self, research_id: str
    ) -> Optional[List[Dict[str, Any]]]:
        """List the notes linked to a research run, newest link first.

        The reverse direction of ``get_research_for_note`` — powers the
        Notes panel on the research results page. Returns ``None`` when
        the research run doesn't exist (the route maps that to 404,
        distinct from "exists but has no notes yet" → ``[]``).

        Column-projected like ``get_backlinks``: ``text_content`` can be
        megabytes per note, and this renders a card list that needs only
        a short preview.
        """
        from ....database.models import ResearchHistory

        preview_len = self.LIST_CONTENT_PREVIEW_CHARS
        with get_user_db_session(self.username) as session:
            if (
                session.query(ResearchHistory.id)
                .filter_by(id=research_id)
                .first()
                is None
            ):
                return None
            rows = (
                session.query(
                    Document.id,
                    Document.title,
                    func.substr(Document.text_content, 1, preview_len + 1),
                    Document.updated_at,
                    NoteResearch.created_at,
                )
                .join(NoteResearch, NoteResearch.document_id == Document.id)
                .filter(NoteResearch.research_id == research_id)
                .order_by(NoteResearch.created_at.desc())
                .all()
            )
            notes = []
            for note_id, title, preview, updated_at, linked_at in rows:
                preview = self._truncate_preview(preview, preview_len)
                notes.append(
                    {
                        "id": note_id,
                        "title": title,
                        "content_preview": preview,
                        "updated_at": updated_at.isoformat()
                        if updated_at
                        else None,
                        "linked_at": linked_at.isoformat()
                        if linked_at
                        else None,
                    }
                )
            return notes

    def _create_note_with_cleanup(
        self, title, content, tags, link_fn, context_label
    ):
        """Create a note and run its post-create ``link_fn`` step
        atomically: if linking raises, delete the just-created note so no
        orphan survives, then re-raise the original error.

        Shared by ``create_note_for_research`` /
        ``create_note_for_document`` — the two paths that create-then-link,
        where a mid-step failure would otherwise leave a note the user
        never asked for. ``context_label`` is the full link-step phrase up
        to (and including) its preposition, so the log reads naturally
        (e.g. ``"Linking research <id> to"`` → "... to fresh note ...").
        """
        note_id = self.create_note(title=title, content=content, tags=tags)
        try:
            link_fn(note_id)
        except Exception:
            logger.exception(
                "{} fresh note {} failed; removing the note so the "
                "operation stays all-or-nothing",
                context_label,
                note_id,
            )
            try:
                self.delete_note(note_id)
            except Exception:
                # Both halves failed — surface the original linking error;
                # the orphan note is visible (not silently lost data).
                logger.exception(
                    "Cleanup of orphan note {} also failed", note_id
                )
            raise
        return note_id

    def create_note_for_research(
        self,
        research_id: str,
        title: Optional[str] = None,
        content: Optional[str] = None,
        tags: Optional[List[str]] = None,
        quote: Optional[str] = None,
        prefix: Optional[str] = None,
        suffix: Optional[str] = None,
    ) -> str:
        """Create a note and link it to a research run, all-or-nothing.

        Used by the results page ("Add note", "Save as note", clip). The
        research row is checked FIRST so a bogus id gets a clean
        ``LookupError`` (route → 404) instead of creating an orphan note
        and then FK-failing on the link. If the link step fails anyway
        (e.g. a concurrent research delete), the just-created note is
        removed so the caller never observes a half-done operation.

        ``title``/``content`` default to a starter derived from the
        research query, so the "Add note" button needs no user input
        before navigating into the editor.
        """
        from ....database.models import ResearchHistory

        with get_user_db_session(self.username) as session:
            research = (
                session.query(ResearchHistory.id, ResearchHistory.query)
                .filter_by(id=research_id)
                .first()
            )
        if research is None:
            raise LookupError("Research not found")

        query_text = (research.query or "").strip()
        if not title:
            title = f"Notes on: {query_text}"[:MAX_TITLE_LENGTH]
        if not content:
            label = escape_markdown_link_label(query_text or research_id)
            content = (
                f"> Notes on the research run "
                f"[{label}](/results/{research_id}).\n\n"
            )

        def _link(new_note_id):
            self.link_research_to_note(new_note_id, research_id)
            if quote:
                # An inline annotation: also record the quote anchor so the
                # results page can highlight the passage (NULL-quote
                # references are plain links and skip this).
                self._add_reference(
                    new_note_id,
                    target_research_id=research_id,
                    quote=quote,
                    prefix=prefix,
                    suffix=suffix,
                )

        return self._create_note_with_cleanup(
            title, content, tags, _link, f"Linking research {research_id} to"
        )

    def _add_reference(
        self,
        note_id: str,
        target_document_id: Optional[str] = None,
        target_research_id: Optional[str] = None,
        quote: Optional[str] = None,
        prefix: Optional[str] = None,
        suffix: Optional[str] = None,
    ) -> int:
        """Insert a NoteReference row (see the model for semantics)."""
        with get_user_db_session(self.username) as session:
            ref = NoteReference(
                note_id=note_id,
                target_document_id=target_document_id,
                target_research_id=target_research_id,
                quote=quote,
                prefix=prefix,
                suffix=suffix,
            )
            session.add(ref)
            try:
                session.commit()
            except Exception:
                self._rollback_quietly(session)
                raise
            return ref.id

    def get_notes_for_document(
        self, document_id: str
    ) -> Optional[List[Dict[str, Any]]]:
        """List the notes referencing a library document, newest first.

        Returns ``None`` when the document doesn't exist (route → 404).
        Column-projected like ``get_notes_for_research``; a note with
        several references (e.g. two annotations) appears once.
        """
        preview_len = self.LIST_CONTENT_PREVIEW_CHARS
        with get_user_db_session(self.username) as session:
            if (
                session.query(Document.id).filter_by(id=document_id).first()
                is None
            ):
                return None
            rows = (
                session.query(
                    Document.id,
                    Document.title,
                    func.substr(Document.text_content, 1, preview_len + 1),
                    Document.updated_at,
                    func.max(NoteReference.created_at),
                )
                .join(NoteReference, NoteReference.note_id == Document.id)
                .filter(NoteReference.target_document_id == document_id)
                .group_by(Document.id)
                .order_by(func.max(NoteReference.created_at).desc())
                .all()
            )
            notes = []
            for note_id, title, preview, updated_at, linked_at in rows:
                preview = self._truncate_preview(preview, preview_len)
                notes.append(
                    {
                        "id": note_id,
                        "title": title,
                        "content_preview": preview,
                        "updated_at": updated_at.isoformat()
                        if updated_at
                        else None,
                        "linked_at": linked_at.isoformat()
                        if linked_at
                        else None,
                    }
                )
            return notes

    def create_note_for_document(
        self,
        document_id: str,
        title: Optional[str] = None,
        content: Optional[str] = None,
        tags: Optional[List[str]] = None,
        quote: Optional[str] = None,
        prefix: Optional[str] = None,
        suffix: Optional[str] = None,
    ) -> str:
        """Create a note referencing a library document, all-or-nothing.

        The document-side twin of ``create_note_for_research``. Targets
        must be non-note documents: annotating a NOTE is deliberately
        unsupported — notes are mutable, so quote anchors would drift on
        every edit (the re-anchoring problem); library documents' extracted
        text is immutable, like research reports.
        """
        with get_user_db_session(self.username) as session:
            row = (
                session.query(Document.id, Document.title)
                .filter_by(id=document_id)
                .first()
            )
            if row is None:
                raise LookupError("Document not found")
            note_source_type_id = self._get_note_source_type_id(session)
            is_note = (
                session.query(Document.id)
                .filter_by(id=document_id, source_type_id=note_source_type_id)
                .first()
                is not None
            )
            if is_note:
                raise ValueError(
                    "notes cannot be annotated — their content is mutable, "
                    "so quote anchors would drift on edit; annotate library "
                    "documents or research reports instead"
                )
            doc_title = (row.title or "").strip() or document_id

        if not title:
            title = f"Notes on: {doc_title}"[:MAX_TITLE_LENGTH]
        if not content:
            label = escape_markdown_link_label(doc_title)
            content = (
                f"> Notes on the document "
                f"[{label}](/library/document/{document_id}).\n\n"
            )

        def _link(new_note_id):
            self._add_reference(
                new_note_id,
                target_document_id=document_id,
                quote=quote,
                prefix=prefix,
                suffix=suffix,
            )

        return self._create_note_with_cleanup(
            title,
            content,
            tags,
            _link,
            f"Referencing document {document_id} from",
        )

    def get_annotations_for_target(
        self,
        document_id: Optional[str] = None,
        research_id: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """List the anchored references (inline annotations) for a target.

        Existence of the target is the caller's concern (the routes check
        it for the 404); a valid target with no anchors returns ``[]``.
        """
        preview_len = self.LIST_CONTENT_PREVIEW_CHARS
        with get_user_db_session(self.username) as session:
            q = (
                session.query(
                    NoteReference.note_id,
                    NoteReference.quote,
                    NoteReference.prefix,
                    NoteReference.suffix,
                    NoteReference.created_at,
                    Document.title,
                    func.substr(Document.text_content, 1, preview_len + 1),
                )
                .join(Document, Document.id == NoteReference.note_id)
                .filter(NoteReference.quote.isnot(None))
            )
            if document_id is not None:
                q = q.filter(NoteReference.target_document_id == document_id)
            else:
                q = q.filter(NoteReference.target_research_id == research_id)
            annotations = []
            for row in q.order_by(NoteReference.created_at.asc()).all():
                (
                    note_id,
                    quote,
                    prefix,
                    suffix,
                    created_at,
                    title,
                    preview,
                ) = row
                preview = self._truncate_preview(preview, preview_len)
                annotations.append(
                    {
                        "note_id": note_id,
                        "quote": quote or "",
                        "prefix": prefix or "",
                        "suffix": suffix or "",
                        "created_at": created_at.isoformat()
                        if created_at
                        else None,
                        "note_title": title,
                        "comment_preview": preview,
                    }
                )
            return annotations

    def has_annotation(
        self,
        note_id: str,
        document_id: Optional[str] = None,
        research_id: Optional[str] = None,
    ) -> bool:
        """True when an anchored reference ties note_id to the target
        (the DELETE routes' precondition)."""
        with get_user_db_session(self.username) as session:
            q = session.query(NoteReference.id).filter(
                NoteReference.note_id == note_id,
                NoteReference.quote.isnot(None),
            )
            if document_id is not None:
                q = q.filter(NoteReference.target_document_id == document_id)
            else:
                q = q.filter(NoteReference.target_research_id == research_id)
            return q.first() is not None

    def update_note_research(
        self,
        note_id: str,
        research_id: str,
        is_collapsed: Optional[bool] = None,
    ) -> bool:
        """Update a NoteResearch row. Currently supports toggling is_collapsed.

        Returns True if the row was found and updated, False otherwise.
        """
        try:
            with get_user_db_session(self.username) as session:
                nr = (
                    session.query(NoteResearch)
                    .filter_by(document_id=note_id, research_id=research_id)
                    .first()
                )
                if not nr:
                    return False
                if is_collapsed is not None:
                    nr.is_collapsed = bool(is_collapsed)
                session.commit()
                return True
        except Exception:
            logger.exception(
                f"Error updating note_research for {note_id}/{research_id}"
            )
            raise

    def reorder_note_research(
        self, note_id: str, research_ids: List[str]
    ) -> bool:
        """Atomically reorder NoteResearch rows for a note so their
        display_order matches the position in research_ids.

        Validates every id belongs to the note before updating.
        Returns True on success.

        Two-pass write because of the
        ``UniqueConstraint('document_id', 'display_order')`` added in
        migration 0021: assigning the final order directly would hit
        an intermediate state where two rows share the same
        display_order (e.g. swapping idx 0 and 2 would try to put
        idx-2 at 0 while idx-0 is still at 0). The first pass moves
        every row into the negative display_order range — guaranteed
        not to collide with the positive target values — and the
        second pass assigns the final positive values.
        """
        if not isinstance(research_ids, list):
            raise ValueError("research_ids must be a list")
        if len(research_ids) > MAX_RESEARCH_PER_NOTE:
            raise ValueError(
                f"too many research_ids (max {MAX_RESEARCH_PER_NOTE})"
            )
        # A duplicate id collapses in a set, so a set-equality check alone would
        # accept e.g. ['A','B','A'] for a note linking {A,B} and then assign A
        # two positions — silently corrupting the order. Reject duplicates.
        if len(research_ids) != len(set(research_ids)):
            return False
        session = None
        try:
            with get_user_db_session(self.username) as session:
                existing = (
                    session.query(NoteResearch)
                    .filter_by(document_id=note_id)
                    .all()
                )
                existing_ids = {nr.research_id for nr in existing}
                if set(research_ids) != existing_ids:
                    return False

                by_id = {nr.research_id: nr for nr in existing}
                # Pass 1: park every row in the negative range so the
                # second pass can assign 0..N-1 without colliding with
                # the existing positive display_orders.
                for idx, rid in enumerate(research_ids):
                    by_id[rid].display_order = -(idx + 1)
                session.flush()
                # Pass 2: final positive values.
                for idx, rid in enumerate(research_ids):
                    by_id[rid].display_order = idx
                session.commit()
                return True
        except Exception:
            # Roll back so a failed flush/commit doesn't leave the shared
            # request session poisoned for the rest of the request.
            self._rollback_quietly(session)
            logger.exception("Error reordering research for note {}", note_id)
            raise

    # Sentinel used by _document_to_note_dict to distinguish "caller passed
    # None as the precomputed value (i.e. document is not indexed)" from
    # "caller did not pass anything; query the DB". Plain None can't carry
    # both meanings.
    _UNSET = object()

    # Upper bound on body size returned in list-view responses. Frontend
    # only ever shows the first ~150 chars; shipping the entire ``text_content``
    # column meant a 200-note page could download multiple MB. The 300-char
    # cap leaves headroom over the UI cap so the truncation isn't visible
    # at the cut-off boundary.
    LIST_CONTENT_PREVIEW_CHARS = 300

    def _document_to_note_dict(
        self,
        document: Document,
        session: Session,
        _collection_count: Any = _UNSET,
        _research_count: Any = _UNSET,
        _indexed_coll: Any = _UNSET,
        include_full_content: bool = True,
    ) -> Dict[str, Any]:
        """Convert a Document to a note dict.

        The three ``_``-prefixed kwargs let list_notes pre-batch the
        aggregate queries (count of collections / research links / first
        indexed-collection row) into 3 grouped SQL statements instead of
        3*N per-row sub-queries. Single-doc callers (get_note) leave them
        unset and pay the per-row cost.
        """
        if _collection_count is self._UNSET:
            _collection_count = (
                session.query(DocumentCollection)
                .filter_by(document_id=document.id)
                .count()
            )
        if _research_count is self._UNSET:
            _research_count = (
                session.query(NoteResearch)
                .filter_by(document_id=document.id)
                .count()
            )
        if _indexed_coll is self._UNSET:
            _indexed_coll = (
                session.query(DocumentCollection)
                .filter_by(document_id=document.id, indexed=True)
                .first()
            )

        collection_count = _collection_count
        research_count = _research_count
        indexed_coll = _indexed_coll

        text_content = document.text_content or ""
        if include_full_content:
            content_value: Optional[str] = text_content
            content_preview: Optional[str] = None
        else:
            content_value = None
            content_preview = self._truncate_preview(
                text_content, self.LIST_CONTENT_PREVIEW_CHARS
            )

        return {
            "id": document.id,
            "title": document.title,
            "content": content_value,
            "content_preview": content_preview,
            "tags": document.tags or [],
            "pinned": document.favorite,
            "is_indexed": indexed_coll is not None,
            "chunk_count": indexed_coll.chunk_count if indexed_coll else 0,
            "last_indexed_at": indexed_coll.last_indexed_at.isoformat()
            if indexed_coll and indexed_coll.last_indexed_at
            else None,
            "created_at": document.created_at.isoformat()
            if document.created_at
            else None,
            "updated_at": document.updated_at.isoformat()
            if document.updated_at
            else None,
            "collection_count": collection_count,
            "research_count": research_count,
        }

    # =========================================================================
    # Version History Methods
    # =========================================================================

    def _create_version_snapshot_in_session(
        self,
        session: Session,
        note_id: str,
        title: str,
        content: str,
        tags: Optional[List[str]],
        change_type: str,
        change_summary: Optional[str] = None,
    ) -> "tuple[str, bool]":
        """Create a NoteVersion row in an existing session.

        Caller is responsible for committing. Used by ``restore_with_bookends``
        to keep PRE_RESTORE + content update + RESTORE in a single
        transaction so process death between writes can't lose the audit
        trail. Dedup is preserved via the (document_id, content_hash)
        check; on a hit, returns the existing version id without inserting.

        Returns ``(version_id, created)``: ``created`` is False when the
        dedup check absorbed the snapshot into an existing row. Callers
        that schedule the async change-summary worker MUST check it —
        passing a dedup-absorbed (historical) version id to the worker
        would overwrite that old row's change_summary with a description
        of a much later edit.

        Note that ``content_hash`` is computed over title + content + tags
        via ``_compute_version_hash`` so title-only or tag-only edits
        produce a distinct hash and aren't silently deduped against an
        existing snapshot. The column name stays ``content_hash`` for
        schema compatibility but its semantics are "version-state hash".
        """
        # NoteVersion.content/tags are NOT NULL (note.py), but the source
        # this snapshots — Document.text_content — IS nullable, and the
        # restore bookend path passes document fields through uncoerced.
        # Coerce here so the version table is never stricter than the row
        # it captures (a NULL would raise IntegrityError on flush). Title
        # is already NOT NULL upstream.
        content = content or ""
        tags = tags or []
        # PRE_RESTORE and RESTORE are audit bookends: by definition their
        # state hash matches an existing version row (PRE_RESTORE = current
        # state, which IS the prior MANUAL_SAVE; RESTORE = the target
        # version's state). Dedup + UNIQUE(document_id, content_hash) would
        # silently drop the bookend, erasing the "user restored here" audit
        # signal. Salt the hash with a fresh UUID for these change types so
        # each row is guaranteed to insert.
        #
        # INVARIANT WARNING for future contributors: for PRE_RESTORE and
        # RESTORE rows, ``content_hash`` is NOT reproducible from
        # ``(title, content, tags)`` via _compute_version_hash — the salt
        # is hash-only and is NOT persisted into the ``tags`` column
        # (clean user-facing data). Any integrity checker that walks
        # NoteVersion rows and recomputes hashes MUST filter on
        # ``change_type NOT IN ('pre_restore', 'restore')`` before
        # comparing — otherwise it will see every restore event as
        # corrupted. Removing the salt to "fix" the divergence would
        # silently reintroduce the audit-row-drop bug this guards
        # against; if you find yourself reaching for that, add a
        # change_type column to the UNIQUE constraint instead.
        is_audit_bookend = change_type in _AUDIT_BOOKEND_TYPES
        if is_audit_bookend:
            salted_tags = list(tags or []) + [
                f"__{change_type}__{uuid.uuid4()}"
            ]
            content_hash = self._compute_version_hash(
                title, content, salted_tags
            )
        else:
            content_hash = self._compute_version_hash(title, content, tags)
            existing = (
                session.query(NoteVersion)
                .filter_by(document_id=note_id, content_hash=content_hash)
                .first()
            )
            if existing:
                return (existing.id, False)

        version_id = str(uuid.uuid4())
        version = NoteVersion(
            id=version_id,
            document_id=note_id,
            title=title,
            content=content,
            tags=tags or [],
            change_type=change_type,
            change_summary=change_summary,
            content_hash=content_hash,
        )
        session.add(version)
        session.flush()
        return (version_id, True)

    def _mark_note_stale_for_reindex_in_session(
        self, session: Session, note_id: str
    ) -> None:
        """Mark a note's embeddings stale after a content/title change.

        Two indexed-state sources must move together:

        * ``DocumentCollection.indexed`` — the legacy flag the auto-index
          worker scans (it runs with ``force_reindex=False``, so a stale
          ``indexed=True`` makes it short-circuit and keep serving the
          pre-edit embedding).
        * ``RagDocumentStatus`` — row-existence is the *canonical* "indexed"
          marker that the RAG status route and ``get_rag_stats`` read.

        ``index_document`` writes BOTH on index; the edit path must clear
        BOTH or the status report shows an edited note as still-indexed
        until (and unless) a re-index actually runs. Deleting the status
        row matches the model's "no row = not indexed" contract — an edited
        note genuinely isn't currently indexed; the worker re-creates the
        row when it re-embeds. Caller commits.
        """
        session.query(DocumentCollection).filter_by(document_id=note_id).update(
            {DocumentCollection.indexed: False},
            synchronize_session=False,
        )
        session.query(RagDocumentStatus).filter_by(document_id=note_id).delete(
            synchronize_session=False
        )

    def _prune_versions_in_session(
        self, session: Session, note_id: str
    ) -> "tuple[int, int]":
        """Prune ordinary and restore-bookend versions to independent caps.

        Caller is responsible for committing. Used by both ``update_note``
        (after its in-session snapshot write) and ``restore_with_bookends``
        (which adds PRE_RESTORE + RESTORE rows without consuming the ordinary
        version budget).

        Returns ``(ordinary_pruned, bookend_pruned)`` — the number of rows
        this call's own DELETE statements actually removed, counted from
        the rows the database itself reports deleting (``DELETE ...
        RETURNING``; same SQLite/SQLCipher baseline the chat service's
        ``UPDATE ... RETURNING`` counters already rely on). The prune
        selects the ids of the oldest rows over the cap, then deletes
        exactly those ids: when a concurrently-committed transaction has
        removed some of them in the SELECT→DELETE window, this call's
        DELETE matches fewer rows and that smaller, honest number is
        returned — never the fetched count, which the previous
        per-instance ``session.delete()`` implementation reported even
        when its DELETE matched nothing (SQLAlchemy only warns on that
        mismatch for non-versioned mappers). The counts therefore never
        over-report what this call removed; they say nothing about rows
        other transactions deleted, and can be lower than the excess the
        caps imply when concurrent pruners shared the work.

        The deletes run in the caller's transaction but are NOT committed
        here: if that transaction later rolls back, these rows survive.
        Callers must NOT log these counts themselves until after their own
        ``session.commit()`` succeeds — logging here (before the commit)
        would claim a prune that a subsequent rollback undoes, turning the
        one operator-facing signal for version loss into a false positive
        on exactly the failure paths it exists to surface. See
        ``update_note`` and ``restore_with_bookends`` for the post-commit
        logging call.
        """
        ordinary_pruned = 0
        ordinary_total = (
            session.query(NoteVersion)
            .filter_by(document_id=note_id)
            .filter(NoteVersion.change_type.notin_(_AUDIT_BOOKEND_TYPES))
            .count()
        )
        excess = ordinary_total - MAX_VERSIONS_PER_NOTE
        if excess > 0:
            # Audit bookends have their own cap below and never reduce the
            # number of ordinary snapshots retained for the user.
            oldest_ids = [
                row_id
                for (row_id,) in session.query(NoteVersion.id)
                .filter_by(document_id=note_id)
                .filter(NoteVersion.change_type.notin_(_AUDIT_BOOKEND_TYPES))
                .order_by(NoteVersion.created_at.asc(), NoteVersion.id.asc())
                .limit(excess)
                .all()
            ]
            if oldest_ids:
                # Delete by the fetched primary keys and count what the
                # DELETE actually matched — the rows the DB reports via
                # RETURNING — not what the SELECT fetched. Under a
                # concurrently-committed delete of the same rows, the ORM's
                # per-instance session.delete() path only WARNS on the
                # rowcount mismatch yet would report the fetched count.
                # synchronize_session=False leaves these rows persistent in the
                # session identity map until commit — do not touch NoteVersion
                # instances after this call.
                result = session.execute(
                    delete(NoteVersion)
                    .where(NoteVersion.id.in_(oldest_ids))
                    .returning(NoteVersion.id)
                    .execution_options(synchronize_session=False)
                )
                ordinary_pruned = len(result.all())

        # Separately bound the bookend pool. Excluding bookends from the prune
        # above keeps the restore trail, but each restore writes two
        # un-prunable rows, so without this ceiling repeated restores grow
        # note_versions without limit. Keep the most recent MAX_BOOKEND_VERSIONS.
        bookend_pruned = 0
        bookend_total = (
            session.query(NoteVersion)
            .filter_by(document_id=note_id)
            .filter(NoteVersion.change_type.in_(_AUDIT_BOOKEND_TYPES))
            .count()
        )
        bookend_excess = bookend_total - MAX_BOOKEND_VERSIONS
        if bookend_excess > 0:
            oldest_bookend_ids = [
                row_id
                for (row_id,) in session.query(NoteVersion.id)
                .filter_by(document_id=note_id)
                .filter(NoteVersion.change_type.in_(_AUDIT_BOOKEND_TYPES))
                .order_by(NoteVersion.created_at.asc(), NoteVersion.id.asc())
                .limit(bookend_excess)
                .all()
            ]
            if oldest_bookend_ids:
                # Same delete-matched counting as the ordinary prune above.
                result = session.execute(
                    delete(NoteVersion)
                    .where(NoteVersion.id.in_(oldest_bookend_ids))
                    .returning(NoteVersion.id)
                    .execution_options(synchronize_session=False)
                )
                bookend_pruned = len(result.all())
        return (ordinary_pruned, bookend_pruned)

    def _log_version_prune(
        self, note_id: str, prune_counts: "tuple[int, int]"
    ) -> None:
        """Log a prune event. Call ONLY after the caller's transaction has
        committed successfully — see ``_prune_versions_in_session`` for why.

        Emits aggregate counts only (never note content or titles), and
        only when at least one row was actually pruned, so log volume
        stays at most one line per save/restore that triggers a prune —
        not one line per pruned version.
        """
        ordinary_pruned, bookend_pruned = prune_counts
        if ordinary_pruned or bookend_pruned:
            logger.info(
                "note version prune: note_id={} ordinary={} bookend={}",
                note_id,
                ordinary_pruned,
                bookend_pruned,
            )

    def restore_with_bookends(
        self, note_id: str, version_id: str
    ) -> "tuple[bool, Optional[str]]":
        """Restore a note to a previous version atomically.

        Wraps PRE_RESTORE snapshot + content update + RESTORE snapshot in
        a single transaction. Earlier code did three separate sessions —
        process death between writes could leave a restored note with
        no audit-trail row. With this method, either all three writes
        land or none do.

        Returns ``(success, error_code)``:
          * ``(True, None)`` — restore complete
          * ``(False, "note_not_found")`` — no document with that id, or
            it isn't a note
          * ``(False, "version_not_found")`` — version id doesn't exist
            for this note
          * ``(False, "internal_error")`` — exception during restore;
            check logs

        The route layer maps these to HTTP statuses.
        """
        try:
            with get_user_db_session(self.username) as session:
                document = self._get_note_in_session(session, note_id)
                if document is None:
                    return (False, "note_not_found")

                version = (
                    session.query(NoteVersion)
                    .filter_by(document_id=note_id, id=version_id)
                    .first()
                )
                if not version:
                    return (False, "version_not_found")

                # Capture for post-session use (link re-parse)
                v_title = version.title
                v_content = version.content
                v_tags = version.tags

                # PRE_RESTORE snapshot of the current document state
                self._create_version_snapshot_in_session(
                    session,
                    note_id,
                    document.title,
                    document.text_content,
                    document.tags,
                    NoteChangeType.PRE_RESTORE.value,
                )

                # Apply the restore to the document
                document.title = v_title
                document.text_content = v_content
                document.tags = v_tags
                content_str = v_content or ""
                document.character_count = len(content_str)
                document.word_count = len(content_str.split())
                document.document_hash = self._compute_content_hash(
                    f"{note_id}:{content_str}"
                )
                document.file_size = len(content_str.encode("utf-8"))

                # RESTORE snapshot marking the post-restore state
                self._create_version_snapshot_in_session(
                    session,
                    note_id,
                    v_title,
                    v_content,
                    v_tags,
                    NoteChangeType.RESTORE.value,
                    change_summary=f"Restored to version {version_id[:8]}",
                )

                # Prune to cap; with bookends the count can exceed the
                # cap by 2 in a single transaction. The deletes are only
                # flushed here — this whole transaction can still roll
                # back below (stale-reindex or link-reparse failure), so
                # the counts are logged only after session.commit()
                # succeeds, not here. See _prune_versions_in_session.
                prune_counts = self._prune_versions_in_session(session, note_id)

                # Stale-vector fix (mirrors update_note): a restore changes
                # content/title, so mark its embeddings stale across both
                # indexed-state sources — the auto-index worker re-embeds
                # and the RAG status report stops showing the pre-restore
                # state as indexed. See _mark_note_stale_for_reindex_in_session.
                self._mark_note_stale_for_reindex_in_session(session, note_id)

                # Re-parse wiki-links INSIDE the restore transaction (against
                # the freshly-restored content), exactly like update_note —
                # NOT in a separate post-commit session. A post-commit reparse
                # raced a concurrent update_note: that save wrote correct
                # NoteLink rows for its NEW content inside its own transaction,
                # then this stale reparse (computed from the restored content)
                # reverted them, leaving the link graph (backlinks/outgoing/
                # unlinked-mentions) inconsistent with Document.text_content.
                # Trade-off: a reparse failure now rolls the whole restore back
                # (the same contract update_note already has) instead of
                # logging and leaving a committed-but-mis-linked restore — an
                # acceptable, consistent change for link-graph correctness.
                self._parse_and_update_links_in_session(
                    session, note_id, v_content or ""
                )

                session.commit()
                self._log_version_prune(note_id, prune_counts)

            return (True, None)

        except Exception:
            logger.exception(
                f"Error restoring version {version_id} for note {note_id}"
            )
            return (False, "internal_error")

    # Note: get_note_versions / get_version / restore_version were removed
    # in PR #3277 — the route layer (web/routers/notes.py) reimplements these
    # queries directly because they need fine-grained control over the
    # session lifetime (e.g., the restore route's PRE_RESTORE/RESTORE
    # bookend snapshots). The service-layer versions had zero callers.
    # Re-add them only when a non-route caller (CLI, scheduled task)
    # actually needs them.

    # =========================================================================
    # Wiki Linking Methods
    # =========================================================================

    # NOTE: ``_parse_and_update_links_in_session`` is used by both
    # ``create_note`` and ``update_note`` so the content insert/update +
    # link rewrite land in a single transaction (atomicity).
    def _parse_and_update_links_in_session(
        self,
        session: Session,
        note_id: str,
        content: str,
        link_overrides: Optional[Dict[str, str]] = None,
    ) -> List[Dict[str, Any]]:
        """Parse [[wiki-style links]] and update NoteLink rows in an
        existing session.

        Caller is responsible for committing. Used by ``update_note`` and
        ``create_note`` so the content update + link rewrite land in one
        transaction — a failure mid-parse rolls the content change back
        with it. The standalone ``_parse_and_update_links`` keeps its own
        session and is used by ``restore_with_bookends`` which has
        explicitly chosen to reparse outside its restore transaction
        (documented at the call site).

        ``link_overrides`` (lowercased link text → target_document_id) lets
        a caller bind a specific ``[[text]]`` to an exact target id.
        ``accept_suggested_link`` passes it so a suggestion accepted for one
        of several same-titled notes links to THAT note — not whichever the
        title resolver happens to pick.

        Resolution priority per link: (1) ``link_overrides``; (2) the id this
        exact link text resolved to before (the rename-safety cache, now
        PREFERRED over a fresh lookup so an accepted/established link stays
        id-stable across reparse instead of being silently retargeted to the
        oldest same-titled note); (3) a fresh title resolution for brand-new
        links. Every id-based target is verified to still be an existing
        note before use.
        """
        # Parse + dedupe targets (first appearance wins) BEFORE applying
        # the cap. The cap exists to bound per-save DB work, and duplicate
        # texts resolve once regardless — counting each repetition against
        # the cap let 1000 repetitions of one ``[[A]]`` silently evict a
        # later distinct ``[[B]]``.
        parsed_targets: List[str] = []
        seen_texts: set[str] = set()
        truncated = 0
        for raw_link_text in LINK_PATTERN.findall(content):
            if len(parsed_targets) >= MAX_LINKS_PER_NOTE:
                truncated += 1
                continue
            # Canonical target text = the portion before the first pipe
            # of the Obsidian/Roam ``[[Target|Display]]`` alias syntax.
            # The display half is presentation-only; resolution, the
            # rename-safety cache key, the stored ``link_text`` and the
            # ``resolved_links`` payload all key off the target so the
            # frontend linkMap (built from outgoing_links.link_text in
            # note-detail.js) matches what ``processWikiLinks`` looks up
            # after it splits on the pipe. Storing the raw aliased text
            # here would leave every aliased link unresolvable on the
            # client and fall back to a slower title search.
            target_text, _sep, _display = raw_link_text.partition("|")
            target_text = target_text.strip()
            if not target_text:
                # Empty/whitespace target ("[[ ]]", "[[|alias]]") is not a
                # link — the frontend renders it as a literal. Pre-fix the
                # raw text was passed through to the resolver, whose
                # empty-prefix startswith('') matched EVERY note and
                # persisted a phantom NoteLink to the user's oldest note.
                continue
            text_lc = target_text.lower()
            if text_lc in seen_texts:
                continue
            seen_texts.add(text_lc)
            parsed_targets.append(target_text)
        if truncated:
            logger.warning(
                "note {} has more than {} distinct wiki-links; dropping "
                "{} matches past the cap to bound per-save DB work",
                note_id,
                MAX_LINKS_PER_NOTE,
                truncated,
            )

        # Existing rows serve three purposes: the rename-safety cache
        # (lowercased link text → target id, so renaming a target doesn't
        # nuke the link on the source's next save), the diff base below,
        # and preservation of per-row state (id, created_at, and the
        # auto_suggested badge from an accepted AI suggestion) on links
        # that survive the reparse. If multiple existing rows share the
        # same link_text (shouldn't happen — UniqueConstraint is on
        # (source, target), not (source, link_text)), the first wins.
        existing_rows = (
            session.query(NoteLink).filter_by(source_document_id=note_id).all()
        )
        existing_link_targets: Dict[str, str] = {}
        for row in existing_rows:
            key = (row.link_text or "").lower().strip()
            existing_link_targets.setdefault(key, row.target_document_id)
        rows_by_target: Dict[str, NoteLink] = {
            row.target_document_id: row for row in existing_rows
        }

        note_source_type_id = self._get_note_source_type_id(session)
        overrides = {
            (k or "").lower().strip(): v
            for k, v in (link_overrides or {}).items()
        }

        # Batch-validate every id-based candidate (priorities 1 and 2) in
        # one query instead of a per-link primary-key lookup — so a
        # stale/deleted/non-note id never resurrects a link, at O(1)
        # round-trips instead of O(links).
        candidate_ids: set[str] = set()
        for target_text in parsed_targets:
            text_lc = target_text.lower()
            for cid in (
                overrides.get(text_lc),
                existing_link_targets.get(text_lc),
            ):
                if cid and cid != note_id:
                    candidate_ids.add(cid)
        valid_targets: Dict[str, str] = {}
        candidate_list = sorted(candidate_ids)
        for start in range(0, len(candidate_list), _IN_CLAUSE_CHUNK):
            chunk = candidate_list[start : start + _IN_CLAUSE_CHUNK]
            valid_targets.update(
                session.query(Document.id, Document.title)
                .filter(
                    Document.id.in_(chunk),
                    Document.source_type_id == note_source_type_id,
                )
                .all()
            )

        def _valid_note_target(doc_id):
            """Return {id, title} if doc_id is an existing note (and not
            the source itself), else None."""
            if not doc_id or doc_id == note_id:
                return None
            title = valid_targets.get(doc_id)
            return {"id": doc_id, "title": title} if title is not None else None

        # Priority-3 pre-pass: batch the exact-title strategy for texts
        # priorities 1-2 don't cover. One IN() query over lower(title)
        # replaces a per-link table scan; ordering + setdefault implements
        # the oldest-wins tie-break (see _resolve_link_internal). The
        # mapping back from DB rows to link texts uses _fold_title_ascii,
        # which mirrors the database's lower().
        fresh_texts = [
            t
            for t in parsed_targets
            if not _valid_note_target(overrides.get(t.lower()))
            and not _valid_note_target(existing_link_targets.get(t.lower()))
        ]
        exact_by_fold: Dict[str, Dict[str, Any]] = {}
        folded_list = sorted({_fold_title_ascii(t) for t in fresh_texts})
        for start in range(0, len(folded_list), _IN_CLAUSE_CHUNK):
            chunk = folded_list[start : start + _IN_CLAUSE_CHUNK]
            rows = (
                session.query(Document.id, Document.title)
                .filter(
                    Document.source_type_id == note_source_type_id,
                    func.lower(Document.title).in_(chunk),
                )
                .order_by(Document.created_at.asc(), Document.id.asc())
                .all()
            )
            for doc_id, title in rows:
                exact_by_fold.setdefault(
                    _fold_title_ascii(title), {"id": doc_id, "title": title}
                )

        resolved_links: List[Dict[str, Any]] = []
        desired: Dict[str, str] = {}  # target id → link text (first wins)
        prefix_memo: Dict[str, Optional[Dict[str, Any]]] = {}
        for target_text in parsed_targets:
            text_lc = target_text.lower()
            # Priority 1: an explicit override (accept_suggested_link binds
            # the exact intended target id, immune to title collisions).
            target = _valid_note_target(overrides.get(text_lc))
            # Priority 2: the id this exact link text previously resolved to.
            # Preferring it over a fresh title lookup keeps an accepted /
            # established link pinned to its note across reparse and
            # keeps a link alive when its target was renamed.
            if not target:
                target = _valid_note_target(existing_link_targets.get(text_lc))
            # Priority 3: fresh title resolution — batched exact match,
            # then the (rare) per-text prefix fallback.
            if not target:
                fold = _fold_title_ascii(target_text)
                target = exact_by_fold.get(fold)
                if not target:
                    if fold not in prefix_memo:
                        prefix_memo[fold] = self._resolve_link_prefix(
                            session, target_text, note_source_type_id
                        )
                    target = prefix_memo[fold]
            if (
                target
                and target["id"] != note_id
                and target["id"] not in desired
            ):
                desired[target["id"]] = target_text
                resolved_links.append(
                    {
                        "link_text": target_text,
                        "target_id": target["id"],
                        "target_title": target["title"],
                    }
                )

        # Apply as a diff instead of delete-all + recreate: surviving rows
        # keep their id, created_at and auto_suggested flag, and an
        # unchanged link set writes zero rows.
        for target_id, row in rows_by_target.items():
            if target_id not in desired:
                session.delete(row)
        for target_id, link_text in desired.items():
            new_text = link_text[:MAX_LINK_TEXT_LENGTH]
            row = rows_by_target.get(target_id)
            if row is None:
                session.add(
                    NoteLink(
                        source_document_id=note_id,
                        target_document_id=target_id,
                        link_text=new_text,
                        auto_suggested=False,
                    )
                )
            elif row.link_text != new_text:
                row.link_text = new_text

        session.flush()
        return resolved_links

    def _parse_and_update_links(
        self, note_id: str, content: str
    ) -> List[Dict[str, Any]]:
        """Standalone version: opens its own session and commits.

        Kept for callers that intentionally manage link reparse outside
        their primary transaction (notably ``restore_with_bookends``, where
        a link-resolution failure is non-fatal and the restore must not
        roll back).
        """
        try:
            with get_user_db_session(self.username) as session:
                resolved = self._parse_and_update_links_in_session(
                    session, note_id, content
                )
                session.commit()
                logger.debug(
                    f"Updated links for note {note_id}: {len(resolved)} links"
                )
                return resolved
        except Exception:
            # Use logger.exception so the stack trace lands in the log.
            # Link parsing failures are non-fatal (callers continue), but
            # silently dropping the cause makes recurring failures
            # invisible to operators.
            logger.exception("Failed to parse links for note {}", note_id)
            return []

    def _resolve_link_internal(
        self, session: Session, link_text: str
    ) -> Optional[Dict[str, Any]]:
        """Resolve a link to a note document.

        Supports the Obsidian/Roam pipe alias syntax
        ``[[Title|Display Text]]``: the target is everything before the
        first ``|``; ``Display Text`` is rendering-only and ignored at
        resolution time. Without this split, a link like
        ``[[My Note|see here]]`` would search for a literal note titled
        "my note|see here" — which never exists — and the link would
        silently fall back to a stale cached target id on every save.

        Two notes can have the same title (e.g. duplicate "TODO" notes).
        Tie-break on ``created_at`` ascending so the link resolves to the
        OLDEST match. Resolving to the newest instead reads as more
        recency-intuitive, but it silently re-points every existing
        ``[[Title]]`` the moment a new note reuses that title (link drift by
        spooky-action-at-a-distance); oldest is stable and deterministic
        (without the order_by, ``.first()`` is at the DB's discretion and can
        flip between calls). Real per-target disambiguation — capturing the
        picked note's id at autocomplete time — is tracked as follow-up work.
        """
        # Strip pipe-alias before lookup. Use partition rather than
        # split so a target containing additional pipes (rare but
        # legal in markdown) doesn't get further mangled.
        target_text, sep, _display = link_text.partition("|")
        if sep:
            link_text = target_text
        link_text = link_text.strip()
        # Degenerate target ("[[ ]]" / "[[|alias]]"): an empty key must
        # never reach the lookup strategies — a LIKE '%' prefix pattern
        # would "resolve" to EVERY note (deterministically the user's
        # oldest one). The frontend treats an empty target as a literal,
        # not a link; mirror that here.
        if not link_text:
            return None
        source_type_id = self._get_note_source_type_id(session)

        # Strategy 1: Exact title match. Fold BOTH sides in SQL: folding
        # the link text in Python instead diverges for non-ASCII, because
        # SQLite's lower() folds ASCII only while str.lower() folds full
        # Unicode — a byte-identical title like "Über Alles" could then
        # never match its own link (lower('Über Alles') = 'Über alles',
        # but Python sent 'über alles'). SQL-side folding keeps ASCII
        # case-insensitivity and makes exact-typed non-ASCII titles
        # resolve. (Case-insensitive matching of the non-ASCII letters
        # themselves would need a custom collation on the connection.)
        document = (
            session.query(Document)
            .filter(
                Document.source_type_id == source_type_id,
                func.lower(Document.title) == func.lower(link_text),
            )
            .order_by(Document.created_at.asc(), Document.id.asc())
            .first()
        )
        if document:
            return {"id": document.id, "title": document.title}

        return self._resolve_link_prefix(session, link_text, source_type_id)

    def _resolve_link_prefix(
        self, session: Session, link_text: str, source_type_id: int
    ) -> Optional[Dict[str, Any]]:
        """Strategy 2: partial (prefix) title match — but only for targets
        long enough to be a meaningful prefix. A 1-2 char target like
        ``[[i]]`` would otherwise prefix-match and silently persist a
        NoteLink to an unrelated note ("Ideas", "Interview notes", ...);
        below the minimum length an exact match (Strategy 1) is the only
        acceptable resolution. Reuses the same floor as the
        unlinked-mention scan.

        ``link_text`` must already be stripped. Both sides are folded in
        SQL for the same non-ASCII reason as Strategy 1; the pattern is
        LIKE-escaped so a target containing wildcards (``[[%]]``,
        ``[[_]]``) matches literally instead of over-matching every note.
        """
        if len(link_text) < self.MIN_MENTION_TITLE_LEN:
            return None
        prefix_pattern = self._escape_like(link_text) + "%"
        document = (
            session.query(Document)
            .filter(
                Document.source_type_id == source_type_id,
                func.lower(Document.title).like(
                    func.lower(prefix_pattern), escape="\\"
                ),
            )
            .order_by(Document.created_at.asc(), Document.id.asc())
            .first()
        )
        if document:
            return {"id": document.id, "title": document.title}

        return None

    # Number of preview chars sent in backlinks / outgoing-links payloads.
    # Used by the column-projection SUBSTR so we don't pull full
    # text_content (up to 50 MB per Document row) just to slice 200
    # chars in Python.
    LINK_CONTENT_PREVIEW_CHARS = 200

    @staticmethod
    def _truncate_preview(raw: Optional[str], preview_len: int) -> str:
        """Trim a preview string to ``preview_len`` chars, appending "..."
        when the source was longer.

        The link-preview queries project ``func.substr(..., 1, preview_len
        + 1)`` from the DB — the +1 is the sentinel: SQLite SUBSTR returns
        at most preview_len+1 chars, so getting the full +1 char means the
        original text_content was longer than preview_len and the preview
        should be ellipsized. (SUBSTR uses 1-based indexing via length.)
        """
        s = raw or ""
        return s[:preview_len] + "..." if len(s) > preview_len else s

    def get_backlinks(self, note_id: str) -> List[Dict[str, Any]]:
        """Get notes that link to the given note.

        Errors propagate to the caller so the route layer can return a
        proper 500 via ``handle_api_error`` — silently returning ``[]``
        on a DB failure would be indistinguishable from "no backlinks"
        and mask production issues.

        Uses ``func.substr`` to project only the preview prefix of
        ``text_content`` from the DB. Pre-fix the JOIN loaded full
        Document rows including the unbounded ``text_content`` blob
        for every backlink source — at 20 backlinks averaging 100 kB
        each, the DB transferred ~2 MB just to slice 4 kB of response.
        """
        with get_user_db_session(self.username) as session:
            preview_len = self.LINK_CONTENT_PREVIEW_CHARS
            results = (
                session.query(
                    Document.id,
                    Document.title,
                    Document.created_at,
                    func.substr(
                        Document.text_content, 1, preview_len + 1
                    ).label("preview"),
                    NoteLink.link_text,
                )
                .join(NoteLink, Document.id == NoteLink.source_document_id)
                .filter(NoteLink.target_document_id == note_id)
                # Deterministic order so the backlinks panel doesn't reshuffle
                # between loads (DB row order is otherwise unspecified).
                .order_by(Document.title.asc(), Document.id.asc())
                .all()
            )

            backlinks = []
            for row in results:
                preview = self._truncate_preview(row.preview, preview_len)
                backlinks.append(
                    {
                        "id": row.id,
                        "title": row.title,
                        "link_text": row.link_text,
                        "content_preview": preview,
                        "created_at": row.created_at.isoformat()
                        if row.created_at
                        else None,
                    }
                )

            return backlinks

    def get_outgoing_links(self, note_id: str) -> List[Dict[str, Any]]:
        """Get notes that this note links to (outgoing links).

        Errors propagate to the caller — see ``get_backlinks`` rationale.
        Uses ``func.substr`` column projection for the same reason.
        """
        with get_user_db_session(self.username) as session:
            preview_len = self.LINK_CONTENT_PREVIEW_CHARS
            results = (
                session.query(
                    Document.id,
                    Document.title,
                    Document.created_at,
                    func.substr(
                        Document.text_content, 1, preview_len + 1
                    ).label("preview"),
                    NoteLink.link_text,
                    NoteLink.auto_suggested,
                )
                .join(NoteLink, Document.id == NoteLink.target_document_id)
                .filter(NoteLink.source_document_id == note_id)
                # Deterministic order so the outgoing-links panel is stable
                # across loads.
                .order_by(Document.title.asc(), Document.id.asc())
                .all()
            )

            outgoing = []
            for row in results:
                preview = self._truncate_preview(row.preview, preview_len)
                outgoing.append(
                    {
                        "id": row.id,
                        # Stable FK to the target note. The frontend
                        # (processWikiLinks) keys its [[link_text]] -> id map on
                        # target_id to resolve wiki-links by id rather than by a
                        # fragile title search; without it that lookup was always
                        # empty and every link fell back to title matching.
                        "target_id": row.id,
                        "title": row.title,
                        "link_text": row.link_text,
                        "content_preview": preview,
                        "created_at": row.created_at.isoformat()
                        if row.created_at
                        else None,
                        # True when the link was created by accepting an
                        # AI suggestion (vs. typed by hand). Lets the UI
                        # badge AI-suggested links.
                        "auto_suggested": bool(row.auto_suggested),
                    }
                )

            return outgoing

    # Titles shorter than this are too generic to mention-match usefully
    # (they'd flag almost every note), so unlinked-mention scanning skips them.
    MIN_MENTION_TITLE_LEN = 3

    def get_unlinked_mentions(
        self, note_id: str, limit: int = 20
    ) -> List[Dict[str, Any]]:
        """Find other notes whose text mentions this note's title but that
        don't yet link to it — Obsidian-style "unlinked mentions".

        Pure lexical (case-insensitive substring on the title), so it needs no
        embeddings/LLM. Notes that already link here are excluded; very short
        titles are skipped to avoid matching everything.
        """
        with get_user_db_session(self.username) as session:
            note_source_type_id = self._get_note_source_type_id(session)
            if not note_source_type_id:
                return []
            note = (
                session.query(Document)
                .filter_by(id=note_id, source_type_id=note_source_type_id)
                .first()
            )
            title = (note.title or "").strip() if note else ""
            if len(title) < self.MIN_MENTION_TITLE_LEN:
                return []

            # Notes that already link to this note — exclude them.
            linked_source_ids = {
                row[0]
                for row in session.query(NoteLink.source_document_id)
                .filter_by(target_document_id=note_id)
                .all()
            }

            # Escape LIKE wildcards in the title so e.g. a "50%" title can't
            # match every note.
            escaped = self._escape_like(title)
            preview_len = self.LINK_CONTENT_PREVIEW_CHARS
            query = session.query(
                Document.id,
                Document.title,
                func.substr(Document.text_content, 1, preview_len + 1).label(
                    "preview"
                ),
            ).filter(
                Document.source_type_id == note_source_type_id,
                Document.id != note_id,
                Document.text_content.ilike(f"%{escaped}%", escape="\\"),
            )
            if linked_source_ids:
                # Exclude already-linking notes in SQL. Done in Python
                # after a ``limit * 3`` over-fetch, a page whose first
                # candidates were mostly already linked silently returned
                # fewer than ``limit`` mentions even though more existed beyond
                # the over-fetch window.
                query = query.filter(
                    Document.id.notin_(list(linked_source_ids))
                )
            rows = (
                # Deterministic order: with no ORDER BY the limited slice was
                # whatever order the DB returned, so repeated calls could
                # surface different mentions. Newest-updated first, id as
                # a stable tiebreaker; mirrors the other link/list panels.
                query.order_by(Document.updated_at.desc(), Document.id)
                .limit(limit)
                .all()
            )

            return [
                {
                    "id": row.id,
                    "title": row.title,
                    "content_preview": self._truncate_preview(
                        row.preview, preview_len
                    ),
                }
                for row in rows
            ]

    def accept_suggested_link(
        self, note_id: str, target_note_id: str
    ) -> Optional[Dict[str, Any]]:
        """Accept an AI-suggested link by inserting [[Target Title]] into the
        note content and creating a NoteLink marked auto_suggested=True.

        Returns the updated note dict on success. Returns None only for a
        benign precondition that means "nothing to accept" — the note or
        target is missing, they are the same note, either is not a note, or
        the target title is only wiki-link syntax. A genuine write failure
        (e.g. update_note's content-size ValueError, or a DB error) is RAISED,
        not collapsed into the same None, so the route can map it to the right
        status instead of a misleading 404.
        """
        try:
            with get_user_db_session(self.username) as session:
                source = session.query(Document).filter_by(id=note_id).first()
                target = (
                    session.query(Document).filter_by(id=target_note_id).first()
                )
                if not source or not target:
                    return None

                if source.id == target.id:
                    logger.warning("Cannot self-link note {}", note_id)
                    return None

                # Check both exist as notes
                source_type_id = self._get_note_source_type_id(session)
                if (
                    source.source_type_id != source_type_id
                    or target.source_type_id != source_type_id
                ):
                    return None

                # If the note already links to this target (e.g. a hand-typed
                # [[Target]]), don't append a duplicate wiki-link or relabel the
                # user's link as AI-suggested — accepting is a no-op.
                already_linked = (
                    session.query(NoteLink)
                    .filter_by(
                        source_document_id=note_id,
                        target_document_id=target_note_id,
                    )
                    .first()
                    is not None
                )
                if already_linked:
                    return self.get_note(note_id)

                # Strip bracket characters from the target title before
                # interpolating into the [[...]] wiki-link syntax.
                # A title containing "]]" would otherwise corrupt the
                # link tokens (e.g. "foo]] [[bar" → "[[foo]] [[bar]]"
                # which the parser would split into two separate links).
                # Also drop any "|" alias portion: the parser partitions
                # the link text on the FIRST pipe and resolves only the
                # pre-pipe part, so a title containing "|" would make the
                # override key below ("a|b") never match the parser's
                # lookup key ("a") — silently bypassing the exact-id
                # binding and falling back to title resolution.
                # Also collapse internal whitespace (newlines included):
                # LINK_PATTERN's character class excludes newlines, so a
                # title containing one would append a "[[a\nb]]" literal the
                # parser can't match — no NoteLink created, yet the method
                # would report success and each retry would append more dead
                # text. `" ".join(split())` folds any whitespace run
                # (newlines/tabs/multiple spaces) to a single space.
                target_title = " ".join(
                    (target.title or "")
                    .replace("[", "")
                    .replace("]", "")
                    .partition("|")[0]
                    .split()
                )
                # Degenerate titles ("|", "[[", empty) strip down to "".
                # Appending "[[]]" would persist a dead literal in the
                # note body (the parser skips empty link text), so refuse
                # instead of silently writing an unlinkable artifact.
                # Return None (the method's failure contract — mirrors
                # the not-found and self-link branches above).
                if not target_title:
                    logger.warning(
                        "Cannot accept link {} -> {}: target title contains "
                        "only wiki-link syntax characters",
                        note_id,
                        target_note_id,
                    )
                    return None

                # Guard the duplicate-title case: if the note already has a
                # link whose text matches this title but points to a
                # DIFFERENT note (e.g. a hand-typed [[TODO]] resolved to an
                # older same-titled note), appending another [[TODO]] would
                # not add a second edge — the parser dedupes link text with
                # Python str.lower(), so the diff would RETARGET the single
                # 'todo' edge to this note and delete the user's existing
                # link to the other one. Bare [[title]] can't express two
                # different targets for the same text, so refuse rather than
                # silently destroy the existing edge.
                norm_title = target_title.lower()
                sibling_links = (
                    session.query(NoteLink)
                    .filter(
                        NoteLink.source_document_id == note_id,
                        NoteLink.target_document_id != target_note_id,
                    )
                    .all()
                )
                if any(
                    (lnk.link_text or "").lower() == norm_title
                    for lnk in sibling_links
                ):
                    logger.warning(
                        "Cannot accept link {} -> {}: the note already links "
                        "'{}' to a different note; bare [[title]] can't "
                        "disambiguate same-titled targets",
                        note_id,
                        target_note_id,
                        target_title,
                    )
                    return None

                # Session A above performed only precondition reads. The body
                # append itself is NOT computed here from source.text_content:
                # that value would be stale by the time update_note's separate
                # write transaction runs, so a save landing in between would be
                # lost. update_note re-reads the current body and appends inside
                # its own transaction (see _append_link_title) — read and write
                # are then atomic.

            # update_note handles the body append (from the note's CURRENT
            # content), versioning, link re-parsing and hash update.
            # Bind the appended [[target_title]] to the EXACT target id via an
            # override so a title shared by several notes — or a title we had
            # to strip brackets from above — links to THIS note, not whichever
            # the title resolver would pick. The override id is
            # preferred on this parse, and the resulting link's id is then
            # preferred on every later reparse (the rename-safety cache), so
            # the binding is durable.
            self.update_note(
                note_id,
                _append_link_title=target_title,
                _link_overrides={target_title.lower().strip(): target_note_id},
            )

            # Flag the newly-created NoteLink as auto_suggested=True so UX can
            # distinguish it from user-typed links.
            with get_user_db_session(self.username) as session:
                link = (
                    session.query(NoteLink)
                    .filter_by(
                        source_document_id=note_id,
                        target_document_id=target_note_id,
                    )
                    .first()
                )
                if link:
                    link.auto_suggested = True
                    session.commit()

            return self.get_note(note_id)

        except Exception:
            # Real write failures (update_note's ValueError content cap, a DB
            # IntegrityError, etc.) must NOT be swallowed into the same None
            # the benign preconditions return — that hid genuine failures
            # behind a misleading "Link could not be accepted" 404. Log for
            # context and re-raise so the route maps it (ValueError -> 400,
            # anything else -> 500).
            logger.exception(
                "Error accepting suggested link {} on {}",
                target_note_id,
                note_id,
            )
            raise

    def resolve_link(self, link_text: str) -> Optional[Dict[str, Any]]:
        """Resolve a [[link]] text to a note.

        Public wrapper around ``_resolve_link_internal``. Caps ``link_text``
        at ``MAX_LINK_TEXT_LENGTH`` defensively even though ``LINK_PATTERN``
        already bounds it — the public route hands its body in untouched.
        """
        if isinstance(link_text, str) and len(link_text) > MAX_LINK_TEXT_LENGTH:
            link_text = link_text[:MAX_LINK_TEXT_LENGTH]
        try:
            with get_user_db_session(self.username) as session:
                return self._resolve_link_internal(session, link_text)
        except Exception:
            # A DB/session failure must NOT collapse into the same None a
            # genuinely unresolvable link returns — the route maps None to a
            # 404 "Note not found", which would present an outage as the note
            # not existing. Log for context and re-raise so the route's
            # handle_api_error surfaces a 500 (same rationale as
            # accept_suggested_link above).
            logger.exception("Error resolving link")
            raise

    def search_notes_for_linking(
        self, query: str, exclude_note_id: Optional[str] = None, limit: int = 10
    ) -> List[Dict[str, Any]]:
        """Search notes for the [[link]] autocomplete feature."""
        try:
            with get_user_db_session(self.username) as session:
                source_type_id = self._get_note_source_type_id(session)
                search_pattern = f"%{self._escape_like(query)}%"

                query_obj = session.query(Document).filter(
                    Document.source_type_id == source_type_id,
                    Document.title.ilike(search_pattern, escape="\\"),
                )

                if exclude_note_id:
                    query_obj = query_obj.filter(Document.id != exclude_note_id)

                documents = (
                    query_obj.order_by(Document.updated_at.desc())
                    .limit(limit)
                    .all()
                )

                return [
                    {
                        "id": doc.id,
                        "title": doc.title,
                        "slug": self._generate_slug(doc.title),
                    }
                    for doc in documents
                ]

        except Exception:
            # Returning [] here would turn an infrastructure failure into an
            # HTTP 200 with an empty autocomplete — indistinguishable from
            # "no matching notes". Log for context and re-raise so the route
            # surfaces a 500 (matches semantic_search's fix in
            # note_ai_service, which removed this exact swallow as masking
            # outages).
            logger.exception(
                "Error searching notes for linking (query_len={})",
                len(query) if query else 0,
            )
            raise