Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: many new features
jinzhenj832031a1479e
diff --git a/NEXT-CLI.md b/NEXT-CLI.mdindex 013baaea..edfdfe89 100644--- a/NEXT-CLI.md+++ b/NEXT-CLI.md@@ -31,6 +31,7 @@ mineru-kit parse 中未出现在 mineru parse 的参数(如 `--backend`、`--m子命令:- mineru server start/stop/restart- mineru parse+- mineru read- mineru search@@ -91,7 +92,7 @@ mineru parse <file> [flags]| Flag | 简写 | 类型 | 默认 | 说明 ||------|------|------|------|------|| `-o, --output` | `-o` | path | `-` (STDOUT) | 输出路径。`-` 或省略表示输出到 STDOUT |-| `-f, --format` | `-f` | string | `markdown` | 输出格式: `markdown`, `text`, `json`, `html`。单选 |+| `-f, --format` | `-f` | string | `markdown` | 输出格式。当前仅支持 `markdown`。 || `--no-marker` | — | bool | false | 输出的 markdown/text 中不含文档结构标记 |### 同步控制@@ -222,40 +223,19 @@ $ mineru parse report.pdf --pages 11~20### 非分页文档(Word/PPT 等)-非分页文档的渐进式阅读方案待团队讨论确定,以下为两个候选方案:--**方案 A:虚拟分页(统一 `--pages` 语义)**--系统内部按段落边界将文档切分为虚拟页(每页约 3000~5000 字符),对外暴露统一的页码接口:+非分页文档当前不引入单独的 `--offset` 参数,而是和分页文档一样复用服务端返回的 continuation cursor。CLI 通过 `--after` 继续读取下一段内容:```bash$ mineru parse long.docx-# → 输出虚拟页 1~5 和倒数 5 页-# → marker: <!-- pages 6~20 not shown. Use: mineru parse long.docx --pages 6~10 -->-```--优势:agent 协议完全统一,不区分文件类型。-劣势:需要解释"虚拟页"概念。+# → 输出第一段内容+# → marker: <!-- next content available.+# Use: mineru parse long.docx --after doc:ab12cd3/tier:standard/page:1/block:12/char:520 -->-**方案 B:字符偏移(`--offset`)**--截断位置对齐到段落边界,marker 中给出字符偏移:--```bash-$ mineru parse long.docx-# → 输出前 ~30K 字符(对齐到段落边界)-# → marker: <!-- truncated at paragraph boundary (char ~30000 of ~150000).-# Next: mineru parse long.docx --offset 30000 -->--$ mineru parse long.docx --offset 30000-# → 输出 30K~60K 字符-# → marker: <!-- Next: mineru parse long.docx --offset 60000 -->+$ mineru parse long.docx --after doc:ab12cd3/tier:standard/page:1/block:12/char:520+# → 输出后续内容```-优势:无新概念,实现简单。-劣势:PDF 用 `--pages`,Word 用 `--offset`,agent 需处理两种参数。--> **团队讨论项**:选择方案 A 或方案 B。+这意味着非分页文档的增量读取当前以 cursor 为正式协议,字符 offset 只作为 cursor 内部语义的一部分存在,不作为 `parse` 的公开 CLI 参数暴露。## STDOUT 输出行为@@ -268,6 +248,20 @@ $ mineru parse long.docx --offset 30000- 输出 `--pages` 指定范围的完整内容,无额外截断- 图片信息同样以 marker 形式嵌入(图片文件单独存储在数据库中)+当使用 `--json` 时,`mineru parse` 输出命令级 JSON envelope,而不是直接输出裸内容对象:++```json+{+ "parse": { "... parse summary ..." },+ "content": { "... DocContentResponse ..." } | null+}+```++其中:+- `parse` 始终存在,描述本次 `parse` 请求的解析状态摘要。+- `content` 仅在结果已经可读取时存在值;`--no-wait` 或等待超时但尚未完成时为 `null`。+- 错误场景仍输出结构化错误 JSON。+## 同步等待行为| 场景 | 默认行为 |@@ -319,6 +313,87 @@ mineru parse doc.pdf --no-marker```+# mineru read++## 概述++`read` 是 `mineru` 的 locator-first 读取子命令。它读取 doclib 中已有的解析结果,不负责 discover、scan、ingest,也不默认创建 parse task。++与 `parse` 的边界:++```text+parse(path) = ensure document is parsed, then read default content+read(locator) = read existing parsed content by stable locator+```++## Usage++```bash+mineru read <locator> [flags]+```++当前 P0 支持:++```bash+mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]+```++## Locator++```text+doc:{short_id}+doc:{short_id}/tier:{tier}+doc:{short_id}/tier:{tier}/page:{page_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}+```++其中:+- `page_no` 和 `block_no` 使用 1-based 编号+- `char:{offset}` 使用 block 渲染文本内的 0-based 字符 offset++## 输出++- `--format markdown`:默认读取文本内容+- `--format image`:读取 page 或 block 的图像输出+- `--json`:输出完整 `DocContentResponse`+- `--output`:由 CLI 在本地写入 markdown 文件或 copy image asset++## Image 约束++- PDF:+ - page locator 支持 image+ - block locator 仅在 block 有非空 bbox 时支持 image+- Office:+ - 仅 image block 支持 image+- doc locator 和 doc/tier locator 不支持 image+- 不支持多页 image++## Continuation++`read` 的 continuation 使用 locator:++```text+<!-- Next: mineru read doc:ab12cd3/tier:standard/page:5 -->+```++## 示例++```bash+# 读取某页+mineru read doc:ab12cd3/tier:standard/page:4++# 读取某个 block 及其上下文+mineru read doc:ab12cd3/tier:standard/page:4/block:12 --context 2++# 导出 page image+mineru read doc:ab12cd3/tier:standard/page:4 --format image --output page4.jpg++# JSON 输出+mineru read doc:ab12cd3/tier:standard/page:4 --json+```++# mineru server## 概述diff --git a/NEXT-ROADMAP.md b/NEXT-ROADMAP.mdindex 3d70edbf..f2a8b993 100644--- a/NEXT-ROADMAP.md+++ b/NEXT-ROADMAP.md@@ -160,7 +160,7 @@ Privacy First 收窄到两件事,分别处理:| 项目 | 验收指标 ||------|---------|| Skill 决策树 | eval 集 100 题 Agent 首选正确率 ≥85% |-| 中间结构统一 | 三 backend 通过统一 schema validation;同输入 chunk_id 跨进程一致 |+| 中间结构统一 | 三 backend 通过统一 schema validation;同输入 page/block locator 跨进程一致 || 文档库 SHA256 缓存 | 二次 parse 相同输入 P95 响应 <100ms;缓存命中率 ≥60% || Agent-native(4.2 七条)| 端到端 5 个 Agent 真实任务场景成功率 ≥80% || 改进计划 | CLI / GUI 首次启动 Tier 1 opt-in 率 ≥40% |@@ -212,14 +212,14 @@ Agent| 结构化 message contract | 所有 CLI 与 MCP 出口遵循统一结构化 schema,替代 free-text 文本输出,Agent 无需文本解析即可消费 || 确定性错误码 | typed error code 替代 free-text 错误信息,每个错误自带修复建议(如 `E_OCR_REQUIRED` 提示加 `--ocr`),Agent 可基于错误码做分支处理与自动重试 || token-budgeted 输出 | 解析支持指定 token 上限,自动按页边界截断并返回 continuation 引导,避免长文档撑爆 Agent context;内置 tokenizer 开箱即用 |-| 可寻址引用 chunk ID | 每个 chunk 输出稳定 ID(含 backend / page / block),支持按 ID 反查,Agent 答案天然可 citation,用户可回溯原文 |-| 区域/页面查询 | 解析阶段支持按页码与 chunk 类型过滤,只取所需内容,避免全文解析的 token 与时延浪费 |+| 可寻址 page/block locator | 每个可引用 block 输出稳定 locator(含 tier / page / block),支持按 locator 反查,Agent 答案天然可 citation,用户可回溯原文 |+| 区域/页面查询 | 解析阶段支持按页码与 block/content 类型过滤,只取所需内容,避免全文解析的 token 与时延浪费 || Skill 决策树 | Skill 内嵌三类映射:"环境检测 → 引导安装(uv install mineru)"、"用户场景 → 命令路由"、"错误码 → 修复动作"。支持普通用户零配置首次使用,降低 Agent 参数选择错误率,配 eval 集回归 || SHA256 内容寻址缓存 | `mineru` 内置文档库提供 SHA256 去重缓存,Agent 相同输入二次调用毫秒级返回 |#### 依赖-本节多数特性依赖 5.3 节中间结构统一的最小子集(chunk 稳定 ID + page + bbox + type)。+本节多数特性依赖 5.3 节中间结构统一的最小子集(稳定 page/block locator + page + bbox + type)。不做的能力(chunking / embedding / chat / RAG / summary 等)见 1.2 节。diff --git a/docs/next/cli.md b/docs/next/cli.mdindex 8fa9386d..47209e2f 100644--- a/docs/next/cli.md+++ b/docs/next/cli.md@@ -13,8 +13,9 @@ CLI 文档已拆分到 [cli/README.md](cli/README.md)。1. [CLI 总览](cli/README.md)2. [mineru](cli/mineru.md)3. [mineru parse](cli/mineru-parse.md)-4. [mineru server](cli/mineru-server.md)-5. [mineru library](cli/mineru-library.md)-6. [mineru-kit](cli/mineru-kit.md)-7. [mineru-kit parse](cli/mineru-kit-parse.md)-8. [mineru-kit api-server](cli/mineru-kit-api-server.md)+4. [mineru read](cli/mineru-read.md)+5. [mineru server](cli/mineru-server.md)+6. [mineru library](cli/mineru-library.md)+7. [mineru-kit](cli/mineru-kit.md)+8. [mineru-kit parse](cli/mineru-kit-parse.md)+9. [mineru-kit api-server](cli/mineru-kit-api-server.md)diff --git a/docs/next/cli/README.md b/docs/next/cli/README.mdindex f1bece62..c04f45cb 100644--- a/docs/next/cli/README.md+++ b/docs/next/cli/README.md@@ -36,11 +36,12 @@ MinerU 仓库提供两款命令行工具:1. [mineru](mineru.md): 理解用户/Agent 入口的整体定位。2. [mineru parse](mineru-parse.md): 理解主动解析、默认 tier 选择、隐私、缓存、STDOUT 和 marker。-3. [mineru server](mineru-server.md): 理解 doclib 生命周期和 parse-server 协作。-4. [mineru library](mineru-library.md): 理解 search、find、info、config、watch 和 parsing-rules。-5. [mineru-kit](mineru-kit.md): 理解无状态工具定位。-6. [mineru-kit parse](mineru-kit-parse.md): 理解批处理解析、目录/stdin、并发和输出冲突。-7. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。+3. [mineru read](mineru-read.md): 理解 locator-first 读取、page/block 定位、image 输出和 continuation。+4. [mineru server](mineru-server.md): 理解 doclib 生命周期和 parse-server 协作。+5. [mineru library](mineru-library.md): 理解 search、find、info、config、watch 和 parsing-rules。+6. [mineru-kit](mineru-kit.md): 理解无状态工具定位。+7. [mineru-kit parse](mineru-kit-parse.md): 理解批处理解析、目录/stdin、并发和输出冲突。+8. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。## 4. 共享约束diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.mdnew file mode 100644index 00000000..5a08540c--- /dev/null+++ b/docs/next/cli/mineru-e2e-test-cases.md@@ -0,0 +1,2750 @@+# mineru CLI 端到端测试用例++状态: Draft+读者: CLI 测试执行 Agent、QA、核心开发者+范围: 只测试本地安装的 `mineru` 命令+非目标: 测试 `mineru-kit`、直接访问数据库、调用内部 Python API、验证具体解析模型质量++## 1. 执行规则++执行 Agent 只允许调用本地安装的 `mineru` 命令。++严禁调用:++- `mineru-kit`+- `python`+- `sqlite`+- `curl`+- 项目内部模块+- 任何直接修改 MinerU 数据库或缓存目录的命令++每条用例必须记录:++- case id+- command+- exit code+- stdout+- stderr+- pass / fail / blocked+- 失败原因++## 2. 前置条件++测试环境需提前准备:++- 本地命令 `mineru` 已安装并在 `PATH` 中。+- 环境变量 `MINERU_E2E_FIXTURE_DIR` 指向测试数据目录。+- 测试数据目录至少包含:+ - `$MINERU_E2E_FIXTURE_DIR/sample.pdf`+ - `$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf`,内容与 `sample.pdf` 相同,路径不同。+ - `$MINERU_E2E_FIXTURE_DIR/watch-dir/watch-doc.pdf`+ - `$MINERU_E2E_FIXTURE_DIR/empty-dir/`,空目录。+ - `$MINERU_E2E_FIXTURE_DIR/unsupported.bin`,不支持的普通二进制或文本文件。+ - `$MINERU_E2E_FIXTURE_DIR/sample doc.pdf`,文件名包含空格,内容可与 `sample.pdf` 相同。+ - `$MINERU_E2E_FIXTURE_DIR/中文样例.pdf`,文件名包含中文,内容可与 `sample.pdf` 相同。+ - `$MINERU_E2E_FIXTURE_DIR/corrupted.pdf`,损坏 PDF。+ - `$MINERU_E2E_FIXTURE_DIR/empty.pdf`,空文件或无法解析出页面的 PDF。+ - `$MINERU_E2E_FIXTURE_DIR/sample.docx`、`sample.pptx`、`sample.xlsx`,Office 样例文件;若当前安装不支持 Office,可按预期失败分支判定。+ - `$MINERU_E2E_FIXTURE_DIR/sample.png`,图片样例文件;若当前安装不支持图片输入,可按预期失败分支判定。+ - `$MINERU_E2E_FIXTURE_DIR/symlink-sample.pdf`,指向 `sample.pdf` 的符号链接;若平台不支持 symlink,可标记相关用例 BLOCKED。+ - `$MINERU_E2E_FIXTURE_DIR/no-read.pdf`,权限不可读文件;若平台无法稳定制造权限场景,可标记相关用例 BLOCKED。+ - `$MINERU_E2E_FIXTURE_DIR/output-dir/`,用于输出文件测试的目录。+- 测试环境允许启动本地 doclib server。+- 若本地没有 standard/pro parse-server,默认 tier 相关用例按预期失败分支判定。+- 若 remote parse-server 不可用,`--remote` 相关用例按预期失败分支判定;若可用,必须验证 remote/via/privacy 等字段。++### 2.1 测试 HOME 与隔离配置++测试 HOME 使用:++```bash+~/mineru-e2e-test+```++进入测试目录后,必须设置以下环境变量,让 doclib 的 DB、日志和 UDS socket 都落在测试目录中:++```bash+cd ~/mineru-e2e-test+export MINERU_DOCLIB_DATA_DIR=`pwd`+export MINERU_DOCLIB_SQLITE_PATH=`pwd`/mineru.db+export MINERU_DOCLIB_LOG_PATH=`pwd`/mineru.log+export MINERU_DOCLIB_UDS_PATH=`pwd`/mineru.sock+```++### 2.2 安装方法++在测试 HOME 中创建独立虚拟环境并安装当前仓库:++```bash+cd ~/mineru-e2e-test+rm -rf .venv+uv venv .venv+source .venv/bin/activate+uv pip install ~/MinerU-Repo+alias mineru="python -m mineru.cli_next.main"+```++安装完成后,执行 Agent 后续仍只调用 `mineru ...` 命令,不直接调用 Python 模块、内部 API 或数据库。++## 3. 顶层命令与帮助++### CLI-001 顶层 help++命令:++```bash+mineru --help+```++预期:++- exit code = 0+- 输出包含 `parse`、`read`、`scan`、`watch`、`search`、`find`、`list`、`show`、`server`、`config`、`invalidate`、`forget`、`cleanup`+- 输出不包含 `mineru-kit`++### CLI-002 子命令 help++命令:++```bash+mineru parse --help+mineru read --help+mineru scan --help+mineru watch --help+mineru search --help+mineru find --help+mineru list --help+mineru show --help+mineru server --help+mineru config --help+mineru invalidate --help+mineru forget --help+mineru cleanup --help+```++预期:++- 每条 exit code = 0+- 每条输出包含 usage 或 options 类帮助信息++### CLI-002A output/help 契约++命令:++```bash+mineru parse --help+mineru read --help+```++预期:++- 两条 exit code = 0+- `--output` help 文案说明可写入文件+- `--output` help 文案或相邻说明应体现父目录可自动创建+- `--json` help 文案或相邻说明应体现 JSON 输出+- parse/read help 不得暗示 `--output` 与 `--json` 互斥++### CLI-003 不存在旧命令++命令:++```bash+mineru info --help+```++预期:++- exit code != 0++## 4. Server 生命周期++### SERVER-001 查询初始状态++命令:++```bash+mineru server status+```++预期:++- exit code = 0+- 输出为 server 运行信息或 `Server is not running.`++### SERVER-001A 查询初始 JSON 状态++命令:++```bash+mineru server status --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- 如果 server 未运行,JSON 为稳定状态结果,至少包含 `running: false`+- server 未运行不应输出 JSON error+- stdout 不包含 `Server is not running.` 人类文本++### SERVER-002 启动 server++命令:++```bash+mineru server start+```++预期:++- exit code = 0+- 如果已运行,输出包含 `already running`+- 如果未运行,输出包含 `started` 或 `Socket`++### SERVER-003 查询运行状态++命令:++```bash+mineru server status+```++预期:++- exit code = 0+- 输出包含 server 状态信息+- 不提示连接失败++### SERVER-004 JSON 状态++命令:++```bash+mineru server status --json+```++预期:++- server 运行时 exit code = 0+- 输出为 JSON 或等价结构化 server 状态+- 至少包含 running、socket、data_dir、队列或文档库统计中的若干字段++### SERVER-005 重复启动 server++前置: SERVER-002 已成功,server 正在运行。++命令:++```bash+mineru server start+```++预期:++- exit code = 0+- 输出包含 `already running`+- 不启动第二个不可控 server 进程+- 后续 `mineru server status` 仍可正常返回++### SERVER-006 restart server++命令:++```bash+mineru server restart+mineru server status --json+```++预期:++- 两条 exit code = 0+- restart 输出包含 stopped/started、started、Socket 或等价生命周期信息+- status 输出为 JSON+- JSON 表示 server 正在运行+- UDS/socket 路径仍落在测试 HOME 配置下++### SERVER-007 stop 后依赖 server 的命令报错可读++命令:++```bash+mineru server stop+mineru list files --limit 1+mineru server start+```++预期:++- stop exit code = 0+- list files exit code != 0+- list files 输出包含 `Cannot connect`、`server`、`Run 'mineru server start' first` 或等价可操作错误+- list files 不包含 Python traceback+- 最后一条 start exit code = 0,用于恢复后续测试环境++### SERVER-009 环境变量路径生效++命令:++```bash+mineru server status --json+```++预期:++- exit code = 0+- 输出为 JSON+- `data_dir` 等价于 `MINERU_DOCLIB_DATA_DIR`+- socket/UDS 字段等价于 `MINERU_DOCLIB_UDS_PATH`,如果字段名为 `socket_path` 则不得为空+- 日志相关字段或启动失败日志路径应落在 `MINERU_DOCLIB_LOG_PATH`++## 5. Config 命令++### CONFIG-001 查看配置++命令:++```bash+mineru config show+```++预期:++- exit code = 0+- 输出包含 `Config` 或配置 key++### CONFIG-002 JSON 查看配置++命令:++```bash+mineru config show --json+```++预期:++- exit code = 0+- 输出为 JSON+- 包含 config 或 sources 信息++### CONFIG-003 设置和读取配置++命令:++```bash+mineru config set parse_server.local.mode disabled+mineru config get parse_server.local.mode+```++预期:++- 两条 exit code = 0+- get 输出包含 `parse_server.local.mode`+- get 输出包含 `disabled`++### CONFIG-003A JSON 读取配置++命令:++```bash+mineru config set parse_server.local.mode disabled+mineru config get parse_server.local.mode --json+```++预期:++- 两条 exit code = 0+- set 使用普通文本输出;本用例不要求 `config set` 支持 `--json`+- get stdout 为可直接解析的 JSON+- get JSON 包含 `parse_server.local.mode`+- get JSON 中 value 为 `disabled` 或等价配置值++### CONFIG-004 unset 配置++命令:++```bash+mineru config unset parse_server.local.mode+mineru config get parse_server.local.mode+```++预期:++- 两条 exit code = 0+- unset 输出包含 `removed` 或 `unchanged`+- get 仍能返回有效配置值++### CONFIG-004A unset 后 JSON 读取配置++命令:++```bash+mineru config set parse_server.local.mode disabled+mineru config unset parse_server.local.mode+mineru config get parse_server.local.mode --json+```++预期:++- 三条 exit code = 0+- unset 使用普通文本输出;本用例不要求 `config unset` 支持 `--json`+- get 输出为可直接解析的 JSON+- unset 后 get 仍能返回有效配置值++### CONFIG-005 exclude-rules++命令:++```bash+mineru config exclude-rules add "*/tmp-mineru-e2e-ignore/*" --priority 10+mineru config exclude-rules list+```++预期:++- 两条 exit code = 0+- list 输出包含该 pattern 或规则 id++### CONFIG-005A exclude-rules JSON 和 remove++命令:++```bash+mineru config exclude-rules add "*/tmp-mineru-e2e-remove/*" --priority 11 --json+mineru config exclude-rules list --json+mineru config exclude-rules remove <rule_id>+mineru config exclude-rules list --json+```++执行说明:++- `<rule_id>` 从第一条 add JSON 输出或第二条 list JSON 输出中提取。++预期:++- 四条 exit code = 0+- add/list JSON 均可直接解析+- remove 前 list 中包含 pattern `*/tmp-mineru-e2e-remove/*`+- remove 输出包含 `removed`、`Exclude rule` 或等价成功信息+- remove 后 list 中不再包含该 rule id++### CONFIG-006 旧 exclude 命令不可用++命令:++```bash+mineru config exclude --help+```++预期:++- exit code != 0++### CONFIG-007 parsing-rules++命令:++```bash+mineru config parsing-rules add "*/mineru-e2e/*" --tier flash --pages all --name e2e-flash-rule+mineru config parsing-rules list+```++预期:++- 两条 exit code = 0+- list 输出包含 pattern+- list 输出包含 `flash`+- list 输出包含 `all`++### CONFIG-008 parsing-rules JSON 和 remove++命令:++```bash+mineru config parsing-rules add "*/mineru-e2e-remove/*" --tier flash --pages 1~1 --name e2e-remove-rule --json+mineru config parsing-rules list --json+mineru config parsing-rules remove <rule_id>+mineru config parsing-rules list --json+```++执行说明:++- `<rule_id>` 从第一条 add JSON 输出或第二条 list JSON 输出中提取。++预期:++- 四条 exit code = 0+- add/list JSON 均可直接解析+- remove 前 list 中包含 pattern、`flash`、`1~1`+- remove 输出包含 `removed`、`Parsing rule` 或等价成功信息+- remove 后 list 中不再包含该 rule id++### CONFIG-009 不存在的配置 key++命令:++```bash+mineru config get not.a.real.key+mineru config get not.a.real.key --json+```++预期:++- 两条命令应有一致、可解释的行为+- 如果 exit code = 0,输出必须明确表示 key 不存在、值为空或来源为默认缺失+- 如果 exit code != 0,输出必须包含 not found、unknown key、invalid key 或等价错误+- `--json` 失败时 stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+- 不包含 Python traceback++## 6. Watch 命令++### WATCH-001 添加 watch++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/watch-dir" --label e2e-watch+```++预期:++- exit code = 0+- 输出包含 `Watch added` 或 id++### WATCH-001A 重复添加 watch++前置: WATCH-001 已成功。++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/watch-dir" --label e2e-watch+```++预期:++- 命令应有明确行为:+ - 若允许幂等,exit code = 0,输出包含 existing、already、Watch added 或等价信息+ - 若不允许重复,exit code != 0,输出包含 duplicate、already exists 或等价错误+- 不产生不可解释的重复 watch 记录+- 不包含 Python traceback++### WATCH-002 列出 watch++命令:++```bash+mineru watch list+```++预期:++- exit code = 0+- 输出包含 `$MINERU_E2E_FIXTURE_DIR/watch-dir` 或 `e2e-watch`++### WATCH-003 JSON 列出 watch++命令:++```bash+mineru watch list --json+```++预期:++- exit code = 0+- 输出为 JSON+- 包含 watches 数组或 watch 信息++### WATCH-004 watch rescan++命令:++```bash+mineru watch rescan "$MINERU_E2E_FIXTURE_DIR/watch-dir" --wait 30+```++预期:++- exit code = 0+- 输出包含 `Scan`+- 状态为 done、running 或 pending 均可接受+- 不出现 `watch_not_found`++### WATCH-004A 使用 watch id rescan++前置: WATCH-002 或 WATCH-003 可获得 watch id。++命令模板:++```bash+mineru watch rescan <watch_id> --wait 30+mineru watch rescan <watch_id> --no-wait --json+```++预期:++- 两条 exit code = 0+- 第一条输出包含 `Scan`+- 第二条输出为可直接解析的 JSON+- JSON 包含 scan id、status、path 或 watch_id 中的部分字段++### WATCH-005 删除 watch++命令:++```bash+mineru watch remove "$MINERU_E2E_FIXTURE_DIR/watch-dir"+```++预期:++- exit code = 0+- 输出包含 `Watch removed`++### WATCH-006 删除不存在的 watch++命令:++```bash+mineru watch remove "$MINERU_E2E_FIXTURE_DIR/not-a-watch-dir"+```++预期:++- exit code != 0+- 输出包含 `watch_not_found`、not found 或等价错误+- 不包含 Python traceback++### WATCH-007 添加不存在目录++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/not-exist-dir" --label e2e-missing-watch+```++预期:++- exit code != 0+- 输出包含 not found、unreachable、invalid path 或等价错误+- 不包含 Python traceback++## 7. Scan 命令++### SCAN-001 扫描单文件++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --wait 30+```++预期:++- exit code = 0+- 输出包含 `Scan`+- 输出包含 seen、refreshed、new、changed、deleted 中的统计字段++### SCAN-002 扫描目录 no-wait++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR" --no-wait --json+```++预期:++- exit code = 0+- 输出为 JSON+- 包含 scan id、status、path 或 kind 字段+- kind 应为 manual++### SCAN-003 扫描不存在路径++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR/not-exist"+mineru scan "$MINERU_E2E_FIXTURE_DIR/not-exist" --json+```++预期:++- 两条 exit code != 0+- 输出包含 not found、unreachable、invalid path 或等价错误+- 不包含 Python traceback+- JSON 模式不得输出半截 JSON 混合 traceback++### SCAN-004 扫描空目录++前置: 测试数据目录预先包含空目录 `$MINERU_E2E_FIXTURE_DIR/empty-dir/`。++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR/empty-dir" --wait 30+mineru scan "$MINERU_E2E_FIXTURE_DIR/empty-dir" --wait 30 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可直接解析+- 统计字段中 seen/new/changed/deleted 等计数为 0 或符合空目录语义+- 不包含 Python traceback++### SCAN-005 扫描不支持文件类型++前置: 测试数据目录预先包含不支持文件 `$MINERU_E2E_FIXTURE_DIR/unsupported.bin`。++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR/unsupported.bin" --wait 30+mineru scan "$MINERU_E2E_FIXTURE_DIR/unsupported.bin" --wait 30 --json+```++预期:++- 两条 exit code = 0 或返回明确的 unsupported 错误+- 如果 exit code = 0,输出统计中应体现 unsupported 或 excluded 计数+- 如果 exit code != 0,输出包含 unsupported、invalid type 或等价错误+- 不包含 Python traceback++## 8. Parse 命令++### PARSE-001 文件不存在++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/not-exist.pdf"+```++预期:++- exit code != 0+- 输出包含 `File not found`++### PARSE-002 显式 flash parse++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60+```++预期:++- exit code = 0+- 输出不包含 Python traceback+- 输出为可读 Markdown、文本内容或 parse 状态提示++### PARSE-003 flash parse JSON++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- exit code = 0+- 输出为 JSON+- 顶层包含 `parse` 与 `content`+- `parse.sha256` 或等价 doc 标识存在+- `parse.tier = flash`+- `parse.status = done`+- `content` 不为 null+- `content.request_scope`、`content.content_ranges` 或 `content.next_request` 中至少一部分字段存在++### PARSE-004 cache hit 行为++重复执行:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- exit code = 0+- 不重新失败+- 若 JSON 中包含 cache_hit,应为 true 或体现已复用结果+- tier 仍为 flash++### PARSE-005 no-wait 行为++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --no-wait --json+```++预期:++- exit code = 0+- 输出为 JSON+- 顶层包含 `parse` 与 `content`+- `parse.status` 为 `pending`、`parsing` 或 `done`+- 若 `parse.status` 不是 `done`,则 `content = null`+- 若命中缓存直接完成,则 `content` 可直接返回+- 不长时间阻塞++### PARSE-006 force 行为++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60 --json+```++预期:++- exit code = 0+- 输出为 JSON+- 不删除旧缓存导致后续普通 parse 失败++### PARSE-006A force 默认输出不打印过程 status++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60+```++预期:++- exit code = 0+- 输出为解析内容、Markdown 或最终可读结果+- 默认模式输出不包含 `Parse status:`+- 默认模式输出不包含 `Parse queued`+- 不包含 Python traceback++### PARSE-006B verbose 输出允许过程 status++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60 --verbose+```++预期:++- exit code = 0+- 输出允许包含 `Parse queued`+- 输出允许包含 `Parse status:`+- 最终仍输出解析内容、Markdown 或最终可读结果+- 不包含 Python traceback++### PARSE-007 默认 tier 行为++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --pages 1~1 --wait 20 --json+```++预期分支:++- 如果本地 standard/pro parse-server 可用:+ - exit code = 0+ - 实际 tier 为 standard 或 pro+ - 实际 tier 不为 flash+- 如果只有 flash 或没有 quality tier:+ - exit code != 0+ - 输出包含 `quality_tier_unavailable`、`no_engine`、`parse_server_unavailable`、start parse-server 或 use remote 等可操作错误+ - 不允许静默返回 flash 内容++### PARSE-008 输出到文件++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output "$MINERU_E2E_FIXTURE_DIR/parse-output.md"+```++预期:++- exit code = 0+- 输出包含 `Written to` 或等价成功信息+- 不在 stdout 大量打印完整文档内容+- 后续可通过 `mineru read` 或重新 `mineru parse` 验证解析缓存仍可用+- 输出文件路径应为命令指定路径++### PARSE-009 JSON 与 output 组合++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output "$MINERU_E2E_FIXTURE_DIR/parse-output-json.md" --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 顶层保持 `parse --json` envelope,包含 `parse` 和 `content`+- 当文件写出成功时,`content` 可以为 null+- JSON 顶层包含 `output`+- `output.status` = `written`+- `output.path` 为实际写入路径,建议为绝对路径或规范化绝对路径+- 输出文件存在,路径为命令指定路径+- stdout 不允许包含 `Written to`、Rich 表格、Markdown 正文或其它人类提示文本+- 不包含 Python traceback++### PARSE-010 limit 截断与 next_request++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --limit 20 --json+```++预期:++- exit code = 0+- 输出为可直接解析的 JSON+- `content` 不为 null+- 如果内容超过 limit,`content` 中应体现 truncated、next_request、cursor、after 或等价续读信息+- 如果内容未超过 limit,`content` 中应明确表示未截断或没有 next_request+- 不包含 JSON 外的 status/info 文本++### PARSE-011 after 续读++前置: PARSE-010 返回 next_request.after 或等价 cursor。++命令模板:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --after <after_cursor> --limit 30000 --json+```++预期:++- exit code = 0+- 输出为可直接解析的 JSON+- `content` 不为 null+- `content.request_scope`、`content.content_ranges` 或等价字段体现 after/cursor 已生效+- 不返回与第一页起始完全相同的截断片段,除非服务端明确说明 cursor 已到末尾++### PARSE-012 no-marker++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --limit 20 --no-marker+```++预期:++- exit code = 0+- 输出不包含 `<!-- Next:`+- 输出不包含 Python traceback++### PARSE-013 remote parse 分支++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --remote --wait 20 --json+```++预期分支:++- 如果 remote parse-server 可用:+ - exit code = 0+ - 输出为可直接解析的 JSON+ - JSON 体现 remote/via/privacy/tier 中的部分字段+- 如果 remote parse-server 不可用:+ - exit code != 0+ - 输出包含 remote、parse-server、unavailable、no_engine 或等价可操作错误+ - stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+ - 不包含 Python traceback++### PARSE-013A remote 默认 tier++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --remote --pages 1~1 --wait 60 --json+```++预期分支:++- 如果 remote parse-server 可用:+ - exit code = 0+ - 输出为可直接解析的 JSON+ - tier 应为 remote 支持的 quality tier,例如 standard 或 pro+ - JSON 体现 remote/via/privacy 中的部分字段+ - 不允许在未声明 fallback 的情况下静默返回本地 flash 内容+- 如果 remote parse-server 不可用:+ - exit code != 0+ - `--json` 输出必须为可直接解析的 JSON error+ - error code/message 包含 remote、parse-server、unavailable、no_engine、quality_tier_unavailable 或等价可操作信息+ - 不包含 Python traceback++### PARSE-013B remote no-wait++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --remote --pages 1~1 --no-wait --json+```++预期分支:++- 如果 remote parse-server 可用:+ - exit code = 0+ - 输出为可直接解析的 JSON+ - 输出为已完成内容、pending/parsing 任务状态或明确缓存结果+ - 不长时间阻塞+- 如果 remote parse-server 不可用:+ - exit code != 0+ - 输出包含 remote、parse-server、unavailable 或等价错误+ - stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+ - 不包含 Python traceback++### PARSE-013C remote force++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --remote --pages 1~1 --force --wait 60 --json+```++预期分支:++- 如果 remote parse-server 可用:+ - exit code = 0+ - 输出为可直接解析的 JSON+ - 不复用旧的 done batch 作为唯一依据,JSON 中应体现新 parse 或 force 后结果+ - 后续普通 remote parse 不因 force 损坏缓存+- 如果 remote parse-server 不可用:+ - exit code != 0+ - 输出包含 remote、parse-server、unavailable 或等价错误+ - stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+ - 不包含 Python traceback++### PARSE-013D remote output++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --remote --pages 1~1 --wait 60 --output "$MINERU_E2E_FIXTURE_DIR/output-dir/remote-output.md"+```++预期分支:++- 如果 remote parse-server 可用:+ - exit code = 0+ - 输出包含 `Written to` 或等价成功信息+ - stdout 不大量打印完整文档内容+ - 输出路径为命令指定路径+- 如果 remote parse-server 不可用:+ - exit code != 0+ - 输出包含 remote、parse-server、unavailable 或等价错误+ - 不创建空的成功输出文件+ - 不包含 Python traceback++### PARSE-013E remote 与 local cache 隔离++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --remote --pages 1~1 --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- 第一条和第三条 local flash 命令 exit code = 0,tier = flash+- 第二条按 PARSE-013A 的 remote 可用/不可用分支判定+- remote 成功或失败均不得污染 local flash 缓存+- 第三条不应因为第二条 remote 失败而失败++### PARSE-013F remote 配置规则++命令:++```bash+mineru config parsing-rules add "*/sample.pdf" --remote --pages 1~1 --name e2e-remote-rule --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --wait 60 --json+mineru config parsing-rules remove <rule_id>+```++执行说明:++- `<rule_id>` 从第一条 add JSON 中提取。++预期分支:++- add/remove exit code = 0,JSON 可解析+- 如果 remote parse-server 可用,parse 应按 remote 规则执行,JSON 体现 remote/via/privacy 中的部分字段+- 如果 remote parse-server 不可用,parse 应返回明确 remote/parse-server 不可用错误+- parse 失败且命令带 `--json` 时,stdout 必须为可直接解析的 JSON error+- remove 后规则不再影响后续 parse++### PARSE-014 非法 format++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --format html+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --format text+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --format json+```++预期:++- 三条 exit code != 0+- 输出包含 invalid choice、not one of、unsupported format 或等价错误+- 不启动解析任务+- 不包含 Python traceback++### PARSE-015 JSON 输出纯净性++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60 --json+```++预期:++- exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 `Parse status:`+- stdout 不包含 `Parse queued`+- stdout 不包含 `Written to`+- stderr 不包含非错误噪声++## 9. Read 命令++前置: PARSE-003 或 PARSE-004 至少成功一次,并从输出、`show file` 或 `list docs` 获得 doc short id。++如果无法获得 short id,READ 子套件标记为 BLOCKED。++### READ-001 读取 page locator++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --limit 30000+```++预期:++- exit code = 0+- 输出为 Markdown、文本或可读内容+- 不包含 traceback++### READ-002 read JSON++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --json+```++预期:++- exit code = 0+- 输出为 JSON+- JSON 包含 request_scope+- request_scope.locator 包含输入 locator 或规范化 locator++### READ-003 read context++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --context 1 --limit 1000+```++预期:++- exit code = 0+- 不报 `context_not_applicable`,除非 locator 粒度确实不支持 context++### READ-004 invalid locator++命令:++```bash+mineru read "doc:not-a-real-doc/tier:flash/page:1"+```++预期:++- exit code != 0+- 输出包含 not found、invalid 或 locator 相关错误+- 不包含 traceback++### READ-005 输出到文件++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --output "$MINERU_E2E_FIXTURE_DIR/read-output.md"+```++预期:++- exit code = 0+- 输出包含 `Written to` 或等价成功信息+- 不在 stdout 大量打印完整文档内容+- 输出文件路径应为命令指定路径+- 不包含 traceback++### READ-006 JSON 与 output 组合++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --output "$MINERU_E2E_FIXTURE_DIR/read-output-json.md" --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 顶层保持 `read --json` 的 DocContentResponse 风格结构+- JSON 包含 sha256、short_id、tier、format、request_scope 或等价字段+- 当文件写出成功时,`content` 应为 null+- JSON 顶层包含 `output`+- `output.status` = `written`+- `output.path` 为实际写入路径,建议为绝对路径或规范化绝对路径+- 输出文件存在,路径为命令指定路径+- stdout 不允许包含 `Written to`、Rich 表格、Markdown 正文或其它人类提示文本+- 不包含 Python traceback++### READ-007 image 格式++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --json+```++预期分支:++- 如果该 locator 支持 image 输出:+ - exit code = 0+ - 输出为可直接解析的 JSON+ - JSON 包含 asset、mime_type、path 或等价字段+- 如果该 locator 不支持 image 输出:+ - exit code != 0+ - 输出包含 unsupported、not available、no image 或等价错误+- 不包含 Python traceback++### READ-008 image 输出到文件++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/read-page.png"+```++预期分支:++- 如果该 locator 支持 image 输出:+ - exit code = 0+ - 输出包含 `Written to` 或等价成功信息+ - 输出路径为命令指定路径+- 如果该 locator 不支持 image 输出:+ - exit code != 0+ - 输出包含 unsupported、not available、no image 或等价错误+- 不包含 Python traceback++### READ-008A image JSON 与 output 组合++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/read-page-json.png" --json+```++预期分支:++- 如果该 locator 支持 image 输出:+ - exit code = 0+ - stdout 为可直接解析的 JSON+ - JSON 顶层保持 `read --json` 的 DocContentResponse 风格结构+ - JSON 包含 `asset` 或等价图片元数据+ - `content` 应为 null+ - JSON 顶层包含 `output`+ - `output.status` = `written`+ - `output.path` 为命令指定输出路径的实际写入路径+ - 不应要求调用方依赖服务端临时 asset path+- 如果该 locator 不支持 image 输出:+ - exit code != 0+ - stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+- 不包含 Python traceback++### READ-009 limit 截断与 next_request++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --limit 20 --json+```++预期:++- exit code = 0+- 输出为可直接解析的 JSON+- 如果内容超过 limit,JSON 应体现 truncated、next_request、cursor、locator 或等价续读信息+- 如果内容未超过 limit,JSON 应明确表示未截断或没有 next_request++### READ-010 使用 next_request 续读++前置: READ-009 返回 next_request.locator。++命令模板:++```bash+mineru read "<next_request.locator>" --limit 30000 --json+```++预期:++- exit code = 0+- 输出为可直接解析的 JSON+- request_scope.locator 体现输入 locator 或规范化 locator+- 不返回与上一段完全相同的起始截断片段,除非服务端明确说明 cursor 已到末尾++### READ-011 no-marker++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --limit 20 --no-marker+```++预期:++- exit code = 0+- 输出不包含 `<!-- Next:`+- 不包含 Python traceback++### READ-012 非法 format++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format html+mineru read "doc:<short_id>/tier:flash/page:1" --format text+mineru read "doc:<short_id>/tier:flash/page:1" --format json+```++预期:++- 三条 exit code != 0+- 输出包含 invalid choice、not one of、unsupported format 或等价错误+- 不包含 Python traceback++### READ-013 JSON 输出纯净性++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --json+```++预期:++- exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 `Written to`+- stdout 不包含 Rich 表格、status/info 文本或 Markdown 内容前缀++## 10. Search 与 Find++### SEARCH-001 find by filename++命令:++```bash+mineru find "sample"+```++预期:++- exit code = 0+- 输出包含 `sample.pdf` 或明确 `No results found`+- 若前面 scan/parse 成功,优先期望找到 `sample.pdf`++### SEARCH-002 find JSON++命令:++```bash+mineru find "sample" --json+```++预期:++- exit code = 0+- 输出为 JSON+- 包含 results、total 或等价字段++### SEARCH-003 search 内容++命令:++```bash+mineru search "sample" --limit 10+```++预期:++- exit code = 0+- 输出为搜索结果或 `No results found`+- 不包含 traceback++### SEARCH-004 search tier filter++命令:++```bash+mineru search "sample" --tier flash --limit 10 --json+```++预期:++- exit code = 0+- 输出为 JSON+- 若有结果,结果 tier 应为 flash++### SEARCH-005 search min-tier++命令:++```bash+mineru search "sample" --min-tier flash --limit 10 --json+```++预期:++- exit code = 0+- 输出为 JSON++### SEARCH-006 find ext filter++命令:++```bash+mineru find "sample" --ext pdf --json+mineru find "sample" --ext docx --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- pdf 过滤下如果有结果,结果 ext 应为 pdf+- docx 过滤下如果有结果,结果 ext 应为 docx+- 不包含 Python traceback++### SEARCH-007 find limit 和 offset 边界++命令:++```bash+mineru find "sample" --limit 1 --json+mineru find "sample" --limit 1 --offset 1 --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- limit 生效,单次返回结果数量不超过 1+- offset 不导致崩溃++### SEARCH-008 search type filter++命令:++```bash+mineru search "sample" --type pdf --limit 10 --json+mineru search "sample" --type docx --limit 10 --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- 如果有结果,结果文件类型应符合对应 type filter+- 不包含 Python traceback++### SEARCH-009 search offset++命令:++```bash+mineru search "sample" --limit 1 --offset 0 --json+mineru search "sample" --limit 1 --offset 1 --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- limit 生效,单次返回结果数量不超过 1+- offset 不导致崩溃++### SEARCH-010 search 无结果++命令:++```bash+mineru search "mineru-e2e-query-that-should-not-exist" --limit 10+mineru search "mineru-e2e-query-that-should-not-exist" --limit 10 --json+```++预期:++- 两条 exit code = 0+- 普通输出包含 `No results found` 或等价空结果提示+- JSON 输出可直接解析+- JSON 中 total 为 0 或 results 为空++### SEARCH-011 find 无结果++命令:++```bash+mineru find "mineru-e2e-filename-that-should-not-exist"+mineru find "mineru-e2e-filename-that-should-not-exist" --json+```++预期:++- 两条 exit code = 0+- 普通输出包含 `No results found` 或等价空结果提示+- JSON 输出可直接解析+- JSON 中 total 为 0 或 results 为空++### SEARCH-012 JSON 输出纯净性++命令:++```bash+mineru find "sample" --json+mineru search "sample" --limit 10 --json+```++预期:++- 两条 exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 Rich 表格、`No results found` 文本或非 JSON 前缀++## 11. List 命令++### LIST-001 list files++命令:++```bash+mineru list files --limit 20+mineru list files --limit 20 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 若前面 scan/parse 成功,应能看到 `sample.pdf` 或相关 file record++### LIST-001A list files filters++命令:++```bash+mineru list files --status active --limit 20 --json+mineru list files --ext pdf --limit 20 --json+mineru list files --limit 1 --offset 1 --json+```++预期:++- 三条 exit code = 0+- 三条输出均为可直接解析的 JSON+- status filter 下如果有结果,结果 status 应为 active+- ext filter 下如果有结果,结果 ext 应为 pdf+- limit/offset 不导致崩溃,返回数量不超过 limit++### LIST-002 list docs++命令:++```bash+mineru list docs --limit 20+mineru list docs --limit 20 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 若前面 parse 成功,应能看到对应 doc++### LIST-002A list docs offset++命令:++```bash+mineru list docs --limit 1 --offset 0 --json+mineru list docs --limit 1 --offset 1 --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- limit 生效,单次返回结果数量不超过 1+- offset 不导致崩溃++### LIST-003 list parses++命令:++```bash+mineru list parses --tier flash --limit 20+mineru list parses --tier flash --limit 20 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 若前面 parse 成功,应有 flash parse 记录++### LIST-003A list parses filters++命令:++```bash+mineru list parses --status done --limit 20 --json+mineru list parses --tier flash --status done --limit 20 --json+mineru list parses --limit 1 --offset 1 --json+```++预期:++- 三条 exit code = 0+- 三条输出均为可直接解析的 JSON+- status filter 下如果有结果,结果 status 应为 done+- tier/status 组合 filter 下如果有结果,结果 tier 应为 flash 且 status 为 done+- limit/offset 不导致崩溃,返回数量不超过 limit++### LIST-004 list scans++命令:++```bash+mineru list scans --limit 20+mineru list scans --limit 20 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 若前面 scan/watch rescan 成功,应有 scan 记录++### LIST-004A list scans filters++命令:++```bash+mineru list scans --status done --limit 20 --json+mineru list scans --kind manual --limit 20 --json+mineru list scans --limit 1 --offset 1 --json+```++预期:++- 三条 exit code = 0+- 三条输出均为可直接解析的 JSON+- status filter 下如果有结果,结果 status 应为 done+- kind filter 下如果有结果,结果 kind 应为 manual+- limit/offset 不导致崩溃,返回数量不超过 limit++### LIST-005 watch-id filters++前置: WATCH-003 可获得 watch id。++命令模板:++```bash+mineru list files --watch-id <watch_id> --limit 20 --json+mineru list scans --watch-id <watch_id> --limit 20 --json+```++预期:++- 两条 exit code = 0+- 两条输出均为可直接解析的 JSON+- 如果有结果,结果应关联该 watch id 或该 watch path++### LIST-006 JSON 输出纯净性++命令:++```bash+mineru list files --limit 1 --json+mineru list docs --limit 1 --json+mineru list parses --limit 1 --json+mineru list scans --limit 1 --json+```++预期:++- 四条 exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 Rich 表格、`No ... found` 文本或非 JSON 前缀++## 12. Show 命令++### SHOW-001 show file++命令:++```bash+mineru show file "$MINERU_E2E_FIXTURE_DIR/sample.pdf"+mineru show file "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 输出包含 filename、size_bytes、page_count 或 parse tiers 中的部分字段++### SHOW-001A show file by sha256++前置: 从 `mineru show file "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --json` 或 `mineru list files --json` 中获得 sha256。++命令模板:++```bash+mineru show file <sha256>+mineru show file <sha256> --json+```++预期分支:++- 如果 CLI 设计支持 sha256 查询 file:+ - 两条 exit code = 0+ - JSON 输出可解析+ - 输出包含 sha256 或对应 filename/path+- 如果 CLI 设计只支持 path:+ - 两条 exit code != 0+ - 输出包含 path、not found、invalid 或等价错误+ - 不包含 Python traceback++### SHOW-002 show doc++从 `mineru list docs --json` 中取一个 sha256。++命令模板:++```bash+mineru show doc <sha256>+mineru show doc <sha256> --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 输出包含 sha256+- show doc 展示关联 files 或 doc metadata++### SHOW-003 show parse++从 `mineru list parses --json` 中取一个 parse id。++命令模板:++```bash+mineru show parse <parse_id>+mineru show parse <parse_id> --json+```++预期:++- 两条 exit code = 0+- 输出包含 parse status、tier、page_range++### SHOW-004 show scan++从 `mineru list scans --json` 中取一个 scan id。++命令模板:++```bash+mineru show scan <scan_id>+mineru show scan <scan_id> --json+```++预期:++- 两条 exit code = 0+- 输出包含 scan status 和统计字段++### SHOW-005 show 不存在资源++命令:++```bash+mineru show parse 999999999+mineru show scan 999999999+mineru show doc 0000000000000000000000000000000000000000000000000000000000000000+mineru show file "$MINERU_E2E_FIXTURE_DIR/not-exist.pdf"+```++预期:++- 四条 exit code != 0+- 输出包含 not found、invalid 或等价错误+- 不包含 Python traceback++### SHOW-006 JSON 输出纯净性++命令模板:++```bash+mineru show file "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --json+mineru show doc <sha256> --json+mineru show parse <parse_id> --json+mineru show scan <scan_id> --json+```++预期:++- 四条 exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 Rich 表格或非 JSON 前缀++## 13. Invalidate++### INVALIDATE-001 invalidate flash++命令:++```bash+mineru invalidate "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash+```++预期:++- exit code = 0+- 输出包含 `Invalidated` 或 `No done batches found`+- 不删除源文件++### INVALIDATE-001A invalidate all tiers++命令:++```bash+mineru invalidate "$MINERU_E2E_FIXTURE_DIR/sample.pdf"+```++预期:++- exit code = 0+- 输出包含 `Invalidated`、`No done batches found` 或等价结果+- 不删除源文件+- 后续可重新 parse++### INVALIDATE-001B invalidate JSON 支持性++命令:++```bash+mineru invalidate "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --json+```++预期:++- 命令必须有明确行为:+ - 如果支持 JSON,exit code = 0,stdout 为可直接解析的 JSON+ - 如果不支持 JSON,exit code != 0,输出包含 no such option、unknown option 或等价错误+- 不包含 Python traceback++### INVALIDATE-001C invalidate 不存在文件++命令:++```bash+mineru invalidate "$MINERU_E2E_FIXTURE_DIR/not-exist.pdf" --tier flash+```++预期:++- exit code != 0+- 输出包含 file not found、not found 或等价错误+- 不包含 Python traceback++### INVALIDATE-002 invalidate 后重新 parse++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- exit code = 0+- 输出为 JSON+- tier = flash+- 不因 invalidate 后旧状态损坏而失败++## 14. Forget++### FORGET-001 默认 dry-run++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf"+```++预期:++- exit code = 0+- 输出包含 `Would forget`+- 不删除源文件+- 后续 `mineru show file "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf"` 不因 dry-run 改变状态++### FORGET-002 实际 forget++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf" --no-dry-run+```++预期:++- exit code = 0+- 输出包含 `Forgot`+- 不删除源文件+- 如果后续重新 scan/parse,该路径可被重新发现++### FORGET-003 forget JSON++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf" --json+```++预期:++- exit code = 0+- 输出为 JSON+- 包含 forgotten_files、matched_as、warnings 或等价字段++### FORGET-004 forget 目录 dry-run++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/watch-dir"+```++预期:++- exit code = 0+- 输出包含 `Would forget`+- 不删除源目录或目录内文件+- 后续 `mineru watch list` 或 `mineru scan` 不因 dry-run 破坏状态++### FORGET-005 forget 目录 execute++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/watch-dir" --no-dry-run+```++预期:++- exit code = 0+- 输出包含 `Forgot`+- 不删除源目录或目录内文件+- 后续重新 scan/watch rescan 可重新发现该目录下文件++### FORGET-006 forget 不存在路径++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/not-exist.pdf"+mineru forget "$MINERU_E2E_FIXTURE_DIR/not-exist.pdf" --json+```++预期:++- 两条命令必须有明确行为+- 普通命令如果 exit code = 0,输出必须明确 forgotten_files 为 0 或有 warning+- 普通命令如果 exit code != 0,输出必须包含 not found 或等价错误+- JSON 命令如果 exit code = 0,stdout 必须为可直接解析的 JSON,且明确 forgotten_files 为 0 或有 warning+- JSON 命令如果 exit code != 0,stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`+- 不包含 Python traceback++### FORGET-007 JSON 输出纯净性++命令:++```bash+mineru forget "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf" --json+```++预期:++- exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 `Would forget`、`Forgot` 或非 JSON 前缀++## 15. Cleanup++### CLEANUP-001 cleanup deleted-files dry-run++命令:++```bash+mineru cleanup deleted-files+mineru cleanup deleted-files --json+```++预期:++- 两条 exit code = 0+- 默认 dry-run+- JSON 输出可解析++### CLEANUP-002 cleanup deleted-files execute++命令:++```bash+mineru cleanup deleted-files --no-dry-run+```++预期:++- exit code = 0+- 输出包含 `Removed`++### CLEANUP-003 cleanup orphan-docs dry-run++命令:++```bash+mineru cleanup orphan-docs+mineru cleanup orphan-docs --json+```++预期:++- 两条 exit code = 0+- 默认 dry-run+- JSON 输出可解析++### CLEANUP-004 cleanup temp++命令:++```bash+mineru cleanup temp --older-than 7+mineru cleanup temp --older-than 7 --json+```++预期:++- 两条 exit code = 0+- JSON 输出可解析+- 输出包含 removed temp file count 或等价字段++### CLEANUP-005 cleanup deleted-files execute JSON++命令:++```bash+mineru cleanup deleted-files --no-dry-run --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- JSON 包含 removed/deleted/dry_run 或等价字段+- 不包含 Python traceback++### CLEANUP-006 cleanup orphan-docs execute++命令:++```bash+mineru cleanup orphan-docs --no-dry-run+mineru cleanup orphan-docs --no-dry-run --json+```++预期:++- 普通命令 exit code = 0+- 普通输出包含 `Removed`+- JSON 命令 exit code = 0+- JSON 命令 stdout 为可直接解析的 JSON+- JSON 包含 removed/orphan/dry_run 或等价字段+- 不包含 Python traceback++### CLEANUP-007 cleanup temp 边界参数++命令:++```bash+mineru cleanup temp --older-than 0 --json+mineru cleanup temp --older-than -1+```++预期:++- `--older-than 0 --json` exit code = 0,输出为可直接解析的 JSON+- `--older-than -1` exit code != 0+- `--older-than -1` 输出包含 invalid、must be non-negative 或等价错误+- 不包含 Python traceback++### CLEANUP-008 JSON 输出纯净性++命令:++```bash+mineru cleanup deleted-files --json+mineru cleanup orphan-docs --json+mineru cleanup temp --older-than 7 --json+```++预期:++- 三条 exit code = 0+- stdout 可被 JSON parser 直接解析+- stdout 第一段非空内容必须是 `{` 或 `[`+- stdout 不包含 `Would remove`、`Removed` 或非 JSON 前缀++## 16. 扩展与边界场景++本章节补充跨命令契约、路径边界、并发、文件类型和更深层行为验证。除明确说明外,执行 Agent 仍只调用 `mineru` 命令。++### JSONERR-001 read JSON 错误输出纯净性++命令:++```bash+mineru read "doc:not-a-real-doc/tier:flash/page:1" --json+```++预期:++- exit code != 0+- stdout 必须为可直接解析的 JSON error+- JSON 包含 `error.type`、`error.code`、`error.message`+- stdout 不得混合 `Error:`、Rich 文本、traceback 或半截 JSON+- stderr 不得混入额外的人类解释文本++### JSONERR-002 watch JSON 错误输出纯净性++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/not-exist-dir" --label e2e-missing-watch --json+mineru watch remove "$MINERU_E2E_FIXTURE_DIR/not-a-watch-dir" --json+mineru watch rescan "$MINERU_E2E_FIXTURE_DIR/not-a-watch-dir" --json+```++预期:++- 三条 exit code != 0+- 三条 stdout 均必须为可直接解析的 JSON error+- JSON 包含 `error.type`、`error.code`、`error.message`+- stdout 不得混合 `Error:`、Rich 文本、traceback 或半截 JSON+- stderr 不得混入额外的人类解释文本++### JSONERR-003 show/config/cleanup JSON 错误输出纯净性++命令:++```bash+mineru show parse 999999999 --json+mineru config get not.a.real.key --json+mineru cleanup temp --older-than -1 --json+```++预期:++- 三条 exit code != 0+- 三条 stdout 均必须为可直接解析的 JSON error+- JSON 包含 `error.type`、`error.code`、`error.message`+- stdout 不得混合 `Error:`、Rich 文本、traceback 或半截 JSON+- stderr 不得混入额外的人类解释文本++说明:++- 本用例只覆盖进入命令实现后的业务错误。+- Typer/Click 参数解析阶段错误不在 JSON 错误统一契约范围内。++### JSONERR-004 server 不可连接时 JSON 错误输出纯净性++命令:++```bash+mineru server stop+mineru scan "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --json+mineru list files --limit 1 --json+mineru search "sample" --limit 1 --json+mineru find "sample" --limit 1 --json+mineru server start+```++预期:++- stop exit code = 0+- scan/list/search/find 四条命令 exit code != 0+- scan/list/search/find 四条 stdout 均必须为可直接解析的 JSON error+- JSON 包含 `error.type`、`error.code`、`error.message`+- stdout 不得混合 `Error:`、Rich 文本、traceback 或半截 JSON+- `mineru server status --json` 的未运行状态不适用本错误契约,见 JSONERR-005+- start exit code = 0,用于恢复后续测试环境++### JSONERR-005 server status JSON 未运行状态++命令:++```bash+mineru server stop+mineru server status --json+mineru server start+```++预期:++- stop exit code = 0+- status exit code = 0+- status stdout 为可直接解析的 JSON+- status JSON 至少包含 `running: false`+- status stdout 不包含 `Server is not running.` 或 JSON error+- start exit code = 0,用于恢复后续测试环境++### WATCH-008 watch add JSON++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/watch-dir" --label e2e-watch-json --json+mineru watch list --json+mineru watch remove "$MINERU_E2E_FIXTURE_DIR/watch-dir" --json+```++预期:++- 三条 exit code = 0+- 三条 stdout 均为可直接解析的 JSON+- add JSON 包含 id、path、label、status 或等价字段+- list JSON 能看到该 watch+- remove JSON 包含 watch_id/removed 或等价字段++### WATCH-009 removable watch++命令:++```bash+mineru watch add "$MINERU_E2E_FIXTURE_DIR/watch-dir" --label e2e-removable --removable --json+mineru watch list --json+mineru watch remove "$MINERU_E2E_FIXTURE_DIR/watch-dir"+```++预期:++- 三条 exit code = 0+- add/list JSON 可直接解析+- watch 记录中 removable 应为 true+- 普通 list 输出中应能体现 removable 或 JSON 中明确体现 removable++### WATCH-010 removable watch unreachable 行为++前置: 需要一个可移除或可临时变为不可访问的 watch fixture;如果当前平台无法稳定制造,标记为 BLOCKED。++命令模板:++```bash+mineru watch add <removable_watch_path> --removable --json+mineru watch rescan <watch_id> --wait 30 --json+mineru watch list --json+```++预期:++- 如果路径可访问,rescan exit code = 0,watch status 为 active+- 如果路径变为不可访问,命令应返回明确 unreachable 状态、scan error 或 watch status=unreachable+- 不包含 Python traceback++### LIST-007 list docs file-type filter++命令:++```bash+mineru list docs --file-type pdf --limit 20 --json+mineru list docs --file-type docx --limit 20 --json+```++预期:++- 两条 exit code = 0+- 两条 stdout 均为可直接解析的 JSON+- 如果有结果,结果 file_type 应符合过滤条件+- 不包含 Python traceback++### SEARCH-013 find offset 契约++命令:++```bash+mineru find "sample" --limit 1 --offset 1 --json+```++预期:++- 如果 CLI 设计支持 find offset,exit code = 0,stdout 为可直接解析的 JSON,返回数量不超过 1+- 如果 CLI 设计不支持 find offset,exit code != 0,输出包含 no such option、unknown option 或等价错误+- 不包含 Python traceback++### PARSE-016 page range 边界++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages all --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 2~1 --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 999~1000 --wait 60 --json+```++预期:++- `--pages all` exit code = 0,stdout 为可直接解析的 JSON+- 反向 page range exit code != 0 或返回明确 page_range_invalid/error JSON+- 超出页码 exit code != 0 或返回明确 page_range_invalid/not found/empty range 错误+- 不包含 Python traceback++### READ-014 locator 粒度边界++前置: 从成功 parse/read JSON 中获得 block/char locator 或 next_request locator。++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1/block:1" --json+mineru read "doc:<short_id>/tier:flash/page:1/block:1/char:1" --json+mineru read "doc:<short_id>/tier:flash/page:999" --json+mineru read "doc:<short_id>/tier:flash/page:1/block:999" --json+```++预期:++- 合法 block/char locator exit code = 0,stdout 为可直接解析的 JSON+- 超出 page/block locator exit code != 0,stdout 必须为可直接解析的 JSON error+- request_scope.locator 体现输入 locator 或规范化 locator+- 不包含 Python traceback++### READ-015 跨页 context++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --context 2 --limit 30000 --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- request_scope.context = 2 或等价字段体现 context 生效+- 如果文档页数不足,命令应优雅返回可用范围,不报 traceback++### FILETYPE-001 Office 和图片输入++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.docx" --tier flash --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pptx" --tier flash --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.xlsx" --tier flash --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.png" --tier flash --wait 60 --json+```++预期分支:++- 如果当前安装支持该文件类型,exit code = 0,stdout 为可直接解析的 JSON,content 或 doc metadata 合理存在+- 如果当前安装不支持该文件类型,exit code != 0,输出包含 unsupported、file_type_unsupported、no_engine 或等价错误+- 不包含 Python traceback++### FILETYPE-002 损坏、空、不可读文件++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/corrupted.pdf" --tier flash --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/empty.pdf" --tier flash --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/no-read.pdf" --tier flash --wait 60 --json+```++预期:++- 三条 exit code != 0,除非当前实现对空文件有明确可接受语义+- 输出包含 file_corrupted、parse_empty、file_permission_denied、file_not_found、unsupported 或等价错误+- 失败命令带 `--json` 时,stdout 必须为可直接解析的 JSON error+- 如果 `no-read.pdf` 权限场景无法稳定制造,可标记该子项 BLOCKED+- 不包含 Python traceback++### PATH-001 路径字符边界++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample doc.pdf" --tier flash --pages 1~1 --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/中文样例.pdf" --tier flash --pages 1~1 --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/symlink-sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- 文件名含空格和中文的两条命令 exit code = 0,stdout 为可直接解析的 JSON+- symlink 命令如果平台支持 symlink,exit code = 0;如果不支持或 fixture 不存在,标记 BLOCKED+- JSON 中 source/path/request_scope 不应乱码+- 不包含 Python traceback++### PATH-002 相对路径和 home 路径++命令:++```bash+mineru parse "sample.pdf" --tier flash --pages 1~1 --wait 60 --json+mineru show file "sample.pdf" --json+mineru parse "~/mineru-e2e-test/sample.pdf" --tier flash --pages 1~1 --wait 60 --json+```++预期:++- 在测试 HOME 下执行时,三条 exit code = 0+- stdout 均为可直接解析的 JSON+- show/parse 应解析到同一个实际文件或等价 canonical path+- CLI 必须主动对输入 path 中的 `~` 执行 `expanduser`+- 不能把带引号的 `"~/mineru-e2e-test/sample.pdf"` 当作当前目录下的字面量相对路径+- 不包含 Python traceback++### OUTPUT-001 output 边界++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output -+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output "$MINERU_E2E_FIXTURE_DIR/output-dir/existing.md"+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output "$MINERU_E2E_FIXTURE_DIR/not-exist-dir/out.md"+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output "~/mineru-e2e-test/output-dir/home-output.md"+```++预期:++- `--output -` 应等价于 stdout 输出,exit code = 0,不创建名为 `-` 的文件+- 输出到已有文件应有明确覆盖或拒绝策略;若覆盖,exit code = 0 且输出包含 `Written to`+- 输出到不存在父目录应自动创建父目录并成功,exit code = 0+- 不存在父目录下的目标文件必须存在,且不为空+- 输出路径中的 `~` 必须由 CLI 主动 `expanduser`,不能创建字面量 `~` 目录+- 不包含 Python traceback++### OUTPUT-001A output 与 JSON 边界++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --wait 60 --output - --json+mineru read "doc:<short_id>/tier:flash/page:1" --output - --json+```++预期:++- 两条 exit code = 0+- stdout 均为可直接解析的 JSON+- `--output - --json` 等价于不指定 `--output`+- JSON 中不新增 `output` 字段+- 不创建名为 `-` 的文件+- stdout 不包含 `Written to`、Rich 表格、Markdown 正文或其它人类提示文本++### OUTPUT-002 read image output 后缀边界++命令模板:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page-as-md.md"+```++预期:++- 如果 image 输出支持任意后缀,exit code = 0,输出文件内容应为图片资产字节+- 如果要求后缀匹配,exit code != 0,输出包含 invalid extension、mime、image 或等价错误+- 不包含 Python traceback++### CONCURRENCY-001 并发 parse force++执行方式:++- 启动两个独立 shell,同时执行同一条命令。+- 执行 Agent 仍只调用 `mineru` 命令,不直接访问数据库。++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60 --json+mineru parse "$MINERU_E2E_FIXTURE_DIR/sample.pdf" --tier flash --pages 1~1 --force --wait 60 --json+```++预期:++- 两个进程均不出现 Python traceback+- 至少一个命令成功;另一个可成功、等待已有任务、或返回明确 lock/queue/busy 错误+- 不允许数据库损坏、后续普通 parse 失败或永久 pending++### CONCURRENCY-002 并发 scan 同一目录++执行方式:++- 启动两个独立 shell,同时执行同一条命令。++命令:++```bash+mineru scan "$MINERU_E2E_FIXTURE_DIR" --wait 30 --json+mineru scan "$MINERU_E2E_FIXTURE_DIR" --wait 30 --json+```++预期:++- 两个进程均不出现 Python traceback+- 两条命令 exit code = 0 或其中一条返回明确 busy/lock/queue 错误+- 后续 `mineru list scans --json` 可正常返回++### CONCURRENCY-003 并发 server start++执行方式:++- 确保 server 已停止。+- 启动两个独立 shell,同时执行 `mineru server start`。++命令:++```bash+mineru server start+mineru server start+```++预期:++- 至少一个命令 exit code = 0+- 另一个命令 exit code = 0 且输出 already running,或 exit code != 0 且输出可读的 socket/busy/started by another process 错误+- 最终 `mineru server status --json` 表示只有一个可用 server+- 不包含 Python traceback++### CONFIG-010 配置持久化++命令:++```bash+mineru config set parse_server.local.mode disabled+mineru server restart+mineru config get parse_server.local.mode --json+mineru config unset parse_server.local.mode+```++预期:++- 四条 exit code = 0+- restart 后 get JSON 仍体现 disabled 或等价 override+- unset 后恢复默认配置来源+- 不包含 Python traceback++### CONFIG-011 rule hit_count 与 scan 影响++命令:++```bash+mineru config exclude-rules add "*/unsupported.bin" --priority 100 --json+mineru scan "$MINERU_E2E_FIXTURE_DIR" --wait 30 --json+mineru config exclude-rules list --json+mineru config exclude-rules remove <rule_id>+```++预期:++- 四条 exit code = 0+- scan JSON 中 excluded 或 unsupported 计数符合 exclude 语义+- list JSON 中该 rule 的 hit_count 应增加,或当前实现明确不统计 scan hit_count+- remove 后规则不再出现在 list 中++### CLEANUP-009 cleanup deleted-files 真实效果++前置: 通过 `mineru forget "$MINERU_E2E_FIXTURE_DIR/sample-copy.pdf" --no-dry-run` 或其它 CLI 操作制造可清理记录。++命令:++```bash+mineru cleanup deleted-files --no-dry-run --json+mineru list files --json+```++预期:++- 两条 exit code = 0+- cleanup JSON 可直接解析+- list files 中不再包含已清理的 deleted 记录,或 cleanup JSON 明确 deleted_files=0+- 不包含 Python traceback++### CLEANUP-010 cleanup orphan-docs 真实效果++前置: 通过 forget 所有关联文件制造 orphan doc;如果无法只通过 CLI 稳定制造,标记 BLOCKED。++命令:++```bash+mineru cleanup orphan-docs --no-dry-run --json+mineru list docs --json+```++预期:++- 两条 exit code = 0+- cleanup JSON 可直接解析+- orphan doc 不再出现在 list docs 中,或 cleanup JSON 明确 orphan_docs=0+- parsed 输出目录不应再被 read/parse 错误引用+- 不包含 Python traceback++### CLEANUP-011 cleanup temp 新旧文件边界++前置: 测试环境预置 doclib temp 目录中的过期文件和未过期文件;如果无法只通过 CLI 稳定制造,标记 BLOCKED。++命令:++```bash+mineru cleanup temp --older-than 7 --json+```++预期:++- exit code = 0+- stdout 为可直接解析的 JSON+- 过期 temp 文件被清理+- 未过期 temp 文件不被清理+- 不包含 Python traceback++### SERVER-012 error summary 与 recent logs++命令:++```bash+mineru parse "$MINERU_E2E_FIXTURE_DIR/corrupted.pdf" --tier flash --wait 20 --json+mineru server status --json+```++预期:++- 第一条按 FILETYPE-002 损坏 PDF 分支判定+- 第二条 exit code = 0,stdout 为可直接解析的 JSON+- status JSON 中 recent_logs 应来自 `MINERU_DOCLIB_LOG_PATH` 或等价日志来源+- 如果错误被记录,error_summary 中应出现 parse/file 错误计数+- 如果当前实现不记录该错误,记录为 fail/issue,不作为 BLOCKED++## 17. 停止 server++### SERVER-010 停止 server++命令:++```bash+mineru server stop+mineru server status+```++预期:++- stop exit code = 0+- status exit code = 0+- status 输出 `Server is not running` 或等价信息++### SERVER-011 启动失败时保留子进程 stderr++执行顺序:++- 本用例必须作为整套 E2E 的最后一个测试执行。+- 本用例会故意制造 server 启动失败,执行后无需恢复测试 server。++执行方式:++- 人工制造一个不会成功建立 UDS 的 server 启动环境,例如把 `MINERU_DOCLIB_UDS_PATH` 指向一个父目录不存在且不可创建的位置。+- 只允许通过环境变量制造失败,不直接修改数据库或内部状态。++命令:++```bash+mineru server start+```++预期:++- exit code != 0+- 输出包含 `See log:` 或等价日志路径提示+- 日志路径应为 `MINERU_DOCLIB_LOG_PATH` 指向的文件或测试 HOME 下的 mineru log+- 日志文件中能看到 server 子进程 stderr 或异常信息+- stdout/stderr 不只给出空泛的启动失败++## 18. 最终报告格式++执行 Agent 最终必须按以下格式汇总:++```text+Summary:+- total: N+- passed: N+- failed: N+- blocked: N++Failures:+1. [case id] command+ expected:+ actual exit code:+ actual stdout:+ actual stderr:+ analysis:++Blocked:+1. [case id] reason++Environment:+- mineru version: <如果 help/status 输出能看到则填写,否则 unknown>+- fixture dir: ...+- quality tier available: standard/pro available | flash only | unknown+```diff --git a/docs/next/cli/mineru-library.md b/docs/next/cli/mineru-library.mdindex 5fb3be66..8cb0ad32 100644--- a/docs/next/cli/mineru-library.md+++ b/docs/next/cli/mineru-library.md@@ -243,6 +243,6 @@ mineru config parsing-rules add "*/合同/*" --tier pro --remoteparsing-rules 允许不指定 tier。执行时必须解析成实际实体 tier,并记录实际 tier;默认选择不能解析为 `flash`。-## 未决问题+## 已收敛规则-watch 升级提示集中维护在 [开放问题清单](../open-questions.md)。+P0 不做基于启发式的 watch 自动提示或自动排队升级。watch 默认使用 `flash`;后台自动升级只由用户显式配置的 parsing-rules 触发。diff --git a/docs/next/cli/mineru-parse.md b/docs/next/cli/mineru-parse.mdindex edd59f1b..a3812c6b 100644--- a/docs/next/cli/mineru-parse.md+++ b/docs/next/cli/mineru-parse.md@@ -10,6 +10,15 @@`mineru parse` 是 `mineru` 的主动文档解析入口。它面向“用户或 Agent 决定读取某个文档”的场景,因此默认应追求可阅读质量,而不是只做低成本索引。+与 [mineru read](mineru-read.md) 的边界:++```text+parse(path) = ensure document is parsed, then read default content+read(locator) = read existing parsed content by stable locator+```++`parse` 负责从文件 path 出发,把文档纳入 doclib 并返回第一段可读内容。后续继续阅读、按页读取、按 block 读取或导出 page/block 图像,应转到 `mineru read`。+设计原则:- 隐私优先:不显式 `--remote` 就不上传文档。@@ -40,7 +49,6 @@ mineru parse <file> [flags]|------|------|------|------|| `--tier` | `flash` / `standard` / `pro` | 不传 | 解析 tier;省略时使用默认选择策略;语义见 [解析 Tier](../tiers.md) || `-p, --pages` | range | `1~10` | 分页文档的页码范围;`all` 表示全部页 |-| `--offset` | integer | `0` | 非分页长文档的继续读取 offset || `--language` | string | 自动 | 文档语言提示,逐步弱化为高级选项 || `--force` | bool | false | 跳过 done 缓存;复用 active parse 或为未覆盖页创建新 parse;不删除或作废旧缓存 |@@ -49,7 +57,8 @@ mineru parse <file> [flags]| Flag | 类型 | 默认 | 说明 ||------|------|------|------|| `-o, --output` | path | `-` | 输出路径;`-` 或省略表示 STDOUT |-| `-f, --format` | markdown / text / middle-json / content-list / structured-content / html | markdown | 输出格式 |+| `-f, --format` | markdown | markdown | 输出格式。当前仅支持 `markdown`。 |+| `--json` | bool | false | 输出命令级 JSON;顶层固定为 `{ "parse": ..., "content": ... }` || `--no-marker` | bool | false | 不输出结构 marker |### 同步控制@@ -85,26 +94,43 @@ mineru parse <file> [flags]分页文档默认读取范围固定为 `1~10`。这个默认值用于让 Agent 以线性、可预测的方式渐进阅读文档,避免默认读取尾页后在后续续读中重复返回相同页面。用户可以通过 `--pages all` 读取全文,或通过显式页码范围读取任意页段。-PDF 使用物理页码:+分页文档使用物理页码:```text<!-- next pages available. Use: mineru parse report.pdf --pages 11~20 -->```-非分页文档可以使用虚拟页或字符 offset:+非分页文档当前也使用 `--after` cursor 继续读取:```text-<!-- truncated at paragraph boundary (char ~30000 of ~150000). Next: mineru parse long.docx --offset 30000 -->+<!-- next content available. Use: mineru parse long.docx --after doc:ab12cd3/tier:standard/page:1/block:12/char:520 -->```marker 是 Agent 的控制协议,不应依赖自然语言猜测。-非分页长文档正式支持 `--offset`。`--offset` 表示从指定字符或逻辑片段位置继续读取;具体 offset 单位和 marker 语法后续在 Agent marker 设计中定稿,但 CLI 参数本身进入正式设计。+当用户后续已经拥有 locator 时,推荐直接使用 `mineru read <locator>`,而不是继续依赖 path + `--pages` / `--after`。++非分页长文档当前正式使用 `--after` cursor 继续读取。`after` 的值来自服务端返回的结构化 `next_request.after`,CLI marker 只负责把这个值渲染为下一条命令。## 7. STDOUT 与文件输出默认输出到 STDOUT,便于 Agent 直接消费。指定 `--output` 时写入文件。+`--json` 时,`mineru parse` 的顶层返回固定为命令级 envelope:++```json+{+ "parse": { "... parse summary ..." },+ "content": { "... DocContentResponse ..." } | null+}+```++规则如下:++- 当解析结果已可读取时,`content` 为 `DocContentResponse`。+- 当使用 `--no-wait` 或等待超时、解析尚未完成时,`content` 为 `null`。+- 错误仍返回 [错误码体系](../errors.md) 定义的结构化错误 JSON。+结构化或可机器消费格式应尽量保持稳定:| 格式 | 用途 |diff --git a/docs/next/cli/mineru-read.md b/docs/next/cli/mineru-read.mdnew file mode 100644index 00000000..b2e3d6d5--- /dev/null+++ b/docs/next/cli/mineru-read.md@@ -0,0 +1,147 @@+# mineru read++状态: Draft+读者: Agent skill 作者、CLI 使用者、核心开发者+范围: `mineru read` 的定位、locator 输入、markdown/image 输出、context 和 continuation+非目标: 从文件 path 触发解析;批量目录扫描;解析 backend 专家参数+底稿: `../../../NEXT-CLI.md`,相关 ADR: [0014-mineru-read-command](../decisions/0014-mineru-read-command.md)++## 1. 定位++`mineru read` 是 `mineru` 的 locator-first 读取命令。它面向“文档已经进入 doclib,后续要继续读其中某个 doc、tier、page、block”的场景。++职责边界:++```text+parse(path) = ensure document is parsed, then read default content+read(locator) = read existing parsed content by stable locator+```++`read` 不负责 discover、scan、ingest,也不默认创建 parse task。它读取的是 doclib 中已有的解析结果。++## 2. Usage++```bash+mineru read <locator> [flags]+```++当前 P0 支持:++```bash+mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]+```++## 3. Locator 输入++`read` 支持以下粒度的 locator:++```text+doc:{short_id}+doc:{short_id}/tier:{tier}+doc:{short_id}/tier:{tier}/page:{page_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}+```++规则:++- `short_id` 是 doclib 为文档生成的稳定短 ID。+- `tier` 取值为 `flash`、`standard`、`pro`。+- `page_no` 和 `block_no` 使用 1-based 编号。+- `char:{offset}` 使用 block 渲染文本内的 0-based 字符 offset。++当只给出 `doc:{short_id}` 时,系统会选择当前已缓存的最高可用非 `flash` tier;如果不存在 `standard` 或 `pro` 结果,则返回错误,不静默降级到 `flash`。++## 4. 核心参数++| Flag | 类型 | 默认 | 说明 |+|------|------|------|------|+| `--format`, `-f` | `markdown` / `image` | `markdown` | 输出 content format |+| `--json` | bool | false | 将整个 CLI 响应包装为 JSON |+| `--limit` | int | `30000` | 文本输出软字符上限 |+| `--context` | int | `0` | 按 locator 周围扩展上下文 |+| `--output`, `-o` | path | 不传 | 将返回内容或 image asset 写入本地路径 |+| `--no-marker` | bool | false | 关闭 continuation marker |++语义区分:++- `--format` 控制 content 本身的格式。+- `--json` 控制 CLI 最外层输出是否为 JSON envelope。++## 5. Markdown 读取++`--format markdown` 是默认模式。++| Locator | 默认读取范围 |+|---------|--------------|+| `doc:{short_id}` | 默认 tier 的默认阅读范围 |+| `doc:{short_id}/tier:{tier}` | 该 tier 的默认阅读范围 |+| `.../page:{page_no}` | 该页 |+| `.../block:{block_no}` | 该 block |+| `.../char:{offset}` | 从该 block 的 offset 起读取 |++`--limit` 是软截断,尽量在页、block、段落、句子、换行或空白边界停止。++### `--context`++`--context N` 的含义随 locator 粒度变化:++| Locator | `--context` 行为 |+|---------|------------------|+| page locator | 读取前后各 N 页 |+| block locator | 读取前后各 N 个 block |+| char locator | 按 block locator 处理上下文,char 只影响起点 |+| doc locator | 返回 `context_not_applicable` |+| doc/tier locator | 返回 `context_not_applicable` |++## 6. Image 读取++`--format image` 是 P0 能力,但范围受文档类型和 locator 粒度限制。++不支持多页 image。++| 文档类型 | doc locator | doc/tier locator | page locator | block locator |+|----------|:-----------:|:----------------:|:------------:|:-------------:|+| PDF | 不支持 | 不支持 | 支持 | 有 bbox 且 bbox 非 empty 时支持 |+| Office | 不支持 | 不支持 | 不支持 | 仅 image block 支持 |+| 其它 | 不支持 | 不支持 | 不支持 | 暂不支持 |++实现语义:++- PDF page image:从原 PDF page 渲染。+- PDF block image:从原 PDF page 渲染后按 bbox 裁剪。+- Office image block:从 Middle JSON 中的 image 数据生成临时 asset。+- `read --output` 是 CLI 本地写文件行为,不是 doclib HTTP API 写文件行为。++如果不带 `--output`,image 模式默认输出 server 返回的临时 asset path。++## 7. JSON 输出++`--json` 时,CLI 输出 `DocContentResponse`。++locator-first 读取时:++- `request_scope.locator` 为规范化 locator。+- `request_scope.context` 为实际生效的 context。+- `next_request` 只写 `locator`。++## 8. Continuation++`read` 的 continuation 使用 locator 模型。++普通 markdown 输出中,如果还有下一段可读内容,CLI 会输出:++```text+<!-- Next: mineru read doc:ab12cd3/tier:standard/page:5 -->+```++`--json` 时,通过 `next_request.locator` 表示下一次建议读取的位置。++## 9. 与 mineru parse 的关系++建议工作流:++1. 第一次从 path 出发,使用 `mineru parse <file>`。+2. 需要继续阅读时,切换到 `mineru read <locator>`。++`parse` 适合“把文件纳入 MinerU 并读默认内容”。`read` 适合“基于已有定位继续读指定位置或导出 page/block 图像”。diff --git a/docs/next/cli/mineru.md b/docs/next/cli/mineru.mdindex 2d3fd739..7b91c98f 100644--- a/docs/next/cli/mineru.md+++ b/docs/next/cli/mineru.md@@ -22,6 +22,7 @@| 子命令 | 作用 | 文档 ||--------|------|------|| `mineru parse` | 主动解析单个文档 | [mineru parse](mineru-parse.md) |+| `mineru read` | 按 locator 继续读取已有解析结果 | [mineru read](mineru-read.md) || `mineru server` | 管理本地 doclib 服务 | [mineru server](mineru-server.md) || `mineru search` | 搜索本地文档库内容 | [mineru library](mineru-library.md) || `mineru find` | 搜索或定位文件 | [mineru library](mineru-library.md) |@@ -57,7 +58,25 @@纯文本文件可以直接读取;Office 和 HTML 通常可本地 CPU 解析;PDF 和图片按 tier 路由到默认选择、`flash`、`standard` 或 `pro`。-## 5. 与 mineru-kit 的关系+## 5. parse 与 read++`mineru` 中有两条读取链路:++```text+parse(path) = ensure document is parsed, then read default content+read(locator) = read existing parsed content by stable locator+```++- `mineru parse` 适合第一次从文件 path 出发读取文档。+- `mineru read` 适合基于 `short_id`、page、block 或 char locator 继续阅读已有解析结果。++典型流程:++1. `mineru parse report.pdf`+2. 从输出或 JSON 响应中拿到后续 locator+3. `mineru read doc:ab12cd3/tier:standard/page:11`++## 6. 与 mineru-kit 的关系`mineru` 使用更少、更稳定的参数集合。复杂批处理、目录展开、stdin 混合输入、输出冲突策略、并发控制等能力放在 `mineru-kit parse`。diff --git a/docs/next/decisions/0001-json-output-formats.md b/docs/next/decisions/0001-json-output-formats.mdindex 0119a8ae..010081aa 100644--- a/docs/next/decisions/0001-json-output-formats.md+++ b/docs/next/decisions/0001-json-output-formats.md@@ -59,7 +59,7 @@ Structured Content 是面向 Agent、新客户端和结构化下游的推荐 JSO- 按页组织。- 标题、段落、列表、公式、图片、表格、代码等语义类型。-- 可选 bbox / locator / chunk id。+- 可选 bbox / locator。- 稳定 schema version。Structured Content 的版本演进通过 schema version 表达,而不是把公开格式名改成 `structured-content-v2`、`structured-content-v3`。diff --git a/docs/next/decisions/0011-doclib-doc-short-id.md b/docs/next/decisions/0011-doclib-doc-short-id.mdindex 74ba6ff5..c00f3d64 100644--- a/docs/next/decisions/0011-doclib-doc-short-id.md+++ b/docs/next/decisions/0011-doclib-doc-short-id.md@@ -106,9 +106,9 @@ SQLite 的错误信息未必稳定区分具体 unique constraint。实现时可拒绝。固定 12 位实现简单,但仍存在理论碰撞;一旦碰撞,需要额外 fallback 规则。持久化 `short_id` 可以在保持短引用的同时由 DB 提供唯一性保证。-### 方案 D: 不持久化 `short_id`,在 block reference 中直接使用 hash 型 `chunk_id`+### 方案 D: 不持久化 `short_id`,在 block reference 中直接使用额外 hash ID-拒绝作为 P0 主方案。hash 型 chunk id 更短且不可枚举,但不如基于 `short_id` 的引用可读。P0 先持久化 `short_id`;hash 型 chunk id 后续可作为补充字段。+拒绝作为 P0 主方案。额外 hash ID 更短且不可枚举,但不如基于 `short_id` 的引用可读。P0 先持久化 `short_id`,并使用可读的 page/block locator。## 影响diff --git a/docs/next/decisions/0012-doclib-block-locator.md b/docs/next/decisions/0012-doclib-block-locator.mdindex fbc479f9..9d113351 100644--- a/docs/next/decisions/0012-doclib-block-locator.md+++ b/docs/next/decisions/0012-doclib-block-locator.md@@ -14,7 +14,7 @@ Agent 读取文档后,需要稳定地引用文档中的具体内容块。引- 不依赖 render 输出是否隐藏某些 block。- 能在 Markdown marker、Structured Content 和 citation record 中复用。-此前 `agent-gaps.md` 讨论过 hash 型 `chunk_id`。本 ADR 将 P0 的主引用模型收敛为局部 locator 与全局 block reference。+此前部分文档把稳定引用描述成额外 ID。本 ADR 将 P0 的主引用模型收敛为局部 locator 与全局 block reference。## 决策@@ -185,9 +185,9 @@ P0 可以不支持短于 `short_id` 的 prefix lookup。调用方传入不完整拒绝。P0 不把 span/cell/list item 作为公开引用目标。细粒度定位后续再设计。-### 方案 E: 使用 hash 型 chunk id 作为主引用+### 方案 E: 使用额外 hash ID 作为主引用-暂缓。hash 型 chunk id 可作为后续补充字段,但 P0 主引用使用可读的 `block_ref`。+拒绝作为 P0 主方案。P0 主引用使用可读的 `block_ref`,避免同时维护两套含义接近的引用 ID。## 影响diff --git a/docs/next/decisions/0014-mineru-read-command.md b/docs/next/decisions/0014-mineru-read-command.mdnew file mode 100644index 00000000..66f5fdc7--- /dev/null+++ b/docs/next/decisions/0014-mineru-read-command.md@@ -0,0 +1,483 @@+# ADR-0014: MinerU Read Command++状态: Accepted+日期: 2026-06-16+相关文档: 0012-doclib-block-locator.md, 0013-doc-content-progressive-reading.md, ../cli/mineru-parse.md, ../workflows.md++## 背景++`mineru parse` 从文件 path 出发,负责入库、解析、等待任务完成,并读取默认内容。Agent 后续继续阅读时,不应一直依赖本地绝对路径或重新传递 path,而应进入稳定 locator 世界。++ADR-0011 定义了 `docs.short_id`,ADR-0012 定义了 page/block locator,ADR-0013 定义了 parse content 的渐进式阅读协议。基于这些能力,需要新增一个 locator-first 的顶级命令:++```bash+mineru read <locator>+```++`read` 的目标是读取 doclib 中已有解析结果。它不负责 discover、scan、ingest,也不默认创建 parse task。++## 决策++新增 `mineru read` 顶级命令:++```bash+mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]+```++`parse` 与 `read` 的职责边界:++```text+parse(path) = ensure document is parsed, then read default content+read(locator) = read existing parsed content by stable locator+```++`parse` 当前只支持 `--format markdown`。++`read` P0 支持:++```text+ContentFormat = Literal["markdown", "image"]+```++`--format` 表示 content format;`--json` 表示 CLI response envelope 使用 JSON。二者不是同一层语义。++## Locator 输入++`read` 支持以下 locator 粒度:++```text+doc:{short_id}+doc:{short_id}/tier:{tier}+doc:{short_id}/tier:{tier}/page:{page_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}+```++规则:++- `page_no` 和 `block_no` 使用 1-based 编号。+- `char:{offset}` 使用 block 渲染文本内的 0-based 字符 offset。+- `doc:{short_id}` 会解析为当前可用的默认高质量 tier;不会静默把 `flash` 当作高质量读取结果。+- `doc:{short_id}/tier:{tier}` 明确读取指定 tier 的已有结果。++## Markdown 读取语义++`--format markdown` 是默认格式。++| Locator | 默认读取范围 |+|---------|--------------|+| `doc:{short_id}` | 默认 tier 的默认阅读范围。 |+| `doc:{short_id}/tier:{tier}` | 该 tier 的默认阅读范围。 |+| `.../page:{page_no}` | 该页。 |+| `.../block:{block_no}` | 该 block。 |+| `.../char:{offset}` | 从该 block 的 offset 起读取。 |++`--limit` 是软字符限制,沿用 ADR-0013 的规则,尽量在页、block、段落、句子、换行或空白边界停止。++### `--context`++`--context N` 的含义随 locator 粒度变化:++| Locator | `--context` 行为 |+|---------|------------------|+| page locator | 读取前后各 N 页。 |+| block locator | 读取前后各 N 个 block。 |+| char locator | 按 block locator 处理上下文,char 只影响起点。 |+| doc locator | 返回 `context_not_applicable`。 |+| doc/tier locator | 返回 `context_not_applicable`。 |++## Image 读取语义++`--format image` 是 P0 能力,但范围受文档类型和 locator 粒度约束。++不支持多页 image 输出。++| 文档类型 | doc locator | doc/tier locator | page locator | block locator |+|----------|:-----------:|:----------------:|:------------:|:-------------:|+| PDF | 不支持 | 不支持 | 支持 | 有 bbox 且 bbox 非 empty 时支持 |+| Office | 不支持 | 不支持 | 不支持 | 仅 image block 支持 |+| 其它 | 不支持 | 不支持 | 不支持 | 暂不支持 |++PDF 的 image 输出规则:++- page image 从原 PDF page 渲染得到。+- block image 从原 PDF page 渲染后按 bbox 裁剪得到。+- block image 不按 block type 判断;只要 bbox 存在且非 empty,就可以输出 image。+- 实现时复用 `PDFDocument.render_page()` / `PDFDocument.crop_image()`,并从 `files` 表按 `sha256` 查找 active source path 读取原 PDF bytes。++Office 的 image 输出规则:++- Office 不支持 doc、doc/tier、page locator 输出 image。+- Office 只有 image block 支持输出 image。+- Office image block 只能从 Middle JSON 中读取 image asset。+- 实现时优先使用 image block 内的 `span.image_base64` 解码生成临时 asset。+- 如果 Middle JSON 中只有 `span.image_path`,仅在该 path 可访问时作为 fallback。+- 当前 doclib parsed 目录只持久化 JSON,不保证已额外持久化 Office image 文件;因此不能依赖 `ParseResult.save()` 产物存在。++默认情况下,image 输出打印 asset path。传入 `--output` 时,由 CLI 在 client 侧把 server 返回的 asset copy 到指定路径。传入 `--json` 时输出完整 `DocContentResponse`。++## 响应模型扩展++`read` 与 `parse` 的读取结果都继续使用 `DocContentResponse`。不能为了 locator-first 删除 parse read 已有字段。++在 ADR-0013 的基础上做最小扩展:++```python+ContentFormat = Literal["markdown", "image"]+++class ContentRequestScope(DoclibModel):+ page_range: str | None = None+ after: str | None = None+ limit: int = 30000+ locator: str | None = None+ context: int = 0+++class ContentNextRequest(DoclibModel):+ page_range: str | None = None+ after: str | None = None+ locator: str | None = None+++class ContentAsset(DoclibModel):+ path: str+ mime_type: str+ size_bytes: int | None = None+ width: int | None = None+ height: int | None = None+++class DocContentResponse(DoclibModel):+ sha256: str+ short_id: str+ tier: Tier+ format: ContentFormat+ content: str+ request_scope: ContentRequestScope+ content_ranges: list[ContentRange]+ truncated: bool = False+ next_request: ContentNextRequest | None = None+ asset: ContentAsset | None = None+```++字段规则:++- parse read 保留现有字段语义。+- parse read 的 `request_scope.locator = None`,`request_scope.context = 0`。+- locator read 的 `request_scope.locator` 填入规范化 locator。+- locator read 的 `request_scope.context` 填入实际生效的 context。+- parse read 的 `next_request` 只写 `page_range` / `after`,不写 `locator`。+- read 的 `next_request` 只写 `locator`,不写 `page_range` / `after`。+- image 输出时 `content=""`,asset 信息写入 `asset`,不把图片路径塞进 `content`。++parse read 返回示例:++```json+{+ "sha256": "...",+ "short_id": "ab12cd3",+ "tier": "standard",+ "format": "markdown",+ "content": "...",+ "request_scope": {+ "page_range": "1~10",+ "after": null,+ "limit": 30000,+ "locator": null,+ "context": 0+ },+ "content_ranges": [+ {+ "page_range": "1~10",+ "start": "doc:ab12cd3/tier:standard/page:1",+ "end": "doc:ab12cd3/tier:standard/page:10/block:18"+ }+ ],+ "truncated": false,+ "next_request": {+ "page_range": "11~20",+ "after": null,+ "locator": null+ },+ "asset": null+}+```++locator read 返回示例:++```json+{+ "sha256": "...",+ "short_id": "ab12cd3",+ "tier": "standard",+ "format": "markdown",+ "content": "...",+ "request_scope": {+ "page_range": "4",+ "after": null,+ "limit": 30000,+ "locator": "doc:ab12cd3/tier:standard/page:4/block:12",+ "context": 2+ },+ "content_ranges": [+ {+ "page_range": "4",+ "start": "doc:ab12cd3/tier:standard/page:4/block:10",+ "end": "doc:ab12cd3/tier:standard/page:4/block:14"+ }+ ],+ "truncated": false,+ "next_request": null,+ "asset": null+}+```++image read 返回示例:++```json+{+ "sha256": "...",+ "short_id": "ab12cd3",+ "tier": "standard",+ "format": "image",+ "content": "",+ "request_scope": {+ "page_range": "4",+ "after": null,+ "limit": 30000,+ "locator": "doc:ab12cd3/tier:standard/page:4/block:12",+ "context": 0+ },+ "content_ranges": [+ {+ "page_range": "4",+ "start": "doc:ab12cd3/tier:standard/page:4/block:12",+ "end": "doc:ab12cd3/tier:standard/page:4/block:12"+ }+ ],+ "truncated": false,+ "next_request": null,+ "asset": {+ "path": "/Users/me/.mineru/exports/ab12cd3-page-4-block-12.png",+ "mime_type": "image/png",+ "size_bytes": 12345,+ "width": 800,+ "height": 320+ }+}+```++## Continuation 与 marker++parse read 保持 ADR-0013 现有行为:++- `next_request.page_range` / `next_request.after` 用于下一次 `mineru parse`。+- CLI continuation marker 渲染为 `mineru parse <path> --pages ... --after ...`。++read 使用 locator continuation:++- `next_request.locator` 用于下一次 `mineru read`。+- CLI continuation marker 渲染为:++```markdown+<!-- Next: mineru read doc:ab12cd3/tier:standard/page:5 -->+```++P0 暂不实现 block locator marker,即不在每个 block 前默认输出:++```markdown+<!-- mineru:locator ... -->+```++`--no-marker` 关闭 continuation marker。++## 实现方案++`parse` 和 `read` 不合并 CLI 参数,也不共享入口 request model。二者共享内部读取计划和执行器。++```text+parse_cmd+ -> ensure_parse+ -> ParseReadRequest+ -> build_read_plan_from_parse()+ -> execute_read_plan()+ -> output_doc_content_response()++read_cmd+ -> LocatorReadRequest+ -> build_read_plan_from_locator()+ -> execute_read_plan()+ -> output_doc_content_response()+```++入口 request:++```python+class ParseReadRequest(DoclibModel):+ sha256: str+ tier: Tier+ page_range: str | None = None+ after: str | None = None+ limit: int = 30000+ format: Literal["markdown"] = "markdown"+ no_marker: bool = False+++class LocatorReadRequest(DoclibModel):+ locator: str+ context: int = 0+ limit: int = 30000+ format: Literal["markdown", "image"] = "markdown"+ no_marker: bool = False+```++内部计划:++```python+class ReadPlan(DoclibModel):+ sha256: str+ short_id: str+ tier: Tier+ page_range: str | None = None+ after: str | None = None+ locator: str | None = None+ context: int = 0+ limit: int = 30000+ format: Literal["markdown", "image"] = "markdown"+ no_marker: bool = False+```++转换规则:++- `build_read_plan_from_parse()` 只处理 `sha256/tier/page_range/after/limit`。+- `build_read_plan_from_parse()` 生成的 plan 中 `locator=None`、`context=0`。+- `build_read_plan_from_locator()` 解析 locator,查出 `sha256/short_id/tier`,并根据 locator 粒度生成 `page_range`、`after`、`locator` 和 `context`。+- doc locator 和 doc/tier locator 使用默认阅读范围。+- page locator 使用单页或 context 扩展后的页范围。+- block locator 使用所在页,并由执行器选择目标 block 和上下文 block。+- char locator 使用所在页,并从 char offset 起读取。++执行器:++```python+def execute_read_plan(plan: ReadPlan) -> DocContentResponse: ...+```++执行器负责:++- load done JSON batches。+- filter pages。+- select page/block/char/context。+- render markdown。+- render page/block image。+- PDF image 使用原 PDF 渲染/crop;Office image 使用 Middle JSON 中的 `span.image_base64` 或可访问的 `span.image_path`。+- apply soft limit。+- build `content_ranges`。+- build `next_request`。+- create temporary image assets when `format="image"`。++CLI 输出 helper:++```python+def output_doc_content_response(+ response: DocContentResponse,+ *,+ json_mode: bool,+ output: str | None,+ source_path: str | None,+ read_mode: bool,+) -> None: ...+```++规则:++- `json_mode=True` 时输出完整 `DocContentResponse`。+- markdown 非 JSON 时输出 `content`,并按入口输出 continuation marker。+- image 非 JSON 时输出 `asset.path`。+- `output` 由 CLI 在 client 侧处理: markdown 写入 `content`,image copy `asset.path` 到目标路径。+- parse marker 使用 `page_range/after`。+- read marker 使用 `locator`。++## HTTP / SDK++P0 新增 locator-first 接口:++```python+def read_content(+ self,+ locator: str,+ *,+ context: int = 0,+ limit: int = 30000,+ format: Literal["markdown", "image"] = "markdown",+ no_marker: bool = False,+) -> DocContentResponse: ...+```++HTTP 路由:++```http+GET /api/v1/content?locator=doc:ab12cd3/tier:standard/page:4&format=markdown&limit=30000+GET /api/v1/content?locator=doc:ab12cd3/tier:standard/page:4/block:12&format=image+```++P0 不为 locator-first content API 提供 POST export。`GET /api/v1/content` 可以在 server 内部生成临时 image asset,但不接受 client 指定的 output path。CLI `read --output` 是 client 侧文件写入/copy 行为,不是 doclib HTTP API 行为。++实现时在 Interface 中定义同步和异步方法,再由 client/server 使用相同签名实现。++## 错误码++| code | 场景 |+|------|------|+| `invalid_locator` | locator 格式非法。 |+| `doc_not_found` | short_id 找不到。 |+| `tier_not_cached` | 指定 tier 没有缓存解析结果。 |+| `page_not_cached` | 指定页没有缓存解析结果。 |+| `block_not_found` | block 不存在。 |+| `char_offset_out_of_range` | char offset 超出 block 内容长度。 |+| `context_not_applicable` | doc 或 doc/tier locator 使用了 context。 |+| `format_not_supported` | 当前 locator 或文档类型不支持该 format。 |+| `multi_page_image_not_supported` | 请求范围覆盖多页 image。 |+| `bbox_not_available` | PDF block 没有 bbox 或 bbox empty。 |+| `asset_not_available` | Office image block 没有可读取 asset。 |++## P0 范围++必须实现:++1. `mineru read <locator>`。+2. doc / doc+tier / page / block / char locator。+3. `--format markdown`。+4. `--format image`,按本文 image 边界实现。+5. `--json`。+6. `--limit`。+7. `--context`,按 locator 粒度规则实现。+8. read continuation marker。+9. parse/read 共享 `ReadPlan` 与 `execute_read_plan()`。+10. `DocContentResponse` 增加 `asset`,`ContentRequestScope` 增加 `locator/context`,`ContentNextRequest` 增加 `locator`。++暂不实现:++1. 多页 image 输出。+2. `--format structured_content`。+3. `--format text`。+4. `--format csv` / `--format html`。+5. block locator marker。+6. search result locator。+7. doc/tier locator 的 `--format image` 多页导出包。++## 后果++正面:++- Agent 可以从 search、content_ranges 或 continuation 中拿到 locator 后,用统一命令继续读取。+- `parse` 和 `read` 共享实际读取执行器,避免两套 render/limit/marker/image 逻辑。+- parse read 已有响应结构不被破坏。+- image 读取成为 locator 的通用能力,而不是 image block 的特殊命令。++代价:++- `DocContentResponse` 会同时承载 parse read 和 locator read 的字段。+- `ContentNextRequest` 同时有 `page_range/after` 和 `locator`,但通过入口规则避免混用。+- image 输出需要补 PDF page render/crop 和 Office asset 读取两条实现路径。diff --git a/docs/next/decisions/0015-cli-output-json-composition.md b/docs/next/decisions/0015-cli-output-json-composition.mdnew file mode 100644index 00000000..00fa18c6--- /dev/null+++ b/docs/next/decisions/0015-cli-output-json-composition.md@@ -0,0 +1,230 @@+# ADR-0015: CLI Output 与 JSON 组合语义++状态: Accepted+日期: 2026-06-17+相关文档: ../cli/mineru.md, ../cli/mineru-parse.md, ../cli/mineru-read.md, ../cli/mineru-e2e-test-cases.md, 0014-mineru-read-command.md++## 背景++`mineru parse` 和 `mineru read` 都支持 `--output` 与 `--json`:++```bash+mineru parse <path> --output out.md --json+mineru read <locator> --output out.md --json+```++这两个选项处在不同语义层:++- `--output` 控制内容产物写到哪里。+- `--json` 控制 CLI stdout 的响应格式是否为机器可读 JSON。++如果二者同时指定时仍输出 `Written to ...` 这类人类文本,会破坏 JSON 模式的自动化契约。反过来,如果简单禁止组合,调用方在写文件后还需要额外调用 `show`、`read` 或 `list` 才能拿到 `sha256`、`short_id`、`tier`、`request_scope` 等结构化信息,降低 Agent 和脚本使用效率。++同时,`--output + --json` 不能引入新的顶层 JSON shape。`parse --json` 和 `read --json` 已各自有稳定的 JSON 输出结构;是否指定 `--output` 只能在该稳定结构上增加写入结果字段,不能改写其顶层组织方式。++因此需要明确 `--output` 与 `--json` 同时指定时的长期 CLI 行为。++## 决策++`--output` 与 `--json` 可以同时指定。++组合语义:++```text+--output 控制内容产物落盘。+--json 控制 stdout 输出命令结果 envelope。+```++当命令成功时:++- 内容写入 `--output` 指定路径。+- stdout 只输出 JSON。+- stdout 不输出 `Written to ...`、Rich 表格、Markdown 内容或其它人类提示文本。+- JSON 顶层 shape 保持与不带 `--output` 时一致。+- JSON 中必须包含写入结果和足够的文档定位信息。++当命令失败时:++- exit code != 0。+- 如果命令带 `--json`,stdout 应输出 JSON error。+- 不输出半截 JSON 混合人类文本。+- 不产生空的成功输出文件;如果部分文件已写入,应由实现尽量清理,或在 JSON error 中明确说明。++## 成功响应++### `mineru parse --output PATH --json`++成功时 stdout 继续输出稳定的 `parse --json` envelope,而不是文档全文。`--output` 只是在该 envelope 上增加写入结果字段:++```json+{+ "parse": {+ "sha256": "...",+ "tier": "flash",+ "page_range": "1",+ "status": "done"+ },+ "content": null,+ "output": {+ "status": "written",+ "path": "/abs/path/out.md"+ }+}+```++字段要求:++- 顶层继续使用稳定的 `parse` / `content` 结构。+- `parse`: 使用 `mineru parse --json` 已定义的稳定解析摘要结构。+- `content`: 当 `--output` 成功写出文件时可以为 `null`;CLI 不要求在写文件成功的同时再把全文内容重复放回 stdout JSON。+- `output`: 顶层对象,至少包含 `status` 和 `path` 两个字段。+- `output.status`: 当前固定为 `written`。+- `output.path`: 实际写入路径,建议为绝对路径或规范化绝对路径。++### `mineru read --output PATH --json`++成功时 stdout 继续输出稳定的 `read --json` 结构;`--output` 只是在该结构上增加写入结果字段。为避免 stdout JSON 同时携带完整正文和写出副作用结果,当 `--output` 生效时,`content` 字段应置为 `null`:++```json+{+ "sha256": "...",+ "short_id": "...",+ "tier": "flash",+ "format": "markdown",+ "content": null,+ "request_scope": {+ "locator": "doc:abc1234/tier:flash/page:1",+ "context": 0,+ "limit": 30000+ },+ "content_ranges": [],+ "output": {+ "status": "written",+ "path": "/abs/path/out.md"+ }+}+```++对于 image 输出:++```json+{+ "sha256": "...",+ "short_id": "...",+ "tier": "flash",+ "format": "image",+ "content": null,+ "request_scope": {+ "locator": "doc:abc1234/tier:flash/page:1",+ "context": 0,+ "limit": 30000+ },+ "asset": {+ "mime_type": "image/png",+ "size_bytes": 12345,+ "width": 1000,+ "height": 1414+ },+ "output": {+ "status": "written",+ "path": "/abs/path/page.png"+ }+}+```++`asset.path` 不应暴露服务端临时文件路径作为主要结果;`output` 是用户指定并可使用的产物路径。如需调试,可额外提供 `source_asset` 字段,但不能要求调用方依赖它。++规则:++- `read --json` 的顶层 shape 不因为 `--output` 改变。+- 对于 text / markdown 写出,CLI 继续返回 `DocContentResponse` 风格结构,但把 `content` 置为 `null`,并额外增加顶层 `output` 对象。+- 对于 image 写出,CLI 也继续返回 `DocContentResponse` 风格结构,并把 `content` 置为 `null`;`output` 是用户可用的最终路径;`asset.path` 如保留,应明确只是服务端临时来源,不是调用方应依赖的主路径。+- `output.status` 当前固定为 `written`;后续如需区分 `copied`、`overwritten` 等状态,应在不改变顶层 shape 的前提下扩展。++## `--output -`++`--output -` 表示输出到 stdout,等价于不指定 `--output`。++规则:++- `mineru parse ... --output -` 输出内容到 stdout。+- `mineru read ... --output -` 输出内容或 asset path 到 stdout。+- `--output - --json` 时,stdout 仍输出 JSON 响应,不写文件,也不新增 `output` 字段。+- 不创建名为 `-` 的文件。++## 输出路径++`--output PATH` 允许自动创建不存在的父目录。++规则:++- 如果父目录不存在,实现应创建父目录。+- 如果父目录无法创建或无写权限,命令失败。+- 已存在的输出文件允许覆盖,除非后续新增显式 `--no-clobber` 之类选项。+- `PATH` 中的 `~` 应由 CLI 主动 `expanduser`。++## JSON 错误契约++所有支持 `--json` 的命令都应遵守统一错误输出:++```json+{+ "error": {+ "type": "invalid_request_error",+ "code": "file_not_found",+ "message": "...",+ "param": "path"+ }+}+```++这条规则不仅适用于 `parse` 和 `read`,也适用于 `watch`、`show`、`config`、`cleanup` 等带 `--json` 的命令。++Typer 在参数解析阶段产生的错误可以保持框架默认输出;但进入命令实现后的业务错误,在 `--json` 下必须输出 JSON error。++## 替代方案++### 方案 A: 禁止 `--output` 与 `--json` 同时指定++不采用。++该方案实现简单,但会让自动化调用变笨。调用方写文件后仍需要额外查询结构化结果,不利于 Agent 和脚本编排。++### 方案 B: `--json` 时忽略 `--output`++不采用。++这会让用户传入的 `--output` 静默失效,风险高,且 `parse` 与 `read` 很容易出现不一致。++### 方案 C: `--output` 时忽略 `--json`++不采用。++这会破坏 `--json` 的核心承诺: stdout 可被机器直接解析。++### 方案 D: 同时输出 JSON 和人类文本++不采用。++混合输出会导致 JSON parser 失败,是最差的自动化体验。++## 影响++- `mineru parse --output PATH --json` 需要保持稳定的 `parse --json` 顶层结构,并增加 `output` 字段;不能输出 `Written to ...`。+- `mineru read --output PATH --json` 需要保持稳定的 `read --json` 顶层结构,并增加 `output` 字段;不能静默忽略 `--output`。+- `parse` 和 `read` 的 help 文案应说明:+ - `--output` 可自动创建父目录。+ - 与 `--json` 同时指定时,stdout 输出写入结果 JSON。+- E2E 测试应断言:+ - `--output + --json` stdout 可直接 JSON parse。+ - 输出文件确实存在。+ - stdout 不包含 `Written to`。+- CLI path 处理应对 `--output` 和输入 path 执行 `expanduser`。++## 后续动作++1. 更新 `mineru parse` 和 `mineru read` 实现,统一 `--output + --json` 响应 envelope。+2. 更新 CLI help 文案。+3. 更新 E2E 测试用例,将不存在父目录的 `--output` 预期改为自动创建并成功。+4. 为 `parse/read --output --json` 添加单元测试和 E2E 复核。+5. 推进所有支持 `--json` 的命令统一业务错误 JSON 输出。diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.mdindex 251129d5..a18e8827 100644--- a/docs/next/decisions/README.md+++ b/docs/next/decisions/README.md@@ -41,6 +41,8 @@| [ADR-0011](0011-doclib-doc-short-id.md) | Accepted | Doclib Doc Short ID || [ADR-0012](0012-doclib-block-locator.md) | Accepted | Doclib Block Locator || [ADR-0013](0013-doc-content-progressive-reading.md) | Accepted | Doc Content Progressive Reading |+| [ADR-0014](0014-mineru-read-command.md) | Accepted | MinerU Read Command |+| [ADR-0015](0015-cli-output-json-composition.md) | Accepted | CLI Output 与 JSON 组合语义 |## 模板diff --git a/docs/next/everydoc-doclib-gap-review.md b/docs/next/everydoc-doclib-gap-review.mdindex 866f7c6b..dbeccbc1 100644--- a/docs/next/everydoc-doclib-gap-review.md+++ b/docs/next/everydoc-doclib-gap-review.md@@ -303,7 +303,7 @@ P0 结论:MinerU 当前状态:-- Middle JSON 文档已有 locator / chunk id 方向。+- Middle JSON 文档已有 locator 方向。- 当前 doclib FTS 仍主要是文档级 `fts_contents`。风险:@@ -333,7 +333,7 @@ MinerU 当前状态:风险:- parser 或 Middle JSON schema 升级后,无法系统性识别需要重新解析的旧缓存。-- Agent locator / chunk id 可能因历史数据结构差异而不稳定。+- Agent locator 可能因历史数据结构差异而不稳定。建议讨论:diff --git a/docs/next/implementation-plan.md b/docs/next/implementation-plan.mdindex a3336209..ee511bcf 100644--- a/docs/next/implementation-plan.md+++ b/docs/next/implementation-plan.md@@ -17,6 +17,7 @@| `blocked` | 需要先完成依赖任务。 || `verify-first` | 代码可能已经部分实现;先补测试或确认行为,再决定是否改代码。 || `design-needed` | 仍需产品或架构确认,不应直接实现。 |+| `done` | 当前代码和测试已满足完成边界;后续只在回归或重构时触碰。 |Agent 通用规则:@@ -52,19 +53,22 @@ ID:### 3.1 当前代码审计范围-本计划已经结合当前代码做过一轮快速审计,但不是完整逐行 review。已检查的关键路径:+本计划已经结合当前代码做过多轮快速审计,但不是完整逐行 review。最近一次对齐时间为 2026-06-16,已检查的关键路径:| 代码路径 | 结论 ||----------|------|| `mineru/doclib/services/parse_svc.py` | 已有 ingest、parse request、页码覆盖判断、JSON 批次写入、FTS 临时 Markdown、tier/remote 路由的基础实现。 || `mineru/doclib/background/compaction.py` | 已有 done parse batch 合并和 JSON 按 `page_idx` 合并逻辑。 |-| `mineru/doclib/routes/parse.py` | 现有 `/parse/content` 已能从 JSON 批次读取并即时 render Markdown;NEXT 目标路径为 `GET /docs/{sha256}/content`。 |-| `mineru/doclib/core/fts.py`、`services/search_svc.py` | FTS 已存 tier,搜索结果已返回来源 tier。 |-| `mineru/doclib/client.py` | 已有 Doclib SDK 和 error envelope -> `MineruError` 基础映射。 |+| `mineru/doclib/server.py` | 新 doclib server 已接管 Interface 路由;`GET /docs/{sha256}/content` 已支持 read-time Markdown、`limit`、`after`、`content_ranges` 和 `next_request`。 |+| `mineru/doclib/client.py` | 同步 Doclib client 已实现 Interface;route metadata 与 server 由测试约束一致。 |+| `mineru/doclib/core/fts.py`、`services/search_svc.py` | FTS 已存 tier;搜索结果已返回来源 tier,并支持 `tier`、`min_tier`、`file_type` 过滤。 |+| `mineru/doclib/locators.py` | 已有 `short_id` 相关 block/page/char cursor helper;P0 引用模型收敛为稳定 page/block locator。 || `mineru/parser/base.py` | `ParseResult.from_dict()` / `from_json()` 仍是 TODO。 |-| `mineru/parser/__init__.py` | Tool SDK `parse()` 已有 backend 参数,但还没有 tier 参数。 |-| `mineru/constants.py` | `Tier` 目前只有 `flash` / `standard` / `pro` 枚举。 |+| `mineru/parser/__init__.py` | Tool SDK `parse()` / `parse_async()` 已有 `tier` 参数,并保留 `backend` 高级参数。 |+| `mineru/types.py` | `Tier`、`TIER_ORDER` 与 Middle JSON typed dataclass 在此定义;尚无 Middle JSON normalize / validator。 || `mineru/errors.py` | 已有 `MineruError`、`engine_error` 映射和错误 envelope helper,但部分新 code 仍未补齐。 |+| `mineru/cli_next/main.py` | `mineru parse/scan/watch/search/find/list/show/server/config/invalidate/forget/cleanup` 已按 NEXT 入口组织;尚无 `mineru telemetry`。 |+| `mineru/parser/api_server.py`、`mineru/parser/api_client.py` | v1 parse API、uploads/files、tiers、usage 和 API-backed parser 已有基础;callback/webhook 本地差异和 chat/responses 仍需明确边界。 |因此,任务分成三类:@@ -85,12 +89,14 @@ Agent 领取任务时,应先读本节。如果任务标记为“已实现需| M2 | doclib 主链路 | watch/ingest/parse/cache/compaction/read-time render 可闭环。 || M3 | tier、privacy、parse-server 路由 | 默认选择、local/remote、standard/pro 行为可验证。 || M4 | CLI / SDK / API 对齐 | 用户入口使用同一语义和错误模型。 |-| M5 | Agent-native 输出 | locator、chunk id、marker、citation 基础可用。 |+| M5 | Agent-native 输出 | locator、marker、citation 基础可用。 |+| M6 | Telemetry | doclib server 聚合、flush、CLI 管理入口和隐私边界可验证。 |建议顺序:```textM0 -> M1 -> M2 -> M3 -> M4 -> M5+M6 可独立并行推进,但不能影响 parse / watch / search 主流程。```M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JSON batch 读取和 read-time render 有依赖关系。@@ -99,37 +105,39 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS| 任务 | 当前代码状态 | Agent 领取方式 ||------|--------------|----------------|-| M0-001 | 测试骨架不足 | 新增测试基础设施。 |-| M0-002 | 已实现需锁定 | 补测试证明 doclib 只落 JSON。 |+| M0-001 | 已实现 | 已有 doclib / parser / CLI 单元测试骨架;新增任务直接复用。 |+| M0-002 | 已实现需锁定 | 已有 JSON-only 行为基础;继续补高风险边界测试。 || M0-003 | 需要实现 | 新增 Middle JSON fixtures。 || M1-001 | 需要实现 | `ParseResult.from_dict()` / `from_json()` 是 TODO。 || M1-002 | 需要实现 | 新增 normalize helper。 || M1-003 | 需要实现 | 新增 validator。 || M1-004 | 部分实现 | 先用 validator 跑 HTML 输出,再最小修。 || M1-005 | 需要实现 | 新增 `bbox_known()`。 |-| M2-001 | 部分实现 | 抽出并统一 batch JSON 路径 helper。 |-| M2-002 | 部分实现 | 修正 cache check 硬编码 data_dir 的风险。 |-| M2-003 | 已实现需锁定 | 补测试锁定未覆盖页入队和 priority bump。 |-| M2-004 | 已实现需锁定 | 补 compaction JSON 合并测试。 |-| M2-005 | 部分实现 | `/parse/content` 已支持 Markdown;补完整 read-time render 边界。 |-| M2-006 | 已实现需锁定 | 补 FTS 不落盘 Markdown 和 tier-gated 测试。 |-| M3-001 | 部分实现 | `tier=None` 已解析;需锁定默认选择不持久化为独立 tier。 |-| M3-002 | 已实现需锁定 | 补 local 不自动 remote 的测试。 |-| M3-003 | 已实现需锁定 | 补 remote fallback local 的测试。 |-| M3-004 | 已实现需锁定 | 补 tier mismatch 不降级的测试和错误 code 检查。 |-| M4-001 | 部分实现 | CLI/doclib 需对齐 read-time render 多格式。 |-| M4-002 | 需要实现 | Tool SDK `parse()` 还没有 `tier` 参数。 |+| M2-001 | 已实现 | `parse_batch_json_path()` 已被 parse_svc / compaction 复用。 |+| M2-002 | 已实现 | cache coverage 与 compaction 均使用配置 data_dir;已有相关测试。 |+| M2-003 | 已实现需锁定 | 未覆盖页入队、active parse 复用和 priority bump 已有实现与测试;继续补失败边界。 |+| M2-004 | 已实现需锁定 | compaction JSON 合并已有实现与测试;继续锁定重复页/invalidated 边界。 |+| M2-005 | 部分实现 | `GET /docs/{sha256}/content` 已支持 Markdown / progressive reading;Content List / HTML read-time render 仍需确认。 |+| M2-006 | 已实现需锁定 | FTS 临时 Markdown、JSON-only、tier-gated 更新已有实现;继续补回归测试。 |+| M3-001 | 已实现需锁定 | `tier=None` 已在入队前解析为实体 tier;需补默认选择错误码边界。 |+| M3-002 | 已实现需锁定 | local 不自动 remote 已有实现;补调用边界测试。 |+| M3-003 | 已实现需锁定 | remote 失败 fallback local 已有实现;补 `via=local` 和 tier 能力测试。 |+| M3-004 | 已实现需锁定 | tier mismatch 不降级已有实现;补错误 code / message 边界测试。 |+| M4-001 | 部分实现 | CLI 已调用 doclib read-time render;JSON/HTML/Content List 输出边界仍需对齐。 |+| M4-002 | 已实现需锁定 | Tool SDK `parse()` / `parse_async()` 已有 `tier` 参数;补 backend 覆盖 tier 测试。 || M4-003 | 部分实现 | Doclib client 已有映射;API-backed parser 等仍需统一。 || M4-004 | 部分实现 | api_server/client 已有基础,需按文档补差异测试。 |-| M5-001 | 需要实现 | 新增 locator/chunk id helper。 |-| M5-002 | blocked | 依赖 M5-001。 |-| M5-003 | 已实现需锁定 | 搜索结果已返回 tier;补测试和 CLI/JSON 边界。 |+| M5-001a | 已实现需锁定 | doclib locator helper 已实现;补 Structured Content / marker 复用边界。 |+| M5-002 | ready | Markdown block marker 尚未完整实现。 |+| M5-003 | 已实现需锁定 | 搜索结果已返回 tier,并支持过滤;补 CLI/JSON 边界。 |+| M6-001 | 需要实现 | Telemetry DB schema、状态管理、聚合与 flush 尚未实现。 |+| M6-002 | 需要实现 | `mineru telemetry status|enable|disable|preview|flush` 尚未实现。 |## 4. M0: 测试与基线### M0-001 建立 doclib parse flow 测试入口-状态: `ready`+状态: `done`目标:@@ -347,8 +355,8 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS具体步骤:-1. 在 schema 或 middle_json helper 模块中定义 `normalize_middle_json(payload, *, backend=None, tier=None, sha256=None)`。-2. 如果 payload 已有 `schema_version` 和 `pages`,补齐缺省 `_meta`。+1. 在 `mineru/schema/middle_json/` 中复用 `MIDDLE_JSON_SCHEMA_VERSION`,并定义 `normalize_middle_json(payload, *, backend=None, tier=None, sha256=None)`。+2. 如果 payload 已有 `schema_version` 和 `pages`,直接接受;`_meta` 在当前 P0 写出结构中可缺省。3. 如果 payload 是 `{"pages": [...]}`,包装成 canonical envelope。4. 如果 payload 是 `{"pdf_info": [...]}`,迁移为 `pages`。5. 将旧 `_backend` 放入 `_meta.backend`。@@ -521,7 +529,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M2-001 抽出 JSON 批次路径 helper-状态: `ready`+状态: `done`目标:@@ -568,7 +576,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M2-002 修正 cache coverage 对 data_dir 的依赖-状态: `verify-first`+状态: `done`目标:@@ -713,7 +721,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M2-005 实现 read-time render from JSON batches-状态: `ready`+状态: `verify-first`目标:@@ -732,7 +740,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS建议修改范围:- `mineru/doclib/services/parse_svc.py`-- `mineru/doclib/routes/parse.py`+- `mineru/doclib/server.py`- `mineru/doclib/client.py`- `tests/...`@@ -813,7 +821,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M3-001 默认 tier 在入队前解析为实际 tier-状态: `ready`+状态: `verify-first`目标:@@ -1007,7 +1015,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M4-001 `mineru parse` 使用 doclib read-time render-状态: `ready`+状态: `verify-first`目标:@@ -1055,7 +1063,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS### M4-002 Tool SDK `parse()` 增加 tier 参数-状态: `ready`+状态: `verify-first`目标:@@ -1204,56 +1212,59 @@ API-backed parser、Doclib SDK、本地 parser 的错误都能被统一捕获,## 9. M5: Agent-native 输出-### M5-001 定义 locator 和 chunk id helper+### M5-001a 锁定 doclib locator helper-状态: `ready`+状态: `verify-first`目标:-为 Agent citation 提供稳定定位基础。+锁定当前 doclib locator / cursor helper 行为,确保 public locator 使用 1-based 页号和块号,且不包含本地路径。依赖:-- M1-003。-- M1-005。+- ADR-0011。+- ADR-0012。参考文档:- [Agent Gaps](middle-json/agent-gaps.md)+- [ADR-0011: Doc Short ID](decisions/0011-doclib-doc-short-id.md)+- [ADR-0012: Doclib Block Locator](decisions/0012-doclib-block-locator.md)建议修改范围:-- `mineru/schema/` 或 `mineru/types.py`+- `mineru/doclib/locators.py`- `tests/...`具体步骤:-1. 定义 `locator_for_block(page, block) -> str`。-2. 定义 `locator_for_span(page, block, span) -> str`。-3. 定义 `chunk_id(meta, locator) -> str`。-4. chunk id 输入包含 schema major、sha256、tier、page_idx、locator。-5. 不把文件路径或文件名放入 chunk id。-6. unknown bbox 输出 `bbox_known=false`。+1. 确认 `locator_for_block(page_no, block_no)` 使用 1-based public number。+2. 确认 `page_ref()`、`block_ref()`、`block_char_ref()` 使用 `short_id`、实体 tier、1-based page/block 和 0-based char offset。+3. 确认 `parse_content_cursor()` 能解析 page / block / char 三种 cursor。+4. 补充或保留测试,避免 0-based page/block 泄漏到 public cursor。+5. 确认 marker / continuation 不包含本地绝对路径。完成边界:-- 同一 fixture 多次生成 locator 稳定。-- 不同 tier 的同一 locator 生成不同 chunk id。-- chunk id 不包含明文路径。+- locator helper 行为由测试锁定。+- page/block public number 均为 1-based。+- char offset 为 block 渲染文本内 0-based offset。+- cursor 中不包含 path 或 filename。验证方式:```bash-.venv/bin/python -m pytest tests -q -k "locator or chunk_id"+.venv/bin/python -m pytest tests -q -k "locator"```禁止范围:-- 不实现完整 chunking 算法。+- 不实现独立 hash 型引用 ID。+- 不实现 span/cell/list-item locator。### M5-002 Markdown locator marker-状态: `blocked`+状态: `ready`目标:@@ -1261,7 +1272,7 @@ Markdown 输出可选择携带 Agent locator marker。依赖:-- M5-001。+- M5-001a。参考文档:@@ -1278,7 +1289,7 @@ Markdown 输出可选择携带 Agent locator marker。1. 找到 `add_markers` 参数当前行为。2. 为 block 输出前增加可选 marker。-3. marker 包含 locator 和 chunk id。+3. marker 包含稳定 page/block locator。4. 默认不输出 marker。5. CLI/SDK 需要显式 opt-in。@@ -1344,37 +1355,151 @@ Markdown 输出可选择携带 Agent locator marker。- 不实现搜索排序重构。-## 10. 可并行性+## 10. M6: Telemetry++### M6-001 实现 telemetry DB 状态、聚合与 flush++状态: `ready`++目标:++实现 doclib server 侧 telemetry 状态管理、本地聚合存储和周期 flush。纯工具层不得具备 telemetry 能力。++依赖:++- doclib DB migration。+- [Telemetry 设计](telemetry.md)。++参考文档:++- [Telemetry 设计](telemetry.md)+- [配置体系: Telemetry](config.md#telemetry)++建议修改范围:++- `mineru/doclib/migrations/001_init.sql`+- `mineru/doclib/services/`+- `mineru/doclib/background/`+- `mineru/doclib/app.py`+- `tests/...`++具体步骤:++1. 增加 telemetry 状态表或配置记录,保存 `consent_state`、内部 `installation_id`、flush lock 和 last flush 状态。+2. 增加 telemetry 聚合表,按 period、metric name、dimensions hash upsert 累加。+3. 实现 metric / dimension 白名单,不允许透传请求体、异常对象、配置对象或任意 dict。+4. 实现 doclib API / CLI source / caller 的 best-effort 透传入口。+5. 实现 flush 任务,成功后删除已确认上报的聚合记录。+6. flush 失败不得影响 parse、watch、search 或任意 doclib API。+7. 用户关闭 telemetry 时停止写入新 metric,并清除未上报聚合数据。++完成边界:++- `consent_state=disabled` 时不写入新 telemetry 聚合。+- `consent_state=enabled` 时 metrics 按小时级 period 聚合。+- flush 成功后本地聚合记录被清理。+- flush 失败保留记录等待下次重试。+- telemetry 不记录路径、文件名、query、snippet、文档内容、traceback 或 API Key。++验证方式:++```bash+.venv/bin/python -m pytest tests -q -k "telemetry"+```++禁止范围:++- 不在 parser SDK、`mineru-kit parse` 或 `mineru-kit api-server` 中加入 telemetry 能力。+- 不实现每事件实时上报。+- 不阻塞主业务链路等待 telemetry。++### M6-002 实现 `mineru telemetry` CLI++状态: `ready`++目标:++提供用户可见的 telemetry 状态查看和开关命令。++依赖:++- M6-001。++参考文档:++- [Telemetry 设计](telemetry.md)+- [CLI 总览](cli.md)++建议修改范围:++- `mineru/cli_next/main.py`+- `mineru/cli_next/commands/`+- `mineru/doclib/base.py`+- `mineru/doclib/client.py`+- `mineru/doclib/server.py`+- `mineru/doclib/types.py`+- `tests/...`++具体步骤:++1. 增加 `mineru telemetry status`。+2. 增加 `mineru telemetry enable`。+3. 增加 `mineru telemetry disable`。+4. 增加 `mineru telemetry preview`,只展示将上报的聚合摘要,不展示敏感字段。+5. 增加 `mineru telemetry flush`,触发一次手动 flush。+6. 首次启动选择流程如暂不实现 UI,应至少让 `consent_state=unset` 可观测,并在 CLI/server status 中提示。++完成边界:++- 用户可以查看当前 consent 状态。+- 用户可以开启和关闭 telemetry。+- 关闭时清理未上报聚合数据。+- preview 不包含路径、文件名、query、snippet、文档内容、traceback 或 API Key。+- 命令失败时返回稳定错误 code。++验证方式:++```bash+.venv/bin/python -m pytest tests -q -k "telemetry or cli"+```++禁止范围:++- 不要求实现图形化首次启动选择。+- 不向 parser/tool 层传递 telemetry 配置。++## 11. 可并行性| 可并行组 | 任务 ||----------|------|| Fixtures / validator | M0-003、M1-003、M1-005 |-| doclib JSON behavior | M0-002、M2-001、M2-002 |+| doclib JSON behavior | M0-002、M2-003、M2-004 || privacy / tier tests | M3-001、M3-002、M3-004 || CLI / SDK | M4-001、M4-002,需避免同文件冲突 |-| Agent locator | M5-001 可在 M1 validator 稳定后开始 |+| Agent locator | M5-001a 可独立锁定;M5-002 依赖 locator helper |+| Telemetry | M6-001 可独立推进;M6-002 依赖 M6-001 |不建议并行:-- M2-001 与 M2-002 同时改 batch path。- M3-001 与 M3-004 同时改 `_resolve_tier()`。- M1-001 与 M2-005 同时改 `ParseResult.from_dict()` 调用边界。-## 11. PR 切分建议+## 12. PR 切分建议| PR | 包含任务 | 目标 ||----|----------|------|-| PR-1 | M0-001, M0-002, M0-003 | 测试骨架和 fixture。 |+| PR-1 | M0-003 | Middle JSON fixture。 || PR-2 | M1-001, M1-002, M1-003 | Middle JSON normalize / round-trip / validate。 |-| PR-3 | M2-001, M2-002, M2-003, M2-004 | doclib JSON 批次、cache coverage、compaction。 |+| PR-3 | M2-003, M2-004 | doclib page coverage 和 compaction 边界锁定。 || PR-4 | M2-005, M2-006 | read-time render 和 FTS。 || PR-5 | M3-001, M3-002, M3-003, M3-004 | tier / privacy / parse-server 路由。 || PR-6 | M4-001, M4-002, M4-003 | CLI / SDK / 错误模型。 |-| PR-7 | M5-001, M5-002, M5-003 | Agent-native locator / marker / search tier。 |+| PR-7 | M5-001a, M5-002, M5-003 | Agent-native locator / marker / search tier。 |+| PR-8 | M6-001, M6-002 | Telemetry DB、flush 和 CLI。 |每个 PR 都应能独立通过测试,并保留向后兼容。-## 12. 完成定义+## 13. 完成定义P0 完成需要满足:@@ -1387,17 +1512,17 @@ P0 完成需要满足:7. `ParseResult.from_json()` 可恢复 JSON 批次。8. Middle JSON validator 覆盖 P0 必填字段。9. 错误 code 对 CLI/SDK/API 可见。-10. workflows 中 13.1 到 13.7 的端到端验收可以通过测试或手工脚本验证。+10. Telemetry consent、聚合、flush 和 CLI 管理入口可验证。+11. Agent-native 输出具备稳定 page/block locator、`next_request`、`truncated` 和 CLI next marker。+12. workflows 中 13.1 到 13.7 的端到端验收可以通过测试或手工脚本验证。P1 完成需要满足:-1. 搜索结果返回来源 tier。-2. Agent 主动读取默认升级到 `standard` / `pro`。-3. locator 和 chunk id 可生成。-4. Markdown 可选输出 locator marker。-5. 高质量解析完成后刷新搜索索引。+1. Agent 主动读取默认升级到 `standard` / `pro`。+2. Markdown 可选输出 locator marker。+3. 高质量解析完成后刷新搜索索引。-## 13. Agent 领取任务时的最终检查+## 14. Agent 领取任务时的最终检查每个任务完成前,Agent 必须回答:diff --git a/docs/next/middle-json.md b/docs/next/middle-json.mdindex 31af5b44..9a79c454 100644--- a/docs/next/middle-json.md+++ b/docs/next/middle-json.md@@ -15,7 +15,7 @@ Middle JSON 已经有一个事实标准: `mineru/types.py` 中的 `PageInfo`、`1. [总览](middle-json/README.md): 当前事实、目标和工作分层。2. [当前事实标准](middle-json/current-standard.md): `PageInfo` / `Block` / `Line` / `Span` 的现状。3. [Backend 差异](middle-json/backend-gaps.md): Pipeline / VLM / Hybrid / Office / HTML 的已解决和未解决问题。-4. [Agent-native Gap](middle-json/agent-gaps.md): chunk id、引用、定位、稳定性和隐私边界。+4. [Agent-native Gap](middle-json/agent-gaps.md): 引用、定位、稳定性和隐私边界。5. [Canonical Envelope](middle-json/envelope.md): 顶层结构、`_meta`、版本和兼容输入。6. [当前 Content List v2 结构盘点](middle-json/structured-content-current.md): 当前 Structured Content 起点的事实结构。7. [Structured Content Schema](middle-json/structured-content-schema.md): NEXT 版结构化内容 JSON 的目标 schema 草案。@@ -26,7 +26,7 @@ Middle JSON 已经有一个事实标准: `mineru/types.py` 中的 `PageInfo`、`- 以当前代码中的 typed dataclass 为起点。- 区分“已经解决”、“部分解决”、“仍需工作”。-- Agent 引用与 chunk id 是 P0 目标。+- Agent 引用与稳定 page/block locator 是 P0 目标。- schema 版本和迁移函数必须能处理历史数据。- render 统一不能只看入口 facade,还要收敛 backend-specific 分支。diff --git a/docs/next/middle-json/README.md b/docs/next/middle-json/README.mdindex 4da18095..356b8c58 100644--- a/docs/next/middle-json/README.md+++ b/docs/next/middle-json/README.md@@ -34,7 +34,7 @@ Line| 顶层 envelope | 旧 CLI 使用 `pdf_info + _backend`;SDK 使用 `ParseResult.pages` / `pages`;底稿希望有 `_meta`。 || backend 细节 | Pipeline/VLM/Hybrid/Office/HTML 对 bbox、index、page_size、preproc_blocks 的质量不同。 || render 消费 | 已有统一 render facade,但内部仍按 backend dispatch。 |-| Agent 能力 | chunk id、引用定位、稳定 span/block 地址和隐私边界还没有落地。 |+| Agent 能力 | 引用定位、稳定 page/block 地址和隐私边界还没有落地。 |## 下一版目标@@ -43,7 +43,7 @@ Middle JSON 下一版要达到以下目标:1. 统一顶层 envelope,兼容历史 `pdf_info` 和当前 `pages`。2. 明确 `PageInfo` / `Block` / `Line` / `Span` 字段契约。3. 为每个 backend 提供 normalization 任务清单。-4. 定义 Agent 可引用的稳定 locator 和 chunk id 规则。+4. 定义 Agent 可引用的稳定 locator 规则。5. 明确 render 层依赖哪些字段,逐步移除对 `_backend` 的长期依赖。6. 提供 migration / validation 的验收标准。@@ -53,7 +53,7 @@ Middle JSON 下一版要达到以下目标:|----|----------|------|| Schema | 稳定 dataclass 字段和 envelope。 | `current-standard.md`、`envelope.md` || Normalization | 补齐 backend 差异。 | `backend-gaps.md` |-| Agent-native | 引用、chunk id、locator。 | `agent-gaps.md` |+| Agent-native | 引用、locator。 | `agent-gaps.md` || Structured Content | 盘点当前 content_list_v2,作为新 schema 起点。 | `structured-content-current.md` || Structured Content Schema | 定义 NEXT 版目标 schema 草案。 | `structured-content-schema.md` || Rendering | 统一 Markdown / Content List / Structured Content 消费。 | `rendering.md` |@@ -63,7 +63,7 @@ Middle JSON 下一版要达到以下目标:下面这些是 P0,因为它们直接阻塞 Agent 场景:-- 稳定 chunk id。+- 稳定 page/block locator。- 可从 Agent answer 追溯到 page / block / bbox / source hash。- 历史 middle json 可迁移到当前 envelope。- `ParseResult.from_dict()` 可以恢复 API / 缓存结果。diff --git a/docs/next/middle-json/agent-gaps.md b/docs/next/middle-json/agent-gaps.mdindex a3b94e06..8f76477b 100644--- a/docs/next/middle-json/agent-gaps.md+++ b/docs/next/middle-json/agent-gaps.md@@ -2,7 +2,7 @@状态: Draft读者: Agent 能力开发者、SDK 开发者、backend 开发者-范围: Agent 使用 Middle JSON 时需要的稳定引用、chunk id、定位和隐私能力+范围: Agent 使用 Middle JSON 时需要的稳定引用、定位和隐私能力底稿: `../../../NEXT-JSON.md`## 目标@@ -19,8 +19,7 @@ Agent 读取文档时,不只是需要 markdown 文本,还需要可以回溯| 能力 | 当前状态 | 影响 ||------|----------|------|| block ref | 已决策,未实现 | Agent 还不能用稳定可读 ID 引用解析块。 |-| chunk id | 暂缓 | hash 型 chunk id 可作为后续补充,不作为 P0 主引用。 |-| locator | 已决策,未实现 | 已有统一 page/block 地址格式,但代码尚未落地。 |+| locator | 已决策,未实现 | 已有统一 page/block 地址格式,是 P0 主引用模型。 || source hash | doclib 有 sha256,但 Middle JSON envelope 未携带 | 跨文件引用不稳定。 || bbox known flag | 未定义 | Office/HTML 的 `EMPTY_BBOX` 会被误解为真实坐标。 || schema version | 未实现 | 历史缓存无法安全迁移。 |@@ -83,32 +82,6 @@ page:{page_no}/block:{block_no}- locator 不依赖 render profile;输出格式隐藏 block 时不能重编号。- P0 不定义 span、cell 或 list-item locator。-## Chunk ID--hash 型 chunk id 暂不作为 P0 主引用。P0 以 `block_ref` 作为 Agent citation 的主 ID。--后续如果需要不可枚举 ID、跨 schema major version 隔离或更短 token,可增加函数:--```text-chunk_id = hash(schema_major, file_sha256, tier, block_ref)-```--输入:--| 输入 | 说明 |-|------|------|-| `schema_major` | schema 主版本,如 `1`。 |-| `file_sha256` | 原文件 SHA-256。 |-| `tier` | 产生该结果的 tier。 |-| `block_ref` | P0 主 block reference。 |--原因:--- `file_sha256` 保证同名不同文件不冲突。-- `block_ref` 已包含 short id、tier、页号和块号,便于回查。-- `schema_major` 允许重大 schema 变化后重新生成。-- 不包含 filename,减少隐私泄漏。-## Citation RecordAgent 对外返回引用时,建议使用 citation record,而不是直接暴露内部 block:@@ -153,9 +126,9 @@ Agent 对外返回引用时,建议使用 citation record,而不是直接暴## Block 粒度-Agent chunk 默认以 block 为最小稳定单元:+Agent citation 默认以 block 为最小稳定单元:-| Block type | Agent 默认 chunk |+| Block type | Agent 默认 citation unit ||------------|------------------|| `text` | 单 block。 || `title` | 单 block,并可作为后续 section context。 |@@ -208,8 +181,7 @@ P1:1. 为 unknown bbox 输出 `bbox_known=false`。2. 为 render markdown marker 增加可选 locator marker。-3. 按需增加 hash 型 `chunk_id`。-4. 如未来需要 child/list item locator,另行定义公开契约。+3. 如未来需要 child/list item locator,另行定义公开契约。验收:diff --git a/docs/next/middle-json/backend-gaps.md b/docs/next/middle-json/backend-gaps.mdindex 4413b8dd..5116c528 100644--- a/docs/next/middle-json/backend-gaps.md+++ b/docs/next/middle-json/backend-gaps.md@@ -25,7 +25,7 @@| `preproc_blocks` | 部分解决 | PDF backend 有,Office/HTML 主要直接产出 `para_blocks`。 | 明确 public schema 是否保留。 || render 统一 | 部分解决 | 有统一 facade,内部仍按 backend dispatch。 | 收敛 backend-specific content list。 || `_backend` | 部分解决 | render 依赖临时字段。 | 迁移到 envelope `_meta.backend`。 |-| chunk id | 未解决 | Agent 无稳定引用。 | 定义函数并实现。 |+| locator | 部分解决 | Agent 需要稳定 page/block 引用。 | 锁定 locator helper 并补齐输出契约。 |## Pipeline@@ -75,7 +75,7 @@仍需工作:1. 明确 VLM block 粒度与 Pipeline OCR 粒度的兼容语义。-2. 统一 VLM-specific type 在 content_list / Agent chunk 中的表达。+2. 统一 VLM-specific type 在 content_list / Agent citation 中的表达。3. 确认归一化坐标绝不进入 public Middle JSON。4. 将 VLM content_list_v2 特殊逻辑逐步归并。@@ -109,7 +109,7 @@验收:- Hybrid 输出带可追踪的 `_meta.features`。-- Hybrid 中每个 Agent chunk 可追溯到原 page 和 bbox。+- Hybrid 中每个 Agent citation 可追溯到原 page 和 bbox。## Office@@ -170,7 +170,7 @@ P0:1. 定义 canonical envelope。2. 实现 validator。3. 实现 migration: `pdf_info/_backend` -> envelope。-4. 实现 chunk id / locator。+4. 实现并锁定 locator。5. 修正 `ParseResult.from_dict()` / `from_json()`。P1:diff --git a/docs/next/middle-json/current-standard.md b/docs/next/middle-json/current-standard.mdindex 3b0b32c0..34d0ca45 100644--- a/docs/next/middle-json/current-standard.md+++ b/docs/next/middle-json/current-standard.md@@ -142,7 +142,7 @@ Office 解析已经使用 `_url`、`_style`、`_children` 表达超链接和文- 顶层 `_meta`。- `schema_version`。- `file.sha256`。-- 统一 chunk id / locator。+- 统一 locator。- `ParseResult.from_dict()` / `from_json()` 的完整恢复逻辑。- 对 `EMPTY_BBOX` 和真实 bbox 的正式语义区分。- 对内部字段公开策略的决策。diff --git a/docs/next/middle-json/envelope.md b/docs/next/middle-json/envelope.mdindex 681ce4c7..d5aadc32 100644--- a/docs/next/middle-json/envelope.md+++ b/docs/next/middle-json/envelope.md@@ -7,7 +7,16 @@## 目标结构-下一版 canonical envelope:+当前 P0 写出的 `pages` 结构先包含顶层 `schema_version` 和 `pages`,暂不写 `_meta`:++```json+{+ "schema_version": "1.0",+ "pages": []+}+```++后续 canonical envelope 目标结构:```json{@@ -37,14 +46,16 @@- 兼容读取旧结构 `pdf_info`。- `_meta.backend` 取代长期依赖 `PageInfo._backend`。- `schema_version` 放在顶层,便于快速判断 migration。+- 代码常量定义为 `mineru.schema.middle_json.MIDDLE_JSON_SCHEMA_VERSION`,由 normalize、validate、writer 和 exporter 统一引用。+- 当前 P0 写出路径只增加 `schema_version`,不新增 `_meta`;`_meta` 由后续 canonical envelope migration / writer 引入。## 字段| 字段 | 类型 | 必带 | 说明 ||------|------|:--:|------|-| `schema_version` | string | 是 | 当前 `"1.0"`。 |+| `schema_version` | string | 是 | 当前 `"1.0"`;代码常量为 `MIDDLE_JSON_SCHEMA_VERSION`。 || `pages` | list[PageInfo] | 是 | typed pages 的 JSON 表达。 |-| `_meta` | object | 是 | 元数据。 |+| `_meta` | object | 后续 | 元数据;当前 P0 写出路径暂不增加。 |## `_meta`@@ -56,17 +67,17 @@| `file` | object | 是 | 文件级信息。 || `features` | object | 是 | 本次解析启用的能力。 || `models` | object | 是 | 实际模型信息。 |-| `parsed_at` | string 或 null | 否 | 解析时间。默认不参与 chunk id。 |+| `parsed_at` | string 或 null | 否 | 解析时间。默认不参与 locator。 |## `_meta.file`| 字段 | 类型 | 必带 | 说明 ||------|------|:--:|------|-| `sha256` | string | 是 | 原文件 SHA-256。Agent chunk id 必需。 |+| `sha256` | string | 是 | 原文件 SHA-256。Agent locator 严格校验时需要。 || `page_count` | integer | 是 | `len(pages)`。 || `filename` | string 或 null | 否 | 原文件名。存在隐私争议,默认可为 null。 |-如果缺少 `sha256`,不能生成稳定 chunk id。migration 可以允许临时为空,但 Agent locator 功能必须报错。+如果缺少 `sha256`,可以生成局部 locator,但不能生成可严格校验的跨文档 block reference。migration 可以允许临时为空,但 Agent citation 功能必须明确降级或报错。## `_meta.features`@@ -164,7 +175,7 @@ def normalize_middle_json(2. 如果 payload 有 `pages`,读取 pages。3. 如果 payload 有 `pdf_info`,读取 `pdf_info`。4. 如果 payload 有 `_backend`,作为 backend fallback。-5. 如果没有 sha256,则保留 null,但禁用 chunk id。+5. 如果没有 sha256,则保留 null,但禁用需要严格校验 source identity 的 citation 能力。6. 输出必须是 canonical envelope。## Validator@@ -204,4 +215,4 @@ P1 校验:## 未决问题-`schema_version` 位置、`filename` 是否默认写入、`parsed_at` 是否默认写入,集中维护在 [开放问题清单](../open-questions.md)。+`filename` 是否默认写入、`parsed_at` 是否默认写入,集中维护在 [开放问题清单](../open-questions.md)。diff --git a/docs/next/middle-json/migration.md b/docs/next/middle-json/migration.mdindex 850bde73..4e1077b4 100644--- a/docs/next/middle-json/migration.md+++ b/docs/next/middle-json/migration.md@@ -61,23 +61,21 @@- validator 能区分 error / warning。- 当前已知 Office unknown bbox 以 warning 处理,不阻塞。-## Phase 3: Agent Locator 与 Chunk ID+## Phase 3: Agent Locator任务:1. 定义 locator。-2. 定义 chunk id 函数。-3. 实现 block locator。-4. 实现 span locator。-5. 实现 citation record helper。-6. doclib 存储 schema version 和 source sha256。+2. 实现 block locator。+3. 实现 citation record helper。+4. doclib 存储 schema version 和 source sha256。验收:-- 同一文件重复解析 chunk id 稳定。-- 不同 tier 的 chunk id 可区分。+- 同一文件重复解析 locator 稳定。+- 不同 tier 的 block reference 可区分。- unknown bbox 输出 `bbox_known=false`。-- Agent 可以从 chunk id 回查 page/block。+- Agent 可以从 block reference 回查 page/block。## Phase 4: Backend Normalization@@ -122,7 +120,7 @@验收:- 老 `*_middle.json` 能被新版 SDK 读取。-- 无 sha256 的数据不能生成 chunk id,但仍可 render。+- 无 sha256 的数据不能生成可严格校验的跨文档引用,但仍可 render。- 迁移不会改变用户可见 markdown 输出。## 风险@@ -131,7 +129,7 @@|------|------|| 强行要求 Office bbox 导致大量无效框 | 使用 `bbox_known=false`,先承认 unknown。 || 改 envelope 破坏旧 CLI | `normalize_middle_json()` 兼容旧 `pdf_info`。 |-| chunk id 因 index 不稳定而漂移 | 先做 normalization,再生成 locator。 |+| locator 因 index 不稳定而漂移 | 先做 normalization,再生成 locator。 || render 收敛过大 | 分阶段,先 facade,后 type-specific helper。 || filename 泄露隐私 | `_meta.file.filename` 默认可为空。 |@@ -142,7 +140,7 @@3. 增加 validator P0。4. 修正 `HtmlParser` 必填字段。5. 定义 `bbox_known()` helper。-6. 定义 `locator_for_block()` 和 `chunk_id()`。+6. 定义 `locator_for_block()`。7. 给 Pipeline/VLM/Office 各加一个 fixture。完成这 7 项后,Middle JSON 就可以支撑 API/SDK 的 `middle_json` output、doclib 缓存恢复和 Agent citation 的第一版闭环。diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex 22a06f0e..0fd64a16 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -124,7 +124,7 @@ P2:为了 Agent 引用,Markdown 可以支持可选 locator marker:```markdown-<!-- mineru:locator page:3/block:12 chunk:ck_... -->+<!-- mineru:locator doc:ab12cd3/tier:standard/page:3/block:12 -->正文内容```diff --git a/docs/next/middle-json/structured-content-current.md b/docs/next/middle-json/structured-content-current.mdindex 8fad7c67..02c35362 100644--- a/docs/next/middle-json/structured-content-current.md+++ b/docs/next/middle-json/structured-content-current.md@@ -78,7 +78,7 @@ list[list[dict]]- 没有显式 `pages` 字段。- 每页没有 `page_idx` / `page_size` / `page_number`。- item 默认没有 `page_idx`;页号只能从外层数组位置推断。-- 没有 `chunk_id` / `locator`。+- 没有稳定 `locator`。## 4. Item 通用形态@@ -556,7 +556,7 @@ Pipeline/Office 输出:1. 顶层是裸二维数组,缺少 version、metadata 和显式 page 对象。2. 页号依赖外层数组下标,缺少稳定 `page_idx`。-3. item 缺少稳定 `id` / `chunk_id` / `locator`。+3. item 缺少稳定 `id` / `locator`。4. Office span 泄漏内部字段,且和 PDF span 结构不一致。5. `bbox=[0,0,0,0]` 可能表示 unknown,而不是真实区域。6. 同一语义在不同 backend 下字段不一致,例如 table/image/chart footnote、code footnote、list attribute。@@ -577,7 +577,7 @@ Pipeline/Office 输出:- 顶层 envelope。- page object。-- item id / locator / chunk id。+- item id / locator。- span schema。- unknown bbox。- media source。diff --git a/docs/next/middle-json/structured-content-schema.md b/docs/next/middle-json/structured-content-schema.mdindex 29aa4590..c63b1ab9 100644--- a/docs/next/middle-json/structured-content-schema.md+++ b/docs/next/middle-json/structured-content-schema.md@@ -159,7 +159,7 @@ p{page_idx}_i{item_idx}- `id` 在同一 Structured Content 文档内唯一。- `id` 不承诺跨不同解析版本稳定。-- 需要跨解析稳定引用时,使用后续 `chunk_id` 或 locator 规则。+- 需要跨解析稳定引用时,使用 page/block locator 规则。### 4.2 `locator`@@ -186,7 +186,7 @@ p{page_idx}_i{item_idx}- `locator` 不包含本地文件路径。- `block_index` 只有在可从 Middle JSON 稳定映射时才写入。-- 后续可以增加 `chunk_id`,但第一版不强制。+- 第一版不增加额外引用 ID,统一使用 locator。### 4.3 `bbox`@@ -603,7 +603,7 @@ P0 validator 应检查:这版 schema 仍需讨论:-1. `chunk_id` 是否第一版必填。+1. locator 是否第一版必填。2. `id` 是否需要跨同一文件、同一 tier、同一版本解析稳定。3. `source.filename` 是否默认写入。4. `parse.backend` 是否进入公开 Structured Content,还是只放在 API response metadata。diff --git a/docs/next/open-questions.md b/docs/next/open-questions.mdindex 6b31231f..758f3989 100644--- a/docs/next/open-questions.md+++ b/docs/next/open-questions.md@@ -49,10 +49,24 @@| `mineru-kit` Agent 暴露 | `mineru-kit` 长期对 Agent skill 隐藏,只作为专家入口;Agent 默认使用 `mineru`。 || `mineru-kit` 参数稳定性 | 暂不划分 `stable` / `experimental` 等稳定性等级,先保持简单。 || parsing-rules 默认 tier | parsing-rules 允许不指定 tier;执行时必须解析为实体 tier,并只记录实际 tier;默认选择不能解析为 `flash`。 |-| Telemetry P0 | P0 必须设计 telemetry;是否作为公开 `docs/telemetry.md` 不强制。 |+| Telemetry P0 | P0 必须实现 doclib server telemetry 状态、聚合、flush 和 CLI 管理入口;纯工具无 telemetry 能力。 || `mineru parse` 默认页码范围 | 分页文档默认读取 `1~10`。 |-| 非分页文档增量读取 | `mineru parse` 正式支持 `--offset`,用于非分页长文档继续读取。 |+| 渐进式阅读协议 | Server 返回结构化 `next_request`;CLI marker 只由 `next_request` 渲染,不作为协议源头,详见 [ADR-0013](decisions/0013-doc-content-progressive-reading.md)。 |+| 非分页文档增量读取 | 非分页长文档通过 `after` cursor 继续读取;当前不为 `mineru parse` 暴露单独的 `--offset` 参数。 |+| Doc short id | `docs.short_id` 按 SHA256 7 位前缀起步、冲突递增长度、写入后保持稳定,详见 [ADR-0011](decisions/0011-doclib-doc-short-id.md)。 |+| Block locator | Agent-native 整体是 P0。P0 public locator 使用 1-based `page_no` / `block_no`,形态为 `doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}`,详见 [ADR-0012](decisions/0012-doclib-block-locator.md)。 |+| `mineru read` | 新增 locator-first 顶级读取命令;`parse` 和 `read` 共享 `ReadPlan` 与 `execute_read_plan()`,`read --format image` 进入 P0,详见 [ADR-0014](decisions/0014-mineru-read-command.md)。 || `search/find/show file` JSON 输出 | `search` 输出文件名、文件大小、页数和 snippet;`find` 输出文件名、文件大小、页数;`show file` 输出文件大小、页数、文档 metadata 摘要、各 tier 已解析页和 active parse 摘要。 |+| Tool SDK `server_url` | Tool SDK 的 PDF VLM / hybrid parser 可以保留 `server_url` 作为 parser-layer 高级 backend 参数;API-backed parser 使用 `api_url`。 |+| `MinerUApiParser` 位置 | API-backed parser 保持现状,公开入口继续使用 `from mineru.parser import MinerUApiParser`;不重命名,不移动到 `mineru.parser.remote`。 |+| `ParseResult` backend 字段 | `ParseResult` 不再持有 `_backend` / `_version_name`;backend 仅允许作为 page / middle-json 内部来源信息存在。 |+| 其他语言 SDK | 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力。 |+| `mineru server status` | `mineru server status` 使用 doclib `ServerStatusResponse`,不与 parse-server `/v1/health` 强行对齐;后续只需决定该 JSON schema 的稳定发布边界。 |+| `mineru-kit` 对外暴露 | `mineru-kit` 保留为专家工具入口;Agent 默认入口是 `mineru`,skill 不主动暴露 `mineru-kit`。 |+| Office/HTML unknown bbox | 公共 schema 允许 unknown bbox;不要求 Office/HTML 在 P0 估算真实 bbox,validator 应区分 unknown 与非法 bbox。 |+| `standard` 硬件基线 | `standard` 当前使用 pipeline 后端;Apple Silicon macOS 约使用 4GB 统一内存,Windows / Linux 需要 NVIDIA GPU 且至少 4GB 显存。详见 [解析 Tier](tiers.md#5-standard)。 |+| watch tier 升级 | P0 不做基于启发式的自动提示或自动排队升级。watch 默认使用 `flash`;后台自动升级只由用户显式配置的 parsing-rules 触发;用户或 Agent 主动读取时再按默认选择策略解析到 `standard` / `pro`。 |+| Middle JSON `schema_version` | 采用 `pages` 的 Middle JSON 顶层结构必须写 `schema_version`;旧 CLI `pdf_info` 结构暂不改。当前只增加 `schema_version` 和 `pages`,暂不增加 `_meta`;代码常量定义为 `mineru.schema.middle_json.MIDDLE_JSON_SCHEMA_VERSION`。 |## 3. Blocker@@ -65,20 +79,18 @@| ID | 问题 | 建议归属 ||----|------|----------|-| OQ-T-001 | `standard` 在 macOS、Windows、Linux、不同内存/显存下的最低硬件基线如何定义。 | Tier 文档 |-| OQ-T-004 | watch 使用 `flash` 后,是否自动提示或自动排队升级高价值文档到 `standard` / `pro`。 | doclib / UX || OQ-T-005 | `mineru-kit` 是否支持不传 tier 的默认选择,还是只接受实体 tier 和 backend。 | CLI 专家工具 |## 5. CLI 与 Agent 协议| ID | 问题 | 建议归属 ||----|------|----------|-| OQ-C-001 | Agent marker 的最终语法放入 CLI 规格,还是拆成独立 Agent message contract。 | CLI / Agent |+| OQ-C-001 | Markdown block marker 作为 P0 Agent-native 输出的一部分时,是否只允许显式 opt-in,而默认只输出普通 Markdown 与 continuation marker。 | CLI / Agent || OQ-C-002 | `mineru` 与 `mineru-kit` 是否共享同一组选项命名。 | CLI || OQ-C-006 | `mineru-kit parse` 是否默认异步处理批量远端任务。 | CLI 专家工具 || OQ-C-007 | `mineru-kit parse` 的 stdin 传文件内容和传路径列表如何区分。 | CLI 专家工具 || OQ-C-008 | `mineru-kit parse` 多格式输出目录结构是否需要稳定 schema。 | CLI 专家工具 |-| OQ-C-012 | `mineru server status` 的 JSON schema 是否和 API health endpoint 对齐。 | CLI / API |+| OQ-C-012 | `mineru server status` 的 JSON schema 是否作为稳定 doclib SDK/API schema 发布。 | CLI / API || OQ-C-013 | 多用户或多项目场景下 UDS 路径是否需要命名空间。 | server 生命周期 |## 6. SDK@@ -89,13 +101,9 @@| OQ-S-002 | 是否提供顶层 `mineru.client` 作为 `mineru.doclib.client.MineruClient` 的稳定别名。 | SDK || OQ-S-003 | 是否需要 `AsyncMineruClient`。 | Doclib SDK || OQ-S-004 | `MineruClient.parse(format=...)` 是否改为 `output_format` 并与 v1 API 对齐。 | Doclib SDK |-| OQ-S-005 | `MinerUApiParser` 是否重命名或移动到 `mineru.parser.remote`。 | API-backed Parser || OQ-S-006 | 是否公开低层 `V1ApiClient`,让开发者直接操作 uploads/jobs/files。 | API SDK || OQ-S-007 | Product SDK 是否只面向 doclib,还是同时提供 cloud API client。 | SDK 分层 |-| OQ-S-008 | 其他语言 SDK 是否只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力。 | SDK 分层 |-| OQ-S-009 | `server_url` 是否只由 `MinerUApiParser` 负责,还是保留在 PDF parser 构造参数中。 | Tool SDK || OQ-S-010 | `parse_batch()` 是否需要统一进度回调接口。 | Tool SDK |-| OQ-S-011 | `ParseResult.to_dict()` 是否包含 `_backend` / `_version_name`,以及字段名是否去下划线。 | ParseResult || OQ-S-012 | 是否增加 `page_count()`、`text()`、`html()` 等便利方法。 | ParseResult || OQ-S-013 | `ParseResult.save()` 的 writer protocol 是否正式定义为 `Protocol`。 | ParseResult || OQ-S-014 | 是否把 api-server 中的 Pydantic models 提取为共享 schema 模块。 | SDK / API |@@ -105,10 +113,8 @@| ID | 问题 | 建议归属 ||----|------|----------|-| OQ-M-001 | `schema_version` 放在顶层还是 `_meta.schema_version`。当前建议顶层。 | Middle JSON envelope || OQ-M-002 | `filename` 是否默认写入 Middle JSON envelope。 | Middle JSON envelope || OQ-M-003 | `parsed_at` 是否默认写入;写入会降低跨机器 diff 稳定性。 | Middle JSON envelope |-| OQ-M-004 | Office/HTML 缺失 bbox、page_size 时,公共 schema 是允许为空,还是要求补齐估算值。 | Middle JSON schema || OQ-M-005 | backend-specific block type 的公开枚举、兼容策略和降级策略如何定稿。 | Middle JSON schema |## 8. Roadmap 与评测@@ -118,7 +124,6 @@| OQ-R-001 | P0 / P1 / P2 是否绑定粗粒度日期承诺。 | Roadmap || OQ-R-002 | WAI 的一年和两年目标值如何设定。 | Roadmap || OQ-R-003 | 解析质量回归框架采用 OmniDocBench,还是另建内部评测集。 | Roadmap / eval |-| OQ-R-004 | `mineru-kit` 对外暴露程度是否进一步收窄。 | Roadmap / CLI || OQ-R-006 | VLM “第一梯队”如何定义 benchmark 和 gap 阈值。 | Roadmap / eval || OQ-R-007 | 对外公开路线图和内部执行路线图是否拆分。 | Roadmap |diff --git a/docs/next/roadmap.md b/docs/next/roadmap.mdindex 85e8f213..67a0b39b 100644--- a/docs/next/roadmap.md+++ b/docs/next/roadmap.md@@ -42,7 +42,7 @@ Agent 使用场景是下一阶段的设计原点。CLI、SDK、MCP 和输出格- 结构化输出,而不是只能解析 free-text。- 确定性错误码,并提供修复建议。- 支持 token-budgeted 输出和 continuation。-- 支持可寻址 chunk id,便于 citation 和回溯。+- 支持可寻址 page/block locator,便于 citation 和回溯。- 支持按页、区域、类型过滤,减少不必要的解析和上下文占用。### 2.3 易用优先@@ -140,12 +140,12 @@ P0 阶段需要优先交付 Agent 可可靠消费的输出能力:- 统一 message contract。- typed error code 和修复建议。- token-budgeted 输出和 continuation。-- 稳定 chunk id。+- 稳定 page/block locator。- 页面、区域和类型过滤。- Skill 决策树。- SHA256 内容寻址缓存。-这些能力依赖 middle_json 的最小统一子集:稳定 chunk id、page、bbox 和 type。+这些能力依赖 middle_json 的最小统一子集:稳定 page/block locator、page、bbox 和 type。### 5.2 Middle JSON 统一@@ -188,7 +188,7 @@ P0 目标是让 Agent 和开发者可以稳定地把 MinerU 当作文档入口- Agent 真实任务成功率。- middle_json schema validation。-- chunk id 跨进程稳定性。+- page/block locator 跨进程稳定性。- 相同输入二次 parse 缓存命中响应。- watch 能发现文件、rules 能触发解析策略、search 能返回可用结果。- telemetry 字段不泄露文档内容。diff --git a/docs/next/sdk.md b/docs/next/sdk.mdindex f750514f..47e953e8 100644--- a/docs/next/sdk.md+++ b/docs/next/sdk.md@@ -41,3 +41,4 @@ SDK 文档定义代码集成入口。它既要让普通开发者知道如何解- SDK 默认遵守隐私优先,不隐式上传本地文件到远端。- Tool SDK 不依赖 doclib;doclib 可以依赖 Tool SDK。- 对外 API 层应避免 import 时加载重依赖。+- 其他语言 SDK 暂无开发计划;如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力。diff --git a/docs/next/sdk/README.md b/docs/next/sdk/README.mdindex be60de0e..8fd1a474 100644--- a/docs/next/sdk/README.md+++ b/docs/next/sdk/README.md@@ -23,6 +23,8 @@Doclib SDK 与 doclib HTTP/UDS API 使用同一套方法和协议语义。项目内部除 `mineru.doclib.client` 外,不应直接通过 HTTP 调用 doclib API;外部客户端未来可以直接依赖 doclib HTTP API。+其他语言 SDK 暂无开发计划。如果未来开发,只覆盖 v1 Unified API,不覆盖本地 doclib UDS 能力;本地 doclib UDS 能力由 Python Doclib SDK 和 MinerU 自身入口承载。+## 依赖方向```text@@ -73,4 +75,4 @@ mineru doclib## 未决问题-顶层别名、`MinerUApiParser` 位置和其他语言 SDK 覆盖范围,集中维护在 [开放问题清单](../open-questions.md)。+顶层别名集中维护在 [开放问题清单](../open-questions.md)。`MinerUApiParser` 位置已收敛,保持 `from mineru.parser import MinerUApiParser`。diff --git a/docs/next/sdk/api-parser.md b/docs/next/sdk/api-parser.mdindex 3fe3627d..b8a435bd 100644--- a/docs/next/sdk/api-parser.md+++ b/docs/next/sdk/api-parser.md@@ -155,6 +155,12 @@ doclib SDK 或 CLI 在调用它之前必须完成隐私策略判断:- `MinerUApiParser` 是该 HTTP 规格的 Python parser 封装。- `api_server` 是该 HTTP 规格的本地无状态 server 实现。-## 未决问题+## 公开入口-`MinerUApiParser` 命名与位置、低层 `V1ApiClient` 是否公开,集中维护在 [开放问题清单](../open-questions.md)。API-backed parser 的异常应收敛到统一 `MineruError` 体系。+`MinerUApiParser` 保持现有命名和位置,公开入口为:++```python+from mineru.parser import MinerUApiParser+```++不新增 `mineru.parser.remote` 迁移路径。低层 `V1ApiClient` 是否公开仍集中维护在 [开放问题清单](../open-questions.md)。API-backed parser 的异常应收敛到统一 `MineruError` 体系。diff --git a/docs/next/sdk/migration.md b/docs/next/sdk/migration.mdindex 724b961c..25cbba61 100644--- a/docs/next/sdk/migration.md+++ b/docs/next/sdk/migration.md@@ -36,7 +36,8 @@ SDK 迁移的目标不是重写现有 parser,而是稳定已经成形的边界- `from mineru.doclib.client import MineruClient`3. 决定是否增加:- `from mineru.client import MineruClient`- - `from mineru.parser.remote import MinerUApiParser`++不新增 `from mineru.parser.remote import MinerUApiParser`;API-backed parser 保持现有入口。验收:diff --git a/docs/next/tiers.md b/docs/next/tiers.mdindex 8e26f3b2..1373338e 100644--- a/docs/next/tiers.md+++ b/docs/next/tiers.md@@ -38,7 +38,7 @@ MinerU 当前定义三个公开 tier:| 底层原理 | 纯 CPU 实现 | 基于模型 | 基于更强模型 || 质量 | 低 | 中 | 高 || 速度 | 最快 | 中等 | 最慢,取决于硬件和远端服务 |-| 本地硬件要求 | 无 GPU / 加速器也可用 | 消费级电脑可用,如 MacBook 或 Windows 笔记本 | 需要高端 GPU / 加速器,或使用远端 |+| 本地硬件要求 | 无 GPU / 加速器也可用 | 使用 pipeline 后端;Apple Silicon macOS 约 4GB 统一内存,Windows / Linux 需要 NVIDIA GPU 且至少 4GB 显存 | 需要高端 GPU / 加速器,或使用远端 || 是否适合 watch 自动处理 | 是 | 一般不默认使用 | 否 || 是否适合用户主动阅读 | 仅在用户明确选择时 | 是,默认最低阅读质量 | 是,质量优先场景 || 典型场景 | 文件发现、快速预览、搜索索引 | 本地隐私解析、普通文档阅读 | 复杂版面、学术论文、高价值文档 |@@ -68,18 +68,30 @@ MinerU 有 local parse-server,也有 remote parse-server。无论 local 还是`flash` 的核心用途是支撑大量文件的自动发现和低成本预处理。MinerU 的 watch 机制会发现很多文件;在系统刚看到这些文件时,并不知道每个文件的价值,也不适合立即使用高算力方案处理。因此 watch 默认使用 `flash` 快速提取最基础内容,用于建立搜索索引和后续发现。+P0 不做基于启发式的自动提示或自动排队升级。watch 使用 `flash` 后,如果需要在后台自动解析到 `standard` 或 `pro`,必须来自用户显式配置的 parsing-rules;系统不根据文件名、内容特征、搜索命中或“高价值文档”判断自行升级。+`flash` 不应被当成默认阅读质量。当 Agent 或用户决定真正读取某个文档时,需求已经从“发现它”变成“尽可能准确地理解它”,此时未指定 tier 应使用默认选择策略,并至少解析到 `standard`。只有在用户明确指定 `flash` 时,才返回 `flash` 的解析内容作为最终阅读结果。## 5. Standard-`standard` 是本地主力解析 tier,底层使用模型,面向普通消费级电脑用户。+`standard` 是本地主力解析 tier,当前使用 `pipeline` 后端。`pipeline` 是一系列小模型串联的解析方案,不加载大的 VLM 模型。这类用户可能拥有 GPU 或加速器,但显存和算力有限。它们不一定完全跑不动 `pro`,但运行 `pro` 通常会很慢。因此 `standard` 是一个算力消耗较低、质量中等、仍然基于模型的解析方案。`standard` 的核心价值是本地隐私解析:当用户不接受把文档发送到远端解析,同时硬件又不是特别高端时,`standard` 应成为本地可用的最佳默认方案。+`standard` 的最低硬件基线按 `pipeline` 后端定义:++| 平台 | 最低硬件基线 |+|------|--------------|+| macOS | 使用 Apple Silicon / M 系列芯片,约使用 4GB 统一内存。 |+| Windows | 需要 NVIDIA GPU,至少 4GB 显存。 |+| Linux | 需要 NVIDIA GPU,至少 4GB 显存。 |++更完整的本地部署要求以项目 README 中的 pipeline 硬件说明为准。+## 6. Pro`pro` 是 MinerU 当前最高质量 tier,也是 `mineru.net/api` 提供的解析层级。@@ -111,6 +123,7 @@ MinerU 的 tier 策略同时遵守隐私优先和质量优先。| 请求 | 默认执行路径 ||------|--------------|| watch 自动发现文件 | 本地 `flash` |+| watch 命中 parsing-rule | 按 rule 中的 tier、页码范围和 remote 配置执行;必须经过能力检查和隐私检查 || 用户主动 parse,未指定 tier;HTTP API 传 JSON `null`;Python SDK 传 `None` | 解析为当前可发现的最高非 `flash` tier || 用户主动指定 `--tier flash` | 本地 `flash` || 用户主动指定 `--tier standard` | 本地 standard;不可用时报错 |@@ -134,4 +147,4 @@ CLI、API 和 SDK 暴露 tier 时,应遵守同一语义:## 10. 未决问题-与 tier 相关的硬件基线、watch 升级提示和 `mineru-kit` 的 tier/backend 边界,集中维护在 [开放问题清单](open-questions.md)。+与 tier 相关的未决问题集中维护在 [开放问题清单](open-questions.md)。diff --git a/docs/next/workflows.md b/docs/next/workflows.mdindex 43926686..1da5e54c 100644--- a/docs/next/workflows.md+++ b/docs/next/workflows.md@@ -184,9 +184,9 @@ watch 默认输出面向系统内部:### 5.7 约束-- watch 自动产出的 `flash` 结果可以用于搜索、预览和提示升级。+- watch 自动产出的 `flash` 结果可以用于搜索和预览;P0 不基于启发式自动提示或自动排队升级。- watch 自动产出的 `flash` 结果不能在用户主动阅读时被静默当作最终解析内容返回。-- 如果 parsing-rule 指定 `standard` 或 `pro`,必须经过能力检查和隐私检查。+- 后台自动升级只由用户显式配置的 parsing-rules 触发;如果 parsing-rule 指定 `standard` 或 `pro`,必须经过能力检查和隐私检查。- parsing-rule 只有显式允许 remote,才可以上传远端。### 5.8 Cleanup 边界@@ -621,12 +621,12 @@ FTS 更新可以在解析完成后临时从 ParseResult 或 Middle JSON 渲染 M9. 主动阅读不会静默命中 `flash`。10. 错误返回可操作 code 和 suggestion。-### P1: Agent-native 阅读+### P0: Agent-native 阅读1. 搜索结果返回来源 tier。2. Agent 主动读取时提升到 `standard` 或 `pro`。3. 输出支持截断 marker 和下一步 page hint。-4. Middle JSON 支持 locator 和 chunk id。+4. Middle JSON 支持稳定 page/block locator。5. Markdown 输出可携带可选 locator marker。6. 高质量解析完成后刷新搜索索引。diff --git a/docs/plans/2026-06-15-cli-next-command-design.md b/docs/plans/2026-06-15-cli-next-command-design.mdindex 5ddc88e2..976f4bd2 100644--- a/docs/plans/2026-06-15-cli-next-command-design.md+++ b/docs/plans/2026-06-15-cli-next-command-design.md@@ -66,7 +66,7 @@ MVP 还在开发阶段,因此本设计不保留旧命令兼容入口。### 4.1 发起解析```bash-mineru parse <file> [--tier flash|standard|pro] [--pages <range>] [--format markdown|text|json|html] [--force] [--remote] [--wait <sec>] [--no-wait] [-o <path>] [--json] [-v]+mineru parse <file> [--tier flash|standard|pro] [--pages <range>] [--format markdown] [--force] [--remote] [--wait <sec>] [--no-wait] [-o <path>] [--json] [-v]```语义:diff --git a/docs/plans/2026-06-17-cli-json-error-consistency-plan.md b/docs/plans/2026-06-17-cli-json-error-consistency-plan.mdnew file mode 100644index 00000000..c5d144c5--- /dev/null+++ b/docs/plans/2026-06-17-cli-json-error-consistency-plan.md@@ -0,0 +1,148 @@+# CLI JSON 模式报错一致性整改计划++**日期**: 2026-06-17+**状态**: 待实施+**范围**: `mineru/cli_next` 中所有已支持 `--json` 的命令,在业务错误和“服务未运行/无法连接”等场景下统一输出结构化 JSON;同时收口 `mineru server status --json` 在 server 未运行时的输出。+**非目标**:+- 不为当前尚未支持 `--json` 的 mutation 命令补加 `--json`+- 不改变 `parse --json`、`read --json` 的成功响应顶层 shape+- 不处理 Typer / Click 参数解析阶段的框架默认错误输出++## 1. 背景++当前 `cli_next` 中大多数命令已经提供 `--json`,但错误路径并不统一:++- `mineru parse --json` 已会输出结构化 JSON error。+- `read`、`search`、`find`、`watch`、`config`、`show`、`cleanup`、`forget`、`server status` 等命令,在业务错误下仍会输出纯文本错误。+- `mineru server status --json` 在 server 未运行时当前会输出 `"Server is not running."` 文本,而不是稳定 JSON。++这使得 `--json` 不能被稳定地当作机器接口使用。++## 2. 目标++统一规则如下:++1. 已支持 `--json` 的命令,在**进入命令实现之后**发生的业务错误,stdout 必须输出:++```json+{+ "error": {+ "type": "invalid_request_error",+ "code": "some_code",+ "message": "...",+ "param": "..."+ }+}+```++2. `stderr` 不得混入额外的人类解释文本;stdout 不得混入 `Error:`、`Written to`、Rich 样式文本或 traceback。++3. `mineru server status --json` 在 server 未运行时,不走 error JSON,而是返回稳定的状态 JSON,例如:++```json+{+ "running": false+}+```++理由:这不是异常,而是命令查询到的合法状态。++4. Typer / Click 在参数解析阶段产生的错误维持框架默认行为,当前阶段不在本计划内统一。++## 3. 影响命令清单++本计划覆盖当前已支持 `--json` 的命令:++- `mineru parse`+- `mineru read`+- `mineru scan`+- `mineru watch add/list/remove/rescan`+- `mineru search`+- `mineru find`+- `mineru list files/docs/parses/scans`+- `mineru show file/doc/parse/scan`+- `mineru server status`+- `mineru config show/get`+- `mineru config exclude-rules add/list`+- `mineru config parsing-rules add/list`+- `mineru forget`+- `mineru cleanup deleted-files/orphan-docs/temp`++不覆盖当前未支持 `--json` 的命令:++- `mineru invalidate`+- `mineru config set/unset`+- `mineru config exclude-rules remove`+- `mineru config parsing-rules remove`++## 4. 实施策略++### 4.1 抽取统一 helper++在 `mineru/cli_next` 中抽取统一的 JSON 错误输出 helper,职责:++- 接受 `Exception`+- 尝试复用 `parse` 已有的 `MineruError` / `error_response` 映射逻辑+- 在 `json_mode=True` 时输出结构化 JSON error+- 在 `json_mode=False` 时维持现有 `print_error(...)`++该 helper 应避免每个命令重复手写:++```python+except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1)+```++### 4.2 server status 特判++`mineru server status` 在 `json_mode=True` 且 server 未运行时:++- 直接输出稳定状态 JSON+- 不走 `print_info("Server is not running.")`+- 不走 error JSON++`json_mode=False` 时维持当前人类可读提示。++### 4.3 保持成功响应 shape 不变++本计划不调整成功响应结构,只整改错误路径:++- `parse --json` 继续使用 `{parse, content}`+- `read --json` 继续使用 `DocContentResponse`+- `list/search/show/... --json` 继续直接输出其 response model++## 5. 分步任务++1. 新增统一 JSON error helper,并将 `parse` 当前逻辑并入公共实现。+2. 将 `read`、`search/find`、`watch`、`scan`、`show`、`config`、`cleanup`、`forget` 接入该 helper。+3. 单独收口 `server status --json` 在 server 未运行时的稳定 JSON 输出。+4. 为各类命令补测试:+ - 业务错误下 stdout 为可解析 JSON+ - 不包含 `Error:` 文本+ - `server status --json` 在未运行时返回状态 JSON+5. 更新 CLI 文档和 E2E 用例中对 `--json` 错误行为的预期。++## 6. 测试矩阵++至少覆盖以下场景:++- `read --json` 读取不存在 locator+- `search --json` 非法 tier 或后端错误+- `watch add --json` 路径不存在+- `show parse --json` 不存在的 parse id+- `config get --json` 不存在的 key+- `cleanup temp --json` 非法 `older_than`+- `server status --json` 在 server 未运行时++断言重点:++- stdout 可直接 `json.loads(...)`+- 退出码符合预期+- stdout 不混入人类文本前缀++## 7. 风险与注意事项++1. 当前部分异常只是一段普通字符串,需要先尽量映射到稳定错误码;若无法映射,也应统一落到 `api_error` 或等价兜底 code,而不是把纯文本直接塞到 stdout。+2. 不能为了统一错误输出而改变成功输出 shape。+3. 不能把“server 未运行”误归类为错误 JSON;该场景属于状态查询结果。diff --git a/mineru/cli_next/__init__.py b/mineru/cli_next/__init__.pyindex 9d0782f9..f20baeb1 100644--- a/mineru/cli_next/__init__.py+++ b/mineru/cli_next/__init__.py@@ -1,2 +1,6 @@-# New CLI entry points (typer-based).-# Temporary package during migration; will replace mineru/cli/ when complete.+"""New CLI entry points (typer-based).++Temporary package during migration; will replace mineru/cli/ when complete.+"""++__all__: list[str] = []diff --git a/mineru/cli_next/commands/__init__.py b/mineru/cli_next/commands/__init__.pynew file mode 100644index 00000000..e4223616--- /dev/null+++ b/mineru/cli_next/commands/__init__.py@@ -0,0 +1,31 @@+"""CLI command submodules — each exposes either a typer app or callback functions."""++from . import (+ cleanup,+ config,+ forget,+ invalidate,+ list_resources,+ parse,+ read,+ scan,+ search,+ server,+ show,+ watch,+)++__all__ = [+ "cleanup",+ "config",+ "forget",+ "invalidate",+ "list_resources",+ "parse",+ "read",+ "scan",+ "search",+ "server",+ "show",+ "watch",+]diff --git a/mineru/cli_next/commands/cleanup.py b/mineru/cli_next/commands/cleanup.pyindex 446822a6..e01da2e0 100644--- a/mineru/cli_next/commands/cleanup.py+++ b/mineru/cli_next/commands/cleanup.py@@ -6,6 +6,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import CleanupDeletedRequest, CleanupOrphansRequest, CleanupTempRequest+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_json, print_successapp = typer.Typer(@@ -25,8 +26,7 @@ def cleanup_deleted_files(try:data = client.cleanup_deleted_files(CleanupDeletedRequest(dry_run=dry_run))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -49,8 +49,7 @@ def cleanup_orphan_docs(try:data = client.cleanup_orphan_docs(CleanupOrphansRequest(dry_run=dry_run))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -73,8 +72,7 @@ def cleanup_temp_files(try:data = client.cleanup_temp_files(CleanupTempRequest(older_than_days=older_than))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -86,6 +84,5 @@ def cleanup_temp_files(def _client() -> DoclibClient:try:return DoclibClient(timeout=30)- except Exception:- print_error("Cannot connect to mineru server. Run 'mineru server start' first.")- raise typer.Exit(1) from None+ except Exception as exc:+ exit_with_error(exc, json_mode=False, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")diff --git a/mineru/cli_next/commands/config.py b/mineru/cli_next/commands/config.pyindex 97951eaf..54b31707 100644--- a/mineru/cli_next/commands/config.py+++ b/mineru/cli_next/commands/config.py@@ -7,6 +7,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import ConfigResponse, ConfigSetRequest, ExcludeRuleRequest, ParsingRuleRequestfrom ...types import Tier+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_json, print_successapp = typer.Typer(help="Configuration management", no_args_is_help=True)@@ -24,8 +25,7 @@ def config_show(json_mode: bool = typer.Option(False, "--json", help="JSON outputry:data = _client().get_config()except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -42,8 +42,7 @@ def config_get(try:data = _client().get_config_key(key)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -60,8 +59,7 @@ def config_set(try:data = _client().set_config(key, ConfigSetRequest(value=value))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)print_success(f"{data.key} = {data.value} [{data.source}]")@@ -72,8 +70,7 @@ def config_unset(key: str = typer.Argument(..., help="Configuration key")) -> Notry:data = _client().unset_config(key)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)action = "removed" if data.removed else "unchanged"print_success(f"{data.key} = {data.value} [{data.source}] ({action})")@@ -89,8 +86,7 @@ def exclude_rules_add(try:data = _client().add_exclude_rule(ExcludeRuleRequest(pattern=pattern, priority=priority))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)@@ -104,8 +100,7 @@ def exclude_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSOtry:data = _client().list_exclude_rules()except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(data)diff --git a/mineru/cli_next/commands/forget.py b/mineru/cli_next/commands/forget.pyindex 5daf93e9..e6945cf7 100644--- a/mineru/cli_next/commands/forget.py+++ b/mineru/cli_next/commands/forget.py@@ -6,6 +6,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import ForgetPathRequest+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_json, print_success@@ -17,15 +18,13 @@ def forget_cmd() -> None:try:client = DoclibClient(timeout=30)- except Exception:- print_error("Cannot connect to mineru server. Run 'mineru server start' first.")- raise typer.Exit(1) from None+ 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:result = client.forget_path(ForgetPathRequest(path=path, dry_run=dry_run))except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)diff --git a/mineru/cli_next/commands/list_resources.py b/mineru/cli_next/commands/list_resources.pyindex 91e0254c..eff2712e 100644--- a/mineru/cli_next/commands/list_resources.py+++ b/mineru/cli_next/commands/list_resources.py@@ -7,6 +7,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import FileStatus, ParseStatus, ScanKind, ScanStatusfrom ...types import Tier+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_jsonapp = typer.Typer(help="List doclib resources", no_args_is_help=True)@@ -24,8 +25,7 @@ def list_parses(try:result = _client().list_parses(status=status, tier=tier, limit=limit, offset=offset)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)@@ -51,8 +51,7 @@ def list_scans(try:result = _client().list_scans(status=status, kind=kind, watch_id=watch_id, limit=limit, offset=offset)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)@@ -81,8 +80,7 @@ def list_files(try:result = _client().list_files(status=status, ext=ext, watch_id=watch_id, limit=limit, offset=offset)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)@@ -107,8 +105,7 @@ def list_docs(try:result = _client().list_docs(file_type=file_type, limit=limit, offset=offset)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.pyindex 4cd517a0..f3fa6e4d 100644--- a/mineru/cli_next/commands/parse.py+++ b/mineru/cli_next/commands/parse.py@@ -2,15 +2,39 @@from __future__ import annotations+import os+import shutilimport timefrom pathlib import Path+from typing import Any+from typing import Literalimport typer+from ...errors import MineruErrorfrom ...doclib.client import DoclibClient-from ...doclib.types import ContentNextRequest, DocContentExportRequest, ParseRequest+from ...doclib.types import ContentNextRequest, DocContentExportRequest, DocContentResponse, ParseRequest, ParseResponsefrom ...types import Tier-from ..output import format_parse_result, print_error, print_info, print_success+from ..json_errors import exit_with_error+from ..output import format_parse_result, print_error, print_info, print_json, print_success+++def _normalize_output_path(output: str | None) -> str | None:+ if output is None or output == "-":+ return output+ return os.path.abspath(os.path.expanduser(output))+++def _ensure_output_parent(output: str | None) -> str | None:+ normalized = _normalize_output_path(output)+ if normalized in (None, "-"):+ return normalized+ Path(normalized).parent.mkdir(parents=True, exist_ok=True)+ return normalized+++def _output_info(path: str) -> dict[str, str]:+ return {"status": "written", "path": path}def parse_cmd(@@ -19,18 +43,18 @@ def parse_cmd(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: str = typer.Option("markdown", "-f", "--format", help="Output format: markdown, text, json, html"),+ 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 file path (default: STDOUT)"),+ 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."""- file_path = str(Path(path).resolve())+ file_path = str(Path(os.path.expanduser(path)).resolve())if not Path(file_path).exists():print_error(f"File not found: {file_path}")@@ -54,12 +78,9 @@ def parse_cmd())except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)- sha256 = result.sha256req_tier = result.tier- result_page_range = result.page_range or pagesstatus = result.statuswait_parse_ids = result.wait_parse_ids@@ -67,13 +88,11 @@ def parse_cmd(if status == "done":if verbose:print_info("Cache hit — returning cached result.")- _output_content(+ _output_parse_result(client,- sha256,- req_tier,- json_mode,- output,- page_range=result_page_range,+ result,+ json_mode=json_mode,+ output=output,after=after,limit=limit,format=format,@@ -84,7 +103,10 @@ def parse_cmd(# no-waitif no_wait or status not in ("pending", "parsing") or not wait_parse_ids:- format_parse_result(result, json_mode=json_mode)+ if json_mode:+ _print_parse_json_response(result, None)+ else:+ format_parse_result(result, json_mode=False)return# poll until done or timeout@@ -103,38 +125,37 @@ def parse_cmd(wait_id_set = set(wait_parse_ids)parse_rows = [row for row in s.parses if row.id in wait_id_set]- filtered_response = s.model_copy(update={"parses": parse_rows, "total": len(parse_rows)})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 or st in ("done", "failed"):+ if verbose and not json_mode:print_info(f" Parse status: {st}")if st == "done":- if not json_mode:- _output_content(- client,- sha256,- req_tier,- json_mode,- output,- page_range=result_page_range,- after=after,- limit=limit,- format=format,- no_marker=no_marker,- source_path=file_path,- )- else:- format_parse_result(filtered_response, json_mode=json_mode)+ done_result = result.model_copy(update={"status": "done"})+ _output_parse_result(+ client,+ done_result,+ json_mode=json_mode,+ output=output,+ after=after,+ limit=limit,+ format=format,+ no_marker=no_marker,+ source_path=file_path,+ )returnif st == "failed":failed = next((row for row in parse_rows if row.status == "failed"), None)- print_error(f"Parse failed: {failed.error_code if failed else '?'} — {failed.error_msg if failed else ''}")- raise typer.Exit(1)+ exit_with_error(+ MineruError(failed.error_code if failed else "parse_failed", failed.error_msg if failed else "", None),+ json_mode=json_mode,+ )- print_info(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")if json_mode:- print_info('{"status":"parsing","tip":"Re-run the same command to continue waiting."}')+ timeout_result = result.model_copy(update={"status": "parsing", "tip": "Re-run the same command to continue waiting."})+ _print_parse_json_response(timeout_result, None)+ else:+ print_info(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")if __name__ != "__main__":@@ -143,36 +164,42 @@ if __name__ != "__main__":app.command()(parse_cmd)-def _output_content(+def _output_parse_result(client: DoclibClient,- sha256: str,- tier: Tier,+ parse_result: ParseResponse,json_mode: bool,output: str | None = None,- page_range: str | None = None,after: str | None = None,limit: int = 30000,format: str = "markdown",no_marker: bool = False,source_path: str | None = None,) -> None:- """Fetch and output parsed content. If --output is specified, server writes to file."""+ """Fetch and output parsed content for a parse command."""+ sha256 = parse_result.sha256+ tier = parse_result.tier+ page_range = parse_result.page_range+ output_path = _ensure_output_parent(output)try:- if output and output != "-":+ if output_path and output_path != "-":exported = client.export_doc_content(sha256,DocContentExportRequest(tier=tier,page_range=page_range,format=format,- output=output,+ output=output_path,no_marker=no_marker,),)+ if json_mode:+ _print_parse_json_response(parse_result, None, output=exported.output)+ returnprint_success(f"Written to {exported.output}")return- content = client.get_doc_content(+ content = _fetch_doc_content(+ client,sha256,tier=tier,page_range=page_range,@@ -181,28 +208,13 @@ def _output_content(format=format,no_marker=no_marker,)- text = content.content or ""- if text:- if json_mode:- import json-- payload = {- "sha256": content.sha256,- "short_id": content.short_id,- "tier": content.tier,- "format": content.format,- "content": text,- "truncated": content.truncated,- "next_request": _next_request_dict(content.next_request),- }- print(json.dumps(payload, ensure_ascii=False))- else:- print(text)- if content.next_request and not no_marker and source_path:- print(_next_marker(source_path, content.next_request))- else:+ if not content.content and content.format == "markdown":print_error("No content returned from parse.")raise typer.Exit(1)+ if json_mode:+ _print_parse_json_response(parse_result, content)+ return+ output_doc_content_response(content, json_mode=json_mode, output=None, source_path=source_path, read_mode=False, no_marker=no_marker)except typer.Exit:raiseexcept Exception as exc:@@ -210,6 +222,91 @@ def _output_content(raise typer.Exit(1) from None+def _fetch_doc_content(+ client: DoclibClient,+ sha256: str,+ *,+ tier: Tier,+ page_range: str | None,+ after: str | None,+ limit: int,+ format: str,+ no_marker: bool,+) -> DocContentResponse:+ return client.get_doc_content(+ sha256,+ tier=tier,+ page_range=page_range,+ after=after,+ limit=limit,+ format=format,+ no_marker=no_marker,+ )+++def _print_parse_json_response(+ parse_result: ParseResponse,+ content: DocContentResponse | None,+ *,+ output: str | None = None,+) -> None:+ 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)+++def output_doc_content_response(+ content: DocContentResponse,+ *,+ json_mode: bool,+ output: str | None,+ source_path: str | None,+ read_mode: bool,+ no_marker: bool,+) -> 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+ print(content.content)+ 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)+ if marker:+ print(marker)++def _next_request_dict(next_request: ContentNextRequest | None) -> dict[str, str] | None:if next_request is None:return None@@ -218,13 +315,23 @@ def _next_request_dict(next_request: ContentNextRequest | None) -> dict[str, strresult["page_range"] = next_request.page_rangeif next_request.after:result["after"] = next_request.after+ if next_request.locator:+ result["locator"] = next_request.locatorreturn result-def _next_marker(path: str, next_request: ContentNextRequest) -> str:+def _parse_next_marker(path: str | None, next_request: ContentNextRequest) -> str | None:+ if not path:+ return Noneparts = ["mineru", "parse", path]if next_request.page_range:parts.extend(["--pages", next_request.page_range])if next_request.after:parts.extend(["--after", next_request.after])return f"<!-- Next: {' '.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_next/commands/read.py b/mineru/cli_next/commands/read.pynew file mode 100644index 00000000..a56e5db4--- /dev/null+++ b/mineru/cli_next/commands/read.py@@ -0,0 +1,54 @@+"""mineru read — read doclib content by locator."""++from __future__ import annotations++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+++def read_cmd(+ 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."""+ 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(+ 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)+++if __name__ != "__main__":++ def _register(app: typer.Typer) -> None:+ app.command()(read_cmd)diff --git a/mineru/cli_next/commands/scan.py b/mineru/cli_next/commands/scan.pyindex 6445b8a1..355b4dc2 100644--- a/mineru/cli_next/commands/scan.py+++ b/mineru/cli_next/commands/scan.py@@ -8,6 +8,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import ScanRequest+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_json, print_success@@ -21,8 +22,7 @@ def scan_cmd(try:_scan_path(path, wait=wait, no_wait=no_wait, json_mode=json_mode)except Exception as exc:- print_error(str(exc) or "Cannot connect to mineru server. Run 'mineru server start' first.")- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")def _scan_path(path: str, *, wait: int, no_wait: bool, json_mode: bool) -> None:diff --git a/mineru/cli_next/commands/search.py b/mineru/cli_next/commands/search.pyindex 0540c525..fa2ee087 100644--- a/mineru/cli_next/commands/search.py+++ b/mineru/cli_next/commands/search.py@@ -6,6 +6,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...types import Tier+from ..json_errors import exit_with_errorfrom ..output import format_search_results, print_error@@ -24,8 +25,7 @@ def search_cmd(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:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)def find_cmd(@@ -40,5 +40,4 @@ def find_cmd(result = client.find(query, ext=ext, limit=limit)format_search_results(result, json_mode=json_mode)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)diff --git a/mineru/cli_next/commands/server.py b/mineru/cli_next/commands/server.pyindex 1c793673..061b800d 100644--- a/mineru/cli_next/commands/server.py+++ b/mineru/cli_next/commands/server.py@@ -10,6 +10,8 @@ import timeimport typerfrom ...config import config+from ...doclib.types import ServerStatusResponse+from ..json_errors import exit_with_errorfrom ..output import format_server_status, print_error, print_info, print_successapp = typer.Typer(help="Server lifecycle management", no_args_is_help=True)@@ -19,6 +21,10 @@ def _socket_path() -> str:return config.doclib.uds.path+def _server_log_path() -> str:+ return os.path.expanduser(config.doclib.log.path)++def _server_running() -> bool:socket_path = _socket_path()if not os.path.exists(socket_path):@@ -59,17 +65,31 @@ def start() -> None:except OSError:pass- proc = subprocess.Popen(- [sys.executable, "-m", "mineru.doclib.app"],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- start_new_session=True,- )+ log_path = _server_log_path()+ log_dir = os.path.dirname(log_path)+ if log_dir:+ os.makedirs(log_dir, exist_ok=True)- if not _wait_for_sock():- proc.kill()- print_error("Server failed to start within 15 seconds.")- raise typer.Exit(1)+ try:+ with open(log_path, "a", encoding="utf-8") as log_file:+ log_file.write("\n--- mineru server start ---\n")+ log_file.flush()+ proc = subprocess.Popen(+ [sys.executable, "-m", "mineru.doclib.app"],+ stdout=log_file,+ stderr=log_file,+ start_new_session=True,+ )++ if not _wait_for_sock():+ proc.kill()+ print_error(f"Server failed to start within 15 seconds. See log: {log_path}")+ raise typer.Exit(1)+ except typer.Exit:+ raise+ except Exception as exc:+ print_error(f"Server failed to start: {exc}. See log: {log_path}")+ raise typer.Exit(1) from Noneprint_success(f"Server started (PID {proc.pid}). Socket: {socket_path}")@@ -111,6 +131,16 @@ def restart() -> None:def status(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:"""Show server status."""if not _server_running():+ if json_mode:+ format_server_status(+ ServerStatusResponse(+ running=False,+ socket_path=_socket_path(),+ data_dir=os.path.expanduser(config.doclib.data_dir),+ ),+ json_mode=True,+ )+ returnprint_info("Server is not running.")return@@ -121,4 +151,4 @@ def status(json_mode: bool = typer.Option(False, "--json", help="JSON output"))data = c.get_server_status()format_server_status(data, json_mode=json_mode)except Exception as exc:- print_error(str(exc))+ exit_with_error(exc, json_mode=json_mode)diff --git a/mineru/cli_next/commands/show.py b/mineru/cli_next/commands/show.pyindex 1bd5a850..b654047c 100644--- a/mineru/cli_next/commands/show.py+++ b/mineru/cli_next/commands/show.py@@ -7,6 +7,7 @@ from pathlib import Pathimport typerfrom ...doclib.client import DoclibClient+from ..json_errors import exit_with_errorfrom ..output import format_info, print_error, print_jsonfrom .scan import _print_scan@@ -22,8 +23,7 @@ def show_parse(try:result = _client().get_parse(parse_id)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)@@ -46,8 +46,7 @@ def show_scan(try:result = _client().get_scan(scan_id)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)_print_scan(result, json_mode=json_mode)@@ -62,8 +61,7 @@ def show_file(try:result = _client().get_file_by_path(file_path)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)format_info(result, json_mode=json_mode)@@ -77,8 +75,7 @@ def show_doc(try:result = _client().get_doc(sha256, expand_files=True)except Exception as exc:- print_error(str(exc))- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode)if json_mode:print_json(result)diff --git a/mineru/cli_next/commands/watch.py b/mineru/cli_next/commands/watch.pyindex 872c7b16..d6a66100 100644--- a/mineru/cli_next/commands/watch.py+++ b/mineru/cli_next/commands/watch.py@@ -8,6 +8,7 @@ import typerfrom ...doclib.client import DoclibClientfrom ...doclib.types import ScanRequest, WatchInfo, WatchRequest+from ..json_errors import exit_with_errorfrom ..output import print_error, print_info, print_json, print_successfrom .scan import _print_scan, _wait_for_scan@@ -25,8 +26,7 @@ def watch_add(try:data = _client().add_watch(WatchRequest(path=path, removable=removable, label=label))except Exception as exc:- print_error(str(exc) or "Cannot add watch target.")- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot add watch target.")if json_mode:print_json(data)@@ -40,8 +40,7 @@ def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON outputtry:data = _client().list_watches()except Exception as exc:- print_error(str(exc) or "Cannot list watch targets.")- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot list watch targets.")if json_mode:print_json(data)@@ -67,8 +66,7 @@ def watch_remove(watch = _resolve_watch(client, target)result = client.remove_watch(watch.id)except Exception as exc:- print_error(str(exc) or "Cannot remove watch target.")- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot remove watch target.")if json_mode:print_json(result)@@ -91,8 +89,7 @@ def watch_rescan(if not no_wait and wait > 0:scan_info = _wait_for_scan(client, scan_info.id, wait)except Exception as exc:- print_error(str(exc) or "Cannot rescan watch target.")- raise typer.Exit(1) from None+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot rescan watch target.")_print_scan(scan_info, json_mode=json_mode)diff --git a/mineru/cli_next/json_errors.py b/mineru/cli_next/json_errors.pynew file mode 100644index 00000000..c2da58ef--- /dev/null+++ b/mineru/cli_next/json_errors.py@@ -0,0 +1,41 @@+"""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]), paramdiff --git a/mineru/cli_next/main.py b/mineru/cli_next/main.pyindex 3dbbcbf4..0e63cbbd 100644--- a/mineru/cli_next/main.py+++ b/mineru/cli_next/main.py@@ -2,6 +2,8 @@from __future__ import annotations+from typing import Literal+import typerfrom click.core import Contextfrom typer.core import TyperGroup@@ -11,6 +13,7 @@ from .commands import cleanup, config, list_resources, server, show, watchTOP_LEVEL_COMMAND_ORDER = ["parse",+ "read","scan","watch","search",@@ -47,12 +50,12 @@ def parse(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: str = typer.Option("markdown", "-f", "--format", help="Output format: markdown, text, json, html"),+ 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 file path (default: STDOUT)"),+ 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"),@@ -78,6 +81,30 @@ def parse()+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,+ )++@app.command()def scan(path: str = typer.Argument(..., help="File or directory path to scan"),diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 4695193b..b59bd857 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -149,6 +149,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:state.start_time = time.time()state.pid = os.getpid()state.data_dir = data_dir+ state.socket_path = os.path.expanduser(cfg.doclib.uds.path)state.config = cfg@app.on_event("shutdown")@@ -227,6 +228,7 @@ class AppState:self.health_check: Any = Noneself.start_time: float = 0.0self.pid: int = 0+ self.socket_path: str = ""self.data_dir: str = ""self.config: Config | None = Nonediff --git a/mineru/doclib/background/__init__.py b/mineru/doclib/background/__init__.pynew file mode 100644index 00000000..3c972d25--- /dev/null+++ b/mineru/doclib/background/__init__.py@@ -0,0 +1,27 @@+"""Background workers and health monitoring for doclib."""++from .compaction import Compaction+from .device_monitor import DeviceMonitor+from .ingest import IngestWorkerPool+from .parse_server_health import (+ ParseServerHealth,+ ParseServerHealthCheck,+ api_server_args_for_tier,+ get_health,+)+from .parse_worker import ParseWorkerPool+from .scan_worker import ScanWorkerPool+from .watch import WatchLoop++__all__ = [+ "Compaction",+ "DeviceMonitor",+ "IngestWorkerPool",+ "ParseServerHealth",+ "ParseServerHealthCheck",+ "ParseWorkerPool",+ "ScanWorkerPool",+ "WatchLoop",+ "api_server_args_for_tier",+ "get_health",+]diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.pyindex d3d43663..39c939ed 100644--- a/mineru/doclib/background/compaction.py+++ b/mineru/doclib/background/compaction.py@@ -10,6 +10,7 @@ import timefrom collections.abc import Sequencefrom typing import cast+from ...schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom ...types import Tierfrom ..core.db import DatabaseManagerfrom ..rows import ParseBatchRow, ParseGroupRow, ParseRow@@ -158,12 +159,14 @@ class Compaction:# write one compacted JSON per merged rangefor page_range in merged_ranges:page_numbers = parse_page_range_set(page_range)- json_pages = [pages_by_page_idx[page_no - 1] for page_no in sorted(page_numbers) if page_no - 1 in pages_by_page_idx]+ json_pages = [+ pages_by_page_idx[page_no - 1] for page_no in sorted(page_numbers) if page_no - 1 in pages_by_page_idx+ ]if not json_pages:continuejson_path = parse_batch_json_path(self.data_dir, sha256, tier, page_range, max_done_at)try:with open(json_path, "w", encoding="utf-8") as f:- json.dump({"pages": json_pages}, f, ensure_ascii=False, indent=2)+ json.dump({"schema_version": MIDDLE_JSON_SCHEMA_VERSION, "pages": json_pages}, f, ensure_ascii=False, indent=1)except Exception:passdiff --git a/mineru/doclib/base.py b/mineru/doclib/base.pyindex ae07bf94..333c2fd0 100644--- a/mineru/doclib/base.py+++ b/mineru/doclib/base.py@@ -20,6 +20,7 @@ from .types import (DocContentExportRequest,DocContentExportResponse,DocContentResponse,+ ContentFormat,DocInfo,ExcludeRuleInfo,ExcludeRuleListResponse,@@ -268,6 +269,25 @@ class DoclibInterface(ABC):"""raise NotImplementedError()+ @abstractmethod+ def read_content(+ self,+ locator: str,+ *,+ context: int = 0,+ limit: int = 30000,+ format: ContentFormat = "markdown",+ no_marker: bool = False,+ ) -> DocContentResponse:+ """Render stored doc content from a stable content locator.++ Raises:+ NotFoundError: when the document or requested parsed content is not cached.+ InvalidRequestError: when locator, context, format, or marker options are invalid.+ MineruError: for render, asset, or server-side failures.+ """+ raise NotImplementedError()+@abstractmethoddef export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:"""Render stored doc content and write it to a server-visible output path.@@ -607,6 +627,19 @@ class AsyncDoclibInterface(ABC):"""Async version of ``DoclibInterface.get_doc_content``."""raise NotImplementedError()+ @abstractmethod+ async def read_content(+ self,+ locator: str,+ *,+ context: int = 0,+ limit: int = 30000,+ format: ContentFormat = "markdown",+ no_marker: bool = False,+ ) -> DocContentResponse:+ """Async version of ``DoclibInterface.read_content``."""+ raise NotImplementedError()+@abstractmethodasync def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:"""Async version of ``DoclibInterface.export_doc_content``."""diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 740123a6..799a21d3 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -25,6 +25,7 @@ from .types import (ConfigSetResponse,ConfigUnsetResponse,ConfigValueResponse,+ ContentFormat,DocContentExportRequest,DocContentExportResponse,DocContentResponse,@@ -222,6 +223,27 @@ class DoclibClient(DoclibInterface):},)+ @route("GET", "/content", tags=("docs",))+ def read_content(+ self,+ locator: str,+ *,+ context: int = 0,+ limit: int = 30000,+ format: ContentFormat = "markdown",+ no_marker: bool = False,+ ) -> DocContentResponse:+ return self._request_model(+ DocContentResponse,+ params={+ "locator": locator,+ "context": context,+ "limit": limit,+ "format": format,+ "no_marker": no_marker,+ },+ )+@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)diff --git a/mineru/doclib/core/__init__.py b/mineru/doclib/core/__init__.pynew file mode 100644index 00000000..cdfad592--- /dev/null+++ b/mineru/doclib/core/__init__.py@@ -0,0 +1,17 @@+"""Core data layer: database, file I/O, and full-text search."""++from .db import DatabaseManager+from .file_io import FileStat, compute_sha256, extract_metadata, get_file_stat+from .fts import FTSManager, strip_sep, tokenize_for_index, tokenize_for_query++__all__ = [+ "DatabaseManager",+ "FTSManager",+ "FileStat",+ "compute_sha256",+ "extract_metadata",+ "get_file_stat",+ "strip_sep",+ "tokenize_for_index",+ "tokenize_for_query",+]diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sqlindex 12448132..1b62db20 100644--- a/mineru/doclib/migrations/001_init.sql+++ b/mineru/doclib/migrations/001_init.sql@@ -1,6 +1,7 @@-- v001: Initial schema-- Applied to new databases. For existing databases, see 002_add_parse_columns.sql.+-- STABLECREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY AUTOINCREMENT,path TEXT NOT NULL UNIQUE,@@ -41,6 +42,7 @@ CREATE TABLE IF NOT EXISTS docs (updated_at INTEGER NOT NULL);+-- STABLECREATE TABLE IF NOT EXISTS parses (id INTEGER PRIMARY KEY AUTOINCREMENT,sha256 TEXT NOT NULL REFERENCES docs(sha256),diff --git a/mineru/doclib/migrations/__init__.py b/mineru/doclib/migrations/__init__.pynew file mode 100644index 00000000..812de9b7--- /dev/null+++ b/mineru/doclib/migrations/__init__.py@@ -0,0 +1 @@+"""Doclib SQL schema migrations."""diff --git a/mineru/doclib/rows.py b/mineru/doclib/rows.pyindex 91a5eb18..61155470 100644--- a/mineru/doclib/rows.py+++ b/mineru/doclib/rows.py@@ -205,6 +205,7 @@ class SearchFileRow(FileRow):class FilenameSearchFileRow(FileRow):title: str | None+ page_count: int | Noneclass ContentSearchResultRow(TypedDict):@@ -214,6 +215,7 @@ class ContentSearchResultRow(TypedDict):filename: str | Noneext: str | Nonesize_bytes: int | None+ page_count: int | Nonetier: Tiersnippet: strpaths: list[str]@@ -225,6 +227,7 @@ class FilenameSearchResultRow(TypedDict):filename: strext: str | Nonesize_bytes: int | None+ page_count: int | Nonetier: strsnippet: strpaths: list[str]diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 0c9e4198..a9b657a2 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -3,24 +3,31 @@from __future__ import annotationsimport asyncio+import base64+import reimport osimport signal+import shutilimport timefrom dataclasses import dataclass+from io import BytesIO+from pathlib import Pathfrom typing import Any, castfrom fastapi import APIRouter, FastAPI, Requestfrom fastapi.responses import JSONResponse+from PIL import Imagefrom ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_forfrom ..render import render_markdownfrom ..render.markdown import blocks_to_markdownfrom ..render.office.output import blocks_to_markdown as office_blocks_to_markdown-from ..types import TIERS, PageInfo, Tier+from ..types import EMPTY_BBOX, TIERS, Block, PageInfo, Span, Tier+from ..utils.pdf_document import PDFDocumentfrom .background.parse_server_health import get_healthfrom .base import AsyncDoclibInterfacefrom .core.db import DatabaseManager-from .locators import block_char_ref, block_ref, page_ref, parse_content_cursor+from .locators import ContentCursor, block_char_ref, block_ref, page_ref, parse_content_cursorfrom .rows import (ContentSearchResultRow,DocRow,@@ -60,6 +67,8 @@ from .types import (ConfigSetResponse,ConfigUnsetResponse,ConfigValueResponse,+ ContentAsset,+ ContentFormat,ContentNextRequest,ContentRange,ContentRequestScope,@@ -126,6 +135,31 @@ class _RenderedContent:cut_inside_page: bool = False+@dataclass(frozen=True)+class _ReadPlan:+ sha256: str+ short_id: str+ tier: Tier+ page_range: str | None+ after: str | None+ locator: str | None+ context: int+ limit: int+ format: ContentFormat+ no_marker: bool+ target: ContentCursor | None = None+ next_mode: str = "parse"+++@dataclass(frozen=True)+class _LocatorParts:+ short_id: str+ tier: Tier | None = None+ page_no: int | None = None+ block_no: int | None = None+ char_offset: int | None = None++class DoclibServer(AsyncDoclibInterface):"""Async doclib server whose routes are declared on interface methods."""@@ -392,14 +426,121 @@ class DoclibServer(AsyncDoclibInterface):format: str = "markdown",no_marker: bool = False,) -> DocContentResponse:- return await self._render_doc_content_response(- sha256,+ return await self._execute_read_plan(+ await self._build_read_plan_from_parse(+ sha256,+ tier=tier,+ page_range=page_range,+ after=after,+ limit=limit,+ format=format,+ no_marker=no_marker,+ )+ )++ @route("GET", "/content", tags=("docs",))+ async def read_content(+ self,+ locator: str,+ *,+ context: int = 0,+ limit: int = 30000,+ format: ContentFormat = "markdown",+ no_marker: bool = False,+ ) -> DocContentResponse:+ return await self._execute_read_plan(+ await self._build_read_plan_from_locator(+ locator,+ context=context,+ limit=limit,+ format=format,+ no_marker=no_marker,+ )+ )++ async def _build_read_plan_from_parse(+ self,+ sha256: str,+ *,+ tier: Tier,+ page_range: str | None,+ after: str | None,+ limit: int,+ format: str,+ no_marker: bool,+ ) -> _ReadPlan:+ 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")++ 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,tier=tier,- page_range=page_range,+ short_id=doc["short_id"],+ page_range=normalized_page_range,after=after,limit=limit,+ format="markdown",+ no_marker=no_marker,+ locator=None,+ context=0,+ target=None,+ next_mode="parse",+ )++ async def _build_read_plan_from_locator(+ self,+ locator: str,+ *,+ context: int,+ limit: int,+ format: ContentFormat,+ no_marker: bool,+ ) -> _ReadPlan:+ limit = max(1, limit)+ context = max(0, context)+ cursor = _parse_doc_locator(locator)+ doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE short_id=?", (cursor.short_id,)))+ if doc is None:+ raise NotFoundError("doc_not_found", f"Document {cursor.short_id} not found.", "locator")++ tier = cursor.tier or await self._default_read_tier(doc["sha256"])+ if tier is None:+ raise NotFoundError("tier_not_cached", f"No parsed tier is cached for document {cursor.short_id}.", "locator")+ if format == "image" and context:+ raise InvalidRequestError("context_not_applicable", "context is not supported for image reads.", "context")+ if cursor.page_no is None and context:+ raise InvalidRequestError("context_not_applicable", "context requires a page, block, or char locator.", "context")++ page_range = _locator_page_range(cursor, doc, context)+ return _ReadPlan(+ sha256=doc["sha256"],+ short_id=doc["short_id"],+ tier=tier,+ page_range=page_range,+ after=_locator_after(cursor),+ locator=_canonical_locator(doc["short_id"], tier, cursor),+ context=context,+ limit=limit,format=format,no_marker=no_marker,+ target=ContentCursor(+ short_id=doc["short_id"],+ tier=tier,+ page_no=cursor.page_no or 1,+ block_no=cursor.block_no,+ char_offset=cursor.char_offset,+ )+ if cursor.page_no is not None+ else None,+ next_mode="read",)@route("POST", "/docs/{sha256}/exports", tags=("docs",))@@ -648,77 +789,101 @@ class DoclibServer(AsyncDoclibInterface):raise NotFoundError("not_cached", "Requested parsed content is not cached.", "page_range")return render_markdown(loaded_pages, add_markers=not no_marker)- async def _render_doc_content_response(- self,- sha256: str,- *,- tier: Tier,- page_range: str | None,- after: str | None,- limit: int,- format: str,- no_marker: bool,- ) -> DocContentResponse:- if format != "markdown":- raise InvalidRequestError("invalid_request", "Only markdown is currently implemented.", "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")-- normalized_page_range = _normalize_content_page_range(page_range, after, doc)- after_cursor = parse_content_cursor(after) if after else None- if after_cursor and after_cursor.short_id != doc["short_id"]:- raise InvalidRequestError("invalid_request", "after cursor does not belong to this document.", "after")- if after_cursor and after_cursor.tier != tier:- raise InvalidRequestError("invalid_request", "after cursor tier does not match request tier.", "after")- if after_cursor and normalized_page_range and after_cursor.page_no not in parse_page_range_set(normalized_page_range):- raise InvalidRequestError("invalid_request", "after cursor is outside requested page_range.", "after")-+ async def _execute_read_plan(self, plan: _ReadPlan) -> DocContentResponse:data_dir = getattr(self.state, "data_dir", os.path.expanduser("~/MinerU"))rows = await self.state.db.fetchall("SELECT page_range, done_at FROM parses WHERE sha256=? AND tier=? AND status=? ORDER BY done_at DESC",- (sha256, tier, PARSE_STATUS_DONE),+ (plan.sha256, plan.tier, PARSE_STATUS_DONE),)- loaded_pages = load_pages_from_done_batches(data_dir, sha256, tier, cast(list[ParseBatchRow], rows))- if normalized_page_range:- loaded_pages = filter_pages_by_user_range(loaded_pages, normalized_page_range)+ loaded_pages = load_pages_from_done_batches(data_dir, plan.sha256, plan.tier, cast(list[ParseBatchRow], rows))+ if plan.page_range:+ loaded_pages = filter_pages_by_user_range(loaded_pages, plan.page_range)if not loaded_pages:raise NotFoundError("not_cached", "Requested parsed content is not cached.", "page_range")+ if plan.format == "image":+ return await self._render_image_response(plan, loaded_pages)++ pages_for_render = _select_context_pages(loaded_pages, plan.target, plan.context)rendered = _render_progressive_markdown(- loaded_pages,- short_id=doc["short_id"],- tier=tier,- after=after_cursor,- limit=limit,- add_markers=not no_marker,+ pages_for_render,+ short_id=plan.short_id,+ tier=plan.tier,+ after=parse_content_cursor(plan.after) if plan.after else None,+ limit=plan.limit,+ add_markers=not plan.no_marker,+ target=plan.target,+ context=plan.context,)if not rendered.content_ranges:raise NotFoundError("not_cached", "Requested parsed content is not cached after cursor.", "after")- next_request = _next_content_request(- rendered=rendered,- request_page_range=normalized_page_range,- after=after,- page_count=doc["page_count"],- paginated=_is_paginated_doc(doc),+ doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (plan.sha256,)))+ page_count = doc["page_count"] if doc else None+ paginated = _is_paginated_doc(doc) if doc else True+ next_request = (+ _next_read_request(rendered, plan.short_id, plan.tier, page_count)+ if plan.next_mode == "read"+ else _next_content_request(+ rendered=rendered,+ request_page_range=plan.page_range,+ after=plan.after,+ page_count=page_count,+ paginated=paginated,+ ))return DocContentResponse(- sha256=sha256,- short_id=doc["short_id"],- tier=tier,+ sha256=plan.sha256,+ short_id=plan.short_id,+ tier=plan.tier,format="markdown",content=rendered.content,- request_scope=ContentRequestScope(page_range=normalized_page_range, after=after, limit=limit),+ request_scope=ContentRequestScope(+ page_range=plan.page_range,+ after=plan.after,+ limit=plan.limit,+ locator=plan.locator,+ context=plan.context,+ ),content_ranges=rendered.content_ranges,truncated=rendered.truncated,next_request=next_request,)+ async def _render_image_response(self, plan: _ReadPlan, loaded_pages: list[PageInfo]) -> DocContentResponse:+ if plan.target is None or plan.target.page_no is None:+ raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")+ if plan.page_range and len(parse_page_range_set(plan.page_range)) != 1:+ raise InvalidRequestError("multi_page_image_not_supported", "image format supports only one page.", "locator")+ page = _find_page(loaded_pages, plan.target.page_no)+ if page is None:+ raise NotFoundError("page_not_cached", f"Page {plan.target.page_no} is not cached.", "locator")++ if _is_office_page(page):+ asset = await self._render_office_image_asset(plan, page)+ else:+ asset = await self._render_pdf_image_asset(plan, page)++ target_ref = plan.locator or page_ref(plan.short_id, plan.tier, plan.target.page_no)+ return DocContentResponse(+ sha256=plan.sha256,+ short_id=plan.short_id,+ tier=plan.tier,+ format="image",+ content="",+ request_scope=ContentRequestScope(+ page_range=plan.page_range,+ after=plan.after,+ limit=plan.limit,+ locator=plan.locator,+ context=plan.context,+ ),+ content_ranges=[ContentRange(page_range=str(plan.target.page_no), start=target_ref, end=target_ref)],+ truncated=False,+ next_request=None,+ asset=asset,+ )+async def _sha256_for_path(self, path: str) -> str | None:row = cast(Sha256Row | None,@@ -733,6 +898,131 @@ class DoclibServer(AsyncDoclibInterface):)return [_file_info(row) for row in rows]+ async def _default_read_tier(self, sha256: str) -> Tier | None:+ rows = cast(+ list[ParseRow],+ await self.state.db.fetchall(+ "SELECT tier FROM parses WHERE sha256=? AND status=? GROUP BY tier",+ (sha256, PARSE_STATUS_DONE),+ ),+ )+ tiers = {row["tier"] for row in rows if row["tier"] in TIERS and row["tier"] != "flash"}+ if not tiers:+ return None+ return sorted(tiers, key=lambda t: TIERS.index(t))[-1]++ async def _render_pdf_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:+ if plan.target is None:+ raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")+ file_row = cast(+ FileRow | None,+ await self.state.db.fetchone(+ "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",+ (plan.sha256, FILE_STATUS_ACTIVE),+ ),+ )+ if file_row is None:+ raise NotFoundError("no_accessible_file", "No active source file found for this document.", "locator")+ source_path = file_row["path"]+ if not source_path.lower().endswith(".pdf"):+ raise InvalidRequestError("format_not_supported", "image format for page/block is only supported for PDF sources.", "format")+ pdf_bytes = Path(source_path).read_bytes()+ with PDFDocument(pdf_bytes) as doc:+ if plan.target.block_no is None:+ image = doc.render_page(plan.target.page_no - 1, scale=2)+ image_bytes = _pil_image_to_bytes(image)+ width, height = image.size+ else:+ block = _find_block_by_no(page, plan.target.block_no)+ if block is None:+ raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")+ if _is_empty_bbox(block.bbox):+ raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")+ image_bytes = doc.crop_image(block.bbox, plan.target.page_no - 1, scale=2)+ width, height = _image_size_from_bytes(image_bytes)+ return _write_temp_asset(self.state.data_dir, plan.short_id, "jpg", image_bytes, mime_type="image/jpeg", width=width, height=height)++ async def _render_office_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:+ if plan.target is None or plan.target.block_no is None:+ raise InvalidRequestError("format_not_supported", "Office image output requires an image block locator.", "format")+ block = _find_block_by_no(page, plan.target.block_no)+ if block is None:+ raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")+ image_span = _first_image_span(block)+ if image_span is None:+ raise InvalidRequestError("format_not_supported", "Office image output is only supported for image blocks.", "format")+ image_bytes, ext, mime_type = _span_image_bytes(image_span)+ if image_bytes is None and image_span.image_path:+ candidate = Path(image_span.image_path)+ if candidate.is_file():+ image_bytes = candidate.read_bytes()+ ext = candidate.suffix.lstrip(".") or "png"+ mime_type = _mime_type_for_ext(ext)+ if image_bytes is None:+ raise NotFoundError("asset_not_available", "Office image asset is not available.", "locator")+ width, height = _image_size_from_bytes(image_bytes)+ return _write_temp_asset(self.state.data_dir, plan.short_id, ext or "png", image_bytes, mime_type=mime_type, width=width, height=height)+++_READ_LOCATOR_RE = re.compile(+ r"^doc:(?P<short_id>[0-9a-fA-F]+)"+ r"(?:/tier:(?P<tier>flash|standard|pro)"+ r"(?:/page:(?P<page_no>[1-9][0-9]*)"+ r"(?:/block:(?P<block_no>[1-9][0-9]*)(?:/char:(?P<char_offset>0|[1-9][0-9]*))?)?)?)?$"+)+++def _parse_doc_locator(locator: str) -> _LocatorParts:+ match = _READ_LOCATOR_RE.match(locator)+ if match is None:+ raise InvalidRequestError("invalid_locator", f"Invalid doclib locator: {locator}", "locator")+ page_no = match.group("page_no")+ block_no = match.group("block_no")+ char_offset = match.group("char_offset")+ return _LocatorParts(+ short_id=match.group("short_id"),+ tier=cast(Tier | None, match.group("tier")),+ page_no=int(page_no) if page_no is not None else None,+ block_no=int(block_no) if block_no is not None else None,+ char_offset=int(char_offset) if char_offset is not None else None,+ )+++def _canonical_locator(short_id: str, tier: Tier, locator: _LocatorParts) -> str:+ if locator.page_no is None:+ return f"doc:{short_id}/tier:{tier}"+ if locator.block_no is None:+ return page_ref(short_id, tier, locator.page_no)+ if locator.char_offset is None:+ return block_ref(short_id, tier, locator.page_no, locator.block_no)+ return block_char_ref(short_id, tier, locator.page_no, locator.block_no, locator.char_offset)+++def _locator_after(locator: _LocatorParts) -> str | None:+ if locator.page_no is None:+ return None+ if locator.block_no is None:+ return None+ return _canonical_locator(locator.short_id, locator.tier or "standard", locator) if locator.char_offset is not None else None+++def _locator_page_range(locator: _LocatorParts, doc: DocRow, context: int) -> str | None:+ page_count = doc.get("page_count") or 1+ if locator.page_no is None:+ return _normalize_content_page_range(None, None, doc)+ start = max(1, locator.page_no - context)+ end = min(page_count, locator.page_no + context)+ return _range_str(start, end)+++def _validate_cursor_for_doc(cursor: ContentCursor, doc: DocRow, tier: Tier, page_range: str | None) -> None:+ if cursor.short_id != doc["short_id"]:+ raise InvalidRequestError("invalid_request", "after cursor does not belong to this document.", "after")+ if cursor.tier != tier:+ raise InvalidRequestError("invalid_request", "after cursor tier does not match request tier.", "after")+ if page_range and cursor.page_no not in parse_page_range_set(page_range):+ raise InvalidRequestError("invalid_request", "after cursor is outside requested page_range.", "after")+def _mask_config(config: dict[str, str]) -> dict[str, str]:return {key: _mask_config_value(key, value) for key, value in config.items()}@@ -852,6 +1142,131 @@ def _page_numbers_to_range_str(page_numbers: set[int]) -> str:return ",".join(ranges)+def _select_context_pages(pages: list[PageInfo], target: ContentCursor | None, context: int) -> list[PageInfo]:+ if target is None or target.page_no is None or context <= 0:+ return pages+ start = target.page_no - context+ end = target.page_no + context+ return [page for page in pages if start <= page.page_idx + 1 <= end]+++def _find_page(pages: list[PageInfo], page_no: int) -> PageInfo | None:+ return next((page for page in pages if page.page_idx + 1 == page_no), None)+++def _find_block_by_no(page: PageInfo, block_no: int) -> Block | None:+ target_index = block_no - 1+ for block in page.para_blocks:+ found = _find_block_by_index(block, target_index)+ if found is not None:+ return found+ for block in page.discarded_blocks:+ found = _find_block_by_index(block, target_index)+ if found is not None:+ return found+ return None+++def _find_block_by_index(block: Block, index: int) -> Block | None:+ if block.index == index:+ return block+ for child in block.blocks:+ found = _find_block_by_index(child, index)+ if found is not None:+ return found+ return None+++def _is_office_page(page: PageInfo) -> bool:+ return page._backend == "office"+++def _is_empty_bbox(bbox: object) -> bool:+ if not isinstance(bbox, (tuple, list)) or len(bbox) != 4:+ return True+ try:+ values = [float(v) for v in bbox]+ except (TypeError, ValueError):+ return True+ return tuple(values) == tuple(float(v) for v in EMPTY_BBOX) or values[0] >= values[2] or values[1] >= values[3]+++def _first_image_span(block: Block) -> Span | None:+ for span in _iter_block_spans(block):+ if span.type == "image":+ return span+ return None+++def _iter_block_spans(block: Block):+ for line in block.lines:+ yield from line.spans+ for child in block.blocks:+ yield from _iter_block_spans(child)+++def _span_image_bytes(span: Span) -> tuple[bytes | None, str, str]:+ if not span.image_base64:+ return None, "png", "image/png"+ match = re.match(r"^data:image/(?P<ext>[^;]+);base64,(?P<data>.+)$", span.image_base64, re.DOTALL)+ if match is None:+ return None, "png", "image/png"+ ext = match.group("ext").lower()+ try:+ return base64.b64decode(match.group("data")), ext, _mime_type_for_ext(ext)+ except Exception:+ return None, ext, _mime_type_for_ext(ext)+++def _pil_image_to_bytes(image: Image.Image) -> bytes:+ with BytesIO() as buffer:+ image.save(buffer, format="JPEG")+ return buffer.getvalue()+++def _image_size_from_bytes(image_bytes: bytes) -> tuple[int | None, int | None]:+ try:+ with Image.open(BytesIO(image_bytes)) as image:+ return image.size+ except Exception:+ return None, None+++def _write_temp_asset(+ data_dir: str,+ short_id: str,+ ext: str,+ image_bytes: bytes,+ *,+ mime_type: str,+ width: int | None,+ height: int | None,+) -> ContentAsset:+ safe_ext = ext.lower().lstrip(".") or "png"+ output_dir = Path(os.path.expanduser(data_dir)) / "tmp" / "read-assets"+ output_dir.mkdir(parents=True, exist_ok=True)+ path = output_dir / f"{short_id}-{int(time.time() * 1000)}.{safe_ext}"+ path.write_bytes(image_bytes)+ return ContentAsset(+ path=str(path),+ mime_type=mime_type,+ size_bytes=len(image_bytes),+ width=width,+ height=height,+ )+++def _mime_type_for_ext(ext: str) -> str:+ normalized = ext.lower().lstrip(".")+ if normalized in {"jpg", "jpeg"}:+ return "image/jpeg"+ if normalized == "webp":+ return "image/webp"+ if normalized == "gif":+ return "image/gif"+ return "image/png"++def _render_progressive_markdown(pages: list[PageInfo],*,@@ -860,6 +1275,8 @@ def _render_progressive_markdown(after: Any,limit: int,add_markers: bool,+ target: ContentCursor | None = None,+ context: int = 0,) -> _RenderedContent:output: list[str] = []ranges: list[ContentRange] = []@@ -873,6 +1290,10 @@ def _render_progressive_markdown(if after and page_no < after.page_no:continuepage_blocks = _page_markdown_blocks(page)+ if target and target.block_no is not None and page_no == target.page_no:+ start_block_no = max(1, target.block_no - context)+ end_block_no = target.block_no + context+ page_blocks = [(index, text) for index, text in page_blocks if start_block_no <= index + 1 <= end_block_no]page_output: list[str] = []page_start_cursor = page_ref(short_id, tier, page_no)page_end_cursor = page_ref(short_id, tier, page_no)@@ -974,11 +1395,16 @@ def _render_progressive_markdown(def _page_markdown_blocks(page: PageInfo) -> list[tuple[int, str]]:backend = page._backend- if backend == "office":- rendered = office_blocks_to_markdown(page.para_blocks, img_bucket_path="", no_rich_content=False)- else:- rendered = blocks_to_markdown(page.para_blocks, img_bucket_path="")- return [(index, text) for index, text in enumerate(rendered) if text.strip()]+ result: list[tuple[int, str]] = []+ for block in page.para_blocks:+ if backend == "office":+ rendered = office_blocks_to_markdown([block], img_bucket_path="", no_rich_content=False)+ else:+ rendered = blocks_to_markdown([block], img_bucket_path="")+ text = _join_markdown([item for item in rendered if item.strip()])+ if text.strip():+ result.append((block.index, text))+ return resultdef _join_markdown(parts: list[str]) -> str:@@ -1054,6 +1480,23 @@ def _next_content_request(return ContentNextRequest(page_range=_range_str(start, end))+def _next_read_request(+ rendered: _RenderedContent,+ short_id: str,+ tier: Tier,+ page_count: int | None,+) -> ContentNextRequest | None:+ if not rendered.content_ranges:+ return None+ if rendered.truncated:+ return ContentNextRequest(locator=rendered.content_ranges[-1].end)+ total_page_count = page_count or rendered.last_page_no+ next_page_no = rendered.last_page_no + 1+ if next_page_no > total_page_count:+ return None+ return ContentNextRequest(locator=page_ref(short_id, tier, next_page_no))++def _last_requested_page(page_range: str | None) -> int | None:if not page_range:return Nonediff --git a/mineru/doclib/services/__init__.py b/mineru/doclib/services/__init__.pynew file mode 100644index 00000000..1e19a727--- /dev/null+++ b/mineru/doclib/services/__init__.py@@ -0,0 +1,41 @@+"""Doclib service layer: parse, scan, config, search, and cleanup."""++from .cleanup_svc import CleanupService+from .config_svc import ConfigService+from .parse_svc import (+ FileRefreshResult,+ FileRefreshStatus,+ ParseFailure,+ ParseService,+ default_parse_range,+ ensure_doc_record,+ expand_page_range,+ filter_pages_by_user_range,+ load_pages_from_done_batches,+ page_range_covered,+ page_range_uncovered,+ parse_batch_json_path,+ parse_page_range_set,+)+from .scan_svc import ScanService+from .search_svc import SearchService++__all__ = [+ "CleanupService",+ "ConfigService",+ "FileRefreshResult",+ "FileRefreshStatus",+ "ParseFailure",+ "ParseService",+ "ScanService",+ "SearchService",+ "default_parse_range",+ "ensure_doc_record",+ "expand_page_range",+ "filter_pages_by_user_range",+ "load_pages_from_done_batches",+ "page_range_covered",+ "page_range_uncovered",+ "parse_batch_json_path",+ "parse_page_range_set",+]diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.pyindex 5a155bbd..fd4d6b7c 100644--- a/mineru/doclib/services/cleanup_svc.py+++ b/mineru/doclib/services/cleanup_svc.py@@ -12,6 +12,7 @@ from ..core.db import DatabaseManagerfrom ..rows import CountRow, DocRow, IdRow, WatchTargetRowfrom ..types import FILE_STATUS_DELETED+FORGET_WATCH_ROOT_WARNING = "Path is a configured watch root and may be rediscovered on the next scan."FORGET_UNDER_ACTIVE_WATCH_WARNING = "Path is under an active watch and may be rediscovered on the next scan."@@ -108,17 +109,10 @@ class CleanupService:raise InvalidRequestError("invalid_request", "Path is required.", "path")watches = cast(list[WatchTargetRow], await self.db.fetchall("SELECT * FROM watches WHERE enabled=1"))- if any(watch["path"] == normalized for watch in watches):- raise InvalidRequestError(- "invalid_request",- "Path is a configured watch root. Use mineru watch remove <path> to remove the watch first.",- "path",- )file_ids = await self._forget_file_ids(normalized)matched_as = await self._forget_matched_as(normalized, file_ids)- active_watch_warning = _active_watch_warning(normalized, watches)- warnings = [active_watch_warning] if active_watch_warning else []+ warnings = _forget_warnings(normalized, watches)if not dry_run and file_ids:placeholders = ",".join("?" * len(file_ids))@@ -167,6 +161,9 @@ class CleanupService:async def cleanup_temp_files(self, older_than_days: int = 7) -> int:"""Remove process temp files (e.g. incomplete parse artifacts)."""+ if older_than_days < 0:+ raise InvalidRequestError("invalid_request", "older_than_days must be non-negative.", "older_than_days")+temp_dir = os.path.join(self.data_dir, "temp")if not os.path.isdir(temp_dir):return 0@@ -212,3 +209,11 @@ def _active_watch_warning(path: str, watches: list[WatchTargetRow]) -> str | Nonif path != watch_path and path.startswith(_path_prefix(watch_path)):return FORGET_UNDER_ACTIVE_WATCH_WARNINGreturn None+++def _forget_warnings(path: str, watches: list[WatchTargetRow]) -> list[str]:+ for watch in watches:+ if watch["path"] == path:+ return [FORGET_WATCH_ROOT_WARNING]+ active_watch_warning = _active_watch_warning(path, watches)+ return [active_watch_warning] if active_watch_warning else []diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.pyindex 7de962a0..b6269343 100644--- a/mineru/doclib/services/config_svc.py+++ b/mineru/doclib/services/config_svc.py@@ -86,6 +86,8 @@ class ConfigService:raise ValueError(f"Path must be absolute: {path}")if os.path.normpath(path) != path:raise ValueError(f"Path must be normalized: {path}")+ if not os.path.isdir(path):+ raise InvalidRequestError("invalid_request", f"Watch path does not exist or is not a directory: {path}", "path")wid = fnvhash.fnv1a_64(path.encode()) & ((1 << 63) - 1)diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex 5e74f34d..db4aead9 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -13,6 +13,7 @@ from typing import Literal, castfrom ...errors import MineruErrorfrom ...parser.base import ParseResult+from ...schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom ...types import TIER_ORDER, PageInfo, Tierfrom ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONSfrom ..core.db import DatabaseManager@@ -776,7 +777,7 @@ class ParseService:try:os.makedirs(output_dir, exist_ok=True)with open(json_path, "w", encoding="utf-8") as f:- json.dump({"pages": new_pages}, f, ensure_ascii=False, indent=2)+ json.dump({"schema_version": MIDDLE_JSON_SCHEMA_VERSION, "pages": new_pages}, f, ensure_ascii=False, indent=1)except Exception as exc:await self._fail_task(task["id"], "parse_json_write_failed", str(exc)[:500])return Falsediff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.pyindex def2989f..f0557e0e 100644--- a/mineru/doclib/services/search_svc.py+++ b/mineru/doclib/services/search_svc.py@@ -86,6 +86,7 @@ class SearchService:"filename": row.get("filename") or fts_file.get("filename"),"ext": fts_file.get("ext", ""),"size_bytes": fts_file.get("size_bytes", 0),+ "page_count": fts_file.get("page_count"),"tier": result_tier,"snippet": snippet,"paths": [f["path"] for f in files],@@ -108,7 +109,7 @@ class SearchService:file_ids = [r["file_id"] for r in rows]placeholders = ",".join("?" * len(file_ids))sql = (- f"SELECT f.*, d.title "+ f"SELECT f.*, d.title, d.page_count "f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "f"WHERE f.id IN ({placeholders}) AND f.status = ?")@@ -132,6 +133,7 @@ class SearchService:"filename": fr["filename"],"ext": fr.get("ext", ""),"size_bytes": fr.get("size_bytes", 0),+ "page_count": fr.get("page_count"),"tier": "","snippet": strip_sep(row.get("snippet", "")),"paths": [fr["path"]],diff --git a/mineru/doclib/types.py b/mineru/doclib/types.pyindex e0d0aed7..7bf66780 100644--- a/mineru/doclib/types.py+++ b/mineru/doclib/types.py@@ -18,7 +18,7 @@ WatchStatus = Literal["active", "unreachable"]InvalidateTarget = Literal["parses"]ForgetMatchedAs = Literal["file", "directory", "none"]ConfigSource = Literal["default", "override"]-ContentFormat = Literal["markdown"]+ContentFormat = Literal["markdown", "image"]PARSE_STATUS_PENDING: ParseStatus = "pending"PARSE_STATUS_PARSING: ParseStatus = "parsing"@@ -263,12 +263,15 @@ class DocContentResponse(DoclibModel):content_ranges: list["ContentRange"] = Field(default_factory=list)truncated: bool = Falsenext_request: "ContentNextRequest | None" = None+ asset: "ContentAsset | None" = Noneclass ContentRequestScope(DoclibModel):page_range: str | None = Noneafter: str | None = Nonelimit: int = 30000+ locator: str | None = None+ context: int = 0class ContentRange(DoclibModel):@@ -280,6 +283,15 @@ class ContentRange(DoclibModel):class ContentNextRequest(DoclibModel):page_range: str | None = Noneafter: str | None = None+ locator: str | None = None+++class ContentAsset(DoclibModel):+ path: str+ mime_type: str+ size_bytes: int | None = None+ width: int | None = None+ height: int | None = Noneclass DocContentExportRequest(DoclibModel):diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 1de0f233..a4e04d4e 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -11,7 +11,6 @@ from __future__ import annotationsimport asyncioimport base64-import dataclassesimport hashlibimport jsonimport os@@ -1230,11 +1229,7 @@ async def _run_job(fid = file_store.create_file_for_output(f"{fr.name}.md", content_bytes, sha256hex=sha)output_files.markdown = OutputFileRef(file_id=fid, bytes=len(content_bytes))elif fmt == "middle_json":- mj = json.dumps(- {"pages": [dataclasses.asdict(p) for p in result.pages]},- ensure_ascii=False,- ).encode("utf-8")-+ mj = json.dumps(result.to_dict(skip_defaults=True), ensure_ascii=False).encode("utf-8")sha = hashlib.sha256(mj).hexdigest()file_store.store_blob(mj, sha256hex=sha)fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha)@@ -1600,6 +1595,21 @@ async def create_job(access_level: AccessLevel = Depends(_resolve_access_level),) -> Response:"""Create a parse job."""+ if body.callback is not None:+ raise HTTPException(+ status_code=400,+ detail=ErrorResponse(+ error=ErrorDetail(+ type="invalid_request_error",+ code="invalid_request",+ message=(+ "Webhook callback is not supported by this Local Parse Server. "+ "Use polling via GET /v1/parse/jobs/{job_id}."+ ),+ ),+ ).model_dump(by_alias=True),+ )+# validate output formats — advanced formats require API keyfor fmt in body.output_formats:if fmt in ("html", "latex", "docx") and access_level == "anonymous":diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex 7b8f2d00..4ec241e4 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom typing import Anyfrom ..render import render_content_list, render_content_list_v2, render_markdown+from ..schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom ..types import PageInfo_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)@@ -30,19 +31,39 @@ class ParseResult:@staticmethoddef from_dict(d: dict[str, Any]) -> ParseResult:- # TODO- ...+ if not isinstance(d, dict):+ raise ValueError("ParseResult.from_dict expects a dict.")++ raw_pages = d.get("pages", d.get("pdf_info", []))+ if not isinstance(raw_pages, list):+ raise ValueError("ParseResult pages must be a list.")++ pages: list[PageInfo] = []+ for raw_page in raw_pages:+ if not isinstance(raw_page, dict):+ raise ValueError("ParseResult page entries must be dicts.")+ page = PageInfo.from_dict(raw_page)+ backend = raw_page.get("_backend")+ if isinstance(backend, str):+ page._backend = backend+ pages.append(page)+ return ParseResult(pages=pages)def to_dict(self, *, skip_defaults: bool = False) -> dict[str, Any]:- return {"pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages]}+ return {+ "schema_version": MIDDLE_JSON_SCHEMA_VERSION,+ "pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages],+ }@staticmethoddef from_json(s: str) -> ParseResult:- # TODO- ...+ data = json.loads(s)+ if not isinstance(data, dict):+ raise ValueError("ParseResult JSON must decode to a dict.")+ return ParseResult.from_dict(data)def to_json(self) -> str:- return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)+ return json.dumps(self.to_dict(), ensure_ascii=False, indent=1)def markdown(self, *, add_markers: bool = False) -> str:return render_markdown(self.pages, add_markers=add_markers)@@ -59,17 +80,17 @@ class ParseResult:writer.write_string("content_list.json",- json.dumps(self.content_list(), ensure_ascii=False, indent=2),+ json.dumps(self.content_list(), ensure_ascii=False, indent=1),)writer.write_string("structured_content.json",- json.dumps(self.content_list_v2(), ensure_ascii=False, indent=2),+ json.dumps(self.content_list_v2(), ensure_ascii=False, indent=1),)if self._model_output is not None:writer.write_string("model_output.json",- json.dumps(self._model_output, ensure_ascii=False, indent=2),+ json.dumps(self._model_output, ensure_ascii=False, indent=1),)for img_path, img_bytes in self.images().items():diff --git a/mineru/schema/middle_json/__init__.py b/mineru/schema/middle_json/__init__.pynew file mode 100644index 00000000..86c25642--- /dev/null+++ b/mineru/schema/middle_json/__init__.py@@ -0,0 +1,385 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass+from typing import Literal++from ...types import BLOCK_TYPES, EMPTY_BBOX, Block, BlockType, ContentType, Line, PageInfo, Span+from .envelope import MIDDLE_JSON_SCHEMA_VERSION++__all__ = [+ "MIDDLE_JSON_SCHEMA_VERSION",+ "ValidationIssue",+ "bbox_known",+ "validate_pages",+]++IssueSeverity = Literal["error", "warning"]++KNOWN_BLOCK_TYPES = BLOCK_TYPES | {"list_item"}+TEXT_SPAN_TYPES = {ContentType.TEXT}+IMAGE_SPAN_TYPES = {ContentType.IMAGE}+TABLE_SPAN_TYPES = {ContentType.TABLE}+EQUATION_SPAN_TYPES = {ContentType.EQUATION, ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}+++@dataclass(frozen=True)+class ValidationIssue:+ severity: IssueSeverity+ code: str+ path: str+ message: str+++def bbox_known(bbox: object) -> bool:+ return _is_bbox(bbox) and tuple(float(v) for v in bbox) != EMPTY_BBOX+++def validate_pages(pages: list[PageInfo]) -> list[ValidationIssue]:+ issues: list[ValidationIssue] = []+ if not isinstance(pages, list):+ return [+ ValidationIssue(+ severity="error",+ code="pages_invalid",+ path="pages",+ message="pages must be a list.",+ )+ ]++ for page_index, page in enumerate(pages):+ page_path = f"pages[{page_index}]"+ if not isinstance(page, PageInfo):+ issues.append(_invalid_type(page_path, "PageInfo"))+ continue++ if not _has_field(page, "page_idx"):+ issues.append(_missing(f"{page_path}.page_idx"))+ elif not _is_int(page.page_idx):+ issues.append(_invalid_type(f"{page_path}.page_idx", "int"))+ elif page.page_idx < 0:+ issues.append(_invalid_value(f"{page_path}.page_idx", "page_idx must be non-negative."))++ page_size: tuple[float, float] | None = None+ if _has_field(page, "page_size") and page.page_size is not None:+ _validate_page_size(page.page_size, f"{page_path}.page_size", issues)+ if _is_page_size(page.page_size):+ page_size = (float(page.page_size[0]), float(page.page_size[1]))++ if getattr(page, "_backend", None) is not None:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="legacy_backend",+ path=f"{page_path}._backend",+ message="_backend is a legacy/internal page field.",+ )+ )++ for attr in ("preproc_blocks", "para_blocks", "discarded_blocks"):+ if not _has_field(page, attr):+ continue+ blocks = getattr(page, attr)+ if not isinstance(blocks, list):+ issues.append(_invalid_type(f"{page_path}.{attr}", "list"))+ continue+ _validate_block_list(blocks, f"{page_path}.{attr}", issues, page_size)+ return issues+++def _validate_block_list(+ blocks: list[object],+ path: str,+ issues: list[ValidationIssue],+ page_size: tuple[float, float] | None,+) -> None:+ seen_indexes: set[int] = set()+ previous_index: int | None = None+ for block_index, block in enumerate(blocks):+ block_path = f"{path}[{block_index}]"+ if not isinstance(block, Block):+ issues.append(_invalid_type(block_path, "Block"))+ continue++ if _has_field(block, "index") and _is_int(block.index):+ if block.index in seen_indexes:+ issues.append(+ ValidationIssue(+ severity="error",+ code="block_index_duplicate",+ path=f"{block_path}.index",+ message=f"block index {block.index} is duplicated within {path}.",+ )+ )+ seen_indexes.add(block.index)+ if previous_index is not None and block.index < previous_index:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="block_index_out_of_order",+ path=f"{block_path}.index",+ message="block indexes should be sorted in ascending order.",+ )+ )+ previous_index = block.index++ _validate_block(block, block_path, issues, page_size)+++def _validate_block(block: Block, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:+ for field_name in ("index", "type", "bbox"):+ if not _has_field(block, field_name):+ issues.append(_missing(f"{path}.{field_name}"))++ if _has_field(block, "index") and not _is_int(block.index):+ issues.append(_invalid_type(f"{path}.index", "int"))+ elif _has_field(block, "index") and block.index < 0:+ issues.append(_invalid_value(f"{path}.index", "block index must be non-negative."))++ if _has_field(block, "type") and not isinstance(block.type, str):+ issues.append(_invalid_type(f"{path}.type", "str"))+ elif _has_field(block, "type") and block.type not in KNOWN_BLOCK_TYPES:+ issues.append(+ ValidationIssue(+ severity="error",+ code="block_type_unknown",+ path=f"{path}.type",+ message=f"unknown block type: {block.type}",+ )+ )+ elif _has_field(block, "type") and block.type == BlockType.TITLE:+ _validate_title_level(block, f"{path}.level", issues)++ if _has_field(block, "bbox"):+ _validate_bbox(block.bbox, f"{path}.bbox", issues, page_size)++ if not _has_field(block, "lines") and not _has_field(block, "blocks"):+ issues.append(_missing(f"{path}.lines_or_blocks"))++ if _has_field(block, "lines"):+ if not isinstance(block.lines, list):+ issues.append(_invalid_type(f"{path}.lines", "list"))+ else:+ for line_index, line in enumerate(block.lines):+ line_path = f"{path}.lines[{line_index}]"+ if not isinstance(line, Line):+ issues.append(_invalid_type(line_path, "Line"))+ continue+ _validate_line(line, line_path, issues, page_size)++ if _has_field(block, "blocks"):+ if not isinstance(block.blocks, list):+ issues.append(_invalid_type(f"{path}.blocks", "list"))+ else:+ _validate_block_list(block.blocks, f"{path}.blocks", issues, page_size)+++def _validate_line(line: Line, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:+ if not _has_field(line, "bbox"):+ issues.append(_missing(f"{path}.bbox"))+ else:+ _validate_bbox(line.bbox, f"{path}.bbox", issues, page_size)++ if not _has_field(line, "spans"):+ issues.append(_missing(f"{path}.spans"))+ return+ if not isinstance(line.spans, list):+ issues.append(_invalid_type(f"{path}.spans", "list"))+ return+ for span_index, span in enumerate(line.spans):+ span_path = f"{path}.spans[{span_index}]"+ if not isinstance(span, Span):+ issues.append(_invalid_type(span_path, "Span"))+ continue+ _validate_span(span, span_path, issues, page_size)+++def _validate_span(span: Span, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:+ for field_name in ("type", "bbox"):+ if not _has_field(span, field_name):+ issues.append(_missing(f"{path}.{field_name}"))++ if _has_field(span, "type") and not isinstance(span.type, str):+ issues.append(_invalid_type(f"{path}.type", "str"))+ if _has_field(span, "bbox"):+ _validate_bbox(span.bbox, f"{path}.bbox", issues, page_size)+ if _has_field(span, "type") and isinstance(span.type, str):+ _validate_span_content(span, path, issues)+++def _validate_bbox(+ bbox: object,+ path: str,+ issues: list[ValidationIssue],+ page_size: tuple[float, float] | None = None,+) -> None:+ if not _is_bbox(bbox):+ issues.append(+ ValidationIssue(+ severity="error",+ code="bbox_invalid",+ path=path,+ message="bbox must contain four numeric coordinates.",+ )+ )+ return++ x0, y0, x1, y1 = (float(v) for v in bbox)+ if (x0, y0, x1, y1) == EMPTY_BBOX:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="bbox_unknown",+ path=path,+ message="bbox is the unknown bbox sentinel.",+ )+ )+ return+ if x1 < x0 or y1 < y0:+ issues.append(+ ValidationIssue(+ severity="error",+ code="bbox_invalid",+ path=path,+ message="bbox coordinates must satisfy x1 >= x0 and y1 >= y0.",+ )+ )+ return+ if page_size is not None:+ page_w, page_h = page_size+ if x0 < 0 or y0 < 0 or x1 > page_w or y1 > page_h:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="bbox_out_of_page",+ path=path,+ message="bbox is outside page_size bounds.",+ )+ )+++def _validate_page_size(page_size: object, path: str, issues: list[ValidationIssue]) -> None:+ if not _is_page_size(page_size):+ issues.append(+ ValidationIssue(+ severity="error",+ code="page_size_invalid",+ path=path,+ message="page_size must contain width and height.",+ )+ )+ return+ if float(page_size[0]) <= 0 or float(page_size[1]) <= 0:+ issues.append(_invalid_value(path, "page_size width and height must be positive."))+++def _validate_title_level(block: Block, path: str, issues: list[ValidationIssue]) -> None:+ if block.level is None:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="title_level_missing",+ path=path,+ message="title block should provide a positive integer level.",+ )+ )+ return+ if not _is_int(block.level) or block.level < 1:+ issues.append(+ ValidationIssue(+ severity="error",+ code="title_level_invalid",+ path=path,+ message="title level must be a positive integer.",+ )+ )+++def _validate_span_content(span: Span, path: str, issues: list[ValidationIssue]) -> None:+ if span.type in TEXT_SPAN_TYPES and not span.content:+ issues.append(+ ValidationIssue(+ severity="warning",+ code="span_content_missing",+ path=f"{path}.content",+ message="text span should provide content.",+ )+ )+ elif span.type in IMAGE_SPAN_TYPES and not (span.image_path or span.image_base64 or span.html):+ issues.append(+ ValidationIssue(+ severity="warning",+ code="span_image_missing",+ path=path,+ message="image span should provide image_path, image_base64, or html.",+ )+ )+ elif span.type in TABLE_SPAN_TYPES and not (span.html or span.content):+ issues.append(+ ValidationIssue(+ severity="warning",+ code="span_table_missing",+ path=path,+ message="table span should provide html or content.",+ )+ )+ elif span.type in EQUATION_SPAN_TYPES and not (span.content or span.latex):+ issues.append(+ ValidationIssue(+ severity="warning",+ code="span_equation_missing",+ path=path,+ message="equation span should provide content or latex.",+ )+ )+++def _is_bbox(bbox: object) -> bool:+ return (+ isinstance(bbox, tuple | list)+ and len(bbox) == 4+ and all(isinstance(v, int | float) and not isinstance(v, bool) for v in bbox)+ )+++def _is_page_size(page_size: object) -> bool:+ return (+ isinstance(page_size, tuple | list)+ and len(page_size) == 2+ and all(isinstance(v, int | float) and not isinstance(v, bool) for v in page_size)+ )+++def _is_int(value: object) -> bool:+ return isinstance(value, int) and not isinstance(value, bool)+++def _has_field(obj: object, name: str) -> bool:+ return hasattr(obj, name)+++def _missing(path: str) -> ValidationIssue:+ return ValidationIssue(+ severity="error",+ code="missing_required_field",+ path=path,+ message=f"{path} is required.",+ )+++def _invalid_type(path: str, expected: str) -> ValidationIssue:+ return ValidationIssue(+ severity="error",+ code="invalid_type",+ path=path,+ message=f"{path} must be {expected}.",+ )+++def _invalid_value(path: str, message: str) -> ValidationIssue:+ return ValidationIssue(+ severity="error",+ code="invalid_value",+ path=path,+ message=message,+ )diff --git a/mineru/schema/middle_json/envelope.py b/mineru/schema/middle_json/envelope.pynew file mode 100644index 00000000..96d5b328--- /dev/null+++ b/mineru/schema/middle_json/envelope.py@@ -0,0 +1,6 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++MIDDLE_JSON_SCHEMA_VERSION: str = "1.0"++__all__ = ["MIDDLE_JSON_SCHEMA_VERSION"]diff --git a/pyproject.toml b/pyproject.tomlindex 6b4f6c33..855a6f12 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -58,13 +58,23 @@ dependencies = ["pylatexenc>=2.10,<3","lxml>=4.0.0,<7.0.0","openpyxl>=3.1.5,<4",+ "aiosqlite>=0.20.0,<1",+ "fnvhash>=0.2.1,<1",+ "watchfiles>=1.0.0,<2","fastapi","python-multipart","uvicorn",- "lxml-stubs",+ "pydantic>=2.0.0",+ "typer>=0.9.0",+ "rich>=13.0.0",+ "jieba>=0.42.1",+ "onnxruntime>=1.17.0",][project.optional-dependencies]+dev = [+ "lxml-stubs",+]test = ["mineru[core]","pytest",@@ -99,7 +109,6 @@ pipeline = ["torch>=2.6.0,<3","torchvision","transformers>=4.57.3,<5.0.0",- "onnxruntime>1.17.0",]gradio = ["gradio>=5.49.1,!=6.0.0,!=6.0.1,!=6.0.2,!=6.1.0,!=6.2.0,!=6.3.0,!=6.4.0,!=6.5.0,!=6.5.1,!=6.6.0,!=6.7.0,<6.9.0",@@ -144,6 +153,7 @@ namespaces = false[tool.setuptools.package-data]"mineru" = ["resources/**"]+"mineru.doclib.migrations" = ["*.sql"]"mineru.model.utils.pytorchocr.utils" = ["resources/**"][tool.setuptools]diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex 07240df0..869f3e65 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -1,15 +1,23 @@from __future__ import annotations+import jsonfrom pathlib import Pathfrom typing import Anyfrom typer.testing import CliRunner-from mineru.cli_next.commands import config, list_resources, parse, show+from mineru.cli_next.commands import config, list_resources, parse, read, server, show+from mineru.cli_next.commands import cleanup as cleanup_cmd+from mineru.cli_next.commands import search as search_mod+from mineru.cli_next.commands import watch as watch_cmdfrom mineru.cli_next.main import appfrom mineru.doclib.types import (+ ContentAsset,+ ContentNextRequest,+ ContentRequestScope,ConfigSetResponse,DocInfo,+ DocContentResponse,FileInfo,FileInfoResponse,ListParsesResponse,@@ -24,13 +32,27 @@ runner = CliRunner()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"])+ read_result = runner.invoke(app, ["read", "--help"])info_result = runner.invoke(app, ["info", "--help"])assert list_result.exit_code == 0assert show_result.exit_code == 0+ assert read_result.exit_code == 0assert info_result.exit_code != 0+def test_parse_and_read_help_document_output_parent_creation() -> None:+ parse_result = runner.invoke(app, ["parse", "--help"])+ read_result = runner.invoke(app, ["read", "--help"])++ assert parse_result.exit_code == 0+ assert read_result.exit_code == 0+ assert "creates parent" in parse_result.output+ assert "directories" in parse_result.output+ assert "creates parent" in read_result.output+ assert "directories" in read_result.output++def test_config_rules_tree_uses_explicit_resource_names_and_remove() -> None:exclude_rules = runner.invoke(app, ["config", "exclude-rules", "--help"])exclude_legacy = runner.invoke(app, ["config", "exclude", "--help"])@@ -118,6 +140,16 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_pcalls.append(kwargs)return ListParsesResponse(parses=[old_failed, new_done], total=2, limit=50, offset=0)+ def get_doc_content(self, *args: Any, **kwargs: Any) -> DocContentResponse:+ return DocContentResponse(+ sha256="a" * 64,+ short_id="aaaaaaa",+ tier="pro",+ format="markdown",+ content="parsed",+ request_scope=ContentRequestScope(page_range="1~10", after=None, limit=30000),+ )+monkeypatch.setattr(parse, "DoclibClient", _Client)result = runner.invoke(app, ["parse", str(source), "--remote", "--wait", "1", "--json"])@@ -125,6 +157,181 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_passert result.exit_code == 0assert calls == [{"ids": [3]}]assert "old failure" not in result.output+ assert "Parse status:" not in result.output+ payload = json.loads(result.output)+ assert payload["parse"]["status"] == "done"+ assert payload["parse"]["wait_parse_ids"] == [3]+ assert payload["content"]["content"] == "parsed"+++def test_parse_json_no_wait_wraps_parse_and_null_content(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:+ return ParseResponse(+ sha256="a" * 64,+ tier="flash",+ page_range="1~1",+ status="pending",+ wait_parse_ids=[3],+ created_parse_ids=[3],+ )++ monkeypatch.setattr(parse, "DoclibClient", _Client)++ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--no-wait", "--json"])++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["parse"]["status"] == "pending"+ assert payload["parse"]["wait_parse_ids"] == [3]+ assert payload["content"] is None+++def test_parse_expands_user_home_in_input_path(monkeypatch: Any, tmp_path: Path) -> None:+ home = tmp_path / "home"+ source = home / "mineru-e2e-test" / "sample.pdf"+ source.parent.mkdir(parents=True)+ source.write_bytes(b"%PDF-1.7\n")+ seen_paths: list[str] = []++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 90++ def ensure_parse(self, request: Any) -> ParseResponse:+ seen_paths.append(request.path)+ return ParseResponse(+ sha256="a" * 64,+ tier="flash",+ page_range="1~1",+ status="pending",+ wait_parse_ids=[3],+ created_parse_ids=[3],+ )++ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setattr(parse, "DoclibClient", _Client)++ result = runner.invoke(app, ["parse", "~/mineru-e2e-test/sample.pdf", "--tier", "flash", "--no-wait", "--json"])++ assert result.exit_code == 0+ assert seen_paths == [str(source.resolve())]+++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")+ output = tmp_path / "nested" / "out.md"++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 90++ 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:+ Path(request.output).write_text("exported", encoding="utf-8")+ return type("Exported", (), {"output": request.output})()++ monkeypatch.setattr(parse, "DoclibClient", _Client)++ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--output", str(output), "--json"])++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["parse"]["status"] == "done"+ assert payload["content"] is None+ assert payload["output"] == {"status": "written", "path": str(output.resolve())}+ assert output.read_text(encoding="utf-8") == "exported"+ assert "Written to" not in result.output+++def test_parse_wait_status_line_is_verbose_only(monkeypatch: Any, tmp_path: Path) -> None:+ source = tmp_path / "demo.pdf"+ source.write_bytes(b"%PDF-1.7\n")++ done = ParseInfo(+ id=3,+ sha256="a" * 64,+ tier="flash",+ page_range="1~1",+ status="done",+ privacy="local",+ via="local",+ created_at=3,+ updated_at=4,+ done_at=4,+ )++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 31++ def ensure_parse(self, request: Any) -> ParseResponse:+ return ParseResponse(+ sha256="a" * 64,+ tier="flash",+ page_range="1~1",+ status="pending",+ wait_parse_ids=[3],+ created_parse_ids=[3],+ )++ def list_parses(self, **kwargs: Any) -> ListParsesResponse:+ return ListParsesResponse(parses=[done], total=1, limit=50, offset=0)++ def get_doc_content(self, *args: Any, **kwargs: Any) -> DocContentResponse:+ return DocContentResponse(+ sha256="a" * 64,+ short_id="aaaaaaa",+ tier="flash",+ format="markdown",+ content="parsed",+ request_scope=ContentRequestScope(locator="doc:aaaaaaa/tier:flash", context=0, limit=30000),+ )++ monkeypatch.setattr(parse, "DoclibClient", _Client)+ monkeypatch.setattr(parse.time, "sleep", lambda seconds: None)++ default_result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--wait", "1"])+ verbose_result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--wait", "1", "--verbose"])++ assert default_result.exit_code == 0+ assert "Parse status:" not in default_result.output+ assert "parsed" in default_result.output+ assert verbose_result.exit_code == 0+ assert "Parse status: done" in verbose_result.output+ assert "parsed" in verbose_result.output+++def test_parse_json_error_output_is_machine_readable(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 == 31++ def ensure_parse(self, request: Any) -> ParseResponse:+ raise RuntimeError(+ "('quality_tier_unavailable', 'No standard or pro engine available. Use --tier flash.', None)"+ )++ monkeypatch.setattr(parse, "DoclibClient", _Client)++ result = runner.invoke(app, ["parse", str(source), "--wait", "1", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "quality_tier_unavailable"+ assert "No standard or pro engine available" in payload["error"]["message"]def test_show_file_uses_get_file_by_path(monkeypatch: Any, tmp_path: Path) -> None:@@ -196,6 +403,39 @@ def test_config_set_uses_key_path_and_value_body(monkeypatch: Any) -> None:assert calls == [("parse_server.local.mode", "managed")]+def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(monkeypatch: Any, tmp_path: Path) -> None:+ popen_calls: list[dict[str, Any]] = []+ log_path = tmp_path / "mineru.log"++ class _Proc:+ pid = 12345++ def kill(self) -> None:+ popen_calls.append({"kill": True})++ def _popen(*args: Any, **kwargs: Any) -> _Proc:+ popen_calls.append({"args": args, "kwargs": kwargs})+ assert kwargs["stdout"] is not server.subprocess.DEVNULL+ assert kwargs["stderr"] is not server.subprocess.DEVNULL+ kwargs["stderr"].write("child failed\n")+ kwargs["stderr"].flush()+ return _Proc()++ monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_wait_for_sock", lambda: False)+ monkeypatch.setattr(server, "_socket_path", lambda: str(tmp_path / "mineru.sock"))+ monkeypatch.setattr(server, "_server_log_path", lambda: str(log_path))+ monkeypatch.setattr(server.subprocess, "Popen", _popen)++ result = runner.invoke(app, ["server", "start"])++ assert result.exit_code == 1+ assert "See log:" in result.output+ assert "mineru.log" in result.output+ assert "child failed\n" in log_path.read_text(encoding="utf-8")+ assert popen_calls[-1] == {"kill": True}++def test_parse_content_read_failure_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:source = tmp_path / "demo.txt"source.write_text("hello", encoding="utf-8")@@ -217,3 +457,261 @@ def test_parse_content_read_failure_exits_nonzero(monkeypatch: Any, tmp_path: Paassert result.exit_code == 1assert "Failed to read content: content missing" in result.output+++def test_read_passes_locator_parameters_to_doclib_client(monkeypatch: Any) -> None:+ calls: list[tuple[str, dict[str, Any]]] = []++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 60++ def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ calls.append((locator, kwargs))+ return DocContentResponse(+ sha256="a" * 64,+ short_id="ab12cd3",+ tier="standard",+ format="markdown",+ content="hello",+ request_scope=ContentRequestScope(locator=locator, context=kwargs["context"], limit=kwargs["limit"]),+ )++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(+ app,+ ["read", "doc:ab12cd3/tier:standard/page:4", "--context", "2", "--limit", "123", "--format", "markdown"],+ )++ assert result.exit_code == 0+ assert calls == [+ (+ "doc:ab12cd3/tier:standard/page:4",+ {"context": 2, "limit": 123, "format": "markdown", "no_marker": False},+ )+ ]+ assert "hello" in result.output+++def test_read_json_output_preserves_locator_next_request(monkeypatch: Any) -> None:+ 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="markdown",+ content="hello",+ request_scope=ContentRequestScope(locator=locator, context=0, limit=30000),+ next_request=ContentNextRequest(locator="doc:ab12cd3/tier:standard/page:5"),+ )++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--json"])++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["next_request"]["locator"] == "doc:ab12cd3/tier:standard/page:5"+++def test_read_json_error_output_is_machine_readable(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 60++ def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ raise RuntimeError("('not_cached', 'Requested parsed content is not cached.', 'locator')")++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "not_cached"+ assert "Error:" not in result.output+++def test_read_json_output_writes_markdown_file_and_returns_output_object(monkeypatch: Any, tmp_path: Path) -> None:+ output = tmp_path / "nested" / "read.md"++ 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="markdown",+ content="hello",+ request_scope=ContentRequestScope(locator=locator, context=0, limit=30000),+ )++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--output", str(output), "--json"])++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["content"] is None+ assert payload["output"] == {"status": "written", "path": str(output.resolve())}+ assert output.read_text(encoding="utf-8") == "hello"+ assert "Written to" not in result.output+++def test_read_json_output_writes_image_file_and_returns_output_object(monkeypatch: Any, tmp_path: Path) -> None:+ asset = tmp_path / "server.png"+ asset.write_bytes(b"png-bytes")+ 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=ContentAsset(path=str(asset), mime_type="image/png"),+ )++ 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 == 0+ payload = json.loads(result.output)+ assert payload["content"] is None+ assert payload["output"] == {"status": "written", "path": str(output.resolve())}+ assert output.read_bytes() == b"png-bytes"+ assert "Written to" 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")+ output = tmp_path / "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=ContentAsset(path=str(asset), mime_type="image/png"),+ )++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--format", "image", "--output", str(output)])++ assert result.exit_code == 0+ assert output.read_bytes() == b"png-bytes"+ assert "Written to" in result.output+ assert str(output) in result.output.replace("\n", "")+++def test_search_json_error_output_is_machine_readable(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 10++ def search(self, *args: Any, **kwargs: Any) -> Any:+ raise RuntimeError("('quality_tier_unavailable', 'No standard or pro engine available.', 'tier')")++ monkeypatch.setattr(search_mod, "DoclibClient", _Client)++ result = runner.invoke(app, ["search", "needle", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "quality_tier_unavailable"+ assert "Error:" not in result.output+++def test_watch_add_json_error_output_is_machine_readable(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 30++ def add_watch(self, request: Any) -> Any:+ raise RuntimeError("('invalid_request', 'Watch path does not exist.', 'path')")++ monkeypatch.setattr(watch_cmd, "DoclibClient", _Client)++ result = runner.invoke(app, ["watch", "add", "/not/exist", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "invalid_request"+ assert payload["error"]["param"] == "path"+ assert "Error:" not in result.output+++def test_config_get_json_error_output_is_machine_readable(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 30++ def get_config_key(self, key: str) -> Any:+ raise RuntimeError("('invalid_request', 'Unknown config key.', 'key')")++ monkeypatch.setattr(config, "DoclibClient", _Client)++ result = runner.invoke(app, ["config", "get", "not.a.real.key", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "invalid_request"+ assert payload["error"]["param"] == "key"+ assert "Error:" not in result.output+++def test_cleanup_temp_json_error_output_is_machine_readable(monkeypatch: Any) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 30++ def cleanup_temp_files(self, request: Any) -> Any:+ raise RuntimeError("('invalid_request', 'older_than must be >= 0', 'older_than')")++ monkeypatch.setattr(cleanup_cmd, "DoclibClient", _Client)++ result = runner.invoke(app, ["cleanup", "temp", "--older-than", "-1", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "invalid_request"+ assert payload["error"]["param"] == "older_than"+ assert "Error:" not in result.output+++def test_server_status_json_not_running_returns_state_json(monkeypatch: Any) -> None:+ monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_socket_path", lambda: "/tmp/mineru.sock")+ monkeypatch.setattr(server.config.doclib, "data_dir", "~/MinerU")++ result = runner.invoke(app, ["server", "status", "--json"])++ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["running"] is False+ assert payload["socket_path"] == "/tmp/mineru.sock"+ assert "Server is not running." not in result.outputdiff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex d0dfdf62..42d2d484 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -1,7 +1,12 @@import asyncio+import tomllib+from pathlib import Pathimport pytest+from fastapi.testclient import TestClient+from mineru.config import PatchedConfig+from mineru.doclib import app as doclib_appfrom mineru.doclib.app import _assert_required_schemafrom mineru.doclib.core.db import DatabaseManager@@ -20,3 +25,36 @@ def test_required_schema_check_fails_before_migration_and_passes_after(tmp_path)assert row == {"name": "parses"}asyncio.run(_run())+++def test_doclib_runtime_dependencies_are_in_base_install() -> None:+ pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"+ pyproject = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))+ dependencies = pyproject["project"]["dependencies"]+ dependency_names = {dependency.split(">", 1)[0].split("=", 1)[0].lower() for dependency in dependencies}++ assert "aiosqlite" in dependency_names+ assert "fnvhash" in dependency_names+ assert "watchfiles" in dependency_names+++def test_server_status_reports_configured_socket_path(monkeypatch, tmp_path) -> None:+ cfg = PatchedConfig(+ doclib={+ "data_dir": str(tmp_path),+ "sqlite": {"path": str(tmp_path / "mineru.db")},+ "log": {"path": str(tmp_path / "mineru.log")},+ "uds": {"path": str(tmp_path / "mineru.sock")},+ }+ )++ def _skip_background_task(*args, **kwargs):+ return None++ monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)++ with TestClient(doclib_app.create_app(cfg)) as client:+ response = client.get("/api/v1/server/status")++ assert response.status_code == 200+ assert response.json()["socket_path"] == str(tmp_path / "mineru.sock")diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex fca2fc68..c277e95e 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -34,6 +34,7 @@ from mineru.doclib.server import DoclibServerfrom mineru.doclib.types import ParseResponsefrom mineru.parser import backend_for_tier, resolve_tier_and_backendfrom mineru.parser.base import ParseResult+from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom mineru.types import PageInfo, Tier@@ -314,6 +315,7 @@ def test_compaction_uses_configured_data_dir(tmp_path: Path) -> None:compacted_path = Path(parse_batch_json_path(str(tmp_path), sha256, tier, "1~2", 2000))compacted = json.loads(compacted_path.read_text(encoding="utf-8"))+ assert compacted["schema_version"] == MIDDLE_JSON_SCHEMA_VERSIONassert compacted["pages"] == [older_page, newer_duplicate]assert sorted(path.name for path in compacted_path.parent.glob("*.json")) == ["1~2_2000.json"]@@ -692,15 +694,16 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:service = SearchService(db, fts)now = 1000docs = [- ("1" * 64, "flash", "pdf", "flash.pdf"),- ("2" * 64, "standard", "pdf", "standard.pdf"),- ("3" * 64, "pro", "docx", "pro.docx"),+ ("1" * 64, "flash", "pdf", "flash.pdf", 2),+ ("2" * 64, "standard", "pdf", "standard.pdf", 12),+ ("3" * 64, "pro", "docx", "pro.docx", 23),]- for sha256, tier, file_type, filename in docs:+ for sha256, tier, file_type, filename, page_count in docs:await db.execute(- "INSERT INTO docs (sha256, short_id, size_bytes, file_type, first_seen_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",- (sha256, sha256[:7], 10, file_type, now, now),+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ (sha256, sha256[:7], 10, file_type, page_count, now, now),)await db.execute("INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "@@ -715,10 +718,12 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:assert exact_total == 1assert [row["tier"] for row in exact_results] == ["standard"]+ assert [row["page_count"] for row in exact_results] == [12]assert min_total == 2assert {row["tier"] for row in min_results} == {"standard", "pro"}assert type_total == 1assert [row["filename"] for row in type_results] == ["pro.docx"]+ assert [row["page_count"] for row in type_results] == [23]asyncio.run(_run())@@ -735,8 +740,9 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_pathfor sha256 in (sha_active, sha_deleted):await db.execute(- "INSERT INTO docs (sha256, short_id, size_bytes, file_type, first_seen_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",- (sha256, sha256[:7], 10, "pdf", now, now),+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "+ "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")@@ -762,6 +768,7 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_pathassert total == 2assert paths_by_sha[sha_active] == [str(tmp_path / "active.pdf")]assert paths_by_sha[sha_deleted] == [str(tmp_path / "deleted-only.pdf")]+ assert {row["sha256"]: row["page_count"] for row in results} == {sha_active: 7, sha_deleted: 9}asyncio.run(_run())@@ -778,8 +785,9 @@ def test_find_filters_by_ext(tmp_path: Path) -> None:for sha256, filename, ext in ((sha_pdf, "report.pdf", "pdf"), (sha_docx, "report.docx", "docx")):await db.execute(- "INSERT INTO docs (sha256, short_id, size_bytes, file_type, first_seen_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",- (sha256, sha256[:7], 10, ext, now, now),+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ (sha256, sha256[:7], 10, ext, 11 if ext == "pdf" else 5, now, now),)file_id = await db.execute_insert("INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "@@ -792,6 +800,7 @@ def test_find_filters_by_ext(tmp_path: Path) -> None:assert total == 1assert [row["filename"] for row in results] == ["report.pdf"]+ assert [row["page_count"] for row in results] == [11]asyncio.run(_run())diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.pyindex 3eba3244..e2e797e2 100644--- a/tests/unittest/test_doclib_interface_contract.py+++ b/tests/unittest/test_doclib_interface_contract.py@@ -1,13 +1,18 @@import inspect+import asynciofrom typing import get_type_hintsimport pytestfrom pydantic import ValidationError+from mineru.errors import InvalidRequestErrorfrom mineru.doclib.app import create_appfrom mineru.doclib.base import AsyncDoclibInterface, DoclibInterfacefrom mineru.doclib.client import DoclibClient+from mineru.doclib.core.db import DatabaseManagerfrom mineru.doclib.server import DoclibServer+from mineru.doclib.services.cleanup_svc import CleanupService+from mineru.doclib.services.config_svc import ConfigServicefrom mineru.doclib.types import (ConfigResponse,DocInfo,@@ -73,6 +78,7 @@ def test_doclib_interface_declares_expected_methods() -> None:"get_doc_by_path","get_doc","get_doc_content",+ "read_content","export_doc_content","search","find",@@ -185,6 +191,7 @@ def test_interface_app_uses_doclib_server_routes() -> None:assert "/api/v1/parsing-rules/{rule_id}" in route_pathsassert "/api/v1/files" in route_pathsassert "/api/v1/docs" in route_paths+ assert "/api/v1/content" in route_pathsassert "/api/v1/docs/{sha256}/exports" in route_pathsassert "/api/docs" in route_pathsassert "/docs" not in route_paths@@ -198,6 +205,49 @@ def test_interface_app_uses_doclib_server_routes() -> None:assert "parse_content" not in route_names+def test_add_watch_rejects_missing_directory(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "mineru.db"))+ await db.initialize()+ service = ConfigService(db)++ with pytest.raises(InvalidRequestError, match="Watch path does not exist"):+ await service.add_watch(str(tmp_path / "not-exist"))++ asyncio.run(_run())+++def test_forget_watch_root_is_allowed_with_warning(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "mineru.db"))+ await db.initialize()+ watch_root = tmp_path / "watch-root"+ watch_root.mkdir()+ await ConfigService(db).add_watch(str(watch_root))+ service = CleanupService(db, str(tmp_path))++ result = await service.forget_path(str(watch_root), dry_run=True)++ assert result["path"] == str(watch_root)+ assert result["matched_as"] == "none"+ assert result["forgotten_files"] == 0+ assert result["warnings"] == ["Path is a configured watch root and may be rediscovered on the next scan."]++ asyncio.run(_run())+++def test_cleanup_temp_rejects_negative_older_than(tmp_path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "mineru.db"))+ await db.initialize()+ service = CleanupService(db, str(tmp_path))++ with pytest.raises(InvalidRequestError, match="older_than_days must be non-negative"):+ await service.cleanup_temp_files(-1)++ asyncio.run(_run())++def test_core_doclib_schemas_are_instantiable() -> None:parse_request = ParseRequest(path="/tmp/a.pdf", tier=None, page_range="1~5")forget_request = ForgetPathRequest(path="/tmp/a.pdf")@@ -390,6 +440,7 @@ def test_get_semantic_methods_do_not_use_request_body_models() -> None:"list_docs","get_doc_by_path","get_doc_content",+ "read_content","search","find","get_file_by_path",@@ -416,6 +467,7 @@ def test_next_cli_doclib_route_shapes_are_declared() -> None:"list_docs": ("GET", "/docs"),"get_doc_by_path": ("GET", "/docs/by-path"),"get_doc_content": ("GET", "/docs/{sha256}/content"),+ "read_content": ("GET", "/content"),"export_doc_content": ("POST", "/docs/{sha256}/exports"),"get_config": ("GET", "/configs"),"get_config_key": ("GET", "/configs/{key}"),@@ -441,6 +493,7 @@ def test_next_cli_doclib_route_shapes_are_declared() -> None:assert server_route.path == path, method_nameassert "output" not in inspect.signature(DoclibInterface.get_doc_content).parameters+ assert "output" not in inspect.signature(DoclibInterface.read_content).parametersassert "limit" in inspect.signature(DoclibInterface.list_parses).parametersassert "limit" in inspect.signature(DoclibInterface.list_docs).parametersassert "file_type" in inspect.signature(DoclibInterface.list_docs).parametersdiff --git a/tests/unittest/test_middle_json_validator.py b/tests/unittest/test_middle_json_validator.pynew file mode 100644index 00000000..b7884011--- /dev/null+++ b/tests/unittest/test_middle_json_validator.py@@ -0,0 +1,166 @@+from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION, validate_pages+from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span+++def _issue_keys(issues):+ return {(issue.severity, issue.code, issue.path) for issue in issues}+++def _valid_page() -> PageInfo:+ return PageInfo(+ page_idx=0,+ page_size=(100, 200),+ para_blocks=[+ Block(+ index=0,+ type="text",+ bbox=(1.0, 2.0, 20.0, 30.0),+ lines=[+ Line(+ bbox=(1.0, 2.0, 20.0, 30.0),+ spans=[Span(type="text", bbox=(1.0, 2.0, 20.0, 10.0), content="hello")],+ )+ ],+ )+ ],+ )+++def test_middle_json_schema_version_is_public_constant() -> None:+ assert MIDDLE_JSON_SCHEMA_VERSION == "1.0"+++def test_validate_pages_accepts_valid_page_tree() -> None:+ assert validate_pages([_valid_page()]) == []+++def test_validate_pages_reports_missing_required_page_and_block_fields() -> None:+ page = _valid_page()+ delattr(page, "page_idx")+ delattr(page.para_blocks[0], "type")++ issues = validate_pages([page])++ assert ("error", "missing_required_field", "pages[0].page_idx") in _issue_keys(issues)+ assert ("error", "missing_required_field", "pages[0].para_blocks[0].type") in _issue_keys(issues)+++def test_validate_pages_distinguishes_unknown_and_invalid_bbox() -> None:+ page = _valid_page()+ page.para_blocks[0].bbox = (0.0, 0.0, 0.0, 0.0)+ page.para_blocks[0].lines[0].bbox = (3.0, 2.0, 1.0, 4.0)++ issues = validate_pages([page])++ assert ("warning", "bbox_unknown", "pages[0].para_blocks[0].bbox") in _issue_keys(issues)+ assert ("error", "bbox_invalid", "pages[0].para_blocks[0].lines[0].bbox") in _issue_keys(issues)+++def test_validate_pages_recurses_into_child_blocks() -> None:+ page = _valid_page()+ page.para_blocks[0].blocks.append(+ Block(+ index=1,+ type="text",+ bbox=(2.0, 2.0, 10.0, 10.0),+ lines=[Line(bbox=(0.0, 0.0, 0.0, 0.0), spans=[])],+ )+ )++ issues = validate_pages([page])++ assert ("warning", "bbox_unknown", "pages[0].para_blocks[0].blocks[0].lines[0].bbox") in _issue_keys(issues)+++def test_validate_pages_reports_wrong_node_types() -> None:+ page = _valid_page()+ page.para_blocks[0].lines.append(object()) # type: ignore[arg-type]++ issues = validate_pages([object(), page]) # type: ignore[list-item]++ assert ("error", "invalid_type", "pages[0]") in _issue_keys(issues)+ assert ("error", "invalid_type", "pages[1].para_blocks[0].lines[1]") in _issue_keys(issues)+++def test_validate_pages_reports_unknown_block_type_and_bad_title_level() -> None:+ page = _valid_page()+ page.para_blocks[0].type = "unknown_type"+ page.para_blocks.append(+ Block(+ index=1,+ type=BlockType.TITLE,+ bbox=(2.0, 2.0, 20.0, 20.0),+ lines=[Line(bbox=(2.0, 2.0, 20.0, 20.0), spans=[])],+ level=0,+ )+ )++ issues = validate_pages([page])++ assert ("error", "block_type_unknown", "pages[0].para_blocks[0].type") in _issue_keys(issues)+ assert ("error", "title_level_invalid", "pages[0].para_blocks[1].level") in _issue_keys(issues)+++def test_validate_pages_reports_block_index_order_and_duplicates() -> None:+ page = _valid_page()+ page.para_blocks.extend(+ [+ Block(index=2, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),+ Block(index=1, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),+ Block(index=1, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),+ ]+ )++ issues = validate_pages([page])++ assert ("warning", "block_index_out_of_order", "pages[0].para_blocks[2].index") in _issue_keys(issues)+ assert ("error", "block_index_duplicate", "pages[0].para_blocks[3].index") in _issue_keys(issues)+++def test_validate_pages_reports_bbox_outside_page_size() -> None:+ page = _valid_page()+ page.para_blocks[0].bbox = (1.0, 2.0, 200.0, 30.0)++ issues = validate_pages([page])++ assert ("warning", "bbox_out_of_page", "pages[0].para_blocks[0].bbox") in _issue_keys(issues)+++def test_validate_pages_reports_span_content_contracts() -> None:+ page = PageInfo(+ page_idx=0,+ para_blocks=[+ Block(+ index=0,+ type=BlockType.TEXT,+ bbox=(1.0, 1.0, 10.0, 10.0),+ lines=[+ Line(+ bbox=(1.0, 1.0, 10.0, 10.0),+ spans=[+ Span(type=ContentType.TEXT, bbox=(1.0, 1.0, 2.0, 2.0)),+ Span(type=ContentType.IMAGE, bbox=(2.0, 1.0, 3.0, 2.0)),+ Span(type=ContentType.TABLE, bbox=(3.0, 1.0, 4.0, 2.0)),+ Span(type=ContentType.INTERLINE_EQUATION, bbox=(4.0, 1.0, 5.0, 2.0)),+ ],+ )+ ],+ )+ ],+ )++ issues = validate_pages([page])++ assert ("warning", "span_content_missing", "pages[0].para_blocks[0].lines[0].spans[0].content") in _issue_keys(issues)+ assert ("warning", "span_image_missing", "pages[0].para_blocks[0].lines[0].spans[1]") in _issue_keys(issues)+ assert ("warning", "span_table_missing", "pages[0].para_blocks[0].lines[0].spans[2]") in _issue_keys(issues)+ assert ("warning", "span_equation_missing", "pages[0].para_blocks[0].lines[0].spans[3]") in _issue_keys(issues)+++def test_validate_pages_warns_legacy_page_backend() -> None:+ page = _valid_page()+ page._backend = "pipeline"++ issues = validate_pages([page])++ assert ("warning", "legacy_backend", "pages[0]._backend") in _issue_keys(issues)diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex a52b18cf..141cf9ce 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -1,6 +1,9 @@from dataclasses import fields+import jsonfrom mineru.parser.base import ParseResult+from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION+from mineru.types import Block, Line, PageInfo, Spandef test_parse_result_does_not_expose_backend_version_or_file_name() -> None:@@ -9,3 +12,110 @@ def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:assert "_backend" not in field_namesassert "_version_name" not in field_namesassert "_file_name" not in field_names+++def test_parse_result_from_dict_restores_pages() -> None:+ result = ParseResult(+ pages=[+ PageInfo(+ page_idx=3,+ page_size=(640, 480),+ para_blocks=[+ Block(+ index=0,+ type="text",+ bbox=(1.0, 2.0, 3.0, 4.0),+ lines=[+ Line(+ bbox=(1.0, 2.0, 3.0, 4.0),+ spans=[Span(type="text", bbox=(1.0, 2.0, 3.0, 4.0), content="hello")],+ )+ ],+ )+ ],+ )+ ]+ )++ restored = ParseResult.from_dict(result.to_dict())++ assert restored.to_dict() == result.to_dict()+ assert restored.pages[0].page_size == (640, 480)+ assert restored.pages[0].para_blocks[0].bbox == (1.0, 2.0, 3.0, 4.0)+ assert restored.pages[0].para_blocks[0].lines[0].spans[0].content == "hello"+++def test_parse_result_to_dict_includes_schema_version_without_meta() -> None:+ result = ParseResult(pages=[PageInfo(page_idx=0)])++ payload = result.to_dict()++ assert payload["schema_version"] == MIDDLE_JSON_SCHEMA_VERSION+ assert "pages" in payload+ assert "_meta" not in payload+++def test_parse_result_from_dict_accepts_pdf_info_and_preserves_page_backend() -> None:+ restored = ParseResult.from_dict(+ {+ "pdf_info": [+ {+ "page_idx": 0,+ "page_size": [100, 200],+ "_backend": "pipeline",+ "preproc_blocks": [+ {+ "index": 0,+ "type": "title",+ "bbox": [1.0, 2.0, 3.0, 4.0],+ "level": 1,+ "lines": [+ {+ "bbox": [1.0, 2.0, 3.0, 4.0],+ "spans": [+ {+ "type": "text",+ "bbox": [1.0, 2.0, 3.0, 4.0],+ "content": "Heading",+ }+ ],+ }+ ],+ }+ ],+ }+ ]+ }+ )++ assert len(restored.pages) == 1+ assert restored.pages[0]._backend == "pipeline"+ assert restored.pages[0].page_size == (100, 200)+ assert restored.pages[0].preproc_blocks[0].level == 1+++def test_parse_result_from_json_restores_pages() -> None:+ data = {+ "pages": [+ {+ "page_idx": 0,+ "para_blocks": [+ {+ "index": 0,+ "type": "text",+ "bbox": [0.0, 0.0, 0.0, 0.0],+ "lines": [+ {+ "bbox": [0.0, 0.0, 0.0, 0.0],+ "spans": [{"type": "text", "bbox": [0.0, 0.0, 0.0, 0.0], "content": "round trip"}],+ }+ ],+ }+ ],+ }+ ]+ }++ restored = ParseResult.from_json(json.dumps(data))++ assert restored.to_dict() == ParseResult.from_dict(data).to_dict()diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex de5c5e3c..c26190f4 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -2,6 +2,7 @@ from pathlib import Pathimport inspectimport pytest+from fastapi.testclient import TestClientfrom pydantic import ValidationErrorfrom mineru.parser.api_client import MinerUApiParser, _parse_result_from_job@@ -148,6 +149,25 @@ def test_create_job_request_accepts_new_format_names_and_rejects_options() -> No)+def test_local_parse_server_rejects_callback(tmp_path: Path) -> None:+ app = create_app(upload_dir=str(tmp_path))+ client = TestClient(app)++ response = client.post(+ "/v1/parse/jobs",+ json={+ "files": [{"source": {"type": "local", "path": str(tmp_path / "demo.pdf")}}],+ "callback": {"url": "https://example.com/mineru-webhook", "secret": "secret"},+ },+ )++ assert response.status_code == 400+ body = response.json()["detail"]+ assert body["error"]["code"] == "invalid_request"+ assert "Webhook callback is not supported" in body["error"]["message"]+ assert app.state.job_store._jobs == {}++def test_output_files_expose_new_names_without_inline_content() -> None:ref = OutputFileRef(file_id="file-1", bytes=12)outputs = OutputFiles(middle_json=ref, structured_content=ref)