Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Consolidate CLI runtime and doclib semantics

jinzhenj4fe4e518bdba
diff --git a/docs/next/decisions/0023-cli-runtime-contract.md b/docs/next/decisions/0023-cli-runtime-contract.md
new file mode 100644
index 00000000..86f8b466
--- /dev/null
+++ b/docs/next/decisions/0023-cli-runtime-contract.md
@@ -0,0 +1,418 @@
+# ADR-0023: CLI Runtime 输出、错误与退出码集中契约
+
+状态: Accepted
+日期: 2026-06-30
+相关文档: ../cli.md, ../cli/mineru.md, ../errors.md, 0015-cli-output-json-composition.md
+
+## 背景
+
+MinerU CLI 目前包含顶层命令和多个子命令,例如 `parse`、`read`、`scan`、`watch rescan`、`show scan`、`config`、`cleanup` 等。这些命令都需要处理 stdout / stderr、`--json`、错误码和 exit code,但实现分散在各个 command 模块中。
+
+已经出现过几类不一致:
+
+- `--json` 模式下 stdout 混入人类可读文本,导致 stdout 不是合法 JSON。
+- 部分错误路径直接 `print_error(...)` 后 `typer.Exit(1)`,绕过 JSON error envelope。
+- 服务端结构化错误在 CLI 侧被 fallback 成 `api_error`。
+- 触发并等待的任务最终 `failed` 时仍 exit `0`。
+- 查询型命令和触发型命令都复用同一个输出函数,容易把资源状态和命令执行结果混淆。
+
+这些问题靠 code review 很难长期避免。后续新增命令时,开发者需要同时记住 stdout / stderr 约定、JSON 输出形状、错误 envelope、连接失败映射、任务状态到 exit code 的转换规则,维护成本高。
+
+因此需要把 CLI 输出、错误和退出码决策集中到一个 runtime 层。命令实现只表达业务动作和结果,不直接决定如何输出和退出。
+
+## 决策
+
+引入 CLI runtime 层,集中控制 stdout / stderr、JSON mode、错误 envelope 和 exit code。
+
+目标模块结构:
+
+```text
+mineru/cli/
+ runtime.py # 统一输出、错误、退出码和命令包装
+ contracts.py # CliContext、CliResult、CliTaskResult 等类型
+ output.py # 底层输出原语,仅 runtime 使用
+ commands/*.py # 参数归一化、调用 client、就近定义一次性 renderer
+```
+
+普通命令模块不应直接调用:
+
+- `print(...)`
+- `typer.echo(...)`
+- `print_error(...)`
+- `print_json(...)`
+- `print_success(...)`
+- `emit_result(...)`
+- `raise typer.Exit(...)`
+
+普通命令模块应通过 `run_cli()` 执行业务 action。简单命令的 action 直接返回业务数据 `T`,复杂命令可以返回 `CliResult[T]` 或 `CliTaskResult[T]`。`run_cli()` 统一捕获异常、输出结果并处理 exit code。
+
+### 输出契约
+
+stdout 只承载命令核心结果。
+
+规则:
+
+- `--json` 成功时,stdout 必须只包含一个合法 JSON 对象。
+- `--json` 错误时,stdout 必须只包含 JSON error envelope。
+- 非 JSON 成功时,stdout 输出核心结果文本。
+- notice、progress、warning、verbose 文本始终写 stderr。
+- 非 JSON 错误时,stderr 输出人类可读错误文本。
+- Typer / Click 参数解析错误可以保留框架默认行为和 exit code `2`。
+
+JSON error envelope 继续使用既有形状:
+
+```json
+{
+ "error": {
+ "type": "invalid_request_error",
+ "code": "file_not_found",
+ "message": "...",
+ "param": "path"
+ }
+}
+```
+
+### Exit Code 契约
+
+CLI exit code 使用以下规则:
+
+| 场景 | Exit code |
+|------|-----------|
+| 命令请求成功完成 | `0` |
+| 命令本身失败,或触发并等待的任务最终失败 | `1` |
+| Typer / Click 参数解析错误 | `2` |
+
+资源状态不能直接等同于命令失败。必须区分查询型命令和触发型命令:
+
+- `mineru show scan <failed_scan_id>` 查询成功,应 exit `0`。
+- `mineru scan <path> --wait ...` 创建并等待的 scan 最终 `failed`,应 exit `1`。
+- `mineru watch rescan <target> --wait ...` 创建并等待的 scan 最终 `failed`,应 exit `1`。
+- `mineru parse <path> --no-wait` 返回 `pending` / `parsing` 是成功提交任务,应 exit `0`。
+- `mineru server status --json` 在 server 未运行时返回 `running=false`,这是状态查询,应 exit `0`。
+
+### Runtime API
+
+使用泛型绑定 `data` 和 `render` 的类型。
+
+```python
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass, field
+from typing import Generic, TypeAlias, TypeVar
+
+from rich.console import ConsoleRenderable
+
+T = TypeVar("T")
+RichObject: TypeAlias = ConsoleRenderable
+PlainObject: TypeAlias = str
+RenderableObject: TypeAlias = RichObject | PlainObject
+RenderableOutput: TypeAlias = RenderableObject | Iterable[RenderableObject]
+CliRenderer = Callable[[T], RenderableOutput | None]
+
+
+@dataclass(frozen=True)
+class CliContext:
+ json_mode: bool
+ verbose: bool = False
+
+
+@dataclass(frozen=True)
+class CliResult(Generic[T]):
+ data: T | None
+ render: CliRenderer[T] | None = None
+ exit_code: int = 0
+ warnings: list[str] = field(default_factory=list)
+ notices: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class CliTaskResult(CliResult[T]):
+ status: str | None = None
+ fail_statuses: frozenset[str] = frozenset({"failed"})
+ fail_if_final_failed: bool = False
+```
+
+`data` 允许为 `None`,便于迁移没有结构化成功载荷的命令。runtime 规定:当 `data is None` 时不得调用 `render`。
+
+公开给普通命令使用的构造函数:
+
+```python
+def cli_ok(
+ data: T | None = None,
+ *,
+ render: CliRenderer[T] | None = None,
+ exit_code: int = 0,
+ warnings: list[str] | None = None,
+ notices: list[str] | None = None,
+) -> CliResult[T]:
+ ...
+
+
+def cli_task(
+ data: T,
+ *,
+ status: str | None,
+ render: CliRenderer[T] | None = None,
+ fail_if_final_failed: bool,
+ fail_statuses: frozenset[str] = frozenset({"failed"}),
+ warnings: list[str] | None = None,
+ notices: list[str] | None = None,
+) -> CliTaskResult[T]:
+ ...
+```
+
+runtime 内部或顶层包装使用:
+
+```python
+def run_cli(
+ ctx: CliContext,
+ action: Callable[[], T | CliResult[T]],
+ *,
+ render: CliRenderer[T] | None = None,
+ warnings: Callable[[T], list[str]] | None = None,
+ notices: Callable[[T], list[str]] | None = None,
+ exit_code: int | Callable[[T], int] = 0,
+) -> None:
+ ...
+
+
+def emit_result(ctx: CliContext, result: CliResult[T]) -> None:
+ ...
+
+
+def emit_error(ctx: CliContext, exc: Exception) -> NoReturn:
+ ...
+```
+
+`emit_error()` 不作为普通命令的推荐公共 API。普通命令应通过抛出 `MineruError`、`InvalidRequestError`、client 异常或其它异常,让 `run_cli()` 统一捕获。`emit_error()` 只用于 runtime 内部、兼容旧代码和少量无法立即迁移的特殊入口。
+
+不提供 `cli_error()`。错误路径统一使用异常,避免命令作者在 `return error` 和 `raise error` 之间做选择。
+
+`server_not_running` 不通过 fallback 文案推断。Doclib client 应抛出 `ServerNotRunningError`,runtime 也可以识别明确的连接异常,例如 `httpx.ConnectError` / `httpx.ConnectTimeout`。
+
+### 命令写法
+
+迁移后的普通命令应接近以下结构:
+
+```python
+def show_file_cmd(path: str, *, json_mode: bool) -> None:
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(
+ ctx,
+ lambda: DoclibClient(timeout=30).get_file_by_path(normalize_cli_path(path)),
+ render=_render_file_info,
+ )
+
+
+def _render_file_info(data: FileInfoResponse) -> str:
+ ...
+```
+
+简单命令不应为了包装 `cli_ok()` 额外定义 `_show_file() -> CliResult[FileInfoResponse]` 这类样板函数。只有当命令逻辑足够复杂、需要独立测试,或需要返回 `CliTaskResult` 时,才保留私有业务 helper。
+
+触发并等待任务的命令应显式声明任务策略:
+
+```python
+def _scan(path: str, *, wait: int, no_wait: bool) -> CliTaskResult[ScanInfo]:
+ scan_info = client.create_scan(...)
+ if not no_wait and wait > 0:
+ scan_info = wait_for_scan(...)
+ return cli_task(
+ scan_info,
+ status=scan_info.status,
+ render=render_scan,
+ fail_if_final_failed=not no_wait,
+ )
+```
+
+查询型命令即使展示 failed 状态,也使用 `cli_ok()`:
+
+```python
+run_cli(ctx, lambda: client.get_scan(scan_id), render=_render_scan)
+```
+
+### Renderer 规则
+
+renderer 只把结构化数据转换为可渲染对象,不执行 IO,不抛 `typer.Exit`。可渲染对象包括字符串、Rich `ConsoleRenderable`、这些对象的 iterable 或 generator。renderer 返回 `None` 表示“非 JSON 模式下不输出核心结果”,不是表示 renderer 自己已经完成输出。
+
+一次性 renderer 应就近放在对应 command 模块中:
+
+```python
+def _render_scan(scan: ScanInfo) -> Table | str:
+ ...
+```
+
+跨命令复用的子格式化函数可以在后续需要时集中到单独模块;当前优先把一次性 renderer 放在调用处附近。
+
+runtime 决定渲染结果写 stdout 还是 stderr;renderer 不关心 JSON mode。
+
+## 替代方案
+
+### 方案 A:继续依赖约定和 code review
+
+不采用。
+
+已有问题说明,分散约定很容易被遗漏。新增命令时需要记住太多细节,长期会继续产生不一致。
+
+### 方案 B:只修当前发现的 bug
+
+不采用作为长期方案。
+
+逐点修复可以缓解当前问题,但无法降低未来新增命令的错误概率。CLI 输出和退出语义仍分散在各命令模块中。
+
+### 方案 C:一次性重写所有 CLI 命令
+
+不采用。
+
+风险过高,容易误改查询型命令、触发型命令和 server lifecycle 命令之间的语义差异。迁移应分阶段进行,保证每一步都能独立验证。
+
+### 方案 D:把 `emit_error()` 作为普通命令公共 API
+
+不采用。
+
+普通命令如果既可以 `return` 结果、又可以直接 `emit_error()`,业务逻辑和输出副作用仍会混在一起。错误路径应优先通过异常表达,由 `run_cli()` 统一捕获。
+
+## 影响
+
+### 对实现
+
+- 新增 `contracts.py` 和 `runtime.py`。
+- 现有 `output.py` 保留为底层输出原语,普通命令不直接调用。
+- 一次性人类文本渲染保留在对应 command 模块中,便于就近阅读。
+- 顶层单命令由 `main.py` 直接注册对应 command 模块函数,避免 `main.py wrapper -> *_cmd` 的重复函数层。
+
+### 对命令开发
+
+新增或修改普通命令时,开发者只需要:
+
+1. 归一化 CLI 参数。
+2. 调用 `DoclibClient` 或本地服务。
+3. 调用 `run_cli()` 并提供业务 action 与 renderer。
+4. 本地语义错误抛 `MineruError` / `InvalidRequestError`。
+
+开发者不应手写 JSON、直接 print、直接 `typer.Exit`。
+
+### 对兼容性
+
+- 成功 JSON 的顶层 shape 不应因为 runtime 迁移改变。
+- 既有错误 JSON envelope 形状保持不变。
+- 非 JSON 文本可以在不改变语义的前提下微调,但不应破坏文档化命令输出。
+- 部分之前错误 exit `0` 的触发型命令会收紧为 exit `1`,这是有意修复。
+
+### 特殊例外
+
+当前仅允许以下特殊路径保留输出副作用:
+
+- `mineru/cli/runtime.py`
+- `mineru/cli/output.py`
+- `mineru/cli/telemetry.py` 的首次交互式 consent prompt;它必须跳过 `--json`、help、CI 和 agent caller 场景。
+
+`mineru/cli/commands/parse.py` 仍有少量内部 `emit_result()`,这是剩余架构债,不属于可扩散模式。例外必须进入 contract test 或专项测试,不能隐式扩散。
+
+## 执行计划
+
+### Phase 1:建立 runtime 与契约测试
+
+状态:已完成。
+
+1. 新增 `mineru/cli/contracts.py`,定义 `CliContext`、`CliResult[T]`、`CliTaskResult[T]`。
+2. 新增 `mineru/cli/runtime.py`,实现 `cli_ok()`、`cli_task()`、`run_cli()`、`emit_result()`、`emit_error()`。
+3. 新增 `tests/unittest/test_cli_runtime_contract.py`,覆盖:
+ - JSON 成功 stdout 为单个 JSON。
+ - JSON 错误 stdout 为 error envelope。
+ - 非 JSON 错误写 stderr。
+ - notices / warnings 写 stderr。
+ - `CliTaskResult` 在 `fail_if_final_failed=True` 且状态为 `failed` 时输出结果后 exit `1`。
+ - `fail_if_final_failed=False` 时 failed 状态 exit `0`。
+ - renderer 支持字符串、Rich 对象、iterable、generator 和 `None`。
+
+### Phase 2:迁移已知高风险命令
+
+状态:已完成。
+
+已完成:
+
+- `scan --wait` / `watch rescan --wait` 最终 failed 时 exit `1`。
+- `show scan <failed>` 保持 exit `0`。
+- `parse` / `read` 内容输出边缘错误已改为 JSON error envelope。
+- config remove 和 invalidate 的 tuple 风格错误字符串已收敛为结构化错误输出。
+- doclib server 未运行不再通过 fallback 文案推断,而是通过 `ServerNotRunningError` / 连接异常识别。
+
+### Phase 3:收紧静态约束
+
+状态:已完成。
+
+新增 AST contract test,扫描 `mineru/cli/commands/**/*.py`:
+
+- 禁止普通命令直接调用 `print(...)`。
+- 禁止普通命令直接调用 `typer.echo(...)`。
+- 禁止普通命令直接调用 `print_error(...)`、`print_json(...)`、`print_success(...)`。
+- 禁止普通命令直接 `raise typer.Exit(...)`。
+
+allowlist 仅包含本 ADR 的特殊例外。迁移期可以临时 allowlist 尚未迁移的命令,但每次新增 allowlist 都需要测试说明。
+
+已增加的约束:
+
+- 已迁移命令不得直接输出。
+- 已迁移命令不得新增 `_xxx() -> CliResult[...]` 样板 helper。
+- renderer 函数不得使用 `Any` 注解。
+- command 模块不允许直接调用 `emit_result()`;`parse.py` 的内部调用作为后续收敛项单独处理。
+
+### Phase 4:迁移剩余命令并清理兼容层
+
+状态:已完成。
+
+已迁移:
+
+- `search`
+- `find`
+- `list parses/scans/files/docs`
+- `show parse/scan/file/doc`
+- `cleanup deleted-files/orphan-docs/temp`
+- `forget`
+- `telemetry status/enable/disable/flush`
+- `config show/get/set/unset`
+- `config exclude-rules add/list/remove`
+- `config parsing-rules add/list/remove`
+- `watch add/list/remove`
+- `scan`
+- `watch rescan`
+- `read`
+- `invalidate`
+- `server start/stop/status/shutdown`
+- `telemetry preview`
+- `version`
+
+后续清理:
+
+- 收敛 `parse.py` 内部多次 `emit_result()` 为更标准的 runtime 结果返回。
+- 若跨命令 renderer 复用明显增加,再引入共享 renderer/formatter 模块。
+
+## 验证矩阵
+
+迁移期间和迁移完成后,测试必须覆盖以下矩阵:
+
+| 命令类型 | 示例 | 成功 exit | 业务 failed 状态 | JSON 错误 stdout |
+|----------|------|-----------|------------------|------------------|
+| 查询 / 展示 | `show scan` | `0` | `0` | envelope |
+| 列表 / 搜索 | `list files`, `search` | `0` | 不适用 | envelope |
+| 触发并等待 | `scan --wait`, `watch rescan --wait` | `0` | `1` | envelope |
+| 只提交任务 | `parse --no-wait` | `0` | 不适用 | envelope |
+| 内容输出 | `parse`, `read` | `0` | `1` | envelope |
+| 配置变更 | `config set`, `config * remove` | `0` | `1` | envelope 若支持 `--json` |
+| 状态查询 | `server status` | `0` | `0` | JSON 状态 |
+
+Golden cases:
+
+- `scan --wait --json` 返回 failed scan JSON 后 exit `1`。
+- `show scan <failed> --json` 返回 scan JSON 后 exit `0`。
+- `parse --json` 内容缺失返回 JSON error 后 exit `1`。
+- `read --format image --output out.png --json` asset 缺失返回 JSON error 后 exit `1`。
+- 所有进入命令实现后的 JSON 错误 stdout 都可 `json.loads`。
+- verbose / progress / warning 不进入 JSON stdout。
+- 连接失败统一映射为 `server_not_running`。
+
+## 后续动作
+
+1. 收敛 `parse.py` 内部直接 `emit_result()`。
+2. 继续用命令级 golden tests 覆盖新增命令的 JSON / stderr / exit code 行为。
+3. 更新 CLI 开发文档,说明新增命令必须使用 runtime。
diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.md
index 85cd97a0..99c3e01b 100644
--- a/docs/next/decisions/README.md
+++ b/docs/next/decisions/README.md
@@ -50,6 +50,7 @@
| [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 语义 |
+| [ADR-0023](0023-cli-runtime-contract.md) | Accepted | CLI Runtime 输出、错误与退出码集中契约 |
## 模板
diff --git a/mineru/cli/commands/cleanup.py b/mineru/cli/commands/cleanup.py
index 87ad7e1a..8b58b4c9 100644
--- a/mineru/cli/commands/cleanup.py
+++ b/mineru/cli/commands/cleanup.py
@@ -5,9 +5,16 @@ from __future__ import annotations
import typer
from ...doclib.client import DoclibClient
-from ...doclib.types import CleanupDeletedRequest, CleanupOrphansRequest, CleanupTempRequest
-from ..json_errors import exit_with_error
-from ..output import print_info, print_json, print_success
+from ...doclib.types import (
+ CleanupDeletedRequest,
+ CleanupDeletedResponse,
+ CleanupOrphansRequest,
+ CleanupOrphansResponse,
+ CleanupTempRequest,
+ CleanupTempResponse,
+)
+from ..contracts import CliContext
+from ..runtime import run_cli
app = typer.Typer(
name="cleanup",
@@ -22,24 +29,11 @@ def cleanup_deleted_files(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove all file rows already marked as deleted."""
- try:
- client = _client()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
- try:
- data = client.cleanup_deleted_files(CleanupDeletedRequest(dry_run=dry_run))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
-
- count = data.deleted_files
- if dry_run:
- print_info(f"Would remove {count} deleted file record(s). Use --no-dry-run to proceed.")
- else:
- print_success(f"Removed {count} deleted file record(s).")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().cleanup_deleted_files(CleanupDeletedRequest(dry_run=dry_run)),
+ render=_render_cleanup_deleted,
+ )
@app.command("orphan-docs")
@@ -48,24 +42,11 @@ def cleanup_orphan_docs(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove docs that are no longer referenced by any file row."""
- try:
- client = _client()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
- try:
- data = client.cleanup_orphan_docs(CleanupOrphansRequest(dry_run=dry_run))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
-
- count = data.orphan_docs
- if dry_run:
- print_info(f"Would remove {count} orphan doc(s). Use --no-dry-run to proceed.")
- else:
- print_success(f"Removed {count} orphan doc(s).")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().cleanup_orphan_docs(CleanupOrphansRequest(dry_run=dry_run)),
+ render=_render_cleanup_orphans,
+ )
@app.command("temp")
@@ -74,21 +55,28 @@ def cleanup_temp_files(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove old process temp files."""
- try:
- client = _client()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
- try:
- data = client.cleanup_temp_files(CleanupTempRequest(older_than_days=older_than))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
-
- print_success(f"Removed {data.temp_files_removed} temp file(s).")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().cleanup_temp_files(CleanupTempRequest(older_than_days=older_than)),
+ render=_render_cleanup_temp,
+ )
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
+
+
+def _render_cleanup_deleted(data: CleanupDeletedResponse) -> str:
+ if data.dry_run:
+ return f"Would remove {data.deleted_files} deleted file record(s). Use --no-dry-run to proceed."
+ return f"Removed {data.deleted_files} deleted file record(s)."
+
+
+def _render_cleanup_orphans(data: CleanupOrphansResponse) -> str:
+ if data.dry_run:
+ return f"Would remove {data.orphan_docs} orphan doc(s). Use --no-dry-run to proceed."
+ return f"Removed {data.orphan_docs} orphan doc(s)."
+
+
+def _render_cleanup_temp(data: CleanupTempResponse) -> str:
+ return f"Removed {data.temp_files_removed} temp file(s)."
diff --git a/mineru/cli/commands/config.py b/mineru/cli/commands/config.py
index c26fb46f..16fee06c 100644
--- a/mineru/cli/commands/config.py
+++ b/mineru/cli/commands/config.py
@@ -3,12 +3,27 @@
from __future__ import annotations
import typer
+from rich.table import Table
from ...doclib.client import DoclibClient
-from ...doclib.types import ConfigResponse, ConfigSetRequest, ExcludeRuleRequest, ParsingRuleRequest
+from ...doclib.types import (
+ ConfigResponse,
+ ConfigSetRequest,
+ ConfigSetResponse,
+ ConfigUnsetResponse,
+ ConfigValueResponse,
+ ExcludeRuleInfo,
+ ExcludeRuleListResponse,
+ ExcludeRuleRequest,
+ ParsingRuleInfo,
+ ParsingRuleListResponse,
+ ParsingRuleRequest,
+ RemoveExcludeRuleResponse,
+ RemoveParsingRuleResponse,
+)
from ...types import Tier
-from ..json_errors import exit_with_error
-from ..output import print_error, print_info, print_json, print_success
+from ..contracts import CliContext
+from ..runtime import run_cli
app = typer.Typer(help="Configuration management", no_args_is_help=True)
@@ -22,15 +37,8 @@ app.add_typer(parsing_rules_app, name="parsing-rules")
@app.command("show")
def config_show(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""Show effective configuration values."""
- try:
- data = _client().get_config()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- _print_config(data)
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().get_config(), render=_render_config)
@app.command("get")
@@ -39,15 +47,8 @@ def config_get(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Show one effective configuration value."""
- try:
- data = _client().get_config_key(key)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- print(f"{data.key} = {data.value} [{data.source}]")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().get_config_key(key), render=_render_config_value)
@app.command("set")
@@ -56,24 +57,15 @@ def config_set(
value: str = typer.Argument(..., help="Configuration value"),
) -> None:
"""Set a configuration override."""
- try:
- data = _client().set_config(key, ConfigSetRequest(value=value))
- except Exception as exc:
- exit_with_error(exc, json_mode=False)
-
- print_success(f"{data.key} = {data.value} [{data.source}]")
+ ctx = CliContext(json_mode=False)
+ run_cli(ctx, lambda: _client().set_config(key, ConfigSetRequest(value=value)), render=_render_config_set)
@app.command("unset")
def config_unset(key: str = typer.Argument(..., help="Configuration key")) -> None:
"""Remove a configuration override and fall back to the default."""
- try:
- data = _client().unset_config(key)
- except Exception as exc:
- exit_with_error(exc, json_mode=False)
-
- action = "removed" if data.removed else "unchanged"
- print_success(f"{data.key} = {data.value} [{data.source}] ({action})")
+ ctx = CliContext(json_mode=False)
+ run_cli(ctx, lambda: _client().unset_config(key), render=_render_config_unset)
@exclude_rules_app.command("add")
@@ -83,45 +75,26 @@ def exclude_rules_add(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Add an exclusion rule."""
- try:
- data = _client().add_exclude_rule(ExcludeRuleRequest(pattern=pattern, priority=priority))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- print_success(f"Exclude rule added: id={data.id}")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(
+ ctx,
+ lambda: _client().add_exclude_rule(ExcludeRuleRequest(pattern=pattern, priority=priority)),
+ render=_render_exclude_rule_added,
+ )
@exclude_rules_app.command("list")
def exclude_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""List exclusion rules."""
- try:
- data = _client().list_exclude_rules()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- if not data.rules:
- print_info("No exclude rules configured.")
- return
- for rule in data.rules:
- print(f" [{rule.id}] {rule.pattern} priority={rule.priority}")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().list_exclude_rules(), render=_render_exclude_rules)
@exclude_rules_app.command("remove")
def exclude_rules_remove(rule_id: int = typer.Argument(..., help="Rule id to remove")) -> None:
"""Remove an exclusion rule."""
- try:
- _client().remove_exclude_rule(rule_id)
- except Exception as exc:
- print_error(str(exc))
- raise typer.Exit(1) from None
-
- print_success(f"Exclude rule {rule_id} removed.")
+ ctx = CliContext(json_mode=False)
+ run_cli(ctx, lambda: _client().remove_exclude_rule(rule_id), render=_render_exclude_rule_removed)
@parsing_rules_app.command("add")
@@ -134,64 +107,106 @@ def parsing_rules_add(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Add a parsing rule."""
- try:
- data = _client().add_parsing_rule(
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(
+ ctx,
+ lambda: _client().add_parsing_rule(
ParsingRuleRequest(pattern=pattern, tier=tier, page_range=pages, remote=remote, name=name)
- )
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- print_success(f"Parsing rule added: id={data.id}")
+ ),
+ render=_render_parsing_rule_added,
+ )
@parsing_rules_app.command("list")
def parsing_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""List parsing rules."""
- try:
- data = _client().list_parsing_rules()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(data)
- return
- if not data.rules:
- print_info("No parsing rules configured.")
- return
- for rule in data.rules:
- flags = []
- if rule.tier:
- flags.append(f"tier={rule.tier}")
- if rule.page_range:
- flags.append(f"pages={rule.page_range}")
- if rule.remote:
- flags.append("remote")
- suffix = f" {', '.join(flags)}" if flags else ""
- print(f" [{rule.id}] {rule.pattern}{suffix}")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().list_parsing_rules(), render=_render_parsing_rules)
@parsing_rules_app.command("remove")
def parsing_rules_remove(rule_id: int = typer.Argument(..., help="Rule id to remove")) -> None:
"""Remove a parsing rule."""
- try:
- _client().remove_parsing_rule(rule_id)
- except Exception as exc:
- print_error(str(exc))
- raise typer.Exit(1) from None
-
- print_success(f"Parsing rule {rule_id} removed.")
+ ctx = CliContext(json_mode=False)
+ run_cli(ctx, lambda: _client().remove_parsing_rule(rule_id), render=_render_parsing_rule_removed)
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
-def _print_config(data: ConfigResponse) -> None:
- print("\n[Config]")
+def _render_config(data: ConfigResponse) -> Table:
+ table = Table(title="Config")
+ table.add_column("Key", style="cyan")
+ table.add_column("Value", style="green")
+ table.add_column("Source")
for key in sorted(data.config):
value = data.config[key]
source = data.sources.get(key, "default")
- print(f" {key} = {value} [{source}]")
+ table.add_row(key, value, source)
+ return table
+
+
+def _render_config_value(data: ConfigValueResponse) -> str:
+ return f"{data.key} = {data.value} [{data.source}]"
+
+
+def _render_config_set(data: ConfigSetResponse) -> str:
+ return f"{data.key} = {data.value} [{data.source}]"
+
+
+def _render_config_unset(data: ConfigUnsetResponse) -> str:
+ action = "removed" if data.removed else "unchanged"
+ return f"{data.key} = {data.value} [{data.source}] ({action})"
+
+
+def _render_exclude_rule_added(data: ExcludeRuleInfo) -> str:
+ return f"Exclude rule added: id={data.id}"
+
+
+def _render_exclude_rules(data: ExcludeRuleListResponse) -> Table | str:
+ if not data.rules:
+ return "No exclude rules configured."
+ table = Table(title="Exclude Rules")
+ table.add_column("ID", justify="right")
+ table.add_column("Pattern", style="cyan")
+ table.add_column("Priority", justify="right")
+ for rule in data.rules:
+ table.add_row(str(rule.id), rule.pattern, str(rule.priority))
+ return table
+
+
+def _render_exclude_rule_removed(data: RemoveExcludeRuleResponse) -> str:
+ action = "removed" if data.removed else "unchanged"
+ return f"Exclude rule {data.rule_id} {action}."
+
+
+def _render_parsing_rule_added(data: ParsingRuleInfo) -> str:
+ return f"Parsing rule added: id={data.id}"
+
+
+def _render_parsing_rules(data: ParsingRuleListResponse) -> Table | str:
+ if not data.rules:
+ return "No parsing rules configured."
+ table = Table(title="Parsing Rules")
+ table.add_column("ID", justify="right")
+ table.add_column("Pattern", style="cyan")
+ table.add_column("Tier")
+ table.add_column("Pages")
+ table.add_column("Remote")
+ table.add_column("Name")
+ for rule in data.rules:
+ table.add_row(
+ str(rule.id),
+ rule.pattern,
+ rule.tier or "-",
+ rule.page_range or "-",
+ "yes" if rule.remote else "no",
+ rule.name or "-",
+ )
+ return table
+
+
+def _render_parsing_rule_removed(data: RemoveParsingRuleResponse) -> str:
+ action = "removed" if data.removed else "unchanged"
+ return f"Parsing rule {data.rule_id} {action}."
diff --git a/mineru/cli/commands/forget.py b/mineru/cli/commands/forget.py
index 8601ea36..39c7b47d 100644
--- a/mineru/cli/commands/forget.py
+++ b/mineru/cli/commands/forget.py
@@ -2,42 +2,33 @@
from __future__ import annotations
+import typer
+
from ...doclib.client import DoclibClient
-from ...doclib.types import ForgetPathRequest
-from ..json_errors import exit_with_error
-from ..output import print_info, print_json, print_success
+from ...doclib.types import ForgetPathRequest, ForgetPathResponse
+from ..contracts import CliContext
from ..path_utils import normalize_cli_path
+from ..runtime import run_cli
def forget_cmd(
- path: str,
- *,
- dry_run: bool = True,
- json_mode: bool = False,
+ path: str = typer.Argument(..., help="File or directory path to forget from doclib"),
+ dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help="Preview only"),
+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
- try:
- client = DoclibClient(timeout=30)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
-
- file_path = normalize_cli_path(path)
- try:
- result = client.forget_path(ForgetPathRequest(path=file_path, dry_run=dry_run))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
-
- for warning in result.warnings:
- print_info(warning)
-
- if dry_run:
- print_info(
- f"Would forget {result.forgotten_files} file record(s) "
- f"(matched_as={result.matched_as}). Use --no-dry-run to proceed."
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: DoclibClient(timeout=30).forget_path(
+ ForgetPathRequest(path=normalize_cli_path(path), dry_run=dry_run),
+ ),
+ render=_render_forget_result,
+ warnings=lambda result: result.warnings,
+ )
+
+
+def _render_forget_result(data: ForgetPathResponse) -> str:
+ if data.dry_run:
+ return (
+ f"Would forget {data.forgotten_files} file record(s) (matched_as={data.matched_as}). Use --no-dry-run to proceed."
)
- return
-
- print_success(f"Forgot {result.forgotten_files} file record(s) (matched_as={result.matched_as}).")
+ return f"Forgot {data.forgotten_files} file record(s) (matched_as={data.matched_as})."
diff --git a/mineru/cli/commands/invalidate.py b/mineru/cli/commands/invalidate.py
index 4ed819df..d573d869 100644
--- a/mineru/cli/commands/invalidate.py
+++ b/mineru/cli/commands/invalidate.py
@@ -7,10 +7,12 @@ from pathlib import Path
import typer
from ...doclib.client import DoclibClient
-from ...doclib.types import InvalidateRequest
+from ...doclib.types import InvalidateRequest, InvalidateResponse
+from ...errors import MineruError
from ...types import Tier
-from ..output import print_error, print_success
from ..path_utils import normalize_cli_path
+from ..contracts import CliContext
+from ..runtime import run_cli
def invalidate_cmd(
@@ -18,28 +20,22 @@ def invalidate_cmd(
tier: Tier | None = typer.Option(None, "--tier", help="Parse tier to invalidate (omit = all tiers)"),
) -> None:
"""Mark done parse results as superseded."""
+ ctx = CliContext(json_mode=False)
+ run_cli(ctx, lambda: _invalidate(path, tier=tier), render=_render_invalidate)
+
+
+def _invalidate(path: str, *, tier: Tier | None) -> InvalidateResponse:
file_path = normalize_cli_path(path)
if not Path(file_path).exists():
- print_error(f"File not found: {file_path}")
- raise typer.Exit(1)
-
- try:
- client = DoclibClient(timeout=10)
- except Exception:
- print_error("Cannot connect to mineru server. Run 'mineru server start' first.")
- raise typer.Exit(1) from None
-
- try:
- result = client.invalidate(InvalidateRequest(path=file_path, tier=tier))
- except Exception as exc:
- print_error(str(exc))
- raise typer.Exit(1) from None
-
- count = result.invalidated_count
- sha256 = result.sha256[:12]
- tier_label = f" (tier={tier})" if tier else ""
+ raise MineruError("file_not_found", f"File not found: {file_path}", "path")
+ return DoclibClient(timeout=10).invalidate(InvalidateRequest(path=file_path, tier=tier))
+
+
+def _render_invalidate(data: InvalidateResponse) -> str:
+ count = data.invalidated_count
+ doc_id = data.short_id
+ tier_label = f" (tier={data.tier})" if data.tier else ""
if count:
- print_success(f"Invalidated {count} batch(es) for {sha256}...{tier_label}. Use 'mineru parse' to re-parse.")
- else:
- print(f"No done batches found for {sha256}...{tier_label}.")
+ return f"Invalidated {count} batch(es) for {doc_id}{tier_label}. Use 'mineru parse' to re-parse."
+ return f"No done batches found for {doc_id}{tier_label}."
diff --git a/mineru/cli/commands/list_resources.py b/mineru/cli/commands/list_resources.py
index eff2712e..241d131e 100644
--- a/mineru/cli/commands/list_resources.py
+++ b/mineru/cli/commands/list_resources.py
@@ -3,12 +3,22 @@
from __future__ import annotations
import typer
+from rich.table import Table
from ...doclib.client import DoclibClient
-from ...doclib.types import FileStatus, ParseStatus, ScanKind, ScanStatus
+from ...doclib.types import (
+ FileStatus,
+ ListDocsResponse,
+ ListFilesResponse,
+ ListParsesResponse,
+ ParseStatus,
+ ScanKind,
+ ScanListResponse,
+ ScanStatus,
+)
from ...types import Tier
-from ..json_errors import exit_with_error
-from ..output import print_error, print_info, print_json
+from ..contracts import CliContext
+from ..runtime import run_cli
app = typer.Typer(help="List doclib resources", no_args_is_help=True)
@@ -22,20 +32,11 @@ def list_parses(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""List parse tasks."""
- try:
- result = _client().list_parses(status=status, tier=tier, limit=limit, offset=offset)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- if not result.parses:
- print_info("No parses found.")
- return
- print(f"Parses ({result.total} total)")
- for item in result.parses:
- print(f" [{item.id}] {item.status} {item.tier} pages={item.page_range} sha256={item.sha256[:12]}")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().list_parses(status=status, tier=tier, limit=limit, offset=offset),
+ render=_render_list_parses,
+ )
@app.command("scans")
@@ -48,23 +49,11 @@ def list_scans(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""List scan tasks."""
- try:
- result = _client().list_scans(status=status, kind=kind, watch_id=watch_id, limit=limit, offset=offset)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- if not result.scans:
- print_info("No scans found.")
- return
- print(f"Scans ({result.total} total)")
- for item in result.scans:
- print(
- f" [{item.id}] {item.status} {item.kind} {item.path} "
- f"seen={item.files_seen} refreshed={item.files_refreshed} errors={item.files_error}"
- )
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().list_scans(status=status, kind=kind, watch_id=watch_id, limit=limit, offset=offset),
+ render=_render_list_scans,
+ )
@app.command("files")
@@ -77,21 +66,11 @@ def list_files(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""List file path records."""
- try:
- result = _client().list_files(status=status, ext=ext, watch_id=watch_id, limit=limit, offset=offset)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- if not result.files:
- print_info("No files found.")
- return
- print(f"Files ({result.total} total)")
- for item in result.files:
- sha = item.sha256[:12] if item.sha256 else "-"
- print(f" [{item.status}] {item.path} ext={item.ext} sha256={sha}")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().list_files(status=status, ext=ext, watch_id=watch_id, limit=limit, offset=offset),
+ render=_render_list_files,
+ )
@app.command("docs")
@@ -102,22 +81,77 @@ def list_docs(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""List active docs."""
- try:
- result = _client().list_docs(file_type=file_type, limit=limit, offset=offset)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- if not result.docs:
- print_info("No docs found.")
- return
- print(f"Docs ({result.total} total)")
- for item in result.docs:
- title = item.title or "-"
- print(f" {item.sha256[:12]} type={item.file_type or '-'} pages={item.page_count or '-'} title={title}")
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().list_docs(file_type=file_type, limit=limit, offset=offset),
+ render=_render_list_docs,
+ )
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
+
+
+def _render_list_parses(data: ListParsesResponse) -> Table | str:
+ if not data.parses:
+ return "No parses found."
+ table = Table(title=f"Parses ({data.total} total)")
+ table.add_column("ID", justify="right")
+ table.add_column("Status", style="green")
+ table.add_column("Tier", style="cyan")
+ table.add_column("Pages")
+ table.add_column("Doc ID")
+ for item in data.parses:
+ table.add_row(str(item.id), item.status, item.tier, item.page_range, item.short_id)
+ return table
+
+
+def _render_list_scans(data: ScanListResponse) -> Table | str:
+ if not data.scans:
+ return "No scans found."
+ table = Table(title=f"Scans ({data.total} total)")
+ table.add_column("ID", justify="right")
+ table.add_column("Status", style="green")
+ table.add_column("Kind", style="cyan")
+ table.add_column("Path")
+ table.add_column("Seen", justify="right")
+ table.add_column("Refreshed", justify="right")
+ table.add_column("Errors", justify="right")
+ for item in data.scans:
+ table.add_row(
+ str(item.id),
+ item.status,
+ item.kind,
+ item.path,
+ str(item.files_seen),
+ str(item.files_refreshed),
+ str(item.files_error),
+ )
+ return table
+
+
+def _render_list_files(data: ListFilesResponse) -> Table | str:
+ if not data.files:
+ return "No files found."
+ table = Table(title=f"Files ({data.total} total)")
+ table.add_column("Status", style="green")
+ table.add_column("Path")
+ table.add_column("Ext", style="cyan")
+ table.add_column("Doc ID")
+ for item in data.files:
+ table.add_row(item.status, item.path, item.ext, item.short_id or "-")
+ return table
+
+
+def _render_list_docs(data: ListDocsResponse) -> Table | str:
+ if not data.docs:
+ return "No docs found."
+ table = Table(title=f"Docs ({data.total} total)")
+ table.add_column("Doc ID")
+ table.add_column("Type", style="cyan")
+ table.add_column("Pages", justify="right")
+ table.add_column("Title")
+ for item in data.docs:
+ title = item.title or "-"
+ table.add_row(item.short_id, item.file_type or "-", str(item.page_count or "-"), title)
+ return table
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index e0e9ed8b..1326e00b 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -3,16 +3,14 @@
from __future__ import annotations
import shlex
-import shutil
import time
+from dataclasses import dataclass
from pathlib import Path
-from typing import Any
-from typing import Literal
+from typing import Any, Literal
import click
import typer
-from ...errors import MineruError
from ...doclib.client import DoclibClient
from ...doclib.types import (
ContentNextRequest,
@@ -23,10 +21,21 @@ from ...doclib.types import (
TelemetryObservation,
TelemetryObservationsRequest,
)
+from ...errors import MineruError
from ...types import Tier
-from ..json_errors import exit_with_error
-from ..output import format_parse_result, print_error, print_json, print_notice, print_success
+from ..contracts import CliContext, CliResult
from ..path_utils import normalize_cli_path
+from ..runtime import cli_ok, emit_result, run_cli
+
+
+@dataclass(frozen=True)
+class ParseTextOutput:
+ text: str
+
+
+@dataclass(frozen=True)
+class ParseSummaryOutput:
+ text: str
def _normalize_output_path(output: str | None) -> str | None:
@@ -47,6 +56,10 @@ def _output_info(path: str) -> dict[str, str]:
return {"status": "written", "path": path}
+def _emit_notice(message: str, *, json_mode: bool) -> None:
+ emit_result(CliContext(json_mode=json_mode), cli_ok(notices=[message]))
+
+
def _validate_page_range_input(page_range: str | None) -> None:
if page_range is None or page_range.strip() == "" or page_range.strip() == "all":
return
@@ -91,34 +104,64 @@ def parse_cmd(
verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),
) -> None:
"""Parse a document file."""
+ ctx = CliContext(json_mode=json_mode, verbose=verbose)
+ run_cli(
+ ctx,
+ lambda: _parse(
+ path,
+ tier=tier,
+ pages=pages,
+ after=after,
+ limit=limit,
+ format=format,
+ force=force,
+ remote=remote,
+ wait=wait,
+ no_wait=no_wait,
+ output=output,
+ no_marker=no_marker,
+ json_mode=json_mode,
+ verbose=verbose,
+ ),
+ )
+
+
+def _parse(
+ path: str,
+ *,
+ tier: Tier | None,
+ pages: str | None,
+ after: str | None,
+ limit: int,
+ format: Literal["markdown"],
+ force: bool,
+ remote: bool,
+ wait: int,
+ no_wait: bool,
+ output: str | None,
+ no_marker: bool,
+ json_mode: bool,
+ verbose: bool,
+) -> None:
file_path = normalize_cli_path(path)
if not Path(file_path).exists():
- exit_with_error(MineruError("file_not_found", f"File not found: {file_path}", "path"), json_mode=json_mode)
+ raise MineruError("file_not_found", f"File not found: {file_path}", "path")
- try:
- _validate_page_range_input(pages)
- except MineruError as exc:
- exit_with_error(exc, json_mode=json_mode)
+ _validate_page_range_input(pages)
- try:
- client = DoclibClient(timeout=wait + 30)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
+ client = DoclibClient(timeout=wait + 30)
# send parse request
- try:
- result = client.ensure_parse(
- ParseRequest(
- path=file_path,
- tier=tier,
- page_range=pages,
- force=force,
- remote=remote,
- )
+ result = client.ensure_parse(
+ ParseRequest(
+ path=file_path,
+ tier=tier,
+ page_range=pages,
+ force=force,
+ remote=remote,
)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ )
req_tier = result.tier
status = result.status
@@ -130,7 +173,7 @@ def parse_cmd(
# cached
if status == "done":
if verbose:
- print_notice("Cache hit — returning cached result.")
+ _emit_notice("Cache hit — returning cached result.", json_mode=json_mode)
_output_parse_result(
client,
result,
@@ -150,16 +193,16 @@ def parse_cmd(
# no-wait
if no_wait or status not in ("pending", "parsing") or not wait_parse_ids:
if json_mode:
- _print_parse_json_response(result, None)
+ _emit_parse_json_response(result, None)
else:
- format_parse_result(result, json_mode=False)
+ emit_result(CliContext(json_mode=False), _prepare_parse_summary_output(result))
if status == "failed":
- raise typer.Exit(1)
+ emit_result(CliContext(json_mode=json_mode), cli_ok(exit_code=1))
return
# poll until done or timeout
if verbose:
- print_notice(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...")
+ _emit_notice(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...", json_mode=json_mode)
wait_started_at = time.time()
deadline = time.time() + wait
@@ -177,7 +220,7 @@ def parse_cmd(
statuses = {row.status for row in parse_rows}
st = "done" if parse_rows and statuses == {"done"} else ("failed" if "failed" in statuses else "parsing")
if verbose and not json_mode:
- print_notice(f" Parse status: {st}")
+ _emit_notice(f" Parse status: {st}", json_mode=json_mode)
if st == "done":
_record_parse_wait(client, wait_parse_ids, "succeeded", wait_started_at)
@@ -200,17 +243,16 @@ def parse_cmd(
if st == "failed":
failed = next((row for row in parse_rows if row.status == "failed"), None)
_record_parse_wait(client, wait_parse_ids, "failed", wait_started_at)
- exit_with_error(
- MineruError(failed.error_code if failed else "parse_failed", failed.error_msg if failed else "", None),
- json_mode=json_mode,
- )
+ raise MineruError(failed.error_code if failed else "parse_failed", failed.error_msg if failed else "", None)
_record_parse_wait(client, wait_parse_ids, "timeout", wait_started_at)
if json_mode:
timeout_result = result.model_copy(update={"status": "parsing", "tip": "Re-run the same command to continue waiting."})
- _print_parse_json_response(timeout_result, None)
+ _emit_parse_json_response(timeout_result, None)
else:
- print_notice(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")
+ _emit_notice(
+ f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}", json_mode=json_mode
+ )
def _record_parse_wait(client: DoclibClient, parse_ids: list[int], status: str, started_at: float) -> None:
@@ -232,12 +274,6 @@ def _record_parse_wait(client: DoclibClient, parse_ids: list[int], status: str,
pass
-if __name__ != "__main__":
-
- def _register(app: typer.Typer) -> None:
- app.command()(parse_cmd)
-
-
def _output_parse_result(
client: DoclibClient,
parse_result: ParseResponse,
@@ -257,55 +293,51 @@ def _output_parse_result(
tier = parse_result.tier
page_range = parse_result.page_range
output_path = _ensure_output_parent(output)
- try:
- if output_path and output_path != "-":
- exported = client.export_doc_content(
- sha256,
- DocContentExportRequest(
- tier=tier,
- page_range=page_range,
- format=format,
- output=output_path,
- no_marker=no_marker,
- ),
- )
- if json_mode:
- _print_parse_json_response(parse_result, None, output=exported.output)
- return
- print_success(f"Written to {exported.output}")
- return
-
- content = _fetch_doc_content(
- client,
+ if output_path and output_path != "-":
+ exported = client.export_doc_content(
sha256,
- tier=tier,
- page_range=page_range,
- after=after,
- limit=limit,
- format=format,
- no_marker=no_marker,
+ DocContentExportRequest(
+ tier=tier,
+ page_range=page_range,
+ format=format,
+ output=output_path,
+ no_marker=no_marker,
+ ),
)
- if not content.content and content.format == "markdown" and not content.content_ranges:
- print_error("No content returned from parse.")
- raise typer.Exit(1)
if json_mode:
- _print_parse_json_response(parse_result, content)
+ _emit_parse_json_response(parse_result, None, output=exported.output)
return
- output_doc_content_response(
+ emit_result(
+ CliContext(json_mode=False), cli_ok(ParseTextOutput(f"Written to {exported.output}"), render=_render_parse_text)
+ )
+ return
+
+ content = _fetch_doc_content(
+ client,
+ sha256,
+ tier=tier,
+ page_range=page_range,
+ after=after,
+ limit=limit,
+ format=format,
+ no_marker=no_marker,
+ )
+ if not content.content and content.format == "markdown" and not content.content_ranges:
+ raise MineruError("parse_empty", "No content returned from parse.")
+ if json_mode:
+ _emit_parse_json_response(parse_result, content)
+ return
+ emit_result(
+ CliContext(json_mode=False),
+ _prepare_parse_content_output(
content,
- json_mode=json_mode,
- output=None,
source_path=source_path,
- read_mode=False,
no_marker=no_marker,
next_marker_tier=next_marker_tier,
next_marker_limit=next_marker_limit,
next_marker_remote=next_marker_remote,
- )
- except typer.Exit:
- raise
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ ),
+ )
def _fetch_doc_content(
@@ -330,113 +362,81 @@ def _fetch_doc_content(
)
-def _print_parse_json_response(
+def _emit_parse_json_response(
parse_result: ParseResponse,
content: DocContentResponse | None,
*,
output: str | None = None,
) -> None:
+ emit_result(CliContext(json_mode=True), cli_ok(_parse_json_payload(parse_result, content, output=output)))
+
+
+def _parse_json_payload(
+ parse_result: ParseResponse,
+ content: DocContentResponse | None,
+ *,
+ output: str | None = None,
+) -> dict[str, Any]:
payload: dict[str, Any] = {
"parse": parse_result.model_dump(mode="json"),
"content": content.model_dump(mode="json") if content is not None else None,
}
if output is not None:
payload["output"] = _output_info(output)
- print_json(payload)
+ return payload
+
+
+def _prepare_parse_summary_output(parse_result: ParseResponse) -> CliResult[ParseSummaryOutput] | CliResult[None]:
+ status = parse_result.status
+ tip = parse_result.tip or ""
+ if status in ("pending", "parsing"):
+ return cli_ok(ParseSummaryOutput(f"Parse {status}... {tip}"), render=_render_parse_summary)
+ if status == "failed":
+ return cli_ok(None, notices=["Parse failed: ? — "])
+ return cli_ok(ParseSummaryOutput(f"Parse complete (tier={parse_result.tier}) {tip}"), render=_render_parse_summary)
+
+
+def _render_parse_summary(data: ParseSummaryOutput) -> str:
+ return data.text
-def output_doc_content_response(
+def _prepare_parse_content_output(
content: DocContentResponse,
*,
- json_mode: bool,
- output: str | None,
source_path: str | None,
- read_mode: bool,
no_marker: bool,
next_marker_tier: Tier | None = None,
next_marker_limit: int | None = None,
next_marker_remote: bool = False,
-) -> None:
- output_path = _ensure_output_parent(output)
- if json_mode and output_path and output_path != "-":
- payload = content.model_dump(mode="json")
- if content.format == "image":
- if content.asset is None:
- print_error("No image asset returned.")
- raise typer.Exit(1)
- shutil.copyfile(content.asset.path, output_path)
- else:
- Path(output_path).write_text(content.content, encoding="utf-8")
- payload["content"] = None
- payload["output"] = _output_info(output_path)
- print_json(payload)
- return
- if json_mode:
- print_json(content)
- return
- if content.format == "image":
- if content.asset is None:
- print_error("No image asset returned.")
- raise typer.Exit(1)
- asset_path = content.asset.path
- if output_path and output_path != "-":
- shutil.copyfile(asset_path, output_path)
- print_success(f"Written to {output_path}")
- return
- print(asset_path)
- return
- if output_path and output_path != "-":
- Path(output_path).write_text(content.content, encoding="utf-8")
- print_success(f"Written to {output_path}")
- return
+) -> CliResult[ParseTextOutput] | CliResult[None]:
if not content.content and content.content_ranges:
message = "No renderable content in requested pages."
if content.next_request and not no_marker:
- marker = (
- _read_next_marker(content.next_request)
- if read_mode
- else _parse_next_marker(
- source_path,
- content.next_request,
- tier=next_marker_tier,
- limit=next_marker_limit,
- remote=next_marker_remote,
- )
- )
- if marker:
- print(_append_next_marker(message, marker))
- return
- typer.echo(message, err=True)
- return
- if content.next_request and not no_marker:
- marker = (
- _read_next_marker(content.next_request)
- if read_mode
- else _parse_next_marker(
+ marker = _parse_next_marker(
source_path,
content.next_request,
tier=next_marker_tier,
limit=next_marker_limit,
remote=next_marker_remote,
)
+ if marker:
+ return cli_ok(ParseTextOutput(_append_next_marker(message, marker)), render=_render_parse_text)
+ return cli_ok(None, notices=[message])
+ if content.next_request and not no_marker:
+ marker = _parse_next_marker(
+ source_path,
+ content.next_request,
+ tier=next_marker_tier,
+ limit=next_marker_limit,
+ remote=next_marker_remote,
)
if marker:
- print(_append_next_marker(content.content, marker))
- return
- print(content.content)
+ return cli_ok(ParseTextOutput(_append_next_marker(content.content, marker)), render=_render_parse_text)
+ return cli_ok(ParseTextOutput(content.content), render=_render_parse_text)
-def _next_request_dict(next_request: ContentNextRequest | None) -> dict[str, str] | None:
- if next_request is None:
- return None
- result: dict[str, str] = {}
- if next_request.page_range:
- result["page_range"] = next_request.page_range
- if next_request.after:
- result["after"] = next_request.after
- if next_request.locator:
- result["locator"] = next_request.locator
- return result
+def _render_parse_text(data: ParseTextOutput) -> str:
+ return data.text
def _append_next_marker(content: str, marker: str) -> str:
@@ -467,9 +467,3 @@ def _parse_next_marker(
if next_request.after:
parts.extend(["--after", next_request.after])
return f"<!-- Next: {shlex.join(parts)} -->"
-
-
-def _read_next_marker(next_request: ContentNextRequest) -> str | None:
- if not next_request.locator:
- return None
- return f"<!-- Next: mineru read {next_request.locator} -->"
diff --git a/mineru/cli/commands/read.py b/mineru/cli/commands/read.py
index a56e5db4..e4a69e3f 100644
--- a/mineru/cli/commands/read.py
+++ b/mineru/cli/commands/read.py
@@ -2,13 +2,24 @@
from __future__ import annotations
+import shutil
+from dataclasses import dataclass
+from pathlib import Path
from typing import Literal
import typer
from ...doclib.client import DoclibClient
-from ..json_errors import exit_with_error
-from .parse import output_doc_content_response
+from ...doclib.types import ContentNextRequest, DocContentResponse
+from ...errors import MineruError
+from ..contracts import CliContext, CliResult
+from ..runtime import cli_ok, run_cli
+from .parse import _append_next_marker, _ensure_output_parent, _output_info
+
+
+@dataclass(frozen=True)
+class ReadTextOutput:
+ text: str
def read_cmd(
@@ -21,34 +32,98 @@ def read_cmd(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Read parsed doclib content by locator."""
- try:
- client = DoclibClient(timeout=60)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
-
- try:
- content = client.read_content(
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(
+ ctx,
+ lambda: _read(
locator,
context=context,
limit=limit,
format=format,
- no_marker=no_marker,
- )
- output_doc_content_response(
- content,
- json_mode=json_mode,
output=output,
- source_path=None,
- read_mode=True,
no_marker=no_marker,
- )
- except typer.Exit:
- raise
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ json_mode=json_mode,
+ ),
+ )
+
+
+def _read(
+ locator: str,
+ *,
+ context: int,
+ limit: int,
+ format: Literal["markdown", "image"],
+ output: str | None,
+ no_marker: bool,
+ json_mode: bool,
+) -> DocContentResponse | dict[str, object] | CliResult[ReadTextOutput] | CliResult[None]:
+ content = DoclibClient(timeout=60).read_content(
+ locator,
+ context=context,
+ limit=limit,
+ format=format,
+ no_marker=no_marker,
+ )
+ return _prepare_read_output(content, json_mode=json_mode, output=output, no_marker=no_marker)
+
+
+def _prepare_read_output(
+ content: DocContentResponse,
+ *,
+ json_mode: bool,
+ output: str | None,
+ no_marker: bool,
+) -> DocContentResponse | dict[str, object] | CliResult[ReadTextOutput] | CliResult[None]:
+ output_path = _ensure_output_parent(output)
+ if json_mode and output_path and output_path != "-":
+ payload: dict[str, object] = content.model_dump(mode="json")
+ if content.format == "image":
+ if content.asset is None:
+ raise MineruError("asset_not_available", "No image asset returned.", "format")
+ shutil.copyfile(content.asset.path, output_path)
+ else:
+ Path(output_path).write_text(content.content, encoding="utf-8")
+ payload["content"] = None
+ payload["output"] = _output_info(output_path)
+ return payload
+
+ if json_mode:
+ return content
+
+ if content.format == "image":
+ if content.asset is None:
+ raise MineruError("asset_not_available", "No image asset returned.", "format")
+ asset_path = content.asset.path
+ if output_path and output_path != "-":
+ shutil.copyfile(asset_path, output_path)
+ return cli_ok(ReadTextOutput(f"Written to {output_path}"), render=_render_read_text)
+ return cli_ok(ReadTextOutput(asset_path), render=_render_read_text)
+
+ if output_path and output_path != "-":
+ Path(output_path).write_text(content.content, encoding="utf-8")
+ return cli_ok(ReadTextOutput(f"Written to {output_path}"), render=_render_read_text)
+
+ if not content.content and content.content_ranges:
+ message = "No renderable content in requested pages."
+ if content.next_request and not no_marker:
+ marker = _read_next_marker(content.next_request)
+ if marker:
+ return cli_ok(ReadTextOutput(_append_next_marker(message, marker)), render=_render_read_text)
+ return cli_ok(None, notices=[message])
+
+ if content.next_request and not no_marker:
+ marker = _read_next_marker(content.next_request)
+ if marker:
+ return cli_ok(ReadTextOutput(_append_next_marker(content.content, marker)), render=_render_read_text)
+
+ return cli_ok(ReadTextOutput(content.content), render=_render_read_text)
+
+def _render_read_text(data: ReadTextOutput) -> str:
+ return data.text
-if __name__ != "__main__":
- def _register(app: typer.Typer) -> None:
- app.command()(read_cmd)
+def _read_next_marker(next_request: ContentNextRequest) -> str | None:
+ if not next_request.locator:
+ return None
+ return f"<!-- Next: mineru read {next_request.locator} -->"
diff --git a/mineru/cli/commands/scan.py b/mineru/cli/commands/scan.py
index 3fa7f54e..09b32426 100644
--- a/mineru/cli/commands/scan.py
+++ b/mineru/cli/commands/scan.py
@@ -2,31 +2,30 @@
from __future__ import annotations
-from pathlib import Path
import time
+from pathlib import Path
+
+import typer
-from ...errors import MineruError
from ...doclib.client import DoclibClient
-from ...doclib.types import ScanRequest
-from ..json_errors import exit_with_error
-from ..output import print_error, print_info, print_json, print_success
+from ...doclib.types import ScanInfo, ScanRequest
+from ...errors import MineruError
+from ..contracts import CliContext, CliTaskResult
from ..path_utils import normalize_cli_path
+from ..runtime import cli_task, run_cli
def scan_cmd(
- path: str,
- *,
- wait: int = 30,
- no_wait: bool = False,
- json_mode: bool = False,
+ path: str = typer.Argument(..., help="File or directory path to scan"),
+ wait: int = typer.Option(30, "--wait", help="Max seconds to wait for scan completion"),
+ no_wait: bool = typer.Option(False, "--no-wait", help="Return immediately after creating the scan"),
+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
- try:
- _scan_path(path, wait=wait, no_wait=no_wait, json_mode=json_mode)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _scan(path, wait=wait, no_wait=no_wait), render=_render_scan)
-def _scan_path(path: str, *, wait: int, no_wait: bool, json_mode: bool) -> None:
+def _scan(path: str, *, wait: int, no_wait: bool) -> CliTaskResult[ScanInfo]:
scan_path = normalize_cli_path(path)
if not Path(scan_path).exists():
raise MineruError("file_not_found", f"File or directory not found: {scan_path}", "path")
@@ -34,17 +33,14 @@ def _scan_path(path: str, *, wait: int, no_wait: bool, json_mode: bool) -> None:
scan_info = client.create_scan(ScanRequest(path=scan_path, kind="manual", source="cli"))
if not no_wait and wait > 0:
scan_info = _wait_for_scan(client, scan_info.id, wait)
- _print_scan(scan_info, json_mode=json_mode)
+ return cli_task(scan_info, status=scan_info.status, render=_render_scan, fail_if_final_failed=not no_wait)
def _client() -> DoclibClient:
- try:
- return DoclibClient(timeout=30)
- except Exception:
- raise RuntimeError("Cannot connect to mineru server. Run 'mineru server start' first.") from None
+ return DoclibClient(timeout=30)
-def _wait_for_scan(client: DoclibClient, scan_id: int, wait_seconds: int) -> object:
+def _wait_for_scan(client: DoclibClient, scan_id: int, wait_seconds: int) -> ScanInfo:
deadline = time.time() + wait_seconds
scan_info = client.get_scan(scan_id)
while scan_info.status in ("pending", "running") and time.time() < deadline:
@@ -53,22 +49,14 @@ def _wait_for_scan(client: DoclibClient, scan_id: int, wait_seconds: int) -> obj
return scan_info
-def _print_scan(scan_info: object, *, json_mode: bool) -> None:
- if json_mode:
- print_json(scan_info)
- return
- status = getattr(scan_info, "status", "?")
+def _render_scan(scan_info: ScanInfo) -> str:
+ status = scan_info.status
if status == "failed":
- print_error(f"Scan failed: {getattr(scan_info, 'error_code', '')} {getattr(scan_info, 'error_msg', '')}")
- return
- message = (
- f"Scan {getattr(scan_info, 'id', '?')} {status}: "
- f"seen={getattr(scan_info, 'files_seen', 0)}, refreshed={getattr(scan_info, 'files_refreshed', 0)}, "
- f"new={getattr(scan_info, 'files_new', 0)}, changed={getattr(scan_info, 'files_changed', 0)}, "
- f"deleted={getattr(scan_info, 'files_deleted', 0)}, unreachable={getattr(scan_info, 'files_unreachable', 0)}, "
- f"excluded={getattr(scan_info, 'files_excluded', 0)}, unsupported={getattr(scan_info, 'files_unsupported', 0)}"
+ return f"Scan failed: {scan_info.error_code or ''} {scan_info.error_msg or ''}"
+ return (
+ f"Scan {scan_info.id} {status}: "
+ f"seen={scan_info.files_seen}, refreshed={scan_info.files_refreshed}, "
+ f"new={scan_info.files_new}, changed={scan_info.files_changed}, "
+ f"deleted={scan_info.files_deleted}, unreachable={scan_info.files_unreachable}, "
+ f"excluded={scan_info.files_excluded}, unsupported={scan_info.files_unsupported}"
)
- if status in ("pending", "running"):
- print_info(message)
- else:
- print_success(message)
diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.py
index d5cf615d..4151bd9d 100644
--- a/mineru/cli/commands/search.py
+++ b/mineru/cli/commands/search.py
@@ -5,18 +5,18 @@ from __future__ import annotations
import typer
from ...doclib.client import DoclibClient
+from ...doclib.types import FindResponse, SearchResponse
from ...types import Tier
-from ..json_errors import exit_with_error
-from ..output import format_find_results, format_search_results
+from ..contracts import CliContext
+from ..runtime import run_cli
+
+FILE_TYPES = "pdf, image, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt"
+FILE_EXTS = "pdf, png, jpg, jpeg, jp2, webp, gif, bmp, tiff, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt"
def search_cmd(
query: str = typer.Argument(..., help="Search query"),
- file_type: str | None = typer.Option(
- None,
- "--type",
- help="File type filter: pdf, image, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",
- ),
+ file_type: str | None = typer.Option(None, "--type", help=f"File type filter: {FILE_TYPES}"),
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"),
limit: int = typer.Option(20, "--limit", "-n", help="Max results"),
@@ -24,28 +24,72 @@ def search_cmd(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Search parsed document content."""
- try:
- client = DoclibClient(timeout=10)
- result = client.search(query, file_type=file_type, tier=tier, min_tier=min_tier, limit=limit, offset=offset)
- format_search_results(result, json_mode=json_mode)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: DoclibClient(timeout=10).search(
+ query,
+ file_type=file_type,
+ tier=tier,
+ min_tier=min_tier,
+ limit=limit,
+ offset=offset,
+ ),
+ render=_render_search_results,
+ )
def find_cmd(
query: str = typer.Argument(..., help="Filename search query"),
- ext: str | None = typer.Option(
- None,
- "--ext",
- help="File extension filter: pdf, png, jpg, jpeg, jp2, webp, gif, bmp, tiff, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",
- ),
+ ext: str | None = typer.Option(None, "--ext", help=f"File extension filter: {FILE_EXTS}"),
limit: int = typer.Option(50, "--limit", "-n", help="Max results"),
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Search filenames only (not document content)."""
- try:
- client = DoclibClient(timeout=10)
- result = client.find(query, ext=ext, limit=limit)
- format_find_results(result, json_mode=json_mode)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: DoclibClient(timeout=10).find(query, ext=ext, limit=limit),
+ render=_render_find_results,
+ )
+
+
+def _render_search_results(data: SearchResponse) -> str:
+ if not data.results:
+ return "No results found."
+
+ lines = [f"Search results ({data.total} total)"]
+ for index, result in enumerate(data.results, start=1):
+ filename = result.title or result.filename or "?"
+ path = _format_result_path(result.paths)
+ item_line = f"{index}. {filename}{path}"
+ if result.tier:
+ item_line += f" Tier: {result.tier}"
+ lines.append(item_line)
+ snippet = _format_snippet(result.snippet)
+ if snippet:
+ lines.append(f" {snippet}")
+ if index < len(data.results):
+ lines.append("")
+ return "\n".join(lines)
+
+
+def _render_find_results(data: FindResponse) -> str:
+ if not data.results:
+ return "No results found."
+
+ lines = [f"Search results ({data.total} total)"]
+ for index, result in enumerate(data.results, start=1):
+ path = _format_result_path(result.paths)
+ lines.append(f"{index}. {result.filename}{path}")
+ if index < len(data.results):
+ lines.append("")
+ return "\n".join(lines)
+
+
+def _format_result_path(paths: list[str]) -> str:
+ if not paths:
+ return ""
+ return f" ({paths[0]})"
+
+
+def _format_snippet(snippet: str | None) -> str:
+ return str(snippet or "").replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ")
diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.py
index 165f446a..c064f1cc 100644
--- a/mineru/cli/commands/server.py
+++ b/mineru/cli/commands/server.py
@@ -7,15 +7,20 @@ import subprocess
import sys
import time
import uuid
+from collections.abc import Iterator
+from typing import Any
import typer
+from rich.panel import Panel
+from rich.table import Table
from ...config import config
from ...doclib.endpoint import remove_endpoint_file
from ...doclib.types import ServerStatusResponse, TCPServerStatus
+from ...errors import MineruError
from ...version import __version__
-from ..json_errors import exit_with_error
-from ..output import format_server_status, print_error, print_info, print_success
+from ..contracts import CliContext, RenderableObject
+from ..runtime import run_cli
app = typer.Typer(help="Server lifecycle management", no_args_is_help=True)
@@ -164,9 +169,12 @@ def _wait_for_sock(timeout: float = 15.0) -> bool:
@app.command()
def start() -> None:
"""Start the mineru server in the background."""
+ run_cli(CliContext(json_mode=False), _start)
+
+
+def _start() -> str:
if _server_running():
- print_info("Server is already running.")
- return
+ return "Server is already running."
log_path = _server_log_path()
stdout_log_path = _server_stdout_log_path()
@@ -178,8 +186,7 @@ def start() -> None:
try:
with _ServerStartLock(_server_start_lock_path()) as start_lock:
if not start_lock.acquired or _server_running():
- print_info("Server is already running.")
- return
+ return "Server is already running."
socket_path = _socket_path()
# Clean stale socket
@@ -209,27 +216,32 @@ def start() -> None:
if not _wait_for_server():
proc.kill()
- print_error(
+ raise MineruError(
+ "service_unavailable",
"Server failed to start within 15 seconds. "
- f"See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}"
+ f"See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}",
)
- raise typer.Exit(1)
- except typer.Exit:
+ except MineruError:
raise
except Exception as exc:
- print_error(f"Server failed to start: {exc}. See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}")
- raise typer.Exit(1) from None
+ raise MineruError(
+ "service_unavailable",
+ f"Server failed to start: {exc}. See log: {log_path}; stdout: {stdout_log_path}; stderr: {stderr_log_path}",
+ ) from exc
- print_success(f"Server started (PID {proc.pid}).")
+ return f"Server started (PID {proc.pid})."
@app.command()
def stop() -> None:
"""Stop the mineru server gracefully."""
+ run_cli(CliContext(json_mode=False), _stop)
+
+
+def _stop() -> str:
if not _server_running():
_cleanup_local_endpoint_files()
- print_info("Server is not running.")
- return
+ return "Server is not running."
try:
from ...doclib.client import DoclibClient
@@ -242,52 +254,315 @@ def stop() -> None:
time.sleep(0.5)
_cleanup_local_endpoint_files()
- print_success("Server stopped.")
+ return "Server stopped."
@app.command()
def restart() -> None:
"""Restart the mineru server."""
+ run_cli(CliContext(json_mode=False), _restart)
+
+
+def _restart() -> str:
if _server_running():
- stop()
+ stop_message = _stop()
time.sleep(1)
- start()
+ start_message = _start()
+ return f"{stop_message}\n{start_message}"
+ return _start()
@app.command()
def status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""Show server status."""
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, _server_status, render=_render_server_status)
+
+
+def _server_status() -> ServerStatusResponse:
if not _server_running():
- if json_mode:
- format_server_status(
- ServerStatusResponse(
- running=False,
- mineru_home=os.path.expanduser(os.getenv("MINERU_HOME", "~/.mineru")),
- version=__version__,
- python_version=sys.version.split()[0],
- socket_path=_socket_path(),
- data_dir=os.path.expanduser(config.doclib.data_dir),
- sqlite_path=os.path.expanduser(config.doclib.sqlite.path),
- log_path=os.path.expanduser(config.doclib.log.resolved_app_path),
- access_log_path=os.path.expanduser(config.doclib.log.resolved_access_path),
- stdout_log_path=os.path.expanduser(config.doclib.log.resolved_stdout_path),
- stderr_log_path=os.path.expanduser(config.doclib.log.resolved_stderr_path),
- tcp=TCPServerStatus(enabled=False, host=None, port=None),
- ),
- json_mode=True,
- )
- return
- print_info("Server is not running.")
- return
+ return _not_running_status()
+ from ...doclib.client import DoclibClient
- try:
- from ...doclib.client import DoclibClient
+ c = DoclibClient(timeout=5)
+ return c.get_server_status()
- c = DoclibClient(timeout=5)
- data = c.get_server_status()
- format_server_status(data, json_mode=json_mode)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+
+def _render_server_status(data: ServerStatusResponse) -> Iterator[RenderableObject]:
+ if not _get(data, "running"):
+ yield "Server is not running."
+ return
+
+ table = Table(title="MinerU Server")
+ table.add_column("Field", style="cyan")
+ table.add_column("Current", style="green")
+ table.add_row("PID", str(_get(data, "pid", "?")))
+ table.add_row("Uptime", f"{_get(data, 'uptime_seconds', 0):.0f}s")
+ table.add_row("Home", _get(data, "mineru_home", ""))
+ table.add_row("Version", _get(data, "version", ""))
+ table.add_row("Python", _get(data, "python_version", ""))
+ table.add_row("Socket", _get(data, "socket_path", ""))
+ table.add_row("Data dir", _get(data, "data_dir", ""))
+ table.add_row("SQLite", _get(data, "sqlite_path", ""))
+ table.add_row("SQLite size", _format_bytes(_get(data, "sqlite_size_bytes")))
+ table.add_row("Log", _get(data, "log_path", ""))
+ tcp_data = _get(data, "tcp")
+ tcp_enabled = bool(_get(tcp_data, "enabled", False))
+ tcp_host = _get(tcp_data, "host", "") or "-"
+ tcp_port = _get(tcp_data, "port")
+ if tcp_enabled:
+ tcp_value = f"http://{tcp_host}:{tcp_port}" if tcp_port is not None else f"http://{tcp_host}:(pending)"
+ else:
+ tcp_value = "disabled"
+ table.add_row("TCP", tcp_value)
+ table.add_row("Files tracked", str(_get(data, "files_total", 0)))
+ table.add_row("Docs indexed", str(_get(data, "docs_total", 0)))
+ table.add_row("Active scans", str(_get(data, "active_scan_count", 0)))
+ table.add_row("Last scan", _format_timestamp_ms(_get(data, "last_scan_at")))
+ table.add_row("Parse queue", str(_get(data, "parse_queue_length", 0)))
+ table.add_row("Ingest queue", str(_get(data, "ingest_queue_length", 0)))
+ table.add_row("Watches", str(_get(data, "watch_count", 0)))
+ yield table
+
+ workers = _get(data, "workers")
+ if workers:
+ worker_table = Table(title="Workers")
+ worker_table.add_column("Component", style="cyan")
+ worker_table.add_column("Running", style="green")
+ worker_table.add_column("Workers", justify="right")
+ worker_table.add_row("Watch", "yes" if _get(workers, "watch_running", False) else "no", "-")
+ worker_table.add_row(
+ "Scan",
+ "yes" if _get(workers, "scan_running", False) else "no",
+ str(_get(workers, "scan_workers", 0)),
+ )
+ worker_table.add_row(
+ "Ingest",
+ "yes" if _get(workers, "ingest_running", False) else "no",
+ str(_get(workers, "ingest_workers", 0)),
+ )
+ worker_table.add_row(
+ "Parse",
+ "yes" if _get(workers, "parse_running", False) else "no",
+ str(_get(workers, "parse_workers", 0)),
+ )
+ worker_table.add_row(
+ "Device monitor",
+ "yes" if _get(workers, "device_monitor_running", False) else "no",
+ "-",
+ )
+ worker_table.add_row(
+ "Compaction",
+ "yes" if _get(workers, "compaction_running", False) else "no",
+ "-",
+ )
+ worker_table.add_row(
+ "Health check",
+ "yes" if _get(workers, "health_check_running", False) else "no",
+ "-",
+ )
+ yield worker_table
+
+ watch_stats = _get(data, "watch_stats", [])
+ if watch_stats:
+ watch_table = Table(title="Watch Stats")
+ watch_table.add_column("Path", style="cyan", no_wrap=True)
+ watch_table.add_column("Status", style="green")
+ watch_table.add_column("Files", justify="right")
+ watch_table.add_column("Active", justify="right")
+ watch_table.add_column("Deleted", justify="right")
+ watch_table.add_column("Unreachable", justify="right")
+ watch_table.add_column("Pending ingest", justify="right")
+ watch_table.add_column("Errors", justify="right")
+ watch_table.add_column("Docs", justify="right")
+ watch_table.add_column("Parses done/pending/parsing/failed", justify="right")
+ for item in watch_stats:
+ parse_counts = (
+ f"{_get(item, 'parse_done_count', 0)}/"
+ f"{_get(item, 'parse_pending_count', 0)}/"
+ f"{_get(item, 'parse_parsing_count', 0)}/"
+ f"{_get(item, 'parse_failed_count', 0)}"
+ )
+ watch_table.add_row(
+ _get(item, "path", ""),
+ _get(item, "status", ""),
+ str(_get(item, "total_files", 0)),
+ str(_get(item, "active_files", 0)),
+ str(_get(item, "deleted_files", 0)),
+ str(_get(item, "unreachable_files", 0)),
+ str(_get(item, "pending_ingest_files", 0)),
+ str(_get(item, "file_error_count", 0)),
+ str(_get(item, "doc_count", 0)),
+ parse_counts,
+ )
+ yield watch_table
+
+ error_rows = _error_summary_rows(_get(data, "error_summary"))
+ if error_rows:
+ error_table = Table(title="Error Summary")
+ error_table.add_column("Scope", style="cyan")
+ error_table.add_column("Code", style="red")
+ error_table.add_column("Count", justify="right")
+ for scope, code, count in error_rows:
+ error_table.add_row(scope, code, str(count))
+ yield error_table
+
+ recent_scans = _get(data, "recent_scans", [])
+ if recent_scans:
+ scan_table = Table(title="Recent Scans")
+ scan_table.add_column("ID", justify="right")
+ scan_table.add_column("Kind", style="cyan")
+ scan_table.add_column("Source")
+ scan_table.add_column("Status", style="green")
+ scan_table.add_column("Path", no_wrap=True)
+ scan_table.add_column("Seen", justify="right")
+ scan_table.add_column("New", justify="right")
+ scan_table.add_column("Changed", justify="right")
+ scan_table.add_column("Deleted", justify="right")
+ scan_table.add_column("Errors", justify="right")
+ scan_table.add_column("Error code", style="red")
+ for item in recent_scans:
+ scan_table.add_row(
+ str(_get(item, "id", "")),
+ _get(item, "kind", ""),
+ _get(item, "source", ""),
+ _get(item, "status", ""),
+ _get(item, "path", ""),
+ str(_get(item, "files_seen", 0)),
+ str(_get(item, "files_new", 0)),
+ str(_get(item, "files_changed", 0)),
+ str(_get(item, "files_deleted", 0)),
+ str(_get(item, "files_error", 0)),
+ _get(item, "error_code", "") or "",
+ )
+ yield scan_table
+
+ ps_data = _get(data, "parse_server")
+ if ps_data:
+ ps_table = Table(title="Parse Server")
+ ps_table.add_column("Target", style="cyan")
+ ps_table.add_column("Healthy", style="green")
+ ps_table.add_column("Endpoint", style="dim")
+ ps_table.add_column("Managed", style="dim")
+ ps_table.add_column("Restart", justify="right")
+ ps_table.add_column("Last probe", style="dim")
+ ps_table.add_column("Last ok", style="dim")
+ ps_table.add_column("Last fail", style="dim")
+ ps_table.add_column("Tiers", style="green")
+ for label, key in [("Local", "local"), ("Remote", "remote")]:
+ ps = _get(ps_data, key, {})
+ if _get(ps, "starting"):
+ healthy_str = "starting"
+ elif _get(ps, "healthy"):
+ healthy_str = "yes"
+ else:
+ healthy_str = "no"
+ tiers_str = ", ".join(_get(ps, "supported_tiers", [])) or "-"
+ mode = _get(ps, "mode", "")
+ label_str = f"{label} ({mode})" if mode else label
+ endpoint = _get(ps, "url", "") or "-"
+ managed_str = "-"
+ restart_str = "-"
+ if key == "local":
+ mode_text = _get(ps, "mode", "")
+ if mode_text == "managed":
+ managed_tier = _get(ps, "managed_tier", "") or "-"
+ managed_pid = _get(ps, "managed_pid")
+ managed_running = "yes" if _get(ps, "managed_running", False) else "no"
+ managed_str = f"tier={managed_tier}, pid={managed_pid or '-'}, running={managed_running}"
+ elif mode_text == "self_hosted":
+ managed_str = _get(ps, "self_hosted_url", "") or "-"
+ restart_str = f"{_get(ps, 'restart_count', 0)}/{_get(ps, 'max_restart_attempts', 0)}"
+ ps_table.add_row(
+ label_str,
+ healthy_str,
+ endpoint,
+ managed_str,
+ restart_str,
+ _format_age_ms(_get(ps, "last_probe_at")),
+ _format_age_ms(_get(ps, "last_success_at")),
+ _format_age_ms(_get(ps, "last_failure_at")),
+ tiers_str,
+ )
+ yield ps_table
+
+ for title, key in (
+ ("Recent App Logs", "app_logs"),
+ ("Recent Access Logs", "access_logs"),
+ ("Recent Stderr Logs", "stderr_logs"),
+ ("Recent Stdout Logs", "stdout_logs"),
+ ):
+ logs = _get(data, key, [])
+ if logs:
+ log_text = "".join(logs)
+ panel = Panel(log_text.strip() or "(empty)", title=title, border_style="dim")
+ yield panel
+
+
+def _not_running_status() -> ServerStatusResponse:
+ return ServerStatusResponse(
+ running=False,
+ mineru_home=os.path.expanduser(os.getenv("MINERU_HOME", "~/.mineru")),
+ version=__version__,
+ python_version=sys.version.split()[0],
+ socket_path=_socket_path(),
+ data_dir=os.path.expanduser(config.doclib.data_dir),
+ sqlite_path=os.path.expanduser(config.doclib.sqlite.path),
+ log_path=os.path.expanduser(config.doclib.log.resolved_app_path),
+ access_log_path=os.path.expanduser(config.doclib.log.resolved_access_path),
+ stdout_log_path=os.path.expanduser(config.doclib.log.resolved_stdout_path),
+ stderr_log_path=os.path.expanduser(config.doclib.log.resolved_stderr_path),
+ tcp=TCPServerStatus(enabled=False, host=None, port=None),
+ )
+
+
+def _get(data: Any, key: str, default: Any = None) -> Any:
+ if isinstance(data, dict):
+ return data.get(key, default)
+ return getattr(data, key, default)
+
+
+def _format_bytes(n: int | None) -> str:
+ if n is None:
+ return "-"
+ units = ["B", "KB", "MB", "GB", "TB"]
+ value = float(n)
+ unit_index = 0
+ while value >= 1024 and unit_index < len(units) - 1:
+ value /= 1024
+ unit_index += 1
+ if unit_index == 0:
+ return f"{int(value)} {units[unit_index]}"
+ return f"{value:.1f} {units[unit_index]}"
+
+
+def _format_timestamp_ms(ts: int | None) -> str:
+ if ts is None:
+ return "-"
+ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts / 1000))
+
+
+def _format_age_ms(ts: int | None) -> str:
+ if ts is None:
+ return "-"
+ age = max(0.0, time.time() - ts / 1000)
+ if age < 60:
+ return f"{age:.0f}s ago"
+ if age < 3600:
+ return f"{age / 60:.0f}m ago"
+ if age < 86400:
+ return f"{age / 3600:.0f}h ago"
+ return f"{age / 86400:.0f}d ago"
+
+
+def _error_summary_rows(error_summary: Any) -> list[tuple[str, str, int]]:
+ if not error_summary:
+ return []
+ rows: list[tuple[str, str, int]] = []
+ for scope, attr in (("file", "file_errors"), ("doc", "doc_errors"), ("parse", "parse_errors")):
+ for bucket in _get(error_summary, attr, []):
+ rows.append((scope, _get(bucket, "code", ""), int(_get(bucket, "count", 0))))
+ return rows
def _cleanup_local_endpoint_files() -> None:
diff --git a/mineru/cli/commands/show.py b/mineru/cli/commands/show.py
index 50c4e625..47dcecea 100644
--- a/mineru/cli/commands/show.py
+++ b/mineru/cli/commands/show.py
@@ -3,12 +3,13 @@
from __future__ import annotations
import typer
+from rich.table import Table
from ...doclib.client import DoclibClient
-from ..json_errors import exit_with_error
-from ..output import format_info, print_json
+from ...doclib.types import DocInfo, FileInfoResponse, ParseInfo, ScanInfo
+from ..contracts import CliContext
from ..path_utils import normalize_cli_path
-from .scan import _print_scan
+from ..runtime import run_cli
app = typer.Typer(help="Show doclib resource details", no_args_is_help=True)
@@ -19,21 +20,11 @@ def show_parse(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Show one parse task."""
- try:
- result = _client().get_parse(parse_id)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- print(f"Parse {result.id}: {result.status}")
- print(f" sha256: {result.sha256}")
- print(f" tier: {result.tier}")
- print(f" pages: {result.page_range}")
- print(f" privacy: {result.privacy}")
- if result.error_code or result.error_msg:
- print(f" error: {result.error_code or ''} {result.error_msg or ''}".rstrip())
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().get_parse(parse_id),
+ render=_render_parse_info,
+ )
@app.command("scan")
@@ -42,12 +33,11 @@ def show_scan(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Show one scan task."""
- try:
- result = _client().get_scan(scan_id)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- _print_scan(result, json_mode=json_mode)
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().get_scan(scan_id),
+ render=_render_scan,
+ )
@app.command("file")
@@ -56,40 +46,102 @@ def show_file(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Show file, doc, and parse state for a local path."""
- file_path = normalize_cli_path(path)
- try:
- result = _client().get_file_by_path(file_path)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- format_info(result, json_mode=json_mode)
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().get_file_by_path(normalize_cli_path(path)),
+ render=_render_file_info,
+ )
@app.command("doc")
def show_doc(
- sha256: str = typer.Argument(..., help="Document sha256"),
+ doc_ref: str = typer.Argument(..., help="Document Doc ID or SHA-256"),
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
- """Show one doc by content hash."""
- try:
- result = _client().get_doc(sha256, expand_files=True)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
-
- if json_mode:
- print_json(result)
- return
- print(f"Doc {result.sha256}")
- print(f" type: {result.file_type or '-'}")
- print(f" title: {result.title or '-'}")
- print(f" pages: {result.page_count if result.page_count is not None else '-'}")
- print(f" image_based: {result.is_image_based}")
- files = result.files or []
- if files:
- print(" files:")
- for file_info in files:
- print(f" [{file_info.status}] {file_info.path}")
+ """Show one doc by Doc ID or content hash."""
+ run_cli(
+ CliContext(json_mode=json_mode),
+ lambda: _client().get_doc(doc_ref, expand_files=True),
+ render=_render_doc_info,
+ )
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
+
+
+def _render_parse_info(data: ParseInfo) -> Table:
+ table = Table(title=f"Parse {data.id}: {data.status}")
+ table.add_column("Field", style="cyan")
+ table.add_column("Value", style="green")
+ table.add_row("SHA-256", data.sha256)
+ table.add_row("Tier", data.tier)
+ table.add_row("Pages", data.page_range)
+ table.add_row("Privacy", data.privacy)
+ if data.error_code or data.error_msg:
+ table.add_row("Error", f"{data.error_code or ''} {data.error_msg or ''}".rstrip())
+ return table
+
+
+def _render_scan(data: ScanInfo) -> Table | str:
+ if data.status == "failed":
+ return f"Scan failed: {data.error_code or ''} {data.error_msg or ''}"
+ table = Table(title=f"Scan {data.id}: {data.status}")
+ table.add_column("Metric", style="cyan")
+ table.add_column("Value", style="green", justify="right")
+ table.add_row("Seen", str(data.files_seen))
+ table.add_row("Refreshed", str(data.files_refreshed))
+ table.add_row("New", str(data.files_new))
+ table.add_row("Changed", str(data.files_changed))
+ table.add_row("Deleted", str(data.files_deleted))
+ table.add_row("Unreachable", str(data.files_unreachable))
+ table.add_row("Excluded", str(data.files_excluded))
+ table.add_row("Unsupported", str(data.files_unsupported))
+ return table
+
+
+def _render_file_info(data: FileInfoResponse) -> Table | str:
+ if not data.file:
+ return "File not found in database."
+
+ table = Table(title=f"File Info: {data.file.filename or '?'}")
+ table.add_column("Field", style="cyan")
+ table.add_column("Value", style="green")
+ table.add_row("Path", data.file.path or "?")
+ table.add_row("Type", data.file.ext or "?")
+ table.add_row("Size", _format_info_bytes(data.file.size_bytes))
+ table.add_row("Doc ID", data.file.short_id or "-")
+ table.add_row("Page count", str(data.doc.page_count if data.doc else "?"))
+ table.add_row("Title", (data.doc.title if data.doc else None) or "—")
+ table.add_row("Author", (data.doc.author if data.doc else None) or "—")
+
+ if data.parsed_tiers:
+ tier_str = ", ".join(f"{tier.tier}={tier.status}" for tier in data.parsed_tiers)
+ table.add_row("Tiers", tier_str)
+
+ return table
+
+
+def _format_info_bytes(n: int | None) -> str:
+ if n is None:
+ return "?"
+ for unit in ("B", "KB", "MB", "GB"):
+ if n < 1024:
+ return f"{n} {unit}"
+ n //= 1024
+ return f"{n} TB"
+
+
+def _render_doc_info(data: DocInfo) -> Table:
+ table = Table(title=f"Doc {data.short_id}")
+ table.add_column("Field", style="cyan")
+ table.add_column("Value", style="green")
+ table.add_row("SHA-256", data.sha256)
+ table.add_row("Type", data.file_type or "-")
+ table.add_row("Title", data.title or "-")
+ table.add_row("Pages", str(data.page_count if data.page_count is not None else "-"))
+ table.add_row("Image based", str(data.is_image_based))
+ if data.files:
+ files = "\n".join(f"[{file_info.status}] {file_info.path}" for file_info in data.files)
+ table.add_row("Files", files)
+ return table
diff --git a/mineru/cli/commands/telemetry.py b/mineru/cli/commands/telemetry.py
index d7e01b42..975869a6 100644
--- a/mineru/cli/commands/telemetry.py
+++ b/mineru/cli/commands/telemetry.py
@@ -3,12 +3,14 @@
from __future__ import annotations
import json
+from typing import Literal
import typer
from ...doclib.client import DoclibClient
-from ..json_errors import exit_with_error
-from ..output import print_json, print_success
+from ...doclib.types import TelemetryActionResponse, TelemetryPayload, TelemetryStatusResponse
+from ..contracts import CliContext
+from ..runtime import run_cli
app = typer.Typer(help="Telemetry management", no_args_is_help=True)
@@ -16,29 +18,15 @@ app = typer.Typer(help="Telemetry management", no_args_is_help=True)
@app.command("status")
def telemetry_status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""Show telemetry status."""
- try:
- data = _client().get_telemetry_status()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
- if json_mode:
- print_json(data)
- return
- last_flush = data.last_flush_at if data.last_flush_at is not None else "never"
- print(f"state: {data.state}")
- print(f"installation_id: {data.installation_id}")
- print(f"pending_periods: {data.pending_periods}")
- print(f"pending_metrics: {data.pending_metrics}")
- print(f"last_flush_at: {last_flush}")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().get_telemetry_status(), render=_render_telemetry_status)
@app.command("preview")
-def telemetry_preview() -> None:
+def telemetry_preview(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""Print the next telemetry request body without sending it."""
- try:
- data = _client().get_telemetry_preview()
- except Exception as exc:
- exit_with_error(exc, json_mode=False)
- print(json.dumps(data.body.model_dump(mode="json"), ensure_ascii=False, indent=2, sort_keys=True))
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().get_telemetry_preview().body, render=_render_telemetry_preview)
@app.command("enable")
@@ -59,22 +47,36 @@ def telemetry_flush(json_mode: bool = typer.Option(False, "--json", help="JSON o
_run_action("flush", json_mode=json_mode)
-def _run_action(action: str, *, json_mode: bool) -> None:
- try:
- data = _client().telemetry_action(action)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
- if json_mode:
- print_json(data)
- return
- if action == "flush":
- print_success(f"telemetry flush: {data.reason or 'success'}")
- return
- print_success(f"telemetry {data.state}")
+def _run_action(action: Literal["enable", "disable", "flush"], *, json_mode: bool) -> None:
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().telemetry_action(action), render=_render_telemetry_action)
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
+def _render_telemetry_status(data: TelemetryStatusResponse) -> str:
+ last_flush = data.last_flush_at if data.last_flush_at is not None else "never"
+ return "\n".join(
+ [
+ f"state: {data.state}",
+ f"installation_id: {data.installation_id}",
+ f"pending_periods: {data.pending_periods}",
+ f"pending_metrics: {data.pending_metrics}",
+ f"last_flush_at: {last_flush}",
+ ]
+ )
+
+
+def _render_telemetry_action(data: TelemetryActionResponse) -> str:
+ if data.action == "flush":
+ return f"telemetry flush: {data.reason or 'success'}"
+ return f"telemetry {data.state}"
+
+
+def _render_telemetry_preview(data: TelemetryPayload) -> str:
+ return json.dumps(data.model_dump(mode="json"), ensure_ascii=False, indent=2, sort_keys=True)
+
+
__all__ = ["app"]
diff --git a/mineru/cli/commands/watch.py b/mineru/cli/commands/watch.py
index 878f9fb0..0b87736a 100644
--- a/mineru/cli/commands/watch.py
+++ b/mineru/cli/commands/watch.py
@@ -3,13 +3,15 @@
from __future__ import annotations
import typer
+from rich.table import Table
from ...doclib.client import DoclibClient
-from ...doclib.types import ScanRequest, WatchInfo, WatchRequest
-from ..json_errors import exit_with_error
-from ..output import print_info, print_json, print_success
+from ...doclib.types import RemoveWatchResponse, ScanInfo, ScanRequest, WatchInfo, WatchListResponse, WatchRequest
+from ...errors import MineruError
+from ..contracts import CliContext, CliTaskResult
from ..path_utils import normalize_cli_path
-from .scan import _print_scan, _wait_for_scan
+from ..runtime import cli_task, run_cli
+from .scan import _render_scan, _wait_for_scan
app = typer.Typer(help="Watch target management", no_args_is_help=True)
@@ -22,37 +24,21 @@ def watch_add(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Add a directory to watch."""
- watch_path = normalize_cli_path(path)
- try:
- data = _client().add_watch(WatchRequest(path=watch_path, removable=removable, label=label))
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot add watch target.")
-
- if json_mode:
- print_json(data)
- return
- print_success(f"Watch added: {data.path} (id={data.id})")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(
+ ctx,
+ lambda: _client().add_watch(
+ WatchRequest(path=normalize_cli_path(path), removable=removable, label=label)
+ ),
+ render=_render_watch_added,
+ )
@app.command("list")
def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
"""List watched directories."""
- try:
- data = _client().list_watches()
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot list watch targets.")
-
- if json_mode:
- print_json(data)
- return
-
- if not data.watches:
- print_info("No watches configured.")
- return
- for watch in data.watches:
- status = watch.status
- extra = " [removable]" if watch.removable else ""
- print(f" [{watch.id}] {watch.path}{extra} [{status}]")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _client().list_watches(), render=_render_watch_list)
@app.command("remove")
@@ -61,17 +47,14 @@ def watch_remove(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove a watched directory."""
- try:
+ ctx = CliContext(json_mode=json_mode)
+
+ def remove_watch() -> RemoveWatchResponse:
client = _client()
watch = _resolve_watch(client, target)
- result = client.remove_watch(watch.id)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot remove watch target.")
+ return client.remove_watch(watch.id)
- if json_mode:
- print_json(result)
- return
- print_success(f"Watch removed: {watch.path}")
+ run_cli(ctx, remove_watch, render=_render_watch_removed)
@app.command("rescan")
@@ -82,22 +65,52 @@ def watch_rescan(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Create a watch scan task for an existing watch target."""
- try:
- client = _client()
- watch = _resolve_watch(client, target)
- scan_info = client.create_scan(ScanRequest(path=watch.path, kind="watch", source="cli", watch_id=watch.id))
- if not no_wait and wait > 0:
- scan_info = _wait_for_scan(client, scan_info.id, wait)
- except Exception as exc:
- exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot rescan watch target.")
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, lambda: _rescan_watch(target, wait=wait, no_wait=no_wait), render=_render_scan)
+
- _print_scan(scan_info, json_mode=json_mode)
+def _rescan_watch(target: str, *, wait: int, no_wait: bool) -> CliTaskResult[ScanInfo]:
+ client = _client()
+ watch = _resolve_watch(client, target)
+ scan_info = client.create_scan(ScanRequest(path=watch.path, kind="watch", source="cli", watch_id=watch.id))
+ if not no_wait and wait > 0:
+ scan_info = _wait_for_scan(client, scan_info.id, wait)
+ return cli_task(scan_info, status=scan_info.status, render=_render_scan, fail_if_final_failed=not no_wait)
def _client() -> DoclibClient:
return DoclibClient(timeout=30)
+def _render_watch_added(data: WatchInfo) -> str:
+ return f"Watch added: {data.path} (id={data.id})"
+
+
+def _render_watch_list(data: WatchListResponse) -> Table | str:
+ if not data.watches:
+ return "No watches configured."
+ table = Table(title="Watches")
+ table.add_column("ID", justify="right")
+ table.add_column("Path", style="cyan")
+ table.add_column("Status", style="green")
+ table.add_column("Removable")
+ table.add_column("Label")
+ for watch in data.watches:
+ table.add_row(
+ str(watch.id),
+ watch.path,
+ watch.status,
+ "yes" if watch.removable else "no",
+ watch.label or "-",
+ )
+ return table
+
+
+def _render_watch_removed(data: RemoveWatchResponse) -> str:
+ action = "removed" if data.removed else "unchanged"
+ return f"Watch {data.watch_id} {action}."
+
+
def _resolve_watch(client: DoclibClient, target: str) -> WatchInfo:
watches = client.list_watches().watches
if target.isdigit():
@@ -105,10 +118,10 @@ def _resolve_watch(client: DoclibClient, target: str) -> WatchInfo:
for watch in watches:
if watch.id == watch_id:
return watch
- raise ValueError(f"watch_not_found: watch id {watch_id} not found")
+ raise MineruError("watch_not_found", f"Watch id {watch_id} not found.", "watch_id")
normalized = normalize_cli_path(target)
for watch in watches:
if normalize_cli_path(watch.path) == normalized:
return watch
- raise ValueError(f"watch_not_found: watch path {normalized} not found")
+ raise MineruError("watch_not_found", f"Watch path {normalized} not found.", "path")
diff --git a/mineru/cli/contracts.py b/mineru/cli/contracts.py
new file mode 100644
index 00000000..e202fb01
--- /dev/null
+++ b/mineru/cli/contracts.py
@@ -0,0 +1,38 @@
+"""Shared CLI runtime contracts."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass, field
+from typing import Generic, TypeAlias, TypeVar
+
+from rich.console import ConsoleRenderable
+
+T = TypeVar("T")
+RichObject: TypeAlias = ConsoleRenderable
+PlainObject: TypeAlias = str
+RenderableObject: TypeAlias = RichObject | PlainObject
+RenderableOutput: TypeAlias = RenderableObject | Iterable[RenderableObject]
+CliRenderer = Callable[[T], RenderableOutput | None]
+
+
+@dataclass(frozen=True)
+class CliContext:
+ json_mode: bool
+ verbose: bool = False
+
+
+@dataclass(frozen=True)
+class CliResult(Generic[T]):
+ data: T | None
+ render: CliRenderer[T] | None = None
+ exit_code: int = 0
+ warnings: list[str] = field(default_factory=list)
+ notices: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class CliTaskResult(CliResult[T]):
+ status: str | None = None
+ fail_statuses: frozenset[str] = frozenset({"failed"})
+ fail_if_final_failed: bool = False
diff --git a/mineru/cli/json_errors.py b/mineru/cli/json_errors.py
deleted file mode 100644
index c2da58ef..00000000
--- a/mineru/cli/json_errors.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Helpers for consistent CLI JSON error output."""
-
-from __future__ import annotations
-
-import ast
-from typing import NoReturn
-
-import typer
-
-from ..errors import MineruError, error_response
-from .output import print_error, print_json
-
-
-def to_mineru_error(exc: Exception, *, fallback_message: str | None = None) -> MineruError:
- if isinstance(exc, MineruError):
- return exc
- parsed = _parse_error_tuple(str(exc))
- if parsed is not None:
- code, message, param = parsed
- return MineruError(code, message, param)
- return MineruError("api_error", fallback_message or str(exc), None)
-
-
-def exit_with_error(exc: Exception, *, json_mode: bool, fallback_message: str | None = None) -> NoReturn:
- mineru_error = to_mineru_error(exc, fallback_message=fallback_message)
- if json_mode:
- print_json(error_response(mineru_error))
- else:
- print_error(mineru_error.message or str(exc))
- raise typer.Exit(1) from None
-
-
-def _parse_error_tuple(raw: str) -> tuple[str, str, str | None] | None:
- try:
- value = ast.literal_eval(raw)
- except (SyntaxError, ValueError):
- return None
- if not isinstance(value, tuple) or len(value) < 2 or not isinstance(value[0], str):
- return None
- param = value[2] if len(value) > 2 and isinstance(value[2], str) else None
- return value[0], str(value[1]), param
diff --git a/mineru/cli/main.py b/mineru/cli/main.py
index 230c3cdb..c29d4fdd 100644
--- a/mineru/cli/main.py
+++ b/mineru/cli/main.py
@@ -3,16 +3,32 @@
from __future__ import annotations
import sys
-from typing import Literal
+from dataclasses import dataclass
import typer
from click.core import Context
from typer.core import TyperGroup
-from ..types import Tier
from .commands import cleanup, config, list_resources, server, show, telemetry, watch
+from .commands.forget import forget_cmd
+from .commands.invalidate import invalidate_cmd
+from .commands.parse import parse_cmd
+from .commands.read import read_cmd
+from .commands.scan import scan_cmd
+from .commands.search import find_cmd, search_cmd
+from .contracts import CliContext
+from .runtime import run_cli
from .telemetry import prepare_cli_telemetry
+
+@dataclass(frozen=True)
+class VersionInfo:
+ mineru_version: str
+ python_version: str
+
+# Typer stores commands and command groups separately before building the Click
+# command tree, so source registration order alone does not preserve the mixed
+# top-level help order.
TOP_LEVEL_COMMAND_ORDER = [
"parse",
"read",
@@ -56,162 +72,42 @@ def root(ctx: typer.Context) -> None:
prepare_cli_telemetry(ctx)
-# top-level commands
-def parse(
- path: str = typer.Argument(..., help="Path to the document file"),
- tier: Tier | None = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro (default: server decides)"),
- pages: str = typer.Option(None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"),
- after: str = typer.Option(None, "--after", help="Continue reading after a content cursor"),
- limit: int = typer.Option(30000, "--limit", help="Soft character limit for STDOUT content"),
- format: Literal["markdown"] = typer.Option("markdown", "-f", "--format", help="Output format: markdown"),
- force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
- remote: bool = typer.Option(False, "--remote", help="Use remote parse-server"),
- wait: int = typer.Option(60, "--wait", help="Max seconds to wait for parse to complete"),
- no_wait: bool = typer.Option(False, "--no-wait", help="Don't wait — return immediately"),
- output: str = typer.Option(None, "-o", "--output", help="Output path; creates parent directories"),
- no_marker: bool = typer.Option(False, "--no-marker", help="Omit document structure markers from output"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
- verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),
-) -> None:
- """Parse a document file."""
- from .commands.parse import parse_cmd
-
- parse_cmd(
- path=path,
- tier=tier,
- pages=pages,
- after=after,
- limit=limit,
- format=format,
- force=force,
- remote=remote,
- wait=wait,
- no_wait=no_wait,
- output=output,
- no_marker=no_marker,
- json_mode=json_mode,
- verbose=verbose,
- )
-
-
-def read(
- locator: str = typer.Argument(..., help="Doclib locator, e.g. doc:ab12cd3/tier:standard/page:4"),
- context: int = typer.Option(0, "--context", help="Read N pages/blocks before and after the locator"),
- limit: int = typer.Option(30000, "--limit", help="Soft character limit for STDOUT content"),
- format: Literal["markdown", "image"] = typer.Option("markdown", "-f", "--format", help="Output format: markdown, image"),
- output: str = typer.Option(None, "-o", "--output", help="Output path; creates parent directories"),
- no_marker: bool = typer.Option(False, "--no-marker", help="Omit continuation marker from output"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
-) -> None:
- """Read parsed doclib content by locator."""
- from .commands.read import read_cmd
-
- read_cmd(
- locator=locator,
- context=context,
- limit=limit,
- format=format,
- output=output,
- no_marker=no_marker,
- json_mode=json_mode,
- )
-
-
-def scan(
- path: str = typer.Argument(..., help="File or directory path to scan"),
- wait: int = typer.Option(30, "--wait", help="Max seconds to wait for scan completion"),
- no_wait: bool = typer.Option(False, "--no-wait", help="Return immediately after creating the scan"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
-) -> None:
- """Create a one-off scan task."""
- from .commands.scan import scan_cmd
-
- scan_cmd(path=path, wait=wait, no_wait=no_wait, json_mode=json_mode)
-
-
+app.command("parse")(parse_cmd)
+app.command("read")(read_cmd)
+app.command("scan")(scan_cmd)
app.add_typer(watch.app, name="watch")
-
-
-def search(
- query: str = typer.Argument(..., help="Search query"),
- file_type: str | None = typer.Option(
- None,
- "--type",
- 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"),
- limit: int = typer.Option(20, "--limit", "-n", help="Max results"),
- offset: int = typer.Option(0, "--offset", help="Result offset"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
-) -> None:
- """Search parsed document content."""
- from .commands.search import search_cmd
-
- search_cmd(query=query, file_type=file_type, tier=tier, min_tier=min_tier, limit=limit, offset=offset, json_mode=json_mode)
-
-
-def find(
- query: str = typer.Argument(..., help="Filename search query"),
- ext: str | None = typer.Option(
- None,
- "--ext",
- 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"),
-) -> None:
- """Search filenames only (not document content)."""
- from .commands.search import find_cmd
-
- find_cmd(query=query, ext=ext, limit=limit, json_mode=json_mode)
-
-
+app.command("search")(search_cmd)
+app.command("find")(find_cmd)
app.add_typer(list_resources.app, name="list")
app.add_typer(show.app, name="show")
app.add_typer(telemetry.app, name="telemetry")
app.add_typer(server.app, name="server")
app.add_typer(config.app, name="config")
+app.command("invalidate")(invalidate_cmd)
+app.command("forget")(forget_cmd)
+app.add_typer(cleanup.app, name="cleanup")
@app.command()
-def invalidate(
- path: str = typer.Argument(..., help="Path to the document file"),
- tier: Tier | None = typer.Option(None, "--tier", help="Parse tier to invalidate (omit = all tiers)"),
-) -> None:
- """Mark done parse results as superseded so the next parse re-runs."""
- from .commands.invalidate import invalidate_cmd
-
- invalidate_cmd(path=path, tier=tier)
-
-
-def forget(
- path: str = typer.Argument(..., help="File or directory path to forget from doclib"),
- dry_run: bool = typer.Option(True, "--dry-run/--no-dry-run", help="Preview only"),
- json_mode: bool = typer.Option(False, "--json", help="JSON output"),
-) -> None:
- """Forget doclib records for a path without deleting source files."""
- from .commands.forget import forget_cmd
-
- forget_cmd(path=path, dry_run=dry_run, json_mode=json_mode)
+def version(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+ """Print MinerU and Python versions."""
+ ctx = CliContext(json_mode=json_mode)
+ run_cli(ctx, _version_info, render=_render_version)
-app.add_typer(cleanup.app, name="cleanup")
+def _version_info() -> VersionInfo:
+ from ..version import __version__
+ return VersionInfo(mineru_version=__version__, python_version=sys.version.split()[0])
-def version() -> None:
- """Print MinerU and Python versions."""
- from ..version import __version__
- typer.echo(f"MinerU version: {__version__}")
- typer.echo(f"Python version: {sys.version.split()[0]}")
+def _render_version(data: VersionInfo) -> str:
+ return "\n".join(
+ [
+ f"MinerU version: {data.mineru_version}",
+ f"Python version: {data.python_version}",
+ ]
+ )
def main() -> None:
diff --git a/mineru/cli/output.py b/mineru/cli/output.py
index a7de393d..8c44fa70 100644
--- a/mineru/cli/output.py
+++ b/mineru/cli/output.py
@@ -1,475 +1,40 @@
-"""Rich-based output formatting for mineru CLI."""
+"""Primitive output functions for MinerU CLI runtimes."""
from __future__ import annotations
import json
-import sys
-import time
+from dataclasses import asdict, is_dataclass
from typing import Any
from pydantic import BaseModel
from pydantic_core import to_json
+from rich.console import Console
+from rich.text import Text
-Table: Any
-Panel: Any
-Text: Any
-stderr_console: Any
+from .contracts import RenderableObject
-try:
- from rich.console import Console
- from rich.table import Table
- from rich.panel import Panel
- from rich.text import Text
- console = Console()
- stderr_console = Console(stderr=True)
-except ImportError:
- console = None
- stderr_console = None
+console = Console()
+stderr_console = Console(stderr=True)
+def print_rich(*objects: RenderableObject) -> None:
+ console.print(*objects)
-def print_error(msg: str) -> None:
- if stderr_console:
- text = Text("Error:", style="red")
- text.append(f" {msg}")
- stderr_console.print(text)
- else:
- print(f"Error: {msg}", file=sys.stderr)
-
-
-def print_success(msg: str) -> None:
- if console:
- console.print(msg, style="green")
- else:
- print(msg)
-
-def print_info(msg: str) -> None:
- if console:
- console.print(msg, style="dim")
- else:
- print(msg)
+def print_notice(msg: str) -> None:
+ stderr_console.print(msg, style="dim")
-def print_notice(msg: str) -> None:
- if stderr_console:
- stderr_console.print(msg, style="dim")
- else:
- print(msg, file=sys.stderr)
+def print_error(msg: str) -> None:
+ text = Text("Error:", style="red")
+ text.append(f" {msg}")
+ stderr_console.print(text)
def print_json(data: Any) -> None:
if isinstance(data, BaseModel):
print(to_json(data, indent=2).decode("utf-8"))
return
- print(json.dumps(data, ensure_ascii=False, indent=2))
-
-
-def _get(data: Any, key: str, default: Any = None) -> Any:
- if isinstance(data, dict):
- return data.get(key, default)
- return getattr(data, key, default)
-
-
-def _format_result_path(paths: Any) -> str:
- if not paths:
- return ""
- return f" ({paths[0]})"
-
-
-def _format_snippet(snippet: Any) -> str:
- return str(snippet or "").replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ")
-
-
-# ── parse ──────────────────────────────────────────────────────
-
-
-def format_parse_result(data: Any, json_mode: bool = False) -> None:
- if json_mode:
- print_json(data)
+ if is_dataclass(data) and not isinstance(data, type):
+ print(json.dumps(asdict(data), ensure_ascii=False, indent=2))
return
-
- status = _get(data, "status", "?")
- tip = _get(data, "tip", "")
-
- if status == "pending" or status == "parsing":
- print_info(f"Parse {status}... {tip}")
- elif status == "failed":
- print_error(f"Parse failed: {_get(data, 'error_code', '?')} — {_get(data, 'error_msg', '')}")
- else:
- print_success(f"Parse complete (tier={_get(data, 'tier', '?')}) {tip}")
-
-
-# ── search ─────────────────────────────────────────────────────
-
-
-def format_search_results(data: Any, json_mode: bool = False) -> None:
- results = _get(data, "results", [])
- total = _get(data, "total", 0)
-
- if json_mode:
- print_json(data)
- return
-
- if not results:
- print_info("No results found.")
- return
-
- lines = [f"Search results ({total} total)"]
- for index, result in enumerate(results, start=1):
- filename = _get(result, "title") or _get(result, "filename", "?")
- tier = _get(result, "tier", "")
- snippet = _format_snippet(_get(result, "snippet", ""))
- path = _format_result_path(_get(result, "paths", []))
- item_line = f"{index}. {filename}{path}"
- if tier:
- item_line += f" Tier: {tier}"
- lines.append(item_line)
- if snippet:
- lines.append(f" {snippet}")
- if index < len(results):
- lines.append("")
-
- output = "\n".join(lines)
- if console:
- console.print(Text(output))
- else:
- print(output)
-
-
-def format_find_results(data: Any, json_mode: bool = False) -> None:
- results = _get(data, "results", [])
- total = _get(data, "total", 0)
-
- if json_mode:
- print_json(data)
- return
-
- if not results:
- print_info("No results found.")
- return
-
- lines = [f"Search results ({total} total)"]
- for index, result in enumerate(results, start=1):
- filename = _get(result, "title") or _get(result, "filename", "?")
- path = _format_result_path(_get(result, "paths", []))
- lines.append(f"{index}. {filename}{path}")
- if index < len(results):
- lines.append("")
-
- output = "\n".join(lines)
- if console:
- console.print(Text(output))
- else:
- print(output)
-
-
-# ── server status ──────────────────────────────────────────────
-
-
-def format_server_status(data: Any, json_mode: bool = False) -> None:
- if json_mode:
- print_json(data)
- return
-
- if not _get(data, "running"):
- print_info("Server is not running.")
- return
-
- if console:
- table = Table(title="MinerU Server")
- table.add_column("Field", style="cyan")
- table.add_column("Current", style="green")
- table.add_row("PID", str(_get(data, "pid", "?")))
- table.add_row("Uptime", f"{_get(data, 'uptime_seconds', 0):.0f}s")
- table.add_row("Home", _get(data, "mineru_home", ""))
- table.add_row("Version", _get(data, "version", ""))
- table.add_row("Python", _get(data, "python_version", ""))
- table.add_row("Socket", _get(data, "socket_path", ""))
- table.add_row("Data dir", _get(data, "data_dir", ""))
- table.add_row("SQLite", _get(data, "sqlite_path", ""))
- table.add_row("SQLite size", _format_bytes(_get(data, "sqlite_size_bytes")))
- table.add_row("Log", _get(data, "log_path", ""))
- tcp_data = _get(data, "tcp")
- tcp_enabled = bool(_get(tcp_data, "enabled", False))
- tcp_host = _get(tcp_data, "host", "") or "-"
- tcp_port = _get(tcp_data, "port")
- if tcp_enabled:
- tcp_value = f"http://{tcp_host}:{tcp_port}" if tcp_port is not None else f"http://{tcp_host}:(pending)"
- else:
- tcp_value = "disabled"
- table.add_row("TCP", tcp_value)
- table.add_row("Files tracked", str(_get(data, "files_total", 0)))
- table.add_row("Docs indexed", str(_get(data, "docs_total", 0)))
- table.add_row("Active scans", str(_get(data, "active_scan_count", 0)))
- table.add_row("Last scan", _format_timestamp_ms(_get(data, "last_scan_at")))
- table.add_row("Parse queue", str(_get(data, "parse_queue_length", 0)))
- table.add_row("Ingest queue", str(_get(data, "ingest_queue_length", 0)))
- table.add_row("Watches", str(_get(data, "watch_count", 0)))
- console.print(table)
-
- workers = _get(data, "workers")
- if workers:
- worker_table = Table(title="Workers")
- worker_table.add_column("Component", style="cyan")
- worker_table.add_column("Running", style="green")
- worker_table.add_column("Workers", justify="right")
- worker_table.add_row("Watch", "yes" if _get(workers, "watch_running", False) else "no", "-")
- worker_table.add_row(
- "Scan",
- "yes" if _get(workers, "scan_running", False) else "no",
- str(_get(workers, "scan_workers", 0)),
- )
- worker_table.add_row(
- "Ingest",
- "yes" if _get(workers, "ingest_running", False) else "no",
- str(_get(workers, "ingest_workers", 0)),
- )
- worker_table.add_row(
- "Parse",
- "yes" if _get(workers, "parse_running", False) else "no",
- str(_get(workers, "parse_workers", 0)),
- )
- worker_table.add_row(
- "Device monitor",
- "yes" if _get(workers, "device_monitor_running", False) else "no",
- "-",
- )
- worker_table.add_row(
- "Compaction",
- "yes" if _get(workers, "compaction_running", False) else "no",
- "-",
- )
- worker_table.add_row(
- "Health check",
- "yes" if _get(workers, "health_check_running", False) else "no",
- "-",
- )
- console.print(worker_table)
-
- watch_stats = _get(data, "watch_stats", [])
- if watch_stats:
- watch_table = Table(title="Watch Stats")
- watch_table.add_column("Path", style="cyan", no_wrap=True)
- watch_table.add_column("Status", style="green")
- watch_table.add_column("Files", justify="right")
- watch_table.add_column("Active", justify="right")
- watch_table.add_column("Deleted", justify="right")
- watch_table.add_column("Unreachable", justify="right")
- watch_table.add_column("Pending ingest", justify="right")
- watch_table.add_column("Errors", justify="right")
- watch_table.add_column("Docs", justify="right")
- watch_table.add_column("Parses done/pending/parsing/failed", justify="right")
- for item in watch_stats:
- parse_counts = (
- f"{_get(item, 'parse_done_count', 0)}/"
- f"{_get(item, 'parse_pending_count', 0)}/"
- f"{_get(item, 'parse_parsing_count', 0)}/"
- f"{_get(item, 'parse_failed_count', 0)}"
- )
- watch_table.add_row(
- _get(item, "path", ""),
- _get(item, "status", ""),
- str(_get(item, "total_files", 0)),
- str(_get(item, "active_files", 0)),
- str(_get(item, "deleted_files", 0)),
- str(_get(item, "unreachable_files", 0)),
- str(_get(item, "pending_ingest_files", 0)),
- str(_get(item, "file_error_count", 0)),
- str(_get(item, "doc_count", 0)),
- parse_counts,
- )
- console.print(watch_table)
-
- error_summary = _get(data, "error_summary")
- error_rows = _error_summary_rows(error_summary)
- if error_rows:
- error_table = Table(title="Error Summary")
- error_table.add_column("Scope", style="cyan")
- error_table.add_column("Code", style="red")
- error_table.add_column("Count", justify="right")
- for scope, code, count in error_rows:
- error_table.add_row(scope, code, str(count))
- console.print(error_table)
-
- recent_scans = _get(data, "recent_scans", [])
- if recent_scans:
- scan_table = Table(title="Recent Scans")
- scan_table.add_column("ID", justify="right")
- scan_table.add_column("Kind", style="cyan")
- scan_table.add_column("Source")
- scan_table.add_column("Status", style="green")
- scan_table.add_column("Path", no_wrap=True)
- scan_table.add_column("Seen", justify="right")
- scan_table.add_column("New", justify="right")
- scan_table.add_column("Changed", justify="right")
- scan_table.add_column("Deleted", justify="right")
- scan_table.add_column("Errors", justify="right")
- scan_table.add_column("Error code", style="red")
- for item in recent_scans:
- scan_table.add_row(
- str(_get(item, "id", "")),
- _get(item, "kind", ""),
- _get(item, "source", ""),
- _get(item, "status", ""),
- _get(item, "path", ""),
- str(_get(item, "files_seen", 0)),
- str(_get(item, "files_new", 0)),
- str(_get(item, "files_changed", 0)),
- str(_get(item, "files_deleted", 0)),
- str(_get(item, "files_error", 0)),
- _get(item, "error_code", "") or "",
- )
- console.print(scan_table)
-
- # parse-server status
- ps_data = _get(data, "parse_server")
- if ps_data:
- ps_table = Table(title="Parse Server")
- ps_table.add_column("Target", style="cyan")
- ps_table.add_column("Healthy", style="green")
- ps_table.add_column("Endpoint", style="dim")
- ps_table.add_column("Managed", style="dim")
- ps_table.add_column("Restart", justify="right")
- ps_table.add_column("Last probe", style="dim")
- ps_table.add_column("Last ok", style="dim")
- ps_table.add_column("Last fail", style="dim")
- ps_table.add_column("Tiers", style="green")
- for label, key in [("Local", "local"), ("Remote", "remote")]:
- ps = _get(ps_data, key, {})
- if _get(ps, "starting"):
- healthy_str = "starting"
- elif _get(ps, "healthy"):
- healthy_str = "yes"
- else:
- healthy_str = "no"
- tiers_str = ", ".join(_get(ps, "supported_tiers", [])) or "-"
- mode = _get(ps, "mode", "")
- label_str = f"{label} ({mode})" if mode else label
- endpoint = _get(ps, "url", "") or "-"
- managed_str = "-"
- restart_str = "-"
- if key == "local":
- mode_text = _get(ps, "mode", "")
- if mode_text == "managed":
- managed_tier = _get(ps, "managed_tier", "") or "-"
- managed_pid = _get(ps, "managed_pid")
- managed_running = "yes" if _get(ps, "managed_running", False) else "no"
- managed_str = (
- f"tier={managed_tier}, pid={managed_pid or '-'}, running={managed_running}"
- )
- elif mode_text == "self_hosted":
- managed_str = _get(ps, "self_hosted_url", "") or "-"
- restart_str = f"{_get(ps, 'restart_count', 0)}/{_get(ps, 'max_restart_attempts', 0)}"
- ps_table.add_row(
- label_str,
- healthy_str,
- endpoint,
- managed_str,
- restart_str,
- _format_age_ms(_get(ps, "last_probe_at")),
- _format_age_ms(_get(ps, "last_success_at")),
- _format_age_ms(_get(ps, "last_failure_at")),
- tiers_str,
- )
- console.print(ps_table)
-
- for title, key in (
- ("Recent App Logs", "app_logs"),
- ("Recent Access Logs", "access_logs"),
- ("Recent Stderr Logs", "stderr_logs"),
- ("Recent Stdout Logs", "stdout_logs"),
- ):
- logs = _get(data, key, [])
- if logs:
- log_text = "".join(logs)
- panel = Panel(log_text.strip() or "(empty)", title=title, border_style="dim")
- console.print(panel)
- else:
- print(f"Server running (PID {_get(data, 'pid')}), {_get(data, 'files_total')} files")
-
-
-# ── info ───────────────────────────────────────────────────────
-
-
-def format_info(data: Any, json_mode: bool = False) -> None:
- if json_mode:
- print_json(data)
- return
-
- file_data = _get(data, "file")
- if not file_data:
- print_info("File not found in database.")
- return
- doc_data = _get(data, "doc")
-
- if console:
- table = Table(title=f"File Info: {_get(file_data, 'filename', '?')}")
- table.add_column("Field", style="cyan")
- table.add_column("Value", style="green")
- table.add_row("Path", _get(file_data, "path", "?"))
- table.add_row("Type", _get(file_data, "ext", "?"))
- table.add_row("Size", _format_bytes(_get(file_data, "size_bytes")))
- table.add_row("SHA-256", (_get(file_data, "sha256") or "")[:16] + "...")
- table.add_row("Page count", str(_get(doc_data, "page_count", "?") if doc_data else "?"))
- table.add_row("Title", (_get(doc_data, "title") if doc_data else None) or "—")
- table.add_row("Author", (_get(doc_data, "author") if doc_data else None) or "—")
-
- tiers = _get(data, "parsed_tiers", [])
- if tiers:
- tier_str = ", ".join(f"{_get(t, 'tier')}={_get(t, 'status')}" for t in tiers)
- table.add_row("Tiers", tier_str)
-
- console.print(table)
- else:
- print(f"{_get(file_data, 'filename')} — {(_get(doc_data, 'title') if doc_data else None) or 'No title'}")
-
-
-# ── helpers ────────────────────────────────────────────────────
-
-
-def _format_bytes(n: int | None) -> str:
- if n is None:
- return "?"
- for unit in ("B", "KB", "MB", "GB"):
- if n < 1024:
- return f"{n} {unit}"
- n //= 1024
- return f"{n} TB"
-
-
-def _format_timestamp_ms(ts: int | None) -> str:
- if ts is None:
- return "-"
- try:
- return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts / 1000))
- except Exception:
- return str(ts)
-
-
-def _format_age_ms(ts: int | None) -> str:
- if ts is None:
- return "-"
- try:
- age_seconds = max(0, int(time.time() - (ts / 1000)))
- except Exception:
- return str(ts)
- if age_seconds < 60:
- return f"{age_seconds}s ago"
- age_minutes = age_seconds // 60
- if age_minutes < 60:
- return f"{age_minutes}m ago"
- age_hours = age_minutes // 60
- if age_hours < 24:
- return f"{age_hours}h ago"
- age_days = age_hours // 24
- return f"{age_days}d ago"
-
-
-def _error_summary_rows(error_summary: Any) -> list[tuple[str, str, int]]:
- if not error_summary:
- return []
- rows: list[tuple[str, str, int]] = []
- for scope, key in (("file", "file_errors"), ("doc", "doc_errors"), ("parse", "parse_errors")):
- for bucket in _get(error_summary, key, []):
- rows.append((scope, _get(bucket, "code", ""), _get(bucket, "count", 0)))
- return rows
+ print(json.dumps(data, ensure_ascii=False, indent=2))
diff --git a/mineru/cli/runtime.py b/mineru/cli/runtime.py
new file mode 100644
index 00000000..191e4273
--- /dev/null
+++ b/mineru/cli/runtime.py
@@ -0,0 +1,189 @@
+"""Centralized CLI output, error, and exit-code runtime."""
+
+from __future__ import annotations
+
+import ast
+from collections.abc import Callable
+from typing import Any, NoReturn, TypeVar
+
+import httpx
+import typer
+
+from ..errors import MineruError, ServerNotRunningError, error_response
+from . import output
+from .contracts import CliContext, CliRenderer, CliResult, CliTaskResult, RenderableOutput, RichObject
+
+T = TypeVar("T")
+
+
+def cli_ok(
+ data: T | None = None,
+ *,
+ render: CliRenderer[T] | None = None,
+ exit_code: int = 0,
+ warnings: list[str] | None = None,
+ notices: list[str] | None = None,
+) -> CliResult[T]:
+ return CliResult(
+ data=data,
+ render=render,
+ exit_code=exit_code,
+ warnings=warnings or [],
+ notices=notices or [],
+ )
+
+
+def cli_task(
+ data: T,
+ *,
+ status: str | None,
+ render: CliRenderer[T] | None = None,
+ fail_if_final_failed: bool,
+ fail_statuses: frozenset[str] = frozenset({"failed"}),
+ warnings: list[str] | None = None,
+ notices: list[str] | None = None,
+) -> CliTaskResult[T]:
+ return CliTaskResult(
+ data=data,
+ render=render,
+ warnings=warnings or [],
+ notices=notices or [],
+ status=status,
+ fail_statuses=fail_statuses,
+ fail_if_final_failed=fail_if_final_failed,
+ )
+
+
+def run_cli(
+ ctx: CliContext,
+ action: Callable[[], T | CliResult[T]],
+ *,
+ render: CliRenderer[T] | None = None,
+ warnings: Callable[[T], list[str]] | None = None,
+ notices: Callable[[T], list[str]] | None = None,
+ exit_code: int | Callable[[T], int] = 0,
+) -> None:
+ try:
+ value = action()
+ except typer.Exit:
+ raise
+ except Exception as exc:
+ emit_error(ctx, exc)
+ result = _coerce_result(value, render=render, warnings=warnings, notices=notices, exit_code=exit_code)
+ emit_result(ctx, result)
+
+
+def emit_result(ctx: CliContext, result: CliResult[T]) -> None:
+ for notice in result.notices:
+ output.print_notice(notice)
+ for warning in result.warnings:
+ output.print_notice(warning)
+
+ if ctx.json_mode:
+ if result.data is not None:
+ output.print_json(result.data)
+
+ elif result.data is not None:
+ rendered_output: RenderableOutput | None
+ if result.render is not None:
+ rendered_output = result.render(result.data)
+ else:
+ rendered_output = str(result.data)
+ if rendered_output is not None:
+ _emit_rendered_output(rendered_output)
+
+ exit_code = _result_exit_code(result)
+ if exit_code:
+ raise typer.Exit(exit_code)
+
+
+def emit_error(ctx: CliContext, exc: Exception) -> NoReturn:
+ mineru_error = to_mineru_error(exc)
+ if ctx.json_mode:
+ output.print_json(error_response(mineru_error))
+ else:
+ output.print_error(mineru_error.message or str(exc))
+ raise typer.Exit(1) from None
+
+
+def _emit_rendered_output(rendered_output: RenderableOutput) -> None:
+ if isinstance(rendered_output, str):
+ print(rendered_output)
+ return
+ if isinstance(rendered_output, RichObject):
+ output.print_rich(rendered_output)
+ return
+ for item in rendered_output:
+ if isinstance(item, str):
+ print(item)
+ elif isinstance(item, RichObject):
+ output.print_rich(item)
+ else:
+ print(item)
+
+
+def to_mineru_error(exc: Exception) -> MineruError:
+ if isinstance(exc, MineruError):
+ return exc
+ if _is_connection_error(exc):
+ return ServerNotRunningError()
+ parsed = _parse_error_tuple(str(exc))
+ if parsed is not None:
+ code, message, param = parsed
+ return MineruError(code, message, param)
+ return MineruError("api_error", str(exc), None)
+
+
+def _result_exit_code(result: CliResult[Any]) -> int:
+ if (
+ isinstance(result, CliTaskResult)
+ and result.fail_if_final_failed
+ and result.status is not None
+ and result.status in result.fail_statuses
+ ):
+ return 1
+ return result.exit_code
+
+
+def _coerce_result(
+ value: T | CliResult[T],
+ *,
+ render: CliRenderer[T] | None,
+ warnings: Callable[[T], list[str]] | None,
+ notices: Callable[[T], list[str]] | None,
+ exit_code: int | Callable[[T], int],
+) -> CliResult[T]:
+ if isinstance(value, CliResult):
+ return value
+ resolved_exit_code = exit_code(value) if callable(exit_code) else exit_code
+ return cli_ok(
+ value,
+ render=render,
+ exit_code=resolved_exit_code,
+ warnings=warnings(value) if warnings is not None else None,
+ notices=notices(value) if notices is not None else None,
+ )
+
+
+def _parse_error_tuple(raw: str) -> tuple[str, str, str | None] | None:
+ try:
+ value = ast.literal_eval(raw)
+ except (SyntaxError, ValueError):
+ return None
+ if not isinstance(value, tuple) or len(value) < 2 or not isinstance(value[0], str):
+ return None
+ param = value[2] if len(value) > 2 and isinstance(value[2], str) else None
+ return value[0], str(value[1]), param
+
+
+def _is_connection_error(exc: Exception) -> bool:
+ return isinstance(
+ exc,
+ (
+ ConnectionRefusedError,
+ ConnectionResetError,
+ ConnectionAbortedError,
+ httpx.ConnectError,
+ httpx.ConnectTimeout,
+ ),
+ )
diff --git a/mineru/cli/telemetry.py b/mineru/cli/telemetry.py
index 44f4fef0..bd10065e 100644
--- a/mineru/cli/telemetry.py
+++ b/mineru/cli/telemetry.py
@@ -24,14 +24,23 @@ PROMPT_COMMANDS = {
"cleanup",
}
-TELEMETRY_CONSENT_MESSAGE = """Help improve MinerU by sending anonymous, locally aggregated usage and diagnostic data.
+TELEMETRY_CONSENT_MESSAGE = """
+Help improve MinerU by sending anonymous, locally aggregated usage and diagnostic data.
-Collected: command names, MinerU version, OS, architecture, Python version, install channel, coarse CPU/GPU categories, success/failure status, error categories, tiers, and performance timing buckets.
-Not collected: document contents, extracted text/images, file names, file paths, raw URLs, search queries, prompts, snippets, tracebacks, exception messages, hostnames, usernames, account IDs, API keys, or exact CPU/GPU models.
+Collected:
+ command names, MinerU version, OS, architecture, Python version, install channel,
+ coarse CPU/GPU categories, success/failure status, error categories, tiers,
+ and performance timing buckets.
+
+NOT collected:
+ document contents, extracted text/images, file names, file paths, raw URLs,
+ search queries, prompts, snippets, tracebacks, exception messages, hostnames,
+ usernames, account IDs, API keys, or exact CPU/GPU models.
Press Enter or type Y to enable, or type N to disable.
You can change this later with `mineru telemetry enable` or `mineru telemetry disable`.
-Preview what would be sent with `mineru telemetry preview`."""
+Preview what would be sent with `mineru telemetry preview`.
+""".strip()
def prepare_cli_telemetry(ctx: typer.Context) -> None:
diff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.py
index b71c8e4a..34e8f8d7 100644
--- a/mineru/doclib/background/ingest.py
+++ b/mineru/doclib/background/ingest.py
@@ -34,19 +34,30 @@ class IngestWorkerPool:
no_task_count = 0
while self.running:
- task = await self._acquire_task()
- if task is None:
- no_task_count += 1
- if no_task_count == 1 or no_task_count % 20 == 0:
- q = cast(
- CountRow | None,
- await self.parse_svc.db.fetchone(
- "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND status=? AND error_code IS NULL",
- (FILE_STATUS_ACTIVE,),
- ),
- )
- logger.debug(f"Ingest worker {worker_id}: queue={q['cnt'] if q else 0}")
- await asyncio.sleep(0.5)
+ try:
+ task = await self._acquire_task()
+ if task is None:
+ no_task_count += 1
+ if no_task_count == 1 or no_task_count % 20 == 0:
+ q = cast(
+ CountRow | None,
+ await self.parse_svc.db.fetchone(
+ "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND status=? AND error_code IS NULL",
+ (FILE_STATUS_ACTIVE,),
+ ),
+ )
+ logger.debug(f"Ingest worker {worker_id}: queue={q['cnt'] if q else 0}")
+ await asyncio.sleep(0.5)
+ continue
+ except Exception as exc:
+ logger.error(
+ "Ingest worker %s loop error: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
+ if self.running:
+ await asyncio.sleep(0.5)
continue
no_task_count = 0
diff --git a/mineru/doclib/background/parse_worker.py b/mineru/doclib/background/parse_worker.py
index 7fa5f5df..6cc6020f 100644
--- a/mineru/doclib/background/parse_worker.py
+++ b/mineru/doclib/background/parse_worker.py
@@ -33,13 +33,24 @@ class ParseWorkerPool:
no_task_count = 0
while self.running:
- task = await self.parse_svc.acquire_task()
- if task is None:
- no_task_count += 1
- if no_task_count == 1 or no_task_count % 20 == 0:
- q = await self.parse_svc.get_queue_length()
- logger.debug(f"Parse worker {worker_id}: queue={q}")
- await asyncio.sleep(0.5)
+ try:
+ task = await self.parse_svc.acquire_task()
+ if task is None:
+ no_task_count += 1
+ if no_task_count == 1 or no_task_count % 20 == 0:
+ q = await self.parse_svc.get_queue_length()
+ logger.debug(f"Parse worker {worker_id}: queue={q}")
+ await asyncio.sleep(0.5)
+ continue
+ except Exception as exc:
+ logger.error(
+ "Parse worker %s loop error: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
+ if self.running:
+ await asyncio.sleep(0.5)
continue
no_task_count = 0
diff --git a/mineru/doclib/background/scan_worker.py b/mineru/doclib/background/scan_worker.py
index 1b3c4438..2e31e9e8 100644
--- a/mineru/doclib/background/scan_worker.py
+++ b/mineru/doclib/background/scan_worker.py
@@ -27,9 +27,20 @@ class ScanWorkerPool:
logger.info("Scan worker %s started", worker_id)
processed = 0
while self.running:
- task = await self.scan_svc.acquire_task()
- if task is None:
- await asyncio.sleep(0.5)
+ try:
+ task = await self.scan_svc.acquire_task()
+ if task is None:
+ await asyncio.sleep(0.5)
+ continue
+ except Exception as exc:
+ logger.error(
+ "Scan worker %s loop error: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
+ if self.running:
+ await asyncio.sleep(0.5)
continue
try:
success = await self.scan_svc.process_scan(task)
diff --git a/mineru/doclib/base.py b/mineru/doclib/base.py
index e33f887d..4e98c155 100644
--- a/mineru/doclib/base.py
+++ b/mineru/doclib/base.py
@@ -111,7 +111,7 @@ class DoclibInterface(ABC):
self,
*,
ids: list[int] | None = None,
- sha256: str | None = None,
+ doc_ref: str | None = None,
tier: Tier | None = None,
status: ParseStatus | None = None,
page_range: str | None = None,
@@ -121,8 +121,10 @@ class DoclibInterface(ABC):
) -> ListParsesResponse:
"""List parse records and optional coverage information.
+ ``doc_ref`` accepts either a full content hash or a short id.
+
Raises:
- InvalidRequestError: for malformed ids, status filters, page ranges, or tier filters.
+ InvalidRequestError: for malformed document references, ids, status filters, page ranges, or tier filters.
MineruError: for server-side failures.
"""
raise NotImplementedError()
@@ -244,12 +246,12 @@ class DoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:
- """Return one doc by content hash.
+ def get_doc(self, doc_ref: str, *, expand_files: bool = False) -> DocInfo:
+ """Return one doc by content hash or short id.
Raises:
- NotFoundError: when ``sha256`` does not exist in doclib.
- InvalidRequestError: when ``sha256`` is malformed.
+ NotFoundError: when the document reference does not exist in doclib.
+ InvalidRequestError: when the document reference is malformed.
MineruError: for server-side failures.
"""
raise NotImplementedError()
@@ -257,7 +259,7 @@ class DoclibInterface(ABC):
@abstractmethod
def get_doc_content(
self,
- sha256: str,
+ doc_ref: str,
*,
tier: Tier,
page_range: str | None = None,
@@ -268,6 +270,8 @@ class DoclibInterface(ABC):
) -> DocContentResponse:
"""Render stored doc content from parsed JSON artifacts.
+ ``doc_ref`` accepts either a full content hash or a short id.
+
Raises:
NotFoundError: when the document or requested parsed content is not cached.
InvalidRequestError: when tier, page_range, format, or marker options are invalid.
@@ -295,9 +299,11 @@ class DoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:
+ def export_doc_content(self, doc_ref: str, request: DocContentExportRequest) -> DocContentExportResponse:
"""Render stored doc content and write it to a server-visible output path.
+ ``doc_ref`` accepts either a full content hash or a short id.
+
Raises:
NotFoundError: when the document or requested parsed content is not cached.
InvalidRequestError: when tier, page_range, format, output, or marker options are invalid.
@@ -555,7 +561,7 @@ class AsyncDoclibInterface(ABC):
self,
*,
ids: list[int] | None = None,
- sha256: str | None = None,
+ doc_ref: str | None = None,
tier: Tier | None = None,
status: ParseStatus | None = None,
page_range: str | None = None,
@@ -634,14 +640,14 @@ class AsyncDoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- async def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:
+ async def get_doc(self, doc_ref: str, *, expand_files: bool = False) -> DocInfo:
"""Async version of ``DoclibInterface.get_doc``."""
raise NotImplementedError()
@abstractmethod
async def get_doc_content(
self,
- sha256: str,
+ doc_ref: str,
*,
tier: Tier,
page_range: str | None = None,
@@ -667,7 +673,7 @@ class AsyncDoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- async def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:
+ async def export_doc_content(self, doc_ref: str, request: DocContentExportRequest) -> DocContentExportResponse:
"""Async version of ``DoclibInterface.export_doc_content``."""
raise NotImplementedError()
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index cf43491d..0c029752 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -132,7 +132,7 @@ class DoclibClient(DoclibInterface):
self,
*,
ids: list[int] | None = None,
- sha256: str | None = None,
+ doc_ref: str | None = None,
tier: Tier | None = None,
status: ParseStatus | None = None,
page_range: str | None = None,
@@ -144,7 +144,7 @@ class DoclibClient(DoclibInterface):
ListParsesResponse,
params={
"ids": ids,
- "sha256": sha256,
+ "doc_ref": doc_ref,
"tier": tier,
"status": status,
"page_range": page_range,
@@ -218,14 +218,14 @@ class DoclibClient(DoclibInterface):
def get_doc_by_path(self, path: str) -> DocInfo:
return self._request_model(DocInfo, params={"path": path})
- @route("GET", "/docs/{sha256}", tags=("docs",))
- def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:
- return self._request_model(DocInfo, path_params={"sha256": sha256}, params={"expand_files": expand_files})
+ @route("GET", "/docs/{doc_ref}", tags=("docs",))
+ def get_doc(self, doc_ref: str, *, expand_files: bool = False) -> DocInfo:
+ return self._request_model(DocInfo, path_params={"doc_ref": doc_ref}, params={"expand_files": expand_files})
- @route("GET", "/docs/{sha256}/content", tags=("docs",))
+ @route("GET", "/docs/{doc_ref}/content", tags=("docs",))
def get_doc_content(
self,
- sha256: str,
+ doc_ref: str,
*,
tier: Tier,
page_range: str | None = None,
@@ -236,7 +236,7 @@ class DoclibClient(DoclibInterface):
) -> DocContentResponse:
return self._request_model(
DocContentResponse,
- path_params={"sha256": sha256},
+ path_params={"doc_ref": doc_ref},
params={
"tier": tier,
"page_range": page_range,
@@ -268,9 +268,9 @@ class DoclibClient(DoclibInterface):
},
)
- @route("POST", "/docs/{sha256}/exports", tags=("docs",))
- def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:
- return self._request_model(DocContentExportResponse, path_params={"sha256": sha256}, body=request)
+ @route("POST", "/docs/{doc_ref}/exports", tags=("docs",))
+ def export_doc_content(self, doc_ref: str, request: DocContentExportRequest) -> DocContentExportResponse:
+ return self._request_model(DocContentExportResponse, path_params={"doc_ref": doc_ref}, body=request)
@route("GET", "/search", tags=("search",))
def search(
diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.py
index 6b74668f..43c954bc 100644
--- a/mineru/doclib/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -2,7 +2,9 @@ from __future__ import annotations
import os
import time
+from collections.abc import Awaitable, Callable
from pathlib import Path
+from typing import TypeVar
import aiosqlite
@@ -12,6 +14,7 @@ from ..config_defaults import CONFIG_DEFAULTS
SCHEMA_VERSION = 1
_MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
+_T = TypeVar("_T")
_CREATE_TABLES_SQL: list[str] = [] # filled by _load_init_sql()
@@ -57,60 +60,65 @@ class DatabaseManager:
"""Create tables, apply migrations, seed default data. Idempotent."""
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
conn = await aiosqlite.connect(self.db_path)
- await conn.execute("PRAGMA journal_mode=WAL")
- await conn.execute("PRAGMA foreign_keys=ON")
-
- if self.sqlite_cfg:
- await conn.execute(f"PRAGMA synchronous={self.sqlite_cfg.synchronous}")
- await conn.execute(f"PRAGMA mmap_size={self.sqlite_cfg.mmap_size}")
- await conn.execute(f"PRAGMA cache_size={self.sqlite_cfg.cache_size}")
- await conn.execute(f"PRAGMA temp_store={self.sqlite_cfg.temp_store}")
- await conn.execute(
- f"PRAGMA wal_autocheckpoint={self.sqlite_cfg.wal_autocheckpoint}"
- )
- await conn.execute(
- f"PRAGMA journal_size_limit={self.sqlite_cfg.journal_size_limit}"
- )
- else:
- await conn.execute("PRAGMA synchronous=NORMAL")
- await conn.execute("PRAGMA mmap_size=268435456")
- await conn.execute("PRAGMA cache_size=-20000")
- await conn.execute("PRAGMA temp_store=MEMORY")
- await conn.execute("PRAGMA wal_autocheckpoint=1000")
- await conn.execute("PRAGMA journal_size_limit=33554432")
-
- for sql in _CREATE_TABLES_SQL:
- await conn.execute(sql)
-
- # ── migrations ──────────────────────────────────────────
- for version in range(1, SCHEMA_VERSION + 1):
- cursor = await conn.execute(
- "SELECT 1 FROM _migrations WHERE version=?", (version,)
- )
- if await cursor.fetchone() is None:
- await _apply_migration(conn, version)
+ try:
+ await conn.execute("PRAGMA journal_mode=WAL")
+ await conn.execute("PRAGMA foreign_keys=ON")
+
+ if self.sqlite_cfg:
+ await conn.execute(f"PRAGMA synchronous={self.sqlite_cfg.synchronous}")
+ await conn.execute(f"PRAGMA mmap_size={self.sqlite_cfg.mmap_size}")
+ await conn.execute(f"PRAGMA cache_size={self.sqlite_cfg.cache_size}")
+ await conn.execute(f"PRAGMA temp_store={self.sqlite_cfg.temp_store}")
await conn.execute(
- "INSERT INTO _migrations (version, applied_at) VALUES (?, ?)",
- (version, _now_ms()),
+ f"PRAGMA wal_autocheckpoint={self.sqlite_cfg.wal_autocheckpoint}"
+ )
+ await conn.execute(
+ f"PRAGMA journal_size_limit={self.sqlite_cfg.journal_size_limit}"
+ )
+ else:
+ await conn.execute("PRAGMA synchronous=NORMAL")
+ await conn.execute("PRAGMA mmap_size=268435456")
+ await conn.execute("PRAGMA cache_size=-20000")
+ await conn.execute("PRAGMA temp_store=MEMORY")
+ await conn.execute("PRAGMA wal_autocheckpoint=1000")
+ await conn.execute("PRAGMA journal_size_limit=33554432")
+
+ for sql in _CREATE_TABLES_SQL:
+ await conn.execute(sql)
+
+ # ── migrations ──────────────────────────────────────────
+ for version in range(1, SCHEMA_VERSION + 1):
+ cursor = await conn.execute(
+ "SELECT 1 FROM _migrations WHERE version=?", (version,)
+ )
+ if await cursor.fetchone() is None:
+ await _apply_migration(conn, version)
+ await conn.execute(
+ "INSERT INTO _migrations (version, applied_at) VALUES (?, ?)",
+ (version, _now_ms()),
+ )
+
+ # ── seed data ───────────────────────────────────────────
+ # Config defaults are code-backed; the DB config table stores overrides only.
+ # Clean legacy seeded rows whose values exactly match current defaults.
+ for key, value in CONFIG_DEFAULTS.items():
+ await conn.execute("DELETE FROM config WHERE key=? AND value=?", (key, value))
+
+ now = _now_ms()
+ for name, pattern in DEFAULT_EXCLUDE_RULES:
+ await conn.execute(
+ "INSERT INTO exclude_rules (name, pattern, priority, created_at, updated_at) "
+ "SELECT ?, ?, 0, ?, ? "
+ "WHERE NOT EXISTS (SELECT 1 FROM exclude_rules WHERE pattern=?)",
+ (name, pattern, now, now, pattern),
)
- # ── seed data ───────────────────────────────────────────
- # Config defaults are code-backed; the DB config table stores overrides only.
- # Clean legacy seeded rows whose values exactly match current defaults.
- for key, value in CONFIG_DEFAULTS.items():
- await conn.execute("DELETE FROM config WHERE key=? AND value=?", (key, value))
-
- now = _now_ms()
- for name, pattern in DEFAULT_EXCLUDE_RULES:
- await conn.execute(
- "INSERT INTO exclude_rules (name, pattern, priority, created_at, updated_at) "
- "SELECT ?, ?, 0, ?, ? "
- "WHERE NOT EXISTS (SELECT 1 FROM exclude_rules WHERE pattern=?)",
- (name, pattern, now, now, pattern),
- )
-
- await conn.commit()
- await conn.close()
+ await conn.commit()
+ except Exception:
+ await self._rollback_quietly(conn)
+ raise
+ finally:
+ await conn.close()
async def _connect(self) -> aiosqlite.Connection:
conn = await aiosqlite.connect(self.db_path)
@@ -124,57 +132,68 @@ class DatabaseManager:
# ── query helpers ──────────────────────────────────────────────
- async def execute(self, sql: str, params: tuple | None = None) -> aiosqlite.Cursor:
+ async def _with_connection(self, operation: Callable[[aiosqlite.Connection], Awaitable[_T]]) -> _T:
conn = await self._connect()
- cursor = await conn.execute(sql, params or ())
- await conn.commit()
- await conn.close()
- return cursor
+ try:
+ result = await operation(conn)
+ await conn.commit()
+ return result
+ except Exception:
+ await self._rollback_quietly(conn)
+ raise
+ finally:
+ await conn.close()
+
+ @staticmethod
+ async def _rollback_quietly(conn: aiosqlite.Connection) -> None:
+ try:
+ await conn.rollback()
+ except Exception:
+ pass
+
+ async def execute(self, sql: str, params: tuple | None = None) -> aiosqlite.Cursor:
+ async def _operation(conn: aiosqlite.Connection) -> aiosqlite.Cursor:
+ return await conn.execute(sql, params or ())
+
+ return await self._with_connection(_operation)
async def execute_insert(self, sql: str, params: tuple | None = None) -> int:
- conn = await self._connect()
- cursor = await conn.execute(sql, params or ())
- await conn.commit()
- lastid = cursor.lastrowid
- await conn.close()
- if lastid is None:
- raise RuntimeError("SQLite insert did not return a row id.")
- return lastid
+ async def _operation(conn: aiosqlite.Connection) -> int:
+ cursor = await conn.execute(sql, params or ())
+ lastid = cursor.lastrowid
+ if lastid is None:
+ raise RuntimeError("SQLite insert did not return a row id.")
+ return lastid
+
+ return await self._with_connection(_operation)
async def fetchone(self, sql: str, params: tuple | None = None) -> dict | None:
- conn = await self._connect()
- cursor = await conn.execute(sql, params or ())
- row = await cursor.fetchone()
- result = dict(row) if row else None
- await conn.commit()
- await conn.close()
- return result
+ async def _operation(conn: aiosqlite.Connection) -> dict | None:
+ cursor = await conn.execute(sql, params or ())
+ row = await cursor.fetchone()
+ return dict(row) if row else None
+
+ return await self._with_connection(_operation)
async def fetchall(self, sql: str, params: tuple | None = None) -> list[dict]:
- conn = await self._connect()
- cursor = await conn.execute(sql, params or ())
- rows = await cursor.fetchall()
- result = [dict(row) for row in rows]
- await conn.commit()
- await conn.close()
- return result
+ async def _operation(conn: aiosqlite.Connection) -> list[dict]:
+ cursor = await conn.execute(sql, params or ())
+ rows = await cursor.fetchall()
+ return [dict(row) for row in rows]
+
+ return await self._with_connection(_operation)
async def commit(self) -> None:
pass
async def execute_atomic(self, statements: list[tuple[str, tuple]]) -> int:
"""Execute multiple statements in a single transaction."""
- conn = await self._connect()
- try:
+ async def _operation(conn: aiosqlite.Connection) -> int:
for sql, params in statements:
await conn.execute(sql, params)
- await conn.commit()
- except Exception:
- await conn.rollback()
- raise
- finally:
- await conn.close()
- return len(statements)
+ return len(statements)
+
+ return await self._with_connection(_operation)
# ── helpers ────────────────────────────────────────────────────────
diff --git a/mineru/doclib/rows.py b/mineru/doclib/rows.py
index 61155470..db4d5559 100644
--- a/mineru/doclib/rows.py
+++ b/mineru/doclib/rows.py
@@ -16,6 +16,7 @@ class FileRow(TypedDict):
size_bytes: int
mtime_ms: int
sha256: str | None
+ short_id: NotRequired[str | None]
watch_id: int | None
status: FileStatus
locked_at: int | None
@@ -48,6 +49,7 @@ class DocRow(TypedDict):
class ParseRow(TypedDict):
id: int
sha256: str
+ short_id: NotRequired[str]
tier: Tier
page_range: str
status: ParseStatus
@@ -210,6 +212,7 @@ class FilenameSearchFileRow(FileRow):
class ContentSearchResultRow(TypedDict):
sha256: str
+ short_id: str
title: str | None
author: str | None
filename: str | None
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 47c8703d..0b6215d4 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -42,6 +42,7 @@ from .rows import (
ParsingRuleRow,
RecentScanRow,
Sha256Row,
+ ShortIdRow,
WatchParseCountRow,
WatchStatsFileRow,
WatchTargetRow,
@@ -171,6 +172,7 @@ class _ReadPlan:
_PUBLIC_IMAGE_BUCKET_PATH = "images"
+_NO_MATCHING_DOC_SHA256 = "__mineru_no_matching_doc__"
@dataclass(frozen=True)
@@ -343,7 +345,7 @@ class DoclibServer(AsyncDoclibInterface):
self,
*,
ids: list[int] | None = None,
- sha256: str | None = None,
+ doc_ref: str | None = None,
tier: Tier | None = None,
status: ParseStatus | None = None,
page_range: str | None = None,
@@ -351,16 +353,17 @@ class DoclibServer(AsyncDoclibInterface):
limit: int = 50,
offset: int = 0,
) -> ListParsesResponse:
+ resolved_sha256 = await self._resolve_doc_filter_sha256(doc_ref)
rows, total, limit, offset = await self._select_parse_rows(
ids=ids,
- sha256=sha256,
+ sha256=resolved_sha256,
tier=tier,
status=status,
include_superseded=include_superseded,
limit=limit,
offset=offset,
)
- coverage = _parse_coverage(page_range, rows) if sha256 and tier and page_range else None
+ coverage = _parse_coverage(page_range, rows) if resolved_sha256 and tier and page_range else None
return ListParsesResponse(
parses=[_parse_info(row, coverage=coverage) for row in rows],
coverage=coverage,
@@ -371,7 +374,10 @@ class DoclibServer(AsyncDoclibInterface):
@route("GET", "/parses/{parse_id}", tags=("parse",))
async def get_parse(self, parse_id: int) -> ParseInfo:
- row = await self.state.db.fetchone("SELECT * FROM parses WHERE id=?", (parse_id,))
+ row = await self.state.db.fetchone(
+ "SELECT p.*, d.short_id AS short_id FROM parses p JOIN docs d ON d.sha256=p.sha256 WHERE p.id=?",
+ (parse_id,),
+ )
if row is None:
raise NotFoundError("job_not_found", f"Parse {parse_id} not found.", "parse_id")
return _parse_info(row)
@@ -380,15 +386,17 @@ class DoclibServer(AsyncDoclibInterface):
async def invalidate(self, request: InvalidateRequest) -> InvalidateResponse:
if request.target != "parses":
raise InvalidRequestError("invalid_request", f"Unsupported invalidate target: {request.target}", "target")
- sha256 = request.sha256
+ doc_row = await self._doc_for_ref(request.doc_ref, param="doc_ref") if request.doc_ref else None
+ sha256 = doc_row["sha256"] if doc_row else None
if sha256 is None and request.path:
file_row = await self.state.parse_svc.ensure_ingested(request.path)
sha256 = file_row["sha256"] if file_row and file_row.get("sha256") else None
if sha256 is None:
raise NotFoundError("file_not_found", "Document not found.", "path")
+ short_id = doc_row["short_id"] if doc_row else await self._short_id_for_sha256(sha256)
count = await self.state.parse_svc.invalidate(sha256, request.tier)
- return InvalidateResponse(target=request.target, sha256=sha256, tier=request.tier, invalidated_count=count)
+ return InvalidateResponse(target=request.target, sha256=sha256, short_id=short_id, tier=request.tier, invalidated_count=count)
@route("POST", "/forget", tags=("files",))
async def forget_path(self, request: ForgetPathRequest) -> ForgetPathResponse:
@@ -444,20 +452,26 @@ class DoclibServer(AsyncDoclibInterface):
limit = max(1, min(limit, 200))
offset = max(0, offset)
file_status = status or FILE_STATUS_ACTIVE
- clauses = ["status=?"]
+ clauses = ["f.status=?"]
params: list[Any] = [file_status]
if ext:
- clauses.append("ext=?")
+ clauses.append("f.ext=?")
params.append(ext.lstrip(".").lower())
if watch_id is not None:
- clauses.append("watch_id=?")
+ clauses.append("f.watch_id=?")
params.append(watch_id)
where = " AND ".join(clauses)
- total_row = await self.state.db.fetchone(f"SELECT COUNT(*) AS cnt FROM files WHERE {where}", tuple(params))
+ total_row = await self.state.db.fetchone(f"SELECT COUNT(*) AS cnt FROM files f WHERE {where}", tuple(params))
rows = cast(
list[FileRow],
await self.state.db.fetchall(
- f"SELECT * FROM files WHERE {where} ORDER BY updated_at DESC LIMIT ? OFFSET ?",
+ f"""
+ SELECT f.*, d.short_id AS short_id
+ FROM files f
+ LEFT JOIN docs d ON d.sha256=f.sha256
+ WHERE {where}
+ ORDER BY f.updated_at DESC LIMIT ? OFFSET ?
+ """,
(*params, limit, offset),
),
)
@@ -501,18 +515,16 @@ class DoclibServer(AsyncDoclibInterface):
raise NotFoundError("doc_not_found", f"Document for file {path} not found.", "path")
return _doc_info(row)
- @route("GET", "/docs/{sha256}", tags=("docs",))
- async def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:
- row = await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,))
- if row is None:
- raise NotFoundError("file_not_found", f"Document {sha256} not found.", "sha256")
- files = await self._files_for_sha256(sha256) if expand_files else None
+ @route("GET", "/docs/{doc_ref}", tags=("docs",))
+ async def get_doc(self, doc_ref: str, *, expand_files: bool = False) -> DocInfo:
+ row = await self._doc_for_ref(doc_ref, param="doc_ref")
+ files = await self._files_for_sha256(row["sha256"]) if expand_files else None
return _doc_info(row, files=files)
- @route("GET", "/docs/{sha256}/content", tags=("docs",))
+ @route("GET", "/docs/{doc_ref}/content", tags=("docs",))
async def get_doc_content(
self,
- sha256: str,
+ doc_ref: str,
*,
tier: Tier,
page_range: str | None = None,
@@ -527,7 +539,7 @@ class DoclibServer(AsyncDoclibInterface):
try:
response = await self._execute_read_plan(
await self._build_read_plan_from_parse(
- sha256,
+ doc_ref,
tier=tier,
page_range=page_range,
after=after,
@@ -581,7 +593,7 @@ class DoclibServer(AsyncDoclibInterface):
async def _build_read_plan_from_parse(
self,
- sha256: str,
+ doc_ref: str,
*,
tier: Tier,
page_range: str | None,
@@ -593,16 +605,14 @@ class DoclibServer(AsyncDoclibInterface):
if format != "markdown":
raise InvalidRequestError("invalid_request", "Only markdown is currently implemented for parse content.", "format")
limit = max(1, limit)
- doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,)))
- if doc is None:
- raise NotFoundError("doc_not_found", f"Document {sha256} not found.", "sha256")
+ doc = await self._doc_for_ref(doc_ref, param="doc_ref")
normalized_page_range = _normalize_content_page_range(page_range, after, doc)
after_cursor = parse_content_cursor(after) if after else None
if after_cursor:
_validate_cursor_for_doc(after_cursor, doc, tier, normalized_page_range)
return _ReadPlan(
- sha256=sha256,
+ sha256=doc["sha256"],
tier=tier,
short_id=doc["short_id"],
page_range=normalized_page_range,
@@ -664,14 +674,15 @@ class DoclibServer(AsyncDoclibInterface):
next_mode="read",
)
- @route("POST", "/docs/{sha256}/exports", tags=("docs",))
- async def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:
+ @route("POST", "/docs/{doc_ref}/exports", tags=("docs",))
+ async def export_doc_content(self, doc_ref: str, request: DocContentExportRequest) -> DocContentExportResponse:
start_ms = _now_ms()
dims = {"content_mode": "export", "output_format": _telemetry_output_format(request.format), "tier": request.tier}
await _record_telemetry_count(self.state, "content.request.count", dimensions=dims)
try:
+ doc = await self._doc_for_ref(doc_ref, param="doc_ref")
content = await self._render_doc_content(
- sha256,
+ doc["sha256"],
tier=request.tier,
page_range=request.page_range,
format=request.format,
@@ -684,7 +695,7 @@ class DoclibServer(AsyncDoclibInterface):
finished_dims = dims | {"status": "succeeded"}
await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)
await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)
- return DocContentExportResponse(sha256=sha256, tier=request.tier, output=output_path)
+ return DocContentExportResponse(sha256=doc["sha256"], short_id=doc["short_id"], tier=request.tier, output=output_path)
except Exception:
finished_dims = dims | {"status": "failed"}
await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)
@@ -750,13 +761,30 @@ class DoclibServer(AsyncDoclibInterface):
@route("GET", "/files/by-path", tags=("files",))
async def get_file_by_path(self, path: str) -> FileInfoResponse:
await self.state.parse_svc.ensure_ingested(path)
- file_row = await self.state.db.fetchone("SELECT * FROM files WHERE path=? AND status=?", (path, FILE_STATUS_ACTIVE))
+ file_row = await self.state.db.fetchone(
+ """
+ SELECT f.*, d.short_id AS short_id
+ FROM files f
+ LEFT JOIN docs d ON d.sha256=f.sha256
+ WHERE f.path=? AND f.status=?
+ """,
+ (path, FILE_STATUS_ACTIVE),
+ )
if file_row is None:
- raise NotFoundError("file_not_found", f"File {path} not found.", "path")
+ raise NotFoundError("file_not_found", f"File record {path} not found in doclib.", "path")
sha256 = file_row["sha256"]
doc_row = await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,)) if sha256 else None
parse_rows = (
- await self.state.db.fetchall("SELECT * FROM parses WHERE sha256=? ORDER BY tier, created_at DESC", (sha256,))
+ await self.state.db.fetchall(
+ """
+ SELECT p.*, d.short_id AS short_id
+ FROM parses p
+ JOIN docs d ON d.sha256=p.sha256
+ WHERE p.sha256=?
+ ORDER BY p.tier, p.created_at DESC
+ """,
+ (sha256,),
+ )
if sha256
else []
)
@@ -1010,32 +1038,41 @@ class DoclibServer(AsyncDoclibInterface):
if ids:
placeholders = ",".join("?" * len(ids))
rows = cast(
- list[ParseRow], await self.state.db.fetchall(f"SELECT * FROM parses WHERE id IN ({placeholders})", tuple(ids))
+ list[ParseRow],
+ await self.state.db.fetchall(
+ f"""
+ SELECT p.*, d.short_id AS short_id
+ FROM parses p
+ JOIN docs d ON d.sha256=p.sha256
+ WHERE p.id IN ({placeholders})
+ """,
+ tuple(ids),
+ ),
)
by_id = {row["id"]: row for row in rows}
ordered = [by_id[parse_id] for parse_id in ids if parse_id in by_id]
return ordered[offset : offset + limit], len(ordered), limit, offset
if sha256:
- clauses.append("sha256=?")
+ clauses.append("p.sha256=?")
params.append(sha256)
if tier:
- clauses.append("tier=?")
+ clauses.append("p.tier=?")
params.append(tier)
if status:
- clauses.append("status=?")
+ clauses.append("p.status=?")
params.append(status)
elif not include_superseded:
- clauses.append("status!=?")
+ clauses.append("p.status!=?")
params.append(PARSE_STATUS_SUPERSEDED)
- sql = "SELECT * FROM parses"
+ sql = "SELECT p.*, d.short_id AS short_id FROM parses p JOIN docs d ON d.sha256=p.sha256"
if clauses:
sql += " WHERE " + " AND ".join(clauses)
- count_sql = "SELECT COUNT(*) AS cnt FROM parses"
+ count_sql = "SELECT COUNT(*) AS cnt FROM parses p JOIN docs d ON d.sha256=p.sha256"
if clauses:
count_sql += " WHERE " + " AND ".join(clauses)
total_row = await self.state.db.fetchone(count_sql, tuple(params))
- sql += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
+ sql += " ORDER BY p.created_at DESC LIMIT ? OFFSET ?"
rows = cast(list[ParseRow], await self.state.db.fetchall(sql, (*params, limit, offset)))
total = total_row["cnt"] if total_row else 0
return rows, total, limit, offset
@@ -1171,10 +1208,44 @@ class DoclibServer(AsyncDoclibInterface):
)
return row["sha256"] if row and row["sha256"] else None
+ async def _doc_for_ref(self, doc_ref: str, *, param: str) -> DocRow:
+ row = await self._maybe_doc_for_ref(doc_ref)
+ if row is None:
+ raise NotFoundError("doc_not_found", f"Document {doc_ref} not found.", param)
+ return row
+
+ async def _maybe_doc_for_ref(self, doc_ref: str) -> DocRow | None:
+ row = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (doc_ref,)))
+ if row is not None:
+ return row
+ return cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE short_id=?", (doc_ref,)))
+
+ async def _resolve_doc_filter_sha256(self, doc_ref: str | None) -> str | None:
+ if doc_ref is None:
+ return None
+ doc = await self._maybe_doc_for_ref(doc_ref)
+ if doc is None:
+ return _NO_MATCHING_DOC_SHA256
+ return doc["sha256"]
+
+ async def _short_id_for_sha256(self, sha256: str) -> str:
+ row = cast(ShortIdRow | None, await self.state.db.fetchone("SELECT short_id FROM docs WHERE sha256=?", (sha256,)))
+ if row is None or not row["short_id"]:
+ raise NotFoundError("doc_not_found", f"Document {sha256} not found.", "sha256")
+ return row["short_id"]
+
async def _files_for_sha256(self, sha256: str) -> list[FileInfo]:
rows = cast(
list[FileRow],
- await self.state.db.fetchall("SELECT * FROM files WHERE sha256=? AND status=?", (sha256, FILE_STATUS_ACTIVE)),
+ await self.state.db.fetchall(
+ """
+ SELECT f.*, d.short_id AS short_id
+ FROM files f
+ JOIN docs d ON d.sha256=f.sha256
+ WHERE f.sha256=? AND f.status=?
+ """,
+ (sha256, FILE_STATUS_ACTIVE),
+ ),
)
return [_file_info(row) for row in rows]
diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.py
index 4f8737ca..4d8f018b 100644
--- a/mineru/doclib/services/cleanup_svc.py
+++ b/mineru/doclib/services/cleanup_svc.py
@@ -27,9 +27,7 @@ class CleanupService:
return cast(
list[DocRow],
await self.db.fetchall(
- "SELECT d.* FROM docs d WHERE NOT EXISTS ("
- " SELECT 1 FROM files f WHERE f.sha256 = d.sha256"
- ")"
+ "SELECT d.* FROM docs d WHERE NOT EXISTS ( SELECT 1 FROM files f WHERE f.sha256 = d.sha256)"
),
)
@@ -111,8 +109,13 @@ class CleanupService:
watches = cast(list[WatchTargetRow], await self.db.fetchall("SELECT * FROM watches WHERE enabled=1"))
file_ids = await self._forget_file_ids(normalized)
- if _is_watch_root(normalized, watches) and file_ids:
- raise InvalidRequestError("invalid_request", "Path is a configured watch root.", "path")
+ if file_ids and _is_watch_root(normalized, watches):
+ raise InvalidRequestError(
+ "invalid_request",
+ "Cannot forget a configured watch root while it contains tracked files."
+ " Remove the watch first or forget a child path.",
+ "path",
+ )
matched_as = await self._forget_matched_as(normalized, file_ids)
warnings = _forget_warnings(normalized, watches)
@@ -203,6 +206,10 @@ def _path_prefix(path: str) -> str:
return path if path.endswith(os.sep) else path + os.sep
+def _is_watch_root(path: str, watches: list[WatchTargetRow]) -> bool:
+ return any(watch["path"] == path for watch in watches)
+
+
def _active_watch_warning(path: str, watches: list[WatchTargetRow]) -> str | None:
for watch in watches:
watch_path = watch["path"]
diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.py
index 0f7c809e..697a631a 100644
--- a/mineru/doclib/services/config_svc.py
+++ b/mineru/doclib/services/config_svc.py
@@ -87,9 +87,9 @@ class ConfigService:
self, path: str, removable: bool = False, label: str | None = None
) -> WatchTargetRow:
if not os.path.isabs(path):
- raise ValueError(f"Path must be absolute: {path}")
+ raise InvalidRequestError("invalid_request", f"Watch path must be absolute: {path}", "path")
if os.path.normpath(path) != path:
- raise ValueError(f"Path must be normalized: {path}")
+ raise InvalidRequestError("invalid_request", f"Watch path must be normalized: {path}", "path")
if not os.path.isdir(path):
raise InvalidRequestError("invalid_request", f"Watch path does not exist or is not a directory: {path}", "path")
@@ -191,7 +191,7 @@ class ConfigService:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(name, pattern, tier, page_range, int(remote), priority, now, now),
)
- raise ValueError(f"Unsupported rule type: {rule_type}")
+ raise _unsupported_rule_type_error(rule_type)
async def list_rules(self, rule_type: RuleType | None = None) -> list[RuleRow]:
if rule_type == RULE_TYPE_EXCLUDE:
@@ -215,7 +215,7 @@ class ConfigService:
),
)
if rule_type is not None:
- raise ValueError(f"Unsupported rule type: {rule_type}")
+ raise _unsupported_rule_type_error(rule_type)
return cast(
list[RuleRow],
await self.db.fetchall(
@@ -239,7 +239,7 @@ class ConfigService:
await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))
return
if rule_type is not None:
- raise ValueError(f"Unsupported rule type: {rule_type}")
+ raise _unsupported_rule_type_error(rule_type)
await self.db.execute("DELETE FROM exclude_rules WHERE id=?", (rule_id,))
await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))
@@ -268,4 +268,8 @@ def _rule_table(rule_type: RuleType) -> str:
return "exclude_rules"
if rule_type == RULE_TYPE_PARSING_RULE:
return "parsing_rules"
- raise ValueError(f"Unsupported rule type: {rule_type}")
+ raise _unsupported_rule_type_error(rule_type)
+
+
+def _unsupported_rule_type_error(rule_type: RuleType) -> InvalidRequestError:
+ return InvalidRequestError("invalid_request", f"Unsupported rule type: {rule_type}", "rule_type")
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index cff08056..accffd65 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -20,7 +20,7 @@ from ..constants import IMAGE_EXTENSIONS, PARSEABLE_EXTENSIONS, TEXT_EXTENSIONS,
from ..core.db import DatabaseManager
from ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_stat
from ..core.fts import FTSManager
-from ..rows import FileRow, PageCountRow, ParseBatchRow, ParseRow, Sha256Row, ShortIdRow, WatchTargetRow
+from ..rows import DocRow, FileRow, ParseBatchRow, ParseRow, Sha256Row, ShortIdRow, WatchTargetRow
from ..types import (
FILE_STATUS_ACTIVE,
FILE_STATUS_DELETED,
@@ -665,8 +665,9 @@ class ParseService:
sha256 = file_row["sha256"]
if sha256 is None:
return _failed_response(tier or "flash", page_range or "", "File could not be ingested.")
- doc = cast(PageCountRow | None, await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,)))
+ doc = cast(DocRow | None, await self.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,)))
page_count = doc["page_count"] if doc else 1
+ short_id = doc["short_id"] if doc else None
privacy = "remote" if remote else "local"
ext = file_row["ext"]
@@ -690,7 +691,7 @@ class ParseService:
"tier",
)
if ext in TEXT_EXTENSIONS:
- return _text_response(sha256)
+ return _text_response(sha256, short_id)
if ext in QUALITY_TIER_EXTENSIONS:
requested_tier = tier or _resolve_default_tier(remote)
else:
@@ -718,7 +719,7 @@ class ParseService:
needed_page_numbers -= covered_page_numbers
if not needed_page_numbers:
- return _done_response(sha256, requested_tier, request_page_range)
+ return _done_response(sha256, short_id, requested_tier, request_page_range)
# ── step 2: remove page numbers covered by pending/parsing batches ──
reused_parse_ids: list[int] = []
@@ -750,6 +751,7 @@ class ParseService:
if not needed_page_numbers:
return ParseResponse(
sha256=sha256,
+ short_id=short_id,
tier=requested_tier,
page_range=request_page_range,
status=PARSE_STATUS_PENDING,
@@ -772,6 +774,7 @@ class ParseService:
created_parse_ids = [parse_id]
return ParseResponse(
sha256=sha256,
+ short_id=short_id,
tier=requested_tier,
page_range=request_page_range,
status=PARSE_STATUS_PENDING,
@@ -902,7 +905,7 @@ class ParseService:
await self._record_parse_task_finished(task_start_ms, tier=tier, status="failed", error_code="parse_failed")
return False
- # save per-batch JSON (markdown is generated on read from /docs/{sha256}/content)
+ # save per-batch JSON (markdown is generated on read from /docs/{doc_ref}/content)
done_at_ms = _now_ms()
json_path = os.path.join(output_dir, _safe_filename(page_range, done_at_ms))
write_start_ms = _now_ms()
@@ -1389,9 +1392,10 @@ def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_ro
return [pages_by_page_idx[page_idx] for page_idx in sorted(pages_by_page_idx)]
-def _done_response(sha256: str, tier: Tier, page_range: str) -> ParseResponse:
+def _done_response(sha256: str, short_id: str | None, tier: Tier, page_range: str) -> ParseResponse:
return ParseResponse(
sha256=sha256,
+ short_id=short_id,
tier=tier,
page_range=page_range,
status=PARSE_STATUS_DONE,
@@ -1403,9 +1407,10 @@ def _done_response(sha256: str, tier: Tier, page_range: str) -> ParseResponse:
)
-def _text_response(sha256: str) -> ParseResponse:
+def _text_response(sha256: str, short_id: str | None) -> ParseResponse:
return ParseResponse(
sha256=sha256,
+ short_id=short_id,
tier="flash",
page_range="1",
status=PARSE_STATUS_DONE,
diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.py
index f0557e0e..998868ba 100644
--- a/mineru/doclib/services/search_svc.py
+++ b/mineru/doclib/services/search_svc.py
@@ -42,7 +42,7 @@ class SearchService:
# join with docs + files
placeholders = ",".join("?" * len(sha256s))
sql = (
- "SELECT f.*, d.title, d.author, d.page_count, d.file_type "
+ "SELECT f.*, d.short_id, d.title, d.author, d.page_count, d.file_type "
"FROM files f JOIN docs d ON f.sha256 = d.sha256 "
f"WHERE f.sha256 IN ({placeholders})"
)
@@ -81,6 +81,7 @@ class SearchService:
results.append(
{
"sha256": sha,
+ "short_id": fts_file["short_id"],
"title": row.get("title") or fts_file.get("title"),
"author": row.get("author") or fts_file.get("author"),
"filename": row.get("filename") or fts_file.get("filename"),
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index 1ff3bf93..b8476357 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -99,6 +99,7 @@ class ParseRequest(DoclibModel):
class ParseResponse(DoclibModel):
sha256: str
+ short_id: str | None = None
tier: Tier
page_range: str
status: ParseStatus
@@ -118,6 +119,7 @@ class ParseCoverage(DoclibModel):
class ParseInfo(DoclibModel):
id: int
sha256: str
+ short_id: str
tier: Tier
page_range: str
status: ParseStatus
@@ -143,13 +145,14 @@ class ListParsesResponse(DoclibModel):
class InvalidateRequest(DoclibModel):
target: InvalidateTarget = "parses"
path: str | None = None
- sha256: str | None = None
+ doc_ref: str | None = None
tier: Tier | None = None
class InvalidateResponse(DoclibModel):
target: str
sha256: str
+ short_id: str
tier: Tier | None = None
invalidated_count: int
@@ -212,6 +215,7 @@ class FileInfo(DoclibModel):
size_bytes: int
mtime_ms: int
sha256: str | None = None
+ short_id: str | None = None
watch_id: int | None = None
status: FileStatus
error_code: str | None = None
@@ -306,12 +310,14 @@ class DocContentExportRequest(DoclibModel):
class DocContentExportResponse(DoclibModel):
sha256: str
+ short_id: str
tier: Tier
output: str
class SearchResult(DoclibModel):
sha256: str
+ short_id: str
title: str | None = None
author: str | None = None
filename: str | None = None
diff --git a/mineru/errors.py b/mineru/errors.py
index c00efa21..54bb18bb 100644
--- a/mineru/errors.py
+++ b/mineru/errors.py
@@ -35,6 +35,17 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {
"model_not_found": "invalid_request_error",
"not_cached": "invalid_request_error",
"no_accessible_file": "invalid_request_error",
+ "asset_not_available": "invalid_request_error",
+ "block_not_found": "invalid_request_error",
+ "doc_not_found": "invalid_request_error",
+ "page_not_cached": "invalid_request_error",
+ "tier_not_cached": "invalid_request_error",
+ "bbox_not_available": "invalid_request_error",
+ "context_not_applicable": "invalid_request_error",
+ "format_not_supported": "invalid_request_error",
+ "invalid_config_key": "invalid_request_error",
+ "invalid_locator": "invalid_request_error",
+ "multi_page_image_not_supported": "invalid_request_error",
"rule_not_found": "invalid_request_error",
"scan_not_found": "invalid_request_error",
"stat_failed": "invalid_request_error",
@@ -56,6 +67,7 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {
"engine_unavailable": "engine_error",
"parse_empty": "engine_error",
"parse_failed": "engine_error",
+ "parse_page_remap_failed": "engine_error",
"parse_timeout": "engine_error",
"quality_tier_unavailable": "engine_error",
# api_error
@@ -85,11 +97,16 @@ _ERROR_STATUS_MAP: dict[ErrorType, int] = {
_ERROR_CODE_STATUS_MAP: dict[str, int] = {
"file_not_found": 404,
+ "asset_not_available": 404,
+ "block_not_found": 404,
+ "doc_not_found": 404,
"job_not_found": 404,
"model_not_found": 404,
"not_cached": 404,
+ "page_not_cached": 404,
"rule_not_found": 404,
"scan_not_found": 404,
+ "tier_not_cached": 404,
"upload_not_found": 404,
"watch_not_found": 404,
}
diff --git a/tests/unittest/test_cli_command_contract.py b/tests/unittest/test_cli_command_contract.py
new file mode 100644
index 00000000..ffd34479
--- /dev/null
+++ b/tests/unittest/test_cli_command_contract.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+
+CLI_COMMANDS_DIR = Path(__file__).parents[2] / "mineru" / "cli" / "commands"
+CLI_MAIN = Path(__file__).parents[2] / "mineru" / "cli" / "main.py"
+CLI_RENDERERS = Path(__file__).parents[2] / "mineru" / "cli" / "renderers.py"
+
+ALLOWED_PRINT_ERROR_CALLS: set[tuple[str, str]] = set()
+
+ALLOWED_TYPER_EXIT_CALLS: set[tuple[str, str]] = set()
+
+ALLOWED_EXIT_WITH_ERROR_CALLS: set[tuple[str, str]] = set()
+
+ALLOWED_EMIT_RESULT_CALLS = {
+ ("commands/parse.py", "_emit_notice"),
+ ("commands/parse.py", "_parse"),
+ ("commands/parse.py", "_output_parse_result"),
+ ("commands/parse.py", "_emit_parse_json_response"),
+}
+
+MIGRATED_QUERY_COMMANDS = {
+ "commands/config.py",
+ "commands/cleanup.py",
+ "commands/forget.py",
+ "commands/invalidate.py",
+ "commands/list_resources.py",
+ "commands/parse.py",
+ "commands/read.py",
+ "commands/scan.py",
+ "commands/search.py",
+ "commands/server.py",
+ "commands/show.py",
+ "commands/telemetry.py",
+ "commands/watch.py",
+}
+
+ALLOWED_DIRECT_OUTPUT_CALLS: set[tuple[str, str, str]] = set()
+
+DIRECT_OUTPUT_NAMES = {
+ "print",
+ "print_info",
+ "print_json",
+ "print_success",
+}
+
+
+def test_cli_commands_do_not_add_unreviewed_direct_error_output_or_exit() -> None:
+ print_error_calls: set[tuple[str, str]] = set()
+ typer_exit_calls: set[tuple[str, str]] = set()
+ exit_with_error_calls: set[tuple[str, str]] = set()
+ emit_result_calls: set[tuple[str, str]] = set()
+
+ for path in [*sorted(CLI_COMMANDS_DIR.glob("*.py")), CLI_MAIN]:
+ module = ast.parse(path.read_text(encoding="utf-8"))
+ parents = _parent_map(module)
+ rel_path = _relative_cli_path(path)
+ for node in ast.walk(module):
+ if not isinstance(node, ast.Call):
+ continue
+ function_name = _enclosing_function_name(node, parents)
+ if _is_name_call(node, "print_error"):
+ print_error_calls.add((rel_path, function_name))
+ if _is_typer_exit_call(node):
+ typer_exit_calls.add((rel_path, function_name))
+ if _is_name_call(node, "exit_with_error"):
+ exit_with_error_calls.add((rel_path, function_name))
+ if _is_name_call(node, "emit_result"):
+ emit_result_calls.add((rel_path, function_name))
+
+ assert print_error_calls <= ALLOWED_PRINT_ERROR_CALLS
+ assert typer_exit_calls <= ALLOWED_TYPER_EXIT_CALLS
+ assert exit_with_error_calls <= ALLOWED_EXIT_WITH_ERROR_CALLS
+ assert emit_result_calls <= ALLOWED_EMIT_RESULT_CALLS
+
+
+def test_migrated_query_commands_do_not_write_output_directly() -> None:
+ direct_output_calls: set[tuple[str, str, str]] = set()
+
+ for path in sorted(CLI_COMMANDS_DIR.glob("*.py")):
+ rel_path = _relative_cli_path(path)
+ if rel_path not in MIGRATED_QUERY_COMMANDS:
+ continue
+ module = ast.parse(path.read_text(encoding="utf-8"))
+ parents = _parent_map(module)
+ for node in ast.walk(module):
+ if not isinstance(node, ast.Call):
+ continue
+ function_name = _enclosing_function_name(node, parents)
+ output_name = _direct_output_call_name(node)
+ if output_name is not None:
+ direct_output_calls.add((rel_path, function_name, output_name))
+
+ assert direct_output_calls <= ALLOWED_DIRECT_OUTPUT_CALLS
+
+
+def test_cli_renderers_do_not_use_any_annotations() -> None:
+ any_annotations: set[tuple[str, str]] = set()
+
+ renderer_paths = [CLI_RENDERERS] if CLI_RENDERERS.exists() else []
+ for path in [*renderer_paths, *sorted(CLI_COMMANDS_DIR.glob("*.py"))]:
+ module = ast.parse(path.read_text(encoding="utf-8"))
+ rel_path = _relative_cli_path(path) if path != CLI_RENDERERS else "renderers.py"
+ for node in ast.walk(module):
+ if not isinstance(node, ast.FunctionDef) or not _is_render_function(node):
+ continue
+ for arg in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]:
+ if _annotation_uses_any(arg.annotation):
+ any_annotations.add((rel_path, f"{node.name}.{arg.arg}"))
+ if _annotation_uses_any(node.returns):
+ any_annotations.add((rel_path, f"{node.name}.return"))
+
+ assert any_annotations == set()
+
+
+def test_migrated_query_commands_do_not_use_cliresult_wrapper_helpers() -> None:
+ wrapper_helpers: set[tuple[str, str]] = set()
+
+ for path in sorted(CLI_COMMANDS_DIR.glob("*.py")):
+ rel_path = _relative_cli_path(path)
+ if rel_path not in MIGRATED_QUERY_COMMANDS:
+ continue
+ module = ast.parse(path.read_text(encoding="utf-8"))
+ for node in ast.walk(module):
+ if (
+ isinstance(node, ast.FunctionDef)
+ and node.name.startswith("_")
+ and _annotation_is_cliresult(node.returns)
+ ):
+ wrapper_helpers.add((rel_path, node.name))
+
+ assert wrapper_helpers == set()
+
+
+def _parent_map(module: ast.AST) -> dict[ast.AST, ast.AST]:
+ parents: dict[ast.AST, ast.AST] = {}
+ for parent in ast.walk(module):
+ for child in ast.iter_child_nodes(parent):
+ parents[child] = parent
+ return parents
+
+
+def _relative_cli_path(path: Path) -> str:
+ cli_dir = Path(__file__).parents[2] / "mineru" / "cli"
+ return path.relative_to(cli_dir).as_posix()
+
+
+def _enclosing_function_name(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> str:
+ current = node
+ while current in parents:
+ current = parents[current]
+ if isinstance(current, ast.FunctionDef):
+ return current.name
+ return "<module>"
+
+
+def _is_name_call(node: ast.Call, name: str) -> bool:
+ return isinstance(node.func, ast.Name) and node.func.id == name
+
+
+def _is_typer_exit_call(node: ast.Call) -> bool:
+ return (
+ isinstance(node.func, ast.Attribute)
+ and node.func.attr == "Exit"
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "typer"
+ )
+
+
+def _direct_output_call_name(node: ast.Call) -> str | None:
+ if isinstance(node.func, ast.Name) and node.func.id in DIRECT_OUTPUT_NAMES:
+ return node.func.id
+ if (
+ isinstance(node.func, ast.Attribute)
+ and node.func.attr == "echo"
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "typer"
+ ):
+ return "typer.echo"
+ return None
+
+
+def _annotation_uses_any(annotation: ast.AST | None) -> bool:
+ if annotation is None:
+ return False
+ for node in ast.walk(annotation):
+ if isinstance(node, ast.Name) and node.id == "Any":
+ return True
+ if isinstance(node, ast.Attribute) and node.attr == "Any":
+ return True
+ return False
+
+
+def _annotation_is_cliresult(annotation: ast.AST | None) -> bool:
+ if annotation is None:
+ return False
+ if isinstance(annotation, ast.Name):
+ return annotation.id == "CliResult"
+ if isinstance(annotation, ast.Attribute):
+ return annotation.attr == "CliResult"
+ if isinstance(annotation, ast.Subscript):
+ return _annotation_is_cliresult(annotation.value)
+ return False
+
+
+def _is_render_function(node: ast.FunctionDef) -> bool:
+ return node.name.startswith("render_") or node.name.startswith("_render_")
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index b1cadbcd..42b1291c 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -8,10 +8,12 @@ from pathlib import Path
from typing import Any
import pytest
+from typer.main import get_command
from typer.testing import CliRunner
from mineru.cli.commands import config, invalidate, list_resources, parse, read, server, show, telemetry
from mineru.cli.commands import cleanup as cleanup_cmd
+from mineru.cli.commands import scan as scan_mod
from mineru.cli.commands import search as search_mod
from mineru.cli.commands import watch as watch_cmd
from mineru.cli import output as output_mod
@@ -23,25 +25,53 @@ from mineru.doclib.types import (
ContentNextRequest,
ContentRange,
ContentRequestScope,
+ ConfigResponse,
ConfigSetResponse,
DocInfo,
DocContentResponse,
+ ExcludeRuleInfo,
+ ExcludeRuleListResponse,
FileInfo,
FileInfoResponse,
+ FindResponse,
+ FindResult,
InvalidateResponse,
+ ListDocsResponse,
+ ListFilesResponse,
ListParsesResponse,
+ ParsingRuleInfo,
+ ParsingRuleListResponse,
ParseInfo,
ParseResponse,
+ ScanListResponse,
+ ScanInfo,
+ SearchResponse,
+ SearchResult,
+ ServerStatusResponse,
TelemetryActionResponse,
TelemetryStatusResponse,
WatchInfo,
+ WatchListResponse,
)
+from mineru.errors import ServerNotRunningError
from mineru.version import __version__
runner = CliRunner()
+class _FakeTable:
+ def __init__(self, *, title: str) -> None:
+ self.title = title
+ self.rows: list[tuple[str, ...]] = []
+
+ def add_column(self, *args: Any, **kwargs: Any) -> None:
+ pass
+
+ def add_row(self, *values: str) -> None:
+ self.rows.append(tuple(values))
+
+
def test_cli_next_exposes_list_and_show_resource_trees() -> None:
list_result = runner.invoke(app, ["list", "--help"])
show_result = runner.invoke(app, ["show", "--help"])
@@ -83,11 +113,35 @@ def test_version_command_prints_mineru_and_python_versions() -> None:
assert f"Python version: {sys.version.split()[0]}" in result.output
-def test_version_command_is_last_in_root_help() -> None:
- result = runner.invoke(app, ["--help"])
+def test_version_json_writes_single_json_object() -> None:
+ result = runner.invoke(app, ["version", "--json"])
assert result.exit_code == 0
- assert result.output.rfind("version") > result.output.rfind("cleanup")
+ payload = json.loads(result.output)
+ assert payload == {"mineru_version": __version__, "python_version": sys.version.split()[0]}
+ assert "MinerU version:" not in result.output
+
+
+def test_root_commands_keep_product_order() -> None:
+ command = get_command(app)
+
+ assert command.list_commands(None) == [
+ "parse",
+ "read",
+ "scan",
+ "watch",
+ "search",
+ "find",
+ "list",
+ "show",
+ "telemetry",
+ "server",
+ "config",
+ "invalidate",
+ "forget",
+ "cleanup",
+ "version",
+ ]
def test_root_help_hides_typer_completion_options() -> None:
@@ -160,27 +214,18 @@ def test_print_error_uses_single_rich_render(monkeypatch: Any) -> None:
assert "--tier flash" in rendered
-def test_find_results_render_as_list_without_empty_search_columns(monkeypatch: Any) -> None:
- printed: list[Any] = []
-
- class _Console:
- def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
- printed.append(item)
-
- monkeypatch.setattr(output_mod, "console", _Console())
-
- output_mod.format_find_results(
- {
- "total": 2,
- "results": [
- {"filename": "resume.pdf", "paths": ["/tmp/resume.pdf"]},
- {"filename": "cv.docx", "paths": ["/tmp/cv.docx"]},
+def test_find_results_render_as_list_without_empty_search_columns() -> None:
+ rendered = search_mod._render_find_results(
+ FindResponse(
+ total=2,
+ query="resume",
+ results=[
+ FindResult(filename="resume.pdf", paths=["/tmp/resume.pdf"]),
+ FindResult(filename="cv.docx", paths=["/tmp/cv.docx"]),
],
- }
+ )
)
- assert len(printed) == 1
- rendered = str(printed[0])
assert "Search results (2 total)" in rendered
assert "1. resume.pdf (/tmp/resume.pdf)" in rendered
assert "\n\n2. cv.docx (/tmp/cv.docx)" in rendered
@@ -189,77 +234,205 @@ def test_find_results_render_as_list_without_empty_search_columns(monkeypatch: A
assert "Paths" not in rendered
-def test_search_results_render_as_list_without_table(monkeypatch: Any) -> None:
- printed: list[Any] = []
-
- class _Console:
- def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
- printed.append(item)
-
- monkeypatch.setattr(output_mod, "console", _Console())
-
- output_mod.format_search_results(
- {
- "total": 1,
- "results": [
- {
- "filename": "resume.pdf",
- "tier": "standard",
- "snippet": "Python\nengineer",
- "paths": ["/tmp/resume.pdf"],
- }
+def test_search_results_render_as_list_without_table() -> None:
+ rendered = search_mod._render_search_results(
+ SearchResponse(
+ total=1,
+ query="python",
+ results=[
+ SearchResult(
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ filename="resume.pdf",
+ tier="standard",
+ snippet="Python\nengineer",
+ paths=["/tmp/resume.pdf"],
+ )
],
- }
+ )
)
- assert len(printed) == 1
- rendered = str(printed[0])
assert "Search results (1 total)" in rendered
assert "1. resume.pdf (/tmp/resume.pdf) Tier: standard" in rendered
assert " Python engineer" in rendered
assert "Snippet:" not in rendered
- assert not hasattr(printed[0], "columns")
-def test_search_result_snippet_preserves_fts_match_after_long_prefix(monkeypatch: Any) -> None:
- printed: list[Any] = []
-
- class _Console:
- def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
- printed.append(item)
-
- monkeypatch.setattr(output_mod, "console", _Console())
-
- output_mod.format_search_results(
- {
- "total": 1,
- "results": [
- {
- "filename": "deepseek.pdf",
- "tier": "flash",
- "snippet": (
+def test_search_result_snippet_preserves_fts_match_after_long_prefix() -> None:
+ rendered = search_mod._render_search_results(
+ SearchResponse(
+ total=1,
+ query="token dropping",
+ results=[
+ SearchResult(
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ filename="deepseek.pdf",
+ tier="flash",
+ snippet=(
"...on each node. Under this constraint, our MoE training framework can nearly "
"achieve full computation-communication overlap. <mark>Token</mark> <mark>Dropping</mark>"
),
- "paths": ["/tmp/deepseek.pdf"],
- }
+ paths=["/tmp/deepseek.pdf"],
+ )
],
- }
+ )
)
- rendered = str(printed[0])
assert "<mark>Token</mark>" in rendered
assert "<mark>Dropping</mark>" in rendered
+def test_list_renderers_return_tables(monkeypatch: Any) -> None:
+ monkeypatch.setattr(list_resources, "Table", _FakeTable)
+ parse = ParseInfo(
+ id=7,
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="standard",
+ page_range="1~2",
+ status="done",
+ privacy="local",
+ created_at=1,
+ updated_at=2,
+ )
+ scan = ScanInfo(
+ id=8,
+ path="/tmp/docs",
+ kind="manual",
+ source="cli",
+ status="done",
+ files_seen=3,
+ files_refreshed=2,
+ files_error=1,
+ created_at=1,
+ updated_at=2,
+ )
+ file_info = FileInfo(
+ filename="demo.pdf",
+ path="/tmp/demo.pdf",
+ ext="pdf",
+ size_bytes=7,
+ mtime_ms=1,
+ sha256="b" * 64,
+ short_id="bbbbbbb",
+ status="active",
+ first_seen_at=1,
+ updated_at=2,
+ )
+ doc = DocInfo(
+ sha256="c" * 64,
+ short_id="ccccccc",
+ size_bytes=7,
+ file_type="pdf",
+ title="Demo",
+ page_count=5,
+ first_seen_at=1,
+ updated_at=2,
+ )
+
+ parses_table = list_resources._render_list_parses(ListParsesResponse(parses=[parse], total=1, limit=50))
+ scans_table = list_resources._render_list_scans(ScanListResponse(scans=[scan], total=1, limit=50))
+ files_table = list_resources._render_list_files(ListFilesResponse(files=[file_info], total=1, limit=50))
+ docs_table = list_resources._render_list_docs(ListDocsResponse(docs=[doc], total=1, limit=50))
+
+ assert parses_table.title == "Parses (1 total)"
+ assert ("7", "done", "standard", "1~2", "aaaaaaa") in parses_table.rows
+ assert scans_table.title == "Scans (1 total)"
+ assert ("8", "done", "manual", "/tmp/docs", "3", "2", "1") in scans_table.rows
+ assert files_table.title == "Files (1 total)"
+ assert ("active", "/tmp/demo.pdf", "pdf", "bbbbbbb") in files_table.rows
+ assert docs_table.title == "Docs (1 total)"
+ assert ("ccccccc", "pdf", "5", "Demo") in docs_table.rows
+
+
+def test_config_and_rule_renderers_return_tables(monkeypatch: Any) -> None:
+ monkeypatch.setattr(config, "Table", _FakeTable)
+
+ config_table = config._render_config(
+ ConfigResponse(config={"parse.default_tier": "standard"}, sources={"parse.default_tier": "override"})
+ )
+ exclude_table = config._render_exclude_rules(
+ ExcludeRuleListResponse(rules=[ExcludeRuleInfo(id=3, pattern="*.tmp", priority=10)])
+ )
+ parsing_table = config._render_parsing_rules(
+ ParsingRuleListResponse(
+ rules=[
+ ParsingRuleInfo(id=4, pattern="*.pdf", tier="standard", page_range="1~2", remote=True, name="pdfs")
+ ]
+ )
+ )
+
+ assert config_table.title == "Config"
+ assert ("parse.default_tier", "standard", "override") in config_table.rows
+ assert exclude_table.title == "Exclude Rules"
+ assert ("3", "*.tmp", "10") in exclude_table.rows
+ assert parsing_table.title == "Parsing Rules"
+ assert ("4", "*.pdf", "standard", "1~2", "yes", "pdfs") in parsing_table.rows
+
+
+def test_watch_list_renderer_returns_table(monkeypatch: Any) -> None:
+ monkeypatch.setattr(watch_cmd, "Table", _FakeTable)
+
+ table = watch_cmd._render_watch_list(
+ WatchListResponse(watches=[WatchInfo(id=2, path="/tmp/docs", label="Docs", removable=True, status="active")])
+ )
+
+ assert table.title == "Watches"
+ assert ("2", "/tmp/docs", "active", "yes", "Docs") in table.rows
+
+
+def test_show_detail_renderers_return_tables(monkeypatch: Any) -> None:
+ monkeypatch.setattr(show, "Table", _FakeTable)
+ parse_info = ParseInfo(
+ id=9,
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="pro",
+ page_range="1",
+ status="done",
+ privacy="local",
+ created_at=1,
+ updated_at=2,
+ )
+ scan_info = ScanInfo(
+ id=10,
+ path="/tmp/docs",
+ kind="manual",
+ source="cli",
+ status="done",
+ files_seen=4,
+ files_refreshed=3,
+ files_unsupported=1,
+ created_at=1,
+ updated_at=2,
+ )
+ doc = DocInfo(
+ sha256="d" * 64,
+ short_id="ddddddd",
+ size_bytes=7,
+ file_type="pdf",
+ title="Doc",
+ page_count=6,
+ first_seen_at=1,
+ updated_at=2,
+ )
+
+ parse_table = show._render_parse_info(parse_info)
+ scan_table = show._render_scan(scan_info)
+ doc_table = show._render_doc_info(doc)
+
+ assert parse_table.title == "Parse 9: done"
+ assert ("Tier", "pro") in parse_table.rows
+ assert scan_table.title == "Scan 10: done"
+ assert ("Seen", "4") in scan_table.rows
+ assert doc_table.title == "Doc ddddddd"
+ assert ("Title", "Doc") in doc_table.rows
+
+
def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> None:
- printed: list[Any] = []
panels: list[dict[str, Any]] = []
- class _Console:
- def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
- printed.append(item)
-
class _Panel:
def __init__(self, renderable: Any, *, title: str, border_style: str) -> None:
self.renderable = renderable
@@ -267,22 +440,25 @@ def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> N
self.border_style = border_style
panels.append({"title": title, "renderable": renderable, "border_style": border_style})
- monkeypatch.setattr(output_mod, "console", _Console())
- monkeypatch.setattr(output_mod, "Panel", _Panel)
-
- output_mod.format_server_status(
- {
- "running": True,
- "pid": 123,
- "uptime_seconds": 1,
- "tcp": {"enabled": False},
- "workers": {},
- "app_logs": ["app\n"],
- "access_logs": ["access\n"],
- "stderr_logs": ["stderr\n"],
- "stdout_logs": ["stdout\n"],
- "recent_logs": ["legacy\n"],
- }
+ monkeypatch.setattr(server, "Panel", _Panel)
+
+ rendered = list(
+ server._render_server_status(
+ ServerStatusResponse(
+ running=True,
+ pid=123,
+ uptime_seconds=1,
+ socket_path="/tmp/doclib.sock",
+ data_dir="/tmp/mineru",
+ sqlite_path="/tmp/doclib.db",
+ log_path="/tmp/doclib.log",
+ app_logs=["app\n"],
+ access_logs=["access\n"],
+ stderr_logs=["stderr\n"],
+ stdout_logs=["stdout\n"],
+ recent_logs=["legacy\n"],
+ )
+ )
)
assert [panel["title"] for panel in panels] == [
@@ -293,7 +469,7 @@ def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> N
]
assert [panel["renderable"] for panel in panels] == ["app", "access", "stderr", "stdout"]
assert all(panel["border_style"] == "dim" for panel in panels)
- assert not any(getattr(item, "title", None) == "Recent Logs" for item in printed)
+ assert not any(getattr(item, "title", None) == "Recent Logs" for item in rendered)
def test_telemetry_status_command_prints_installation_id(monkeypatch: Any) -> None:
@@ -345,9 +521,11 @@ def test_interactive_unset_prompt_enables_telemetry(monkeypatch: Any) -> None:
assert actions == ["enable"]
prompt_text = "\n".join(echoed)
assert "Help improve MinerU by sending anonymous, locally aggregated usage and diagnostic data." in prompt_text
- assert "Collected: command names, MinerU version, OS, architecture, Python version" in prompt_text
+ assert "Collected:" in prompt_text
+ assert "command names, MinerU version, OS, architecture, Python version" in prompt_text
assert "coarse CPU/GPU categories" in prompt_text
- assert "Not collected: document contents, extracted text/images, file names, file paths" in prompt_text
+ assert "NOT collected:" in prompt_text
+ assert "document contents, extracted text/images, file names, file paths" in prompt_text
assert "search queries, prompts, snippets, tracebacks, exception messages" in prompt_text
assert "API keys, or exact CPU/GPU models" in prompt_text
assert "Press Enter or type Y to enable, or type N to disable." in prompt_text
@@ -452,6 +630,7 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_p
old_failed = ParseInfo(
id=2,
sha256="a" * 64,
+ short_id="aaaaaaa",
tier="pro",
page_range="1~10",
status="failed",
@@ -464,6 +643,7 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_p
new_done = ParseInfo(
id=3,
sha256="a" * 64,
+ short_id="aaaaaaa",
tier="pro",
page_range="1~10",
status="done",
@@ -556,6 +736,7 @@ def test_parse_verbose_json_writes_queue_notice_to_stderr(monkeypatch: Any, tmp_
done = ParseInfo(
id=3,
sha256="a" * 64,
+ short_id="aaaaaaa",
tier="flash",
page_range="1~1",
status="done",
@@ -611,7 +792,7 @@ def test_parse_json_connection_error_is_machine_readable(monkeypatch: Any, tmp_p
class _Client:
def __init__(self, *, timeout: int) -> None:
- raise RuntimeError("cannot connect")
+ raise ServerNotRunningError()
monkeypatch.setattr(parse, "DoclibClient", _Client)
@@ -619,15 +800,15 @@ def test_parse_json_connection_error_is_machine_readable(monkeypatch: Any, tmp_p
assert result.exit_code == 1
payload = json.loads(result.stdout)
- assert payload["error"]["code"] == "api_error"
- assert "Cannot connect to mineru server" in payload["error"]["message"]
+ assert payload["error"]["code"] == "server_not_running"
+ assert "Local mineru server is not running" in payload["error"]["message"]
assert "Error:" not in result.stdout
def test_cleanup_json_connection_error_is_machine_readable(monkeypatch: Any) -> None:
class _Client:
def __init__(self, *, timeout: int) -> None:
- raise RuntimeError("cannot connect")
+ raise ServerNotRunningError()
monkeypatch.setattr(cleanup_cmd, "DoclibClient", _Client)
@@ -635,8 +816,8 @@ def test_cleanup_json_connection_error_is_machine_readable(monkeypatch: Any) ->
assert result.exit_code == 1
payload = json.loads(result.stdout)
- assert payload["error"]["code"] == "api_error"
- assert "Cannot connect to mineru server" in payload["error"]["message"]
+ assert payload["error"]["code"] == "server_not_running"
+ assert "Local mineru server is not running" in payload["error"]["message"]
assert "Error:" not in result.stdout
@@ -659,6 +840,42 @@ def test_config_parsing_rules_list_json_error_is_machine_readable(monkeypatch: A
assert "Error:" not in result.stdout
+def test_config_exclude_rules_remove_non_json_prints_message_not_error_tuple(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def remove_exclude_rule(self, rule_id: int) -> None:
+ assert rule_id == 123
+ raise RuntimeError("('rule_not_found', 'Exclude rule missing.', 'rule_id')")
+
+ monkeypatch.setattr(config, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["config", "exclude-rules", "remove", "123"])
+
+ assert result.exit_code == 1
+ assert "Exclude rule missing." in result.output
+ assert "('rule_not_found'" not in result.output
+
+
+def test_config_parsing_rules_remove_non_json_prints_message_not_error_tuple(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def remove_parsing_rule(self, rule_id: int) -> None:
+ assert rule_id == 456
+ raise RuntimeError("('rule_not_found', 'Parsing rule missing.', 'rule_id')")
+
+ monkeypatch.setattr(config, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["config", "parsing-rules", "remove", "456"])
+
+ assert result.exit_code == 1
+ assert "Parsing rule missing." in result.output
+ assert "('rule_not_found'" not in result.output
+
+
def test_parse_failed_response_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.unsupported"
source.write_bytes(b"unsupported")
@@ -868,6 +1085,25 @@ def test_watch_add_normalizes_user_path_before_request(monkeypatch: Any, tmp_pat
assert seen_paths == [os.path.normpath(os.path.abspath(os.path.expanduser("~/Documents/../Documents")))]
+def test_watch_remove_missing_id_preserves_watch_not_found_json_error(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def list_watches(self) -> Any:
+ return type("WatchList", (), {"watches": []})()
+
+ monkeypatch.setattr(watch_cmd, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["watch", "remove", "123", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"]["code"] == "watch_not_found"
+ assert payload["error"]["param"] == "watch_id"
+ assert "Error:" not in result.output
+
+
def test_parse_json_output_writes_file_and_returns_output_object(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
@@ -880,7 +1116,7 @@ def test_parse_json_output_writes_file_and_returns_output_object(monkeypatch: An
def ensure_parse(self, request: Any) -> ParseResponse:
return ParseResponse(sha256="a" * 64, tier="flash", page_range="1~1", status="done", cache_hit=True)
- def export_doc_content(self, sha256: str, request: Any) -> Any:
+ def export_doc_content(self, doc_ref: str, request: Any) -> Any:
Path(request.output).write_text("exported", encoding="utf-8")
return type("Exported", (), {"output": request.output})()
@@ -904,6 +1140,7 @@ def test_parse_wait_status_line_is_verbose_only(monkeypatch: Any, tmp_path: Path
done = ParseInfo(
id=3,
sha256="a" * 64,
+ short_id="aaaaaaa",
tier="flash",
page_range="1~1",
status="done",
@@ -1021,6 +1258,121 @@ def test_scan_missing_path_json_error_is_machine_readable(tmp_path: Path) -> Non
assert "Error:" not in result.output
+def test_scan_wait_failed_status_exits_nonzero_after_json_output(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "docs"
+ source.mkdir()
+ failed_scan = ScanInfo(
+ id=7,
+ path=str(source.resolve()),
+ kind="manual",
+ source="cli",
+ status="failed",
+ files_seen=1,
+ files_error=1,
+ error_code="scan_failed",
+ error_msg="scan boom",
+ created_at=1,
+ updated_at=2,
+ )
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def create_scan(self, request: Any) -> ScanInfo:
+ assert request.path == str(source.resolve())
+ return failed_scan.model_copy(update={"status": "pending"})
+
+ def get_scan(self, scan_id: int) -> ScanInfo:
+ assert scan_id == 7
+ return failed_scan
+
+ monkeypatch.setattr(scan_mod, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["scan", str(source), "--wait", "1", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["status"] == "failed"
+ assert payload["error_code"] == "scan_failed"
+
+
+def test_watch_rescan_wait_failed_status_exits_nonzero_after_json_output(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "watched"
+ source.mkdir()
+ watch = WatchInfo(id=3, path=str(source.resolve()), status="active")
+ failed_scan = ScanInfo(
+ id=9,
+ path=str(source.resolve()),
+ kind="watch",
+ source="cli",
+ watch_id=3,
+ status="failed",
+ files_seen=1,
+ files_error=1,
+ error_code="scan_failed",
+ error_msg="watch scan boom",
+ created_at=1,
+ updated_at=2,
+ )
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def list_watches(self) -> WatchListResponse:
+ return WatchListResponse(watches=[watch])
+
+ def create_scan(self, request: Any) -> ScanInfo:
+ assert request.watch_id == 3
+ return failed_scan.model_copy(update={"status": "pending"})
+
+ def get_scan(self, scan_id: int) -> ScanInfo:
+ assert scan_id == 9
+ return failed_scan
+
+ monkeypatch.setattr(watch_cmd, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["watch", "rescan", "3", "--wait", "1", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["status"] == "failed"
+ assert payload["error_code"] == "scan_failed"
+
+
+def test_show_scan_failed_status_remains_successful_query(monkeypatch: Any, tmp_path: Path) -> None:
+ failed_scan = ScanInfo(
+ id=9,
+ path=str(tmp_path / "watched"),
+ kind="watch",
+ source="cli",
+ status="failed",
+ files_seen=1,
+ files_error=1,
+ error_code="scan_failed",
+ error_msg="watch scan boom",
+ created_at=1,
+ updated_at=2,
+ )
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def get_scan(self, scan_id: int) -> ScanInfo:
+ assert scan_id == 9
+ return failed_scan
+
+ monkeypatch.setattr(show, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["show", "scan", "9", "--json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["status"] == "failed"
+
+
def test_show_file_uses_get_file_by_path(monkeypatch: Any, tmp_path: Path) -> None:
calls: list[str] = []
source = tmp_path / "demo.pdf"
@@ -1087,6 +1439,59 @@ def test_show_file_normalizes_user_path_before_request(monkeypatch: Any, tmp_pat
assert calls == [os.path.normpath(os.path.abspath(os.path.expanduser("~/docs/../docs/demo.pdf")))]
+def test_show_file_renderer_uses_file_info_table(monkeypatch: Any) -> None:
+ tables: list[Any] = []
+
+ class _Table:
+ def __init__(self, *, title: str) -> None:
+ self.title = title
+ self.rows: list[tuple[str, str]] = []
+ tables.append(self)
+
+ def add_column(self, *args: Any, **kwargs: Any) -> None:
+ pass
+
+ def add_row(self, key: str, value: str) -> None:
+ self.rows.append((key, value))
+
+ monkeypatch.setattr(show, "Table", _Table)
+
+ rendered = show._render_file_info(
+ FileInfoResponse(
+ file=FileInfo(
+ filename="demo.pdf",
+ path="/tmp/demo.pdf",
+ ext="pdf",
+ size_bytes=2048,
+ mtime_ms=1,
+ sha256="a" * 64,
+ short_id="abcdef1",
+ status="active",
+ first_seen_at=1,
+ updated_at=1,
+ ),
+ doc=DocInfo(
+ sha256="a" * 64,
+ short_id="abcdef1",
+ size_bytes=2048,
+ title="Demo",
+ author="Alice",
+ page_count=3,
+ first_seen_at=1,
+ updated_at=1,
+ ),
+ )
+ )
+
+ assert rendered == tables[0]
+ assert tables[0].title == "File Info: demo.pdf"
+ assert ("Path", "/tmp/demo.pdf") in tables[0].rows
+ assert ("Size", "2 KB") in tables[0].rows
+ assert ("Doc ID", "abcdef1") in tables[0].rows
+ assert ("Title", "Demo") in tables[0].rows
+ assert ("Author", "Alice") in tables[0].rows
+
+
def test_invalidate_normalizes_user_path_before_request(monkeypatch: Any, tmp_path: Path) -> None:
home = tmp_path / "home"
source = home / "docs" / "demo.pdf"
@@ -1100,7 +1505,13 @@ def test_invalidate_normalizes_user_path_before_request(monkeypatch: Any, tmp_pa
def invalidate(self, request: Any) -> InvalidateResponse:
calls.append(request.path)
- return InvalidateResponse(target="parses", sha256="a" * 64, tier=request.tier, invalidated_count=1)
+ return InvalidateResponse(
+ target="parses",
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier=request.tier,
+ invalidated_count=1,
+ )
monkeypatch.setenv("HOME", str(home))
monkeypatch.setattr(invalidate, "DoclibClient", _Client)
@@ -1111,6 +1522,27 @@ def test_invalidate_normalizes_user_path_before_request(monkeypatch: Any, tmp_pa
assert calls == [os.path.normpath(os.path.abspath(os.path.expanduser("~/docs/../docs/demo.pdf")))]
+def test_invalidate_non_json_prints_message_not_error_tuple(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 10
+
+ def invalidate(self, request: Any) -> None:
+ assert request.path == str(source.resolve())
+ raise RuntimeError("('not_cached', 'Requested parsed content is not cached.', 'path')")
+
+ monkeypatch.setattr(invalidate, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["invalidate", str(source)])
+
+ assert result.exit_code == 1
+ assert "Requested parsed content is not cached." in result.output
+ assert "('not_cached'" not in result.output
+
+
def test_show_doc_expands_files(monkeypatch: Any) -> None:
calls: list[tuple[str, bool]] = []
@@ -1118,9 +1550,9 @@ def test_show_doc_expands_files(monkeypatch: Any) -> None:
def __init__(self, *, timeout: int) -> None:
assert timeout == 30
- def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:
- calls.append((sha256, expand_files))
- return DocInfo(sha256=sha256, short_id=sha256[:7], size_bytes=7, first_seen_at=1, updated_at=1, files=[])
+ def get_doc(self, doc_ref: str, *, expand_files: bool = False) -> DocInfo:
+ calls.append((doc_ref, expand_files))
+ return DocInfo(sha256=doc_ref, short_id=doc_ref[:7], size_bytes=7, first_seen_at=1, updated_at=1, files=[])
monkeypatch.setattr(show, "DoclibClient", _Client)
@@ -1259,6 +1691,40 @@ def test_parse_content_read_failure_non_json_prints_message_not_error_tuple(monk
assert "('not_cached'" not in result.output
+def test_parse_empty_cached_content_json_reports_error_envelope(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 90
+
+ def ensure_parse(self, request: Any) -> ParseResponse:
+ assert request.path == str(source.resolve())
+ return ParseResponse(sha256="a" * 64, tier="flash", page_range="1", status="done", cache_hit=True)
+
+ def get_doc_content(self, *args: Any, **kwargs: Any) -> DocContentResponse:
+ return DocContentResponse(
+ sha256="a" * 64,
+ short_id="ab12cd3",
+ tier="flash",
+ format="markdown",
+ content="",
+ request_scope=ContentRequestScope(page_range="1", limit=30000),
+ content_ranges=[],
+ )
+
+ monkeypatch.setattr(parse, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"]["code"] == "parse_empty"
+ assert payload["error"]["message"] == "No content returned from parse."
+ assert "Error:" not in result.output
+
+
def test_parse_empty_cached_content_non_json_reports_no_renderable_content(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
@@ -1456,6 +1922,36 @@ def test_read_json_output_writes_image_file_and_returns_output_object(monkeypatc
assert "Written to" not in result.output
+def test_read_json_image_output_missing_asset_reports_error_envelope(monkeypatch: Any, tmp_path: Path) -> None:
+ output = tmp_path / "nested" / "local.png"
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 60
+
+ def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:
+ return DocContentResponse(
+ sha256="a" * 64,
+ short_id="ab12cd3",
+ tier="standard",
+ format="image",
+ content="",
+ request_scope=ContentRequestScope(locator=locator, context=0, limit=30000),
+ asset=None,
+ )
+
+ monkeypatch.setattr(read, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--format", "image", "--output", str(output), "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"]["code"] == "asset_not_available"
+ assert payload["error"]["message"] == "No image asset returned."
+ assert not output.exists()
+ assert "Error:" not in result.output
+
+
def test_read_image_output_copies_server_asset_locally(monkeypatch: Any, tmp_path: Path) -> None:
asset = tmp_path / "server.png"
asset.write_bytes(b"png-bytes")
diff --git a/tests/unittest/test_cli_runtime_contract.py b/tests/unittest/test_cli_runtime_contract.py
new file mode 100644
index 00000000..7befc7f4
--- /dev/null
+++ b/tests/unittest/test_cli_runtime_contract.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+import json
+import sys
+import types
+
+import pytest
+import typer
+
+from mineru.cli import output
+from mineru.cli import contracts
+from mineru.cli.contracts import CliContext
+from mineru.cli.runtime import cli_ok, cli_task, emit_error, emit_result, run_cli
+from mineru.errors import MineruError
+
+
[email protected](autouse=True)
+def _plain_output(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(output, "print_notice", lambda msg: print(msg, file=sys.stderr))
+ monkeypatch.setattr(output, "print_error", lambda msg: print(f"Error: {msg}", file=sys.stderr))
+
+ def print_rich(*objects: object) -> None:
+ for item in objects:
+ print(item)
+
+ monkeypatch.setattr(output, "print_rich", print_rich)
+
+
+def test_emit_result_json_mode_writes_single_json_object(capsys: pytest.CaptureFixture[str]) -> None:
+ result = cli_ok({"status": "done", "count": 2})
+
+ emit_result(CliContext(json_mode=True), result)
+
+ captured = capsys.readouterr()
+ assert json.loads(captured.out) == {"status": "done", "count": 2}
+ assert captured.err == ""
+
+
+def test_run_cli_accepts_plain_action_result(capsys: pytest.CaptureFixture[str]) -> None:
+ run_cli(
+ CliContext(json_mode=False),
+ lambda: {"name": "demo"},
+ render=lambda data: f"name={data['name']}",
+ warnings=lambda data: [f"warning for {data['name']}"],
+ )
+
+ captured = capsys.readouterr()
+ assert captured.out == "name=demo\n"
+ assert captured.err == "warning for demo\n"
+
+
+def test_run_cli_accepts_renderable_sequence(capsys: pytest.CaptureFixture[str]) -> None:
+ run_cli(
+ CliContext(json_mode=False),
+ lambda: {"name": "demo"},
+ render=lambda data: [f"name={data['name']}", "status=done"],
+ )
+
+ captured = capsys.readouterr()
+ assert captured.out == "name=demo\nstatus=done\n"
+ assert captured.err == ""
+
+
+def test_run_cli_accepts_renderable_generator(capsys: pytest.CaptureFixture[str]) -> None:
+ def render(data: dict[str, str]):
+ yield f"name={data['name']}"
+ yield "status=done"
+
+ run_cli(CliContext(json_mode=False), lambda: {"name": "demo"}, render=render)
+
+ captured = capsys.readouterr()
+ assert captured.out == "name=demo\nstatus=done\n"
+ assert captured.err == ""
+
+
+def test_cli_renderer_type_does_not_allow_side_effect_only_renderer() -> None:
+ assert not isinstance(contracts.CliRenderer, types.UnionType)
+ assert "None" in str(contracts.CliRenderer)
+
+
+def test_run_cli_treats_none_renderer_result_as_no_output(capsys: pytest.CaptureFixture[str]) -> None:
+ def render(data: dict[str, str]) -> None:
+ del data
+
+ run_cli(CliContext(json_mode=False), lambda: {"name": "demo"}, render=render)
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert captured.err == ""
+
+
+def test_run_cli_json_mode_does_not_call_renderer(capsys: pytest.CaptureFixture[str]) -> None:
+ called = False
+
+ def render(data: dict[str, str]) -> None:
+ nonlocal called
+ called = True
+ print(f"side-effect={data['name']}")
+
+ run_cli(CliContext(json_mode=True), lambda: {"name": "demo"}, render=render)
+
+ captured = capsys.readouterr()
+ assert json.loads(captured.out) == {"name": "demo"}
+ assert captured.err == ""
+ assert called is False
+
+
+def test_emit_error_json_mode_writes_error_envelope_to_stdout(capsys: pytest.CaptureFixture[str]) -> None:
+ with pytest.raises(typer.Exit) as exc_info:
+ emit_error(CliContext(json_mode=True), MineruError("file_not_found", "File missing.", "path"))
+
+ captured = capsys.readouterr()
+ assert exc_info.value.exit_code == 1
+ assert json.loads(captured.out) == {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "file_not_found",
+ "message": "File missing.",
+ "param": "path",
+ }
+ }
+ assert captured.err == ""
+
+
+def test_emit_error_non_json_writes_human_error_to_stderr(capsys: pytest.CaptureFixture[str]) -> None:
+ with pytest.raises(typer.Exit) as exc_info:
+ emit_error(CliContext(json_mode=False), MineruError("file_not_found", "File missing.", "path"))
+
+ captured = capsys.readouterr()
+ assert exc_info.value.exit_code == 1
+ assert captured.out == ""
+ assert captured.err == "Error: File missing.\n"
+
+
+def test_emit_result_writes_notices_and_warnings_to_stderr(capsys: pytest.CaptureFixture[str]) -> None:
+ result = cli_ok(
+ {"status": "done"},
+ notices=["started"],
+ warnings=["be careful"],
+ )
+
+ emit_result(CliContext(json_mode=True), result)
+
+ captured = capsys.readouterr()
+ assert json.loads(captured.out) == {"status": "done"}
+ assert captured.err == "started\nbe careful\n"
+
+
+def test_task_result_failed_status_exits_one_after_output(capsys: pytest.CaptureFixture[str]) -> None:
+ result = cli_task(
+ {"id": 3, "status": "failed"},
+ status="failed",
+ fail_if_final_failed=True,
+ )
+
+ with pytest.raises(typer.Exit) as exc_info:
+ emit_result(CliContext(json_mode=True), result)
+
+ captured = capsys.readouterr()
+ assert exc_info.value.exit_code == 1
+ assert json.loads(captured.out) == {"id": 3, "status": "failed"}
+
+
+def test_task_result_failed_status_can_be_query_success(capsys: pytest.CaptureFixture[str]) -> None:
+ result = cli_task(
+ {"id": 3, "status": "failed"},
+ status="failed",
+ fail_if_final_failed=False,
+ )
+
+ emit_result(CliContext(json_mode=True), result)
+
+ captured = capsys.readouterr()
+ assert json.loads(captured.out) == {"id": 3, "status": "failed"}
diff --git a/tests/unittest/test_doclib_background_workers.py b/tests/unittest/test_doclib_background_workers.py
new file mode 100644
index 00000000..3914c947
--- /dev/null
+++ b/tests/unittest/test_doclib_background_workers.py
@@ -0,0 +1,67 @@
+import asyncio
+import sqlite3
+
+from mineru.doclib.background.ingest import IngestWorkerPool
+from mineru.doclib.background.parse_worker import ParseWorkerPool
+from mineru.doclib.background.scan_worker import ScanWorkerPool
+
+
+def test_parse_worker_survives_acquire_error() -> None:
+ async def _run() -> None:
+ class _ParseService:
+ pool: ParseWorkerPool
+
+ async def acquire_task(self) -> None:
+ self.pool.running = False
+ raise sqlite3.OperationalError("database is locked")
+
+ async def get_queue_length(self) -> int:
+ return 0
+
+ service = _ParseService()
+ pool = ParseWorkerPool(service, num_workers=1) # type: ignore[arg-type]
+ service.pool = pool
+ pool.running = True
+
+ await pool._worker(0)
+
+ asyncio.run(_run())
+
+
+def test_ingest_worker_survives_acquire_error() -> None:
+ async def _run() -> None:
+ class _ParseService:
+ pass
+
+ service = _ParseService()
+ pool = IngestWorkerPool(service, num_workers=1, lock_timeout_sec=60) # type: ignore[arg-type]
+
+ async def _raise_once() -> None:
+ pool.running = False
+ raise sqlite3.OperationalError("database is locked")
+
+ pool._acquire_task = _raise_once # type: ignore[method-assign]
+ pool.running = True
+
+ await pool._worker(0)
+
+ asyncio.run(_run())
+
+
+def test_scan_worker_survives_acquire_error() -> None:
+ async def _run() -> None:
+ class _ScanService:
+ pool: ScanWorkerPool
+
+ async def acquire_task(self) -> None:
+ self.pool.running = False
+ raise sqlite3.OperationalError("database is locked")
+
+ service = _ScanService()
+ pool = ScanWorkerPool(service, num_workers=1) # type: ignore[arg-type]
+ service.pool = pool
+ pool.running = True
+
+ await pool._worker(0)
+
+ asyncio.run(_run())
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 5bf31288..5bb4cc07 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -21,18 +21,19 @@ from mineru.doclib.background.parse_server_health import (
ParseServerHealthCheck,
api_server_args_for_tier,
select_available_managed_port,
- stop_managed_parse_server,
start_managed_parse_server,
+ stop_managed_parse_server,
)
from mineru.doclib.background.watch import WatchLoop
+from mineru.doclib.config_defaults import CONFIG_DEFAULTS
from mineru.doclib.core.db import DatabaseManager
from mineru.doclib.core.file_io import FileStat, get_file_stat
from mineru.doclib.core.fts import FTSManager
-from mineru.doclib.config_defaults import CONFIG_DEFAULTS
-from mineru.errors import InvalidRequestError
+from mineru.doclib.locators import ContentCursor
+from mineru.doclib.server import DoclibServer, _ReadPlan
+from mineru.doclib.services import parse_svc as parse_svc_module
from mineru.doclib.services.cleanup_svc import CleanupService
from mineru.doclib.services.config_svc import ConfigService
-from mineru.doclib.services import parse_svc as parse_svc_module
from mineru.doclib.services.parse_svc import (
ParseFailure,
ParseService,
@@ -46,9 +47,8 @@ from mineru.doclib.services.parse_svc import (
)
from mineru.doclib.services.scan_svc import ScanService
from mineru.doclib.services.search_svc import SearchService
-from mineru.doclib.locators import ContentCursor
-from mineru.doclib.server import DoclibServer, _ReadPlan
-from mineru.doclib.types import ParseResponse, WatchRequest
+from mineru.doclib.types import DocContentExportRequest, InvalidateRequest, ParseResponse, WatchRequest
+from mineru.errors import InvalidRequestError, NotFoundError
from mineru.parser import backend_for_tier, resolve_tier_and_backend
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
@@ -143,7 +143,7 @@ class _FakeDB:
path = params[0]
if self.file_row and self.file_row["path"] == path and self.file_row["status"] == "active":
return self.file_row
- if sql.startswith("SELECT page_count FROM docs WHERE sha256="):
+ if sql.startswith("SELECT page_count FROM docs WHERE sha256=") or sql.startswith("SELECT * FROM docs WHERE sha256="):
sha256 = params[0]
if self.doc_row and self.doc_row["sha256"] == sha256:
return self.doc_row
@@ -164,11 +164,7 @@ class _FakeDB:
return [row for row in self.parses if row["id"] in ids]
if sql.startswith("SELECT * FROM parses WHERE sha256=? AND tier=? AND status=?"):
sha256, tier, status = params
- rows = [
- row
- for row in self.parses
- if row["sha256"] == sha256 and row["tier"] == tier and row["status"] == status
- ]
+ rows = [row for row in self.parses if row["sha256"] == sha256 and row["tier"] == tier and row["status"] == status]
return sorted(rows, key=lambda row: row["done_at"] or 0, reverse=True)
if sql.startswith("SELECT page_range, done_at FROM parses WHERE sha256=? AND tier=? AND status=?"):
sha256, tier, status = params
@@ -180,11 +176,7 @@ class _FakeDB:
return sorted(rows, key=lambda row: row["done_at"] or 0, reverse=True)
if sql.startswith("SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN (?, ?)"):
sha256, tier, *statuses = params
- return [
- row
- for row in self.parses
- if row["sha256"] == sha256 and row["tier"] == tier and row["status"] in statuses
- ]
+ return [row for row in self.parses if row["sha256"] == sha256 and row["tier"] == tier and row["status"] in statuses]
if sql.startswith("SELECT * FROM parses WHERE sha256=? AND status=?"):
sha256, status = params
rows = [row for row in self.parses if row["sha256"] == sha256 and row["status"] == status]
@@ -254,6 +246,13 @@ def _image_result(image_path: str, image_bytes: bytes = b"image-bytes") -> Parse
return ParseResult(pages=[_image_page(image_path)], _image_cache=image_cache)
+def _text_page(text: str) -> PageInfo:
+ span = Span(type=ContentType.TEXT, bbox=(1, 1, 20, 10), content=text)
+ line = Line(bbox=(1, 1, 20, 10), spans=[span])
+ block = Block(index=0, type=BlockType.TEXT, bbox=(1, 1, 20, 10), lines=[line])
+ return PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[block], _backend="vlm")
+
+
def test_load_pages_from_done_batches_keeps_newest_page_idx(tmp_path: Path) -> None:
sha256 = "a" * 64
tier = "standard"
@@ -436,7 +435,9 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: py
kwargs["stderr"].flush()
return _Proc()
- monkeypatch.setattr("mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582)
+ monkeypatch.setattr(
+ "mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582
+ )
monkeypatch.setattr("mineru.doclib.background.parse_server_health.subprocess.Popen", _popen)
proc, url = start_managed_parse_server(
@@ -526,7 +527,9 @@ def test_managed_parse_server_restart_writes_stdout_and_stderr_logs(monkeypatch:
monkeypatch.setattr(
"mineru.doclib.background.parse_server_health.get_parse_server_stderr_log_path", lambda: str(parse_stderr_log_path)
)
- monkeypatch.setattr("mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582)
+ monkeypatch.setattr(
+ "mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582
+ )
monkeypatch.setattr("mineru.doclib.background.parse_server_health.subprocess.Popen", _popen)
checker = ParseServerHealthCheck(
@@ -570,7 +573,9 @@ def test_managed_parse_server_restart_stops_recorded_proc_before_start(monkeypat
return _Proc()
monkeypatch.setattr("mineru.doclib.background.parse_server_health.stop_managed_parse_server", _stop)
- monkeypatch.setattr("mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582)
+ monkeypatch.setattr(
+ "mineru.doclib.background.parse_server_health.select_available_managed_port", lambda *args, **kwargs: 16582
+ )
monkeypatch.setattr(
"mineru.doclib.background.parse_server_health.open_managed_parse_server_logs",
lambda *args, **kwargs: nullcontext((None, None)),
@@ -659,11 +664,7 @@ def test_data_dir_is_not_runtime_kv_config(tmp_path: Path) -> None:
def test_remote_parse_server_default_url_is_declared_once() -> None:
default_url = CONFIG_DEFAULTS["parse_server.remote.url"]
doclib_dir = Path(__file__).parents[2] / "mineru" / "doclib"
- occurrences = [
- path
- for path in doclib_dir.rglob("*.py")
- if default_url in path.read_text(encoding="utf-8")
- ]
+ occurrences = [path for path in doclib_dir.rglob("*.py") if default_url in path.read_text(encoding="utf-8")]
assert occurrences == [doclib_dir / "config_defaults.py"]
@@ -763,9 +764,7 @@ def test_ingest_binds_file_sha_before_creating_parse_task(tmp_path: Path, monkey
row = await service.ingest_file(str(source))
dangling_parses = await db.fetchall(
- "SELECT p.id FROM parses p "
- "LEFT JOIN files f ON f.sha256=p.sha256 AND f.status='active' "
- "WHERE f.id IS NULL",
+ "SELECT p.id FROM parses p LEFT JOIN files f ON f.sha256=p.sha256 AND f.status='active' WHERE f.id IS NULL",
)
assert row is not None
@@ -807,16 +806,21 @@ def test_request_parse_explicit_image_ingests_and_queues_parse(tmp_path: Path, m
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,))
+ doc_row = await db.fetchone(
+ "SELECT short_id, 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 doc_row is not None
+ assert result.short_id == doc_row["short_id"]
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 doc_row == {"short_id": result.short_id, "file_type": "image", "page_count": 1, "is_image_based": 1}
assert parse_rows == [{"tier": "flash", "page_range": "1", "status": "pending"}]
asyncio.run(_run())
@@ -1002,7 +1006,7 @@ def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path:
"first_seen_at": 100,
"updated_at": 100,
},
- doc_row={"sha256": sha256, "page_count": 10},
+ doc_row={"sha256": sha256, "short_id": "eeeeeee", "page_count": 10},
)
service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
@@ -1013,6 +1017,7 @@ def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path:
assert result.reused_parse_ids == [11]
assert result.created_parse_ids == [12]
assert result.page_range == "1~10"
+ assert result.short_id == "eeeeeee"
assert result.status == "pending"
assert result.cache_hit is False
assert db.updated_priorities == [11]
@@ -1022,7 +1027,15 @@ def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path:
def test_list_parse_records_by_ids_returns_precise_status(tmp_path: Path) -> None:
parses = [
{"id": 1, "sha256": "f" * 64, "tier": "standard", "page_range": "1~5", "status": "done", "done_at": 1000},
- {"id": 2, "sha256": "f" * 64, "tier": "standard", "page_range": "6~10", "status": "failed", "error_code": "parse_failed", "error_msg": "boom"},
+ {
+ "id": 2,
+ "sha256": "f" * 64,
+ "tier": "standard",
+ "page_range": "6~10",
+ "status": "failed",
+ "error_code": "parse_failed",
+ "error_msg": "boom",
+ },
]
db = _FakeDB(parses=parses, file_row=None)
service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
@@ -1144,7 +1157,9 @@ def test_ensure_ingested_rebinds_changed_text_file_to_new_sha(tmp_path: Path) ->
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
source.write_text("old", encoding="utf-8")
@@ -1178,7 +1193,9 @@ def test_refresh_file_marks_missing_known_path_deleted(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
source.write_text("content", encoding="utf-8")
@@ -1208,7 +1225,9 @@ def test_ensure_ingested_maps_read_permission_error_to_file_permission_denied(
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "locked.pdf"
source.write_bytes(b"%PDF-1.7\n")
@@ -1236,7 +1255,9 @@ def test_refresh_file_records_stat_error_without_marking_deleted(tmp_path: Path,
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
source.write_text("content", encoding="utf-8")
@@ -1268,7 +1289,9 @@ def test_ingest_worker_skips_files_with_blocking_stat_errors(tmp_path: Path, mon
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
source.write_text("content", encoding="utf-8")
@@ -1297,7 +1320,9 @@ def test_ingest_worker_preserves_precise_file_access_errors(tmp_path: Path) -> N
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
now = 1000
file_id = await db.execute_insert(
@@ -1326,7 +1351,9 @@ def test_ingest_worker_skips_any_file_with_existing_error(tmp_path: Path) -> Non
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "note.txt"
now = 1000
await db.execute_insert(
@@ -1376,11 +1403,13 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:
assert exact_total == 1
assert [row["tier"] for row in exact_results] == ["standard"]
+ assert [row["short_id"] for row in exact_results] == ["2" * 7]
assert [row["page_count"] for row in exact_results] == [12]
assert min_total == 2
assert {row["tier"] for row in min_results} == {"standard", "pro"}
assert type_total == 1
assert [row["filename"] for row in type_results] == ["pro.docx"]
+ assert [row["short_id"] for row in type_results] == ["3" * 7]
assert [row["page_count"] for row in type_results] == [23]
asyncio.run(_run())
@@ -1402,7 +1431,9 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_path
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(sha256, sha256[:7], 10, "pdf", 7 if sha256 == sha_active else 9, now, now),
)
- await fts.replace(sha256=sha256, tier="standard", text="fallback needle", title="", author="", filename=f"{sha256[0]}.pdf")
+ await fts.replace(
+ sha256=sha256, tier="standard", text="fallback needle", title="", author="", filename=f"{sha256[0]}.pdf"
+ )
await db.execute(
"INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
@@ -1468,7 +1499,9 @@ def test_refresh_file_marks_only_current_file_unreachable_when_watch_root_is_mis
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- service = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
root = tmp_path / "removable"
root.mkdir()
watch = await config_svc.add_watch(str(root), removable=True)
@@ -1485,7 +1518,9 @@ def test_refresh_file_marks_only_current_file_unreachable_when_watch_root_is_mis
root.rmdir()
refreshed = await service.refresh_file(str(source), watch_id=watch["id"])
- source_row = await db.fetchone("SELECT status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),))
+ source_row = await db.fetchone(
+ "SELECT status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),)
+ )
other_row = await db.fetchone("SELECT status FROM files WHERE path=?", (str(other),))
watch_row = await db.fetchone("SELECT status, unreachable_at FROM watches WHERE id=?", (watch["id"],))
@@ -1508,7 +1543,9 @@ def test_remove_watch_converts_unreachable_files_to_deleted_and_unbinds_watch(tm
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- service = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
root = tmp_path / "removable"
root.mkdir()
watch = await config_svc.add_watch(str(root), removable=True)
@@ -1544,7 +1581,9 @@ def test_watch_scan_refreshes_known_active_paths_before_walk(tmp_path: Path) ->
await db.initialize()
config_svc = ConfigService(db)
fts = FTSManager(db)
- service = ParseService(db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
watch_loop = WatchLoop(db=db, config_svc=config_svc, parse_svc=service, scan_interval_sec=300)
root = tmp_path / "watched"
root.mkdir()
@@ -1572,7 +1611,9 @@ def test_watch_scan_marks_root_unreachable_without_refreshing_all_files(tmp_path
await db.initialize()
config_svc = ConfigService(db)
fts = FTSManager(db)
- service = ParseService(db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
watch_loop = WatchLoop(db=db, config_svc=config_svc, parse_svc=service, scan_interval_sec=300)
root = tmp_path / "removable"
root.mkdir()
@@ -1603,7 +1644,9 @@ def test_device_monitor_queues_watch_scan_when_removable_watch_recovers(tmp_path
await db.initialize()
config_svc = ConfigService(db)
fts = FTSManager(db)
- parse_svc = ParseService(db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=fts, config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
monitor = DeviceMonitor(db=db, config_svc=config_svc, interval_sec=5, scan_svc=scan_svc)
root = tmp_path / "removable"
@@ -1651,7 +1694,9 @@ def test_scan_service_creates_and_processes_manual_file_scan(tmp_path: Path) ->
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
source = tmp_path / "note.txt"
source.write_text("content", encoding="utf-8")
@@ -1682,7 +1727,9 @@ def test_scan_service_directory_scan_applies_excludes_and_counts_unsupported(tmp
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
root = tmp_path / "docs"
root.mkdir()
@@ -1716,7 +1763,13 @@ def test_refresh_file_ignores_office_temp_lock_files(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=ConfigService(db), data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db,
+ fts=FTSManager(db),
+ config_svc=ConfigService(db),
+ data_dir=str(tmp_path / "data"),
+ parse_lock_timeout_sec=1800,
+ )
source = tmp_path / "~$package-size.xlsx"
source.write_bytes(b"\x15Microsoft Office lock")
@@ -1734,7 +1787,13 @@ def test_ensure_ingested_ignores_existing_office_temp_lock_file_row(tmp_path: Pa
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
- service = ParseService(db=db, fts=FTSManager(db), config_svc=ConfigService(db), data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ service = ParseService(
+ db=db,
+ fts=FTSManager(db),
+ config_svc=ConfigService(db),
+ data_dir=str(tmp_path / "data"),
+ parse_lock_timeout_sec=1800,
+ )
source = tmp_path / "~$package-size.xlsx"
source.write_bytes(b"\x15Microsoft Office lock")
now = 1000
@@ -1756,7 +1815,9 @@ def test_scan_service_directory_scan_ignores_office_temp_lock_files(tmp_path: Pa
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
root = tmp_path / "docs"
root.mkdir()
@@ -1847,7 +1908,9 @@ def test_scan_service_reuses_pending_scan_for_same_kind_and_path(tmp_path: Path)
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
root = tmp_path / "docs"
root.mkdir()
@@ -1867,7 +1930,9 @@ def test_scan_service_does_not_reuse_stale_running_scan_for_same_kind_and_path(t
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1)
root = tmp_path / "docs"
root.mkdir()
@@ -1910,9 +1975,7 @@ def test_watch_ids_are_stable_standard_library_hashes(tmp_path: Path) -> None:
root.mkdir()
watch = await config_svc.add_watch(str(root))
- expected = int.from_bytes(hashlib.blake2b(str(root).encode("utf-8"), digest_size=8).digest(), "big") & (
- (1 << 63) - 1
- )
+ expected = int.from_bytes(hashlib.blake2b(str(root).encode("utf-8"), digest_size=8).digest(), "big") & ((1 << 63) - 1)
assert watch["id"] == expected
@@ -1920,13 +1983,19 @@ def test_watch_ids_are_stable_standard_library_hashes(tmp_path: Path) -> None:
def test_doclib_server_list_responses_include_pagination_metadata(tmp_path: Path) -> None:
+ class _NoopParseService:
+ async def ensure_ingested(self, path: str) -> None:
+ return None
+
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
- server = DoclibServer(SimpleNamespace(db=db, scan_svc=scan_svc))
+ server = DoclibServer(SimpleNamespace(db=db, scan_svc=scan_svc, parse_svc=_NoopParseService()))
for index in range(3):
sha256 = str(index + 1) * 64
@@ -1950,6 +2019,7 @@ def test_doclib_server_list_responses_include_pagination_metadata(tmp_path: Path
)
parses = await server.list_parses(limit=1, offset=1)
+ files = await server.list_files(limit=1, offset=1)
scans = await server.list_scans(limit=1, offset=1)
docs = await server.list_docs(file_type="pdf", limit=1, offset=1)
@@ -1957,6 +2027,18 @@ def test_doclib_server_list_responses_include_pagination_metadata(tmp_path: Path
assert parses.limit == 1
assert parses.offset == 1
assert len(parses.parses) == 1
+ assert parses.parses[0].short_id == "2" * 7
+
+ assert files.total == 3
+ assert files.limit == 1
+ assert files.offset == 1
+ assert len(files.files) == 1
+ assert files.files[0].short_id == "2" * 7
+
+ file_detail = await server.get_file_by_path(str(tmp_path / "doc-1.pdf"))
+ assert file_detail.file.short_id == "2" * 7
+ assert len(file_detail.active_parses) == 1
+ assert file_detail.active_parses[0].short_id == "2" * 7
assert scans.total == 3
assert scans.limit == 1
@@ -1971,12 +2053,116 @@ def test_doclib_server_list_responses_include_pagination_metadata(tmp_path: Path
asyncio.run(_run())
+def test_doclib_server_accepts_short_id_for_sha256_doc_inputs(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ config_svc = ConfigService(db)
+ fts = FTSManager(db)
+ parse_svc = ParseService(
+ db=db,
+ fts=fts,
+ config_svc=config_svc,
+ data_dir=str(tmp_path),
+ parse_lock_timeout_sec=1800,
+ )
+ server = DoclibServer(SimpleNamespace(db=db, data_dir=str(tmp_path), parse_svc=parse_svc))
+ now = 1000
+ sha256 = "a" * 64
+ short_id = "aaaaaaa"
+ await db.execute(
+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (sha256, short_id, 12, "pdf", 1, now, now),
+ )
+ await db.execute(
+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (str(tmp_path / "doc.pdf"), "doc.pdf", "pdf", 12, now, sha256, "active", now, now),
+ )
+ await db.execute(
+ "INSERT INTO parses (sha256, tier, page_range, status, privacy, done_at, created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ (sha256, "standard", "1", "done", "local", now, now, now),
+ )
+ _write_batch(
+ tmp_path,
+ sha256,
+ "standard",
+ "1",
+ now,
+ ParseResult([_text_page("hello short id")]).to_dict(skip_defaults=True)["pages"],
+ )
+
+ doc_by_short_id = await server.get_doc(short_id, expand_files=True)
+ doc_by_sha256 = await server.get_doc(sha256, expand_files=True)
+ parses_by_short_id = await server.list_parses(doc_ref=short_id)
+ parses_by_sha256 = await server.list_parses(doc_ref=sha256)
+ missing_parses = await server.list_parses(doc_ref="ccccccc")
+ content = await server.get_doc_content(short_id, tier="standard", page_range="1")
+ export_path = tmp_path / "out.md"
+ exported = await server.export_doc_content(
+ short_id,
+ DocContentExportRequest(tier="standard", page_range="1", output=str(export_path)),
+ )
+ invalidated = await server.invalidate(InvalidateRequest(doc_ref=short_id, tier="standard"))
+
+ assert doc_by_short_id.sha256 == sha256
+ assert doc_by_short_id.short_id == short_id
+ assert doc_by_short_id.files is not None
+ assert doc_by_short_id.files[0].short_id == short_id
+ assert doc_by_sha256.short_id == short_id
+ assert parses_by_short_id.total == 1
+ assert parses_by_short_id.parses[0].sha256 == sha256
+ assert parses_by_sha256.total == 1
+ assert parses_by_sha256.parses[0].short_id == short_id
+ assert missing_parses.total == 0
+ assert content.sha256 == sha256
+ assert content.short_id == short_id
+ assert "hello short id" in content.content
+ assert exported.sha256 == sha256
+ assert exported.short_id == short_id
+ assert export_path.read_text(encoding="utf-8")
+ assert invalidated.sha256 == sha256
+ assert invalidated.short_id == short_id
+ assert invalidated.invalidated_count == 1
+
+ with pytest.raises(NotFoundError) as missing_doc_exc:
+ await server.get_doc("ccccccc")
+ assert missing_doc_exc.value.code == "doc_not_found"
+ assert missing_doc_exc.value.param == "doc_ref"
+
+ asyncio.run(_run())
+
+
+def test_get_file_by_path_missing_doclib_record_message_is_not_disk_file_not_found(tmp_path: Path) -> None:
+ class _ParseSvc:
+ async def ensure_ingested(self, path: str) -> None:
+ return None
+
+ async def _run() -> None:
+ db = _FakeDB(parses=[], file_row=None)
+ server = DoclibServer(SimpleNamespace(db=db, parse_svc=_ParseSvc()))
+
+ with pytest.raises(NotFoundError) as exc_info:
+ await server.get_file_by_path(str(tmp_path / "sample.png"))
+
+ assert exc_info.value.code == "file_not_found"
+ assert exc_info.value.param == "path"
+ assert "File record" in exc_info.value.message
+ assert "doclib" in exc_info.value.message
+
+ asyncio.run(_run())
+
+
def test_scan_service_cleanup_keeps_latest_terminal_scans_and_active_tasks(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
for index in range(1002):
@@ -2012,7 +2198,9 @@ def test_watch_loop_queues_watch_scan_when_scan_service_is_available(tmp_path: P
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
- parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ parse_svc = ParseService(
+ db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
watch_loop = WatchLoop(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_interval_sec=300, scan_svc=scan_svc)
root = tmp_path / "watched"
@@ -2259,7 +2447,18 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
await db.execute(
"INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, status, error_code, first_seen_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (str(tmp_path / "watched" / "blocked-ingest.pdf"), "blocked-ingest.pdf", "pdf", 7, now, watch["id"], "active", "ingest_failed", now, now),
+ (
+ str(tmp_path / "watched" / "blocked-ingest.pdf"),
+ "blocked-ingest.pdf",
+ "pdf",
+ 7,
+ now,
+ watch["id"],
+ "active",
+ "ingest_failed",
+ now,
+ now,
+ ),
)
await db.execute(
"INSERT INTO parses (sha256, tier, page_range, status, privacy, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
@@ -2331,7 +2530,10 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
assert status.recent_scans[1].error_msg == "hidden message"
assert status.last_scan_at == now + 5
assert status.error_summary is not None
- assert [(bucket.code, bucket.count) for bucket in status.error_summary.file_errors] == [("ingest_failed", 1), ("stat_failed", 1)]
+ assert [(bucket.code, bucket.count) for bucket in status.error_summary.file_errors] == [
+ ("ingest_failed", 1),
+ ("stat_failed", 1),
+ ]
assert [(bucket.code, bucket.count) for bucket in status.error_summary.doc_errors] == [("open_failed", 1)]
assert [(bucket.code, bucket.count) for bucket in status.error_summary.parse_errors] == [("parse_failed", 1)]
@@ -2471,7 +2673,9 @@ def test_ingest_records_doc_error_when_metadata_extraction_fails(tmp_path: Path,
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)
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=_NoRulesConfig(), data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
source = tmp_path / "broken.pdf"
source.write_bytes(b"%PDF-1.4\nnot actually a valid pdf")
@@ -2751,9 +2955,7 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
sidecar = image_dir / image_path
sidecar.parent.mkdir(parents=True)
sidecar.write_bytes(
- base64.b64decode(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
- )
+ base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
)
image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)
diff --git a/tests/unittest/test_doclib_db.py b/tests/unittest/test_doclib_db.py
new file mode 100644
index 00000000..ced34085
--- /dev/null
+++ b/tests/unittest/test_doclib_db.py
@@ -0,0 +1,22 @@
+import asyncio
+import sqlite3
+
+import pytest
+
+from mineru.doclib.core.db import DatabaseManager
+
+
+def test_failed_write_rolls_back_and_closes_connection(tmp_path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.execute("CREATE TABLE parent (id INTEGER PRIMARY KEY)")
+ await db.execute("CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id))")
+
+ with pytest.raises(sqlite3.IntegrityError):
+ await db.execute_insert("INSERT INTO child(parent_id) VALUES (?)", (999,))
+
+ await db.execute("INSERT INTO parent(id) VALUES (?)", (1,))
+ row = await db.fetchone("SELECT id FROM parent")
+ assert row == {"id": 1}
+
+ asyncio.run(_run())
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index 2e1a9d79..f6624c05 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -1,6 +1,6 @@
-import inspect
import asyncio
-from typing import get_type_hints
+import inspect
+from typing import Any, cast, get_type_hints
import pytest
from pydantic import ValidationError
@@ -202,8 +202,9 @@ def test_interface_app_uses_doclib_server_routes(tmp_path) -> None:
assert "/api/v1/parsing-rules/{rule_id}" in route_paths
assert "/api/v1/files" in route_paths
assert "/api/v1/docs" in route_paths
+ assert "/api/v1/docs/{doc_ref}" in route_paths
assert "/api/v1/content" in route_paths
- assert "/api/v1/docs/{sha256}/exports" in route_paths
+ assert "/api/v1/docs/{doc_ref}/exports" in route_paths
assert "/api/docs" in route_paths
assert "/docs" not in route_paths
assert "/api/v1/config" not in route_paths
@@ -228,6 +229,44 @@ def test_add_watch_rejects_missing_directory(tmp_path) -> None:
asyncio.run(_run())
+def test_add_watch_rejects_non_absolute_or_unnormalized_path_with_structured_error(tmp_path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ConfigService(db)
+
+ with pytest.raises(InvalidRequestError) as relative_exc:
+ await service.add_watch("relative/path")
+ assert relative_exc.value.code == "invalid_request"
+ assert relative_exc.value.param == "path"
+
+ root = tmp_path / "root"
+ root.mkdir()
+ unnormalized = str(root / ".." / root.name)
+
+ with pytest.raises(InvalidRequestError) as normalized_exc:
+ await service.add_watch(unnormalized)
+ assert normalized_exc.value.code == "invalid_request"
+ assert normalized_exc.value.param == "path"
+
+ asyncio.run(_run())
+
+
+def test_config_service_rejects_unsupported_rule_type_with_structured_error(tmp_path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ConfigService(db)
+
+ with pytest.raises(InvalidRequestError) as exc_info:
+ await service.list_rules(cast(Any, "bad-rule-type"))
+
+ assert exc_info.value.code == "invalid_request"
+ assert exc_info.value.param == "rule_type"
+
+ asyncio.run(_run())
+
+
def test_forget_watch_root_is_allowed_with_warning(tmp_path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
@@ -303,6 +342,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:
size_bytes=123,
mtime_ms=11,
sha256="abc",
+ short_id="abc",
watch_id=1,
status="active",
error_code="scan_failed",
@@ -330,6 +370,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:
parse_info = ParseInfo(
id=1,
sha256="abc",
+ short_id="abc",
tier="standard",
page_range="1~2",
status="pending",
@@ -378,6 +419,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:
)
search_result = SearchResult(
sha256="abc",
+ short_id="abc",
filename="a.pdf",
tier="standard",
snippet="matched text",
@@ -496,9 +538,10 @@ def test_next_cli_doclib_route_shapes_are_declared() -> None:
"get_file_by_path": ("GET", "/files/by-path"),
"list_docs": ("GET", "/docs"),
"get_doc_by_path": ("GET", "/docs/by-path"),
- "get_doc_content": ("GET", "/docs/{sha256}/content"),
+ "get_doc": ("GET", "/docs/{doc_ref}"),
+ "get_doc_content": ("GET", "/docs/{doc_ref}/content"),
"read_content": ("GET", "/content"),
- "export_doc_content": ("POST", "/docs/{sha256}/exports"),
+ "export_doc_content": ("POST", "/docs/{doc_ref}/exports"),
"get_config": ("GET", "/configs"),
"get_config_key": ("GET", "/configs/{key}"),
"set_config": ("PUT", "/configs/{key}"),
diff --git a/tests/unittest/test_errors.py b/tests/unittest/test_errors.py
index d3578a02..894b9551 100644
--- a/tests/unittest/test_errors.py
+++ b/tests/unittest/test_errors.py
@@ -1,6 +1,9 @@
from __future__ import annotations
-from mineru.errors import MineruError, http_status_for, error_type_for, registered_error_codes
+import httpx
+
+from mineru.cli.runtime import to_mineru_error
+from mineru.errors import MineruError, ServerNotRunningError, http_status_for, error_type_for, registered_error_codes
DOCLIB_PERSISTED_ERROR_CODES = {
@@ -17,14 +20,26 @@ DOCLIB_PERSISTED_ERROR_CODES = {
}
DOCLIB_CONTRACT_ERROR_CODES = {
+ "asset_not_available",
+ "bbox_not_available",
+ "block_not_found",
+ "context_not_applicable",
+ "doc_not_found",
"engine_unavailable",
+ "format_not_supported",
+ "invalid_config_key",
+ "invalid_locator",
+ "multi_page_image_not_supported",
"no_engine",
"not_cached",
+ "page_not_cached",
+ "parse_page_remap_failed",
"parse_server_unavailable",
"quality_tier_unavailable",
"rule_not_found",
"scan_not_found",
"tier_mismatch",
+ "tier_not_cached",
"watch_not_found",
}
@@ -40,9 +55,16 @@ def test_doclib_error_code_types_are_stable() -> None:
assert error_type_for("file_permission_denied") == "invalid_request_error"
assert error_type_for("stat_failed") == "invalid_request_error"
assert error_type_for("no_accessible_file") == "invalid_request_error"
+ assert error_type_for("bbox_not_available") == "invalid_request_error"
+ assert error_type_for("context_not_applicable") == "invalid_request_error"
+ assert error_type_for("format_not_supported") == "invalid_request_error"
+ assert error_type_for("invalid_config_key") == "invalid_request_error"
+ assert error_type_for("invalid_locator") == "invalid_request_error"
+ assert error_type_for("multi_page_image_not_supported") == "invalid_request_error"
assert error_type_for("parse_empty") == "engine_error"
assert error_type_for("parse_failed") == "engine_error"
+ assert error_type_for("parse_page_remap_failed") == "engine_error"
assert error_type_for("quality_tier_unavailable") == "engine_error"
assert error_type_for("ingest_failed") == "api_error"
@@ -55,10 +77,15 @@ def test_doclib_error_code_types_are_stable() -> None:
def test_http_status_for_error_codes_is_stable() -> None:
assert http_status_for("invalid_request") == 400
assert http_status_for("file_not_found") == 404
+ assert http_status_for("asset_not_available") == 404
+ assert http_status_for("block_not_found") == 404
+ assert http_status_for("doc_not_found") == 404
assert http_status_for("job_not_found") == 404
assert http_status_for("not_cached") == 404
+ assert http_status_for("page_not_cached") == 404
assert http_status_for("rule_not_found") == 404
assert http_status_for("scan_not_found") == 404
+ assert http_status_for("tier_not_cached") == 404
assert http_status_for("watch_not_found") == 404
assert http_status_for("invalid_api_key") == 401
@@ -76,3 +103,27 @@ def test_mineru_error_string_is_human_readable() -> None:
"Requested parsed content is not cached."
)
assert str(MineruError("not_cached")) == "not_cached"
+
+
+def test_cli_server_not_running_error_is_preserved() -> None:
+ error = to_mineru_error(ServerNotRunningError())
+
+ assert error.code == "server_not_running"
+ assert error.type == "api_error"
+ assert error.message == "Local mineru server is not running. Run 'mineru server start'."
+
+
+def test_cli_connection_error_uses_server_not_running_code() -> None:
+ error = to_mineru_error(httpx.ConnectError("connection refused"))
+
+ assert error.code == "server_not_running"
+ assert error.type == "api_error"
+ assert error.message == "Local mineru server is not running. Run 'mineru server start'."
+
+
+def test_cli_unknown_exception_uses_exception_message() -> None:
+ error = to_mineru_error(RuntimeError("boom"))
+
+ assert error.code == "api_error"
+ assert error.type == "api_error"
+ assert error.message == "boom"