Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
Fix doclib file type tier semantics
jinzhenje216122bd9ec
diff --git a/docs/next/decisions/0022-doclib-file-type-tier-remote-semantics.md b/docs/next/decisions/0022-doclib-file-type-tier-remote-semantics.mdnew file mode 100644index 00000000..1f0dad33--- /dev/null+++ b/docs/next/decisions/0022-doclib-file-type-tier-remote-semantics.md@@ -0,0 +1,155 @@+# ADR-0022: Doclib 文件类型、Tier 与 Remote 语义++状态: Accepted+日期: 2026-06-29+相关文档: ../cli/mineru-parse.md, ../tiers.md, ../errors.md++## 背景++`mineru parse` 支持多种输入格式,但不同格式背后的解析路径并不相同:++- PDF 和 image 可以进入质量 tier 路径,支持 `flash`、`standard` 和 `pro`。+- Office 文件走专门的 Office parser,实际只支持 `flash`。+- text / html 类输入不走 PDF 质量后端,也只具备 `flash` 语义。++此前 Office 文件显式传入 `--tier standard` 或 `--tier pro` 时,会在服务层静默覆盖为 `flash`。CLI 和 JSON 输出只显示最终 tier,无法表达“用户请求被忽略”。这会让自动化脚本、测试和用户判断误以为 standard/pro 已被执行。++同时,image 文件需要支持显式 `parse` 并进入 doclib,但 watch / scan 不应把目录中发现的图片自动当作文档纳入库。`--remote` 也需要明确边界:remote 后端只用于质量解析,不支持 `flash`,也不支持非 PDF / image 输入。++因此需要把文件类型、tier、remote 的组合语义显式化,避免静默降级。++## 决策++### 文件类型集合++doclib 区分两个文件集合:++- `DISCOVERABLE_EXTENSIONS`:watch / scan 自动发现的文档格式。+- `PARSEABLE_EXTENSIONS`:显式 `mineru parse` 可接受的格式。++image 扩展名只进入 `PARSEABLE_EXTENSIONS`,不进入 `DISCOVERABLE_EXTENSIONS`。因此:++- 用户显式执行 `mineru parse image.png` 时,图片会入库、生成 `files` / `docs` 记录,并创建 parse 任务。+- watch / scan 遇到图片文件时忽略,不自动把图片当作文档发现。+- 显式 parse 后,image 与其它文档一样可出现在 show / list / search / find 等 doclib 查询面。++`ALLOWED_EXTENSIONS` 不再保留。调用方应根据语义选择 `DISCOVERABLE_EXTENSIONS` 或 `PARSEABLE_EXTENSIONS`。++### Tier 能力矩阵++质量 tier 只对 PDF 和 image 有意义。++| 文件类型 | `flash` | `standard` | `pro` |+|----------|---------|------------|-------|+| PDF | 支持 | 支持 | 支持 |+| image | 支持 | 支持 | 支持 |+| Office (`docx` / `pptx` / `xlsx`) | 支持 | 不支持 | 不支持 |+| text / html (`txt` / `md` / `csv` / `rst` / `tex` / `html` / `htm`) | 支持 | 不支持 | 不支持 |++当非 PDF / image 文件显式请求 `standard` 或 `pro` 时,doclib 不再自动降级为 `flash`,而是返回 `InvalidRequestError`:++- `code`: `tier_unsupported_for_file_type`+- `param`: `tier`++未显式传入 tier 的非 PDF / image 文件继续按 `flash` 语义处理。++### Remote 能力矩阵++`--remote` 只支持 PDF 和 image,并且不支持 `flash` tier。++| 文件类型 | `--remote` |+|----------|------------|+| PDF | 支持 `standard` / `pro`,不支持 `flash` |+| image | 支持 `standard` / `pro`,不支持 `flash` |+| Office | 不支持 |+| text / html | 不支持 |++当非 PDF / image 文件请求 `--remote` 时,doclib 返回 `InvalidRequestError`:++- `code`: `remote_unsupported_for_file_type`+- `param`: `remote`++当 PDF / image 同时请求 `--remote --tier flash` 时,doclib 返回 `InvalidRequestError`:++- `code`: `tier_unsupported_for_remote`+- `param`: `tier`++当 PDF / image 请求 `--remote` 且未显式传入 tier 时,继续使用现有默认 tier 解析逻辑:根据 remote parse server health 选择可用的最高质量 tier。++### 错误优先级++当多个参数同时冲突时,优先返回更贴近显式冲突参数的错误:++1. `--remote` 与非 PDF / image 文件冲突时,返回 `remote_unsupported_for_file_type`。+2. PDF / image 的 `--remote --tier flash` 冲突时,返回 `tier_unsupported_for_remote`。+3. 非 PDF / image 的 `--tier standard/pro` 冲突时,返回 `tier_unsupported_for_file_type`。++例如 `sample.docx --remote --tier flash` 优先报告 remote 不支持该文件类型,而不是报告 remote 不支持 flash。++## 替代方案++### 方案 A:继续自动降级为 `flash`,在 `tip` 中提示++未采用。++原因:++- 自动化脚本可能只检查退出码和 `status=done`,warning / tip 容易被忽略。+- 用户显式指定 `standard/pro` 表示质量预期,静默或半静默降级会制造错误判断。+- 当前响应模型只有 `tip`,没有稳定的 warnings 列表;把冲突语义塞进提示字段不够可靠。++### 方案 B:为所有格式保留 `standard/pro` 名义兼容++未采用。++原因:++- Office、text、html 并没有对应 PDF 质量后端能力。+- 名义兼容会让 `parse.tier` 和 locator tier 与实际解析路径脱节。+- 后续如果这些格式真的支持质量 tier,应作为新能力显式加入,而不是提前保留虚假语义。++### 方案 C:watch / scan 也自动发现 image++未采用。++原因:++- 用户目录中的图片数量通常远高于文档数量,自动发现会显著增加噪声。+- image 更适合作为显式 parse 的输入,而不是默认文档库扫描目标。+- 显式 parse 已能覆盖需要把图片纳入 doclib 的场景。++## 影响++### 对 CLI / API++- 冲突参数组合从“成功但实际降级”改为 400 类 `InvalidRequestError`。+- JSON 输出、普通 CLI 输出和 `-v` 模式都通过统一错误通道表达冲突,不依赖 warning 文本。+- 新增错误码需要在错误文档中保持可发现。++### 对 doclib 存储++- 显式 parse 的 image 会写入 `files` 和 `docs`,`docs.file_type` 为 `image`。+- `docs.is_image_based` 保留 metadata 中的图片型信息。+- watch / scan 不会因为目录中存在图片而自动创建 doclib 记录。++### 对兼容性++- 这是有意的行为收紧。依赖 `docx --tier standard/pro` 或非 PDF / image `--remote` 成功退出的脚本需要调整。+- 未显式指定质量 tier 的 Office、text、html 解析仍保持 `flash` 语义。+- PDF / image 的本地 `flash` 和本地 / remote `standard/pro` 路径保持可用。++### 对测试++测试应覆盖:++- 显式 parse image 能入库并创建 parse 任务。+- watch / scan 不自动发现 image。+- 非 PDF / image 请求 `standard/pro` 报 `tier_unsupported_for_file_type`。+- 非 PDF / image 请求 `--remote` 报 `remote_unsupported_for_file_type`。+- PDF / image 请求 `--remote --tier flash` 报 `tier_unsupported_for_remote`。++## 后续动作++1. 在 CLI / tier / error 文档中同步文件类型、tier、remote 的能力矩阵。+2. 如果未来 Office 或 text/html 支持质量 tier,应通过新 ADR 或本 ADR 的 superseding 记录更新能力矩阵。+3. 如果需要非错误型 warning 通道,应设计稳定的 `warnings` / `hints` 响应字段,而不是复用 `tip` 承载参数冲突。diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.mdindex c82478a7..85cd97a0 100644--- a/docs/next/decisions/README.md+++ b/docs/next/decisions/README.md@@ -49,6 +49,7 @@| [ADR-0019](0019-mineru-kit-models-command.md) | Accepted | MinerU Kit Models Command || [ADR-0020](0020-doclib-schema-stability-boundary.md) | Accepted | Doclib Schema Stability Boundary || [ADR-0021](0021-doclib-local-transport-discovery.md) | Accepted | Doclib 本地 Transport 与 Endpoint Discovery |+| [ADR-0022](0022-doclib-file-type-tier-remote-semantics.md) | Accepted | Doclib 文件类型、Tier 与 Remote 语义 |## 模板diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.pyindex 1c03847e..d5cf615d 100644--- a/mineru/cli/commands/search.py+++ b/mineru/cli/commands/search.py@@ -15,7 +15,7 @@ def search_cmd(file_type: str | None = typer.Option(None,"--type",- help="File type filter: pdf, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",+ help="File type filter: pdf, image, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",),tier: Tier | None = typer.Option(None, "--tier", help="Exact search index tier: flash, standard, pro"),min_tier: Tier | None = typer.Option(None, "--min-tier", help="Minimum search index tier: flash, standard, pro"),@@ -37,7 +37,7 @@ def find_cmd(ext: str | None = typer.Option(None,"--ext",- help="File extension filter: pdf, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",+ help="File extension filter: pdf, png, jpg, jpeg, jp2, webp, gif, bmp, tiff, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",),limit: int = typer.Option(50, "--limit", "-n", help="Max results"),json_mode: bool = typer.Option(False, "--json", help="JSON output"),diff --git a/mineru/cli/main.py b/mineru/cli/main.pyindex 5c995d48..230c3cdb 100644--- a/mineru/cli/main.py+++ b/mineru/cli/main.py@@ -141,7 +141,7 @@ def search(file_type: str | None = typer.Option(None,"--type",- help="File type filter: pdf, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",+ help="File type filter: pdf, image, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",),tier: Tier | None = typer.Option(None, "--tier", help="Exact search index tier: flash, standard, pro"),min_tier: Tier | None = typer.Option(None, "--min-tier", help="Minimum search index tier: flash, standard, pro"),@@ -161,7 +161,7 @@ def find(ext: str | None = typer.Option(None,"--ext",- help="File extension filter: pdf, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",+ help="File extension filter: pdf, png, jpg, jpeg, jp2, webp, gif, bmp, tiff, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",),limit: int = typer.Option(50, "--limit", "-n", help="Max results"),json_mode: bool = typer.Option(False, "--json", help="JSON output"),diff --git a/mineru/doclib/background/watch.py b/mineru/doclib/background/watch.pyindex a926fc64..0b910e91 100644--- a/mineru/doclib/background/watch.py+++ b/mineru/doclib/background/watch.py@@ -10,7 +10,7 @@ from pathlib import Pathfrom watchfiles import awatchfrom ..core.db import DatabaseManager-from ..constants import ALLOWED_EXTENSIONS, is_office_temp_lock_file+from ..constants import DISCOVERABLE_EXTENSIONS, is_office_temp_lock_filefrom ..services.config_svc import ConfigServicefrom ..services.parse_svc import ParseServicefrom ..services.scan_svc import ScanService@@ -97,7 +97,7 @@ class WatchLoop:for fname in files:filepath = os.path.join(root, fname)ext = Path(filepath).suffix.lstrip(".").lower()- if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):+ if ext not in DISCOVERABLE_EXTENSIONS or is_office_temp_lock_file(filepath):continueif await self.config_svc.is_path_excluded(filepath):continue@@ -131,7 +131,7 @@ class WatchLoop:async def _handle_event(self, filepath: str, watch_id: int) -> None:ext = Path(filepath).suffix.lstrip(".").lower()- if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):+ if ext not in DISCOVERABLE_EXTENSIONS or is_office_temp_lock_file(filepath):returnif await self.config_svc.is_path_excluded(filepath):returndiff --git a/mineru/doclib/constants.py b/mineru/doclib/constants.pyindex af7233be..58284bca 100644--- a/mineru/doclib/constants.py+++ b/mineru/doclib/constants.py@@ -12,6 +12,17 @@ OFFICE_EXTENSIONS: set[str] = {"xlsx",}+IMAGE_EXTENSIONS: set[str] = {+ "bmp",+ "gif",+ "jp2",+ "jpeg",+ "jpg",+ "png",+ "tiff",+ "webp",+}+TEXT_EXTENSIONS: set[str] = {"csv","md",@@ -21,7 +32,7 @@ TEXT_EXTENSIONS: set[str] = {"txt",}-ALLOWED_EXTENSIONS: set[str] = {+DISCOVERABLE_EXTENSIONS: set[str] = {"pdf",*OFFICE_EXTENSIONS,"html",@@ -45,6 +56,11 @@ ALLOWED_EXTENSIONS: set[str] = {# "mbox",}+PARSEABLE_EXTENSIONS: set[str] = {+ *DISCOVERABLE_EXTENSIONS,+ *IMAGE_EXTENSIONS,+}+def is_office_temp_lock_file(path: str | Path) -> bool:file_path = Path(path)diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex c10ff3c8..cff08056 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -16,7 +16,7 @@ from urllib.parse import urlparsefrom ...errors import InvalidRequestError, MineruErrorfrom ...parser.base import ParseResultfrom ...types import TIER_ORDER, PageInfo, Tier-from ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONS, is_office_temp_lock_file+from ..constants import IMAGE_EXTENSIONS, PARSEABLE_EXTENSIONS, TEXT_EXTENSIONS, is_office_temp_lock_filefrom ..core.db import DatabaseManagerfrom ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_statfrom ..core.fts import FTSManager@@ -60,8 +60,11 @@ DOC_TYPE_BY_EXT = {"markdown": "markdown","htm": "html","html": "html",+ **dict.fromkeys(IMAGE_EXTENSIONS, "image"),}+QUALITY_TIER_EXTENSIONS: set[str] = {"pdf", *IMAGE_EXTENSIONS}+FileRefreshStatus = Literal["known", "new", "changed", "missing", "deleted", "unreachable", "unsupported", "error"]@@ -193,6 +196,7 @@ async def ensure_doc_record(author: str | None,subject: str | None,keywords: str | None,+ is_image_based: int = 0,error_code: str | None,error_msg: str | None,first_seen_at: int,@@ -206,8 +210,8 @@ async def ensure_doc_record(short_id = sha256[:length]await db.execute("INSERT OR IGNORE INTO docs (sha256, short_id, size_bytes, file_type, page_count, "- "title, author, subject, keywords, error_code, error_msg, first_seen_at, updated_at) "- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "title, author, subject, keywords, is_image_based, error_code, error_msg, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(sha256,short_id,@@ -218,6 +222,7 @@ async def ensure_doc_record(author,subject,keywords,+ is_image_based,error_code,error_msg,first_seen_at,@@ -273,6 +278,7 @@ class ParseService:watch_id: int | None = None,*,ensure_ingested: bool = False,+ allow_images: bool = False,) -> FileRefreshResult:"""Refresh one source path against the files table.@@ -281,7 +287,7 @@ class ParseService:"""ext = Path(path).suffix.lower().lstrip(".")existing = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))- if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(path):+ if ext not in PARSEABLE_EXTENSIONS or (ext in IMAGE_EXTENSIONS and not allow_images) or is_office_temp_lock_file(path):return FileRefreshResult(file=_file_info(existing), status="unsupported")try:@@ -295,7 +301,7 @@ class ParseService:result = await self._refresh_existing_file_with_stat(path, ext, stat, existing, watch_id)if ensure_ingested and result.needs_ingest:- row = await self.ingest_file(path, watch_id=watch_id)+ row = await self.ingest_file(path, watch_id=watch_id, allow_images=allow_images)return FileRefreshResult(file=_file_info(row), status=result.status)return result@@ -417,19 +423,26 @@ class ParseService:row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],)))return FileRefreshResult(file=_file_info(row), status="error")- async def ensure_ingested(self, path: str, watch_id: int | None = None) -> FileRow | None:+ async def ensure_ingested(self, path: str, watch_id: int | None = None, *, allow_images: bool = False) -> FileRow | None:"""Synchronously discover and ingest a source path when needed."""- refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True)+ refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True, allow_images=allow_images)if refreshed.file is None or refreshed.status == "unsupported":return Nonereturn cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))- async def ingest_file(self, path: str, watch_id: int | None = None, *, trigger: str = "parse") -> FileRow | None:+ async def ingest_file(+ self,+ path: str,+ watch_id: int | None = None,+ *,+ trigger: str = "parse",+ allow_images: bool = False,+ ) -> FileRow | None:"""Ingest a discovered file: SHA-256 + metadata + trigger default parse."""start_ms = _now_ms()status = "succeeded"try:- return await self._ingest_file(path, watch_id=watch_id)+ return await self._ingest_file(path, watch_id=watch_id, allow_images=allow_images)except PermissionError as exc:status = "failed"await self._mark_file_error(path, "file_permission_denied", str(exc))@@ -449,10 +462,10 @@ class ParseService:(error_code, error_msg[:500], now, path),)- async def _ingest_file(self, path: str, watch_id: int | None = None) -> FileRow | None:+ async def _ingest_file(self, path: str, watch_id: int | None = None, *, allow_images: bool = False) -> FileRow | None:"""Ingest implementation without telemetry wrapper."""ext = Path(path).suffix.lower().lstrip(".")- if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(path):+ if ext not in PARSEABLE_EXTENSIONS or (ext in IMAGE_EXTENSIONS and not allow_images) or is_office_temp_lock_file(path):return Nonestat = await get_file_stat(path)@@ -573,6 +586,7 @@ class ParseService:author=metadata["author"],subject=metadata["subject"],keywords=metadata["keywords"],+ is_image_based=int(metadata.get("is_image_based") or 0),error_code=metadata_error_code,error_msg=metadata_error_msg,first_seen_at=now,@@ -644,7 +658,7 @@ class ParseService:) -> ParseResponse:"""Handle a parse request from CLI. Returns info for status polling."""# ensure the path is current before trusting files.sha256- file_row = await self.ensure_ingested(path)+ file_row = await self.ensure_ingested(path, allow_images=True)if file_row is None:return _failed_response(tier or "flash", page_range or "", "File could not be ingested.")@@ -654,13 +668,32 @@ class ParseService:doc = cast(PageCountRow | None, await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,)))page_count = doc["page_count"] if doc else 1privacy = "remote" if remote else "local"+ ext = file_row["ext"]# ── resolve tier (before cache check) ──- requested_tier = tier or _resolve_default_tier(remote)- ext = file_row["ext"]+ if remote and ext not in QUALITY_TIER_EXTENSIONS:+ raise InvalidRequestError(+ "remote_unsupported_for_file_type",+ f"Remote parsing is only supported for PDF and image files; '{ext}' files use local flash parsing.",+ "remote",+ )+ if remote and tier == "flash":+ raise InvalidRequestError(+ "tier_unsupported_for_remote",+ "--remote does not support tier 'flash'; use --tier standard or --tier pro.",+ "tier",+ )+ if tier in ("standard", "pro") and ext not in QUALITY_TIER_EXTENSIONS:+ raise InvalidRequestError(+ "tier_unsupported_for_file_type",+ f"Tier '{tier}' is only supported for PDF and image files; '{ext}' files use --tier flash.",+ "tier",+ )if ext in TEXT_EXTENSIONS:return _text_response(sha256)- if ext in ("docx", "pptx", "xlsx"):+ if ext in QUALITY_TIER_EXTENSIONS:+ requested_tier = tier or _resolve_default_tier(remote)+ else:requested_tier = "flash"# ── expand page range ──diff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.pyindex 4cc53d0b..0501d0dc 100644--- a/mineru/doclib/services/scan_svc.py+++ b/mineru/doclib/services/scan_svc.py@@ -9,7 +9,7 @@ from pathlib import Pathfrom typing import Any, castfrom ...errors import InvalidRequestError, NotFoundError-from ..constants import ALLOWED_EXTENSIONS, is_office_temp_lock_file+from ..constants import DISCOVERABLE_EXTENSIONS, is_office_temp_lock_filefrom ..core.file_io import get_file_statfrom ..rows import PathRow, ScanRow, WatchTargetRowfrom ..types import (@@ -298,7 +298,7 @@ class ScanService:filepath = os.path.join(root, fname)counters.files_seen += 1ext = Path(filepath).suffix.lstrip(".").lower()- if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):+ if ext not in DISCOVERABLE_EXTENSIONS or is_office_temp_lock_file(filepath):counters.files_unsupported += 1continueif apply_excludes and await self.config_svc.is_path_excluded(filepath):diff --git a/mineru/errors.py b/mineru/errors.pyindex f6b9f756..c00efa21 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -38,7 +38,10 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {"rule_not_found": "invalid_request_error","scan_not_found": "invalid_request_error","stat_failed": "invalid_request_error",+ "remote_unsupported_for_file_type": "invalid_request_error","tier_mismatch": "invalid_request_error",+ "tier_unsupported_for_file_type": "invalid_request_error",+ "tier_unsupported_for_remote": "invalid_request_error","watch_not_found": "invalid_request_error",# authentication_error"invalid_api_key": "authentication_error",diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex 584dd497..785a6edd 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -111,11 +111,33 @@ def test_search_and_find_help_list_filter_values() -> None:assert search_result.exit_code == 0assert find_result.exit_code == 0- assert "File type filter: pdf, docx, pptx," in search_result.output- assert "xlsx, html, markdown, csv, rst," in search_result.output- assert "tex, txt" in search_result.output- assert "File extension filter: pdf, docx, pptx, xlsx," in find_result.output- assert "html, htm, md, markdown, csv, rst, tex, txt" in find_result.output+ assert "File type filter:" in search_result.output+ for token in ("pdf", "image", "docx", "pptx", "xlsx", "html", "markdown", "csv", "rst", "tex", "txt"):+ assert token in search_result.output+ assert "File extension filter:" in find_result.output+ for token in (+ "pdf",+ "png",+ "jpg",+ "jpeg",+ "jp2",+ "webp",+ "gif",+ "bmp",+ "tiff",+ "docx",+ "pptx",+ "xlsx",+ "html",+ "htm",+ "md",+ "markdown",+ "csv",+ "rst",+ "tex",+ "txt",+ ):+ assert token in find_result.outputdef test_print_error_uses_single_rich_render(monkeypatch: Any) -> None:diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex f74b501f..5bf31288 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -775,6 +775,192 @@ def test_ingest_binds_file_sha_before_creating_parse_task(tmp_path: Path, monkeyasyncio.run(_run())+def test_request_parse_explicit_image_ingests_and_queues_parse(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_NoRulesConfig(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )+ source = tmp_path / "scan.png"+ source.write_bytes(b"png-bytes")++ async def _metadata(path: str) -> dict[str, Any]:+ return {+ "page_count": 1,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_image_based": 1,+ }++ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)++ result = await service.request_parse(str(source), tier="flash")+ file_row = await db.fetchone("SELECT path, ext, sha256, status FROM files WHERE path=?", (str(source),))+ doc_row = await db.fetchone("SELECT file_type, page_count, is_image_based FROM docs WHERE sha256=?", (result.sha256,))+ parse_rows = await db.fetchall("SELECT tier, page_range, status FROM parses WHERE sha256=?", (result.sha256,))++ assert result.status == "pending"+ assert result.tier == "flash"+ assert file_row is not None+ assert file_row["ext"] == "png"+ assert file_row["sha256"] == result.sha256+ assert file_row["status"] == "active"+ assert doc_row == {"file_type": "image", "page_count": 1, "is_image_based": 1}+ assert parse_rows == [{"tier": "flash", "page_range": "1", "status": "pending"}]++ asyncio.run(_run())++[email protected]("ext", ["txt", "html", "docx", "pptx", "xlsx"])[email protected]("tier", ["standard", "pro"])+def test_request_parse_rejects_quality_tiers_for_non_pdf_image_inputs(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ext: str,+ tier: Tier,+) -> None:+ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_NoRulesConfig(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )+ source = tmp_path / f"sample.{ext}"+ source.write_text("content", encoding="utf-8")++ async def _metadata(path: str) -> dict[str, Any]:+ return {+ "page_count": 1,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_image_based": 0,+ }++ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)++ with pytest.raises(InvalidRequestError) as exc_info:+ await service.request_parse(str(source), tier=tier)++ assert exc_info.value.code == "tier_unsupported_for_file_type"+ assert exc_info.value.param == "tier"+ assert tier in exc_info.value.message+ assert ext in exc_info.value.message++ asyncio.run(_run())++[email protected]("ext", ["txt", "html", "docx", "pptx", "xlsx"])+def test_request_parse_rejects_remote_for_non_pdf_image_inputs(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ext: str,+) -> None:+ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_NoRulesConfig(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )+ source = tmp_path / f"sample.{ext}"+ source.write_text("content", encoding="utf-8")++ async def _metadata(path: str) -> dict[str, Any]:+ return {+ "page_count": 1,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_image_based": 0,+ }++ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)++ with pytest.raises(InvalidRequestError) as exc_info:+ await service.request_parse(str(source), remote=True)++ assert exc_info.value.code == "remote_unsupported_for_file_type"+ assert exc_info.value.param == "remote"+ assert ext in exc_info.value.message++ asyncio.run(_run())++[email protected]("ext", ["pdf", "png"])+def test_request_parse_rejects_flash_tier_for_remote_quality_inputs(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ext: str,+) -> None:+ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_NoRulesConfig(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )+ source = tmp_path / f"sample.{ext}"+ source.write_bytes(b"%PDF-1.4\n" if ext == "pdf" else b"png-bytes")++ async def _metadata(path: str) -> dict[str, Any]:+ return {+ "page_count": 1,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_image_based": int(ext != "pdf"),+ }++ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)++ with pytest.raises(InvalidRequestError) as exc_info:+ await service.request_parse(str(source), tier="flash", remote=True)++ assert exc_info.value.code == "tier_unsupported_for_remote"+ assert exc_info.value.param == "tier"+ assert "flash" in exc_info.value.message+ assert "remote" in exc_info.value.message++ asyncio.run(_run())++def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path: Path) -> None:sha256 = "e" * 64source = tmp_path / "doc.pdf"@@ -1626,6 +1812,36 @@ def test_watch_event_ignores_office_temp_lock_files(tmp_path: Path) -> None:asyncio.run(_run())+def test_watch_event_ignores_image_files(tmp_path: Path) -> None:+ async def _run() -> None:+ class _ConfigService:+ async def is_path_excluded(self, path: str) -> bool:+ return False++ class _ParseService:+ def __init__(self) -> None:+ self.refreshed: list[str] = []++ async def refresh_file(self, filepath: str, watch_id: int) -> None:+ self.refreshed.append(filepath)++ parse_svc = _ParseService()+ watch_loop = WatchLoop(+ db=SimpleNamespace(),+ config_svc=_ConfigService(),+ parse_svc=parse_svc,+ scan_interval_sec=300,+ )+ image_file = tmp_path / "scan.png"+ image_file.write_bytes(b"png-bytes")++ await watch_loop._handle_event(str(image_file), watch_id=1)++ assert parse_svc.refreshed == []++ asyncio.run(_run())++def test_scan_service_reuses_pending_scan_for_same_kind_and_path(tmp_path: Path) -> None:async def _run() -> None:db = DatabaseManager(str(tmp_path / "doclib.db"))