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..pdfneeds the optionalpypdfbackend (seePYPDF_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, andretrieval sidecar --registeris 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 (seeproject_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 | |
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 | |
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 | |
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 | |
clear_process_cache()
¶
Clear the process-level ensure_sidecar memo (test hook).
Source code in engine/retrieval/extractors.py
366 367 368 | |
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 | |
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 | |
extractor_for(path)
¶
Return the registered extractor for path's suffix, or None.
Source code in engine/retrieval/extractors.py
308 309 310 | |
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 | |
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 | |
load_manifest(root)
¶
Load the extraction manifest for root; missing/corrupt -> {}.
Source code in engine/retrieval/extractors.py
408 409 410 411 412 413 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
sidecar_relpath(rel_source)
¶
Return the project-relative sidecar path for rel_source.
Source code in engine/retrieval/extractors.py
399 400 401 | |
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 | |
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).