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
refactor doclib CLI API contracts
jinzhenjdd94c2148654
diff --git a/NEXT-CLI.md b/NEXT-CLI.mdindex 4e136298..9182d3b3 100644--- a/NEXT-CLI.md+++ b/NEXT-CLI.md@@ -536,11 +536,11 @@ mineru config parse-server remote.api-key <key> # 远程 API Key## 核心表```-files 文件实例(path, sha256, size, mtime, watch_id, scan_status)+files 文件实例(path, sha256, size, mtime, watch_id, status)docs 文档内容(sha256 主键, parse_status, parse_tier, parsed_pages)fts_index 全文搜索索引(解析产出的文本)fts_filenames 文件名搜索索引-watch_targets 监控目录配置+watches 监控目录配置rules 解析规则(parsing-rules + exclude)config KV 全局配置```diff --git a/NEXT-DESIGN.md b/NEXT-DESIGN.mdindex f6352dd5..500f9f5b 100644--- a/NEXT-DESIGN.md+++ b/NEXT-DESIGN.md@@ -145,8 +145,8 @@ CREATE TABLE files (size_bytes INTEGER NOT NULL,mtime_ms INTEGER NOT NULL,sha256 TEXT REFERENCES docs(sha256),- watch_id INTEGER REFERENCES watch_targets(id),- scan_status TEXT NOT NULL DEFAULT 'active', -- active / deleted / unreachable+ watch_id INTEGER REFERENCES watches(id),+ status TEXT NOT NULL DEFAULT 'active', -- active / deleted / unreachablelocked_at INTEGER, -- Unix epoch mserror_code TEXT, -- 错误码,e.g. "permission_denied"error_msg TEXT, -- 人类可读错误描述@@ -157,7 +157,7 @@ CREATE TABLE files (CREATE INDEX idx_files_sha256 ON files(sha256);CREATE INDEX idx_files_watch_id ON files(watch_id);-CREATE INDEX idx_files_scan_status ON files(scan_status);+CREATE INDEX idx_files_status ON files(status);```#### docs — 文档内容(SHA-256 去重)@@ -173,7 +173,7 @@ CREATE TABLE docs (author TEXT,subject TEXT,keywords TEXT,- is_scanned INTEGER NOT NULL DEFAULT 0,+ is_image_based INTEGER NOT NULL DEFAULT 0,meta_tier TEXT, -- 当前 metadata 的来源 tier,NULL 表示尚未解析error_code TEXT, -- 内容身份级错误码,e.g. "metadata_failed"error_msg TEXT, -- 人类可读错误描述@@ -333,17 +333,17 @@ CREATE VIRTUAL TABLE fts_filenames USING fts5();```-#### watch_targets — 监控目录+#### watches — 监控目录```sql-CREATE TABLE watch_targets (+CREATE TABLE watches(id INTEGER PRIMARY KEY, -- 路径的 hash,稳定 IDpath TEXT NOT NULL UNIQUE,label TEXT,removable INTEGER NOT NULL DEFAULT 0,enabled INTEGER NOT NULL DEFAULT 1,recursive INTEGER NOT NULL DEFAULT 0,- watch_status TEXT NOT NULL DEFAULT 'active', -- active / unreachable+ status TEXT NOT NULL DEFAULT 'active', -- active / unreachableunreachable_at INTEGER, -- Unix epoch mslast_scan_at INTEGER, -- Unix epoch mslast_scan_files INTEGER DEFAULT 0@@ -437,7 +437,7 @@ SET locked_at = ?WHERE id = (SELECT id FROM filesWHERE sha256 IS NULL- AND scan_status = 'active'+ AND status = 'active'AND (locked_at IS NULL OR locked_at < ?)ORDER BY first_seen_at ASCLIMIT 1@@ -647,12 +647,12 @@ managed 模式崩溃恢复:DeviceMonitor 每 5 秒检测:→ os.stat(watch_path)→ 成功(设备插入/恢复):- UPDATE watch_targets SET watch_status='active', unreachable_at=NULL- UPDATE files SET scan_status='active' WHERE watch_id=? AND scan_status='unreachable'+ UPDATE watches SET status='active', unreachable_at=NULL+ UPDATE files SET status='active' WHERE watch_id=? AND status='unreachable'触发增量扫描→ 失败(设备拔出):- UPDATE watch_targets SET watch_status='unreachable', unreachable_at=?- UPDATE files SET scan_status='unreachable' WHERE watch_id=? AND scan_status='active'+ UPDATE watches SET status='unreachable', unreachable_at=?+ UPDATE files SET status='unreachable' WHERE watch_id=? AND status='active'正在进行的解析任务标记特殊错误(非永久失败,设备恢复后可重试)```@@ -793,7 +793,7 @@ mineru config parse-server remote.api-key sk-xxx### 7.4 Watch 目录-通过 `watch_targets` 表管理,CLI 操作:+通过 `watches` 表管理,CLI 操作:```bashmineru watch add ~/Documentsdiff --git a/docs/next/architecture.md b/docs/next/architecture.mdindex 6a1d0dcb..eac8528f 100644--- a/docs/next/architecture.md+++ b/docs/next/architecture.md@@ -105,11 +105,11 @@ doclib 的核心数据模型围绕三张表展开:| `filename` / `ext` / `size_bytes` / `mtime_ms` | 文件基础信息 || `sha256` | 入库后关联到 `docs` || `watch_id` | 来源 watch 目录 |-| `scan_status` | `active` / `deleted` / `unreachable` |+| `status` | `active` / `deleted` / `unreachable` || `locked_at` | IngestWorker 抢占锁 || `error_code` / `error_msg` | 文件级错误 |-`scan_status` 表达路径可达性,而不是 doc 生命周期:+`status` 表达路径可达性,而不是 doc 生命周期:| 状态 | 含义 | 默认搜索可见 | 是否保护 doc ||------|------|--------------|--------------|@@ -130,7 +130,7 @@ doclib 的核心数据模型围绕三张表展开:| `sha256` | 文档内容主键 || `file_type` / `page_count` | 入库阶段尽量提取;`file_type` 是短类型名,例如 `pdf` / `docx` || `title` / `author` / `subject` / `keywords` | 文档 metadata,做保护性截断 |-| `is_scanned` | 文档属性 |+| `is_image_based` | 文档是否以页面图片为主,缺少可用文字层 || `meta_tier` | 当前 metadata 来源 tier || `error_code` / `error_msg` | 内容身份级错误,例如加密、损坏、metadata 失败 |@@ -161,7 +161,7 @@ metadata 更新规则:入库阶段写基础 metadata;解析完成后,只|----|------|| `fts_contents` | 内容全文搜索,只保留最高 tier 文本 || `fts_filenames` | 文件名搜索 |-| `watch_targets` | 监控目录、可插拔设备状态 |+| `watches` | 监控目录、可插拔设备状态 || `exclude_rules` | exclude 路径规则 || `parsing_rules` | parsing-rule 路径规则 || `config` | SQLite KV 配置 |@@ -207,7 +207,7 @@ SQLite 运行在 WAL 模式,使用 FTS5 提供搜索能力。每次 DB 操作3. 如果 path 不存在于 active `files`,插入记录并设置 `sha256=NULL`。4. 如果 path 已存在且 `mtime_ms`、`size_bytes` 均未变化,不做重新入库。5. 如果 path 已存在但 `mtime_ms` 或 `size_bytes` 变化,更新文件 stat,清空 `files.sha256`、锁和错误字段。-6. `IngestWorker` 通过原子 SQL 抢占 `scan_status=active AND sha256 IS NULL` 的文件。+6. `IngestWorker` 通过原子 SQL 抢占 `status=active AND sha256 IS NULL` 的文件。`birthtime_ms` 暂不进入 P0。文件创建时间在不同平台上的语义和可用性不一致,目前还没有明确的产品或 Agent 行为依赖它;P0 不记录该字段,也不使用它参与文件变化判定。7. 计算 SHA256,提取 metadata。@@ -413,7 +413,7 @@ Watch 默认发现文档、Office、电子书、Apple 文档、文本、网页deleted file cleanup 与 orphan doc cleanup 是两个独立动作。-- deleted file cleanup 只删除 `scan_status='deleted'` 的 file row,并清理对应 `fts_filenames`。+- deleted file cleanup 只删除 `status='deleted'` 的 file row,并清理对应 `fts_filenames`。- 手动 cleanup deleted 立即删除所有 deleted file rows。- 后台 cleanup deleted 固定保留 7 天后删除。- deleted cleanup 不自动删除 docs、parses、parsed JSON 或 `fts_contents`。diff --git a/docs/next/cli/mineru-library.md b/docs/next/cli/mineru-library.mdindex 781244b4..b6b7aa89 100644--- a/docs/next/cli/mineru-library.md+++ b/docs/next/cli/mineru-library.md@@ -149,7 +149,7 @@ mineru cleanup tempdeleted file cleanup:-- 立即删除所有 `scan_status=deleted` 的 file row。+- 立即删除所有 `status=deleted` 的 file row。- 删除 file row 时删除对应 `fts_filenames`。- 不自动删除 docs、parses、parsed JSON 或 `fts_contents`。- 第一版不提供 `--older-than` 参数;后台任务固定保留 deleted file row 7 天后再清理。@@ -230,7 +230,7 @@ mineru watch rescan ~/Documentsmineru watch rescan 3```-`mineru watch rescan <watch-path-or-id>` 只接受已配置 watch root 或 watch id。它创建 `kind=watch` 的后台 scan task,会更新 `watch_targets.last_scan_at` / `last_scan_files`。+`mineru watch rescan <watch-path-or-id>` 只接受已配置 watch root 或 watch id。它创建 `kind=watch` 的后台 scan task,会更新 `watches.last_scan_at` / `last_scan_files`。如果只想扫描 watch 下的某个子目录或任意 path,使用 `mineru scan <path>`。diff --git a/docs/next/config.md b/docs/next/config.mdindex 1ce71dc1..3584bbe6 100644--- a/docs/next/config.md+++ b/docs/next/config.md@@ -13,7 +13,7 @@MinerU 有两类配置:- **启动前配置**:doclib server 启动之前就必须知道,通常来自文件形式的配置或内置默认值。-- **运行时配置**:doclib server 启动之后可从 SQLite 读取和修改,由 `config`、`watch_targets`、`exclude_rules`、`parsing_rules` 等表承载。+- **运行时配置**:doclib server 启动之后可从 SQLite 读取和修改,由 `config`、`watches`、`exclude_rules`、`parsing_rules` 等表承载。配置必须服务两个产品原则:@@ -61,7 +61,7 @@ MinerU 有两类配置:| 来源 | 例子 | 存储 | 说明 ||------|------|------|------|| SQLite `config` 表 | `watch_default_tier`、`parse_server.local.mode` | KV | doclib 运行时配置 |-| `watch_targets` 表 | watch 目录、可插拔设备状态 | 表结构 | 文件发现配置 |+| `watches` 表 | watch 目录、可插拔设备状态 | 表结构 | 文件发现配置 || `exclude_rules` 表 | exclude | 表结构 | 路径排除规则 || `parsing_rules` 表 | parsing-rules | 表结构 | 路径解析规则 || 当前命令显式参数 | `--tier pro`、`--remote` | 不持久化 | 当前请求覆盖 |diff --git a/docs/next/decisions/0006-doclib-file-change-detection.md b/docs/next/decisions/0006-doclib-file-change-detection.mdindex 4b433eac..b12be6ec 100644--- a/docs/next/decisions/0006-doclib-file-change-detection.md+++ b/docs/next/decisions/0006-doclib-file-change-detection.md@@ -40,7 +40,7 @@ doclib 引入统一的轻量文件发现/刷新步骤,建议命名为 `discove### 重新入库-`IngestWorker` 只处理 `scan_status=active AND sha256 IS NULL` 的文件。+`IngestWorker` 只处理 `status=active AND sha256 IS NULL` 的文件。处理步骤:@@ -66,8 +66,8 @@ watch 对路径变化的职责:watch scan 的 P0 策略是不新增 `files.last_seen_at` 字段,而是执行两阶段刷新:1. scan 开始时先检查 watch root 是否可达。-2. 如果 watch root 不可达,只更新 `watch_targets.watch_status=unreachable`,不逐个刷新该 watch 下的所有 files。-3. 如果 watch root 可达,先读取该 watch 下 `scan_status=active` 的已知 file paths,逐个调用统一发现方法;这一步用于发现已删除文件。+2. 如果 watch root 不可达,只更新 `watches.status=unreachable`,不逐个刷新该 watch 下的所有 files。+3. 如果 watch root 可达,先读取该 watch 下 `status=active` 的已知 file paths,逐个调用统一发现方法;这一步用于发现已删除文件。4. 然后再执行 `os.walk()`,对当前文件系统中存在的文件逐个调用统一发现方法;这一步用于发现新文件和变化文件。这个方案会让已知且仍存在的文件在一轮 scan 中可能被 stat 两次,但它避免了:@@ -87,15 +87,15 @@ watch scan 的 P0 策略是不新增 `files.last_seen_at` 字段,而是执行规则如下:- `FileNotFoundError` 表示 path 缺失,进入 deleted / unreachable 判断。-- `PermissionError` 不表示 deleted,应写入 `files.error_code=file_permission_denied` 和 `files.error_msg`,保留当前 `scan_status`。-- 其他 stat `OSError` 不表示 deleted,应写入 `files.error_code=stat_failed` 和 `files.error_msg`,保留当前 `scan_status`。+- `PermissionError` 不表示 deleted,应写入 `files.error_code=file_permission_denied` 和 `files.error_msg`,保留当前 `status`。+- 其他 stat `OSError` 不表示 deleted,应写入 `files.error_code=stat_failed` 和 `files.error_msg`,保留当前 `status`。- 当文件被标记为 `deleted` 或 `unreachable` 时,应清空 `files.error_code` / `files.error_msg`。- 已经是 `deleted` 的 file,后续即使所属 removable watch root 不可达,也不应改为 `unreachable`。- `deleted` file 可以重新变为 `active`。只要同一路径重新可读,应重置 `sha256=NULL`,让 ingest 重新确认内容身份。当同步 path 调用发现文件缺失,且所属 removable watch root 不可达时:-- 允许立即把当前 `watch_targets.watch_status` 更新为 `unreachable`,并写入 `unreachable_at`。+- 允许立即把当前 `watches.status` 更新为 `unreachable`,并写入 `unreachable_at`。- 只允许把当前 path 对应的 file 标记为 `unreachable`。- 不允许在同步调用中批量更新该 watch 下的所有 active files,避免一次用户请求触发长时间 DB 写入。@@ -107,9 +107,9 @@ watch scan 的 P0 策略是不新增 `files.last_seen_at` 字段,而是执行删除 removable watch 时:-- active files: `watch_id=NULL`,`scan_status` 保持 `active`。-- deleted files: `watch_id=NULL`,`scan_status` 保持 `deleted`。-- unreachable files: `watch_id=NULL`,`scan_status` 改为 `deleted`,写入 `deleted_at`。+- active files: `watch_id=NULL`,`status` 保持 `active`。+- deleted files: `watch_id=NULL`,`status` 保持 `deleted`。+- unreachable files: `watch_id=NULL`,`status` 改为 `deleted`,写入 `deleted_at`。- 不立即删除 file row。file row 和 filename FTS 的生命周期仍然保持一致,清理交给 cleanup。### 必须检查文件变化的 path 操作@@ -163,7 +163,7 @@ Parse batch 绑定的是 `sha256`,不是 path。`ParseWorker` 执行任务前必须通过 `sha256` 查找当前 active file:```sql-SELECT * FROM files WHERE sha256=? AND scan_status='active' LIMIT 1+SELECT * FROM files WHERE sha256=? AND status='active' LIMIT 1```如果 path 已变化并被清空 `sha256`,旧 parse batch 不得继续读取这个 path 的新内容。此时:diff --git a/docs/next/decisions/0007-doclib-file-availability-lifecycle.md b/docs/next/decisions/0007-doclib-file-availability-lifecycle.mdindex 999205b7..c44e8ab9 100644--- a/docs/next/decisions/0007-doclib-file-availability-lifecycle.md+++ b/docs/next/decisions/0007-doclib-file-availability-lifecycle.md@@ -20,7 +20,7 @@ doclib 不只需要判断“同一路径内容是否变化”,还需要判断### 文件状态-`files.scan_status` 使用三种状态:+`files.status` 使用三种状态:| 状态 | 含义 | 默认 find | 默认 search | 是否保护 doc ||------|------|-----------|----------------|--------------|@@ -83,7 +83,7 @@ deleted file cleanup 与 orphan doc cleanup 是两个独立动作,互不连带deleted file cleanup:-- 只删除 `scan_status='deleted'` 的 file row。+- 只删除 `status='deleted'` 的 file row。- 手动命令立即删除所有 deleted file rows。- 后台任务只删除保留超过 7 天的 deleted file rows。- 删除 file row 时清理对应 `fts_filenames`。@@ -92,7 +92,7 @@ deleted file cleanup:orphan doc cleanup:- 只删除完全没有任何 file row 关联的 docs。-- 判断条件不区分 file 的 `scan_status`:+- 判断条件不区分 file 的 `status`:```sqlSELECT d.*@@ -140,7 +140,7 @@ FTS 生命周期跟随其对应主表记录:### 方案 C: 标记 deleted 时立即删除 filename FTS-拒绝。`fts_filenames` 的生命周期应与 `files` row 一致。默认 find 通过 `scan_status='active'` 控制可见性即可。+拒绝。`fts_filenames` 的生命周期应与 `files` row 一致。默认 find 通过 `status='active'` 控制可见性即可。### 方案 D: search 默认返回 unreachable / deleteddiff --git a/docs/next/decisions/0009-doclib-scan-task.md b/docs/next/decisions/0009-doclib-scan-task.mdindex 5d7e56b1..f15bfdee 100644--- a/docs/next/decisions/0009-doclib-scan-task.md+++ b/docs/next/decisions/0009-doclib-scan-task.md@@ -61,7 +61,7 @@ CREATE TABLE scans (path TEXT NOT NULL,kind TEXT NOT NULL, -- manual / watchsource TEXT NOT NULL DEFAULT 'unknown',- watch_id INTEGER REFERENCES watch_targets(id),+ watch_id INTEGER REFERENCES watches(id),status TEXT NOT NULL DEFAULT 'pending',locked_at INTEGER,created_at INTEGER NOT NULL,@@ -85,7 +85,7 @@ CREATE TABLE scans (CREATE INDEX idx_scans_status ON scans(status, created_at);CREATE INDEX idx_scans_kind_path_status ON scans(kind, path, status);-CREATE INDEX idx_scans_watch_status ON scans(watch_id, status);+CREATE INDEX idx_scans_watch_id_status ON scans(watch_id, status);````scans` 不记录 per-file 明细。P0 只做 summary。更细的 refresh log 可作为后续能力另行设计。@@ -121,7 +121,7 @@ watch scan 负责:- 用户或 Agent 触发的 watch rescan。- 设备恢复后立即执行的 watch scan。-watch scan 使用 watch 的 enabled/status/removable 语义,并更新 `watch_targets.last_scan_at` / `last_scan_files`。+watch scan 使用 watch 的 enabled/status/removable 语义,并更新 `watches.last_scan_at` / `last_scan_files`。## source@@ -245,7 +245,7 @@ manual scan 或 watch scan 发现新文件 / 变化文件时:- 应用 exclude rules。- 执行两阶段扫描:- 1. 先读取 DB 中该目录前缀下 `scan_status=active` 的已知 file rows,并逐个 `refresh_file()`,用于发现 deleted / unreachable / stat error。+ 1. 先读取 DB 中该目录前缀下 `status=active` 的已知 file rows,并逐个 `refresh_file()`,用于发现 deleted / unreachable / stat error。2. 再执行 `os.walk()`,对当前文件系统中支持的文件逐个 `refresh_file()`,用于发现新文件和变化文件。- 统计 exclude 命中的文件为 `files_excluded`。- 统计 unsupported extension 为 `files_unsupported`。@@ -269,7 +269,7 @@ watch scan 必须绑定 watch。1. 读取 watch target。2. 如果 watch 不存在或 disabled,scan `failed`,写 `error_code`。3. 如果 watch root 不可达:- - 更新 `watch_targets.watch_status=unreachable`。+ - 更新 `watches.status=unreachable`。- scan status 写 `done`,不是 `failed`。- 不在同步 scan 中逐个刷新该 watch 下所有 files。- 批量 active -> unreachable 收敛仍由 DeviceMonitor 或后台策略处理。@@ -277,7 +277,7 @@ watch scan 必须绑定 watch。- 更新 watch status 为 `active`。- 执行两阶段扫描。- 应用 exclude rules。- - 更新 `watch_targets.last_scan_at` / `last_scan_files`。+ - 更新 `watches.last_scan_at` / `last_scan_files`。watch scan 与 manual directory scan 的主要区别:diff --git a/docs/next/decisions/0010-doclib-watch-cli.md b/docs/next/decisions/0010-doclib-watch-cli.mdindex 03a27762..ddf25419 100644--- a/docs/next/decisions/0010-doclib-watch-cli.md+++ b/docs/next/decisions/0010-doclib-watch-cli.md@@ -88,7 +88,7 @@ mineru config parse-server ...- 不创建 watch。- 不要求 path 是 watch root。-- 不更新 `watch_targets.last_scan_at` / `last_scan_files`。+- 不更新 `watches.last_scan_at` / `last_scan_files`。- 写入 `scans.kind = manual`。- 扫描目录时应用 exclude rules。- 扫描文件时不应用 exclude rules,因为这是显式点名文件。@@ -114,7 +114,7 @@ mineru config parse-server ...- 写入 `scans.kind = watch`。- 绑定 `watch_id`。- 使用 watch 的 enabled / status / removable 语义。-- 更新 `watch_targets.last_scan_at` / `last_scan_files`。+- 更新 `watches.last_scan_at` / `last_scan_files`。## `watch rescan` 目标解析diff --git a/docs/next/doclib-error-handling-gap-review.md b/docs/next/doclib-error-handling-gap-review.mdindex 952775d0..c77b392d 100644--- a/docs/next/doclib-error-handling-gap-review.md+++ b/docs/next/doclib-error-handling-gap-review.md@@ -86,7 +86,7 @@- ingest worker 只领取:- `sha256 IS NULL`- - `scan_status = active`+ - `status = active`- `error_code IS NULL`- 任何已有 `files.error_code` 的 file 都不会被 ingest worker 自动重试。- `file_permission_denied`、`stat_failed`、`ingest_failed` 都会阻止自动领取。@@ -287,7 +287,7 @@建议:-- 为 `watch_targets` 增加错误字段,或复用 scan task 记录 watch scan 失败:+- 为 `watches` 增加错误字段,或复用 scan task 记录 watch scan 失败:- `error_code`- `error_msg`- `last_error_at`diff --git a/docs/next/everydoc-doclib-gap-review.md b/docs/next/everydoc-doclib-gap-review.mdindex 12199345..866f7c6b 100644--- a/docs/next/everydoc-doclib-gap-review.md+++ b/docs/next/everydoc-doclib-gap-review.md@@ -47,7 +47,7 @@处理结果:-- 数据模型有 `files.scan_status = active / deleted / unreachable`。+- 数据模型有 `files.status = active / deleted / unreachable`。- `refresh_file()` 统一处理 new / changed / known / deleted / unreachable / stat error。- 删除/变更检测入口包括 watch event、watch scan,以及 4 个同步 source file path 操作: parse、info、docs?path、invalidate(path)。- watch scan 采用两阶段刷新: 先 refresh DB 中该 watch 下的 active paths,再 `os.walk()` 发现当前文件系统中的新路径和变化路径。@@ -101,9 +101,9 @@处理结果:- `remove_watch(path)` 删除 watch target 前先处理关联 file rows。-- active files: `watch_id=NULL`,`scan_status` 保持 `active`。-- deleted files: `watch_id=NULL`,`scan_status` 保持 `deleted`。-- unreachable files: `watch_id=NULL`,`scan_status` 改为 `deleted`,写入 `deleted_at`。+- active files: `watch_id=NULL`,`status` 保持 `active`。+- deleted files: `watch_id=NULL`,`status` 保持 `deleted`。+- unreachable files: `watch_id=NULL`,`status` 改为 `deleted`,写入 `deleted_at`。- 不立即删除 file row,也不清理 FTS。后续优化:@@ -181,7 +181,7 @@ P0 结论:- 每个 watch stats 包括 total / active / deleted / unreachable files。- 每个 watch stats 包括 pending ingest files、file error count、doc count。- 每个 watch stats 包括 parse pending / parsing / failed / done count。-- 每个 watch stats 保留 watch path、label、removable、watch_status、last_scan_at、last_scan_files。+- 每个 watch stats 保留 watch path、label、removable、status、last_scan_at、last_scan_files。- `ServerStatusResponse` 增加 `error_summary`,按 `files` / `docs` / `parses` 聚合 `error_code` 数量。- `mineru server status` 在默认输出中增加 Watch Stats 和 Error Summary 表。- JSON 模式返回完整结构。diff --git a/docs/next/workflows.md b/docs/next/workflows.mdindex 7ea011ef..9b9cef56 100644--- a/docs/next/workflows.md+++ b/docs/next/workflows.md@@ -111,7 +111,7 @@ watch 的目标是发现文件、建立基础索引和支持后续搜索,不3. 执行统一文件发现/刷新: 新路径写入 `files` 并设置 `sha256=NULL`;已知路径先比较 `mtime_ms` 和 `size_bytes`。4. 如果已知路径未变化,跳过重新入库。5. 如果已知路径变化,更新文件 stat,清空 `files.sha256`,让 ingest worker 重新处理。-6. `IngestWorker` 抢占 `scan_status=active AND sha256 IS NULL` 的文件。+6. `IngestWorker` 抢占 `status=active AND sha256 IS NULL` 的文件。7. 计算 SHA256,提取基础 metadata。8. 写入或更新 `docs`。9. 写入文件名索引。@@ -134,10 +134,10 @@ watch 的目标是发现文件、建立基础索引和支持后续搜索,不| 阶段 | 主要状态 ||------|----------|-| 发现路径 | `files.scan_status=active` |+| 发现路径 | `files.status=active` || 检测到变化 | 更新 `files.size_bytes/mtime_ms`,并设置 `files.sha256=NULL` |-| 文件缺失且设备可达 | `files.scan_status=deleted`,保留 `sha256`,写入 `deleted_at` |-| removable 设备不可达 | 后台 `DeviceMonitor` 可将 `watch_targets.watch_status=unreachable`,并批量把相关 active files 变为 `unreachable`;同步 path 调用只允许更新当前文件和 watch 状态 |+| 文件缺失且设备可达 | `files.status=deleted`,保留 `sha256`,写入 `deleted_at` |+| removable 设备不可达 | 后台 `DeviceMonitor` 可将 `watches.status=unreachable`,并批量把相关 active files 变为 `unreachable`;同步 path 调用只允许更新当前文件和 watch 状态 || removable 设备恢复 | watch 和 files 恢复为 `active`,并立即对该 watch 执行 scan || 入库完成 | `files.sha256` 指向 `docs.sha256` || 创建任务 | `parses.status=pending`,`tier=flash` 或 rule tier |@@ -166,8 +166,8 @@ watch event、所有 scan 操作和所有同步 source file path 操作都必须watch scan 的 P0 删除检测采用“两阶段刷新”:-1. scan 开始时先检查 watch root 是否可达;不可达时只更新 `watch_targets.watch_status=unreachable` 并返回。-2. root 可达时,先读取该 watch 下 `scan_status=active` 的已知 file paths,并逐个调用统一文件刷新逻辑。+1. scan 开始时先检查 watch root 是否可达;不可达时只更新 `watches.status=unreachable` 并返回。+2. root 可达时,先读取该 watch 下 `status=active` 的已知 file paths,并逐个调用统一文件刷新逻辑。3. 再执行 `os.walk()` 扫描文件系统,发现当前存在的新文件或变化文件。4. 因此同一个已知且仍存在的文件可能在一轮 scan 中被 refresh 两次;P0 接受这部分后台 IO 成本,换取不增加 `files.last_seen_at` 字段和不引入独立删除判断逻辑。@@ -194,7 +194,7 @@ deleted file cleanup 与 orphan doc cleanup 分开执行。deleted file cleanup:-- 手动命令立即删除所有 `scan_status=deleted` 的 file row。+- 手动命令立即删除所有 `status=deleted` 的 file row。- 后台任务固定保留 7 天后删除 deleted file row。- 删除 file row 时删除对应 `fts_filenames`。- 不自动删除 docs、parses、parsed JSON 或 `fts_contents`。diff --git a/docs/plans/2026-06-15-cli-next-command-design.md b/docs/plans/2026-06-15-cli-next-command-design.mdnew file mode 100644index 00000000..3fdc4987--- /dev/null+++ b/docs/plans/2026-06-15-cli-next-command-design.md@@ -0,0 +1,566 @@+# MinerU CLI Next 命令设计草案++**日期**: 2026-06-15+**状态**: 设计阶段(待评审)+**范围**: `mineru/cli_next` 面向 doclib server/client 的命令结构+**非目标**: `mineru-kit` 专家参数、parse-server HTTP API 细节、旧命令兼容层++## 1. 背景++当前 `cli_next` 已经具备本地 doclib 的核心能力:单文件解析、scan task、watch target、搜索、文件信息、配置、清理、forget、server 生命周期管理等。++主要问题不是能力缺失,而是命令分组还没有稳定:++- `mineru parse <file>` 与 `mineru parse list` / `parses` 这类命名如果同时存在,容易让用户分不清“发起解析动作”和“查看解析任务集合”。+- `mineru scan <path>`、`mineru scan status <id>`、`mineru scan list` 把动作和资源查询混在同一个顶层动词下,当前实现也需要手动解析伪子命令。+- `mineru info <path>` 保留为文件信息短别名,但不继续扩展到 parse、scan、doc、server 等其他对象。+- `mineru config parse-server ...` 可以被通用 `mineru config set <key> <value>` 覆盖,专用子树会增加重复入口。+- `config show` 需要展示哪些值来自代码默认值,哪些值来自用户 override。++MVP 还在开发阶段,因此除 `info <path>` 作为 `show file <path>` 的短别名外,本设计不保留旧命令兼容入口。++## 2. 设计原则++1. **动作和资源分离**+ - `parse`、`scan` 保留为发起动作。+ - `list`、`show` 负责查询已有资源。++2. **单复数不混用**+ - 不设计 `parse` 和 `parses` 两个并列顶层命令。+ - 资源集合统一放到 `list <resource>`,单对象详情统一放到 `show <resource> <id>`。++3. **对象类型显式**+ - `show parse <parse_id>` 比 `info <id>` 清楚。+ - `show scan <scan_id>` 比 `scan status <scan_id>` 更清楚,因为它不会和“发起 scan”抢同一个命令空间。++4. **配置走 KV**+ - `config show/get/set/unset` 是配置 KV 的唯一入口。+ - parse-server 相关配置使用 `parse_server.*` key,不再提供 `config parse-server` 快捷命令。++5. **暂不增加内容读取子命令**+ - 暂不加入 `mineru content <sha256> --tier standard --pages 1~5`。+ - 暂不加入 `mineru show doc <sha256> --content --tier standard --pages 1~5`。+ - 解析内容读取继续由 `mineru parse <file>` 的输出行为承担。++## 3. 推荐命令树++### 3.1 顶层命令++| 命令 | 职责 |+|------|------|+| `mineru parse <file>` | 发起或复用单文件解析,并输出内容或任务状态 |+| `mineru scan <path>` | 发起一次性 scan task |+| `mineru search <query>` | 搜索已解析内容 |+| `mineru find <query>` | 按文件名或路径定位 doclib 文件记录 |+| `mineru list <resource>` | 列出资源集合 |+| `mineru show <resource> <id>` | 查看资源详情 |+| `mineru info <path>` | 查看文件信息,作为 `show file <path>` 的短别名 |+| `mineru watch ...` | 管理 watch target |+| `mineru config ...` | 管理运行时配置和规则 |+| `mineru cleanup ...` | 清理 doclib 历史记录和临时文件 |+| `mineru forget <path>` | 从 doclib 忘记路径记录,不删除源文件 |+| `mineru invalidate <path>` | 作废已有解析缓存,使后续 parse 重新运行 |+| `mineru server ...` | 管理本地 doclib server 生命周期 |++## 4. Parse 相关命令++### 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]+```++语义:++- 只负责“用户主动要求解析这个文件”。+- 命中 done cache 时直接输出内容。+- 未命中时创建或复用 parse task。+- `--no-wait` 或超时后返回可继续查询的 parse 状态。++不在 `parse` 下增加 `list/status/show` 子命令。++### 4.2 列出解析任务++```bash+mineru list parses [--status pending|parsing|done|failed|superseded] [--tier flash|standard|pro] [--limit 50] [--json]+```++说明:++- `list parses` 使用复数资源名,因为它返回集合。+- 这里的 `parses` 只出现在 `list` 的资源位置,不作为顶层命令。++### 4.3 查看解析任务详情++```bash+mineru show parse <parse_id> [--json]+```++说明:++- 用于查看单个 parse task 的详细状态、错误、tier、pages、关联 sha256、产物路径等。+- 不读取正文内容。++## 5. Scan 相关命令++### 5.1 发起 scan++```bash+mineru scan <path> [--wait <sec>] [--no-wait] [--json]+```++语义:++- 创建一次性 scan task。+- 不创建 watch。+- 不上传远端。+- 目录 scan 应用 exclude rules;显式文件 scan 不应用 exclude rules。++### 5.2 列出 scan tasks++```bash+mineru list scans [--status pending|running|done|failed] [--kind manual|watch] [--watch-id <id>] [--limit 50] [--json]+```++替代当前:++```bash+mineru scan list+```++### 5.3 查看 scan 详情++```bash+mineru show scan <scan_id> [--json]+```++说明:++- 展示 scan 计数、路径、kind、watch_id、错误信息和时间戳。++## 6. Doc/File 相关命令++### 6.1 文件信息++```bash+mineru show file <path> [--json]+mineru info <path> [--json]+```++说明:++- `file` 代表路径记录,展示 path、sha256、大小、mtime、status、parse 概要。+- `info <path>` 先保留,作为 `show file <path>` 的短别名。+- `info` 只面向 path/file,不扩展为多对象查询命令。+- 如果文件不存在但 DB 中有历史记录,应展示历史状态,而不是只报 file not found。++### 6.2 文件列表++```bash+mineru list files [--status active|deleted|unreachable] [--ext <ext>] [--watch-id <id>] [--limit 200] [--offset 0] [--json]+```++说明:++- `list files` 返回 doclib 中的文件路径记录,而不是去磁盘重新扫描。+- 默认列出 active files。+- 默认排序为 `updated_at DESC`,便于查看最近入库或变化的文件。+- `--status deleted|unreachable` 用于排查 scan/watch 状态。+- 当前 server/client 暂无独立 list files endpoint,MVP 实现时需要新增。++### 6.3 文档信息++```bash+mineru show doc <sha256> [--json]+```++说明:++- 仅展示 doc metadata、关联路径、已解析 tier/pages、active parses、FTS 状态。+- 不加 `--content`。+- 内容读取命令暂不纳入本轮设计。++### 6.4 文档列表++```bash+mineru list docs [--path <path>] [--file-type <type>] [--limit 200] [--json]+```++说明:++- `list docs` 返回已入库文档集合,以 sha256 去重。+- 支持按 `docs.file_type` 过滤,例如 `pdf`、`docx`。+- 现有 doclib server/client 已有 `GET /docs` / `DoclibClient.list_docs(path=...)` 能力,但需要补 `file_type` / `limit` 参数。+- `--path <path>` 可用于按文件路径反查关联 doc。++## 7. Search 和 Find++保留现有顶层命令:++```bash+mineru search <query> [--type <ext>] [--tier <tier>] [--min-tier <tier>] [--limit 20] [--offset 0] [--json]+mineru find <query> [--ext <ext>] [--limit 50] [--json]+```++理由:++- `search` 和 `find` 是用户高频动作,不需要强行归到 `list` 或 `show`。+- `search` 查内容,`find` 查文件名/路径,语义清楚。++## 8. Watch++保留资源管理子树:++```bash+mineru watch add <path> [--removable] [--label <label>] [--json]+mineru watch list [--json]+mineru watch remove <path-or-id> [--json]+mineru watch rescan <path-or-id> [--wait <sec>] [--no-wait] [--json]+```++说明:++- `watch rescan` 是针对已配置 watch target 的动作,保留在 `watch` 子树下合理。+- 任意路径的一次性扫描仍使用 `mineru scan <path>`。++不支持 `mineru list watches`。watch 是明确的管理子树,集合查询保留为 `mineru watch list`。++## 9. Config++### 9.1 KV 配置++```bash+mineru config show [--json]+mineru config get <key> [--json]+mineru config set <key> <value>+mineru config unset <key>+```++语义:++- 默认值必须在代码中定义,不存储在 DB 中。+- DB `config` 表只存用户 override。+- `config get <key>` 对未知 key 返回错误。+- `config unset <key>` 删除 override,使该 key 回到代码默认值。+- `config show` 展示最终生效值,并标注来源。++人类可读输出示例:++```text+[Config]+ data_dir = ~/MinerU [default]+ default_tier = flash [default]+ parse_server.local.mode = managed [override]+ parse_server.remote.api_key = sk-abc******xyz789 [override]+```++JSON 输出建议:++```json+{+ "config": {+ "data_dir": "~/MinerU",+ "parse_server.local.mode": "managed",+ "parse_server.remote.api_key": "sk-abc******xyz789"+ },+ "sources": {+ "data_dir": "default",+ "parse_server.local.mode": "override",+ "parse_server.remote.api_key": "override"+ }+}+```++敏感 key 在人类可读输出和 JSON 输出中均脱敏处理。脱敏规则为首尾各保留 6 个字符,中间替换为 `******`;长度不足以保留首尾时按安全优先原则整体替换为 `******`。++### 9.2 parse-server 配置++不再提供:++```bash+mineru config parse-server local.mode managed+mineru config parse-server remote.url https://...+```++改为:++```bash+mineru config set parse_server.local.mode managed+mineru config set parse_server.local.managed_tier standard+mineru config set parse_server.local.self_hosted_url http://127.0.0.1:8000+mineru config set parse_server.local.self_hosted_api_key <key>+mineru config set parse_server.remote.url https://mineru.net/api+mineru config set parse_server.remote.api_key <key>+```++### 9.3 Rules++保留在 `config` 子树下:++```bash+mineru config exclude-rules add <pattern> [--priority 0]+mineru config exclude-rules list [--json]+mineru config exclude-rules remove <rule_id>++mineru config parsing-rules add <pattern> [--tier <tier>] [--pages <range>] [--remote] [--name <name>]+mineru config parsing-rules list [--json]+mineru config parsing-rules remove <rule_id>+```++说明:++- exclude-rules 和 parsing-rules 是配置的一部分,不需要提升为顶层命令。+- rules 删除统一使用 `remove`,避免 `rm` 缩写降低自解释性。++### 9.4 Doclib HTTP Path 命名++MVP 阶段不保留旧 HTTP path 兼容入口,直接把配置子资源从 `/config/...` 下移到资源自身路径。++| 能力 | 新 HTTP path | 替换旧 HTTP path |+|------|--------------|------------------|+| KV config 列表 / 展示 | `GET /configs` | `GET /config` |+| KV config 单 key 查询 | `GET /configs/{key}` | 新增 |+| KV config 单 key 设置 | `PUT /configs/{key}` | `POST /config` |+| KV config 单 key unset | `DELETE /configs/{key}` | 新增 |+| watch 添加 | `POST /watches` | `POST /config/watch` |+| watch 列表 | `GET /watches` | `GET /config/watch` |+| watch 删除 | `DELETE /watches/{watch_id}` | `DELETE /config/watch` |+| exclude rule 添加 | `POST /exclude-rules` | `POST /config/exclude` |+| exclude rule 列表 | `GET /exclude-rules` | `GET /config/exclude` |+| exclude rule 删除 | `DELETE /exclude-rules/{rule_id}` | `DELETE /config/exclude/{rule_id}` |+| parsing rule 添加 | `POST /parsing-rules` | `POST /config/parsing-rules` |+| parsing rule 列表 | `GET /parsing-rules` | `GET /config/parsing-rules` |+| parsing rule 删除 | `DELETE /parsing-rules/{rule_id}` | `DELETE /config/parsing-rules/{rule_id}` |+| server shutdown | `POST /server/shutdown` | `POST /shutdown` |+| doc 内容读取 | `GET /docs/{sha256}/content` | 保留,但必须只读 |+| doc 内容导出 | `POST /docs/{sha256}/exports` | 从 `GET /docs/{sha256}/content?output=...` 拆出 |++`PUT /configs/{key}` 的 request body 只包含 value,不重复携带 key:++```json+{+ "value": "managed"+}+```++响应返回脱敏后的生效值和来源:++```json+{+ "key": "parse_server.local.mode",+ "value": "managed",+ "source": "override"+}+```++`GET /docs/{sha256}/content` 必须保持只读,不支持 `output` 参数。需要让 server 写出文件时使用 `POST /docs/{sha256}/exports`。导出 request body:++```json+{+ "tier": "standard",+ "pages": "1~5",+ "format": "markdown",+ "output": "/absolute/or/server-visible/path.md",+ "no_marker": false+}+```++导出响应:++```json+{+ "sha256": "<sha256>",+ "tier": "standard",+ "output": "/absolute/or/server-visible/path.md"+}+```++## 10. Cleanup、Forget、Invalidate、Server++### 10.1 Cleanup++保留现有命令:++```bash+mineru cleanup deleted-files [--dry-run|--no-dry-run] [--json]+mineru cleanup orphan-docs [--dry-run|--no-dry-run] [--json]+mineru cleanup temp [--older-than <days>] [--json]+```++### 10.2 Forget++保留现有命令:++```bash+mineru forget <path> [--dry-run|--no-dry-run] [--json]+```++### 10.3 Invalidate++保留现有命令:++```bash+mineru invalidate <path> [--tier <tier>]+```++说明:++- `invalidate` 是明确的缓存操作,作为顶层命令可以接受。+- 如果后续命令数量过多,可并入 `mineru cache invalidate <path>`,但 MVP 不建议扩散。++### 10.4 Server++保留现有命令:++```bash+mineru server start+mineru server stop+mineru server restart+mineru server status [--json]+```++## 11. 不纳入本轮的命令++暂不设计:++```bash+mineru content <sha256> --tier standard --pages 1~5+mineru show doc <sha256> --content --tier standard --pages 1~5+mineru parse list+mineru parses ...+mineru scan list+mineru scan status <scan_id>+mineru status parse <parse_id>+mineru status scan <scan_id>+mineru status server+mineru config parse-server ...+```++其中内容读取命令需要先明确两个问题:++- 用户是想按 `sha256` 读取已有解析产物,还是想沿用路径作为主入口。+- 内容读取是否需要支持 page range、format、marker、offset,以及这些参数是否应与 `parse` 完全一致。++## 12. 从当前实现迁移的改动清单++### 12.1 CLI 命令结构++新增 Typer 子树:++- `list`+- `show`++调整:++- `mineru scan <path>` 继续保留为顶层动作。+- 删除 `scan_cmd` 中对 `status` / `list` 的手动伪子命令解析。+- `mineru list scans` 调用现有 `DoclibClient.list_scans()`。+- `mineru list docs` 调用 `DoclibClient.list_docs()`,并补齐 `file_type` / `limit` 参数。+- `mineru list files` 需要新增 server/client/interface endpoint。+- `mineru show scan <id>` 调用现有 `DoclibClient.get_scan()`。+- `mineru list parses` 调用现有 `DoclibClient.list_parses()`,并补齐 `limit` 参数透传。+- `mineru show parse <id>` 调用现有 `DoclibClient.get_parse()`。+- `mineru show file <path>` 复用现有 `get_file_info()`。+- `mineru info <path>` 复用 `show file <path>` 的实现。+- `mineru show doc <sha256>` 调用现有 `DoclibClient.get_doc(expand_files=True)`。++删除:++- `mineru scan list`+- `mineru scan status <id>`+- `mineru config parse-server ...`++### 12.2 Config 默认值和 unset++实现要求:++- 新增代码级 `CONFIG_DEFAULTS`。+- DB 初始化不再把默认值写入 `config` 表。+- 启动或 migration 时清理历史上与默认值完全相同的 seeded rows。+- `ConfigService.get(key)` 返回 override,否则返回代码默认值。+- `ConfigService.get_all()` 返回默认值与 override 合并后的生效配置。+- `ConfigResponse` 增加 `sources: dict[str, "default" | "override"]`。+- `mineru config show` 人类可读输出标注 `[default]` / `[override]`。+- `mineru config unset <key>` 删除 override。++### 12.3 Doclib HTTP route 结构++直接修改 server/client/interface route,不保留旧 path:++- `GET /config` 改为 `GET /configs`。+- 新增 `GET /configs/{key}`,支持 `mineru config get <key>`。+- `POST /config` 改为 `PUT /configs/{key}`,request body 为 `{"value": "<value>"}`。+- 新增 `DELETE /configs/{key}`,支持 `mineru config unset <key>`。+- `POST /config/watch` 改为 `POST /watches`。+- `GET /config/watch` 改为 `GET /watches`。+- `DELETE /config/watch` 改为 `DELETE /watches/{watch_id}`;CLI 的 `watch remove <path-or-id>` 如果收到 path,需要先从 `GET /watches` 解析出 `watch_id`。+- `POST /config/exclude` 改为 `POST /exclude-rules`。+- `GET /config/exclude` 改为 `GET /exclude-rules`。+- `DELETE /config/exclude/{rule_id}` 改为 `DELETE /exclude-rules/{rule_id}`。+- `POST /config/parsing-rules` 改为 `POST /parsing-rules`。+- `GET /config/parsing-rules` 改为 `GET /parsing-rules`。+- `DELETE /config/parsing-rules/{rule_id}` 改为 `DELETE /parsing-rules/{rule_id}`。+- `POST /shutdown` 改为 `POST /server/shutdown`,与 `GET /server/status` 放在同一 server 子树下。+- `GET /docs/{sha256}/content` 移除 `output` 参数,保持只读。+- 新增 `POST /docs/{sha256}/exports`,用于需要 server 写文件的导出场景。++### 12.4 文档同步++设计确认后需要同步:++- `docs/next/cli/mineru.md`+- `docs/next/cli/mineru-library.md`+- `docs/next/sdk/doclib-client.md`+- route contract / interface contract tests++## 13. 完整 MVP 命令列表++```bash+mineru parse <file>+mineru scan <path>+mineru search <query>+mineru find <query>++mineru list parses+mineru list scans+mineru list files+mineru list docs++mineru show parse <parse_id>+mineru show scan <scan_id>+mineru show file <path>+mineru show doc <sha256>+mineru info <path>++mineru watch add <path>+mineru watch list+mineru watch remove <path-or-id>+mineru watch rescan <path-or-id>++mineru config show+mineru config get <key>+mineru config set <key> <value>+mineru config unset <key>+mineru config exclude-rules add <pattern>+mineru config exclude-rules list+mineru config exclude-rules remove <rule_id>+mineru config parsing-rules add <pattern>+mineru config parsing-rules list+mineru config parsing-rules remove <rule_id>++mineru cleanup deleted-files+mineru cleanup orphan-docs+mineru cleanup temp++mineru forget <path>+mineru invalidate <path>++mineru server start+mineru server stop+mineru server restart+mineru server status+```++## 14. 待确认问题++暂无。diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.pyindex 9978699a..152398f8 100644--- a/mineru/cli_next/commands/parse.py+++ b/mineru/cli_next/commands/parse.py@@ -8,7 +8,7 @@ from pathlib import Pathimport typerfrom ...doclib.client import DoclibClient-from ...doclib.types import ParseRequest+from ...doclib.types import DocContentExportRequest, ParseRequestfrom ...types import Tierfrom ..output import format_parse_result, print_error, print_success, print_info@@ -77,7 +77,7 @@ def parse_cmd(if status == "done":if verbose:print_info("Cache hit — returning cached result.")- _output_content(client, sha256, req_tier, json_mode, output, pages=result_pages, format=format)+ _output_content(client, sha256, req_tier, json_mode, output, pages=result_pages, format=format, no_marker=no_marker)return# no-wait@@ -107,7 +107,16 @@ def parse_cmd(if st == "done":if not json_mode:- _output_content(client, sha256, req_tier, json_mode, output, pages=result_pages, format=format)+ _output_content(+ client,+ sha256,+ req_tier,+ json_mode,+ output,+ pages=result_pages,+ format=format,+ no_marker=no_marker,+ )else:format_parse_result(s, json_mode=json_mode)return@@ -130,24 +139,32 @@ if __name__ != "__main__":def _output_content(- client,+ client: DoclibClient,sha256: str,tier: Tier,json_mode: bool,output: str | None = None,pages: str | None = None,format: str = "markdown",+ no_marker: bool = False,) -> None:"""Fetch and output parsed content. If --output is specified, server writes to file."""try:- content = client.get_doc_content(sha256, tier=tier, output=output, pages=pages, format=format)if output and output != "-":- if content.output:- print_success(f"Written to {content.output}")- else:- print_error("Failed to write output file.")+ exported = client.export_doc_content(+ sha256,+ DocContentExportRequest(+ tier=tier,+ pages=pages,+ format=format,+ output=output,+ no_marker=no_marker,+ ),+ )+ print_success(f"Written to {exported.output}")return+ content = client.get_doc_content(sha256, tier=tier, pages=pages, format=format, no_marker=no_marker)text = content.content or ""if text:if json_mode:diff --git a/mineru/cli_next/commands/scan.py b/mineru/cli_next/commands/scan.pyindex 4288f39d..47b7f0aa 100644--- a/mineru/cli_next/commands/scan.py+++ b/mineru/cli_next/commands/scan.py@@ -7,7 +7,7 @@ import timeimport typerfrom ...doclib.client import DoclibClient-from ...doclib.types import ScanKind, ScanRequest, ScanTaskStatus+from ...doclib.types import ScanKind, ScanRequest, ScanStatusfrom ..output import print_error, print_info, print_json, print_success@@ -25,7 +25,7 @@ def scan_cmd(command = args[0]try:if command == "status":- _scan_status(args[1:], json_mode=json_mode)+ _show_scan_task(args[1:], json_mode=json_mode)returnif command == "list":_scan_list(args[1:], json_mode=json_mode)@@ -44,7 +44,7 @@ def _scan_path(path: str, *, wait: int, no_wait: bool, json_mode: bool) -> None:_print_scan(scan_info, json_mode=json_mode)-def _scan_status(args: list[str], *, json_mode: bool) -> None:+def _show_scan_task(args: list[str], *, json_mode: bool) -> None:if len(args) != 1:raise ValueError("Usage: mineru scan status <scan_id>")scan_info = _client().get_scan(int(args[0]))@@ -53,7 +53,7 @@ def _scan_status(args: list[str], *, json_mode: bool) -> None:def _scan_list(args: list[str], *, json_mode: bool) -> None:limit = 50- status: ScanTaskStatus | None = None+ status: ScanStatus | None = Nonekind: ScanKind | None = Nonewatch_id: int | None = Nonediff --git a/mineru/cli_next/commands/watch.py b/mineru/cli_next/commands/watch.pyindex 16e77543..872c7b16 100644--- a/mineru/cli_next/commands/watch.py+++ b/mineru/cli_next/commands/watch.py@@ -51,19 +51,21 @@ def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON outputprint_info("No watches configured.")returnfor watch in data.watches:- status = watch.watch_status+ status = watch.statusextra = " [removable]" if watch.removable else ""print(f" [{watch.id}] {watch.path}{extra} [{status}]")@app.command("remove")def watch_remove(- path: str = typer.Argument(..., help="Watch directory path to remove"),+ target: str = typer.Argument(..., help="Watch id or exact watch root path to remove"),json_mode: bool = typer.Option(False, "--json", help="JSON output"),) -> None:"""Remove a watched directory."""try:- result = _client().remove_watch(path)+ client = _client()+ 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@@ -71,7 +73,7 @@ def watch_remove(if json_mode:print_json(result)return- print_success(f"Watch removed: {result.path}")+ print_success(f"Watch removed: {watch.path}")@app.command("rescan")diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.pyindex 24a31a93..a9c70f55 100644--- a/mineru/cli_next/output.py+++ b/mineru/cli_next/output.py@@ -156,7 +156,7 @@ def format_server_status(data: Any, json_mode: bool = False) -> None:)watch_table.add_row(_get(item, "path", ""),- _get(item, "watch_status", ""),+ _get(item, "status", ""),str(_get(item, "total_files", 0)),str(_get(item, "active_files", 0)),str(_get(item, "deleted_files", 0)),diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 1553f5cb..cc1b5f4b 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -155,7 +155,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:@app.exception_handler(MineruError)async def mineru_error_handler(_request: Request, exc: MineruError) -> JSONResponse:return JSONResponse(- status_code=http_status_for(exc.code, exc.type),+ status_code=http_status_for(exc.code),content=error_response(exc),)@@ -173,7 +173,26 @@ def create_app(cfg: Config | None = None) -> FastAPI:class AppState:- pass+ def __init__(self) -> None:+ self.db: Any = None+ self.fts: Any = None+ self.config_svc: Any = None+ self.parse_svc: Any = None+ self.scan_svc: Any = None+ self.search_svc: Any = None+ self.cleanup_svc: Any = None+ self.parse_server_proc: Any = None+ self.watch: Any = None+ self.scan_workers: Any = None+ self.ingest_workers: Any = None+ self.parse_workers: Any = None+ self.device_monitor: Any = None+ self.compaction: Any = None+ self.health_check: Any = None+ self.start_time: float = 0.0+ self.pid: int = 0+ self.data_dir: str = ""+ self.config: Config | None = Nonedef main() -> None:diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.pyindex 17a035bb..cc89fc54 100644--- a/mineru/doclib/background/compaction.py+++ b/mineru/doclib/background/compaction.py@@ -7,10 +7,13 @@ import json as _jsonimport loggingimport osimport time+from collections.abc import Sequence+from typing import cast+from ...types import Tierfrom ..core.db import DatabaseManager+from ..rows import ParseBatchRow, ParseGroupRow, ParseRowfrom ..services.parse_svc import parse_batch_json_path, parse_range_set-from ...types import Tierfrom ..types import PARSE_STATUS_DONE, PARSE_STATUS_SUPERSEDEDlogger = logging.getLogger("mineru.compaction")@@ -41,10 +44,13 @@ class Compaction:async def _compact(self) -> int:"""Scan all (sha256, tier) pairs with multiple done batches and merge them."""- rows = await self.db.fetchall(- "SELECT sha256, tier FROM parses WHERE status=? "- "GROUP BY sha256, tier HAVING COUNT(*) > 1",- (PARSE_STATUS_DONE,),+ rows = cast(+ list[ParseGroupRow],+ await self.db.fetchall(+ "SELECT sha256, tier FROM parses WHERE status=? "+ "GROUP BY sha256, tier HAVING COUNT(*) > 1",+ (PARSE_STATUS_DONE,),+ ),)total_merged = 0for r in rows:@@ -53,10 +59,13 @@ class Compaction:return total_mergedasync def _compact_doc_tier(self, sha256: str, tier: Tier) -> int:- rows = await self.db.fetchall(- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status=? "- "ORDER BY done_at DESC",- (sha256, tier, PARSE_STATUS_DONE),+ rows = cast(+ list[ParseRow],+ await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status=? "+ "ORDER BY done_at DESC",+ (sha256, tier, PARSE_STATUS_DONE),+ ),)if len(rows) <= 1:return 0@@ -110,8 +119,12 @@ class Compaction:return len(rows) - len(merged_ranges)async def _compact_json(- self, sha256: str, tier: Tier, merged_ranges: list[str],- done_rows: list[dict], max_done_at: int,+ self,+ sha256: str,+ tier: Tier,+ merged_ranges: list[str],+ done_rows: Sequence[ParseBatchRow],+ max_done_at: int,) -> None:"""Merge per-batch JSON files to match compacted parses rows.Only reads files belonging to *done_rows* — ignores superseded files."""diff --git a/mineru/doclib/background/device_monitor.py b/mineru/doclib/background/device_monitor.pyindex a0609d97..bfbfbfd5 100644--- a/mineru/doclib/background/device_monitor.py+++ b/mineru/doclib/background/device_monitor.py@@ -8,7 +8,7 @@ import timefrom ..core.db import DatabaseManagerfrom ..services.config_svc import ConfigService-from ..types import SCAN_STATUS_ACTIVE, SCAN_STATUS_UNREACHABLE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLE+from ..types import FILE_STATUS_ACTIVE, FILE_STATUS_UNREACHABLE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLEclass DeviceMonitor:@@ -30,9 +30,9 @@ class DeviceMonitor:await self.config_svc.update_watch_status(w["id"], WATCH_STATUS_UNREACHABLE)now = int(time.time() * 1000)await self.db.execute(- "UPDATE files SET scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=NULL, updated_at=? "- "WHERE watch_id=? AND scan_status=?",- (SCAN_STATUS_UNREACHABLE, now, w["id"], SCAN_STATUS_ACTIVE),+ "UPDATE files SET status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=NULL, updated_at=? "+ "WHERE watch_id=? AND status=?",+ (FILE_STATUS_UNREACHABLE, now, w["id"], FILE_STATUS_ACTIVE),)unreachable = await self.config_svc.get_watches_by_status(WATCH_STATUS_UNREACHABLE)@@ -42,9 +42,9 @@ class DeviceMonitor:await self.config_svc.update_watch_status(w["id"], WATCH_STATUS_ACTIVE)now = int(time.time() * 1000)await self.db.execute(- "UPDATE files SET scan_status=?, updated_at=? "- "WHERE watch_id=? AND scan_status=?",- (SCAN_STATUS_ACTIVE, now, w["id"], SCAN_STATUS_UNREACHABLE),+ "UPDATE files SET status=?, updated_at=? "+ "WHERE watch_id=? AND status=?",+ (FILE_STATUS_ACTIVE, now, w["id"], FILE_STATUS_UNREACHABLE),)except (FileNotFoundError, OSError):passdiff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.pyindex 0e5ab3d7..7da61100 100644--- a/mineru/doclib/background/ingest.py+++ b/mineru/doclib/background/ingest.py@@ -5,9 +5,11 @@ from __future__ import annotationsimport asyncioimport loggingimport time+from typing import cast+from ..rows import CountRow, FileRow, IngestTaskRowfrom ..services.parse_svc import ParseService-from ..types import SCAN_STATUS_ACTIVE+from ..types import FILE_STATUS_ACTIVElogger = logging.getLogger("mineru.ingest")@@ -35,10 +37,13 @@ class IngestWorkerPool:if task is None:no_task_count += 1if no_task_count == 1 or no_task_count % 20 == 0:- q = await self.parse_svc.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status=? "- "AND error_code IS NULL",- (SCAN_STATUS_ACTIVE,),+ q = cast(+ CountRow | None,+ await self.parse_svc.db.fetchone(+ "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND status=? "+ "AND error_code IS NULL",+ (FILE_STATUS_ACTIVE,),+ ),)logger.info(f"Ingest worker {worker_id}: queue={q['cnt'] if q else 0}")await asyncio.sleep(0.5)@@ -60,22 +65,25 @@ class IngestWorkerPool:logger.info(f"Ingest worker {worker_id} stopped, processed {processed} total")- async def _acquire_task(self) -> dict | None:+ async def _acquire_task(self) -> FileRow | None:now = int(time.time() * 1000)timeout = now - 60 * 1000 # 60s ingest lock timeout- return await self.parse_svc.db.fetchone(- "UPDATE files SET locked_at=? "- "WHERE id = ("- " SELECT id FROM files "- " WHERE sha256 IS NULL AND scan_status=? "- " AND error_code IS NULL "- " AND (locked_at IS NULL OR locked_at < ?) "- " ORDER BY first_seen_at ASC LIMIT 1"- ") RETURNING *",- (now, SCAN_STATUS_ACTIVE, timeout),+ return cast(+ FileRow | None,+ await self.parse_svc.db.fetchone(+ "UPDATE files SET locked_at=? "+ "WHERE id = ("+ " SELECT id FROM files "+ " WHERE sha256 IS NULL AND status=? "+ " AND error_code IS NULL "+ " AND (locked_at IS NULL OR locked_at < ?) "+ " ORDER BY first_seen_at ASC LIMIT 1"+ ") RETURNING *",+ (now, FILE_STATUS_ACTIVE, timeout),+ ),)- async def _handle_ingest_error(self, task: dict, exc: Exception) -> None:+ async def _handle_ingest_error(self, task: IngestTaskRow, exc: Exception) -> None:try:if isinstance(exc, FileNotFoundError):watch_id = task.get("watch_id")diff --git a/mineru/doclib/background/watch.py b/mineru/doclib/background/watch.pyindex b6c428c5..1be49f88 100644--- a/mineru/doclib/background/watch.py+++ b/mineru/doclib/background/watch.py@@ -13,7 +13,7 @@ from ..constants import ALLOWED_EXTENSIONSfrom ..services.config_svc import ConfigServicefrom ..services.parse_svc import ParseServicefrom ..services.scan_svc import ScanService-from ..types import SCAN_STATUS_ACTIVE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLE+from ..types import FILE_STATUS_ACTIVE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLEclass WatchLoop:@@ -34,7 +34,7 @@ class WatchLoop:active_ids: set[int] = set()for w in watches:- if w["watch_status"] != WATCH_STATUS_ACTIVE:+ if w["status"] != WATCH_STATUS_ACTIVE:continueactive_ids.add(w["id"])@@ -65,8 +65,8 @@ class WatchLoop:try:rows = await self.db.fetchall(- "SELECT path FROM files WHERE watch_id=? AND scan_status=?",- (watch_id, SCAN_STATUS_ACTIVE),+ "SELECT path FROM files WHERE watch_id=? AND status=?",+ (watch_id, FILE_STATUS_ACTIVE),)for row in rows:await self._refresh_file(row["path"], watch_id)diff --git a/mineru/doclib/base.py b/mineru/doclib/base.pyindex 462c4268..3f0f796b 100644--- a/mineru/doclib/base.py+++ b/mineru/doclib/base.py@@ -15,12 +15,17 @@ from .types import (ConfigResponse,ConfigSetRequest,ConfigSetResponse,+ ConfigUnsetResponse,+ ConfigValueResponse,+ DocContentExportRequest,+ DocContentExportResponse,DocContentResponse,DocInfo,ExcludeRuleInfo,ExcludeRuleListResponse,ExcludeRuleRequest,FileInfoResponse,+ ListFilesResponse,FindResponse,ForgetPathRequest,ForgetPathResponse,@@ -44,7 +49,8 @@ from .types import (ScanKind,ScanListResponse,ScanRequest,- ScanTaskStatus,+ FileStatus,+ ScanStatus,WatchInfo,WatchListResponse,WatchRequest,@@ -102,6 +108,7 @@ class DoclibInterface(ABC):status: str | None = None,pages: str | None = None,include_superseded: bool = False,+ limit: int = 50,) -> ListParsesResponse:"""List parse records and optional coverage information.@@ -158,7 +165,7 @@ class DoclibInterface(ABC):self,*,limit: int = 50,- status: ScanTaskStatus | None = None,+ status: ScanStatus | None = None,kind: ScanKind | None = None,watch_id: int | None = None,) -> ScanListResponse:@@ -182,7 +189,31 @@ class DoclibInterface(ABC):raise NotImplementedError()@abstractmethod- def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ def list_files(+ self,+ *,+ status: FileStatus | None = None,+ ext: str | None = None,+ watch_id: int | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> ListFilesResponse:+ """List file rows known to doclib.++ Raises:+ InvalidRequestError: when filters, limit, or offset are invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_docs(+ self,+ *,+ path: str | None = None,+ file_type: str | None = None,+ limit: int = 200,+ ) -> ListDocsResponse:"""List active docs, optionally filtered by path.Raises:@@ -210,7 +241,6 @@ class DoclibInterface(ABC):tier: Tier,pages: str | None = None,format: str = "markdown",- output: str | None = None,no_marker: bool = False,) -> DocContentResponse:"""Render stored doc content from parsed JSON artifacts.@@ -222,6 +252,17 @@ class DoclibInterface(ABC):"""raise NotImplementedError()+ @abstractmethod+ def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:+ """Render stored doc content and write it to a server-visible output path.++ Raises:+ NotFoundError: when the document or requested parsed content is not cached.+ InvalidRequestError: when tier, pages, format, output, or marker options are invalid.+ MineruError: for render, filesystem, or server-side failures.+ """+ raise NotImplementedError()+@abstractmethoddef search(self,@@ -272,7 +313,17 @@ class DoclibInterface(ABC):raise NotImplementedError()@abstractmethod- def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:+ def get_config_key(self, key: str) -> ConfigValueResponse:+ """Return one runtime config key.++ Raises:+ InvalidRequestError: when the key is unknown.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def set_config(self, key: str, request: ConfigSetRequest) -> ConfigSetResponse:"""Set one runtime config key.Raises:@@ -281,6 +332,16 @@ class DoclibInterface(ABC):"""raise NotImplementedError()+ @abstractmethod+ def unset_config(self, key: str) -> ConfigUnsetResponse:+ """Remove one runtime config override and return the resulting default-backed value.++ Raises:+ InvalidRequestError: when the key is unknown.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()+@abstractmethoddef add_watch(self, request: WatchRequest) -> WatchInfo:"""Add a watch target.@@ -303,12 +364,12 @@ class DoclibInterface(ABC):raise NotImplementedError()@abstractmethod- def remove_watch(self, path: str) -> RemoveWatchResponse:+ def remove_watch(self, watch_id: int) -> RemoveWatchResponse:"""Remove a watch target.Raises:NotFoundError: when the watch target does not exist.- InvalidRequestError: when the path is malformed.+ InvalidRequestError: when ``watch_id`` is invalid.MineruError: for server-side failures."""raise NotImplementedError()@@ -437,6 +498,7 @@ class AsyncDoclibInterface(ABC):status: str | None = None,pages: str | None = None,include_superseded: bool = False,+ limit: int = 50,) -> ListParsesResponse:"""Async version of ``DoclibInterface.list_parses``."""raise NotImplementedError()@@ -466,7 +528,7 @@ class AsyncDoclibInterface(ABC):self,*,limit: int = 50,- status: ScanTaskStatus | None = None,+ status: ScanStatus | None = None,kind: ScanKind | None = None,watch_id: int | None = None,) -> ScanListResponse:@@ -479,7 +541,26 @@ class AsyncDoclibInterface(ABC):raise NotImplementedError()@abstractmethod- async def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ async def list_files(+ self,+ *,+ status: FileStatus | None = None,+ ext: str | None = None,+ watch_id: int | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> ListFilesResponse:+ """Async version of ``DoclibInterface.list_files``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_docs(+ self,+ *,+ path: str | None = None,+ file_type: str | None = None,+ limit: int = 200,+ ) -> ListDocsResponse:"""Async version of ``DoclibInterface.list_docs``."""raise NotImplementedError()@@ -496,12 +577,16 @@ class AsyncDoclibInterface(ABC):tier: Tier,pages: str | None = None,format: str = "markdown",- output: str | None = None,no_marker: bool = False,) -> DocContentResponse:"""Async version of ``DoclibInterface.get_doc_content``."""raise NotImplementedError()+ @abstractmethod+ async def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:+ """Async version of ``DoclibInterface.export_doc_content``."""+ raise NotImplementedError()+@abstractmethodasync def search(self,@@ -532,10 +617,20 @@ class AsyncDoclibInterface(ABC):raise NotImplementedError()@abstractmethod- async def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:+ async def get_config_key(self, key: str) -> ConfigValueResponse:+ """Async version of ``DoclibInterface.get_config_key``."""+ raise NotImplementedError()++ @abstractmethod+ async def set_config(self, key: str, request: ConfigSetRequest) -> ConfigSetResponse:"""Async version of ``DoclibInterface.set_config``."""raise NotImplementedError()+ @abstractmethod+ async def unset_config(self, key: str) -> ConfigUnsetResponse:+ """Async version of ``DoclibInterface.unset_config``."""+ raise NotImplementedError()+@abstractmethodasync def add_watch(self, request: WatchRequest) -> WatchInfo:"""Async version of ``DoclibInterface.add_watch``."""@@ -547,7 +642,7 @@ class AsyncDoclibInterface(ABC):raise NotImplementedError()@abstractmethod- async def remove_watch(self, path: str) -> RemoveWatchResponse:+ async def remove_watch(self, watch_id: int) -> RemoveWatchResponse:"""Async version of ``DoclibInterface.remove_watch``."""raise NotImplementedError()diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 0701d084..20008c8d 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections.abc import Callablefrom typing import Any, Final, TypeVarimport httpx@@ -22,6 +23,10 @@ from .types import (ConfigResponse,ConfigSetRequest,ConfigSetResponse,+ ConfigUnsetResponse,+ ConfigValueResponse,+ DocContentExportRequest,+ DocContentExportResponse,DocContentResponse,DocInfo,ExcludeRuleInfo,@@ -34,6 +39,7 @@ from .types import (InvalidateRequest,InvalidateResponse,ListDocsResponse,+ ListFilesResponse,ListParsesResponse,ParseInfo,ParseRequest,@@ -48,7 +54,8 @@ from .types import (ScanKind,ScanListResponse,ScanRequest,- ScanTaskStatus,+ FileStatus,+ ScanStatus,SearchResponse,ServerStatusResponse,ShutdownResponse,@@ -86,7 +93,7 @@ class DoclibClient(DoclibInterface):def get_server_status(self) -> ServerStatusResponse:return self._request_model(ServerStatusResponse)- @route("POST", "/shutdown", tags=("server",))+ @route("POST", "/server/shutdown", tags=("server",))def shutdown_server(self) -> ShutdownResponse:return self._request_model(ShutdownResponse)@@ -104,6 +111,7 @@ class DoclibClient(DoclibInterface):status: str | None = None,pages: str | None = None,include_superseded: bool = False,+ limit: int = 50,) -> ListParsesResponse:return self._request_model(ListParsesResponse,@@ -114,6 +122,7 @@ class DoclibClient(DoclibInterface):"status": status,"pages": pages,"include_superseded": include_superseded,+ "limit": limit,},)@@ -138,7 +147,7 @@ class DoclibClient(DoclibInterface):self,*,limit: int = 50,- status: ScanTaskStatus | None = None,+ status: ScanStatus | None = None,kind: ScanKind | None = None,watch_id: int | None = None,) -> ScanListResponse:@@ -151,9 +160,30 @@ class DoclibClient(DoclibInterface):def get_scan(self, scan_id: int) -> ScanInfo:return self._request_model(ScanInfo, path_params={"scan_id": scan_id})+ @route("GET", "/files", tags=("files",))+ def list_files(+ self,+ *,+ status: FileStatus | None = None,+ ext: str | None = None,+ watch_id: int | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> ListFilesResponse:+ return self._request_model(+ ListFilesResponse,+ params={"status": status, "ext": ext, "watch_id": watch_id, "limit": limit, "offset": offset},+ )+@route("GET", "/docs", tags=("docs",))- def list_docs(self, *, path: str | None = None) -> ListDocsResponse:- return self._request_model(ListDocsResponse, params={"path": path})+ def list_docs(+ self,+ *,+ path: str | None = None,+ file_type: str | None = None,+ limit: int = 200,+ ) -> ListDocsResponse:+ return self._request_model(ListDocsResponse, params={"path": path, "file_type": file_type, "limit": limit})@route("GET", "/docs/{sha256}", tags=("docs",))def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:@@ -167,7 +197,6 @@ class DoclibClient(DoclibInterface):tier: Tier,pages: str | None = None,format: str = "markdown",- output: str | None = None,no_marker: bool = False,) -> DocContentResponse:return self._request_model(@@ -177,11 +206,14 @@ class DoclibClient(DoclibInterface):"tier": tier,"pages": pages,"format": format,- "output": output,"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)+@route("GET", "/search", tags=("search",))def search(self,@@ -195,7 +227,14 @@ class DoclibClient(DoclibInterface):) -> SearchResponse:return self._request_model(SearchResponse,- params={"query": query, "file_type": file_type, "tier": tier, "min_tier": min_tier, "limit": limit, "offset": offset},+ params={+ "query": query,+ "file_type": file_type,+ "tier": tier,+ "min_tier": min_tier,+ "limit": limit,+ "offset": offset,+ },)@route("GET", "/find", tags=("search",))@@ -206,47 +245,55 @@ class DoclibClient(DoclibInterface):def get_file_info(self, path: str) -> FileInfoResponse:return self._request_model(FileInfoResponse, params={"path": path})- @route("GET", "/config", tags=("config",))+ @route("GET", "/configs", tags=("config",))def get_config(self) -> ConfigResponse:return self._request_model(ConfigResponse)- @route("POST", "/config", tags=("config",))- def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:- return self._request_model(ConfigSetResponse, body=request)+ @route("GET", "/configs/{key}", tags=("config",))+ def get_config_key(self, key: str) -> ConfigValueResponse:+ return self._request_model(ConfigValueResponse, path_params={"key": key})++ @route("PUT", "/configs/{key}", tags=("config",))+ def set_config(self, key: str, request: ConfigSetRequest) -> ConfigSetResponse:+ return self._request_model(ConfigSetResponse, path_params={"key": key}, body=request)++ @route("DELETE", "/configs/{key}", tags=("config",))+ def unset_config(self, key: str) -> ConfigUnsetResponse:+ return self._request_model(ConfigUnsetResponse, path_params={"key": key})- @route("POST", "/config/watch", tags=("config",))+ @route("POST", "/watches", tags=("watches",))def add_watch(self, request: WatchRequest) -> WatchInfo:return self._request_model(WatchInfo, body=request)- @route("GET", "/config/watch", tags=("config",))+ @route("GET", "/watches", tags=("watches",))def list_watches(self) -> WatchListResponse:return self._request_model(WatchListResponse)- @route("DELETE", "/config/watch", tags=("config",))- def remove_watch(self, path: str) -> RemoveWatchResponse:- return self._request_model(RemoveWatchResponse, params={"path": path})+ @route("DELETE", "/watches/{watch_id}", tags=("watches",))+ def remove_watch(self, watch_id: int) -> RemoveWatchResponse:+ return self._request_model(RemoveWatchResponse, path_params={"watch_id": watch_id})- @route("POST", "/config/exclude", tags=("config",))+ @route("POST", "/exclude-rules", tags=("rules",))def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:return self._request_model(ExcludeRuleInfo, body=request)- @route("GET", "/config/exclude", tags=("config",))+ @route("GET", "/exclude-rules", tags=("rules",))def list_exclude_rules(self) -> ExcludeRuleListResponse:return self._request_model(ExcludeRuleListResponse)- @route("DELETE", "/config/exclude/{rule_id}", tags=("config",))+ @route("DELETE", "/exclude-rules/{rule_id}", tags=("rules",))def remove_exclude_rule(self, rule_id: int) -> RemoveExcludeRuleResponse:return self._request_model(RemoveExcludeRuleResponse, path_params={"rule_id": rule_id})- @route("POST", "/config/parsing-rules", tags=("config",))+ @route("POST", "/parsing-rules", tags=("rules",))def add_parsing_rule(self, request: ParsingRuleRequest) -> ParsingRuleInfo:return self._request_model(ParsingRuleInfo, body=request)- @route("GET", "/config/parsing-rules", tags=("config",))+ @route("GET", "/parsing-rules", tags=("rules",))def list_parsing_rules(self) -> ParsingRuleListResponse:return self._request_model(ParsingRuleListResponse)- @route("DELETE", "/config/parsing-rules/{rule_id}", tags=("config",))+ @route("DELETE", "/parsing-rules/{rule_id}", tags=("rules",))def remove_parsing_rule(self, rule_id: int) -> RemoveParsingRuleResponse:return self._request_model(RemoveParsingRuleResponse, path_params={"rule_id": rule_id})@@ -280,6 +327,8 @@ class DoclibClient(DoclibInterface):resp = self._client.get(path, params=query_params)elif route_info.method == "POST":resp = self._client.post(path, params=query_params, json=json_data or {})+ elif route_info.method == "PUT":+ resp = self._client.put(path, params=query_params, json=json_data or {})elif route_info.method == "DELETE":resp = self._client.delete(path, params=query_params)else:@@ -290,7 +339,7 @@ class DoclibClient(DoclibInterface):data = _decode_response(resp)return response_model.model_validate(data)- def _calling_route_method(self) -> object:+ def _calling_route_method(self) -> Callable[..., Any]:import inspectframe = inspect.currentframe()diff --git a/mineru/doclib/config_defaults.py b/mineru/doclib/config_defaults.pynew file mode 100644index 00000000..41021959--- /dev/null+++ b/mineru/doclib/config_defaults.py@@ -0,0 +1,25 @@+"""Code-backed default values for doclib runtime config."""++from __future__ import annotations++from typing import Literal++ConfigSource = Literal["default", "override"]++CONFIG_DEFAULTS: dict[str, str] = {+ "data_dir": "~/MinerU",+ "default_tier": "flash",+ "scan_interval_sec": "300",+ "ingest_lock_timeout_sec": "60",+ "parse_lock_timeout_sec": "1800",+ "device_check_interval_sec": "5",+ "parse_server.local.mode": "disabled",+ "parse_server.local.managed_tier": "standard",+ "parse_server.local.self_hosted_url": "",+ "parse_server.local.self_hosted_api_key": "",+ "parse_server.remote.url": "https://mineru.net/api",+ "parse_server.remote.api_key": "",+}++CONFIG_SOURCE_DEFAULT: ConfigSource = "default"+CONFIG_SOURCE_OVERRIDE: ConfigSource = "override"diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.pyindex de2d92bf..6b74668f 100644--- a/mineru/doclib/core/db.py+++ b/mineru/doclib/core/db.py@@ -7,6 +7,7 @@ from pathlib import Pathimport aiosqlitefrom ...config import SQLiteConfig+from ..config_defaults import CONFIG_DEFAULTSSCHEMA_VERSION = 1_MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"@@ -26,18 +27,6 @@ def _load_init_sql() -> list[str]:_CREATE_TABLES_SQL = _load_init_sql()-DEFAULT_CONFIG = {- "data_dir": "~/MinerU",- "default_tier": "flash",- "scan_interval_sec": "300",- "ingest_lock_timeout_sec": "60",- "parse_lock_timeout_sec": "1800",- "device_check_interval_sec": "5",- "parse_server.local.mode": "disabled",- "parse_server.local.managed_tier": "standard",- "parse_server.remote.url": "https://mineru.net/api",-}-DEFAULT_EXCLUDE_RULES = [("系统-*/Library/*", "*/Library/*"),("系统-*/.git/*", "*/.git/*"),@@ -106,10 +95,10 @@ class DatabaseManager:)# ── seed data ───────────────────────────────────────────- for key, value in DEFAULT_CONFIG.items():- await conn.execute(- "INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)", (key, value)- )+ # Config defaults are code-backed; the DB config table stores overrides only.+ # Clean legacy seeded rows whose values exactly match current defaults.+ for key, value in CONFIG_DEFAULTS.items():+ await conn.execute("DELETE FROM config WHERE key=? AND value=?", (key, value))now = _now_ms()for name, pattern in DEFAULT_EXCLUDE_RULES:@@ -148,6 +137,8 @@ class DatabaseManager:await conn.commit()lastid = cursor.lastrowidawait conn.close()+ if lastid is None:+ raise RuntimeError("SQLite insert did not return a row id.")return lastidasync def fetchone(self, sql: str, params: tuple | None = None) -> dict | None:diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.pyindex 0b93e020..1bc4b4df 100644--- a/mineru/doclib/core/file_io.py+++ b/mineru/doclib/core/file_io.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport hashlibimport os+from dataclasses import dataclassfrom pathlib import Pathimport pypdfium2@@ -15,7 +16,7 @@ try:except ImportError:Document = None # type: ignore[assignment]try:- from pptx import Presentation+ from pptx import Presentation # type: ignore[reportMissingImports]except ImportError:Presentation = None # type: ignore[assignment]try:@@ -48,13 +49,16 @@ async def compute_sha256(filepath: str) -> str:# ── file stat ──────────────────────────────────────────────────────-async def get_file_stat(filepath: str) -> dict:- def _stat() -> dict:+@dataclass(frozen=True)+class FileStat:+ size_bytes: int+ mtime_ms: int+++async def get_file_stat(filepath: str) -> FileStat:+ def _stat() -> FileStat:st = os.stat(filepath)- return {- "size_bytes": st.st_size,- "mtime_ms": int(st.st_mtime * 1000),- }+ return FileStat(size_bytes=st.st_size, mtime_ms=int(st.st_mtime * 1000))return await asyncio.to_thread(_stat)@@ -73,7 +77,7 @@ async def extract_metadata(filepath: str) -> dict:"author": None,"subject": None,"keywords": None,- "is_scanned": 0,+ "is_image_based": 0,}if ext == "pdf":diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.pyindex b792e8e0..62256743 100644--- a/mineru/doclib/core/fts.py+++ b/mineru/doclib/core/fts.py@@ -10,6 +10,7 @@ except ImportError:jieba = None # type: ignore[assignment]from ...types import Tier+from ..rows import FtsContentSearchRow, FtsFilenameSearchRowfrom .db import DatabaseManagerFTS_SEP = ""@@ -70,18 +71,21 @@ class FTSManager:])- async def search(self, query: str, limit: int = 200) -> list[dict]:+ async def search(self, query: str, limit: int = 200) -> list[FtsContentSearchRow]:tokens = _sanitize_query_tokens(tokenize_for_query(query))if not tokens:return []fts_query = " ".join(tokens)try:- return await self.db.fetchall(- "SELECT sha256, title, author, filename, tier, "- "snippet(fts_contents, 2, '<mark>', '</mark>', '...', 40) AS snippet, rank "- "FROM fts_contents WHERE fts_contents MATCH ? "- "ORDER BY rank LIMIT ?",- (fts_query, limit),+ return cast(+ list[FtsContentSearchRow],+ await self.db.fetchall(+ "SELECT sha256, title, author, filename, tier, "+ "snippet(fts_contents, 2, '<mark>', '</mark>', '...', 40) AS snippet, rank "+ "FROM fts_contents WHERE fts_contents MATCH ? "+ "ORDER BY rank LIMIT ?",+ (fts_query, limit),+ ),)except Exception:return []@@ -108,18 +112,21 @@ class FTSManager:])- async def search_filenames(self, query: str, limit: int = 50) -> list[dict]:+ async def search_filenames(self, query: str, limit: int = 50) -> list[FtsFilenameSearchRow]:tokens = _sanitize_query_tokens(tokenize_for_query(query))if not tokens:return []fts_query = " ".join(tokens)try:- return await self.db.fetchall(- "SELECT file_id, ext, "- "snippet(fts_filenames, 1, '<mark>', '</mark>', '...', 40) AS snippet "- "FROM fts_filenames WHERE fts_filenames MATCH ? "- "ORDER BY rank LIMIT ?",- (fts_query, limit),+ return cast(+ list[FtsFilenameSearchRow],+ await self.db.fetchall(+ "SELECT file_id, ext, "+ "snippet(fts_filenames, 1, '<mark>', '</mark>', '...', 40) AS snippet "+ "FROM fts_filenames WHERE fts_filenames MATCH ? "+ "ORDER BY rank LIMIT ?",+ (fts_query, limit),+ ),)except Exception:return []diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sqlindex ebbe0f07..65851b0f 100644--- a/mineru/doclib/migrations/001_init.sql+++ b/mineru/doclib/migrations/001_init.sql@@ -9,8 +9,8 @@ CREATE TABLE IF NOT EXISTS files (size_bytes INTEGER NOT NULL,mtime_ms INTEGER NOT NULL,sha256 TEXT REFERENCES docs(sha256),- watch_id INTEGER REFERENCES watch_targets(id),- scan_status TEXT NOT NULL DEFAULT 'active',+ watch_id INTEGER REFERENCES watches(id),+ status TEXT NOT NULL DEFAULT 'active',locked_at INTEGER,error_code TEXT,error_msg TEXT,@@ -19,8 +19,8 @@ CREATE TABLE IF NOT EXISTS files (updated_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS idx_files_watch_id ON files(watch_id);-CREATE INDEX IF NOT EXISTS idx_files_scan_status ON files(scan_status);-CREATE INDEX IF NOT EXISTS idx_files_sha256_status ON files(sha256, scan_status);+CREATE INDEX IF NOT EXISTS idx_files_status ON files(status);+CREATE INDEX IF NOT EXISTS idx_files_sha256_status ON files(sha256, status);CREATE TABLE IF NOT EXISTS docs (sha256 TEXT PRIMARY KEY NOT NULL,@@ -32,7 +32,7 @@ CREATE TABLE IF NOT EXISTS docs (author TEXT,subject TEXT,keywords TEXT,- is_scanned INTEGER NOT NULL DEFAULT 0,+ is_image_based INTEGER NOT NULL DEFAULT 0,meta_tier TEXT,error_code TEXT,error_msg TEXT,@@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS scans (path TEXT NOT NULL,kind TEXT NOT NULL,source TEXT NOT NULL DEFAULT 'unknown',- watch_id INTEGER REFERENCES watch_targets(id),+ watch_id INTEGER REFERENCES watches(id),status TEXT NOT NULL DEFAULT 'pending',locked_at INTEGER,files_seen INTEGER NOT NULL DEFAULT 0,@@ -85,7 +85,7 @@ CREATE TABLE IF NOT EXISTS scans ();CREATE INDEX IF NOT EXISTS idx_scans_status ON scans(status, created_at ASC);CREATE INDEX IF NOT EXISTS idx_scans_kind_path_status ON scans(kind, path, status);-CREATE INDEX IF NOT EXISTS idx_scans_watch_status ON scans(watch_id, status);+CREATE INDEX IF NOT EXISTS idx_scans_watch_id_status ON scans(watch_id, status);CREATE VIRTUAL TABLE IF NOT EXISTS fts_contents USING fts5(sha256 UNINDEXED,@@ -104,14 +104,14 @@ CREATE VIRTUAL TABLE IF NOT EXISTS fts_filenames USING fts5(tokenize='unicode61');-CREATE TABLE IF NOT EXISTS watch_targets (+CREATE TABLE IF NOT EXISTS watches (id INTEGER PRIMARY KEY,path TEXT NOT NULL UNIQUE,label TEXT,removable INTEGER NOT NULL DEFAULT 0,enabled INTEGER NOT NULL DEFAULT 1,recursive INTEGER NOT NULL DEFAULT 0,- watch_status TEXT NOT NULL DEFAULT 'active',+ status TEXT NOT NULL DEFAULT 'active',unreachable_at INTEGER,last_scan_at INTEGER,last_scan_files INTEGER NOT NULL DEFAULT 0,diff --git a/mineru/doclib/rows.py b/mineru/doclib/rows.pynew file mode 100644index 00000000..51c603cc--- /dev/null+++ b/mineru/doclib/rows.py@@ -0,0 +1,270 @@+"""Typed SQLite row shapes used inside doclib services."""++from __future__ import annotations++from typing import NotRequired, TypedDict++from ..types import Tier+from .types import ParseStatus, RuleType, ScanKind, ScanSource, FileStatus, ScanStatus, WatchStatus+++class FileRow(TypedDict):+ id: int+ path: str+ filename: str+ ext: str+ size_bytes: int+ mtime_ms: int+ sha256: str | None+ watch_id: int | None+ status: FileStatus+ locked_at: int | None+ error_code: str | None+ error_msg: str | None+ deleted_at: int | None+ first_seen_at: int+ updated_at: int+++class DocRow(TypedDict):+ sha256: str+ size_bytes: int+ file_type: str | None+ page_count: int | None+ language: str | None+ title: str | None+ author: str | None+ subject: str | None+ keywords: str | None+ is_image_based: int+ meta_tier: Tier | None+ error_code: str | None+ error_msg: str | None+ first_seen_at: int+ updated_at: int+++class ParseRow(TypedDict):+ id: int+ sha256: str+ tier: Tier+ pages: str+ status: ParseStatus+ priority: int+ locked_at: int | None+ error_code: str | None+ error_msg: str | None+ privacy: str+ via: str | None+ done_at: int | None+ created_at: int+ updated_at: int+++class ScanRow(TypedDict):+ id: int+ path: str+ kind: ScanKind+ source: ScanSource+ watch_id: int | None+ status: ScanStatus+ locked_at: int | None+ files_seen: int+ files_refreshed: int+ files_new: int+ files_changed: int+ files_deleted: int+ files_unreachable: int+ files_error: int+ files_unsupported: int+ files_excluded: int+ error_code: str | None+ error_msg: str | None+ started_at: int | None+ finished_at: int | None+ created_at: int+ updated_at: int+++class WatchTargetRow(TypedDict):+ id: int+ path: str+ label: str | None+ removable: int+ enabled: int+ recursive: int+ status: WatchStatus+ unreachable_at: int | None+ last_scan_at: int | None+ last_scan_files: int+ created_at: int+ updated_at: int+++class ExcludeRuleRow(TypedDict):+ id: int+ name: str | None+ pattern: str+ enabled: int+ priority: int+ hit_count: int+ created_at: int+ updated_at: int+ rule_type: NotRequired[RuleType]+ tier: NotRequired[None]+ pages: NotRequired[None]+ remote: NotRequired[int]+++class ParsingRuleRow(TypedDict):+ id: int+ name: str | None+ pattern: str+ tier: Tier | None+ pages: str | None+ remote: int+ enabled: int+ priority: int+ hit_count: int+ created_at: int+ updated_at: int+ rule_type: NotRequired[RuleType]+++RuleRow = ExcludeRuleRow | ParsingRuleRow+++class ConfigRow(TypedDict):+ key: str+ value: str+++class IdRow(TypedDict):+ id: int+++class PathRow(TypedDict):+ path: str+++class CountRow(TypedDict):+ cnt: int+++class PageCountRow(TypedDict):+ page_count: int | None+++class Sha256Row(TypedDict):+ sha256: str | None+++class ParseGroupRow(TypedDict):+ sha256: str+ tier: Tier+++class ParseBatchRow(TypedDict):+ pages: str+ done_at: int | None+++class IngestTaskRow(TypedDict):+ id: int+ path: str+ watch_id: int | None+++class FtsContentSearchRow(TypedDict):+ sha256: str+ title: str+ author: str+ filename: str+ tier: Tier+ snippet: str+ rank: float+++class FtsFilenameSearchRow(TypedDict):+ file_id: int+ ext: str+ snippet: str+++class SearchFileRow(FileRow):+ title: str | None+ author: str | None+ page_count: int | None+ file_type: str | None+++class FilenameSearchFileRow(FileRow):+ title: str | None+++class ContentSearchResultRow(TypedDict):+ sha256: str+ title: str | None+ author: str | None+ filename: str | None+ ext: str | None+ size_bytes: int | None+ tier: Tier+ snippet: str+ paths: list[str]+++class FilenameSearchResultRow(TypedDict):+ sha256: str | None+ title: str | None+ filename: str+ ext: str | None+ size_bytes: int | None+ tier: str+ snippet: str+ paths: list[str]+++class WatchStatsFileRow(TypedDict):+ watch_id: int+ total_files: int+ active_files: int+ deleted_files: int+ unreachable_files: int+ pending_ingest_files: int+ file_error_count: int+ doc_count: int+++class WatchParseCountRow(TypedDict):+ watch_id: int+ status: ParseStatus+ cnt: int+++class ErrorBucketRow(TypedDict):+ code: str+ cnt: int+++class RecentScanRow(TypedDict):+ id: int+ path: str+ kind: ScanKind+ source: ScanSource+ watch_id: int | None+ status: ScanStatus+ files_seen: int+ files_refreshed: int+ files_new: int+ files_changed: int+ files_deleted: int+ files_unreachable: int+ files_error: int+ files_unsupported: int+ files_excluded: int+ error_code: str | None+ started_at: int | None+ finished_at: int | None+ created_at: int+ updated_at: intdiff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 2feff92b..809f23fc 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -16,8 +16,35 @@ from ..render import render_markdownfrom ..types import TIERS, Tierfrom .background.parse_server_health import get_healthfrom .base import AsyncDoclibInterface+from .core.db import DatabaseManager+from .rows import (+ ContentSearchResultRow,+ DocRow,+ ErrorBucketRow,+ ExcludeRuleRow,+ FilenameSearchResultRow,+ FileRow,+ ParseBatchRow,+ ParseRow,+ ParsingRuleRow,+ RecentScanRow,+ Sha256Row,+ WatchParseCountRow,+ WatchStatsFileRow,+ WatchTargetRow,+)from .services.parse_svc import filter_pages_by_user_range, load_pages_from_done_batches, parse_range_setfrom .types import (+ PARSE_STATUS_DONE,+ PARSE_STATUS_FAILED,+ PARSE_STATUS_PARSING,+ PARSE_STATUS_PENDING,+ PARSE_STATUS_SUPERSEDED,+ RULE_TYPE_EXCLUDE,+ RULE_TYPE_PARSING_RULE,+ FILE_STATUS_ACTIVE,+ FILE_STATUS_DELETED,+ FILE_STATUS_UNREACHABLE,CleanupDeletedRequest,CleanupDeletedResponse,CleanupOrphansRequest,@@ -27,6 +54,10 @@ from .types import (ConfigResponse,ConfigSetRequest,ConfigSetResponse,+ ConfigUnsetResponse,+ ConfigValueResponse,+ DocContentExportRequest,+ DocContentExportResponse,DocContentResponse,DocInfo,ErrorBucket,@@ -36,6 +67,7 @@ from .types import (ExcludeRuleRequest,FileInfo,FileInfoResponse,+ ListFilesResponse,FindResponse,FindResult,ForgetPathRequest,@@ -45,16 +77,6 @@ from .types import (ListDocsResponse,ListParsesResponse,LocalParseServerStatus,- PARSE_STATUS_DONE,- PARSE_STATUS_FAILED,- PARSE_STATUS_PARSING,- PARSE_STATUS_PENDING,- PARSE_STATUS_SUPERSEDED,- RULE_TYPE_EXCLUDE,- RULE_TYPE_PARSING_RULE,- SCAN_STATUS_ACTIVE,- SCAN_STATUS_DELETED,- SCAN_STATUS_UNREACHABLE,ParseCoverage,ParseInfo,ParseRequest,@@ -68,15 +90,16 @@ from .types import (RemoveExcludeRuleResponse,RemoveParsingRuleResponse,RemoveWatchResponse,- SearchResponse,- SearchResult,- ServerStatusResponse,- ShutdownResponse,ScanInfo,ScanKind,ScanListResponse,ScanRequest,- ScanTaskStatus,+ FileStatus,+ ScanStatus,+ SearchResponse,+ SearchResult,+ ServerStatusResponse,+ ShutdownResponse,TierParseInfo,WatchInfo,WatchListResponse,@@ -122,12 +145,12 @@ class DoclibServer(AsyncDoclibInterface):@route("GET", "/server/status", tags=("server",))async def get_server_status(self) -> ServerStatusResponse:files_total = await self.state.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE scan_status=?", (SCAN_STATUS_ACTIVE,)+ "SELECT COUNT(*) as cnt FROM files WHERE status=?", (FILE_STATUS_ACTIVE,))docs_total = await self.state.db.fetchone("SELECT COUNT(*) as cnt FROM docs")ingest_q = await self.state.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status=? AND error_code IS NULL",- (SCAN_STATUS_ACTIVE,),+ "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND status=? AND error_code IS NULL",+ (FILE_STATUS_ACTIVE,),)watches = await self.state.config_svc.list_watches()uptime = time.time() - self.state.start_time if hasattr(self.state, "start_time") else 0@@ -151,7 +174,7 @@ class DoclibServer(AsyncDoclibInterface):recent_logs=_tail_log(getattr(self.state, "data_dir", "")),)- @route("POST", "/shutdown", tags=("server",))+ @route("POST", "/server/shutdown", tags=("server",))async def shutdown_server(self) -> ShutdownResponse:if hasattr(self.state, "shutdown"):result = self.state.shutdown()@@ -182,6 +205,7 @@ class DoclibServer(AsyncDoclibInterface):status: str | None = None,pages: str | None = None,include_superseded: bool = False,+ limit: int = 50,) -> ListParsesResponse:rows = await self._select_parse_rows(ids=ids,@@ -189,6 +213,7 @@ class DoclibServer(AsyncDoclibInterface):tier=tier,status=status,include_superseded=include_superseded,+ limit=limit,)coverage = _parse_coverage(pages, rows) if sha256 and tier and pages else Nonereturn ListParsesResponse(parses=[_parse_info(row, coverage=coverage) for row in rows], coverage=coverage)@@ -233,7 +258,7 @@ class DoclibServer(AsyncDoclibInterface):self,*,limit: int = 50,- status: ScanTaskStatus | None = None,+ status: ScanStatus | None = None,kind: ScanKind | None = None,watch_id: int | None = None,) -> ScanListResponse:@@ -244,21 +269,76 @@ class DoclibServer(AsyncDoclibInterface):async def get_scan(self, scan_id: int) -> ScanInfo:return await self.state.scan_svc.get_scan(scan_id)+ @route("GET", "/files", tags=("files",))+ async def list_files(+ self,+ *,+ status: FileStatus | None = None,+ ext: str | None = None,+ watch_id: int | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> ListFilesResponse:+ limit = max(1, min(limit, 200))+ offset = max(0, offset)+ file_status = status or FILE_STATUS_ACTIVE+ clauses = ["status=?"]+ params: list[Any] = [file_status]+ if ext:+ clauses.append("ext=?")+ params.append(ext.lstrip(".").lower())+ if watch_id is not None:+ clauses.append("watch_id=?")+ params.append(watch_id)+ where = " AND ".join(clauses)+ total_row = await self.state.db.fetchone(f"SELECT COUNT(*) AS cnt FROM files WHERE {where}", tuple(params))+ rows = cast(+ list[FileRow],+ await self.state.db.fetchall(+ f"SELECT * FROM files WHERE {where} ORDER BY updated_at DESC LIMIT ? OFFSET ?",+ (*params, limit, offset),+ ),+ )+ total = total_row["cnt"] if total_row else 0+ return ListFilesResponse(files=[_file_info(row) for row in rows], total=total, limit=limit, offset=offset)+@route("GET", "/docs", tags=("docs",))- async def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ async def list_docs(+ self,+ *,+ path: str | None = None,+ file_type: str | None = None,+ limit: int = 200,+ ) -> ListDocsResponse:+ limit = max(1, min(limit, 200))+ clauses: list[str] = []+ params: list[Any] = []+ if file_type:+ clauses.append("d.file_type=?")+ params.append(file_type.lstrip(".").lower())if path:await self.state.parse_svc.ensure_ingested(path)+ clauses.extend(["f.path=?", "f.status=?"])+ params.extend([path, FILE_STATUS_ACTIVE])rows = await self.state.db.fetchall(- "SELECT d.* FROM docs d JOIN files f ON f.sha256=d.sha256 "- "WHERE f.path=? AND f.scan_status=?",- (path, SCAN_STATUS_ACTIVE),+ f"SELECT d.* FROM docs d JOIN files f ON f.sha256=d.sha256 WHERE {' AND '.join(clauses)} "+ "ORDER BY d.updated_at DESC LIMIT ?",+ (*params, limit),)else:+ if clauses:+ clauses.append(+ "EXISTS (SELECT 1 FROM files f WHERE f.sha256=d.sha256 AND f.status=?)"+ )+ params.append(FILE_STATUS_ACTIVE)+ else:+ clauses.append(+ "EXISTS (SELECT 1 FROM files f WHERE f.sha256=d.sha256 AND f.status=?)"+ )+ params.append(FILE_STATUS_ACTIVE)rows = await self.state.db.fetchall(- "SELECT d.* FROM docs d WHERE EXISTS ("- " SELECT 1 FROM files f WHERE f.sha256=d.sha256 AND f.scan_status=?"- ") ORDER BY d.updated_at DESC LIMIT 200",- (SCAN_STATUS_ACTIVE,),+ f"SELECT d.* FROM docs d WHERE {' AND '.join(clauses)} ORDER BY d.updated_at DESC LIMIT ?",+ (*params, limit),)return ListDocsResponse(docs=[_doc_info(row) for row in rows])@@ -278,31 +358,25 @@ class DoclibServer(AsyncDoclibInterface):tier: Tier,pages: str | None = None,format: str = "markdown",- output: str | None = None,no_marker: bool = False,) -> DocContentResponse:- if format != "markdown":- raise InvalidRequestError("invalid_request", "Only markdown is currently implemented.", "format")- data_dir = getattr(self.state, "data_dir", os.path.expanduser("~/MinerU"))- rows = await self.state.db.fetchall(- "SELECT pages, done_at FROM parses WHERE sha256=? AND tier=? AND status=? ORDER BY done_at DESC",- (sha256, tier, PARSE_STATUS_DONE),- )- loaded_pages = load_pages_from_done_batches(data_dir, sha256, tier, rows)- if pages:- loaded_pages = filter_pages_by_user_range(loaded_pages, pages)- if not loaded_pages:- raise NotFoundError("not_cached", "Requested parsed content is not cached.", "pages")+ content = await self._render_doc_content(sha256, tier=tier, pages=pages, format=format, no_marker=no_marker)+ return DocContentResponse(sha256=sha256, tier=tier, content=content)- content = render_markdown(loaded_pages, add_markers=not no_marker)- output_path = None- if output and output != "-":- output_path = os.path.abspath(output)- os.makedirs(os.path.dirname(output_path), exist_ok=True)- with open(output_path, "w", encoding="utf-8") as f:- f.write(content)- content = None- return DocContentResponse(sha256=sha256, tier=tier, content=content, output=output_path)+ @route("POST", "/docs/{sha256}/exports", tags=("docs",))+ async def export_doc_content(self, sha256: str, request: DocContentExportRequest) -> DocContentExportResponse:+ content = await self._render_doc_content(+ sha256,+ tier=request.tier,+ pages=request.pages,+ format=request.format,+ no_marker=request.no_marker,+ )+ output_path = os.path.abspath(request.output)+ os.makedirs(os.path.dirname(output_path), exist_ok=True)+ with open(output_path, "w", encoding="utf-8") as f:+ f.write(content)+ return DocContentExportResponse(sha256=sha256, tier=request.tier, output=output_path)@route("GET", "/search", tags=("search",))async def search(@@ -323,7 +397,9 @@ class DoclibServer(AsyncDoclibInterface):limit=limit,offset=offset,)- return SearchResponse(results=[_search_result(row) for row in results if row.get("tier") in TIERS], total=total, query=query)+ return SearchResponse(+ results=[_search_result(row) for row in results if row.get("tier") in TIERS], total=total, query=query+ )@route("GET", "/find", tags=("search",))async def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:@@ -333,7 +409,9 @@ class DoclibServer(AsyncDoclibInterface):@route("GET", "/info", tags=("info",))async def get_file_info(self, path: str) -> FileInfoResponse:await self.state.parse_svc.ensure_ingested(path)- file_row = await self.state.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status=?", (path, SCAN_STATUS_ACTIVE))+ file_row = await self.state.db.fetchone(+ "SELECT * FROM files WHERE path=? AND status=?", (path, FILE_STATUS_ACTIVE)+ )if file_row is None:raise NotFoundError("file_not_found", f"File {path} not found.", "path")sha256 = file_row["sha256"]@@ -344,7 +422,9 @@ class DoclibServer(AsyncDoclibInterface):else [])parsed_tiers = [_tier_parse_info(row) for row in parse_rows if row["status"] == PARSE_STATUS_DONE]- active_parses = [_parse_info(row) for row in parse_rows if row["status"] in {PARSE_STATUS_PENDING, PARSE_STATUS_PARSING}]+ active_parses = [+ _parse_info(row) for row in parse_rows if row["status"] in {PARSE_STATUS_PENDING, PARSE_STATUS_PARSING}+ ]return FileInfoResponse(file=_file_info(file_row),doc=_doc_info(doc_row) if doc_row else None,@@ -352,33 +432,49 @@ class DoclibServer(AsyncDoclibInterface):active_parses=active_parses,)- @route("GET", "/config", tags=("config",))+ @route("GET", "/configs", tags=("config",))async def get_config(self) -> ConfigResponse:- return ConfigResponse(config=await self.state.config_svc.get_all())-- @route("POST", "/config", tags=("config",))- async def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:- await self.state.config_svc.set(request.key, request.value)- return ConfigSetResponse(key=request.key, value=request.value)-- @route("POST", "/config/watch", tags=("config",))+ config, sources = await self.state.config_svc.get_all_with_sources()+ return ConfigResponse(config=_mask_config(config), sources=sources)++ @route("GET", "/configs/{key}", tags=("config",))+ async def get_config_key(self, key: str) -> ConfigValueResponse:+ value = await self.state.config_svc.get(key)+ source = await self.state.config_svc.get_source(key)+ return ConfigValueResponse(key=key, value=_mask_config_value(key, value or ""), source=source)++ @route("PUT", "/configs/{key}", tags=("config",))+ async def set_config(self, key: str, request: ConfigSetRequest) -> ConfigSetResponse:+ await self.state.config_svc.set(key, request.value)+ value = await self.state.config_svc.get(key)+ source = await self.state.config_svc.get_source(key)+ return ConfigSetResponse(key=key, value=_mask_config_value(key, value or ""), source=source)++ @route("DELETE", "/configs/{key}", tags=("config",))+ async def unset_config(self, key: str) -> ConfigUnsetResponse:+ removed = await self.state.config_svc.unset(key)+ value = await self.state.config_svc.get(key)+ source = await self.state.config_svc.get_source(key)+ return ConfigUnsetResponse(key=key, value=_mask_config_value(key, value or ""), source=source, removed=removed)++ @route("POST", "/watches", tags=("watches",))async def add_watch(self, request: WatchRequest) -> WatchInfo:row = await self.state.config_svc.add_watch(request.path, removable=request.removable, label=request.label)return _watch_info(row)- @route("GET", "/config/watch", tags=("config",))+ @route("GET", "/watches", tags=("watches",))async def list_watches(self) -> WatchListResponse:return WatchListResponse(watches=[_watch_info(row) for row in await self.state.config_svc.list_watches()])- @route("DELETE", "/config/watch", tags=("config",))- async def remove_watch(self, path: str) -> RemoveWatchResponse:- existing = await self.state.db.fetchone("SELECT path FROM watch_targets WHERE path=?", (path,))+ @route("DELETE", "/watches/{watch_id}", tags=("watches",))+ async def remove_watch(self, watch_id: int) -> RemoveWatchResponse:+ existing = await self.state.db.fetchone("SELECT id FROM watches WHERE id=?", (watch_id,))if existing is None:- raise NotFoundError("watch_not_found", f"Watch target {path} not found.", "path")- await self.state.config_svc.remove_watch(path)- return RemoveWatchResponse(path=path, removed=True)+ raise NotFoundError("watch_not_found", f"Watch target {watch_id} not found.", "watch_id")+ await self.state.config_svc.remove_watch_by_id(watch_id)+ return RemoveWatchResponse(watch_id=watch_id, removed=True)- @route("POST", "/config/exclude", tags=("config",))+ @route("POST", "/exclude-rules", tags=("rules",))async def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:rule_id = await self.state.config_svc.add_rule(request.name or "",@@ -389,12 +485,12 @@ class DoclibServer(AsyncDoclibInterface):row = await self.state.db.fetchone("SELECT * FROM exclude_rules WHERE id=?", (rule_id,))return _exclude_rule_info(row)- @route("GET", "/config/exclude", tags=("config",))+ @route("GET", "/exclude-rules", tags=("rules",))async def list_exclude_rules(self) -> ExcludeRuleListResponse:rows = await self.state.config_svc.list_rules(RULE_TYPE_EXCLUDE)return ExcludeRuleListResponse(rules=[_exclude_rule_info(row) for row in rows])- @route("DELETE", "/config/exclude/{rule_id}", tags=("config",))+ @route("DELETE", "/exclude-rules/{rule_id}", tags=("rules",))async def remove_exclude_rule(self, rule_id: int) -> RemoveExcludeRuleResponse:existing = await self.state.db.fetchone("SELECT id FROM exclude_rules WHERE id=?", (rule_id,))if existing is None:@@ -402,7 +498,7 @@ class DoclibServer(AsyncDoclibInterface):await self.state.config_svc.remove_rule(rule_id, RULE_TYPE_EXCLUDE)return RemoveExcludeRuleResponse(rule_id=rule_id, removed=True)- @route("POST", "/config/parsing-rules", tags=("config",))+ @route("POST", "/parsing-rules", tags=("rules",))async def add_parsing_rule(self, request: ParsingRuleRequest) -> ParsingRuleInfo:rule_id = await self.state.config_svc.add_rule(request.name or "",@@ -416,12 +512,12 @@ class DoclibServer(AsyncDoclibInterface):row = await self.state.db.fetchone("SELECT * FROM parsing_rules WHERE id=?", (rule_id,))return _parsing_rule_info(row)- @route("GET", "/config/parsing-rules", tags=("config",))+ @route("GET", "/parsing-rules", tags=("rules",))async def list_parsing_rules(self) -> ParsingRuleListResponse:rows = await self.state.config_svc.list_rules(RULE_TYPE_PARSING_RULE)return ParsingRuleListResponse(rules=[_parsing_rule_info(row) for row in rows])- @route("DELETE", "/config/parsing-rules/{rule_id}", tags=("config",))+ @route("DELETE", "/parsing-rules/{rule_id}", tags=("rules",))async def remove_parsing_rule(self, rule_id: int) -> RemoveParsingRuleResponse:existing = await self.state.db.fetchone("SELECT id FROM parsing_rules WHERE id=?", (rule_id,))if existing is None:@@ -452,12 +548,16 @@ class DoclibServer(AsyncDoclibInterface):tier: Tier | None,status: str | None,include_superseded: bool,- ) -> list[dict[str, Any]]:+ limit: int,+ ) -> list[ParseRow]:+ limit = max(1, min(limit, 200))clauses: list[str] = []params: list[object] = []if ids:placeholders = ",".join("?" * len(ids))- rows = await self.state.db.fetchall(f"SELECT * FROM parses WHERE id IN ({placeholders})", tuple(ids))+ rows = cast(+ list[ParseRow], await self.state.db.fetchall(f"SELECT * FROM parses WHERE id IN ({placeholders})", tuple(ids))+ )by_id = {row["id"]: row for row in rows}return [by_id[parse_id] for parse_id in ids if parse_id in by_id]if sha256:@@ -478,20 +578,67 @@ class DoclibServer(AsyncDoclibInterface):sql = "SELECT * FROM parses"if clauses:sql += " WHERE " + " AND ".join(clauses)- sql += " ORDER BY created_at DESC"- return await self.state.db.fetchall(sql, tuple(params))+ sql += " ORDER BY created_at DESC LIMIT ?"+ return cast(list[ParseRow], await self.state.db.fetchall(sql, (*params, limit)))++ async def _render_doc_content(+ self,+ sha256: str,+ *,+ tier: Tier,+ pages: str | None,+ format: str,+ no_marker: bool,+ ) -> str:+ if format != "markdown":+ raise InvalidRequestError("invalid_request", "Only markdown is currently implemented.", "format")+ data_dir = getattr(self.state, "data_dir", os.path.expanduser("~/MinerU"))+ rows = await self.state.db.fetchall(+ "SELECT pages, done_at FROM parses WHERE sha256=? AND tier=? AND status=? ORDER BY done_at DESC",+ (sha256, tier, PARSE_STATUS_DONE),+ )+ loaded_pages = load_pages_from_done_batches(data_dir, sha256, tier, cast(list[ParseBatchRow], rows))+ if pages:+ loaded_pages = filter_pages_by_user_range(loaded_pages, pages)+ if not loaded_pages:+ raise NotFoundError("not_cached", "Requested parsed content is not cached.", "pages")+ return render_markdown(loaded_pages, add_markers=not no_marker)async def _sha256_for_path(self, path: str) -> str | None:- row = await self.state.db.fetchone("SELECT sha256 FROM files WHERE path=? AND scan_status=?", (path, SCAN_STATUS_ACTIVE))+ row = cast(+ Sha256Row | None,+ await self.state.db.fetchone("SELECT sha256 FROM files WHERE path=? AND status=?", (path, FILE_STATUS_ACTIVE)),+ )return row["sha256"] if row and row["sha256"] else Noneasync def _files_for_sha256(self, sha256: str) -> list[FileInfo]:- rows = await self.state.db.fetchall("SELECT * FROM files WHERE sha256=? AND scan_status=?", (sha256, SCAN_STATUS_ACTIVE))+ rows = cast(+ list[FileRow],+ await self.state.db.fetchall("SELECT * FROM files WHERE sha256=? AND status=?", (sha256, FILE_STATUS_ACTIVE)),+ )return [_file_info(row) for row in rows]-async def _mineru_error_handler(_request: Request, exc: MineruError) -> JSONResponse:- return JSONResponse(status_code=http_status_for(exc.code, exc.type), content=error_response(exc))+def _mask_config(config: dict[str, str]) -> dict[str, str]:+ return {key: _mask_config_value(key, value) for key, value in config.items()}+++def _mask_config_value(key: str, value: str) -> str:+ if not _is_sensitive_config_key(key) or not value:+ return value+ if len(value) <= 12:+ return "******"+ return f"{value[:6]}******{value[-6:]}"+++def _is_sensitive_config_key(key: str) -> bool:+ lowered = key.lower()+ return "api_key" in lowered or "token" in lowered or "secret" in lowered or "password" in lowered+++async def _mineru_error_handler(_request: Request, exc: Exception) -> JSONResponse:+ mineru_error = exc if isinstance(exc, MineruError) else MineruError("internal_error", str(exc))+ return JSONResponse(status_code=http_status_for(mineru_error.code), content=error_response(mineru_error))async def _unexpected_error_handler(_request: Request, exc: Exception) -> JSONResponse:@@ -528,25 +675,31 @@ def _tail_log(data_dir: str, lines: int = 100) -> list[str]:return fh.readlines()[-lines:]-async def _watch_stats(db: Any, watches: list[dict[str, Any]]) -> list[WatchStats]:- file_rows = await db.fetchall(- "SELECT watch_id, "- "COUNT(*) AS total_files, "- "SUM(CASE WHEN scan_status=? THEN 1 ELSE 0 END) AS active_files, "- "SUM(CASE WHEN scan_status=? THEN 1 ELSE 0 END) AS deleted_files, "- "SUM(CASE WHEN scan_status=? THEN 1 ELSE 0 END) AS unreachable_files, "- "SUM(CASE WHEN scan_status=? AND sha256 IS NULL AND error_code IS NULL THEN 1 ELSE 0 END) AS pending_ingest_files, "- "SUM(CASE WHEN error_code IS NOT NULL THEN 1 ELSE 0 END) AS file_error_count, "- "COUNT(DISTINCT sha256) AS doc_count "- "FROM files WHERE watch_id IS NOT NULL GROUP BY watch_id",- (SCAN_STATUS_ACTIVE, SCAN_STATUS_DELETED, SCAN_STATUS_UNREACHABLE, SCAN_STATUS_ACTIVE),+async def _watch_stats(db: DatabaseManager, watches: list[WatchTargetRow]) -> list[WatchStats]:+ file_rows = cast(+ list[WatchStatsFileRow],+ await db.fetchall(+ "SELECT watch_id, "+ "COUNT(*) AS total_files, "+ "SUM(CASE WHEN status=? THEN 1 ELSE 0 END) AS active_files, "+ "SUM(CASE WHEN status=? THEN 1 ELSE 0 END) AS deleted_files, "+ "SUM(CASE WHEN status=? THEN 1 ELSE 0 END) AS unreachable_files, "+ "SUM(CASE WHEN status=? AND sha256 IS NULL AND error_code IS NULL THEN 1 ELSE 0 END) AS pending_ingest_files, "+ "SUM(CASE WHEN error_code IS NOT NULL THEN 1 ELSE 0 END) AS file_error_count, "+ "COUNT(DISTINCT sha256) AS doc_count "+ "FROM files WHERE watch_id IS NOT NULL GROUP BY watch_id",+ (FILE_STATUS_ACTIVE, FILE_STATUS_DELETED, FILE_STATUS_UNREACHABLE, FILE_STATUS_ACTIVE),+ ),)- parse_rows = await db.fetchall(- "SELECT f.watch_id AS watch_id, p.status AS status, COUNT(*) AS cnt "- "FROM parses p "- "JOIN (SELECT DISTINCT watch_id, sha256 FROM files WHERE watch_id IS NOT NULL AND sha256 IS NOT NULL) f "- "ON f.sha256 = p.sha256 "- "GROUP BY f.watch_id, p.status"+ parse_rows = cast(+ list[WatchParseCountRow],+ await db.fetchall(+ "SELECT f.watch_id AS watch_id, p.status AS status, COUNT(*) AS cnt "+ "FROM parses p "+ "JOIN (SELECT DISTINCT watch_id, sha256 FROM files WHERE watch_id IS NOT NULL AND sha256 IS NOT NULL) f "+ "ON f.sha256 = p.sha256 "+ "GROUP BY f.watch_id, p.status"+ ),)files_by_watch = {row["watch_id"]: row for row in file_rows}@@ -566,7 +719,7 @@ async def _watch_stats(db: Any, watches: list[dict[str, Any]]) -> list[WatchStatpath=watch["path"],label=watch.get("label"),removable=bool(watch.get("removable", False)),- watch_status=watch["watch_status"],+ status=watch["status"],total_files=file_counts.get("total_files", 0) or 0,active_files=file_counts.get("active_files", 0) or 0,deleted_files=file_counts.get("deleted_files", 0) or 0,@@ -585,25 +738,28 @@ async def _watch_stats(db: Any, watches: list[dict[str, Any]]) -> list[WatchStatreturn stats-async def _error_summary(db: Any) -> ErrorSummary:+async def _error_summary(db: DatabaseManager) -> ErrorSummary:file_errors = await _error_buckets(db, "files")doc_errors = await _error_buckets(db, "docs")parse_errors = await _error_buckets(db, "parses")return ErrorSummary(file_errors=file_errors, doc_errors=doc_errors, parse_errors=parse_errors)-async def _recent_scans(db: Any, limit: int = 5) -> list[RecentScanInfo]:- rows = await db.fetchall(- "SELECT id, path, kind, source, watch_id, status, files_seen, files_refreshed, files_new, files_changed, "- "files_deleted, files_unreachable, files_error, files_unsupported, files_excluded, error_code, "- "started_at, finished_at, created_at, updated_at "- "FROM scans ORDER BY created_at DESC, id DESC LIMIT ?",- (limit,),+async def _recent_scans(db: DatabaseManager, limit: int = 5) -> list[RecentScanInfo]:+ rows = cast(+ list[RecentScanRow],+ await db.fetchall(+ "SELECT id, path, kind, source, watch_id, status, files_seen, files_refreshed, files_new, files_changed, "+ "files_deleted, files_unreachable, files_error, files_unsupported, files_excluded, error_code, "+ "started_at, finished_at, created_at, updated_at "+ "FROM scans ORDER BY created_at DESC, id DESC LIMIT ?",+ (limit,),+ ),)return [RecentScanInfo.model_validate(row) for row in rows]-async def _error_buckets(db: Any, table: str) -> list[ErrorBucket]:+async def _error_buckets(db: DatabaseManager, table: str) -> list[ErrorBucket]:sql_by_table = {"files": ("SELECT error_code AS code, COUNT(*) AS cnt FROM files "@@ -618,31 +774,31 @@ async def _error_buckets(db: Any, table: str) -> list[ErrorBucket]:"WHERE error_code IS NOT NULL GROUP BY error_code ORDER BY cnt DESC, error_code"),}- rows = await db.fetchall(sql_by_table[table])+ rows = cast(list[ErrorBucketRow], await db.fetchall(sql_by_table[table]))return [ErrorBucket(code=row["code"], count=row["cnt"]) for row in rows]-def _file_info(row: dict[str, Any]) -> FileInfo:+def _file_info(row: FileRow) -> FileInfo:return FileInfo.model_validate(row)-def _doc_info(row: dict[str, Any], *, files: list[FileInfo] | None = None) -> DocInfo:+def _doc_info(row: DocRow, *, files: list[FileInfo] | None = None) -> DocInfo:data = dict(row)data["files"] = filesreturn DocInfo.model_validate(data)-def _parse_info(row: dict[str, Any], *, coverage: ParseCoverage | None = None) -> ParseInfo:+def _parse_info(row: ParseRow, *, coverage: ParseCoverage | None = None) -> ParseInfo:data = dict(row)data["coverage"] = coveragereturn ParseInfo.model_validate(data)-def _tier_parse_info(row: dict[str, Any]) -> TierParseInfo:+def _tier_parse_info(row: ParseRow) -> TierParseInfo:return TierParseInfo.model_validate(row)-def _watch_info(row: dict[str, Any]) -> WatchInfo:+def _watch_info(row: WatchTargetRow) -> WatchInfo:data = dict(row)data["removable"] = bool(data.get("removable", False))data["enabled"] = bool(data.get("enabled", True))@@ -650,13 +806,13 @@ def _watch_info(row: dict[str, Any]) -> WatchInfo:return WatchInfo.model_validate(data)-def _exclude_rule_info(row: dict[str, Any] | None) -> ExcludeRuleInfo:+def _exclude_rule_info(row: ExcludeRuleRow | None) -> ExcludeRuleInfo:if row is None:raise NotFoundError("rule_not_found", "Exclude rule not found.", "rule_id")return ExcludeRuleInfo.model_validate(row)-def _parsing_rule_info(row: dict[str, Any] | None) -> ParsingRuleInfo:+def _parsing_rule_info(row: ParsingRuleRow | None) -> ParsingRuleInfo:if row is None:raise NotFoundError("rule_not_found", "Parsing rule not found.", "rule_id")data = dict(row)@@ -665,17 +821,17 @@ def _parsing_rule_info(row: dict[str, Any] | None) -> ParsingRuleInfo:return ParsingRuleInfo.model_validate(data)-def _search_result(row: dict[str, Any]) -> SearchResult:+def _search_result(row: ContentSearchResultRow) -> SearchResult:data = dict(row)data["tier"] = cast(Tier, data["tier"])return SearchResult.model_validate(data)-def _find_result(row: dict[str, Any]) -> FindResult:+def _find_result(row: FilenameSearchResultRow) -> FindResult:return FindResult.model_validate(row)-def _parse_coverage(request_pages: str, rows: list[dict[str, Any]]) -> ParseCoverage:+def _parse_coverage(request_pages: str, rows: list[ParseRow]) -> ParseCoverage:requested = parse_range_set(request_pages)done_pages: set[int] = set()active_pages: set[int] = set()diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.pyindex 499037fd..5a155bbd 100644--- a/mineru/doclib/services/cleanup_svc.py+++ b/mineru/doclib/services/cleanup_svc.py@@ -5,10 +5,12 @@ from __future__ import annotationsimport osimport shutilimport time+from typing import castfrom ...errors import InvalidRequestErrorfrom ..core.db import DatabaseManager-from ..types import SCAN_STATUS_DELETED+from ..rows import CountRow, DocRow, IdRow, WatchTargetRow+from ..types import FILE_STATUS_DELETEDFORGET_UNDER_ACTIVE_WATCH_WARNING = "Path is under an active watch and may be rediscovered on the next scan."@@ -20,11 +22,14 @@ class CleanupService:# ── orphan docs ─────────────────────────────────────────────- async def find_orphan_docs(self) -> list[dict]:- return await self.db.fetchall(- "SELECT d.* FROM docs d WHERE NOT EXISTS ("- " SELECT 1 FROM files f WHERE f.sha256 = d.sha256"- ")"+ async def find_orphan_docs(self) -> list[DocRow]:+ return cast(+ list[DocRow],+ await self.db.fetchall(+ "SELECT d.* FROM docs d WHERE NOT EXISTS ("+ " SELECT 1 FROM files f WHERE f.sha256 = d.sha256"+ ")"+ ),)async def cleanup_orphans(self, dry_run: bool = True) -> int:@@ -49,20 +54,23 @@ class CleanupService:# ── deleted files ───────────────────────────────────────────async def cleanup_deleted(self, dry_run: bool = True) -> int:- row = await self.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE scan_status=?",- (SCAN_STATUS_DELETED,),+ row = cast(+ CountRow | None,+ await self.db.fetchone(+ "SELECT COUNT(*) as cnt FROM files WHERE status=?",+ (FILE_STATUS_DELETED,),+ ),)count = row["cnt"] if row else 0if not dry_run and count > 0:await self.db.execute(- "DELETE FROM fts_filenames WHERE file_id IN (SELECT id FROM files WHERE scan_status=?)",- (SCAN_STATUS_DELETED,),+ "DELETE FROM fts_filenames WHERE file_id IN (SELECT id FROM files WHERE status=?)",+ (FILE_STATUS_DELETED,),)await self.db.execute(- "DELETE FROM files WHERE scan_status=?",- (SCAN_STATUS_DELETED,),+ "DELETE FROM files WHERE status=?",+ (FILE_STATUS_DELETED,),)await self.db.commit()@@ -70,20 +78,23 @@ class CleanupService:async def cleanup_deleted_older_than(self, older_than_days: int = 7) -> int:threshold = _days_ago_ms(older_than_days)- row = await self.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE scan_status=? AND deleted_at < ?",- (SCAN_STATUS_DELETED, threshold),+ row = cast(+ CountRow | None,+ await self.db.fetchone(+ "SELECT COUNT(*) as cnt FROM files WHERE status=? AND deleted_at < ?",+ (FILE_STATUS_DELETED, threshold),+ ),)count = row["cnt"] if row else 0if count > 0:await self.db.execute(- "DELETE FROM fts_filenames WHERE file_id IN (SELECT id FROM files WHERE scan_status=? AND deleted_at < ?)",- (SCAN_STATUS_DELETED, threshold),+ "DELETE FROM fts_filenames WHERE file_id IN (SELECT id FROM files WHERE status=? AND deleted_at < ?)",+ (FILE_STATUS_DELETED, threshold),)await self.db.execute(- "DELETE FROM files WHERE scan_status=? AND deleted_at < ?",- (SCAN_STATUS_DELETED, threshold),+ "DELETE FROM files WHERE status=? AND deleted_at < ?",+ (FILE_STATUS_DELETED, threshold),)await self.db.commit()@@ -96,7 +107,7 @@ class CleanupService:if not normalized:raise InvalidRequestError("invalid_request", "Path is required.", "path")- watches = await self.db.fetchall("SELECT * FROM watch_targets WHERE enabled=1")+ 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",@@ -132,9 +143,12 @@ class CleanupService:async def _forget_file_ids(self, path: str) -> list[int]:prefix = _path_prefix(path)upper = prefix + "\U0010ffff"- rows = await self.db.fetchall(- "SELECT id FROM files WHERE path=? OR (path>=? AND path<?) ORDER BY path",- (path, prefix, upper),+ rows = cast(+ list[IdRow],+ await self.db.fetchall(+ "SELECT id FROM files WHERE path=? OR (path>=? AND path<?) ORDER BY path",+ (path, prefix, upper),+ ),)return [row["id"] for row in rows]@@ -190,10 +204,10 @@ def _path_prefix(path: str) -> str:return path if path.endswith(os.sep) else path + os.sep-def _active_watch_warning(path: str, watches: list[dict]) -> str | None:+def _active_watch_warning(path: str, watches: list[WatchTargetRow]) -> str | None:for watch in watches:watch_path = watch["path"]- if watch.get("watch_status") != "active":+ if watch.get("status") != "active":continueif path != watch_path and path.startswith(_path_prefix(watch_path)):return FORGET_UNDER_ACTIVE_WATCH_WARNINGdiff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.pyindex deccaac8..bd37e9eb 100644--- a/mineru/doclib/services/config_svc.py+++ b/mineru/doclib/services/config_svc.py@@ -5,17 +5,21 @@ from __future__ import annotationsimport fnmatchimport osimport time+from typing import castimport fnvhash+from ...errors import InvalidRequestErrorfrom ...types import Tier+from ..config_defaults import CONFIG_DEFAULTS, CONFIG_SOURCE_DEFAULT, CONFIG_SOURCE_OVERRIDE, ConfigSourcefrom ..core.db import DatabaseManager+from ..rows import ConfigRow, RuleRow, WatchTargetRowfrom ..types import (RULE_TYPE_EXCLUDE,RULE_TYPE_PARSING_RULE,- SCAN_STATUS_ACTIVE,- SCAN_STATUS_DELETED,- SCAN_STATUS_UNREACHABLE,+ FILE_STATUS_ACTIVE,+ FILE_STATUS_DELETED,+ FILE_STATUS_UNREACHABLE,WATCH_STATUS_UNREACHABLE,RuleType,WatchStatus,@@ -29,23 +33,54 @@ class ConfigService:# ── KV config ───────────────────────────────────────────────async def get(self, key: str, default: str | None = None) -> str | None:- row = await self.db.fetchone("SELECT value FROM config WHERE key=?", (key,))+ if key in CONFIG_DEFAULTS and default is None:+ default = CONFIG_DEFAULTS[key]+ row = cast(ConfigRow | None, await self.db.fetchone("SELECT value FROM config WHERE key=?", (key,)))return row["value"] if row else defaultasync def set(self, key: str, value: str) -> None:+ self._validate_config_key(key)+ if CONFIG_DEFAULTS[key] == value:+ await self.unset(key)+ returnawait self.db.execute("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, value))+ async def unset(self, key: str) -> bool:+ self._validate_config_key(key)+ cursor = await self.db.execute("DELETE FROM config WHERE key=?", (key,))+ return cursor.rowcount > 0+async def get_all(self) -> dict[str, str]:- rows = await self.db.fetchall("SELECT key, value FROM config")- return {r["key"]: r["value"] for r in rows}+ config, _sources = await self.get_all_with_sources()+ return config++ async def get_source(self, key: str) -> ConfigSource:+ self._validate_config_key(key)+ row = cast(ConfigRow | None, await self.db.fetchone("SELECT value FROM config WHERE key=?", (key,)))+ return CONFIG_SOURCE_OVERRIDE if row else CONFIG_SOURCE_DEFAULT++ async def get_all_with_sources(self) -> tuple[dict[str, str], dict[str, ConfigSource]]:+ rows = cast(list[ConfigRow], await self.db.fetchall("SELECT key, value FROM config"))+ overrides = {r["key"]: r["value"] for r in rows}+ config = dict(CONFIG_DEFAULTS)+ config.update(overrides)+ sources: dict[str, ConfigSource] = {key: CONFIG_SOURCE_DEFAULT for key in CONFIG_DEFAULTS}+ for key in overrides:+ if key in CONFIG_DEFAULTS:+ sources[key] = CONFIG_SOURCE_OVERRIDE+ return config, sources++ def _validate_config_key(self, key: str) -> None:+ if key not in CONFIG_DEFAULTS:+ raise InvalidRequestError("invalid_config_key", f"Unknown config key: {key}", "key")# ── watch targets ───────────────────────────────────────────async def add_watch(self, path: str, removable: bool = False, label: str | None = None- ) -> dict:+ ) -> WatchTargetRow:if not os.path.isabs(path):raise ValueError(f"Path must be absolute: {path}")if os.path.normpath(path) != path:@@ -57,60 +92,72 @@ class ConfigService:now = int(time.time() * 1000)await self.db.execute(- "INSERT INTO watch_targets (id, path, label, removable, created_at, updated_at) "+ "INSERT INTO watches (id, path, label, removable, created_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?) ""ON CONFLICT(path) DO UPDATE SET ""label=excluded.label, removable=excluded.removable, updated_at=excluded.updated_at",(wid, path, label, int(removable), now, now),)- return await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (wid,))+ row = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE id=?", (wid,)))+ if row is None:+ raise RuntimeError(f"Watch target {wid} not found after insert.")+ return row- async def list_watches(self) -> list[dict]:- return await self.db.fetchall(- "SELECT * FROM watch_targets WHERE enabled=1 ORDER BY path"+ async def list_watches(self) -> list[WatchTargetRow]:+ return cast(+ list[WatchTargetRow],+ await self.db.fetchall("SELECT * FROM watches WHERE enabled=1 ORDER BY path"),)async def remove_watch(self, path: str) -> None:- watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE path=?", (path,))+ watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE path=?", (path,)))if watch is None:return+ await self.remove_watch_by_id(watch["id"])+ async def remove_watch_by_id(self, watch_id: int) -> None:+ watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE id=?", (watch_id,)))+ if watch is None:+ returnnow = int(time.time() * 1000)await self.db.execute_atomic([("UPDATE files SET watch_id=NULL, updated_at=? "- "WHERE watch_id=? AND scan_status IN (?, ?)",- (now, watch["id"], SCAN_STATUS_ACTIVE, SCAN_STATUS_DELETED),+ "WHERE watch_id=? AND status IN (?, ?)",+ (now, watch["id"], FILE_STATUS_ACTIVE, FILE_STATUS_DELETED),),(- "UPDATE files SET watch_id=NULL, scan_status=?, deleted_at=?, updated_at=? "- "WHERE watch_id=? AND scan_status=?",- (SCAN_STATUS_DELETED, now, now, watch["id"], SCAN_STATUS_UNREACHABLE),+ "UPDATE files SET watch_id=NULL, status=?, deleted_at=?, updated_at=? "+ "WHERE watch_id=? AND status=?",+ (FILE_STATUS_DELETED, now, now, watch["id"], FILE_STATUS_UNREACHABLE),),("UPDATE scans SET watch_id=NULL, updated_at=? WHERE watch_id=?", (now, watch["id"])),- ("DELETE FROM watch_targets WHERE id=?", (watch["id"],)),+ ("DELETE FROM watches WHERE id=?", (watch["id"],)),])- async def get_watches_by_status(self, watch_status: WatchStatus) -> list[dict]:- return await self.db.fetchall(- "SELECT * FROM watch_targets WHERE watch_status=? AND enabled=1",- (watch_status,),+ async def get_watches_by_status(self, status: WatchStatus) -> list[WatchTargetRow]:+ return cast(+ list[WatchTargetRow],+ await self.db.fetchall(+ "SELECT * FROM watches WHERE status=? AND enabled=1",+ (status,),+ ),)async def update_watch_status(self, watch_id: int, status: WatchStatus) -> None:now = int(time.time() * 1000)unreachable_at = now if status == WATCH_STATUS_UNREACHABLE else Noneawait self.db.execute(- "UPDATE watch_targets SET watch_status=?, unreachable_at=?, updated_at=? WHERE id=?",+ "UPDATE watches SET status=?, unreachable_at=?, updated_at=? WHERE id=?",(status, unreachable_at, now, watch_id),)async def update_watch_scan_stats(self, watch_id: int, file_count: int) -> None:now = int(time.time() * 1000)await self.db.execute(- "UPDATE watch_targets SET last_scan_at=?, last_scan_files=?, updated_at=? WHERE id=?",+ "UPDATE watches SET last_scan_at=?, last_scan_files=?, updated_at=? WHERE id=?",(now, file_count, now, watch_id),)@@ -141,33 +188,42 @@ class ConfigService:)raise ValueError(f"Unsupported rule type: {rule_type}")- async def list_rules(self, rule_type: RuleType | None = None) -> list[dict]:+ async def list_rules(self, rule_type: RuleType | None = None) -> list[RuleRow]:if rule_type == RULE_TYPE_EXCLUDE:- return await self.db.fetchall(- "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "- "0 AS remote, enabled, priority, hit_count, created_at, updated_at "- "FROM exclude_rules WHERE enabled=1 ORDER BY priority DESC",- (RULE_TYPE_EXCLUDE,),+ return cast(+ list[RuleRow],+ await self.db.fetchall(+ "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "+ "0 AS remote, enabled, priority, hit_count, created_at, updated_at "+ "FROM exclude_rules WHERE enabled=1 ORDER BY priority DESC",+ (RULE_TYPE_EXCLUDE,),+ ),)if rule_type == RULE_TYPE_PARSING_RULE:- return await self.db.fetchall(- "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "- "enabled, priority, hit_count, created_at, updated_at "- "FROM parsing_rules WHERE enabled=1 ORDER BY priority DESC",- (RULE_TYPE_PARSING_RULE,),+ return cast(+ list[RuleRow],+ await self.db.fetchall(+ "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "+ "enabled, priority, hit_count, created_at, updated_at "+ "FROM parsing_rules WHERE enabled=1 ORDER BY priority DESC",+ (RULE_TYPE_PARSING_RULE,),+ ),)if rule_type is not None:raise ValueError(f"Unsupported rule type: {rule_type}")- return await self.db.fetchall(- "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "- "0 AS remote, enabled, priority, hit_count, created_at, updated_at "- "FROM exclude_rules WHERE enabled=1 "- "UNION ALL "- "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "- "enabled, priority, hit_count, created_at, updated_at "- "FROM parsing_rules WHERE enabled=1 "- "ORDER BY rule_type, priority DESC",- (RULE_TYPE_EXCLUDE, RULE_TYPE_PARSING_RULE),+ return cast(+ list[RuleRow],+ await self.db.fetchall(+ "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "+ "0 AS remote, enabled, priority, hit_count, created_at, updated_at "+ "FROM exclude_rules WHERE enabled=1 "+ "UNION ALL "+ "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "+ "enabled, priority, hit_count, created_at, updated_at "+ "FROM parsing_rules WHERE enabled=1 "+ "ORDER BY rule_type, priority DESC",+ (RULE_TYPE_EXCLUDE, RULE_TYPE_PARSING_RULE),+ ),)async def remove_rule(self, rule_id: int, rule_type: RuleType | None = None) -> None:@@ -182,10 +238,10 @@ class ConfigService:await self.db.execute("DELETE FROM exclude_rules WHERE id=?", (rule_id,))await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))- async def match_rules(self, file_path: str, rule_type: RuleType) -> list[dict]:+ async def match_rules(self, file_path: str, rule_type: RuleType) -> list[RuleRow]:rules = await self.list_rules(rule_type)table = _rule_table(rule_type)- matched: list[dict] = []+ matched: list[RuleRow] = []for rule in rules:if fnmatch.fnmatch(file_path, rule["pattern"]):matched.append(rule)diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex ad9a5813..7277ddc5 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -6,16 +6,18 @@ import asyncioimport json as _jsonimport osimport time+from collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Path-from typing import Literal+from typing import Literal, castfrom ...errors import MineruErrorfrom ...types import PageInfo, TIER_ORDER, Tierfrom ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONSfrom ..core.db import DatabaseManager-from ..core.file_io import compute_sha256, extract_metadata, get_file_stat+from ..core.file_io import FileStat, compute_sha256, extract_metadata, get_file_statfrom ..core.fts import FTSManager+from ..rows import FileRow, PageCountRow, ParseBatchRow, ParseRow, WatchTargetRowfrom ..types import (PARSE_STATUS_DONE,PARSE_STATUS_FAILED,@@ -23,11 +25,12 @@ from ..types import (PARSE_STATUS_PENDING,PARSE_STATUS_SUPERSEDED,RULE_TYPE_PARSING_RULE,- SCAN_STATUS_ACTIVE,- SCAN_STATUS_DELETED,- SCAN_STATUS_UNREACHABLE,+ FILE_STATUS_ACTIVE,+ FILE_STATUS_DELETED,+ FILE_STATUS_UNREACHABLE,WATCH_STATUS_UNREACHABLE,FileInfo,+ ParseResponse,)from .config_svc import ConfigService@@ -92,7 +95,7 @@ def filter_pages_by_user_range(pages: list[PageInfo], requested_pages: str) -> lreturn [page for page in pages if page.page_idx + 1 in requested]-def pages_covered(request_pages: str, done_batches: list[dict]) -> bool:+def pages_covered(request_pages: str, done_batches: list[ParseRow]) -> bool:"""Check whether request_pages is fully covered by done batches.Batches are sorted by done_at DESC so newer batches take precedence."""needed = parse_range_set(request_pages)@@ -104,7 +107,7 @@ def pages_covered(request_pages: str, done_batches: list[dict]) -> bool:return False-def pages_uncovered(request_pages: str, done_batches: list[dict]) -> set[int]:+def pages_uncovered(request_pages: str, done_batches: list[ParseRow]) -> set[int]:"""Return the subset of request_pages NOT covered by any done batch."""needed = parse_range_set(request_pages)covered: set[int] = set()@@ -201,7 +204,7 @@ class ParseService:classification, and optional synchronous ingest."""ext = Path(path).suffix.lower().lstrip(".")- existing = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))+ existing = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))if ext not in ALLOWED_EXTENSIONS:return FileRefreshResult(file=_file_info(existing), status="unsupported")@@ -224,15 +227,15 @@ class ParseService:self,path: str,ext: str,- stat: dict,- existing: dict | None,+ stat: FileStat,+ existing: FileRow | None,watch_id: int | None,) -> FileRefreshResult:now = _now_ms()filename = Path(path).name- if existing and existing["scan_status"] == SCAN_STATUS_ACTIVE:- unchanged = existing["mtime_ms"] == stat["mtime_ms"] and existing["size_bytes"] == stat["size_bytes"]+ if existing and existing["status"] == FILE_STATUS_ACTIVE:+ unchanged = existing["mtime_ms"] == stat.mtime_ms and existing["size_bytes"] == stat.size_bytesif unchanged:return FileRefreshResult(file=_file_info(existing), status="known")@@ -243,33 +246,33 @@ class ParseService:(filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,watch_id,now,existing["id"],),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],)))return FileRefreshResult(file=_file_info(row), status="changed")if existing:await self.db.execute("UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, "- "sha256=NULL, watch_id=COALESCE(?, watch_id), scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, "+ "sha256=NULL, watch_id=COALESCE(?, watch_id), status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, ""deleted_at=NULL, updated_at=? WHERE id=?",(filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,watch_id,- SCAN_STATUS_ACTIVE,+ FILE_STATUS_ACTIVE,now,existing["id"],),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],)))return FileRefreshResult(file=_file_info(row), status="changed")file_id = await self.db.execute_insert(@@ -280,43 +283,43 @@ class ParseService:path,filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,watch_id,now,now,),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (file_id,))+ row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (file_id,)))return FileRefreshResult(file=_file_info(row), status="new")- async def _refresh_missing_file(self, path: str, existing: dict | None) -> FileRefreshResult:+ async def _refresh_missing_file(self, path: str, existing: FileRow | None) -> FileRefreshResult:if existing is None:return FileRefreshResult(file=None, status="missing")now = _now_ms()- scan_status = SCAN_STATUS_DELETED+ file_status = FILE_STATUS_DELETEDdeleted_at = now- if existing["scan_status"] != SCAN_STATUS_DELETED and await self._is_missing_due_to_unreachable_watch(existing):- scan_status = SCAN_STATUS_UNREACHABLE+ if existing["status"] != FILE_STATUS_DELETED and await self._is_missing_due_to_unreachable_watch(existing):+ file_status = FILE_STATUS_UNREACHABLEdeleted_at = Noneawait self.db.execute(- "UPDATE files SET scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=?, updated_at=? WHERE id=?",- (scan_status, deleted_at, now, existing["id"]),+ "UPDATE files SET status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=?, updated_at=? WHERE id=?",+ (file_status, deleted_at, now, existing["id"]),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))- status: FileRefreshStatus = "unreachable" if scan_status == SCAN_STATUS_UNREACHABLE else "deleted"- return FileRefreshResult(file=_file_info(row), status=status)+ row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],)))+ refresh_status: FileRefreshStatus = "unreachable" if file_status == FILE_STATUS_UNREACHABLE else "deleted"+ return FileRefreshResult(file=_file_info(row), status=refresh_status)- async def _is_missing_due_to_unreachable_watch(self, file_row: dict) -> bool:+ async def _is_missing_due_to_unreachable_watch(self, file_row: FileRow) -> bool:watch_id = file_row.get("watch_id")if watch_id is None:return False- watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (watch_id,))+ watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE id=?", (watch_id,)))if not watch or not watch.get("removable"):return False- if watch["watch_status"] == WATCH_STATUS_UNREACHABLE:+ if watch["status"] == WATCH_STATUS_UNREACHABLE:return Truetry:await get_file_stat(watch["path"])@@ -326,7 +329,7 @@ class ParseService:return Truereturn False- async def _refresh_stat_error(self, existing: dict | None, error_code: str, error_msg: str) -> FileRefreshResult:+ async def _refresh_stat_error(self, existing: FileRow | None, error_code: str, error_msg: str) -> FileRefreshResult:if existing is None:return FileRefreshResult(file=None, status="error")@@ -335,17 +338,17 @@ class ParseService:"UPDATE files SET sha256=NULL, locked_at=NULL, error_code=?, error_msg=?, updated_at=? WHERE id=?",(error_code, error_msg[:500], now, existing["id"]),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],)))return FileRefreshResult(file=_file_info(row), status="error")- async def ensure_ingested(self, path: str, watch_id: int | None = None) -> dict | None:+ async def ensure_ingested(self, path: str, watch_id: int | None = None) -> FileRow | None:"""Synchronously discover and ingest a source path when needed."""refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True)if refreshed.file is None:return None- return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))+ return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))- async def ingest_file(self, path: str, watch_id: int | None = None) -> dict | None:+ async def ingest_file(self, path: str, watch_id: int | None = None) -> FileRow | None:"""Ingest a discovered file: SHA-256 + metadata + trigger default parse."""ext = Path(path).suffix.lower().lstrip(".")if ext not in ALLOWED_EXTENSIONS:@@ -356,12 +359,15 @@ class ParseService:now = _now_ms()filename = Path(path).name- existing_path = await self.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status=?", (path, SCAN_STATUS_ACTIVE))+ existing_path = cast(+ FileRow | None,+ await self.db.fetchone("SELECT * FROM files WHERE path=? AND status=?", (path, FILE_STATUS_ACTIVE)),+ )if existing_path and existing_path["sha256"] == sha256:return existing_path# check if same content (sha256) is already tracked by another path- existing_sha = await self.db.fetchone("SELECT * FROM files WHERE sha256=?", (sha256,))+ existing_sha = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE sha256=?", (sha256,)))if existing_sha:# same content, possibly a new or changed path — bind this file row# to the existing doc without duplicating docs/parses.@@ -373,8 +379,8 @@ class ParseService:(filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,sha256,watch_id,now,@@ -390,15 +396,15 @@ class ParseService:path,filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,sha256,watch_id,now,now,),)- file_row = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))+ file_row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))if file_row:await self.fts.upsert_filename(file_row["id"], Path(path).stem, ext)return file_row@@ -417,7 +423,7 @@ class ParseService:"author": None,"subject": None,"keywords": None,- "is_scanned": 0,+ "is_image_based": 0,}# Office: no page_count → default to 1@@ -437,8 +443,8 @@ class ParseService:path,filename,ext,- stat["size_bytes"],- stat["mtime_ms"],+ stat.size_bytes,+ stat.mtime_ms,watch_id,now,now,@@ -451,7 +457,7 @@ class ParseService:"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(sha256,- stat["size_bytes"],+ stat.size_bytes,_file_type_from_ext(ext),page_count,metadata["title"],@@ -488,7 +494,7 @@ class ParseService:author=metadata["author"] or "",filename=filename,)- return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))+ return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))# determine tier and pages for initial parsetier: Tier = "flash"@@ -520,7 +526,7 @@ class ParseService:(sha256, now, path),)- return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))+ return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))# ── parse request ───────────────────────────────────────────@@ -532,15 +538,17 @@ class ParseService:pages: str | None = None,force: bool = False,remote: bool = False,- ) -> dict:+ ) -> ParseResponse:"""Handle a parse request from CLI. Returns info for status polling."""# ensure the path is current before trusting files.sha256file_row = await self.ensure_ingested(path)if file_row is None:- return {"sha256": "", "tier": tier or "", "status": "error", "tip": "File could not be ingested."}+ return _failed_response(tier or "flash", pages or "", "File could not be ingested.")sha256 = file_row["sha256"]- doc = await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,))+ if sha256 is None:+ return _failed_response(tier or "flash", pages or "", "File could not be ingested.")+ doc = cast(PageCountRow | None, await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,)))page_count = doc["page_count"] if doc else 1privacy = "remote" if remote else "local"@@ -560,9 +568,12 @@ class ParseService:# ── step 1: remove pages covered by valid done batches ──if not force:- done_batches = await self.db.fetchall(- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status=? ORDER BY done_at DESC",- (sha256, requested_tier, PARSE_STATUS_DONE),+ done_batches = cast(+ list[ParseRow],+ await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status=? ORDER BY done_at DESC",+ (sha256, requested_tier, PARSE_STATUS_DONE),+ ),)for batch in done_batches:if not _json_file_exists_by_batch(self.data_dir, sha256, requested_tier, batch):@@ -575,9 +586,12 @@ class ParseService:# ── step 2: remove pages covered by pending/parsing batches ──reused_parse_ids: list[int] = []- active_batches = await self.db.fetchall(- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN (?, ?)",- (sha256, requested_tier, PARSE_STATUS_PENDING, PARSE_STATUS_PARSING),+ active_batches = cast(+ list[ParseRow],+ await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN (?, ?)",+ (sha256, requested_tier, PARSE_STATUS_PENDING, PARSE_STATUS_PARSING),+ ),)if active_batches:active_covered: set[int] = set()@@ -598,17 +612,17 @@ class ParseService:)if not needed:- return {- "sha256": sha256,- "tier": requested_tier,- "pages": request_pages_str,- "status": PARSE_STATUS_PENDING,- "cache_hit": False,- "wait_parse_ids": reused_parse_ids,- "created_parse_ids": [],- "reused_parse_ids": reused_parse_ids,- "tip": "Pages already queued. Priority bumped.",- }+ return ParseResponse(+ sha256=sha256,+ tier=requested_tier,+ pages=request_pages_str,+ status=PARSE_STATUS_PENDING,+ cache_hit=False,+ wait_parse_ids=reused_parse_ids,+ created_parse_ids=[],+ reused_parse_ids=reused_parse_ids,+ tip="Pages already queued. Priority bumped.",+ )# ── step 3: enqueue remaining uncovered pages ──uncovered_str = _pages_set_to_str(needed)@@ -619,16 +633,16 @@ class ParseService:(sha256, requested_tier, uncovered_str, PARSE_STATUS_PENDING, privacy, now, now),)created_parse_ids = [parse_id]- return {- "sha256": sha256,- "tier": requested_tier,- "pages": request_pages_str,- "status": PARSE_STATUS_PENDING,- "cache_hit": False,- "wait_parse_ids": reused_parse_ids + created_parse_ids,- "created_parse_ids": created_parse_ids,- "reused_parse_ids": reused_parse_ids,- }+ return ParseResponse(+ sha256=sha256,+ tier=requested_tier,+ pages=request_pages_str,+ status=PARSE_STATUS_PENDING,+ cache_hit=False,+ wait_parse_ids=reused_parse_ids + created_parse_ids,+ created_parse_ids=created_parse_ids,+ reused_parse_ids=reused_parse_ids,+ )# ── worker ──────────────────────────────────────────────────@@ -640,20 +654,23 @@ class ParseService:)return row["cnt"] if row else 0- async def acquire_task(self) -> dict | None:+ async def acquire_task(self) -> ParseRow | None:now = _now_ms()timeout = now - 30 * 60 * 1000 # 30min lock timeout- return await self.db.fetchone(- "UPDATE parses SET locked_at=?, status=? "- "WHERE id = ("- " SELECT id FROM parses WHERE status=? "- " AND (locked_at IS NULL OR locked_at < ?) "- " ORDER BY priority DESC, created_at ASC LIMIT 1"- ") RETURNING *",- (now, PARSE_STATUS_PARSING, PARSE_STATUS_PENDING, timeout),+ return cast(+ ParseRow | None,+ await self.db.fetchone(+ "UPDATE parses SET locked_at=?, status=? "+ "WHERE id = ("+ " SELECT id FROM parses WHERE status=? "+ " AND (locked_at IS NULL OR locked_at < ?) "+ " ORDER BY priority DESC, created_at ASC LIMIT 1"+ ") RETURNING *",+ (now, PARSE_STATUS_PARSING, PARSE_STATUS_PENDING, timeout),+ ),)- async def process_doc(self, task: dict) -> bool:+ async def process_doc(self, task: ParseRow) -> bool:"""Execute parse for a batch. Returns True on success."""sha256 = task["sha256"]tier = task["tier"]@@ -666,9 +683,12 @@ class ParseService:return False# find the file- file_row = await self.db.fetchone(- "SELECT * FROM files WHERE sha256=? AND scan_status=? LIMIT 1",- (sha256, SCAN_STATUS_ACTIVE),+ file_row = cast(+ FileRow | None,+ await self.db.fetchone(+ "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",+ (sha256, FILE_STATUS_ACTIVE),+ ),)if file_row is None:await self._fail_task(task["id"], "no_accessible_file", "No active file found for this document")@@ -736,7 +756,7 @@ class ParseService:# ── parse routing helpers ─────────────────────────────────────- async def _parse_via_local(self, file_row: dict, tier: Tier, pages: str) -> list:+ async def _parse_via_local(self, file_row: FileRow, tier: Tier, pages: str) -> list:"""Parse via local library call."""from ...parser import parse@@ -750,7 +770,7 @@ class ParseService:async def _parse_via_api(self,- file_row: dict,+ file_row: FileRow,tier: Tier,pages: str,privacy: str,@@ -838,7 +858,7 @@ class ParseService:)async def get_parse_record(self, parse_id: int) -> dict | None:- row = await self.db.fetchone("SELECT * FROM parses WHERE id=?", (parse_id,))+ row = cast(ParseRow | None, await self.db.fetchone("SELECT * FROM parses WHERE id=?", (parse_id,)))return _parse_record_response(row) if row else Noneasync def list_parse_records(@@ -853,7 +873,7 @@ class ParseService:) -> dict:if ids:placeholders = ",".join("?" * len(ids))- rows = await self.db.fetchall(f"SELECT * FROM parses WHERE id IN ({placeholders})", tuple(ids))+ rows = cast(list[ParseRow], await self.db.fetchall(f"SELECT * FROM parses WHERE id IN ({placeholders})", tuple(ids)))rows_by_id = {row["id"]: row for row in rows}ordered_rows = [rows_by_id[parse_id] for parse_id in ids if parse_id in rows_by_id]return {"parses": [_parse_record_response(row) for row in ordered_rows]}@@ -878,8 +898,8 @@ class ParseService:if clauses:sql += " WHERE " + " AND ".join(clauses)sql += " ORDER BY created_at DESC"- rows = await self.db.fetchall(sql, tuple(params))- result = {"parses": [_parse_record_response(row) for row in rows]}+ rows = cast(list[ParseRow], await self.db.fetchall(sql, tuple(params)))+ result: dict[str, object] = {"parses": [_parse_record_response(row) for row in rows]}if sha256 and tier and pages:result["coverage"] = _parse_coverage(pages, rows)return result@@ -899,7 +919,7 @@ class ParseService:# ── internal helpers ────────────────────────────────────────- async def _maybe_update_fts(self, sha256: str, tier: Tier, text: str, file_row: dict) -> None:+ async def _maybe_update_fts(self, sha256: str, tier: Tier, text: str, file_row: FileRow) -> None:existing_tier = await self.fts.get_tier(sha256)if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(tier, -1):return # current FTS data is from a higher or equal tier@@ -935,19 +955,26 @@ class ParseService:)async def _rebuild_fts_after_invalidate(self, sha256: str) -> None:- file_row = await self.db.fetchone(- "SELECT * FROM files WHERE sha256=? AND scan_status=? LIMIT 1",- (sha256, SCAN_STATUS_ACTIVE),+ file_row = cast(+ FileRow | None,+ await self.db.fetchone(+ "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",+ (sha256, FILE_STATUS_ACTIVE),+ ),)if file_row is None:await self.fts.delete(sha256)return- rows = await self.db.fetchall(- "SELECT * FROM parses WHERE sha256=? AND status=? ORDER BY done_at DESC",- (sha256, PARSE_STATUS_DONE),+ rows = cast(+ list[ParseRow],+ await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND status=? ORDER BY done_at DESC",+ (sha256, PARSE_STATUS_DONE),+ ),)- tiers = sorted({row["tier"] for row in rows}, key=lambda t: TIER_ORDER.get(t, -1), reverse=True)+ tier_set: set[Tier] = {row["tier"] for row in rows}+ tiers = sorted(tier_set, key=lambda item: TIER_ORDER.get(item, -1), reverse=True)for tier in tiers:tier_rows = [row for row in rows if row["tier"] == tier]pages = load_pages_from_done_batches(self.data_dir, sha256, tier, tier_rows)@@ -988,7 +1015,7 @@ def _resolve_default_tier(remote: bool = False) -> Tier:)-def _json_file_exists_by_batch(data_dir: str, sha256: str, tier: Tier, batch: dict) -> bool:+def _json_file_exists_by_batch(data_dir: str, sha256: str, tier: Tier, batch: ParseRow) -> bool:"""Check that the JSON result file for a parses batch row actually exists on disk."""json_path = parse_batch_json_path(data_dir, sha256, tier, batch["pages"], batch["done_at"])return os.path.isfile(json_path)@@ -1000,7 +1027,7 @@ def parse_batch_json_path(data_dir: str, sha256: str, tier: Tier, pages: str, doreturn os.path.join(os.path.expanduser(data_dir), "parsed", sha256[:2], sha256, tier, f"{key}.json")-def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_rows: list[dict]) -> list[PageInfo]:+def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_rows: Sequence[ParseBatchRow]) -> list[PageInfo]:"""Load valid done JSON batches and keep the newest page for duplicate page_idx values."""pages_by_idx: dict[int, PageInfo] = {}for row in reversed(done_rows):@@ -1018,35 +1045,49 @@ def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_roreturn [pages_by_idx[idx] for idx in sorted(pages_by_idx)]-def _done_response(sha256: str, tier: Tier, pages: str) -> dict:- return {- "sha256": sha256,- "tier": tier,- "pages": pages,- "status": PARSE_STATUS_DONE,- "cache_hit": True,- "wait_parse_ids": [],- "created_parse_ids": [],- "reused_parse_ids": [],- "tip": "Cached. Use --force to re-parse.",- }+def _done_response(sha256: str, tier: Tier, pages: str) -> ParseResponse:+ return ParseResponse(+ sha256=sha256,+ tier=tier,+ pages=pages,+ status=PARSE_STATUS_DONE,+ cache_hit=True,+ wait_parse_ids=[],+ created_parse_ids=[],+ reused_parse_ids=[],+ tip="Cached. Use --force to re-parse.",+ )-def _text_response(sha256: str) -> dict:- return {- "sha256": sha256,- "tier": "flash",- "pages": "1",- "status": PARSE_STATUS_DONE,- "cache_hit": False,- "wait_parse_ids": [],- "created_parse_ids": [],- "reused_parse_ids": [],- "tip": "Plain text files do not require parsing.",- }+def _text_response(sha256: str) -> ParseResponse:+ return ParseResponse(+ sha256=sha256,+ tier="flash",+ pages="1",+ status=PARSE_STATUS_DONE,+ cache_hit=False,+ wait_parse_ids=[],+ created_parse_ids=[],+ reused_parse_ids=[],+ tip="Plain text files do not require parsing.",+ )+++def _failed_response(tier: Tier, pages: str, tip: str) -> ParseResponse:+ return ParseResponse(+ sha256="",+ tier=tier,+ pages=pages,+ status=PARSE_STATUS_FAILED,+ cache_hit=False,+ wait_parse_ids=[],+ created_parse_ids=[],+ reused_parse_ids=[],+ tip=tip,+ )-def _parse_record_response(row: dict) -> dict:+def _parse_record_response(row: ParseRow) -> dict:error = Noneif row.get("error_code") or row.get("error_msg"):error = {"code": row.get("error_code"), "message": row.get("error_msg")}@@ -1063,7 +1104,7 @@ def _parse_record_response(row: dict) -> dict:}-def _parse_coverage(request_pages: str, rows: list[dict]) -> dict:+def _parse_coverage(request_pages: str, rows: list[ParseRow]) -> dict:requested = parse_range_set(request_pages)done_pages: set[int] = set()active_pages: set[int] = set()@@ -1091,7 +1132,7 @@ def _local_parse_server_url(mode: str, health: object) -> str | None:return None-def _file_info(row: dict | None) -> FileInfo | None:+def _file_info(row: FileRow | None) -> FileInfo | None:return FileInfo.model_validate(row) if row is not None else Nonediff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.pyindex bb641d12..4849e0cf 100644--- a/mineru/doclib/services/scan_svc.py+++ b/mineru/doclib/services/scan_svc.py@@ -6,26 +6,27 @@ import osimport timeimport loggingfrom pathlib import Path-from typing import Any+from typing import Any, castfrom ...errors import InvalidRequestError, NotFoundErrorfrom ..constants import ALLOWED_EXTENSIONSfrom ..core.file_io import get_file_stat+from ..rows import PathRow, ScanRow, WatchTargetRowfrom ..types import (SCAN_KIND_MANUAL,SCAN_KIND_WATCH,- SCAN_STATUS_ACTIVE,- SCAN_TASK_STATUS_DONE,- SCAN_TASK_STATUS_FAILED,- SCAN_TASK_STATUS_PENDING,- SCAN_TASK_STATUS_RUNNING,+ FILE_STATUS_ACTIVE,+ SCAN_STATUS_DONE,+ SCAN_STATUS_FAILED,+ SCAN_STATUS_PENDING,+ SCAN_STATUS_RUNNING,SCAN_SOURCE_UNKNOWN,WATCH_STATUS_ACTIVE,WATCH_STATUS_UNREACHABLE,ScanInfo,ScanKind,ScanSource,- ScanTaskStatus,+ ScanStatus,)from ..core.db import DatabaseManagerfrom .config_svc import ConfigService@@ -69,9 +70,12 @@ class ScanService:elif watch_id is not None:raise InvalidRequestError("invalid_request", "watch_id is only valid for watch scans.", "watch_id")- active = await self.db.fetchone(- "SELECT * FROM scans WHERE kind=? AND path=? AND status IN (?, ?) ORDER BY created_at ASC LIMIT 1",- (kind, normalized_path, SCAN_TASK_STATUS_PENDING, SCAN_TASK_STATUS_RUNNING),+ active = cast(+ ScanRow | None,+ await self.db.fetchone(+ "SELECT * FROM scans WHERE kind=? AND path=? AND status IN (?, ?) ORDER BY created_at ASC LIMIT 1",+ (kind, normalized_path, SCAN_STATUS_PENDING, SCAN_STATUS_RUNNING),+ ),)if active is not None:return _scan_info(active)@@ -80,9 +84,9 @@ class ScanService:scan_id = await self.db.execute_insert("INSERT INTO scans (path, kind, source, watch_id, status, created_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?)",- (normalized_path, kind, source, watch_id, SCAN_TASK_STATUS_PENDING, now, now),+ (normalized_path, kind, source, watch_id, SCAN_STATUS_PENDING, now, now),)- row = await self.db.fetchone("SELECT * FROM scans WHERE id=?", (scan_id,))+ row = cast(ScanRow | None, await self.db.fetchone("SELECT * FROM scans WHERE id=?", (scan_id,)))if row is None:raise NotFoundError("scan_not_found", f"Scan {scan_id} not found after creation.", "scan_id")return _scan_info(row)@@ -91,7 +95,7 @@ class ScanService:self,*,limit: int = 50,- status: ScanTaskStatus | None = None,+ status: ScanStatus | None = None,kind: ScanKind | None = None,watch_id: int | None = None,) -> list[ScanInfo]:@@ -108,38 +112,44 @@ class ScanService:clauses.append("watch_id=?")params.append(watch_id)where = f"WHERE {' AND '.join(clauses)}" if clauses else ""- rows = await self.db.fetchall(- f"SELECT * FROM scans {where} ORDER BY created_at DESC LIMIT ?",- (*params, limit),+ rows = cast(+ list[ScanRow],+ await self.db.fetchall(+ f"SELECT * FROM scans {where} ORDER BY created_at DESC LIMIT ?",+ (*params, limit),+ ),)return [_scan_info(row) for row in rows]async def get_scan(self, scan_id: int) -> ScanInfo:- row = await self.db.fetchone("SELECT * FROM scans WHERE id=?", (scan_id,))+ row = cast(ScanRow | None, await self.db.fetchone("SELECT * FROM scans WHERE id=?", (scan_id,)))if row is None:raise NotFoundError("scan_not_found", f"Scan {scan_id} not found.", "scan_id")return _scan_info(row)- async def acquire_task(self) -> dict | None:+ async def acquire_task(self) -> ScanRow | None:now = _now_ms()timeout = now - 30 * 60 * 1000- return await self.db.fetchone(- "UPDATE scans SET locked_at=?, status=?, started_at=COALESCE(started_at, ?), updated_at=? "- "WHERE id = ("- " SELECT id FROM scans WHERE status=? AND (locked_at IS NULL OR locked_at < ?) "- " ORDER BY created_at ASC LIMIT 1"- ") RETURNING *",- (now, SCAN_TASK_STATUS_RUNNING, now, now, SCAN_TASK_STATUS_PENDING, timeout),+ return cast(+ ScanRow | None,+ await self.db.fetchone(+ "UPDATE scans SET locked_at=?, status=?, started_at=COALESCE(started_at, ?), updated_at=? "+ "WHERE id = ("+ " SELECT id FROM scans WHERE status=? AND (locked_at IS NULL OR locked_at < ?) "+ " ORDER BY created_at ASC LIMIT 1"+ ") RETURNING *",+ (now, SCAN_STATUS_RUNNING, now, now, SCAN_STATUS_PENDING, timeout),+ ),)- async def process_scan(self, task: dict) -> bool:+ async def process_scan(self, task: ScanRow) -> bool:try:counters = await self._run_scan(task)except Exception as exc:now = _now_ms()await self.db.execute("UPDATE scans SET status=?, locked_at=NULL, error_code=?, error_msg=?, finished_at=?, updated_at=? WHERE id=?",- (SCAN_TASK_STATUS_FAILED, "scan_failed", str(exc)[:500], now, now, task["id"]),+ (SCAN_STATUS_FAILED, "scan_failed", str(exc)[:500], now, now, task["id"]),)await self.cleanup_terminal_scan_logs()return False@@ -150,7 +160,7 @@ class ScanService:"files_deleted=?, files_unreachable=?, files_error=?, files_unsupported=?, files_excluded=?, ""finished_at=?, updated_at=? WHERE id=?",(- SCAN_TASK_STATUS_DONE,+ SCAN_STATUS_DONE,counters.files_seen,counters.files_refreshed,counters.files_new,@@ -165,8 +175,9 @@ class ScanService:task["id"],),)- if task["kind"] == SCAN_KIND_WATCH and task.get("watch_id") is not None:- await self.config_svc.update_watch_scan_stats(task["watch_id"], counters.files_refreshed)+ task_watch_id = task["watch_id"]+ if task["kind"] == SCAN_KIND_WATCH and task_watch_id is not None:+ await self.config_svc.update_watch_scan_stats(task_watch_id, counters.files_refreshed)await self.cleanup_terminal_scan_logs()return True@@ -176,12 +187,12 @@ class ScanService:"DELETE FROM scans WHERE status IN (?, ?) AND id NOT IN ("" SELECT id FROM scans WHERE status IN (?, ?) ORDER BY created_at DESC, id DESC LIMIT ?"")",- (SCAN_TASK_STATUS_DONE, SCAN_TASK_STATUS_FAILED, SCAN_TASK_STATUS_DONE, SCAN_TASK_STATUS_FAILED, keep),+ (SCAN_STATUS_DONE, SCAN_STATUS_FAILED, SCAN_STATUS_DONE, SCAN_STATUS_FAILED, keep),)except Exception as exc:logger.warning("Failed to cleanup terminal scan logs: %s", exc)- async def _run_scan(self, task: dict) -> "_ScanCounters":+ async def _run_scan(self, task: ScanRow) -> "_ScanCounters":path = task["path"]kind = task["kind"]watch_id = task.get("watch_id")@@ -197,7 +208,7 @@ class ScanService:except OSError:await self.config_svc.update_watch_status(watch["id"], WATCH_STATUS_UNREACHABLE)return counters- if watch["watch_status"] == WATCH_STATUS_UNREACHABLE:+ if watch["status"] == WATCH_STATUS_UNREACHABLE:await self.config_svc.update_watch_status(watch["id"], WATCH_STATUS_ACTIVE)if os.path.isdir(path):@@ -249,14 +260,17 @@ class ScanService:await self._refresh_file(path, watch_id=watch_id, counters=counters)async def _scan_missing_path(self, path: str, *, watch_id: int | None, counters: "_ScanCounters") -> None:- existing = await self.db.fetchone("SELECT path FROM files WHERE path=?", (path,))+ existing = cast(PathRow | None, await self.db.fetchone("SELECT path FROM files WHERE path=?", (path,)))if existing is not None:await self._refresh_file(existing["path"], watch_id=watch_id, counters=counters)prefix = _dir_prefix(path)- rows = await self.db.fetchall(- "SELECT path FROM files WHERE path>=? AND path<? AND scan_status=? ORDER BY path",- (prefix, prefix + chr(0x10FFFF), SCAN_STATUS_ACTIVE),+ rows = cast(+ list[PathRow],+ await self.db.fetchall(+ "SELECT path FROM files WHERE path>=? AND path<? AND status=? ORDER BY path",+ (prefix, prefix + chr(0x10FFFF), FILE_STATUS_ACTIVE),+ ),)for row in rows:await self._refresh_file(row["path"], watch_id=watch_id, counters=counters)@@ -271,12 +285,12 @@ class ScanService:prefix = _dir_prefix(path)params: tuple[Any, ...]if watch_id is None:- sql = "SELECT path FROM files WHERE path>=? AND path<? AND scan_status=? ORDER BY path"- params = (prefix, prefix + chr(0x10FFFF), SCAN_STATUS_ACTIVE)+ sql = "SELECT path FROM files WHERE path>=? AND path<? AND status=? ORDER BY path"+ params = (prefix, prefix + chr(0x10FFFF), FILE_STATUS_ACTIVE)else:- sql = "SELECT path FROM files WHERE watch_id=? AND scan_status=? ORDER BY path"- params = (watch_id, SCAN_STATUS_ACTIVE)- rows = await self.db.fetchall(sql, params)+ sql = "SELECT path FROM files WHERE watch_id=? AND status=? ORDER BY path"+ params = (watch_id, FILE_STATUS_ACTIVE)+ rows = cast(list[PathRow], await self.db.fetchall(sql, params))for row in rows:await self._refresh_file(row["path"], watch_id=watch_id, counters=counters)@@ -285,11 +299,11 @@ class ScanService:counters.add_refresh(result.status)return result- async def _resolve_watch(self, path: str, watch_id: int | None) -> dict:+ async def _resolve_watch(self, path: str, watch_id: int | None) -> WatchTargetRow:if watch_id is not None:- watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (watch_id,))+ watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE id=?", (watch_id,)))else:- watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE path=?", (path,))+ watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE path=?", (path,)))if watch is None:raise NotFoundError("watch_not_found", "Watch target not found.", "watch_id")return watch@@ -327,5 +341,5 @@ def _dir_prefix(path: str) -> str:return path.rstrip(os.sep) + os.sep-def _scan_info(row: dict[str, Any]) -> ScanInfo:+def _scan_info(row: ScanRow) -> ScanInfo:return ScanInfo.model_validate(row)diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.pyindex 55e2e52d..def2989f 100644--- a/mineru/doclib/services/search_svc.py+++ b/mineru/doclib/services/search_svc.py@@ -2,10 +2,13 @@from __future__ import annotations+from typing import cast+from ...types import TIER_ORDER, Tierfrom ..core.db import DatabaseManagerfrom ..core.fts import FTSManager, strip_sep-from ..types import SCAN_STATUS_ACTIVE+from ..rows import ContentSearchResultRow, FilenameSearchFileRow, FilenameSearchResultRow, SearchFileRow+from ..types import FILE_STATUS_ACTIVEclass SearchService:@@ -23,7 +26,7 @@ class SearchService:min_tier: Tier | None = None,limit: int = 20,offset: int = 0,- ) -> tuple[list[dict], int]:+ ) -> tuple[list[ContentSearchResultRow], int]:"""Full-text search. Returns (results, total_count)."""rows = await self.fts.search(query, limit=200)if not rows:@@ -49,29 +52,31 @@ class SearchService:sql += " AND d.file_type = ?"params.append(file_type.lower())- file_rows = await self.db.fetchall(sql, params)+ file_rows = cast(list[SearchFileRow], await self.db.fetchall(sql, tuple(params)))# group files by sha256- files_by_doc: dict[str, list[dict]] = {}+ files_by_doc: dict[str, list[SearchFileRow]] = {}for fr in file_rows:sha = fr["sha256"]+ if sha is None:+ continueif sha not in files_by_doc:files_by_doc[sha] = []files_by_doc[sha].append(fr)# build results- results: list[dict] = []+ results: list[ContentSearchResultRow] = []for row in rows:sha = row["sha256"]all_files = files_by_doc.get(sha, [])if not all_files:continue- active_files = [file for file in all_files if file.get("scan_status") == SCAN_STATUS_ACTIVE]+ active_files = [file for file in all_files if file.get("status") == FILE_STATUS_ACTIVE]files = active_files or all_filesfts_file = files[0]snippet = strip_sep(row.get("snippet", ""))- tier = row.get("tier") or ""+ result_tier = row["tier"]results.append({@@ -81,7 +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),- "tier": tier,+ "tier": result_tier,"snippet": snippet,"paths": [f["path"] for f in files],}@@ -94,7 +99,7 @@ class SearchService:async def search_filenames(self, query: str, ext: str | None = None, limit: int = 50- ) -> tuple[list[dict], int]:+ ) -> tuple[list[FilenameSearchResultRow], int]:"""Search filenames only. Returns (results, total_count)."""rows = await self.fts.search_filenames(query, limit=limit)if not rows:@@ -105,17 +110,17 @@ class SearchService:sql = (f"SELECT f.*, d.title "f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "- f"WHERE f.id IN ({placeholders}) AND f.scan_status = ?"+ f"WHERE f.id IN ({placeholders}) AND f.status = ?")- params = [*file_ids, SCAN_STATUS_ACTIVE]+ params = [*file_ids, FILE_STATUS_ACTIVE]if ext:sql += " AND f.ext = ?"params.append(ext.lower().lstrip("."))- file_rows = await self.db.fetchall(sql, params)+ file_rows = cast(list[FilenameSearchFileRow], await self.db.fetchall(sql, tuple(params)))files_by_id = {fr["id"]: fr for fr in file_rows}- results: list[dict] = []+ results: list[FilenameSearchResultRow] = []for row in rows:fr = files_by_id.get(row["file_id"])if not fr:diff --git a/mineru/doclib/types.py b/mineru/doclib/types.pyindex b2be8759..204ed97f 100644--- a/mineru/doclib/types.py+++ b/mineru/doclib/types.py@@ -9,14 +9,15 @@ from pydantic import BaseModel, Fieldfrom ..types import TierParseStatus = Literal["pending", "parsing", "done", "failed", "superseded"]-ScanStatus = Literal["active", "deleted", "unreachable"]-ScanTaskStatus = Literal["pending", "running", "done", "failed"]+FileStatus = Literal["active", "deleted", "unreachable"]+ScanStatus = Literal["pending", "running", "done", "failed"]ScanKind = Literal["manual", "watch"]ScanSource = Literal["unknown", "cli", "sdk", "api", "watch", "system"]RuleType = Literal["exclude", "parsing_rule"]WatchStatus = Literal["active", "unreachable"]InvalidateTarget = Literal["parses"]ForgetMatchedAs = Literal["file", "directory", "none"]+ConfigSource = Literal["default", "override"]PARSE_STATUS_PENDING: ParseStatus = "pending"PARSE_STATUS_PARSING: ParseStatus = "parsing"@@ -24,14 +25,14 @@ PARSE_STATUS_DONE: ParseStatus = "done"PARSE_STATUS_FAILED: ParseStatus = "failed"PARSE_STATUS_SUPERSEDED: ParseStatus = "superseded"-SCAN_STATUS_ACTIVE: ScanStatus = "active"-SCAN_STATUS_DELETED: ScanStatus = "deleted"-SCAN_STATUS_UNREACHABLE: ScanStatus = "unreachable"+FILE_STATUS_ACTIVE: FileStatus = "active"+FILE_STATUS_DELETED: FileStatus = "deleted"+FILE_STATUS_UNREACHABLE: FileStatus = "unreachable"-SCAN_TASK_STATUS_PENDING: ScanTaskStatus = "pending"-SCAN_TASK_STATUS_RUNNING: ScanTaskStatus = "running"-SCAN_TASK_STATUS_DONE: ScanTaskStatus = "done"-SCAN_TASK_STATUS_FAILED: ScanTaskStatus = "failed"+SCAN_STATUS_PENDING: ScanStatus = "pending"+SCAN_STATUS_RUNNING: ScanStatus = "running"+SCAN_STATUS_DONE: ScanStatus = "done"+SCAN_STATUS_FAILED: ScanStatus = "failed"SCAN_KIND_MANUAL: ScanKind = "manual"SCAN_KIND_WATCH: ScanKind = "watch"@@ -71,7 +72,7 @@ class ShutdownResponse(DoclibModel):class RemoveWatchResponse(DoclibModel):- path: str+ watch_id: intremoved: bool@@ -173,7 +174,7 @@ class ScanInfo(DoclibModel):kind: ScanKindsource: ScanSource = "unknown"watch_id: int | None = None- status: ScanTaskStatus+ status: ScanStatusfiles_seen: int = 0files_refreshed: int = 0files_new: int = 0@@ -201,7 +202,7 @@ class RecentScanInfo(DoclibModel):kind: ScanKindsource: ScanSource = "unknown"watch_id: int | None = None- status: ScanTaskStatus+ status: ScanStatusfiles_seen: int = 0files_refreshed: int = 0files_new: int = 0@@ -226,7 +227,7 @@ class FileInfo(DoclibModel):mtime_ms: intsha256: str | None = Nonewatch_id: int | None = None- scan_status: ScanStatus+ status: FileStatuserror_code: str | None = Noneerror_msg: str | None = Nonedeleted_at: int | None = None@@ -234,6 +235,13 @@ class FileInfo(DoclibModel):updated_at: int+class ListFilesResponse(DoclibModel):+ files: list[FileInfo] = Field(default_factory=list)+ total: int+ limit: int+ offset: int = 0++class DocInfo(DoclibModel):sha256: strsize_bytes: int@@ -244,7 +252,7 @@ class DocInfo(DoclibModel):keywords: str | None = Nonepage_count: int | None = Nonelanguage: str | None = None- is_scanned: int = 0+ is_image_based: int = 0meta_tier: Tier | None = Noneerror_code: str | None = Noneerror_msg: str | None = None@@ -261,7 +269,20 @@ class DocContentResponse(DoclibModel):sha256: strtier: Tiercontent: str | None = None- output: str | None = None+++class DocContentExportRequest(DoclibModel):+ tier: Tier+ pages: str | None = None+ format: str = "markdown"+ output: str+ no_marker: bool = False+++class DocContentExportResponse(DoclibModel):+ sha256: str+ tier: Tier+ output: strclass SearchResult(DoclibModel):@@ -311,18 +332,31 @@ class TierParseInfo(DoclibModel):done_at: int | None = None-class ConfigSetRequest(DoclibModel):- key: str+class ConfigValueRequest(DoclibModel):value: strclass ConfigResponse(DoclibModel):config: dict[str, str] = Field(default_factory=dict)+ sources: dict[str, ConfigSource] = Field(default_factory=dict)-class ConfigSetResponse(DoclibModel):+class ConfigValueResponse(DoclibModel):key: strvalue: str+ source: ConfigSource+++class ConfigSetRequest(ConfigValueRequest):+ pass+++class ConfigSetResponse(ConfigValueResponse):+ pass+++class ConfigUnsetResponse(ConfigValueResponse):+ removed: bool = Trueclass WatchRequest(DoclibModel):@@ -338,7 +372,7 @@ class WatchInfo(DoclibModel):removable: bool = Falseenabled: bool = Truerecursive: bool = False- watch_status: WatchStatus+ status: WatchStatusunreachable_at: int | None = Nonelast_scan_at: int | None = Nonelast_scan_files: int = 0@@ -421,7 +455,7 @@ class WatchStats(DoclibModel):path: strlabel: str | None = Noneremovable: bool = False- watch_status: WatchStatus+ status: WatchStatustotal_files: int = 0active_files: int = 0deleted_files: int = 0diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.pyindex 0fb82ec8..803c9d4f 100644--- a/mineru/utils/config_reader.py+++ b/mineru/utils/config_reader.py@@ -5,13 +5,6 @@ from typing import Anyfrom loguru import logger-try:- import torch- import torch_npu-except ImportError:- pass--# 定义配置文件名常量CONFIG_FILE_NAME = os.getenv("MINERU_TOOLS_CONFIG_JSON", "mineru.json")@@ -78,6 +71,10 @@ def get_device() -> str:device_mode = os.getenv("MINERU_DEVICE_MODE", None)if device_mode is not None:return device_mode+ try:+ import torch+ except ImportError:+ return "cpu"try:if torch.cuda.is_available(): # type: ignorereturn "cuda"@@ -89,6 +86,8 @@ def get_device() -> str:except Exception:passtry:+ import torch_npu+if torch_npu.npu.is_available(): # type: ignorereturn "npu"except Exception:diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex 124e75c0..717e294b 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -12,7 +12,9 @@ from mineru.doclib.background.ingest import IngestWorkerPoolfrom mineru.doclib.background.parse_server_health import api_server_args_for_tierfrom mineru.doclib.background.watch import WatchLoopfrom mineru.doclib.core.db import DatabaseManager+from mineru.doclib.core.file_io import FileStat, get_file_statfrom mineru.doclib.core.fts import FTSManager+from mineru.doclib.config_defaults import CONFIG_DEFAULTSfrom mineru.errors import InvalidRequestErrorfrom mineru.doclib.services.cleanup_svc import CleanupServicefrom mineru.doclib.services.config_svc import ConfigService@@ -26,6 +28,7 @@ from mineru.doclib.services.parse_svc import (from mineru.doclib.services.scan_svc import ScanServicefrom mineru.doclib.services.search_svc import SearchServicefrom mineru.doclib.server import DoclibServer+from mineru.doclib.types import ParseResponsefrom mineru.parser import backend_for_tier, resolve_tier_and_backendfrom mineru.types import PageInfo, Tier@@ -115,7 +118,7 @@ class _FakeDB:async def fetchone(self, sql: str, params: tuple[Any, ...]) -> dict[str, Any] | None:if sql.startswith("SELECT * FROM files WHERE path="):path = params[0]- if self.file_row and self.file_row["path"] == path and self.file_row["scan_status"] == "active":+ if self.file_row and self.file_row["path"] == path and self.file_row["status"] == "active":return self.file_rowif sql.startswith("SELECT page_count FROM docs WHERE sha256="):sha256 = params[0]@@ -123,7 +126,7 @@ class _FakeDB:return self.doc_rowif sql.startswith("SELECT * FROM files WHERE sha256="):sha256 = params[0]- if self.file_row and self.file_row["sha256"] == sha256 and self.file_row["scan_status"] == "active":+ if self.file_row and self.file_row["sha256"] == sha256 and self.file_row["status"] == "active":return self.file_rowif sql.startswith("SELECT status FROM parses WHERE id=") or sql.startswith("SELECT * FROM parses WHERE id="):parse_id = params[0]@@ -211,6 +214,47 @@ def test_managed_api_server_args_use_tier_for_process_start() -> None:assert api_server_args_for_tier("pro") == ["--tier", "pro", "--port", "15981"]+def test_get_file_stat_returns_typed_file_stat(tmp_path: Path) -> None:+ source = tmp_path / "note.txt"+ source.write_text("content", encoding="utf-8")++ stat = asyncio.run(get_file_stat(str(source)))++ assert isinstance(stat, FileStat)+ assert stat.size_bytes == source.stat().st_size+ assert stat.mtime_ms == int(source.stat().st_mtime * 1000)+++def test_config_defaults_are_code_backed_and_unset_removes_override(tmp_path: Path) -> None:+ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "mineru.db"))+ await db.initialize()+ service = ConfigService(db)++ seeded_rows = await db.fetchall("SELECT key, value FROM config ORDER BY key")+ assert seeded_rows == []++ assert await service.get("parse_server.local.mode") == CONFIG_DEFAULTS["parse_server.local.mode"]+ config, sources = await service.get_all_with_sources()+ assert config["parse_server.local.mode"] == CONFIG_DEFAULTS["parse_server.local.mode"]+ assert sources["parse_server.local.mode"] == "default"++ await service.set("parse_server.local.mode", "managed")+ assert await service.get("parse_server.local.mode") == "managed"+ config, sources = await service.get_all_with_sources()+ assert config["parse_server.local.mode"] == "managed"+ assert sources["parse_server.local.mode"] == "override"++ await service.unset("parse_server.local.mode")+ assert await service.get("parse_server.local.mode") == CONFIG_DEFAULTS["parse_server.local.mode"]+ config, sources = await service.get_all_with_sources()+ assert config["parse_server.local.mode"] == CONFIG_DEFAULTS["parse_server.local.mode"]+ assert sources["parse_server.local.mode"] == "default"+ assert await db.fetchall("SELECT key, value FROM config ORDER BY key") == []++ asyncio.run(_run())++def test_compaction_uses_configured_data_dir(tmp_path: Path) -> None:sha256 = "b" * 64tier = "standard"@@ -239,7 +283,7 @@ def test_compaction_uses_configured_data_dir(tmp_path: Path) -> None:def test_invalidate_deletes_fts_when_no_done_batches_remain(tmp_path: Path) -> None:sha256 = "c" * 64parses = [{"sha256": sha256, "tier": "standard", "pages": "1", "status": "done", "done_at": 1000}]- db = _FakeDB(parses=parses, file_row={"sha256": sha256, "scan_status": "active", "filename": "doc.pdf"})+ db = _FakeDB(parses=parses, file_row={"sha256": sha256, "status": "active", "filename": "doc.pdf"})fts = _FakeFTS()service = ParseService(db=db, fts=fts, config_svc=None, data_dir=str(tmp_path))@@ -259,7 +303,7 @@ def test_invalidate_rebuilds_fts_from_highest_remaining_done_tier(tmp_path: Path{"sha256": sha256, "tier": "flash", "pages": "1", "status": "done", "done_at": 1000},{"sha256": sha256, "tier": "standard", "pages": "1", "status": "done", "done_at": 2000},]- db = _FakeDB(parses=parses, file_row={"sha256": sha256, "scan_status": "active", "filename": "doc.pdf"})+ db = _FakeDB(parses=parses, file_row={"sha256": sha256, "status": "active", "filename": "doc.pdf"})fts = _FakeFTS()service = ParseService(db=db, fts=fts, config_svc=None, data_dir=str(tmp_path))@@ -306,7 +350,7 @@ def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path:"path": path,"filename": "doc.pdf","sha256": sha256,- "scan_status": "active",+ "status": "active","ext": "pdf","mtime_ms": int(stat.st_mtime * 1000),"size_bytes": stat.st_size,@@ -319,12 +363,13 @@ def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path:result = asyncio.run(service.request_parse(path, tier="standard", pages="1~10", force=True))- assert result["wait_parse_ids"] == [11, 12]- assert result["reused_parse_ids"] == [11]- assert result["created_parse_ids"] == [12]- assert result["pages"] == "1~10"- assert result["status"] == "pending"- assert result["cache_hit"] is False+ assert isinstance(result, ParseResponse)+ assert result.wait_parse_ids == [11, 12]+ assert result.reused_parse_ids == [11]+ assert result.created_parse_ids == [12]+ assert result.pages == "1~10"+ assert result.status == "pending"+ assert result.cache_hit is Falseassert db.updated_priorities == [11]assert parses[-1]["pages"] == "1~5,9~10"@@ -421,15 +466,15 @@ def test_refresh_file_marks_missing_known_path_deleted(tmp_path: Path) -> None:source.unlink()refreshed = await service.refresh_file(str(source))- row = await db.fetchone("SELECT sha256, scan_status, deleted_at FROM files WHERE path=?", (str(source),))+ row = await db.fetchone("SELECT sha256, status, deleted_at FROM files WHERE path=?", (str(source),))assert refreshed.status == "deleted"assert refreshed.file is not Noneassert refreshed.file.sha256 == original_sha- assert refreshed.file.scan_status == "deleted"+ assert refreshed.file.status == "deleted"assert row is not Noneassert row["sha256"] == original_sha- assert row["scan_status"] == "deleted"+ assert row["status"] == "deleted"assert row["deleted_at"] is not Noneasyncio.run(_run())@@ -452,14 +497,14 @@ def test_refresh_file_records_stat_error_without_marking_deleted(tmp_path: Path,monkeypatch.setattr(parse_svc_module, "get_file_stat", _permission_denied)refreshed = await service.refresh_file(str(source))- row = await db.fetchone("SELECT scan_status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),))+ row = await db.fetchone("SELECT status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),))assert refreshed.status == "error"assert refreshed.file is not None- assert refreshed.file.scan_status == "active"+ assert refreshed.file.status == "active"assert refreshed.file.error_code == "file_permission_denied"assert row is not None- assert row["scan_status"] == "active"+ assert row["status"] == "active"assert row["error_code"] == "file_permission_denied"assert row["error_msg"] == "permission denied"assert row["deleted_at"] is None@@ -566,7 +611,7 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:(sha256, 10, file_type, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / filename), filename, filename.rsplit(".", 1)[1], 10, now, sha256, "active", now, now),)@@ -604,17 +649,17 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_pathawait fts.replace(sha256=sha256, tier="standard", text="fallback needle", title="", author="", filename=f"{sha256[0]}.pdf")await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "active.pdf"), "active.pdf", "pdf", 10, now, sha_active, "active", now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "deleted-copy.pdf"), "deleted-copy.pdf", "pdf", 10, now, sha_active, "deleted", now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "deleted-only.pdf"), "deleted-only.pdf", "pdf", 10, now, sha_deleted, "deleted", now, now),)@@ -645,7 +690,7 @@ def test_find_filters_by_ext(tmp_path: Path) -> None:(sha256, 10, ext, now, now),)file_id = await db.execute_insert(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / filename), filename, ext, 10, now, sha256, "active", now, now),)@@ -681,19 +726,19 @@ def test_refresh_file_marks_only_current_file_unreachable_when_watch_root_is_misroot.rmdir()refreshed = await service.refresh_file(str(source), watch_id=watch["id"])- source_row = await db.fetchone("SELECT scan_status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),))- other_row = await db.fetchone("SELECT scan_status FROM files WHERE path=?", (str(other),))- watch_row = await db.fetchone("SELECT watch_status, unreachable_at FROM watch_targets WHERE id=?", (watch["id"],))+ source_row = await db.fetchone("SELECT status, error_code, error_msg, deleted_at FROM files WHERE path=?", (str(source),))+ other_row = await db.fetchone("SELECT status FROM files WHERE path=?", (str(other),))+ watch_row = await db.fetchone("SELECT status, unreachable_at FROM watches WHERE id=?", (watch["id"],))assert refreshed.status == "unreachable"assert source_row is not None- assert source_row["scan_status"] == "unreachable"+ assert source_row["status"] == "unreachable"assert source_row["error_code"] is Noneassert source_row["error_msg"] is Noneassert source_row["deleted_at"] is None- assert other_row == {"scan_status": "active"}+ assert other_row == {"status": "active"}assert watch_row is not None- assert watch_row["watch_status"] == "unreachable"+ assert watch_row["status"] == "unreachable"assert watch_row["unreachable_at"] is not Noneasyncio.run(_run())@@ -717,16 +762,16 @@ def test_remove_watch_converts_unreachable_files_to_deleted_and_unbinds_watch(tm"INSERT INTO scans (path, kind, source, watch_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",(str(root), "watch", "cli", watch["id"], "done", now, now),)- await db.execute("UPDATE files SET scan_status=? WHERE path=?", ("unreachable", str(source)))+ await db.execute("UPDATE files SET status=? WHERE path=?", ("unreachable", str(source)))await config_svc.remove_watch(str(root))- row = await db.fetchone("SELECT watch_id, scan_status, deleted_at FROM files WHERE path=?", (str(source),))- watch_row = await db.fetchone("SELECT * FROM watch_targets WHERE id=?", (watch["id"],))+ row = await db.fetchone("SELECT watch_id, status, deleted_at FROM files WHERE path=?", (str(source),))+ watch_row = await db.fetchone("SELECT * FROM watches WHERE id=?", (watch["id"],))scan_row = await db.fetchone("SELECT path, kind, watch_id FROM scans WHERE path=?", (str(root),))assert row is not Noneassert row["watch_id"] is None- assert row["scan_status"] == "deleted"+ assert row["status"] == "deleted"assert row["deleted_at"] is not Noneassert watch_row is Noneassert scan_row == {"path": str(root), "kind": "watch", "watch_id": None}@@ -753,10 +798,10 @@ def test_watch_scan_refreshes_known_active_paths_before_walk(tmp_path: Path) ->source.unlink()await watch_loop._initial_scan(str(root), watch["id"])- row = await db.fetchone("SELECT scan_status, deleted_at FROM files WHERE path=?", (str(source),))+ row = await db.fetchone("SELECT status, deleted_at FROM files WHERE path=?", (str(source),))assert row is not None- assert row["scan_status"] == "deleted"+ assert row["status"] == "deleted"assert row["deleted_at"] is not Noneasyncio.run(_run())@@ -782,12 +827,12 @@ def test_watch_scan_marks_root_unreachable_without_refreshing_all_files(tmp_pathsource.unlink()root.rmdir()await watch_loop._initial_scan(str(root), watch["id"])- file_row = await db.fetchone("SELECT scan_status FROM files WHERE path=?", (str(source),))- watch_row = await db.fetchone("SELECT watch_status, unreachable_at FROM watch_targets WHERE id=?", (watch["id"],))+ file_row = await db.fetchone("SELECT status FROM files WHERE path=?", (str(source),))+ watch_row = await db.fetchone("SELECT status, unreachable_at FROM watches WHERE id=?", (watch["id"],))- assert file_row == {"scan_status": "active"}+ assert file_row == {"status": "active"}assert watch_row is not None- assert watch_row["watch_status"] == "unreachable"+ assert watch_row["status"] == "unreachable"assert watch_row["unreachable_at"] is not Noneasyncio.run(_run())@@ -811,7 +856,7 @@ def test_scan_service_creates_and_processes_manual_file_scan(tmp_path: Path) ->assert await scan_svc.process_scan(task) is Truedone = await scan_svc.get_scan(scan.id)- file_row = await db.fetchone("SELECT path, sha256, scan_status FROM files WHERE path=?", (str(source),))+ file_row = await db.fetchone("SELECT path, sha256, status FROM files WHERE path=?", (str(source),))assert done.status == "done"assert done.files_seen == 1@@ -819,7 +864,7 @@ def test_scan_service_creates_and_processes_manual_file_scan(tmp_path: Path) ->assert done.files_new == 1assert file_row is not Noneassert file_row["sha256"] is None- assert file_row["scan_status"] == "active"+ assert file_row["status"] == "active"asyncio.run(_run())@@ -950,7 +995,7 @@ def test_cleanup_deleted_files_does_not_cleanup_orphan_docs(tmp_path: Path) -> N(sha256, 7, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, deleted_at, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, deleted_at, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "deleted.txt"), "deleted.txt", "txt", 7, now, sha256, "deleted", now, now, now),)@@ -990,12 +1035,12 @@ def test_cleanup_orphans_keeps_docs_referenced_by_deleted_or_unreachable_files(t(sha256, 7, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, deleted_at, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, deleted_at, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "deleted.txt"), "deleted.txt", "txt", 7, now, deleted_sha, "deleted", now, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "unreachable.txt"), "unreachable.txt", "txt", 7, now, unreachable_sha, "unreachable", now, now),)@@ -1037,12 +1082,12 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->("metadata_failed", sha_pending),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "watched" / "done.pdf"), "done.pdf", "pdf", 7, now, sha_done, watch["id"], "active", now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, scan_status, error_code, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, status, error_code, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "watched" / "pending.pdf"),@@ -1059,12 +1104,12 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "watched" / "need-ingest.pdf"), "need-ingest.pdf", "pdf", 7, now, watch["id"], "active", now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, scan_status, error_code, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, status, error_code, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(tmp_path / "watched" / "blocked-ingest.pdf"), "blocked-ingest.pdf", "pdf", 7, now, watch["id"], "active", "ingest_failed", now, now),)@@ -1151,7 +1196,7 @@ def test_forget_path_deletes_file_row_and_filename_fts_without_deleting_doc(tmp_(sha256, "standard", "content", "doc.pdf"),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(path, "doc.pdf", "pdf", 7, now, sha256, "active", now, now),)@@ -1196,12 +1241,12 @@ def test_forget_directory_matches_historical_prefix_rows(tmp_path: Path) -> None(sha256, 7, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(root / "a.pdf"), "a.pdf", "pdf", 7, now, sha_a, "active", now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(str(root / "nested" / "b.pdf"), "b.pdf", "pdf", 7, now, sha_b, "deleted", now, now),)@@ -1233,7 +1278,7 @@ def test_forget_rejects_watch_root_and_warns_under_active_watch(tmp_path: Path)("a" * 64, 7, now, now),)await db.execute(- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, scan_status, first_seen_at, updated_at) "+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, status, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(path, "doc.pdf", "pdf", 7, now, "a" * 64, watch["id"], "active", now, now),)@@ -1306,7 +1351,7 @@ def test_process_doc_marks_empty_page_result_failed(tmp_path: Path) -> None:file_row={"path": "/tmp/doc.pdf","sha256": sha256,- "scan_status": "active",+ "status": "active","filename": "doc.pdf","title": "","author": "",@@ -1359,7 +1404,7 @@ def test_process_doc_fails_when_batch_json_cannot_be_written(tmp_path: Path) ->file_row={"path": "/tmp/doc.pdf","sha256": sha256,- "scan_status": "active",+ "status": "active","filename": "doc.pdf","title": "","author": "",diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.pyindex f1cd5ed0..b2914c46 100644--- a/tests/unittest/test_doclib_interface_contract.py+++ b/tests/unittest/test_doclib_interface_contract.py@@ -10,6 +10,7 @@ from mineru.doclib.server import DoclibServerfrom mineru.doclib.types import (ConfigResponse,DocInfo,+ DocContentExportRequest,ErrorBucket,ErrorInfo,ErrorResponse,@@ -19,6 +20,7 @@ from mineru.doclib.types import (ExcludeRuleRequest,FileInfo,FileInfoResponse,+ ListFilesResponse,FindResponse,FindResult,ForgetPathRequest,@@ -63,14 +65,18 @@ def test_doclib_interface_declares_expected_methods() -> None:"create_scan","list_scans","get_scan",+ "list_files","list_docs","get_doc","get_doc_content",+ "export_doc_content","search","find","get_file_info","get_config",+ "get_config_key","set_config",+ "unset_config","add_watch","list_watches","remove_watch",@@ -143,9 +149,25 @@ def test_interface_app_uses_doclib_server_routes() -> None:route_paths = {getattr(route, "path", "") for route in app.routes}assert "/api/v1/server/status" in route_paths+ assert "/api/v1/server/shutdown" in route_paths+ assert "/api/v1/configs" in route_paths+ assert "/api/v1/configs/{key}" in route_paths+ assert "/api/v1/watches" in route_paths+ assert "/api/v1/watches/{watch_id}" in route_paths+ assert "/api/v1/exclude-rules" in route_paths+ assert "/api/v1/exclude-rules/{rule_id}" in route_paths+ assert "/api/v1/parsing-rules" in route_paths+ assert "/api/v1/parsing-rules/{rule_id}" in route_paths+ assert "/api/v1/files" in route_pathsassert "/api/v1/docs" in route_paths+ assert "/api/v1/docs/{sha256}/exports" in route_pathsassert "/api/docs" in route_pathsassert "/docs" not in route_paths+ assert "/api/v1/config" not in route_paths+ assert "/api/v1/config/watch" not in route_paths+ assert "/api/v1/config/exclude" not in route_paths+ assert "/api/v1/config/parsing-rules" not in route_paths+ assert "/api/v1/shutdown" not in route_pathsassert "create_parses" not in route_namesassert "parse_content" not in route_names@@ -162,7 +184,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:watch_stats = WatchStats(watch_id=1,path="/tmp",- watch_status="active",+ status="active",total_files=3,active_files=2,deleted_files=1,@@ -185,13 +207,14 @@ def test_core_doclib_schemas_are_instantiable() -> None:mtime_ms=11,sha256="abc",watch_id=1,- scan_status="active",+ status="active",error_code="scan_failed",error_msg="failed",first_seen_at=20,updated_at=30,deleted_at=None,)+ files = ListFilesResponse(files=[file_info], total=1, limit=200, offset=0)doc_info = DocInfo(sha256="abc",size_bytes=123,@@ -199,7 +222,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:subject="demo",keywords="a,b",page_count=3,- is_scanned=0,+ is_image_based=0,meta_tier="standard",first_seen_at=40,updated_at=50,@@ -228,7 +251,7 @@ def test_core_doclib_schemas_are_instantiable() -> None:parsed_tiers=[tier_info],active_parses=[parse_info],)- watch = WatchInfo(id=1, path="/tmp", recursive=True, watch_status="active", last_scan_at=100, last_scan_files=3)+ watch = WatchInfo(id=1, path="/tmp", recursive=True, status="active", last_scan_at=100, last_scan_files=3)exclude_rule = ExcludeRuleInfo(id=2, pattern="*.tmp", hit_count=4)parsing_rule = ParsingRuleInfo(id=3, pattern="*.pdf", tier="standard", pages="1~5", remote=True)watches = WatchListResponse(watches=[watch])@@ -248,9 +271,10 @@ def test_core_doclib_schemas_are_instantiable() -> None:find_result = FindResult(filename="a.pdf", ext="pdf", size_bytes=123, page_count=3, paths=["/tmp/a.pdf"])search_response = SearchResponse(results=[search_result], total=1, query="matched")find_response = FindResponse(results=[find_result], total=1, query="a")- config = ConfigResponse(config={"watch_default_tier": "standard"})+ config = ConfigResponse(config={"watch_default_tier": "standard"}, sources={"watch_default_tier": "override"})shutdown_response = ShutdownResponse(accepted=True, message="Server shutting down...")- remove_watch_response = RemoveWatchResponse(path="/tmp", removed=True)+ remove_watch_response = RemoveWatchResponse(watch_id=1, removed=True)+ export_request = DocContentExportRequest(tier="standard", output="/tmp/a.md")remove_exclude_response = RemoveExcludeRuleResponse(rule_id=2, removed=True)remove_parsing_response = RemoveParsingRuleResponse(rule_id=3, removed=True)exclude_rule_request = ExcludeRuleRequest(pattern="*.tmp")@@ -263,6 +287,8 @@ def test_core_doclib_schemas_are_instantiable() -> None:assert forget_response.matched_as == "file"assert scan_request.kind == "manual"assert scan_list.scans[0].id == 1+ assert files.files == [file_info]+ assert files.total == 1assert "format" not in ParseRequest.model_fieldsassert status.files_total == 0assert status.watch_stats == [watch_stats]@@ -295,8 +321,10 @@ def test_core_doclib_schemas_are_instantiable() -> None:assert "sha256" not in FindResult.model_fieldsassert "snippet" not in FindResult.model_fieldsassert config.config == {"watch_default_tier": "standard"}+ assert config.sources == {"watch_default_tier": "override"}assert shutdown_response.accepted- assert remove_watch_response.path == "/tmp"+ assert remove_watch_response.watch_id == 1+ assert export_request.output == "/tmp/a.md"assert remove_exclude_response.rule_id == 2assert remove_parsing_response.rule_id == 3assert exclude_rule_request.pattern == "*.tmp"@@ -322,6 +350,7 @@ def test_get_semantic_methods_do_not_use_request_body_models() -> None:get_semantic_methods = ["list_parses","list_scans",+ "list_files","list_docs","get_doc_content","search",@@ -338,3 +367,42 @@ def test_get_doc_expands_files_only_when_requested() -> None:signature = inspect.signature(DoclibInterface.get_doc)assert "expand_files" in signature.parametersassert signature.parameters["expand_files"].default is False+++def test_next_cli_doclib_route_shapes_are_declared() -> None:+ expected_routes = {+ "shutdown_server": ("POST", "/server/shutdown"),+ "list_parses": ("GET", "/parses"),+ "list_files": ("GET", "/files"),+ "list_docs": ("GET", "/docs"),+ "get_doc_content": ("GET", "/docs/{sha256}/content"),+ "export_doc_content": ("POST", "/docs/{sha256}/exports"),+ "get_config": ("GET", "/configs"),+ "get_config_key": ("GET", "/configs/{key}"),+ "set_config": ("PUT", "/configs/{key}"),+ "unset_config": ("DELETE", "/configs/{key}"),+ "add_watch": ("POST", "/watches"),+ "list_watches": ("GET", "/watches"),+ "remove_watch": ("DELETE", "/watches/{watch_id}"),+ "add_exclude_rule": ("POST", "/exclude-rules"),+ "list_exclude_rules": ("GET", "/exclude-rules"),+ "remove_exclude_rule": ("DELETE", "/exclude-rules/{rule_id}"),+ "add_parsing_rule": ("POST", "/parsing-rules"),+ "list_parsing_rules": ("GET", "/parsing-rules"),+ "remove_parsing_rule": ("DELETE", "/parsing-rules/{rule_id}"),+ }++ for method_name, (method, path) in expected_routes.items():+ client_route = getattr(DoclibClient, method_name)._route_info+ server_route = getattr(DoclibServer, method_name)._route_info+ assert client_route.method == method, method_name+ assert client_route.path == path, method_name+ assert server_route.method == method, method_name+ assert server_route.path == path, method_name++ assert "output" not in inspect.signature(DoclibInterface.get_doc_content).parameters+ assert "limit" in inspect.signature(DoclibInterface.list_parses).parameters+ assert "limit" in inspect.signature(DoclibInterface.list_docs).parameters+ assert "file_type" in inspect.signature(DoclibInterface.list_docs).parameters+ assert "watch_id" in inspect.signature(DoclibInterface.remove_watch).parameters+ assert "path" not in inspect.signature(DoclibInterface.remove_watch).parameters