Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ultrawiki): describe the pictures and transcribe the recordings

Ruben Lütke6cd61864a367
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 2b9bae4f71..d6dd1bd7d9 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2168,6 +2168,20 @@ class UltraWikiConfig(BaseModel):
rerank_model: str = "" # only for rerank_provider="llm"; empty = cheap tier
ollama_endpoint: str = "http://localhost:11434"
+ # How hard the background lane works at turning pictures into words and
+ # recordings into transcripts:
+ # "frugal" (default) - one item at a time, and only while every other
+ # stage is idle. A photo library is tens of
+ # thousands of model calls, so this must never race
+ # the import it follows.
+ # "eager" - same lane, still one at a time, but it also runs
+ # while other stages have work.
+ # "off" - nothing is described or transcribed. Photos stay
+ # findable by filename, folder and capture date.
+ # Nothing here is a hard requirement: an install with no vision-capable
+ # provider simply keeps its backlog until one appears.
+ media_enrich: str = "frugal"
+
# Where the readable Markdown projection is written (the Obsidian vault).
# Empty = "wiki/ultrawiki-vault" under the data dir — beside the normal
# wiki's own vault and never inside it: UltraWiki writes to its own files,
diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.py
index a2ad6c3923..659768794d 100644
--- a/jarvis/plugins/stt/groq_api.py
+++ b/jarvis/plugins/stt/groq_api.py
@@ -179,13 +179,41 @@ class GroqWhisperAPI:
self._client = httpx.AsyncClient(timeout=self._timeout_s)
return self._client
- async def _post_transcription(self, wav_bytes: bytes) -> Transcript:
+ async def transcribe_container(
+ self, data: bytes, *, filename: str = "recording", language: str | None = None
+ ) -> Transcript:
+ """Transcribe an ENCODED audio file (m4a, opus, mp3, mp4, wav, ...).
+
+ The optional capability the UltraWiki enrichment stage looks for. The
+ live microphone path delivers raw PCM, which everything else here
+ wraps in a WAV container; an imported voice note is already encoded and
+ this endpoint takes those formats directly. Passing the container
+ through untouched is deliberate — re-wrapping it would corrupt it.
+ """
+ if not data:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ if language and language != "auto":
+ previous = self._language
+ self._language = language
+ try:
+ return await self._post_transcription(data, filename=filename)
+ finally:
+ self._language = previous
+ return await self._post_transcription(data, filename=filename)
+
+ async def _post_transcription(
+ self, wav_bytes: bytes, *, filename: str = "audio.wav"
+ ) -> Transcript:
if not self._api_key:
raise RuntimeError(
"GROQ_API_KEY missing; provide api_key=... or set the env var."
)
- files = {"file": ("audio.wav", wav_bytes, "audio/wav")}
+ # The NAME carries the container format to the service, so an imported
+ # `.opus` must not be announced as `audio.wav`.
+ upload_name = _upload_name(filename)
+ mime = "audio/wav" if upload_name.endswith(".wav") else "application/octet-stream"
+ files = {"file": (upload_name, wav_bytes, mime)}
data: dict[str, str] = {
"model": self._model,
"response_format": "verbose_json",
@@ -229,6 +257,21 @@ def _read_keyring_secret(service: str, username: str) -> str:
return ""
+#: Container extensions these transcription APIs accept. A name outside the
+#: list is uploaded as `.wav`, which is what the live path always sends.
+_ACCEPTED_UPLOAD_SUFFIXES: frozenset[str] = frozenset(
+ {".wav", ".mp3", ".mp4", ".m4a", ".ogg", ".oga", ".opus", ".flac", ".webm", ".mpga", ".mpeg"}
+)
+
+
+def _upload_name(filename: str) -> str:
+ """A safe multipart filename that still carries the real extension."""
+ from pathlib import PurePosixPath # noqa: PLC0415 — tiny, local
+
+ suffix = PurePosixPath(str(filename or "")).suffix.lower()
+ return f"audio{suffix}" if suffix in _ACCEPTED_UPLOAD_SUFFIXES else "audio.wav"
+
+
def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:
"""Wrap int16 little-endian PCM in a minimal WAV header (in memory)."""
buf = io.BytesIO()
diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.py
index 100fb980b5..93d24241e5 100644
--- a/jarvis/plugins/stt/openai_api.py
+++ b/jarvis/plugins/stt/openai_api.py
@@ -190,6 +190,32 @@ class OpenAIWhisperAPI:
self._language = previous
return await self._post_transcription(wav_bytes)
+ async def transcribe_container(
+ self, data: bytes, *, filename: str = "recording", language: str | None = None
+ ) -> Transcript:
+ """Transcribe an ENCODED audio file (m4a, opus, mp3, mp4, wav, ...).
+
+ The optional capability the UltraWiki enrichment stage looks for. The
+ live microphone path delivers raw PCM, which is why everything else
+ here wraps PCM in a WAV container — but an imported voice note arrives
+ already encoded, and this endpoint accepts those formats directly.
+ Decoding them locally would mean shipping a media stack to every
+ install, including headless servers that have no other use for one.
+
+ The container is passed through untouched: the service identifies the
+ format itself, and re-wrapping it would be the one way to corrupt it.
+ """
+ if not data:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ if language and language != "auto":
+ previous = self._language
+ self._language = language
+ try:
+ return await self._post_transcription(data, filename=filename)
+ finally:
+ self._language = previous
+ return await self._post_transcription(data, filename=filename)
+
def _ensure_model(self) -> None:
"""No-op compat shim — cloud STT has nothing to warm up.
@@ -261,9 +287,16 @@ class OpenAIWhisperAPI:
self._endpoint_url = base.rstrip("/") + "/audio/transcriptions"
return self._endpoint_url
- async def _post_transcription(self, wav_bytes: bytes) -> Transcript:
+ async def _post_transcription(
+ self, wav_bytes: bytes, *, filename: str = "audio.wav"
+ ) -> Transcript:
url = self._ensure_endpoint()
- files = {"file": ("audio.wav", wav_bytes, "audio/wav")}
+ # The NAME is how the service identifies the container, so an imported
+ # `.opus` must not be announced as `audio.wav`. The content type stays
+ # generic: the extension is the signal these APIs actually read.
+ upload_name = _upload_name(filename)
+ mime = "audio/wav" if upload_name.endswith(".wav") else "application/octet-stream"
+ files = {"file": (upload_name, wav_bytes, mime)}
data: dict[str, str] = {
"model": self._model,
"response_format": "verbose_json",
@@ -295,6 +328,21 @@ class OpenAIWhisperAPI:
# Helpers (module-private)
# ----------------------------------------------------------------------
+#: Container extensions these transcription APIs accept. A name outside the
+#: list is uploaded as `.wav`, which is what the live path always sends.
+_ACCEPTED_UPLOAD_SUFFIXES: frozenset[str] = frozenset(
+ {".wav", ".mp3", ".mp4", ".m4a", ".ogg", ".oga", ".opus", ".flac", ".webm", ".mpga", ".mpeg"}
+)
+
+
+def _upload_name(filename: str) -> str:
+ """A safe multipart filename that still carries the real extension."""
+ from pathlib import PurePosixPath # noqa: PLC0415 — tiny, local
+
+ suffix = PurePosixPath(str(filename or "")).suffix.lower()
+ return f"audio{suffix}" if suffix in _ACCEPTED_UPLOAD_SUFFIXES else "audio.wav"
+
+
def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:
"""Wrap int16 little-endian PCM in a minimal WAV header (in memory)."""
buf = io.BytesIO()
diff --git a/jarvis/ultrawiki/media_enrich.py b/jarvis/ultrawiki/media_enrich.py
new file mode 100644
index 0000000000..c21463d5f6
--- /dev/null
+++ b/jarvis/ultrawiki/media_enrich.py
@@ -0,0 +1,400 @@
+"""Turn a picture into words and a recording into a transcript.
+
+The stage that finally makes a photo library searchable by what is IN it,
+rather than only by when and where it was taken. It runs behind everything
+else, one item at a time, and it is allowed to achieve nothing: an install
+with no vision-capable provider and no speech recognition keeps its photos
+findable by filename, folder and capture date, and drains this queue the day
+a capable provider appears.
+
+Three rules it does not bend:
+
+* **Capability, never a provider name (AP-21).** The chain is filtered on
+ ``supports_vision`` / the presence of a container-transcription method. A
+ new provider becomes eligible by declaring the capability, and nothing here
+ needs to learn its name.
+* **A model that cannot see must never be asked to describe.** This is the
+ one failure that would be worse than doing nothing: a text-only model handed
+ an invisible image will happily invent a plausible photo, and that fiction
+ would be indexed as memory. So the chain is filtered up front AND the prompt
+ gives the model an explicit way to say it sees nothing, which is validated.
+* **Off every hot path (AP-26 / AP-9).** Imports are lazy, the work happens in
+ the pipeline's own worker, and nothing here is reachable from boot or from a
+ voice turn.
+"""
+
+from __future__ import annotations
+
+import base64
+import logging
+from dataclasses import dataclass, field
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "CANNOT_SEE_MARKER",
+ "EnrichResult",
+ "describe_image",
+ "transcribe_recording",
+ "vision_chain",
+]
+
+#: The exact token a model is told to answer when it received no picture.
+#: Its presence in a reply is treated as "no description", never as content —
+#: the difference between an honest gap and an indexed hallucination.
+CANNOT_SEE_MARKER = "NO_IMAGE_RECEIVED"
+
+#: Bytes of one media file handed to a provider. Above this the item keeps its
+#: honest reason instead of an upload that would be refused anyway.
+MAX_IMAGE_BYTES = 8 * 1024 * 1024
+MAX_AUDIO_BYTES = 24 * 1024 * 1024
+
+#: Characters kept from a description or transcript.
+MAX_DESCRIPTION_CHARS = 4000
+MAX_TRANSCRIPT_CHARS = 40_000
+
+_DEFAULT_TIMEOUT_S = 90.0
+
+_VISION_SYSTEM = (
+ "You describe images for a personal search index. Write plainly and only "
+ "about what is actually visible."
+)
+
+_VISION_PROMPT = (
+ "Describe this image so its owner can find it again by searching in their "
+ "own words months from now.\n\n"
+ "Cover, in one short paragraph: what kind of picture it is (photo, "
+ "screenshot, document scan, diagram), the setting, the notable objects, "
+ "roughly how many people are in it and what they are doing, and the mood "
+ "or occasion if it is evident. Then, if the image contains readable text, "
+ "add a line 'Text:' followed by that text verbatim.\n\n"
+ "Do not guess names of people or places. Do not invent details you cannot "
+ "see. Write in English.\n\n"
+ f"If no image reached you, reply with exactly {CANNOT_SEE_MARKER} and "
+ "nothing else."
+)
+
+#: MIME types by media kind, from the filename. Providers need one, and a
+#: wrong one is rejected by some APIs, so an unknown suffix falls back to the
+#: family's most permissive type rather than to a guess.
+_IMAGE_MIME: dict[str, str] = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".bmp": "image/bmp",
+ ".heic": "image/heic",
+ ".heif": "image/heif",
+ ".avif": "image/avif",
+ ".tif": "image/tiff",
+ ".tiff": "image/tiff",
+}
+
+
+@dataclass(slots=True)
+class EnrichResult:
+ """What one enrichment attempt produced, and honestly why when nothing.
+
+ ``retryable`` separates "this build cannot do it" (install a key, try
+ again later) from "this file will never yield anything" (a corrupt photo),
+ so a queue does not spin forever on the second.
+ """
+
+ text: str = ""
+ ok: bool = False
+ reason: str = ""
+ provider: str = ""
+ retryable: bool = True
+ meta: dict[str, Any] = field(default_factory=dict)
+
+
+def _suffix(filename: str) -> str:
+ from pathlib import Path # noqa: PLC0415 — lazy, keeps import cost off boot
+
+ return Path(filename).suffix.lower()
+
+
+def _image_mime(filename: str) -> str:
+ return _IMAGE_MIME.get(_suffix(filename), "image/jpeg")
+
+
+# ---------------------------------------------------------------------------
+# Pictures
+# ---------------------------------------------------------------------------
+
+
+def vision_chain(cfg: Any, registry: Any) -> list[tuple[str, str | None]]:
+ """The provider chain filtered down to those that can actually see.
+
+ Built on the same key-aware, cross-family chain the distillation stage
+ uses (AP-22), then narrowed by the ``supports_vision`` capability read off
+ the provider CLASS — cheap, and it needs no credentials to evaluate.
+
+ A provider whose vision support is only decided at runtime is trusted to
+ declare a truthful default on its class; the prompt's explicit
+ "I saw no image" escape is the second line of defence for exactly that
+ case, so a wrong declaration costs a wasted call, never a fabricated
+ description.
+ """
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy (AP-26)
+ build_wiki_provider_chain,
+ credential_ready_wiki_providers,
+ )
+
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ configured = str(getattr(ultrawiki, "distill_provider", "") or "").strip()
+ primary = configured or str(getattr(getattr(cfg, "brain", None), "primary", "") or "")
+
+ available = set(registry.available())
+ chain = build_wiki_provider_chain(
+ primary=primary,
+ model_override="",
+ available=available,
+ credential_ready=credential_ready_wiki_providers(available=available, config=cfg),
+ )
+ return [(name, model) for name, model in chain if _can_see(registry, name)]
+
+
+def _can_see(registry: Any, name: str) -> bool:
+ """Whether a provider declares vision support. Never raises."""
+ try:
+ provider_class = registry.get_class(name)
+ except Exception: # noqa: BLE001 — an unloadable provider simply cannot see
+ return False
+ return bool(getattr(provider_class, "supports_vision", False))
+
+
+async def describe_image(
+ data: bytes,
+ *,
+ filename: str,
+ cfg: Any,
+ registry: Any = None,
+ timeout_s: float = _DEFAULT_TIMEOUT_S,
+) -> EnrichResult:
+ """One picture as searchable prose, or an honest reason why not."""
+ if not data:
+ return EnrichResult(reason="the file is empty", retryable=False)
+ if len(data) > MAX_IMAGE_BYTES:
+ return EnrichResult(
+ reason=(
+ f"the picture is larger than {MAX_IMAGE_BYTES // (1024 * 1024)} MB, "
+ "which is more than a provider will accept"
+ ),
+ retryable=False,
+ )
+
+ if registry is None:
+ from jarvis.brain.provider_registry import ( # noqa: PLC0415 — lazy (AP-26)
+ BrainProviderRegistry,
+ )
+
+ registry = BrainProviderRegistry()
+
+ chain = vision_chain(cfg, registry)
+ if not chain:
+ return EnrichResult(
+ reason=(
+ "no configured provider can read images; connect one that "
+ "does and this picture is described automatically"
+ )
+ )
+
+ from jarvis.core.protocols import ( # noqa: PLC0415 — lazy (AP-26)
+ BrainMessage,
+ BrainRequest,
+ ImageBlock,
+ )
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy (AP-26)
+ complete_with_fallback,
+ )
+
+ request = BrainRequest(
+ messages=(
+ BrainMessage(
+ role="user",
+ content=_VISION_PROMPT,
+ images=(
+ ImageBlock(
+ mime=_image_mime(filename),
+ data_b64=base64.b64encode(data).decode("ascii"),
+ ),
+ ),
+ ),
+ ),
+ system=_VISION_SYSTEM,
+ temperature=0.1, # description, not creativity
+ max_tokens=900,
+ stream=True,
+ )
+
+ result = await complete_with_fallback(
+ registry=registry,
+ chain=chain,
+ request=request,
+ timeout_s=timeout_s,
+ label="UltraWikiImageDescriber",
+ aggregate=_aggregate,
+ validate=_validate_description,
+ )
+ if result is None:
+ return EnrichResult(reason="no provider that can read images returned a usable description")
+ aggregated, provider = result
+ text = _clean(str(getattr(aggregated, "text", "") or ""))[:MAX_DESCRIPTION_CHARS]
+ return EnrichResult(text=text, ok=True, provider=provider)
+
+
+def _aggregate(chunks: Any) -> Any:
+ """Collapse a provider's stream into one object carrying ``.text``."""
+
+ @dataclass(slots=True)
+ class _Aggregated:
+ text: str
+
+ if isinstance(chunks, str):
+ return _Aggregated(text=chunks)
+ parts: list[str] = []
+ for chunk in chunks or ():
+ piece = getattr(chunk, "text", None)
+ parts.append(piece if isinstance(piece, str) else str(chunk))
+ return _Aggregated(text="".join(parts))
+
+
+def _validate_description(aggregated: Any) -> bool:
+ """Reject a non-answer so the chain moves on to the next provider.
+
+ The ``NO_IMAGE_RECEIVED`` check is the load-bearing one: it is how a
+ provider that took the call but never saw the picture is caught before its
+ invented description is stored as a memory.
+ """
+ text = _clean(str(getattr(aggregated, "text", "") or ""))
+ if not text or len(text) < 15:
+ return False
+ return CANNOT_SEE_MARKER not in text.upper()
+
+
+def _clean(text: str) -> str:
+ return "\n".join(line.rstrip() for line in text.strip().splitlines()).strip()
+
+
+# ---------------------------------------------------------------------------
+# Recordings
+# ---------------------------------------------------------------------------
+
+
+async def transcribe_recording(
+ data: bytes,
+ *,
+ filename: str,
+ cfg: Any,
+ stt: Any = None,
+ timeout_s: float = _DEFAULT_TIMEOUT_S,
+) -> EnrichResult:
+ """A voice note or video soundtrack as text, or an honest reason why not.
+
+ Uses the OPTIONAL ``transcribe_container`` capability: a provider that can
+ take an encoded file (m4a, opus, mp3, mp4) rather than the raw PCM frames
+ the live microphone path produces. Decoding those formats ourselves would
+ mean a media library on every install, including headless servers that
+ have no use for one — so the capability is asked for, and its absence is
+ reported plainly instead of worked around.
+ """
+ if not data:
+ return EnrichResult(reason="the file is empty", retryable=False)
+ if len(data) > MAX_AUDIO_BYTES:
+ return EnrichResult(
+ reason=(
+ f"the recording is larger than {MAX_AUDIO_BYTES // (1024 * 1024)} MB, "
+ "which is more than a transcription provider will accept"
+ ),
+ retryable=False,
+ )
+
+ if stt is None:
+ stt = await _resolve_stt(cfg)
+ if stt is None:
+ return EnrichResult(
+ reason=(
+ "no speech recognition is configured; set one up and this "
+ "recording is transcribed automatically"
+ )
+ )
+
+ transcribe = getattr(stt, "transcribe_container", None)
+ if not callable(transcribe):
+ configured = getattr(stt, "provider_name", None) or type(stt).__name__
+ return EnrichResult(
+ reason=(
+ f"the configured speech recognition ({configured}) reads live "
+ "microphone audio but cannot take an audio FILE; a provider "
+ "that can is needed to transcribe this recording"
+ )
+ )
+
+ import asyncio # noqa: PLC0415 — lazy
+
+ try:
+ transcript = await asyncio.wait_for(transcribe(data, filename=filename), timeout=timeout_s)
+ except TimeoutError:
+ return EnrichResult(reason="transcription timed out")
+ except Exception as exc: # noqa: BLE001 — one file never breaks the queue
+ log.debug("media enrich: transcription failed for %s", filename, exc_info=True)
+ return EnrichResult(reason=f"transcription failed ({type(exc).__name__}: {exc})")
+
+ text = _clean(str(getattr(transcript, "text", "") or transcript or ""))
+ if not text:
+ return EnrichResult(
+ reason="the recording holds no recognisable speech",
+ retryable=False,
+ )
+ return EnrichResult(
+ text=text[:MAX_TRANSCRIPT_CHARS],
+ ok=True,
+ provider=type(stt).__name__,
+ )
+
+
+async def _resolve_stt(cfg: Any) -> Any:
+ """The configured speech-recognition provider, or ``None``. Never raises.
+
+ Built fresh rather than borrowed from the live voice pipeline on purpose:
+ a background transcription must never contend with the microphone path for
+ a native engine (AP-24 — a shared ctranslate2 model called concurrently
+ hangs unrecoverably).
+ """
+ from jarvis.core import registry # noqa: PLC0415 — lazy (AP-26)
+
+ name = str(getattr(getattr(cfg, "stt", None), "provider", "") or "").strip()
+ if not name:
+ return None
+ try:
+ provider_class = registry.load("jarvis.stt", name)
+ except Exception: # noqa: BLE001 — an absent provider is simply absent
+ log.debug("media enrich: STT provider %s unavailable", name, exc_info=True)
+ return None
+ # A provider that cannot take a file is not worth constructing: doing so
+ # can load a multi-gigabyte model for a call that will be refused anyway.
+ if not callable(getattr(provider_class, "transcribe_container", None)):
+ return _Uncapable(provider_class.__name__)
+ try:
+ return provider_class(cfg)
+ except Exception: # noqa: BLE001 — a provider that will not build is absent
+ log.debug("media enrich: STT provider %s did not build", name, exc_info=True)
+ return None
+
+
+class _Uncapable:
+ """Stands in for a provider that exists but cannot read an audio file.
+
+ Named rather than ``None`` so the reason a recording stays untranscribed
+ says WHICH provider is configured — "no speech recognition" would be a
+ lie when one is set up and simply reads live audio only.
+ """
+
+ def __init__(self, provider_name: str) -> None:
+ self.provider_name = provider_name
+
+ def __repr__(self) -> str: # pragma: no cover — diagnostics only
+ return f"<uncapable STT provider {self.provider_name}>"
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index ee94c65296..103aa7add2 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -57,7 +57,9 @@ __all__ = [
"KEYWORD_BATCH",
"EMBED_BATCH",
"DISTILL_BATCH",
+ "MEDIA_BATCH",
"MAX_EMBED_CHARS",
+ "MAX_MEDIA_BYTES",
"IDLE_SLEEP_S",
"BUSY_SLEEP_S",
"PipelineWorker",
@@ -68,6 +70,17 @@ KEYWORD_BATCH = 200
EMBED_BATCH = 32
DISTILL_BATCH = 4
+#: Media enrichment claims ONE item per pass, and only when every other stage
+#: found nothing to do. Describing a picture costs a model call, and a photo
+#: library is tens of thousands of them — so this lane is deliberately the
+#: slowest thing in the system rather than something that races the import it
+#: is supposed to follow.
+MEDIA_BATCH = 1
+
+#: Bytes of one media file read for enrichment. Above this the providers would
+#: refuse the upload anyway, and reading it would only cost memory.
+MAX_MEDIA_BYTES = 24 * 1024 * 1024
+
#: Character budget per embedded TEXT — now per passage, not per item.
#:
#: It used to be a content cap: an item was cut here and everything past it
@@ -207,6 +220,12 @@ class PipelineWorker:
attempted += await self._keyword_pass()
attempted += await self._embed_pass()
attempted += await self._distill_pass()
+ # Media enrichment runs only in the gaps. It is the one stage that can
+ # be skipped forever without anything breaking, so by default it never
+ # takes a turn away from a stage that cannot. "eager" opts out of that
+ # deference; it does not raise the batch size.
+ if not attempted or self._media_mode() == "eager":
+ attempted += await self._media_pass()
return attempted
# -- shared helpers ------------------------------------------------------
@@ -695,3 +714,186 @@ class PipelineWorker:
int(item["id"]), ItemState.DISTILLED, **self._claim_guard(item)
)
)
+
+ # -- media enrichment ----------------------------------------------------
+
+ async def _media_pass(self) -> int:
+ """Describe one picture, or transcribe one recording. Frugal by design.
+
+ This lane is the only one that may achieve nothing forever: an install
+ with no vision-capable provider keeps its photos findable by filename,
+ folder and capture date, and drains the backlog the day one appears.
+ So every failure here is recorded on the item and the loop moves on —
+ nothing retries in a tight circle, and nothing blocks.
+ """
+ mode = self._media_mode()
+ if mode == "off":
+ return 0
+ pending = await self._pending_media(MEDIA_BATCH)
+ if not pending:
+ self._clear_stage_pause("media")
+ return 0
+ worked = 0
+ for item in pending:
+ try:
+ await self._enrich_one(item)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — one file never stops the lane
+ log.warning(
+ "UltraWiki media enrichment failed for item %s: %s",
+ item.get("id"),
+ exc,
+ )
+ await self._record_media_outcome(
+ item, text="", reason=f"enrichment failed ({type(exc).__name__})"
+ )
+ worked += 1
+ return worked
+
+ def _media_mode(self) -> str:
+ """``frugal`` (default), ``eager`` or ``off``, from the config."""
+ ultrawiki = getattr(self._cfg, "ultrawiki", None)
+ raw = str(getattr(ultrawiki, "media_enrich", "") or "").strip().lower()
+ return raw if raw in ("off", "frugal", "eager") else "frugal"
+
+ async def _pending_media(self, limit: int) -> list[dict[str, Any]]:
+ """Media items awaiting enrichment; empty when the store predates it."""
+ fetch = getattr(self._store, "pending_media_items", None)
+ if not callable(fetch):
+ return []
+ try:
+ return await fetch(limit=limit)
+ except Exception: # noqa: BLE001 — a query failure pauses the lane, nothing else
+ log.debug("UltraWiki: media backlog query failed", exc_info=True)
+ return []
+
+ async def _enrich_one(self, item: dict[str, Any]) -> None:
+ from jarvis.ultrawiki import media as media_mod # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.ultrawiki import media_enrich # noqa: PLC0415 — lazy (AP-26)
+
+ metadata = dict(item.get("metadata") or {})
+ kind = str(metadata.get("media_kind") or "")
+ reference = media_mod.ref_from_metadata(metadata)
+ if reference is None:
+ await self._record_media_outcome(
+ item,
+ text="",
+ reason="this item carries no reference back to the original file",
+ retryable=False,
+ )
+ return
+
+ data = await asyncio.to_thread(_read_media_bytes, media_mod, reference)
+ if data is None:
+ await self._record_media_outcome(
+ item,
+ text="",
+ reason="the original file is no longer where it was imported from",
+ retryable=False,
+ )
+ return
+
+ filename = reference.display_name
+ if kind == "image":
+ result = await media_enrich.describe_image(
+ data, filename=filename, cfg=self._cfg
+ )
+ elif kind in ("audio", "video"):
+ result = await media_enrich.transcribe_recording(
+ data, filename=filename, cfg=self._cfg
+ )
+ else:
+ await self._record_media_outcome(
+ item,
+ text="",
+ reason=f"nothing here knows how to read a {kind or 'file'} of this kind",
+ retryable=False,
+ )
+ return
+
+ if not result.ok:
+ self._note_stage_pause("media", result.reason)
+ await self._record_media_outcome(
+ item, text="", reason=result.reason, retryable=result.retryable
+ )
+ return
+ self._clear_stage_pause("media")
+ await self._record_media_outcome(
+ item, text=result.text, reason="", provider=result.provider, kind=kind
+ )
+
+ async def _record_media_outcome(
+ self,
+ item: dict[str, Any],
+ *,
+ text: str,
+ reason: str,
+ retryable: bool = True,
+ provider: str = "",
+ kind: str = "",
+ ) -> None:
+ """Write the outcome back, through the ordinary upsert path.
+
+ Success APPENDS to the body rather than replacing it: the file facts
+ underneath (name, folder, capture date, camera, place) are what makes
+ the item findable by time and place, and a description does not
+ supersede them. The changed body changes the content hash, which is
+ what puts the item back at ``captured`` so the normal ladder embeds
+ and distils the new text — no separate re-indexing path to maintain.
+
+ A failure leaves the body untouched and only records why. ``retryable``
+ false clears the pending flag so a permanently unreadable file stops
+ being picked up; true leaves it set, and the next capable provider
+ drains it.
+ """
+ from jarvis.ultrawiki.types import RawItem # noqa: PLC0415 — lazy
+
+ metadata = dict(item.get("metadata") or {})
+ body = str(item.get("body_raw") or "")
+ if not text:
+ # A failure changes nothing about the content, and unchanged
+ # content makes ``upsert_items`` leave the row completely untouched
+ # (its zero-new-work guarantee) — so the note has to be written
+ # through the narrow metadata path or it would vanish, and the same
+ # file would be retried forever with nothing to show for it.
+ metadata["enrich_error"] = reason
+ if not retryable:
+ metadata["enrich_pending"] = False
+ await self._store.set_item_metadata(int(item["id"]), metadata)
+ return
+
+ metadata["enrich_pending"] = False
+ metadata["enriched_by"] = provider
+ metadata.pop("enrich_error", None)
+ label = "Transcript" if kind in ("audio", "video") else "Description"
+ body = f"{body}\n\n{label}: {text}".strip()
+
+ await self._store.upsert_items(
+ str(item.get("source_id") or ""),
+ [
+ RawItem(
+ external_id=str(item.get("external_id") or ""),
+ body=body,
+ permalink=str(item.get("permalink") or ""),
+ timestamp_utc=str(item.get("timestamp_utc") or ""),
+ title=str(item.get("title") or ""),
+ thread_key=str(item.get("thread_key") or ""),
+ author_raw=str(item.get("author_raw") or ""),
+ metadata=metadata,
+ )
+ ],
+ )
+
+
+def _read_media_bytes(media_mod: Any, reference: Any) -> bytes | None:
+ """Read one media file's bytes in a worker thread. Blocking; never raises."""
+ stream = media_mod.open_media(reference)
+ if stream is None:
+ return None
+ try:
+ with stream:
+ return stream.read(MAX_MEDIA_BYTES)
+ except (OSError, RuntimeError, ValueError):
+ log.debug("UltraWiki: media file could not be read", exc_info=True)
+ return None
diff --git a/jarvis/ultrawiki/schema.sql b/jarvis/ultrawiki/schema.sql
index ae4ee887be..a69bcee832 100644
--- a/jarvis/ultrawiki/schema.sql
+++ b/jarvis/ultrawiki/schema.sql
@@ -86,6 +86,10 @@ CREATE TABLE IF NOT EXISTS uw_items (
state TEXT NOT NULL DEFAULT 'captured'
CHECK (state IN ('captured', 'keyword_indexed', 'embedded',
'distilled', 'failed')),
+ -- Whatever the connector attached to the RawItem: the source format, a
+ -- file's modification time, a photo's capture date and camera, and the
+ -- reference an enrichment run needs to reopen a media file's bytes.
+ metadata_json TEXT NOT NULL DEFAULT '{}',
attempt_count INTEGER NOT NULL DEFAULT 0,
next_retry_at TEXT,
last_error TEXT,
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index f2e6eb873b..b642b09e21 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -279,6 +279,60 @@ _ITEM_LIST_COLUMNS = (
)
+def _metadata_json(item: RawItem) -> str:
+ """A ``RawItem``'s metadata as storable JSON; ``"{}"`` for anything odd.
+
+ Never raises: a connector may attach whatever it likes, and one
+ unserialisable value must cost that item its metadata rather than the
+ whole batch its transaction.
+ """
+ metadata = getattr(item, "metadata", None)
+ if not isinstance(metadata, dict) or not metadata:
+ return "{}"
+ try:
+ return json.dumps(metadata, ensure_ascii=False, default=str)
+ except (TypeError, ValueError):
+ log.debug("UltraStore: metadata of %s is not serialisable", item.external_id)
+ return "{}"
+
+
+def _parse_metadata(row: Any) -> dict[str, Any]:
+ """One row's stored metadata. Empty for a row written before the column."""
+ try:
+ raw = row["metadata_json"]
+ except (KeyError, IndexError, TypeError):
+ return {}
+ if not raw:
+ return {}
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+def _media_pending_only(
+ rows: list[dict[str, Any]], limit: int
+) -> list[dict[str, Any]]:
+ """Keep only rows whose metadata really flags a pending enrichment.
+
+ The SQL narrows with a substring match, which is the same on every
+ backend but also matches an item that merely records ``enrich_pending``
+ as ``false``. The exact decision therefore happens here, on the parsed
+ metadata, where a serializer's spacing cannot change the answer.
+ """
+ kept: list[dict[str, Any]] = []
+ for row in rows:
+ metadata = row.get("metadata") or {}
+ if not isinstance(metadata, dict):
+ continue
+ if metadata.get("enrich_pending") is True:
+ kept.append(row)
+ if len(kept) >= max(1, int(limit)):
+ break
+ return kept
+
+
def _item_filter_sql(
*,
source_id: str | None,
@@ -318,6 +372,11 @@ _UNSET: Any = object()
#: columns are read from ``PRAGMA table_info`` first — the pattern of
#: ``jarvis/missions/event_store.py``.
_ADDITIVE_COLUMNS: tuple[tuple[str, str, str], ...] = (
+ # Connectors have always attached metadata to a RawItem — the source
+ # format, a file's modification time, a chat's participants — and it was
+ # dropped on the way into the store, silently. Nothing depended on it
+ # until media items had to carry the reference back to their own bytes.
+ ("uw_items", "metadata_json", "TEXT NOT NULL DEFAULT '{}'"),
("uw_sources", "last_notice", "TEXT"),
("uw_sync_state", "last_outcome_at", "TEXT"),
("uw_sync_state", "last_outcome_status", "TEXT"),
@@ -787,8 +846,8 @@ class UltraStore:
"INSERT INTO uw_items"
" (source_id, external_id, thread_key, author_raw, title,"
" body_raw, permalink, timestamp_utc, areas_json,"
- " content_hash, state, created_at, updated_at)"
- " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ " content_hash, state, metadata_json, created_at, updated_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
source_id,
item.external_id,
@@ -801,6 +860,7 @@ class UltraStore:
areas_json,
identity,
ItemState.CAPTURED.value,
+ _metadata_json(item),
now,
now,
),
@@ -816,8 +876,9 @@ class UltraStore:
"UPDATE uw_items SET thread_key = ?, author_raw = ?,"
" title = ?, body_raw = ?, permalink = ?,"
" timestamp_utc = ?, areas_json = ?, content_hash = ?,"
- " state = ?, attempt_count = 0, next_retry_at = NULL,"
- " last_error = NULL, deleted_at = NULL, updated_at = ?"
+ " state = ?, metadata_json = ?, attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL,"
+ " deleted_at = NULL, updated_at = ?"
" WHERE id = ?",
(
item.thread_key,
@@ -829,6 +890,7 @@ class UltraStore:
areas_json,
identity,
ItemState.CAPTURED.value,
+ _metadata_json(item),
now,
row["id"],
),
@@ -887,6 +949,7 @@ class UltraStore:
"areas": json.loads(row["areas_json"] or "[]"),
"content_hash": row["content_hash"],
"state": row["state"],
+ "metadata": _parse_metadata(row),
"attempt_count": row["attempt_count"],
"next_retry_at": row["next_retry_at"],
"last_error": row["last_error"],
@@ -977,6 +1040,47 @@ class UltraStore:
)
return [dict(row) for row in rows], total
+ async def set_item_metadata(self, item_id: int, metadata: dict[str, Any]) -> None:
+ """Replace one item's metadata WITHOUT touching its content or state.
+
+ The narrow path a side lane needs to record an outcome. It cannot go
+ through :meth:`upsert_items`: unchanged content leaves the row
+ completely untouched by design (the zero-new-work guarantee), so a
+ failure note written that way would be silently discarded and the same
+ file would be retried forever with nothing to show for it.
+
+ Content, hash, state and retry bookkeeping are deliberately untouched
+ — this records what was learned ABOUT an item, never what it says.
+ """
+ async with self._txn() as conn:
+ await conn.execute(
+ "UPDATE uw_items SET metadata_json = ? WHERE id = ?",
+ (json.dumps(metadata or {}, ensure_ascii=False, default=str), int(item_id)),
+ )
+
+ async def pending_media_items(self, *, limit: int = 8) -> list[dict[str, Any]]:
+ """Media items still waiting to be described or transcribed.
+
+ Deliberately NOT a new pipeline state (AP-4): a fifth value crossing
+ Python, SQL, Pydantic, TypeScript and the UI is the drift class this
+ repo has paid for four times, and enrichment is a SIDE lane rather
+ than a step every item takes. The flag lives in the item's metadata
+ and the SQL narrows on it with a plain ``LIKE`` — no JSON operator, so
+ this one query is identical on both backends — with the exact decision
+ made in Python, where a serializer's spacing cannot change the answer.
+
+ Oldest first: a backlog should drain in the order it built up.
+ """
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT * FROM uw_items"
+ " WHERE deleted_at IS NULL AND metadata_json LIKE '%enrich_pending%'"
+ " ORDER BY id ASC LIMIT ?",
+ (max(1, int(limit)) * 4,),
+ )
+ return _media_pending_only([self._item_row_to_dict(row) for row in rows], limit)
+
async def claim_batch(
self,
target_state: ItemState | str,
@@ -2062,6 +2166,7 @@ class PostgresStore:
" content_hash TEXT NOT NULL,"
" state TEXT NOT NULL DEFAULT 'captured'"
f" CHECK (state IN ({states})),"
+ " metadata_json TEXT NOT NULL DEFAULT '{}',"
" attempt_count INTEGER NOT NULL DEFAULT 0,"
" next_retry_at TEXT, last_error TEXT, deleted_at TEXT,"
" created_at TEXT NOT NULL, updated_at TEXT NOT NULL,"
@@ -2378,9 +2483,9 @@ class PostgresStore:
"INSERT INTO uw_items"
" (source_id, external_id, thread_key, author_raw, title,"
" body_raw, permalink, timestamp_utc, areas_json,"
- " content_hash, state, created_at, updated_at)"
+ " content_hash, state, metadata_json, created_at, updated_at)"
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,"
- " %s, %s)",
+ " %s, %s, %s)",
(
source_id,
item.external_id,
@@ -2393,6 +2498,7 @@ class PostgresStore:
areas_json,
identity,
ItemState.CAPTURED.value,
+ _metadata_json(item),
now,
now,
),
@@ -2406,8 +2512,9 @@ class PostgresStore:
"UPDATE uw_items SET thread_key = %s, author_raw = %s,"
" title = %s, body_raw = %s, permalink = %s,"
" timestamp_utc = %s, areas_json = %s, content_hash = %s,"
- " state = %s, attempt_count = 0, next_retry_at = NULL,"
- " last_error = NULL, deleted_at = NULL, updated_at = %s"
+ " state = %s, metadata_json = %s, attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL,"
+ " deleted_at = NULL, updated_at = %s"
" WHERE id = %s",
(
item.thread_key,
@@ -2419,6 +2526,7 @@ class PostgresStore:
areas_json,
identity,
ItemState.CAPTURED.value,
+ _metadata_json(item),
now,
row["id"],
),
@@ -2460,6 +2568,7 @@ class PostgresStore:
"areas": json.loads(row["areas_json"] or "[]"),
"content_hash": row["content_hash"],
"state": row["state"],
+ "metadata": _parse_metadata(row),
"attempt_count": row["attempt_count"],
"next_retry_at": row["next_retry_at"],
"last_error": row["last_error"],
@@ -2537,6 +2646,34 @@ class PostgresStore:
)
return [dict(row) for row in rows], total
+ async def set_item_metadata(self, item_id: int, metadata: dict[str, Any]) -> None:
+ """Replace one item's metadata without touching its content or state.
+
+ Mirrors the SQLite implementation (see its docstring for why a side
+ lane cannot record an outcome through ``upsert_items``).
+ """
+ async with self._txn() as conn:
+ await conn.execute(
+ "UPDATE uw_items SET metadata_json = %s WHERE id = %s",
+ (json.dumps(metadata or {}, ensure_ascii=False, default=str), int(item_id)),
+ )
+
+ async def pending_media_items(self, *, limit: int = 8) -> list[dict[str, Any]]:
+ """Media items still waiting to be described or transcribed.
+
+ Mirrors the SQLite implementation exactly (see its docstring for why
+ this is a metadata flag rather than a fifth pipeline state).
+ """
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT * FROM uw_items"
+ " WHERE deleted_at IS NULL AND metadata_json LIKE '%%enrich_pending%%'"
+ " ORDER BY id ASC LIMIT %s",
+ (max(1, int(limit)) * 4,),
+ )
+ return _media_pending_only([self._item_row_to_dict(row) for row in rows], limit)
+
async def claim_batch(
self,
target_state: ItemState | str,
diff --git a/tests/unit/ultrawiki/test_media_enrich.py b/tests/unit/ultrawiki/test_media_enrich.py
new file mode 100644
index 0000000000..ec227abd7c
--- /dev/null
+++ b/tests/unit/ultrawiki/test_media_enrich.py
@@ -0,0 +1,287 @@
+"""Turning a picture into words — and refusing to invent any.
+
+The failure this file exists to prevent: a text-only model, handed an image it
+never received, writing a confident description of a photo it cannot see. That
+fiction would be indexed as memory and be indistinguishable from a real one.
+Everything else here is ordinary plumbing; the ``NO_IMAGE_RECEIVED`` and
+chain-filter tests are the load-bearing ones.
+
+Offline throughout — no provider is contacted, and the registry is a fake.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.ultrawiki import media_enrich
+from jarvis.ultrawiki.media_enrich import (
+ CANNOT_SEE_MARKER,
+ EnrichResult,
+ describe_image,
+ transcribe_recording,
+ vision_chain,
+)
+
+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
+
+
+class _FakeClass:
+ def __init__(self, supports_vision: bool) -> None:
+ self.supports_vision = supports_vision
+
+
+class _FakeRegistry:
+ """Stands in for the brain provider registry, with declared capabilities."""
+
+ def __init__(self, providers: dict[str, bool]) -> None:
+ self._providers = providers
+
+ def available(self) -> list[str]:
+ return sorted(self._providers)
+
+ def get_class(self, name: str) -> Any:
+ return _FakeClass(self._providers[name])
+
+
+class _Cfg:
+ class ultrawiki: # noqa: N801 — mirrors the config attribute path
+ distill_provider = ""
+
+ class brain: # noqa: N801
+ primary = "seeing"
+
+ class stt: # noqa: N801
+ provider = ""
+
+
+def all_credential_ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Treat every registered provider as having a usable credential."""
+ import jarvis.memory.wiki.provider_chain as chain_mod
+
+ monkeypatch.setattr(
+ chain_mod, "credential_ready_wiki_providers", lambda **kwargs: set(kwargs["available"])
+ )
+ monkeypatch.setattr(chain_mod, "_cheap_model_for", lambda name: "", raising=False)
+
+
+# ---------------------------------------------------------------------------
+# The chain: capability, never a name
+# ---------------------------------------------------------------------------
+
+
+def test_only_providers_that_declare_vision_reach_the_chain(all_credential_ready):
+ registry = _FakeRegistry({"seeing": True, "blind": False, "also-seeing": True})
+ names = [name for name, _model in vision_chain(_Cfg(), registry)]
+ assert "blind" not in names
+ assert set(names) == {"seeing", "also-seeing"}
+
+
+def test_a_provider_that_will_not_load_is_treated_as_blind(all_credential_ready):
+ class _Broken(_FakeRegistry):
+ def get_class(self, name: str) -> Any:
+ if name == "broken":
+ raise RuntimeError("plugin import failed")
+ return super().get_class(name)
+
+ registry = _Broken({"seeing": True, "broken": True})
+ assert [name for name, _ in vision_chain(_Cfg(), registry)] == ["seeing"]
+
+
+async def test_no_seeing_provider_means_an_honest_reason_not_a_guess(
+ all_credential_ready,
+):
+ registry = _FakeRegistry({"blind": False})
+ result = await describe_image(PNG, filename="a.png", cfg=_Cfg(), registry=registry)
+ assert result.ok is False
+ assert result.text == ""
+ assert "images" in result.reason
+ # Retryable: connecting a capable provider later must drain the backlog.
+ assert result.retryable is True
+
+
+# ---------------------------------------------------------------------------
+# The one that matters: never store a description of an unseen image
+# ---------------------------------------------------------------------------
+
+
+async def test_a_model_that_admits_it_saw_no_image_is_rejected(
+ all_credential_ready, monkeypatch: pytest.MonkeyPatch
+):
+ """The prompt gives the model an escape hatch; this is it being honoured.
+
+ Without this check the reply would be stored verbatim — and a model that
+ answers the marker is precisely one that would otherwise have invented a
+ photo.
+ """
+ seen: list[Any] = []
+
+ async def _fake_complete(**kwargs: Any) -> Any:
+ # Mirror the real helper: run validate(), and report failure when no
+ # attempt passes it.
+ validate = kwargs["validate"]
+ aggregate = kwargs["aggregate"]
+ seen.append(kwargs["request"])
+ answer = aggregate(f"{CANNOT_SEE_MARKER}")
+ return None if not validate(answer) else (answer, "seeing")
+
+ import jarvis.memory.wiki.provider_chain as chain_mod
+
+ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)
+
+ registry = _FakeRegistry({"seeing": True})
+ result = await describe_image(PNG, filename="a.png", cfg=_Cfg(), registry=registry)
+ assert result.ok is False
+ assert result.text == ""
+ assert seen, "the provider was never called"
+
+
+async def test_an_empty_or_trivial_answer_is_rejected(all_credential_ready, monkeypatch):
+ async def _fake_complete(**kwargs: Any) -> Any:
+ validate, aggregate = kwargs["validate"], kwargs["aggregate"]
+ answer = aggregate("ok")
+ return None if not validate(answer) else (answer, "seeing")
+
+ import jarvis.memory.wiki.provider_chain as chain_mod
+
+ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)
+ result = await describe_image(
+ PNG, filename="a.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})
+ )
+ assert result.ok is False
+
+
+async def test_a_real_description_comes_back_with_its_provider(
+ all_credential_ready, monkeypatch
+):
+ async def _fake_complete(**kwargs: Any) -> Any:
+ aggregate = kwargs["aggregate"]
+ answer = aggregate(
+ "A photo of two people on a beach at sunset, holding surfboards.\n"
+ "Text: Malibu 2019"
+ )
+ assert kwargs["validate"](answer)
+ return answer, "seeing"
+
+ import jarvis.memory.wiki.provider_chain as chain_mod
+
+ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)
+ result = await describe_image(
+ PNG, filename="a.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})
+ )
+ assert result.ok is True
+ assert "surfboards" in result.text
+ assert result.provider == "seeing"
+
+
+async def test_the_image_actually_reaches_the_request(all_credential_ready, monkeypatch):
+ """A request without the image attached would be the silent version of the
+ same bug: the model answers about nothing and sounds fine."""
+ captured: dict[str, Any] = {}
+
+ async def _fake_complete(**kwargs: Any) -> Any:
+ captured["request"] = kwargs["request"]
+ answer = kwargs["aggregate"]("A photograph of a mountain range at dawn.")
+ return answer, "seeing"
+
+ import jarvis.memory.wiki.provider_chain as chain_mod
+
+ monkeypatch.setattr(chain_mod, "complete_with_fallback", _fake_complete)
+ await describe_image(
+ PNG, filename="peak.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})
+ )
+ message = captured["request"].messages[0]
+ assert len(message.images) == 1
+ assert message.images[0].mime == "image/png"
+ assert message.images[0].data_b64
+
+
+# ---------------------------------------------------------------------------
+# Limits and empties
+# ---------------------------------------------------------------------------
+
+
+async def test_an_oversized_picture_is_refused_permanently(all_credential_ready):
+ huge = b"\x89PNG\r\n\x1a\n" + b"\x00" * (media_enrich.MAX_IMAGE_BYTES + 1)
+ result = await describe_image(
+ huge, filename="huge.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})
+ )
+ assert result.ok is False
+ assert result.retryable is False, "retrying an oversized file forever is a loop"
+
+
+async def test_an_empty_file_is_refused_permanently(all_credential_ready):
+ result = await describe_image(
+ b"", filename="a.png", cfg=_Cfg(), registry=_FakeRegistry({"seeing": True})
+ )
+ assert result.ok is False
+ assert result.retryable is False
+
+
+# ---------------------------------------------------------------------------
+# Recordings
+# ---------------------------------------------------------------------------
+
+
+class _FileCapableSTT:
+ async def transcribe_container(self, data: bytes, *, filename: str = "") -> Any:
+ class _T:
+ text = f"transcript of {filename}"
+
+ return _T()
+
+
+class _MicOnlySTT:
+ provider_name = "local-whisper"
+
+
+async def test_a_recording_is_transcribed_when_the_provider_takes_a_file():
+ result = await transcribe_recording(
+ b"OggS-audio", filename="PTT-0003.opus", cfg=_Cfg(), stt=_FileCapableSTT()
+ )
+ assert result.ok is True
+ assert "PTT-0003.opus" in result.text
+
+
+async def test_a_microphone_only_provider_says_so_by_name():
+ """"No speech recognition" would be a lie when one is configured."""
+ result = await transcribe_recording(
+ b"OggS-audio", filename="note.opus", cfg=_Cfg(), stt=_MicOnlySTT()
+ )
+ assert result.ok is False
+ assert "local-whisper" in result.reason
+ assert result.retryable is True
+
+
+async def test_a_provider_that_raises_never_breaks_the_lane():
+ class _Broken:
+ async def transcribe_container(self, data: bytes, *, filename: str = "") -> Any:
+ raise RuntimeError("upstream refused")
+
+ result = await transcribe_recording(
+ b"OggS-audio", filename="note.opus", cfg=_Cfg(), stt=_Broken()
+ )
+ assert result.ok is False
+ assert "upstream refused" in result.reason
+
+
+async def test_silence_is_a_permanent_outcome_not_a_retry():
+ class _Silent:
+ async def transcribe_container(self, data: bytes, *, filename: str = "") -> Any:
+ class _T:
+ text = " "
+
+ return _T()
+
+ result = await transcribe_recording(
+ b"OggS-audio", filename="note.opus", cfg=_Cfg(), stt=_Silent()
+ )
+ assert result.ok is False
+ assert result.retryable is False
+
+
+def test_enrich_result_defaults_to_retryable():
+ """A new failure mode must default to "try again", never to "give up"."""
+ assert EnrichResult().retryable is True
diff --git a/tests/unit/ultrawiki/test_pipeline_media.py b/tests/unit/ultrawiki/test_pipeline_media.py
new file mode 100644
index 0000000000..b61cafbfc8
--- /dev/null
+++ b/tests/unit/ultrawiki/test_pipeline_media.py
@@ -0,0 +1,324 @@
+"""The media enrichment lane, end to end against a real store, fully offline.
+
+Two things are pinned here that nothing else could catch:
+
+* **Connector metadata survives the store.** It did not, for the store's whole
+ life, and nothing noticed — connectors attached it to every RawItem and it
+ was dropped on the way in. Nothing depended on it until a photo had to carry
+ the reference back to its own bytes.
+* **The lane defers.** Describing a picture costs a model call and a photo
+ library is tens of thousands of them, so it must never delay the keyword
+ indexing of the text that arrived alongside.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.ultrawiki.pipeline import PipelineWorker
+from jarvis.ultrawiki.store import UltraStore
+from jarvis.ultrawiki.types import ConsentState, ItemState, RawItem
+
+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
+
+#: These workers use an INJECTED distiller, so the production credential probe
+#: must never run — a test whose outcome depends on the host's keys is the
+#: AP-23 trap.
+DISTILL_READY = lambda: (True, "") # noqa: E731 — a one-line test seam
+
+
+async def distill_never(cfg: Any, *, title: str, body: str, source_kind: str) -> Any:
+ raise AssertionError("distill_fn must not be called in this test")
+
+
+def media_cfg(mode: str = "frugal") -> SimpleNamespace:
+ return SimpleNamespace(
+ ultrawiki=SimpleNamespace(
+ enabled=True,
+ db_backend="sqlite",
+ embedding_provider="",
+ embedding_model="",
+ distill_provider="",
+ distill_model="",
+ rerank_provider="",
+ ollama_endpoint="",
+ media_enrich=mode,
+ ),
+ memory=SimpleNamespace(data_dir="unused"),
+ brain=SimpleNamespace(primary=""),
+ )
+
+
+def worker_for(store: Any, cfg: Any) -> PipelineWorker:
+ return PipelineWorker(
+ store,
+ cfg,
+ embedding_backend_factory=lambda: None,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+
+
+def text_item(index: int) -> RawItem:
+ return RawItem(
+ external_id=f"ext-{index:04d}",
+ body=f"body text number {index}",
+ permalink=f"app://item/{index}",
+ timestamp_utc="2026-01-01T00:00:00Z",
+ title=f"Item {index}",
+ )
+
+
+def photo_item(index: int, path: Path, *, pending: bool = True) -> RawItem:
+ """An item shaped exactly as the folder walk produces one for a photo."""
+ return RawItem(
+ external_id=f"photo-{index:04d}.png",
+ body=(
+ f"File: photo-{index:04d}.png\nFolder: 2019\n"
+ "Taken: 2019-08-14T17:03:22Z"
+ ),
+ permalink=path.as_uri(),
+ timestamp_utc="2019-08-14T17:03:22Z",
+ title=f"photo-{index:04d}",
+ metadata={
+ "media_kind": "image",
+ "enrich_pending": pending,
+ "captured_at": "2019-08-14T17:03:22Z",
+ "media_ref_kind": "file",
+ "media_ref_path": str(path),
+ },
+ )
+
+
+async def store(tmp_path: Path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ await instance.upsert_source("src1", connector="local-folder", label="Test source")
+ await instance.set_consent("src1", ConsentState.APPROVED)
+ yield instance
+ await instance.close()
+
+
+async def only_item(store: Any, external_id: str = "") -> dict[str, Any]:
+ rows, _total = await store.list_items(source_id="src1", limit=50)
+ if external_id:
+ rows = [row for row in rows if str(row.get("title", "")).startswith("photo")]
+ item = await store.get_item(int(rows[0]["id"]))
+ assert item is not None
+ return item
+
+
+def patch_describe(monkeypatch: pytest.MonkeyPatch, fn: Any) -> None:
+ import jarvis.ultrawiki.media_enrich as enrich_mod
+
+ monkeypatch.setattr(enrich_mod, "describe_image", fn)
+
+
+# ---------------------------------------------------------------------------
+# Metadata reaching the store at all
+# ---------------------------------------------------------------------------
+
+
+class TestMetadataSurvivesTheStore:
+ async def test_connector_metadata_is_persisted_and_read_back(self, store, tmp_path):
+ await store.upsert_items("src1", [photo_item(1, tmp_path / "a.png")])
+ item = await only_item(store)
+ assert item["metadata"]["media_kind"] == "image"
+ assert item["metadata"]["enrich_pending"] is True
+ assert item["metadata"]["media_ref_path"] == str(tmp_path / "a.png")
+
+ async def test_an_item_without_metadata_reads_as_an_empty_mapping(self, store):
+ await store.upsert_items("src1", [text_item(1)])
+ item = await only_item(store)
+ assert item["metadata"] == {}
+
+ async def test_unserialisable_metadata_costs_that_item_its_metadata_only(
+ self, store, tmp_path
+ ):
+ """One odd value must never cost the whole batch its transaction."""
+ odd = RawItem(
+ external_id="odd",
+ body="body",
+ permalink="app://odd",
+ timestamp_utc="2026-01-01T00:00:00Z",
+ title="Odd",
+ metadata={"handle": object()},
+ )
+ counts = await store.upsert_items("src1", [odd, text_item(2)])
+ assert counts.new == 2
+
+
+# ---------------------------------------------------------------------------
+# The backlog query
+# ---------------------------------------------------------------------------
+
+
+class TestMediaBacklog:
+ async def test_only_items_actually_waiting_are_claimed(self, store, tmp_path):
+ await store.upsert_items(
+ "src1",
+ [
+ photo_item(1, tmp_path / "a.png"),
+ photo_item(2, tmp_path / "b.png", pending=False),
+ text_item(3),
+ ],
+ )
+ pending = await store.pending_media_items(limit=10)
+ assert [row["external_id"] for row in pending] == ["photo-0001.png"]
+
+ async def test_a_store_with_no_media_returns_nothing(self, store):
+ await store.upsert_items("src1", [text_item(1)])
+ assert await store.pending_media_items(limit=10) == []
+
+
+# ---------------------------------------------------------------------------
+# The pass itself
+# ---------------------------------------------------------------------------
+
+
+class TestMediaPass:
+ async def test_a_described_photo_keeps_its_file_facts_and_gains_the_text(
+ self, store, tmp_path, monkeypatch
+ ):
+ """The description is APPENDED: the facts underneath are what make the
+ photo findable by time and place, and prose does not supersede them."""
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [photo_item(1, photo)])
+
+ async def _describe(data, *, filename, cfg, **kwargs):
+ from jarvis.ultrawiki.media_enrich import EnrichResult
+
+ assert data.startswith(b"\x89PNG"), "the real bytes must reach the model"
+ assert filename == "a.png"
+ return EnrichResult(
+ text="Two people on a beach.", ok=True, provider="seeing"
+ )
+
+ patch_describe(monkeypatch, _describe)
+ assert await worker_for(store, media_cfg())._media_pass() == 1
+
+ item = await only_item(store)
+ assert "Two people on a beach." in item["body_raw"]
+ assert "Taken: 2019-08-14T17:03:22Z" in item["body_raw"]
+ assert item["metadata"]["enrich_pending"] is False
+ assert item["metadata"]["enriched_by"] == "seeing"
+ # A changed body sends the item back through the normal ladder, so the
+ # description is embedded and distilled like any other text.
+ assert item["state"] == ItemState.CAPTURED.value
+ assert await store.pending_media_items(limit=10) == []
+
+ async def test_a_failure_leaves_the_item_findable_and_still_queued(
+ self, store, tmp_path, monkeypatch
+ ):
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [photo_item(1, photo)])
+
+ async def _describe(data, *, filename, cfg, **kwargs):
+ from jarvis.ultrawiki.media_enrich import EnrichResult
+
+ return EnrichResult(reason="no provider can read images")
+
+ patch_describe(monkeypatch, _describe)
+ await worker_for(store, media_cfg())._media_pass()
+
+ item = await only_item(store)
+ assert "Taken: 2019-08-14T17:03:22Z" in item["body_raw"]
+ assert item["metadata"]["enrich_error"] == "no provider can read images"
+ # Still queued: connecting a capable provider later must drain it.
+ assert item["metadata"]["enrich_pending"] is True
+
+ async def test_a_deleted_original_stops_being_retried(self, store, tmp_path):
+ """A file removed between import and description is ordinary; retrying
+ it forever would be a loop with no end."""
+ await store.upsert_items("src1", [photo_item(1, tmp_path / "gone.png")])
+ await worker_for(store, media_cfg())._media_pass()
+
+ item = await only_item(store)
+ assert item["metadata"]["enrich_pending"] is False
+ assert "no longer where it was imported from" in item["metadata"]["enrich_error"]
+
+ async def test_off_means_nothing_is_touched(self, store, tmp_path):
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [photo_item(1, photo)])
+ assert await worker_for(store, media_cfg("off"))._media_pass() == 0
+ assert len(await store.pending_media_items(limit=10)) == 1
+
+ async def test_the_lane_defers_to_every_other_stage(self, store, tmp_path):
+ """Frugal means: only in the gaps. A photo must never delay the keyword
+ indexing of the text that arrived with it."""
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [text_item(1), photo_item(1, photo)])
+
+ calls: list[int] = []
+ worker = worker_for(store, media_cfg())
+ original = worker._media_pass
+
+ async def _counting() -> int:
+ calls.append(1)
+ return await original()
+
+ worker._media_pass = _counting # type: ignore[method-assign]
+
+ assert await worker.run_once() > 0, "the keyword stage had work"
+ assert calls == [], "the media lane must not run while a stage has work"
+ await worker.run_once()
+ assert calls == [1], "it gets its turn once the ladder is idle"
+
+ async def test_an_enricher_that_raises_never_stops_the_loop(
+ self, store, tmp_path, monkeypatch
+ ):
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [photo_item(1, photo)])
+
+ async def _boom(data, *, filename, cfg, **kwargs):
+ raise RuntimeError("provider exploded")
+
+ patch_describe(monkeypatch, _boom)
+ assert await worker_for(store, media_cfg())._media_pass() == 1
+
+ item = await only_item(store)
+ assert "RuntimeError" in item["metadata"]["enrich_error"]
+
+ async def test_a_store_without_the_backlog_query_is_simply_skipped(self, tmp_path):
+ """An older store object must degrade, not raise."""
+
+ class _OldStore:
+ async def upsert_items(self, *args, **kwargs): # pragma: no cover
+ raise AssertionError("nothing should be written")
+
+ assert await worker_for(_OldStore(), media_cfg())._media_pass() == 0
+
+ async def test_a_failure_note_does_not_reprocess_the_item(
+ self, store, tmp_path, monkeypatch
+ ):
+ """The trap this caught: recording a failure through the ordinary
+ upsert writes NOTHING, because unchanged content is left untouched by
+ design — so the note vanished and the file was retried forever."""
+ photo = tmp_path / "a.png"
+ photo.write_bytes(PNG)
+ await store.upsert_items("src1", [photo_item(1, photo)])
+ before = await only_item(store)
+
+ async def _describe(data, *, filename, cfg, **kwargs):
+ from jarvis.ultrawiki.media_enrich import EnrichResult
+
+ return EnrichResult(reason="the provider is out of credit")
+
+ patch_describe(monkeypatch, _describe)
+ await worker_for(store, media_cfg())._media_pass()
+
+ after = await only_item(store)
+ assert after["metadata"]["enrich_error"] == "the provider is out of credit"
+ # The item did NOT go back through the ladder: nothing about its
+ # content changed, so re-embedding it would be pure waste.
+ assert after["content_hash"] == before["content_hash"]
+ assert after["state"] == before["state"]