Skip to content

retrieval.extractors

Sidecar-transcript extraction for non-text-native document formats (PDF + agent-only media). Stdlib-only at import scope — this module must import cleanly with zero optional extras installed, same guarantee as the rest of the default pipeline; the pypdf backend is imported lazily, only inside the functions that actually need it.

EXTRACTABLE_EXTENSIONS splits into three tiers:

  • MACHINE_EXTRACTABLE_EXTENSIONS (.pdf, .srt, .vtt) — has a registered machine extractor. .pdf needs the optional pypdf backend (see PYPDF_EXTENSIONS); .srt/.vtt (caption files) are extracted by a stdlib-only converter (_extract_captions, captions/1) that needs no extra at all.
  • AGENT_ONLY_EXTENSIONS (.docx, .pptx, .xlsx, .png, .jpg, .jpeg, .gif, .webp) — no machine extractor exists at all, but a coding agent can read/view the file natively; every such file always indexes as an "agent-only"-reason stub, and retrieval sidecar --register is the only way to index its real content.
  • AGENT_ORCHESTRATED_EXTENSIONS (.mp4, .mov, .mkv, .webm, .mp3, .m4a, .wav, .flac) — no machine extractor, and no native agent-readable path either: an agent must orchestrate an external ASR tool via Bash, then register the result. Every such file indexes as an "agent-orchestrated"-reason stub. Uncapped at discovery (see project_loader._is_eligible_file) and never byte-read by this module (see "Stat-only identity for tier 3" below).

PYPDF_EXTENSIONS ({".pdf"}) is the strict subset of MACHINE_EXTRACTABLE_EXTENSIONS that actually needs the pypdf backend — require_extractors() and ensure_sidecar's backend-missing-stub branch key off this set, not the broader one, so a caption-only corpus never triggers the pypdf guidance error.

A file's extracted text is written once to a Markdown "sidecar" file under <project-root>/.agentic-retrieval/extracted/<rel-path>.md (always under the project root, deliberately ignoring RETRIEVAL_INDEX_DIR — a sidecar is a citation target a coding agent Read()s by project-relative path, so it must live in the tree being indexed even when the cache itself is redirected elsewhere). A content-hash + extractor-version manifest (manifest.json, alongside the sidecars) makes re-extraction a no-op on unchanged files across the multiple loader passes index --auto performs per run.

Every failure mode (encrypted, malformed, empty, no-text-layer, backend-missing, agent-only) still produces a non-empty, human-readable stub sidecar — an empty sidecar would yield zero chunks and silently vanish from every index.

Key public functions relevant to the agent-authored recovery path: register_sidecar (write a sidecar from a hand-authored transcript, never imports pypdf), sidecar_states (per-source-file state report backing retrieval sidecar --list), and agent_sidecar_revision (extracts the fingerprint-relevant revision string from a manifest entry, consumed by retrieval.persistence.compute_fingerprint).

Sidecar-transcript extraction for non-text-native document formats (PDF + agent-only media).

Stdlib-only at import scope (dataclasses, hashlib, io, json, os, re, struct, sys, time, statistics, unicodedata, pathlib, typing) — this module must import cleanly with zero optional extras installed, same guarantee as the rest of the default pipeline. The pypdf backend is imported lazily, only inside the functions that actually need it, mirroring the guidance-RuntimeError convention used by retrieval.retrievers._require_backends and retrieval.ast_chunker.chunk_code.

This module deliberately does not import retrieval.persistence or retrieval.project_loader: persistence imports project_loader, which imports this module — importing either back would create a cycle. _CACHE_DIRNAME therefore duplicates persistence.CACHE_DIRNAME's value as its own constant (see the drift-guard test in tests/test_extractors.py that asserts the two stay equal).

Design: a PDF's extracted text is written once to a Markdown "sidecar" file under <project-root>/.agentic-retrieval/extracted/<rel-path>.md (always under the project root, deliberately ignoring RETRIEVAL_INDEX_DIR — a sidecar is a citation target a coding agent Read()s by project-relative path, so it must live in the tree being indexed even when the cache itself is redirected elsewhere). A content-hash + extractor-version manifest (manifest.json, alongside the sidecars) makes re-extraction a no-op on unchanged files across the multiple loader passes index --auto performs per run. Every failure mode (encrypted, malformed, empty, no-text-layer, backend-missing) still produces a non-empty, human-readable sidecar — the chunker returns zero chunks for blank input, so an empty stub would silently vanish from every index.

No-install alternative: when pypdf isn't installed (or installing it isn't an option), register_sidecar lets a coding agent that read the PDF itself hand-author the transcript and register it directly — never importing pypdf on that path either. An agent-authored entry is a durable, first-class sidecar (AGENT_EXTRACTOR_VERSION), never silently superseded by a later pypdf install; only an explicit retrieval extract --force overwrites it. See retrieval sidecar --list --register (retrieval.cli) and the retrieval skill's "Without the pdf extra" section.

Beyond PDF (and caption files, .srt/.vtt — a second stdlib-only machine extractor, see _extract_captions), a second tier of media (AGENT_ONLY_EXTENSIONS — office docs and images) has no machine extractor at all: ensure_sidecar always writes an "agent-only" stub for these suffixes, regardless of what's installed, and the retrieval sidecar --register workflow above is the only way to index their real content.

A third tier (AGENT_ORCHESTRATED_EXTENSIONS — audio/video) goes further still: an agent cannot even read these natively, so it must orchestrate an external tool (ASR via Bash) and register the result the same way. Because these files can be arbitrarily large, ensure_sidecar/register_sidecar never read their bytes at all for identity purposes — see _source_identity's stat-only "stat/1" hash for this tier, versus the byte-hash "sha256/1" every other tier uses.

Extraction dataclass

Raw extraction result for one PDF's bytes (backend-agnostic).

Source code in engine/retrieval/extractors.py
199
200
201
202
203
204
205
206
207
@dataclass(frozen=True)
class Extraction:
    """Raw extraction result for one PDF's bytes (backend-agnostic)."""

    text: str
    status: str
    reason: str
    pages: int
    truncated: bool

Sidecar dataclass

A resolved, on-disk sidecar — what ensure_sidecar returns.

Source code in engine/retrieval/extractors.py
210
211
212
213
214
215
216
217
218
219
@dataclass(frozen=True)
class Sidecar:
    """A resolved, on-disk sidecar — what ``ensure_sidecar`` returns."""

    docid: str
    path: Path
    text: str
    status: str
    reason: str
    cache_hit: bool

agent_sidecar_revision(entry)

Return entry's sidecar_sha256 when it's an agent-authored manifest entry, else "".

Feeds persistence.compute_fingerprint: mixing this into a discovered file's fingerprint line makes an agent transcript's own content (not just the source PDF's stat) part of staleness detection, so re-registering a changed transcript triggers a reindex even though the source PDF's own bytes/mtime never changed.

Source code in engine/retrieval/extractors.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
def agent_sidecar_revision(entry: Dict[str, Any]) -> str:
    """Return *entry*'s ``sidecar_sha256`` when it's an agent-authored
    manifest entry, else ``""``.

    Feeds ``persistence.compute_fingerprint``: mixing this into a
    discovered file's fingerprint line makes an agent transcript's own
    content (not just the source PDF's stat) part of staleness detection,
    so re-registering a changed transcript triggers a reindex even though
    the source PDF's own bytes/mtime never changed.
    """
    if entry.get("authored_by") != AUTHORED_BY_AGENT:
        return ""
    return entry.get("sidecar_sha256", "")

backend_available()

Lazy-import probe for the pypdf backend.

Used ONLY for content regeneration / staleness decisions (see ensure_sidecar's cache-hit check and needs_reextraction) — NEVER for file-discovery eligibility, which must stay deterministic regardless of which optional extras happen to be installed in a given environment.

Source code in engine/retrieval/extractors.py
351
352
353
354
355
356
357
358
359
360
361
362
363
def backend_available() -> bool:
    """Lazy-import probe for the ``pypdf`` backend.

    Used ONLY for content regeneration / staleness decisions (see
    ``ensure_sidecar``'s cache-hit check and ``needs_reextraction``) — NEVER
    for file-discovery eligibility, which must stay deterministic regardless
    of which optional extras happen to be installed in a given environment.
    """
    try:
        import pypdf  # noqa: F401
    except ImportError:
        return False
    return True

clear_process_cache()

Clear the process-level ensure_sidecar memo (test hook).

Source code in engine/retrieval/extractors.py
366
367
368
def clear_process_cache() -> None:
    """Clear the process-level ``ensure_sidecar`` memo (test hook)."""
    _PROCESS_MEMO.clear()

ensure_sidecar(root, source, *, force=False)

Return the sidecar for source (a file under root), extracting (and caching) it if needed.

Reads source's bytes exactly once (hashes and extracts from the same read — avoids a TOCTOU window between "hash it" and "extract it"), checked first against a process-level memo keyed by (abs_path, st_size, st_mtime_ns) (cheap re-calls within one index --auto run), then against the on-disk manifest (cache hit requires: entry present, sha256 match, extractor-version match, sidecar file present with matching size, and not a stale backend-missing stub now that a backend is installed).

Source code in engine/retrieval/extractors.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def ensure_sidecar(
    root: "os.PathLike[str] | str", source: "os.PathLike[str] | str", *, force: bool = False
) -> Sidecar:
    """Return the sidecar for *source* (a file under *root*), extracting
    (and caching) it if needed.

    Reads *source*'s bytes exactly once (hashes and extracts from the same
    read — avoids a TOCTOU window between "hash it" and "extract it"),
    checked first against a process-level memo keyed by
    ``(abs_path, st_size, st_mtime_ns)`` (cheap re-calls within one
    ``index --auto`` run), then against the on-disk manifest (cache hit
    requires: entry present, sha256 match, extractor-version match, sidecar
    file present with matching size, and not a stale ``backend-missing``
    stub now that a backend is installed).
    """
    root_path = Path(root).resolve()
    source_path = Path(source).resolve()
    rel = source_path.relative_to(root_path).as_posix()
    stat = source_path.stat()
    memo_key = (str(source_path), stat.st_size, stat.st_mtime_ns)
    if not force and memo_key in _PROCESS_MEMO:
        return _PROCESS_MEMO[memo_key]

    sidecar_rel = sidecar_relpath(rel)
    sidecar_path = root_path / sidecar_rel

    manifest = load_manifest(root_path)
    entries = manifest.setdefault("entries", {})
    entry = entries.get(rel)

    suffix = source_path.suffix.lower()
    is_tier3 = suffix in AGENT_ORCHESTRATED_EXTENSIONS
    # Tier-3 (audio/video): never read the source's bytes — _source_identity
    # stat-hashes it instead. `data` stays empty and is never handed to an
    # extractor below (tier-3 has none registered, so that branch is never
    # taken for these suffixes).
    data = b"" if is_tier3 else source_path.read_bytes()
    sha256, source_bytes, identity = _source_identity(
        source_path, stat=stat, data=None if is_tier3 else data
    )

    if _is_cache_hit(entry, sha256, sidecar_path, force):
        text = sidecar_path.read_text(encoding="utf-8")
        sidecar = Sidecar(
            docid=sidecar_rel, path=sidecar_path, text=text,
            status=entry.get("status", "ok"), reason=entry.get("reason", ""), cache_hit=True,
        )
        _PROCESS_MEMO[memo_key] = sidecar
        return sidecar

    extractor = extractor_for(source_path)
    if extractor is None:
        # No machine extractor exists at all for this suffix (agent-only
        # media, or agent-orchestrated tier-3 audio/video): never a
        # "backend missing" situation and must never look like one —
        # needs_reextraction/_is_cache_hit key on the literal
        # "backend-missing" reason to self-heal a stub once pypdf becomes
        # available, and a no-extractor stub must never be caught by that
        # (it would loop forever re-stubbing a docx or an mp4). The two
        # no-extractor tiers get distinct messages/reasons (never
        # "backend-missing" for either) — see _warn_agent_only /
        # _warn_agent_orchestrated and the anti-loop invariant above.
        if is_tier3:
            _warn_agent_orchestrated()
            extraction = _stub("agent-orchestrated", _MSG_AGENT_ORCHESTRATED)
        else:
            _warn_agent_only()
            extraction = _stub("agent-only", _MSG_AGENT_ONLY)
    elif suffix in PYPDF_EXTENSIONS and not backend_available():
        # A registered extractor exists but needs the pypdf backend, which
        # isn't installed — distinct from the no-extractor branch above:
        # this one DOES self-heal once pypdf becomes available.
        _warn_backend_missing()
        extraction = _stub("backend-missing", _MSG_BACKEND_MISSING)
    else:
        extraction = extractor(data)

    sidecar_text = _render_sidecar(rel, extraction, version=extractor_version_for(source_path))
    sidecar_path.parent.mkdir(parents=True, exist_ok=True)
    sidecar_path.write_text(sidecar_text, encoding="utf-8")

    entries[rel] = {
        "sha256": sha256,
        "source_bytes": source_bytes,
        "identity": identity,
        "extractor_version": extractor_version_for(source_path),
        "sidecar": sidecar_rel,
        "sidecar_bytes": len(sidecar_text.encode("utf-8")),
        "pages": extraction.pages,
        "status": extraction.status,
        "reason": extraction.reason,
        "truncated": extraction.truncated,
    }
    manifest["schema"] = 1
    manifest["extractor_version"] = EXTRACTOR_VERSION
    manifest["engine_version"] = _engine_version()
    manifest["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    save_manifest(root_path, manifest)

    sidecar = Sidecar(
        docid=sidecar_rel, path=sidecar_path, text=sidecar_text,
        status=extraction.status, reason=extraction.reason, cache_hit=False,
    )
    _PROCESS_MEMO[memo_key] = sidecar
    return sidecar

extract_dir(root)

Sidecar directory for root: always <root>/.agentic-retrieval/extracted.

Deliberately ignores RETRIEVAL_INDEX_DIR (unlike persistence.index_dir): a sidecar is a citation target a coding agent Read()s by project-relative path, so it must live inside the project tree being indexed even when the index cache itself is redirected to a shared external directory.

Source code in engine/retrieval/extractors.py
387
388
389
390
391
392
393
394
395
396
def extract_dir(root: "os.PathLike[str] | str") -> Path:
    """Sidecar directory for *root*: always ``<root>/.agentic-retrieval/extracted``.

    Deliberately ignores ``RETRIEVAL_INDEX_DIR`` (unlike
    ``persistence.index_dir``): a sidecar is a citation target a coding agent
    ``Read()``s by project-relative path, so it must live inside the project
    tree being indexed even when the index *cache* itself is redirected to a
    shared external directory.
    """
    return Path(root).resolve() / _CACHE_DIRNAME / "extracted"

extractor_for(path)

Return the registered extractor for path's suffix, or None.

Source code in engine/retrieval/extractors.py
308
309
310
def extractor_for(path: "os.PathLike[str] | str") -> Callable[[bytes], Extraction] | None:
    """Return the registered extractor for *path*'s suffix, or ``None``."""
    return _EXTRACTORS.get(Path(path).suffix.lower())

extractor_version_for(path)

Return the manifest extractor_version string to stamp for path's suffix: its _EXTRACTOR_VERSIONS override if one was registered (e.g. captions/1 for .srt/.vtt), else the top-level EXTRACTOR_VERSION (pypdf's, unchanged default).

Source code in engine/retrieval/extractors.py
313
314
315
316
317
318
def extractor_version_for(path: "os.PathLike[str] | str") -> str:
    """Return the manifest ``extractor_version`` string to stamp for
    *path*'s suffix: its ``_EXTRACTOR_VERSIONS`` override if one was
    registered (e.g. ``captions/1`` for ``.srt``/``.vtt``), else the
    top-level ``EXTRACTOR_VERSION`` (pypdf's, unchanged default)."""
    return _EXTRACTOR_VERSIONS.get(Path(path).suffix.lower(), EXTRACTOR_VERSION)

invalidate_process_cache(source)

Drop every _PROCESS_MEMO entry for source, regardless of the (size, mtime_ns) it was memoized under.

register_sidecar calls this after writing a new manifest entry: the process memo is keyed by (abs_path, st_size, st_mtime_ns) of the source PDF, which registration doesn't touch, so a stale stub result from an earlier ensure_sidecar call in this same process would otherwise keep being served instead of the freshly registered transcript.

Source code in engine/retrieval/extractors.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def invalidate_process_cache(source: "os.PathLike[str] | str") -> None:
    """Drop every ``_PROCESS_MEMO`` entry for *source*, regardless of the
    ``(size, mtime_ns)`` it was memoized under.

    ``register_sidecar`` calls this after writing a new manifest entry: the
    process memo is keyed by ``(abs_path, st_size, st_mtime_ns)`` of the
    *source* PDF, which registration doesn't touch, so a stale ``stub``
    result from an earlier ``ensure_sidecar`` call in this same process
    would otherwise keep being served instead of the freshly registered
    transcript.
    """
    resolved = str(Path(source).resolve())
    for key in [k for k in _PROCESS_MEMO if k[0] == resolved]:
        del _PROCESS_MEMO[key]

load_manifest(root)

Load the extraction manifest for root; missing/corrupt -> {}.

Source code in engine/retrieval/extractors.py
408
409
410
411
412
413
def load_manifest(root: "os.PathLike[str] | str") -> Dict[str, Any]:
    """Load the extraction manifest for *root*; missing/corrupt -> ``{}``."""
    try:
        return json.loads(_manifest_path(root).read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {}

needs_reextraction(root)

True if root's manifest has a backend-missing stub entry and a backend is now installed (self-healing regeneration trigger consumed by persistence.is_stale). False (with a single stat, no read) when no manifest exists yet.

Source code in engine/retrieval/extractors.py
435
436
437
438
439
440
441
442
443
444
445
446
447
def needs_reextraction(root: "os.PathLike[str] | str") -> bool:
    """True if *root*'s manifest has a ``backend-missing`` stub entry and a
    backend is now installed (self-healing regeneration trigger consumed by
    ``persistence.is_stale``). False (with a single ``stat``, no read) when
    no manifest exists yet.
    """
    if not _manifest_path(root).exists():
        return False
    if not backend_available():
        return False
    manifest = load_manifest(root)
    entries = manifest.get("entries", {})
    return any(entry.get("reason") == "backend-missing" for entry in entries.values())

prune_manifest(root, keep_rel)

Drop manifest entries for source files not in keep_rel (explicit-use only).

Source code in engine/retrieval/extractors.py
426
427
428
429
430
431
432
def prune_manifest(root: "os.PathLike[str] | str", keep_rel: Iterable[str]) -> None:
    """Drop manifest entries for source files not in *keep_rel* (explicit-use only)."""
    manifest = load_manifest(root)
    keep = set(keep_rel)
    entries = manifest.get("entries", {})
    manifest["entries"] = {k: v for k, v in entries.items() if k in keep}
    save_manifest(root, manifest)

register_extractor(suffix, fn, *, version=None)

Register fn as the extractor for files with suffix (e.g. .pdf).

version, when given, is recorded in _EXTRACTOR_VERSIONS and folded into _ACCEPTED_EXTRACTOR_VERSIONS — a non-pypdf extractor (e.g. the caption converter, captions/1) stamps its own manifest-entry extractor_version via extractor_version_for instead of the top-level EXTRACTOR_VERSION (which stays pypdf's). Omitting version (the .pdf registration below) leaves EXTRACTOR_VERSION as that suffix's version, unchanged from prior releases.

Source code in engine/retrieval/extractors.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def register_extractor(
    suffix: str, fn: Callable[[bytes], Extraction], *, version: str | None = None
) -> None:
    """Register *fn* as the extractor for files with *suffix* (e.g. ``.pdf``).

    *version*, when given, is recorded in ``_EXTRACTOR_VERSIONS`` and folded
    into ``_ACCEPTED_EXTRACTOR_VERSIONS`` — a non-pypdf extractor (e.g. the
    caption converter, ``captions/1``) stamps its own manifest-entry
    ``extractor_version`` via ``extractor_version_for`` instead of the
    top-level ``EXTRACTOR_VERSION`` (which stays pypdf's). Omitting *version*
    (the ``.pdf`` registration below) leaves ``EXTRACTOR_VERSION`` as that
    suffix's version, unchanged from prior releases.
    """
    global _ACCEPTED_EXTRACTOR_VERSIONS
    _EXTRACTORS[suffix.lower()] = fn
    if version is not None:
        _EXTRACTOR_VERSIONS[suffix.lower()] = version
        _ACCEPTED_EXTRACTOR_VERSIONS = frozenset(
            {EXTRACTOR_VERSION, AGENT_EXTRACTOR_VERSION} | set(_EXTRACTOR_VERSIONS.values())
        )

register_sidecar(root, source, transcript, *, truncated=False)

Register an agent-authored transcript as source's sidecar.

The no-pypdf recovery path for PDFs, and the only indexing path for AGENT_ONLY_EXTENSIONS media (docx/pptx/xlsx/images), which have no machine extractor at all: a coding agent that read source natively (e.g. via its own Read tool, or vision for an image) can hand-write the extracted text and register it here instead of (or in place of) installing the pdf extra. Never imports pypdf on any path — this function works identically whether or not the backend is installed.

Writes the same sidecar-Markdown shape ensure_sidecar would (source + extractor header, then the transcript), stamped with AGENT_EXTRACTOR_VERSION so _is_cache_hit recognizes it as fresh and needs_reextraction/extract --force know not to silently treat it as a stale pypdf stub (see module docstring's supersede policy). truncated is the caller-declared truncation flag when the caller already truncated its own transcript upstream; this function additionally truncates at MAX_TRANSCRIPT_CHARS itself if needed, OR-ing the two flags together.

Source code in engine/retrieval/extractors.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
def register_sidecar(
    root: "os.PathLike[str] | str",
    source: "os.PathLike[str] | str",
    transcript: str,
    *,
    truncated: bool = False,
) -> Sidecar:
    """Register an agent-authored *transcript* as *source*'s sidecar.

    The no-pypdf recovery path for PDFs, and the **only** indexing path for
    ``AGENT_ONLY_EXTENSIONS`` media (docx/pptx/xlsx/images), which have no
    machine extractor at all: a coding agent that read *source* natively
    (e.g. via its own ``Read`` tool, or vision for an image) can hand-write
    the extracted text and register it here instead of (or in place of)
    installing the ``pdf`` extra. Never imports ``pypdf`` on any path — this
    function works identically whether or not the backend is installed.

    Writes the same sidecar-Markdown shape ``ensure_sidecar`` would (source
    + extractor header, then the transcript), stamped with
    ``AGENT_EXTRACTOR_VERSION`` so ``_is_cache_hit`` recognizes it as fresh
    and ``needs_reextraction``/``extract --force`` know not to silently
    treat it as a stale pypdf stub (see module docstring's supersede
    policy). *truncated* is the caller-declared truncation flag when the
    caller already truncated its own transcript upstream; this function
    additionally truncates at ``MAX_TRANSCRIPT_CHARS`` itself if needed,
    OR-ing the two flags together.
    """
    root_path = Path(root).resolve()
    source_path = Path(source).resolve()
    try:
        rel = source_path.relative_to(root_path).as_posix()
    except ValueError:
        raise ValueError(f"{source_path} is not under root {root_path}") from None
    if not source_path.is_file():
        raise ValueError(f"source file not found: {source_path}")
    if source_path.suffix.lower() not in EXTRACTABLE_EXTENSIONS:
        raise ValueError(
            f"{rel!r} has a suffix not in EXTRACTABLE_EXTENSIONS "
            f"({sorted(EXTRACTABLE_EXTENSIONS)})"
        )

    if not transcript.strip():
        raise ValueError("transcript is empty")

    text = _LEADING_COMMENT_RE.sub("", transcript)
    pages = len(_UNIT_HEADING_RE.findall(text))
    if len(text) > MAX_TRANSCRIPT_CHARS:
        text, was_truncated = _truncate_agent_transcript(text)
        truncated = truncated or was_truncated

    # Never read_bytes() a tier-3 (audio/video) source — _source_identity
    # stat-hashes it instead, same as ensure_sidecar.
    sha256, source_bytes, identity = _source_identity(source_path)

    extraction = Extraction(text=text, status="ok", reason="", pages=pages, truncated=truncated)
    sidecar_text = _render_sidecar(rel, extraction, version=AGENT_EXTRACTOR_VERSION)
    sidecar_rel = sidecar_relpath(rel)
    sidecar_path = root_path / sidecar_rel
    sidecar_path.parent.mkdir(parents=True, exist_ok=True)
    sidecar_path.write_text(sidecar_text, encoding="utf-8")
    sidecar_sha256 = hashlib.sha256(sidecar_text.encode("utf-8")).hexdigest()

    manifest = load_manifest(root_path)
    entries = manifest.setdefault("entries", {})
    entries[rel] = {
        "sha256": sha256,
        "source_bytes": source_bytes,
        "identity": identity,
        "extractor_version": AGENT_EXTRACTOR_VERSION,
        "sidecar": sidecar_rel,
        "sidecar_bytes": len(sidecar_text.encode("utf-8")),
        "pages": pages,
        "status": "ok",
        "reason": "",
        "truncated": truncated,
        "authored_by": AUTHORED_BY_AGENT,
        "authored_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "sidecar_sha256": sidecar_sha256,
    }
    manifest["schema"] = 1
    manifest["extractor_version"] = EXTRACTOR_VERSION
    manifest["engine_version"] = _engine_version()
    manifest["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    save_manifest(root_path, manifest)

    invalidate_process_cache(source_path)

    return Sidecar(
        docid=sidecar_rel, path=sidecar_path, text=sidecar_text,
        status="ok", reason="", cache_hit=False,
    )

require_extractors(extensions)

Raise a guidance RuntimeError if extensions needs the pypdf backend and it isn't installed (mirrors retrieval.retrievers' guidance-RuntimeError convention: RuntimeError, not ImportError, two-line message).

Only checks extension membership in PYPDF_EXTENSIONS (currently .pdf) — never probes import success for eligibility/discovery, only for this explicit preflight call. Every other extractable suffix (AGENT_ONLY_EXTENSIONS, stdlib-only machine extractors like captions, AGENT_ORCHESTRATED_EXTENSIONS) never needs a backend, so they're excluded from this guard — this is a deliberate split from the former "any MACHINE_EXTRACTABLE_EXTENSIONS member needs pypdf" conflation, which would have misreported a caption-only tree as needing pypdf.

Source code in engine/retrieval/extractors.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def require_extractors(extensions: Iterable[str]) -> None:
    """Raise a guidance ``RuntimeError`` if *extensions* needs the ``pypdf``
    backend and it isn't installed (mirrors ``retrieval.retrievers``'
    guidance-``RuntimeError`` convention: ``RuntimeError``, not
    ``ImportError``, two-line message).

    Only checks extension membership in ``PYPDF_EXTENSIONS`` (currently
    ``.pdf``) — never probes import success for eligibility/discovery, only
    for this explicit preflight call. Every other extractable suffix
    (``AGENT_ONLY_EXTENSIONS``, stdlib-only machine extractors like
    captions, ``AGENT_ORCHESTRATED_EXTENSIONS``) never needs a backend, so
    they're excluded from this guard — this is a deliberate split from the
    former "any ``MACHINE_EXTRACTABLE_EXTENSIONS`` member needs pypdf"
    conflation, which would have misreported a caption-only tree as needing
    ``pypdf``.
    """
    if not any(ext.lower() in PYPDF_EXTENSIONS for ext in extensions):
        return
    try:
        import pypdf  # noqa: F401
    except ImportError as exc:  # pragma: no cover - guidance path
        raise RuntimeError(
            "PDF extraction needs the 'pdf' extra:\n"
            "  uv pip install -e '.[pdf]'\n"
            "No-install alternative: an agent can author the transcript "
            "itself and register it with `retrieval sidecar --register "
            "<pdf> --transcript <file>`."
        ) from exc

save_manifest(root, manifest)

Atomically write manifest (tmp file + os.replace).

Source code in engine/retrieval/extractors.py
416
417
418
419
420
421
422
423
def save_manifest(root: "os.PathLike[str] | str", manifest: Dict[str, Any]) -> None:
    """Atomically write *manifest* (tmp file + ``os.replace``)."""
    directory = extract_dir(root)
    directory.mkdir(parents=True, exist_ok=True)
    path = _manifest_path(root)
    tmp_path = path.with_suffix(path.suffix + ".tmp")
    tmp_path.write_text(json.dumps(manifest), encoding="utf-8")
    os.replace(tmp_path, path)

sidecar_relpath(rel_source)

Return the project-relative sidecar path for rel_source.

Source code in engine/retrieval/extractors.py
399
400
401
def sidecar_relpath(rel_source: str) -> str:
    """Return the project-relative sidecar path for *rel_source*."""
    return f"{_CACHE_DIRNAME}/extracted/{rel_source}.md"

sidecar_states(root, sources)

Report each of sources' sidecar state, for retrieval sidecar --list (see _entry_state for the state taxonomy).

Source code in engine/retrieval/extractors.py
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
def sidecar_states(
    root: "os.PathLike[str] | str", sources: Iterable["os.PathLike[str] | str"]
) -> List[Dict[str, Any]]:
    """Report each of *sources*' sidecar state, for ``retrieval sidecar
    --list`` (see ``_entry_state`` for the state taxonomy)."""
    root_path = Path(root).resolve()
    entries = load_manifest(root_path).get("entries", {})
    results: List[Dict[str, Any]] = []
    for source in sources:
        source_path = Path(source).resolve()
        rel = source_path.relative_to(root_path).as_posix()
        entry = entries.get(rel)
        results.append(_sidecar_state_record(rel, entry, _entry_state(entry, source_path)))
    return results

Extractor-version / status taxonomy

extractor_version Written by status
pypdf-text/1 (EXTRACTOR_VERSION) ensure_sidecar (the pypdf backend) ok, or stub (see the stub taxonomy below)
captions/1 (CAPTIONS_EXTRACTOR_VERSION) ensure_sidecar (.srt/.vtt, stdlib-only) ok, or stub (no-cues/malformed)
agent-authored/1 (AGENT_EXTRACTOR_VERSION) register_sidecar (an agent-authored transcript) always ok — an agent transcript never renders as a stub

All three extractor-version strings are accepted as "fresh" by _is_cache_hit (membership in _ACCEPTED_EXTRACTOR_VERSIONS, which is {EXTRACTOR_VERSION, AGENT_EXTRACTOR_VERSION} | set(_EXTRACTOR_VERSIONS.values()) — rebuilt automatically whenever register_extractor(..., version=...) registers a new per-suffix version, not equality against a single constant). extractor_version_for(path) returns the version to stamp for a given path's suffix: its _EXTRACTOR_VERSIONS override if one is registered, else the top-level EXTRACTOR_VERSION.

Stub taxonomy (status == "stub")

reason When
encrypted Password-protected PDF; the empty-password decrypt attempt failed
crypto-unavailable Encrypted PDF using a method needing the optional cryptography package
empty PDF with zero pages
no-text-layer Scanned/image-only PDF (no OCR performed)
malformed Corrupted or unsupported PDF structure
backend-missing PDF, but pypdf is not installed
no-cues Caption file (.srt/.vtt) parses but contains zero cues (timed text)
malformed (captions) Caption file has no --> cue-timing lines at all — not recognizable as SRT/VTT
agent-only AGENT_ONLY_EXTENSIONS suffix (docx/pptx/xlsx/image) — no machine extractor exists for this format at all, regardless of what's installed; distinct from backend-missing so it's never mistaken for a stale pypdf stub that self-heals once pypdf becomes available (needs_reextraction/_is_cache_hit key on the literal "backend-missing" string)
agent-orchestrated AGENT_ORCHESTRATED_EXTENSIONS suffix (audio/video) — no machine extractor, and no native agent-readable path either; distinct from both agent-only and backend-missing for the same self-heal-avoidance reason

Backend-missing degradation vs. hard failure

index/query never hard-fail on a missing pypdf backend — a PDF without a usable backend still indexes as a searchable, backend-missing stub, with a single warning: pypdf is not installed line printed to stderr per process (_warn_backend_missing). The retrieval extract subcommand is the one place a missing backend does hard-fail, via an explicit preflight require_extractors() call — see CLI reference: extract. require_extractors's guidance message and the backend-missing stub's own text both point at retrieval sidecar --register as the no-install alternative.

Supersede policy: agent-authored entries are never auto-replaced

An agent-authored sidecar (register_sidecar) is treated as a durable, first-class transcript — installing the pdf extra later does not cause it to be silently regenerated by pypdf (needs_reextraction and _is_cache_hit's backend-missing check both stay pinned on the literal reason == "backend-missing" string, which an agent entry never has). The one deliberate escape hatch is retrieval extract --force, which prints warning: overwriting N agent-authored sidecar(s) with pypdf output to stderr before doing so.

Agent-only media has no degradation path

Unlike PDF's backend-missing stub, an agent-only stub never "self-heals": require_extractors and backend_available() both only ever concern pypdf/MACHINE_EXTRACTABLE_EXTENSIONS, so there is no install that turns an agent-only stub into a real transcript — retrieval sidecar --register is the only path. extract never attempts these suffixes either (see CLI reference: extract); its --prune keep-set still preserves a registered agent-only sidecar, since pruning is based on discovery (extractors.EXTRACTABLE_EXTENSIONS), not on what extract's own extraction loop touched.

Stat-only identity for tier 3 (audio/video)

Every tier except AGENT_ORCHESTRATED_EXTENSIONS identifies a source file by a real SHA-256 hash of its bytes (identity: "sha256/1" in the manifest entry). Tier 3 is the exception: _source_identity never calls read_bytes() on an audio/video source — it computes sha256("stat/1|{st_size}|{st_mtime_ns}") from a single os.stat() call instead, stored under the same sha256 manifest key with a sibling identity: "stat/1" field marking it as a stat fingerprint rather than a content hash. This is deliberate: these files can be arbitrarily large and are uncapped at discovery, so the engine has no business allocating a multi-GB buffer just to hash bytes it then discards. ensure_sidecar, register_sidecar, and _entry_state (backing sidecar --list) all route through this one helper.

Trade-off: an in-place edit that happens to preserve both file size and mtime produces a false cache hit under "stat/1" — impossible under "sha256/1", which would catch any content change. retrieval extract --force (or ensure_sidecar(..., force=True)) is the escape hatch when that matters.

Section headings: ## Page N and ## [HH:MM:SS] ...

_UNIT_HEADING_RE (used for both unit counting and truncation boundaries) matches two heading shapes: the PDF convention (## Page N) and the time-coded convention used by caption/media transcripts (## [HH:MM:SS] label). Both are treated identically by the chunker — heading density sets chunk size — and both are honored by register_sidecar's oversized-transcript truncation (_truncate_at_unit_boundary, cutting only at a whole-unit boundary, never mid-page or mid-section).

Next steps