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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): read the documents a real folder is full of
Ruben Lütkeb983f1883ff9
diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.pyindex 74d1012a4b..7aa3c631f5 100644--- a/jarvis/ultrawiki/connectors/local_folder.py+++ b/jarvis/ultrawiki/connectors/local_folder.py@@ -41,6 +41,11 @@ from collections.abc import AsyncIterator, Sequencefrom datetime import UTC, datetimefrom pathlib import Path+from jarvis.ultrawiki.document_text import (+ DOCUMENT_EXTENSIONS,+ extract_document_text,+ is_document,+)from jarvis.ultrawiki.types import (AuthKind,ConnectorCapabilities,@@ -106,6 +111,7 @@ def _path_exists(text: str) -> bool:except (OSError, ValueError):return False+#: Directory names never walked, on top of every dot-prefixed one. These hold#: machine output, not knowledge: dependency trees, byte-code caches, and the#: per-OS application-data folders. Importing a home folder without this list@@ -258,6 +264,7 @@ class LocalFolderConnector:*_DATA_EXTENSIONS,*_MARKUP_EXTENSIONS,*_CODE_EXTENSIONS,+ *DOCUMENT_EXTENSIONS,)#: Directory names skipped in addition to hidden (dot-prefixed) ones.SKIP_DIR_NAMES: frozenset[str] = NOISE_DIR_NAMES@@ -343,8 +350,7 @@ class LocalFolderConnector:return rootif exists:raise LocalFolderRootError(- f"{root} is a file, not a folder. Point this source at the "- f"folder that CONTAINS it."+ f"{root} is a file, not a folder. Point this source at the folder that CONTAINS it.")raise LocalFolderRootError(f"There is no folder at {root}. Check the path: a value copied "@@ -425,6 +431,31 @@ class LocalFolderConnector:items.append(item)return items+ def _body_for(self, path: Path, size: int) -> str | None:+ """The file's text, or ``None`` when there is none worth an item.++ Two different reads behind one call: an opaque document goes through+ an extractor (and carries its own, far larger size ceiling — a PDF is+ mostly layout, and judging it by the plain-text limit would drop every+ real one), everything else is read as UTF-8 with replacement.+ """+ if is_document(path):+ return extract_document_text(path)+ if size > self.MAX_FILE_BYTES:+ log.info(+ "%s: skipping %s (%d bytes exceeds the %d-byte limit)",+ self.id,+ path,+ size,+ self.MAX_FILE_BYTES,+ )+ return None+ try:+ return path.read_text(encoding="utf-8", errors="replace")+ except OSError as exc:+ log.debug("%s: read failed for %s: %s", self.id, path, exc)+ return None+def _mtime_ns(self, path: Path) -> int | None:try:return path.stat().st_mtime_ns@@ -438,19 +469,8 @@ class LocalFolderConnector:except OSError as exc:log.debug("%s: stat failed for %s: %s", self.id, path, exc)return None- if stat.st_size > self.MAX_FILE_BYTES:- log.info(- "%s: skipping %s (%d bytes exceeds the %d-byte limit)",- self.id,- path,- stat.st_size,- self.MAX_FILE_BYTES,- )- return None- try:- body = path.read_text(encoding="utf-8", errors="replace")- except OSError as exc:- log.debug("%s: read failed for %s: %s", self.id, path, exc)+ body = self._body_for(path, stat.st_size)+ if body is None:return Nonereturn RawItem(external_id=self._external_id_for(root, path),diff --git a/jarvis/ultrawiki/document_text.py b/jarvis/ultrawiki/document_text.pynew file mode 100644index 0000000000..9169312c1b--- /dev/null+++ b/jarvis/ultrawiki/document_text.py@@ -0,0 +1,270 @@+"""Read plain text out of the opaque document formats a real folder holds.++A folder a user actually chooses is not a notes vault: it holds PDFs, Word+files and slide decks next to the markdown. Those are containers, not text —+reading them as UTF-8 yields megabytes of replacement characters — so the+folder walk routes them here instead.++Two rules govern everything below:++* **A failure is a SKIP, never a raise.** One password-protected PDF or one+ truncated ``.docx`` must not end a walk over ten thousand files. Every+ extractor returns ``None`` and logs; the caller drops that one file.+* **No new dependency for the Office formats.** ``.docx`` and ``.pptx`` are+ zip archives of XML, which the standard library opens on every platform.+ Only PDF needs ``pypdf``, which is already a base requirement — and a+ install without it degrades to a logged skip rather than an import error+ (charter §3: the walk still has to work on a bare server).++Nothing here touches the event loop: every function BLOCKS on file I/O and is+called from the connector's worker thread.+"""++from __future__ import annotations++import logging+import xml.etree.ElementTree as ET+import zipfile+from pathlib import Path++log = logging.getLogger(__name__)++#: Suffixes routed to an extractor instead of being read as UTF-8 text.+DOCUMENT_EXTENSIONS: tuple[str, ...] = (".pdf", ".docx", ".pptx")++#: Size ceiling for a document. Far above the plain-text limit (a 40-page PDF+#: with figures is routinely 20 MB and holds a few pages of prose), far below+#: anything that could exhaust memory on a small VPS.+MAX_DOCUMENT_BYTES = 64 * 1024 * 1024++#: Characters kept from one document. A 900-page manual is a reference work,+#: not one retrievable thought; the chunker downstream splits what arrives.+MAX_DOCUMENT_CHARS = 2 * 1024 * 1024++#: OOXML text-bearing leaf elements, by namespace. WordprocessingML uses+#: ``<w:t>``; DrawingML (slides, and text boxes inside any Office file) uses+#: ``<a:t>``. Matched on the LOCAL name so a file written by a different+#: producer with a different prefix still reads.+_TEXT_TAGS = frozenset({"t"})++#: Elements that end a line: a Word paragraph / line break, a slide paragraph.+#: Without these, "The ledger" and "reconciliation" concatenate into one token+#: that no search will ever match.+_BREAK_TAGS = frozenset({"p", "br", "tab", "cr"})++#: A document part that declares a DTD or an entity. OOXML producers never do;+#: an "entity bomb" is nothing but declarations, so their PRESENCE is the+#: signal. Checked on the raw bytes before any parser sees them, because this+#: check cannot be broken by a parser-internals change (defence in depth: the+#: parser below refuses the same thing again).+_DTD_MARKERS: tuple[bytes, ...] = (b"<!DOCTYPE", b"<!ENTITY", b"<!doctype")+++def is_document(path: Path) -> bool:+ """``True`` when ``path`` needs an extractor rather than a UTF-8 read."""+ return path.suffix.lower() in DOCUMENT_EXTENSIONS+++def extract_document_text(path: Path) -> str | None:+ """Plain text of one document, or ``None`` when it holds none we can read.++ ``None`` covers every honest miss: oversized, encrypted, corrupt, a scan+ without a text layer, or an extractor that is not installed. Blocking.+ """+ try:+ size = path.stat().st_size+ except OSError as exc:+ log.debug("document skipped, stat failed for %s: %s", path, exc)+ return None+ if size > MAX_DOCUMENT_BYTES:+ log.info(+ "document skipped: %s is %d bytes, over the %d-byte limit",+ path,+ size,+ MAX_DOCUMENT_BYTES,+ )+ return None+ suffix = path.suffix.lower()+ if suffix == ".pdf":+ return _clean(_pdf_text(path))+ if suffix in (".docx", ".pptx"):+ return _clean(_ooxml_text(path))+ return None+++def _clean(text: str | None) -> str | None:+ """Normalize whitespace; whitespace-only extraction counts as nothing."""+ if not text:+ return None+ stripped = text.strip()+ if not stripped:+ return None+ return stripped[:MAX_DOCUMENT_CHARS]+++def _pdf_text(path: Path) -> str | None:+ try:+ from pypdf import PdfReader # noqa: PLC0415 — lazy (AP-26)+ except ImportError:+ log.info(+ "PDF skipped: %s needs the 'pypdf' package, which is not installed in this environment",+ path,+ )+ return None+ try:+ reader = PdfReader(str(path))+ if reader.is_encrypted:+ # An empty user password is the common "protected but readable"+ # case; anything else is genuinely locked and gets skipped.+ try:+ opened = reader.decrypt("")+ except Exception: # noqa: BLE001 — a locked file is a skip+ opened = 0+ if not opened:+ log.info("PDF skipped: %s is password protected", path)+ return None+ pages = list(reader.pages)+ except Exception as exc: # noqa: BLE001 — a broken PDF is a skip, not a stop+ log.info("PDF skipped: %s could not be opened (%s)", path, type(exc).__name__)+ return None+ parts: list[str] = []+ total = 0+ for index, page in enumerate(pages):+ try:+ text = page.extract_text() or ""+ except Exception as exc: # noqa: BLE001 — one bad page, not a bad file+ log.debug("page %d of %s could not be extracted: %s", index, path, exc)+ continue+ if not text.strip():+ continue+ parts.append(text)+ total += len(text)+ if total >= MAX_DOCUMENT_CHARS:+ break+ return "\n\n".join(parts) if parts else None+++def _ooxml_text(path: Path) -> str | None:+ """Text of a Word document or slide deck, in reading order."""+ try:+ with zipfile.ZipFile(path) as archive:+ names = _ooxml_parts(path.suffix.lower(), archive.namelist())+ if not names:+ log.info("document skipped: %s holds no readable text part", path)+ return None+ chunks = [_part_text(archive, name, path) for name in names]+ except (zipfile.BadZipFile, OSError) as exc:+ log.info("document skipped: %s could not be opened (%s)", path, type(exc).__name__)+ return None+ body = "\n\n".join(chunk for chunk in chunks if chunk)+ return body or None+++def _ooxml_parts(suffix: str, names: list[str]) -> list[str]:+ """The XML parts holding body text, in the order they are read."""+ if suffix == ".docx":+ return [name for name in names if name == "word/document.xml"]+ slides = [+ name for name in names if name.startswith("ppt/slides/slide") and name.endswith(".xml")+ ]+ # slide2 before slide10: sort on the number, not the string.+ return sorted(slides, key=_slide_order)+++def _slide_order(name: str) -> tuple[int, str]:+ digits = "".join(ch for ch in Path(name).stem if ch.isdigit())+ return (int(digits) if digits else 0, name)+++def _part_text(archive: zipfile.ZipFile, name: str, path: Path) -> str:+ try:+ raw = archive.read(name)+ except (KeyError, zipfile.BadZipFile, OSError) as exc:+ log.debug("part %s of %s is unreadable: %s", name, path, exc)+ return ""+ if any(marker in raw for marker in _DTD_MARKERS):+ log.warning(+ "document skipped: %s declares a DTD or entity, which no Office "+ "producer emits and an entity-expansion attack consists of",+ path,+ )+ return ""+ try:+ root = ET.fromstring(raw, parser=_safe_parser()) # noqa: S314 — hardened+ except ET.ParseError as exc:+ log.info("document skipped: %s holds malformed XML (%s)", path, exc)+ return ""+ except Exception as exc: # noqa: BLE001 — a refused entity surfaces here+ log.warning("document skipped: %s was refused by the parser (%s)", path, exc)+ return ""+ return _element_text(root)+++class _RefusedEntity(ValueError):+ """Raised from the parser callback when a document declares an entity."""+++def _safe_parser() -> ET.XMLParser:+ """An ElementTree parser that refuses to declare or fetch any entity.++ The stdlib parser expands internal entities, which is the whole mechanism+ behind "billion laughs": a handful of nested declarations expand to+ gigabytes and take the process with them. OOXML has no legitimate use for+ custom entities, so refusing the DECLARATION removes the class instead of+ trying to bound the expansion. External references are refused too, so a+ document can never make this machine fetch a URL.++ Best-effort by construction: ``XMLParser.parser`` is a CPython detail, and+ on a runtime that does not expose it the byte-level DTD check above is+ already the blocking guard.+ """+ # noqa S314: this factory IS the hardening the rule asks for. defusedxml is+ # not a dependency here (it would add one to the universal base install for+ # a guard the two layers below already give), so the entity handlers are+ # disarmed directly and a DTD is refused on the bytes before this runs.+ parser = ET.XMLParser() # noqa: S314+ expat = getattr(parser, "parser", None)+ if expat is None: # pragma: no cover - non-CPython runtime+ return parser++ def _refuse(*_args: object, **_kwargs: object) -> None:+ raise _RefusedEntity("this document declares an XML entity")++ for handler in (+ "EntityDeclHandler",+ "UnparsedEntityDeclHandler",+ "ExternalEntityRefHandler",+ ):+ try:+ setattr(expat, handler, _refuse)+ except (AttributeError, TypeError): # pragma: no cover - defensive+ log.debug("XML hardening: %s could not be installed", handler)+ return parser+++def _element_text(root: ET.Element) -> str:+ """Walk the tree, joining text leaves and honoring paragraph breaks."""+ pieces: list[str] = []+ for element in root.iter():+ local = _local_name(element.tag)+ if local in _TEXT_TAGS and element.text:+ pieces.append(element.text)+ elif local in _BREAK_TAGS and pieces and pieces[-1] != "\n":+ pieces.append("\n")+ return "".join(pieces)+++def _local_name(tag: object) -> str:+ """``{namespace}t`` -> ``t``; a comment's callable tag -> ``""``."""+ if not isinstance(tag, str):+ return ""+ return tag.rpartition("}")[2]+++__all__ = [+ "DOCUMENT_EXTENSIONS",+ "MAX_DOCUMENT_BYTES",+ "MAX_DOCUMENT_CHARS",+ "extract_document_text",+ "is_document",+]diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex abd3b10618..aae2df04e6 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -371,6 +371,80 @@ class TestLocalFolderFileTypes:assert [item.external_id for item in items] == ["note.md"]+def _write_docx(path: Path, paragraphs: list[str]) -> Path:+ """A minimal but real .docx (a zip of OOXML), written at test time."""+ import zipfile++ body = "".join(f"<w:p><w:r><w:t>{text}</w:t></w:r></w:p>" for text in paragraphs)+ document = (+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<w:document xmlns:w="http://schemas.openxmlformats.org/'+ f'wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>'+ )+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ archive.writestr("word/document.xml", document)+ return path+++class TestLocalFolderDocuments:+ """PDFs and Word files are what a real folder is FULL of.++ They are containers, not text: reading them as UTF-8 produced a body of+ replacement characters, so they were excluded — which made "import my+ Desktop" quietly mean "import the two text files on my Desktop".+ """++ async def test_a_word_document_is_imported_with_its_text(self, tmp_path: Path):+ _write_docx(tmp_path / "ledger.docx", ["The quarterly ledger reconciliation"])+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["ledger.docx"]+ assert "quarterly ledger" in items[0].body++ async def test_a_document_title_falls_back_to_the_file_name(self, tmp_path: Path):+ _write_docx(tmp_path / "ledger.docx", ["Body text"])+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert items[0].title == "ledger"++ async def test_a_document_holding_no_readable_text_is_skipped(+ self, tmp_path: Path+ ):+ """An item with an empty body is worse than no item: it ranks and lies."""+ import zipfile++ path = tmp_path / "scan.docx"+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ (tmp_path / "real.md").write_text("# Real", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["real.md"]++ async def test_the_plain_text_size_cap_does_not_apply_to_documents(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ """A 3 MB PDF holding two pages of prose must not be dropped as "big"."""+ monkeypatch.setattr(LocalFolderConnector, "MAX_FILE_BYTES", 64)+ _write_docx(tmp_path / "ledger.docx", ["The quarterly ledger " * 40])+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["ledger.docx"]++ async def test_a_broken_document_never_ends_the_walk(self, tmp_path: Path):+ (tmp_path / "a-broken.docx").write_bytes(b"not a zip")+ (tmp_path / "b-good.md").write_text("# Good", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["b-good.md"]++# ---------------------------------------------------------------------------# Jarvis conversations# ---------------------------------------------------------------------------diff --git a/tests/unit/ultrawiki/test_document_text.py b/tests/unit/ultrawiki/test_document_text.pynew file mode 100644index 0000000000..58a8741808--- /dev/null+++ b/tests/unit/ultrawiki/test_document_text.py@@ -0,0 +1,225 @@+"""Unit tests for reading text out of the document formats a real folder holds.++"Import my Desktop" means the PDFs, Word files and slide decks that live+there, not only the two plain-text suffixes the folder connector started+with. Everything here is generated at test time — no opaque binaries in git —+and every failure mode must degrade to a skip, never to a crash: a folder+walk that dies on one broken file imports nothing at all.+"""++from __future__ import annotations++import zipfile+from pathlib import Path++import pytest++from jarvis.ultrawiki.document_text import (+ DOCUMENT_EXTENSIONS,+ extract_document_text,+ is_document,+)++WORD_XML = (+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/'+ '2006/main"><w:body>'+ "<w:p><w:r><w:t>The quarterly ledger</w:t></w:r></w:p>"+ "<w:p><w:r><w:t>reconciliation lives here.</w:t></w:r></w:p>"+ "</w:body></w:document>"+)++SLIDE_XML = (+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" '+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'+ "<p:cSld><p:spTree>"+ "<p:sp><p:txBody><a:p><a:r><a:t>Telescope maintenance</a:t></a:r></a:p>"+ "</p:txBody></p:sp>"+ "</p:spTree></p:cSld></p:sld>"+)+++def _make_docx(path: Path, document_xml: str = WORD_XML) -> Path:+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ archive.writestr("word/document.xml", document_xml)+ return path+++def _make_pptx(path: Path) -> Path:+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ archive.writestr("ppt/slides/slide1.xml", SLIDE_XML)+ return path+++def _make_pdf(path: Path, pages: list[str]) -> Path:+ """A real, tiny PDF written at test time (mirrors the export-import tests)."""+ pypdf = pytest.importorskip("pypdf")+ from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject++ writer = pypdf.PdfWriter()+ for text in pages:+ page = writer.add_blank_page(width=200, height=200)+ source = pypdf.PdfWriter()+ text_page = source.add_blank_page(width=200, height=200)+ content = DecodedStreamObject()+ content.set_data(+ f"BT /F1 12 Tf 20 100 Td ({text}) Tj ET".encode("latin-1", "replace")+ )+ font = DictionaryObject()+ font[NameObject("/Type")] = NameObject("/Font")+ font[NameObject("/Subtype")] = NameObject("/Type1")+ font[NameObject("/BaseFont")] = NameObject("/Helvetica")+ resources = DictionaryObject()+ fonts = DictionaryObject()+ fonts[NameObject("/F1")] = source._add_object(font) # noqa: SLF001+ resources[NameObject("/Font")] = fonts+ text_page[NameObject("/Resources")] = resources+ text_page[NameObject("/Contents")] = source._add_object(content) # noqa: SLF001+ page.merge_page(text_page)+ with path.open("wb") as handle:+ writer.write(handle)+ return path+++class TestFormatRecognition:+ def test_the_document_suffixes_are_recognised(self):+ assert is_document(Path("a.pdf"))+ assert is_document(Path("a.docx"))+ assert is_document(Path("A.PDF")), "suffix matching must be case-blind"++ def test_plain_text_is_not_a_document(self):+ """Text files go down the UTF-8 path; only opaque formats come here."""+ assert not is_document(Path("a.md"))+ assert not is_document(Path("a.py"))++ def test_the_extension_set_is_lowercase_and_dotted(self):+ assert all(ext.startswith(".") and ext.islower() for ext in DOCUMENT_EXTENSIONS)+++class TestWordAndSlides:+ def test_word_paragraphs_are_extracted_in_order(self, tmp_path: Path):+ path = _make_docx(tmp_path / "ledger.docx")+ text = extract_document_text(path)+ assert text is not None+ assert "The quarterly ledger" in text+ assert text.index("quarterly") < text.index("reconciliation")++ def test_word_paragraphs_do_not_run_together(self, tmp_path: Path):+ """Two paragraphs concatenated into one word would poison retrieval."""+ text = extract_document_text(_make_docx(tmp_path / "ledger.docx"))+ assert text is not None+ assert "ledgerreconciliation" not in text.replace(" ", "")++ def test_slide_text_is_extracted(self, tmp_path: Path):+ text = extract_document_text(_make_pptx(tmp_path / "deck.pptx"))+ assert text is not None+ assert "Telescope maintenance" in text++ def test_a_docx_without_a_document_part_is_skipped(self, tmp_path: Path):+ path = tmp_path / "empty.docx"+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("[Content_Types].xml", "<Types/>")+ assert extract_document_text(path) is None++ def test_a_docx_that_is_not_a_zip_is_skipped_not_raised(self, tmp_path: Path):+ path = tmp_path / "broken.docx"+ path.write_bytes(b"this is not a zip at all")+ assert extract_document_text(path) is None++ def test_malformed_xml_inside_a_docx_is_skipped_not_raised(self, tmp_path: Path):+ path = _make_docx(tmp_path / "torn.docx", document_xml="<w:document><w:body>")+ assert extract_document_text(path) is None+++class TestHostileDocuments:+ """A folder holds files from the internet, not only files the user wrote.++ A downloaded ``.docx`` is attacker-controlled XML. The stdlib parser+ expands internal entities, so a few lines of declaration expand to+ gigabytes ("billion laughs") and take the whole app down with them during+ an unattended import. OOXML never needs custom entities, so the parser+ refuses to declare ANY - which removes the entity-expansion class outright+ rather than trying to bound it.+ """++ def test_an_entity_bomb_is_refused_rather_than_expanded(self, tmp_path: Path):+ bomb = (+ '<?xml version="1.0"?>'+ "<!DOCTYPE lolz ["+ ' <!ENTITY lol "lol">'+ ' <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">'+ ' <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">'+ "]>"+ '<w:document xmlns:w="http://schemas.openxmlformats.org/'+ 'wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>&lol2;'+ "</w:t></w:r></w:p></w:body></w:document>"+ )+ path = _make_docx(tmp_path / "bomb.docx", document_xml=bomb)+ assert extract_document_text(path) is None++ def test_a_clean_document_still_parses_after_the_hardening(+ self, tmp_path: Path+ ):+ """The guard must not cost us ordinary Word files."""+ text = extract_document_text(_make_docx(tmp_path / "fine.docx"))+ assert text is not None+ assert "quarterly ledger" in text.lower()+++class TestPdf:+ def test_pdf_page_text_is_extracted(self, tmp_path: Path):+ path = _make_pdf(tmp_path / "report.pdf", ["Quarterly ledger reconciliation"])+ text = extract_document_text(path)+ assert text is not None+ assert "ledger" in text.lower()++ def test_every_page_contributes(self, tmp_path: Path):+ path = _make_pdf(tmp_path / "two.pdf", ["First page here", "Second page here"])+ text = extract_document_text(path)+ assert text is not None+ assert "First page" in text+ assert "Second page" in text++ def test_a_pdf_without_extractable_text_is_skipped(self, tmp_path: Path):+ """A scan holds pixels, not text; an empty item is worse than no item."""+ pypdf = pytest.importorskip("pypdf")+ path = tmp_path / "scan.pdf"+ writer = pypdf.PdfWriter()+ writer.add_blank_page(width=200, height=200)+ with path.open("wb") as handle:+ writer.write(handle)+ assert extract_document_text(path) is None++ def test_a_corrupt_pdf_is_skipped_not_raised(self, tmp_path: Path):+ path = tmp_path / "torn.pdf"+ path.write_bytes(b"%PDF-1.7\nbut then nothing that parses")+ assert extract_document_text(path) is None++ def test_an_oversized_document_is_skipped(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ from jarvis.ultrawiki import document_text++ monkeypatch.setattr(document_text, "MAX_DOCUMENT_BYTES", 16)+ path = _make_pdf(tmp_path / "big.pdf", ["Quarterly ledger reconciliation"])+ assert extract_document_text(path) is None++ def test_a_missing_pypdf_degrades_to_a_skip(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ """Charter §3: a headless install without the extra must still walk."""+ path = _make_pdf(tmp_path / "report.pdf", ["Quarterly ledger"])+ import builtins++ real_import = builtins.__import__++ def _refuse_pypdf(name, *args, **kwargs):+ if name == "pypdf" or name.startswith("pypdf."):+ raise ImportError("pypdf is not installed")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _refuse_pypdf)+ assert extract_document_text(path) is None