diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index edf5502..831bd40 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -54,6 +54,13 @@ jobs: - name: Unit tests (offline) run: python -m unittest discover -s tests -v + # 第三方集成件(integrations/factscribe-legal)的测试:纯标准库、离线。 + # 放进主矩阵是有意的:它的 TOML 读取层在 3.10 走自带兜底解析器、 + # 在 3.11+ 走标准库 tomllib —— 两边必须读出同一份事实账, + # 所以这个矩阵(含 3.10)就是它的回归线。 + - name: Integration tests (offline, integrations/factscribe-legal) + run: python -m unittest discover -s integrations/factscribe-legal/tests -v + # Acceptance sample must stay red for exactly the reasons we document: # exit 1 = violations found (not 0 = false green, not 2 = broken config). - name: Acceptance sample fails as documented diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d0389f..dda9f67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and will not change without a major version bump. - **Breaking**: protocol literals hard-cut to the `factscribe` namespace — project schema `factscribe-project/3.x` (the older `factscribe/3.x` alias still reads), fact schema `factscribe-fact/3.x`, stamp `factscribe-stamp/3.0`, report `factscribe-report/3.0`, magic comments `% factscribe:generated` / `% factscribe:table-map`; the deprecated old-name config fallback is removed — only `factscribe.toml` is read, so data written under the previous old-name config file or schema strings is no longer read. The on-disk working directory was renamed to `factscribe-dev`. ### Added +- **New third-party integration: `integrations/factscribe-legal/`** — adds a *legal dimension* gate next to the existing evidence-chain gates. paperkit checks that a number in the text traces back to a signed, hashed source; it does not check whether that source is a statute, whether the statute is in force on the reference date, or whether the number really appears in the statute — three failures that are all silent. The integration ships four offline gates over official open-data artifacts: `verify` (France, LEGI article XML), `verify-cn` (China, FLK official detail JSON), `verify-case` (China, official case corpus) and `verify-it` (Italy, Normattiva AKN). Two-layer evidence: the fact ledger points at a derived *evidence card*, and the gate recomputes the hash of the **official bytes** the card declares — so tampering with the official XML is caught even though upstream stays green (the two layers do not overlap). New codes: `LEGAL_PROV_UNKNOWN` `LEGAL_PROV_NOT_IN_FORCE` `LEGAL_PROV_HASH_MISMATCH` `LEGAL_CARD_SHA256_MISMATCH` `LEGAL_CARD_NO_HASH` `LEGAL_QUOTE_MISMATCH` (red) and `LEGAL_PROV_SCHEDULED` `LEGAL_PROV_REPEALED` `LEGAL_PROV_VIEW_MISMATCH` `LEGAL_PROV_AMBIGUOUS` `LEGAL_COVERAGE_GAP` (yellow); `CN_*` `CASE_*` `IT_*` for the other three. Exit codes follow the frozen contract (0 green / 1 red / 2 config / 3 yellow). stdlib-only, no network in tests, no `eval`, no change to `factscribe/` (not in `packages`, no new dependency, upstream codes untouched) — it lives under `integrations/` like `minifactscribe`. Python ≥ 3.10: the fact ledger is read with stdlib `tomllib` on 3.11+ and with a bundled fallback parser on 3.10; the two are cross-checked to produce byte-identical ledgers, because upstream's own 3.10 fallback mis-parses nested arrays. CI runs the integration's tests offline across the whole 3.10–3.14 matrix. Python total 1357 (unchanged by this PR); factscribe-legal integration 50. See `docs/implementation/INTEGRATION-LEGAL.md`. - Dual-name unification (双名归一): the project name is now `factscribe` everywhere. The project config file is `factscribe.toml`; `init`, error messages, `--help`, docs and the UI only name `factscribe.toml`. The exemption macro `\pkignore` is renamed to `\fsignore` (generated preamble, scanner, R-07 diagnostic `FSIGNORE_QUANT` — formerly `PKIGNORE_QUANT` — fixtures, docs and the preview renderer all follow); package author attribution is `factscribe contributors`; the stale pre-rename egg-info build artifact is removed. - Page-level actions: the fact form opens from a top-right "append fact" button; the reports page scaffolds a commented `report.toml` template (`POST /api/reports/template`, `partial` status); the citations page can append a BibTeX entry (`POST /api/citations/add`) and delete one by key (`POST /api/citations/delete`). Preview also renders `\paragraph`, `\citep`-family, `\checkmark`, `\pkignore`, table captions, abstract/quote/description and starred environments; the audit button moved into the issues panel. Python total 1356; Node total 158. - Three pages get a top-right action each. **Facts**: `#btn-wb-fact-add` in the `#panel-facts` header opens the existing `#wb-fact-card` (no second implementation of the form), scrolls it into view and puts the caret in `#wb-fact-id`. **Reports**: `#btn-report-new` asks for a report id (default `report-YYYYMMDD`) and calls the new `POST /api/reports/template`, which writes a commented `factscribe/report@1` template to `/reports/.report.toml` (`schema`, `id`, `experiment`, `status = "partial"`, `generated_at`, `population = { id = … }` plus a commented-out example metric); the id whitelist is `[A-Za-z0-9._-]` (400 `REPORT_ID_INVALID`), an existing target is 409 `REPORT_EXISTS`, and a read-only workbench gets 403 `READ_ONLY`. The page then refreshes the report list, selects the new report and says 「模板已建,填好 metrics 后检查/封存/签收」; the empty state now explains where reports come from instead of naming a glob. **Citations**: `#btn-cite-add` opens an inline `#cite-form` (key / title / author / year / DOI / arXiv) that calls the new `POST /api/citations/add` — the entry is appended to the project's `cfg.bib` with an atomic write (409 `CITATION_EXISTS` on a duplicate key, 400 `CITATION_INVALID` on a key outside `[A-Za-z0-9:._-]+`) — and every row gains a delete button (`data-cite-delete=""`) that confirms first and then calls `POST /api/citations/delete`, which locates the entry's line range with `citations.parse_bib` and removes exactly that block (404 `CITATION_MISSING` when the key is unknown); other entries are left untouched. Both citation actions are disabled on a read-only workbench. New module `factscribe/citeedit.py`; MiniFactScribe proxies the three paths as `/api/workbench/reports/template` and `/api/workbench/citations/add|delete`. Python total 1356; Node total 158. diff --git a/docs/implementation/INTEGRATION-LEGAL.md b/docs/implementation/INTEGRATION-LEGAL.md new file mode 100644 index 0000000..7d5ebb5 --- /dev/null +++ b/docs/implementation/INTEGRATION-LEGAL.md @@ -0,0 +1,160 @@ +# INTEGRATION-LEGAL|第三方集成件:法律维度(法国 / 中国 / 中国案例 / 意大利) + +> 日期:2026-11-15 +> 对应规范:`docs/design/SPEC-V1.md` §2.3(paperkit 的诚实边界:只核「账本一致」,不核「科学为真」) +> 对应集成件:`integrations/factscribe-legal/`(**第三方件,不进 `factscribe/` 包**) +> 纪律:**上游 `factscribe/` 一行未改** —— 行为、退出码、违规码、`packages = ["factscribe"]` 打包范围都不动。 +> 本文件只记「这个集成件在哪、判什么、边界在哪、读数是多少」。 + +## 0. 结论(先看这里) + +| 事项 | 结果 | +|---|---| +| 进不进上游包 | **不进**。放 `integrations/factscribe-legal/`,沿用 `integrations/minifactscribe/` 的先例;`pyproject.toml` 的 `packages = ["factscribe"]` 不变 | +| 上游核心改动 | **零**。`factscribe/`、`SPEC-*`、`README*.md` 的码表、退出码契约均未动 | +| 新增依赖 | **零**。纯标准库,无网络调用,无 `eval` | +| Python 版本 | **≥ 3.10**(CI 矩阵 3.10–3.14 全跑;3.10 走自带 TOML 兜底解析器) | +| 退出码 | 沿用上游:**0 绿 / 1 红 / 2 配置错 / 3 黄**(`verify`/`verify-cn`/`verify-case`/`verify-it` 四个子命令一致) | +| 集成件自测 | **50 例全绿**(离线);上游自身测试 **1356 例全绿**(加了集成件目录后不变) | +| 真实项目读数 | 法国 **0 红 / 1 黄**(`LEGAL_COVERAGE_GAP`)|中国法条 **0 红 / 0 黄**|中国案例 **0 红 / 0 黄**|意大利 **0 红 / 0 黄**(参考日取 2026-11-14;改用 2026-11-15 则报 `IT_VERSION_GAP` 黄) | +| 事实账规模(真实项目) | 法国 15 条|中国法条 16 条|中国案例 7 条|意大利 9 条|管道 13 条(合计 60 条) | +| 篡改检出 | 法国官方 XML 被改 → 上游是绿的、法律闸是红的(两层不重叠);CN/IT 篡改演示各 5/5 命中 | + +## 1. 改动地图 + +| 文件 | 责任 | +|---|---| +| `integrations/factscribe-legal/factscribe_legal/provisions.py` | 法国侧语料读取(LEGI 版本池)、法文数字词 → 整数、`norm_text` | +| `integrations/factscribe-legal/factscribe_legal/verify.py` | 法国闸:法条存在性、参考日生效、官方字节哈希、卡片哈希、值出自正文、语料/现行视图一致性 | +| `integrations/factscribe-legal/factscribe_legal/cn_corpus.py` | 中国侧语料读取(FLK catalog 目录树) | +| `integrations/factscribe-legal/factscribe_legal/cn_verify.py` | 中国法条闸:法规现行有效、条文号存在、官方件未变、卡片链完整 | +| `integrations/factscribe-legal/factscribe_legal/case_verify.py` | 中国案例闸:案号/日期/金额与官方件一致、卡片正文未分叉、回执链完整 | +| `integrations/factscribe-legal/factscribe_legal/it_verify.py` | 意大利闸:条文存在、官方 AKN 哈希、条文切片哈希、卡片字段一致、值出自 AKN 正文、参考日版本差 | +| `integrations/factscribe-legal/factscribe_legal/facts_ledger.py` | 事实账同值检测与 `dup_ok` 标注(上游 R-04 的 `DUPLICATE_VALUE` 需要显式承认同值) | +| `integrations/factscribe-legal/factscribe_legal/_toml.py` | TOML 读取层:3.11+ 用 `tomllib`,3.10 用自带兜底解析器 | +| `integrations/factscribe-legal/factscribe_legal/cli.py` | `fetch` / `verify` / `verify-cn` / `verify-case` / `verify-it` | +| `integrations/factscribe-legal/tests/` | 50 例离线测试(含双向、跨版本、假绿回归) | +| `.github/workflows/test.yml` | 加一步:在主矩阵(3.10–3.14)里跑集成件的离线测试 | + +## 2. 为什么它值得单独成一件 + +上游判的是**证据链**:正文里的数字能不能回到一份签过字、算过哈希的原始材料。 +它不判「这份材料是不是法条」「这条法条今天还有效」「这个数字是不是真的出自这条法条」。 + +这三条在法律写作里最容易翻车,且**都是静默翻车**: + +- 法条被修改后**旧版本不会消失** ⇒ 按条文编号引用会悄悄拿到旧文本; +- 法条常把数字写成词(`trente-cinq heures`)⇒ 不解析法文数字词就核不出出处; +- 官方法条是**多形态**的(原始 / 现行 / 多时效)⇒ 不钉版本就是在赌。 + +所以本集成件做的事只有一件:**把「引用的是不是那条、那天的、那个字节」变成机械判定。** + +## 3. 四个闸的判据与边界 + +### 3.1 法国(`verify`) + +| 码 | 严重度 | 判什么 | +|---|---|---| +| `LEGAL_PROV_UNKNOWN` | 红 | 引用的法条在语料里不存在 | +| `LEGAL_PROV_NOT_IN_FORCE` | 红 | 参考日当天该版本不生效(引了旧版或未来版) | +| `LEGAL_PROV_HASH_MISMATCH` | 红 | 现算官方 XML 哈希 ≠ 语料记录的哈希(官方字节被人动过) | +| `LEGAL_CARD_SHA256_MISMATCH` | 红 | 现算证据卡哈希 ≠ 事实账 `source_sha256`(卡被人动过) | +| `LEGAL_CARD_NO_HASH` | 红 | 卡里没有 `OFFICIAL_XML_SHA256` 声明(无法复核) | +| `LEGAL_QUOTE_MISMATCH` | 红 | 事实里的值不出现于该法条的官方正文 | +| `LEGAL_PROV_SCHEDULED` | 黄 | 引的是已排期、尚未生效的版本 | +| `LEGAL_PROV_REPEALED` | 黄 | 引的是已废止版本 | +| `LEGAL_PROV_VIEW_MISMATCH` | 黄 | 语料版本与现行视图不是同一份 | +| `LEGAL_PROV_AMBIGUOUS` | 黄 | 同一编号能定到多条(版本选不唯一) | +| `LEGAL_COVERAGE_GAP` | 黄 | 参考日当天的官方件没拿到(版本池落后) | + +**边界**:绿**不代表**法条写得对,只代表「引用的法条真实存在、哈希未变、且在参考日生效」。 + +### 3.2 中国法条(`verify-cn`) + +红:`CN_PROV_UNKNOWN` `CN_PROV_NOT_IN_FORCE` `CN_ARTICLE_NOT_FOUND` `CN_CARD_MISSING` +`CN_CARD_NO_HASH` `CN_CARD_SHA256_MISMATCH` `CN_OFFICIAL_HASH_MISMATCH` `CN_VALUE_MISMATCH`。 + +**边界(必须写进任何引用本闸结论的地方)**:中国侧官方件**不含条文正文** +⇒ 能核「法规现行有效」「条文号存在」「官方件未变」,**不能**核「数字出自正文」。 +这是官方发布形态决定的,不是实现的缺陷。 + +### 3.3 中国案例(`verify-case`) + +红:`CASE_OFFICIAL_MISSING` `CASE_CARD_MISSING` `CASE_OFFICIAL_HASH_MISMATCH` +`CASE_NO_MISMATCH` `CASE_DATE_MISMATCH` `CASE_AMOUNT_MISMATCH` +`CASE_VALUE_NOT_IN_OFFICIAL` `CASE_CARD_TEXT_DIVERGED` `CASE_CHAIN_BROKEN`。 + +**边界**:人民法院案例库存的是**要旨体例案例稿**,不是判决书原文(无抬头、无审判长、无落款印章)。 +本闸核的是「这份案例稿与官方件一致」,不是「判决书原文没被改」。 + +### 3.4 意大利(`verify-it`) + +红:`IT_PROV_UNKNOWN` `IT_CARD_MISSING` `IT_CARD_NO_HASH` `IT_CARD_SHA256_MISMATCH` +`IT_SOURCE_HASH_MISMATCH` `IT_ARTICLE_HASH_MISMATCH` `IT_ARTICLE_NOT_IN_SOURCE` +`IT_CARD_FIELD_MISMATCH` `IT_QUOTE_MISMATCH`;黄:`IT_VERSION_GAP`。 + +**边界**:`IT_VERSION_GAP` 只说明**参考日**的版本没拿到,是黄不是红。 + +## 4. 两层证据:为什么不能只靠上游 + +``` +runs/-legal/ + official/.xml 权威层:官方条文 XML 原字节 —— 法条本体 + .card.txt 派生层:证据卡(元数据 + 法文数字归一 + 官方正文) + index.json 语料索引(官方标识、哈希、版本日期) +``` + +事实账指向**卡片**(上游的字面回查需要数字以阿拉伯数字出现),卡里声明 `OFFICIAL_XML_SHA256`, +法律闸**现算官方字节的哈希**再复核。 + +⇒ 上游钉住卡片没被改;法律闸钉住官方字节没被改。 +**实测两层不重叠:官方 XML 被改时,上游是绿的,法律闸是红的。** + +## 5. 三条工程纪律(都被实测教过) + +### 5.1 归属靠文件名后缀,不靠卡内标记 + +维度后缀 `.it.card.txt` / `.cn.card.txt` / `.case.card.txt` / 法国侧 `.card.txt`。 +若靠「卡内有没有某个字段」来判归属,则「卡被删 / 卡被篡改」会被**静默跳过** ⇒ 变成假绿 +(与「空集伪装成全绿」同源)。 + +### 5.2 3.10 的 TOML 兜底不能图省事复用上游的 + +上游 `factscribe/config.py` 自带 3.10 兜底解析器(`_mini_toml`)。实测它**不认嵌套数组**: +`nested = [["x"], ["y", "z"]]` 会被拆成 `[['x'], '["y"', '"z"']`。 +若直接复用,同一份事实账在 3.10 与 3.11 上会读出**不同结构** ⇒ 门禁结论不可复现。 + +所以本集成件自带一份兜底解析器,并配交叉校验测试:**对事实账用得到的子集, +它与标准库 `tomllib` 逐字相同**(`tests/test_toml_compat.py`)。 +另外留了一条测试锁住「上游在我们真正用到的子集上与 `tomllib` 一致」, +上游哪天改方言,这条会先响。 + +### 5.3 官方件的身份由官方元数据自证,不由文件名决定 + +证据卡必须同时带**官方稳定标识**(`LEGIARTI` / `ACT_URN` / `ACT_ELI`)、 +**官方标题与日期**、**官方正文**;文件名只放官方标识。 +曾发生过:把一份 AKN 命名成「劳动法典」,实际取回的是另一部法典(`codiceRedaz` 参数抄错, +而文件名是自己起的 ⇒ 错误被自洽地固化)。修法就是这条:**身份由官方元数据 + 内容自证。** + +另有一条日期纪律:**官方件里常有两套日期**(文本日期戳 = 最后一次修法日; +取件参数 `dataVigenza` = 参考日当天生效的版本)⇒ **判「版本时效」必须比后者**。 + +## 6. 自测 + +```bash +python3 -m unittest discover -s integrations/factscribe-legal/tests -v # 50 例 +``` + +三类回归: + +- **双向**:每条红码都有「必须触发」与「不该触发」两个用例(上游 CONTRIBUTING §5 的做法)。 +- **防假绿**:多级 source 路径曾整批被跳过(假绿);空集不许伪装成全绿。 +- **跨版本**:TOML 读取层在兜底解析器与标准库上必须读出同一份事实账; + 把 `tomllib` 从 import 里掐掉后,包仍须可用(3.10 的真实处境)。 + +## 7. 刻意没做的事 + +- **没做**判例自动下载:各法域的官方发布形态不一样(法国的 DILA 交数据文件, + 中国的裁判文书网交阅读界面且协议禁批量),所以本集成件只消费「已经钉好哈希的官方件」。 +- **没做**中文法律文书里的 NLP 抽取:那是另一个量级的问题,不该混进一个证据链闸里。 +- **没改**上游 `factscribe/` 的任何一行:包括码表、退出码、SPEC 文档。 diff --git a/integrations/factscribe-legal/README.md b/integrations/factscribe-legal/README.md new file mode 100644 index 0000000..1a6ec3c --- /dev/null +++ b/integrations/factscribe-legal/README.md @@ -0,0 +1,157 @@ +# factscribe-legal —— 给 paperkit 接上「法律」这一维(第三方集成) + +> 这是**第三方集成件**,不是 paperkit 的一部分。 +> 它不进 `factscribe/` 包,不改上游任何行为、退出码或违规码; +> 沿用 `integrations/minifactscribe/` 的先例。 + +## 它补的是哪一维 + +paperkit 判的是:**正文里的数字,能不能回到一份签过字、算过哈希的原始材料**。 + +它不判「这份材料是不是法条」「这条法条今天还有效」「这个数字是不是真的出自这条法条」。 +这三条正是法律写作里最容易翻车的地方: + +| 问题 | 怎么判 | 码 | +|---|---|---| +| 引用的法条是不是真的存在? | 红 | `LEGAL_PROV_UNKNOWN` | +| 引的是不是**旧版本**(法条已被修改)? | 红 | `LEGAL_PROV_NOT_IN_FORCE` | +| 引的是不是**还没生效**的未来版本? | 黄 | `LEGAL_PROV_SCHEDULED` | +| 引的是不是已废止版本? | 黄 | `LEGAL_PROV_REPEALED` | +| 官方材料有没有被人动过? | 红 | `LEGAL_PROV_HASH_MISMATCH` | +| 派生证据卡有没有被人动过? | 红 | `LEGAL_CARD_SHA256_MISMATCH` / `LEGAL_CARD_NO_HASH` | +| 事实里的数字**真的出自这条法条**吗? | 红 | `LEGAL_QUOTE_MISMATCH` | +| 语料版本和现行视图是不是同一个? | 黄 | `LEGAL_PROV_VIEW_MISMATCH` | +| 同一编号能不能定到唯一一条? | 黄 | `LEGAL_PROV_AMBIGUOUS` | +| 参考日当天的官方件没拿到? | 黄 | `LEGAL_COVERAGE_GAP` | + +后两条是关键:**法国法条被修改后老版本不会消失**,按条文编号引用会静默拿到旧文本; +而法国法条常把数字写成词(`trente-cinq heures`),不解析法文数字词就核不出出处。 + +### 法文数字也要算数 + +本集成把法文数字词解析成整数再比对(`trente-cinq → 35`、`quatre-vingt-dix → 90`、 +`soixante-douze → 72`),所以「引用 35 小时」能自动对上原文。 + +## 四个闸,四个法域 + +| 子命令 | 法域 | 官方件是什么 | 能判到哪一层 | +|---|---|---|---| +| `verify` | 法国(Code du travail) | LEGI 官方条文 XML | 数字真出自官方正文(含法文数字词) | +| `verify-cn` | 中国(国家法律法规数据库) | 官方详情 JSON 派生卡 | 法规现行有效、条文号存在、官方件未变 | +| `verify-case` | 中国(人民法院案例库入库案例) | 官方案例正文 + 回执链 | 案号/日期/金额与官方件一致 | +| `verify-it` | 意大利(Normattiva) | 官方 AKN XML + 条文切片 | 数值真出自官方 AKN 正文 | + +各闸的错误码(**红 = 必须修,黄 = 不是绿**): + +| 闸 | 红 | 黄 | +|---|---|---| +| `verify` | `LEGAL_PROV_UNKNOWN` `LEGAL_PROV_NOT_IN_FORCE` `LEGAL_PROV_HASH_MISMATCH` `LEGAL_CARD_SHA256_MISMATCH` `LEGAL_CARD_NO_HASH` `LEGAL_QUOTE_MISMATCH` | `LEGAL_PROV_SCHEDULED` `LEGAL_PROV_REPEALED` `LEGAL_PROV_VIEW_MISMATCH` `LEGAL_PROV_AMBIGUOUS` `LEGAL_COVERAGE_GAP` | +| `verify-cn` | `CN_PROV_UNKNOWN` `CN_PROV_NOT_IN_FORCE` `CN_ARTICLE_NOT_FOUND` `CN_CARD_MISSING` `CN_CARD_NO_HASH` `CN_CARD_SHA256_MISMATCH` `CN_OFFICIAL_HASH_MISMATCH` `CN_VALUE_MISMATCH` | — | +| `verify-case` | `CASE_OFFICIAL_MISSING` `CASE_CARD_MISSING` `CASE_OFFICIAL_HASH_MISMATCH` `CASE_NO_MISMATCH` `CASE_DATE_MISMATCH` `CASE_AMOUNT_MISMATCH` `CASE_VALUE_NOT_IN_OFFICIAL` `CASE_CARD_TEXT_DIVERGED` `CASE_CHAIN_BROKEN` | — | +| `verify-it` | `IT_PROV_UNKNOWN` `IT_CARD_MISSING` `IT_CARD_NO_HASH` `IT_CARD_SHA256_MISMATCH` `IT_SOURCE_HASH_MISMATCH` `IT_ARTICLE_HASH_MISMATCH` `IT_ARTICLE_NOT_IN_SOURCE` `IT_CARD_FIELD_MISMATCH` `IT_QUOTE_MISMATCH` | `IT_VERSION_GAP` | + +**各闸的判据边界(很重要,不要越界引用)**: + +- 中国侧官方件**不含条文正文** ⇒ `verify-cn` 能核「法规现行有效」「条文号存在」「官方件未变」, + **不能**核「数字出自正文」。这不是缺陷,是官方发布形态决定的。 +- 案例库存的是**要旨体例案例稿**,不是判决书原文 ⇒ `verify-case` 核的是「这份案例稿与官方件一致」。 +- `verify-it` 判的是「数值出自官方 AKN 条文」;`IT_VERSION_GAP` 只说明**参考日**的版本没拿到, + 是黄不是红。 + +## 两层证据 + +``` +runs/run-YYYYMMDD-legal/ + official/.xml 权威层:官方条文 XML 原字节 —— 法条本体 + .card.txt 派生层:证据卡(元数据 + 法文数字归一 + 官方正文) + index.json 语料索引(官方标识、哈希、版本日期) +``` + +事实账指向**卡片**(上游的字面回查需要数字以阿拉伯数字出现), +卡里声明 `OFFICIAL_XML_SHA256`,法律闸**现算官方字节的哈希**再复核。 + +⇒ 上游钉住卡片没被改;法律闸钉住官方字节没被改。**两层都不丢**, +而且两层的篡改会落在不同闸上(实测:官方 XML 被改,上游是绿的)。 + +证据卡的字段名一律大写、稳定、可机读: + +- 法国:`NUM` `LEGIARTI` `ETAT` `DATE_DEBUT` `DATE_FIN` `REFERENCE_DATE` + `OFFICIAL_XML` `OFFICIAL_XML_BYTES` `TEXT_CHARS` `NUMERIC_NORMALIZATION` +- 意大利:`ACT_URN` `ACT_ELI` `ACT_TITLE` `DATA_GU` `CODICE_REDAZIONALE` + `ARTICLE_EID` `ARTICLE_NUM` `VERSION_DATE` `FETCH_VIGENZA` `REFERENCE_DATE` + `SOURCE_FILE` `OFFICIAL_XML_SHA256` `ARTICLE_SHA256` `TEXT_SHA256` `LICENCE` `ATTRIBUTION` + +**归属靠文件名后缀判定**(`.it.card.txt` / `.cn.card.txt` / `.case.card.txt` / 法国侧的 `.card.txt`), +不靠卡内有没有某个标记字段 —— 靠标记猜会让「卡被删 / 卡被篡改」被静默跳过,变成假绿。 + +## 用法 + +```bash +# 1) 把要引用的法条物化进项目(官方 XML + 证据卡 + 哈希) +python3 -m factscribe_legal fetch \ + --corpus runs/run-20261114-legal \ + --project . \ + --nums L3121-27 L1225-1 L1242-2 + +# 2) 跑法律专项校验(参考日 = 讨论时点) +python3 -m factscribe_legal verify \ + --project . \ + --corpus runs/run-20261114-legal \ + --date 2026-11-14 \ + --view out/legifrance/view_20261114/merged_current.jsonl + +# 3) 中国法条 / 中国案例 / 意大利法条 +python3 -m factscribe_legal verify-cn --project . --catalog out/cn/catalog_full.jsonl.gz --date 2026-11-14 +python3 -m factscribe_legal verify-case --project . +python3 -m factscribe_legal verify-it --project . --corpus runs/run-20261115-it --date 2026-11-15 +``` + +退出码沿用上游:**0 绿 / 1 红 / 2 配置错 / 3 黄**。 + +## 与上游核心的关系 + +- 上游 `factscribe/` **一行未改**:行为、退出码、违规码、`packages = ["factscribe"]` 打包范围都不动。 +- 本包**不 import 上游 `factscribe`**(只 import 标准库)⇒ 可以单独拷走单跑,也可以放进上游仓里共存。 +- 事实账的字段用上游已有的那套(`id` / `claim` / `value` / `source` / `source_sha256` / + `locator` / `confidence` / `derived_from`),**不新增 schema**。 + +## 自测 + +```bash +python3 -m unittest discover -s integrations/factscribe-legal/tests -v +``` + +**50 条测试,全部离线**(不联网、不写仓库外的东西)。含三类回归: + +- **双向**:每条红码都有「必须触发」与「不该触发」两个用例(上游 §5 的做法)。 +- **防假绿**:多级 source 路径曾经整批被跳过 ⇒ 测它;空集不许伪装成全绿。 +- **跨版本可复现**:TOML 读取层在 3.10 兜底解析器与 3.11+ 标准库 `tomllib` 上 + 必须读出**同一份**事实账(见下)。 + +## 依赖 + +**Python ≥ 3.10,纯标准库,无网络调用,无 `eval`。** + +TOML 读取(`factscribe_legal/_toml.py`)有一处刻意设计:3.11+ 用标准库 `tomllib`, +3.10 用本包自带的极简解析器。**不直接复用上游 `factscribe.config.load_toml`** —— +实测上游那份 3.10 兜底解析器不认嵌套数组(`nested = [["x"], ["y", "z"]]` 会被拆成三个字符串), +若复用它,同一份事实账在 3.10 与 3.11 上会读出不同结构,门禁结论不可复现。 +本包的兜底解析器有交叉校验测试:对事实账用得到的子集,与标准库 `tomllib` **逐字相同**。 + +## 语料从哪来 + +各法域的官方件都取自官方**开放数据**通道(不是爬页面): + +| 法域 | 官方通道 | 形态 | 许可 | +|---|---|---|---| +| 法国 | DILA LEGI 增量包(`echanges.dila.gouv.fr/OPENDATA/LEGI/`) | 官方 XML | 开放许可(Etalab) | +| 中国 | 国家法律法规数据库(FLK)详情 JSON | 官方 JSON | 官方公开接口 | +| 中国案例 | 人民法院案例库入库案例正文 | 官方正文 + 回执 | 官方用户协议(个人查询、建库须走程序) | +| 意大利 | Normattiva OpenData API(`caricaAKN`) | 官方 AKN XML | CC BY 4.0 | + +取件、钉哈希、建卡、选版(`date_debut <= T < date_fin`)的脚本在各自的工程仓里, +本包只消费「已经钉好哈希的官方件」。 + +## 许可 + +MIT(与上游一致)。 diff --git a/integrations/factscribe-legal/factscribe_legal/__init__.py b/integrations/factscribe-legal/factscribe_legal/__init__.py new file mode 100644 index 0000000..c1aa690 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/__init__.py @@ -0,0 +1,19 @@ +""" +factscribe_legal —— 给 FactScribe 接上「法律」这一维度的第三方集成。 + +设计原则(沿用上游 integrations/minifactscribe 的先例): + * **不改上游任何代码**:独立包,独立目录,独立退出码契约; + * 上游管「数字绑定到事实」,本包管「事实的来源是法条、且这个数字真的出自那条法条」。 + +两层分工: + FactScribe 正文 \\fact{A1} ⇒ 该句数字必须落在 A1 的值域;source_sha256 现算比对 + factscribe_legal A1.source 指向法条 ⇒ 该法条必须在参考日生效,且其官方 XML 哈希未变, + 且 A1 的值确实出现在该法条的官方正文里(含法文数字词:trente-cinq → 35) + +用法见 CLI:factscribe-legal fetch / factscribe-legal verify +""" +__version__ = "0.1.0" + +from .provisions import Provision, load_corpus, fr_number_to_int # noqa: F401 + +__all__ = ["Provision", "load_corpus", "fr_number_to_int", "__version__"] diff --git a/integrations/factscribe-legal/factscribe_legal/__main__.py b/integrations/factscribe-legal/factscribe_legal/__main__.py new file mode 100644 index 0000000..6e42b4b --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/__main__.py @@ -0,0 +1,6 @@ +"""python3 -m factscribe_legal 入口。""" +import sys + +from .cli import main + +sys.exit(main()) diff --git a/integrations/factscribe-legal/factscribe_legal/_toml.py b/integrations/factscribe-legal/factscribe_legal/_toml.py new file mode 100644 index 0000000..4d60388 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/_toml.py @@ -0,0 +1,302 @@ +"""TOML 读取层:让本包在 Python 3.10 上也能跑,且不引入任何第三方依赖。 + +为什么需要这一层 +---------------- +上游 paperkit 的 CI 矩阵是 Python 3.10–3.14,而标准库 `tomllib` 是 3.11 才有的。 +本集成包若在模块顶层 `import tomllib`,在 3.10 上直接 ImportError —— 整个包装不上, +上游 CI 的 3.10 那一格会红。 + +解析器怎么选(一条环境只走一条路径,结论可复现) +-------------------------------------------------- +1. **Python 3.11+**:标准库 `tomllib`。 +2. **Python 3.10**:本文件自带的极简解析器 `mini_loads`。 +3. 环境变量 `FACTSCRIBE_LEGAL_TOML=mini` 可强制走极简解析器 —— + 用来在没有 3.10 解释器的机器上验证那条兜底路径(`tests/test_toml_compat.py` 这么用)。 + +**为什么不直接复用上游 `factscribe.config.load_toml`?** +实测过(2026-11-15):上游那份 3.10 兜底解析器(`factscribe/config.py::_mini_toml`) +不认嵌套数组 —— `nested = [["x"], ["y", "z"]]` 会被拆成 `[['x'], '["y"', '"z"']`。 +若直接复用它,则同一份事实账在 3.10 与 3.11 上会读出**不同的结构**, +门禁结论不可复现。本包因此自带一份极简解析器,并用交叉校验测试保证 +**它对事实账用得到的子集与标准库 `tomllib` 逐字相同**(见 tests/test_toml_compat.py)。 + +自带解析器的边界 +---------------- +只覆盖事实账用得到的子集:表、表数组、字符串、数组、数字、布尔。 +子集之外的写法(内联表、多行字符串、日期时间)**直接报错**,不猜、不静默跳过 +(沿用上游 "fail closed / no silent passes" 的规矩)。 +""" +import os +from pathlib import Path + +__all__ = ["load_toml", "mini_loads", "parser_name", "TomlSubsetError"] + + +class TomlSubsetError(ValueError): + """文件里有本解析器不覆盖的写法 —— fail closed,不猜。""" + + +_ESCAPES = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\", "b": "\b", "f": "\f"} + + +# -------------------------------------------------------------------------- +# 极简解析器(3.10 兜底 / 交叉校验用) +# -------------------------------------------------------------------------- + +def _strip_comment(line): + """去掉行尾注释;引号内的 # 不算注释。""" + out = [] + quote = None + i = 0 + while i < len(line): + ch = line[i] + if quote: + out.append(ch) + if ch == "\\" and quote == '"' and i + 1 < len(line): + out.append(line[i + 1]) + i += 2 + continue + if ch == quote: + quote = None + elif ch in "\"'": + quote = ch + out.append(ch) + elif ch == "#": + break + else: + out.append(ch) + i += 1 + if quote: + raise TomlSubsetError("引号未闭合:%r" % line) + return "".join(out) + + +def _parse_basic_string(s): + if len(s) < 2 or not s.endswith('"'): + raise TomlSubsetError("字符串未闭合:%r" % s) + body = s[1:-1] + out = [] + i = 0 + while i < len(body): + ch = body[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + i += 1 + if i >= len(body): + raise TomlSubsetError("转义未结束:%r" % s) + e = body[i] + if e in _ESCAPES: + out.append(_ESCAPES[e]) + i += 1 + elif e == "u": + hexs = body[i + 1:i + 5] + if len(hexs) != 4: + raise TomlSubsetError("坏的 \\u 转义:%r" % s) + try: + out.append(chr(int(hexs, 16))) + except ValueError: + raise TomlSubsetError("坏的 \\u 转义:%r" % s) + i += 5 + else: + raise TomlSubsetError("不认识的转义 \\%s:%r" % (e, s)) + return "".join(out) + + +def _parse_literal_string(s): + if len(s) < 2 or not s.endswith("'"): + raise TomlSubsetError("字符串未闭合:%r" % s) + return s[1:-1] + + +def _split_items(body): + """按顶层逗号切数组元素(引号内、嵌套括号内的逗号不算)。""" + items = [] + cur = [] + depth = 0 + quote = None + i = 0 + while i < len(body): + ch = body[i] + if quote: + cur.append(ch) + if ch == "\\" and quote == '"' and i + 1 < len(body): + cur.append(body[i + 1]) + i += 2 + continue + if ch == quote: + quote = None + i += 1 + continue + if ch in "\"'": + quote = ch + cur.append(ch) + elif ch == "[": + depth += 1 + cur.append(ch) + elif ch == "]": + depth -= 1 + cur.append(ch) + elif ch == "," and depth == 0: + items.append("".join(cur)) + cur = [] + else: + cur.append(ch) + i += 1 + if quote: + raise TomlSubsetError("引号未闭合") + tail = "".join(cur).strip() + if tail: + items.append(tail) + return items + + +def _parse_value(raw): + s = raw.strip() + if not s: + raise TomlSubsetError("空值") + if s.startswith('"'): + return _parse_basic_string(s) + if s.startswith("'"): + return _parse_literal_string(s) + if s.startswith("["): + if not s.endswith("]"): + raise TomlSubsetError("数组未闭合:%r" % raw) + body = s[1:-1].strip() + if not body: + return [] + return [_parse_value(it.strip()) for it in _split_items(body)] + if s.startswith("{"): + raise TomlSubsetError("不覆盖内联表:%r" % raw) + if s in ("true", "false"): + return s == "true" + try: + if any(c in s for c in ".eE"): + return float(s.replace("_", "")) + return int(s.replace("_", "")) + except ValueError: + raise TomlSubsetError("不认识的取值:%r" % raw) + + +def _unquote_key(k): + k = k.strip() + if len(k) >= 2 and k[0] == k[-1] and k[0] in "\"'": + return k[1:-1] + return k + + +def _split_dotted(path): + parts = [] + for p in path.split("."): + p = _unquote_key(p) + if not p: + raise TomlSubsetError("空表名:%r" % path) + parts.append(p) + return parts + + +def _table_for(root, path): + cur = root + for part in _split_dotted(path): + nxt = cur.get(part) + if nxt is None: + nxt = {} + cur[part] = nxt + elif isinstance(nxt, list): + # [[a.b]] 之后又出现 [a.b.c]:落到最后一个数组元素里 + nxt = nxt[-1] + elif not isinstance(nxt, dict): + raise TomlSubsetError("表名冲突:%r" % path) + cur = nxt + return cur + + +def mini_loads(text): + """极简 TOML 解析:只覆盖事实账用得到的子集。""" + root = {} + cur = root + lines = text.splitlines() + i = 0 + while i < len(lines): + raw = lines[i] + i += 1 + s = _strip_comment(raw).strip() + if not s: + continue + if s.startswith("[["): + if not s.endswith("]]"): + raise TomlSubsetError("表数组头未闭合:%r" % raw) + name = s[2:-2].strip() + parent, _, leaf = name.rpartition(".") + holder = _table_for(root, parent) if parent else root + leaf = _unquote_key(leaf) + arr = holder.setdefault(leaf, []) + if not isinstance(arr, list): + raise TomlSubsetError("[[%s]] 与同名表冲突" % name) + cur = {} + arr.append(cur) + continue + if s.startswith("["): + if not s.endswith("]"): + raise TomlSubsetError("表头未闭合:%r" % raw) + cur = _table_for(root, s[1:-1].strip()) + continue + if "=" not in s: + raise TomlSubsetError("无法解析的行:%r" % raw) + key, _, value = s.partition("=") + key = key.strip() + value = value.strip() + # 多行数组 + while value.startswith("[") and value.count("[") > value.count("]") and i < len(lines): + value += " " + _strip_comment(lines[i]).strip() + i += 1 + parsed = _parse_value(value) + if "." in key: + parent, _, leaf = key.rpartition(".") + _table_for(cur, parent)[_unquote_key(leaf)] = parsed + else: + cur[_unquote_key(key)] = parsed + return root + + +# -------------------------------------------------------------------------- +# 分发 +# -------------------------------------------------------------------------- + +def _read_text(path): + try: + raw = Path(path).read_bytes() + except OSError as exc: + raise TomlSubsetError("读不了 %s:%s" % (path, exc)) + try: + return raw.decode("utf-8") + except UnicodeDecodeError as exc: + raise TomlSubsetError("%s 不是合法 UTF-8:%s" % (path, exc)) + + +def _resolve(): + forced = os.environ.get("FACTSCRIBE_LEGAL_TOML", "").strip().lower() + if forced == "mini": + return "mini", None + try: + import tomllib + except ModuleNotFoundError: + return "mini", None + return "tomllib", tomllib + + +def parser_name(): + """当前实际用的解析器(写进报告/日志,便于复现时确认口径)。""" + return _resolve()[0] + + +def load_toml(path): + """读一个 TOML 文件,返回 dict。""" + name, fn = _resolve() + if name == "upstream": + return fn(Path(path)) + text = _read_text(path) + if name == "tomllib": + return fn.loads(text) + return mini_loads(text) diff --git a/integrations/factscribe-legal/factscribe_legal/case_verify.py b/integrations/factscribe-legal/factscribe_legal/case_verify.py new file mode 100644 index 0000000..d4fe72f --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/case_verify.py @@ -0,0 +1,219 @@ +"""中国**案例**维度专项校验:把「引的是哪条官方案例、官方正文有没有被动过、那个赔偿金额是不是真出自官方正文」变成机械判定。 + +与法条两个维度的判据差异(因为官方材料形态不同): + 法条维度(法国):官方件 = 条文 XML ⇒ 可判「数字出自该条正文」 + 法条维度(中国):官方件 = 详情 JSON(只有目录树,无正文)⇒ 只能判「第X条在目录树里」 + **案例维度(中国):官方件 = 官方入库案例的正文全文** ⇒ 又能判「数字出自官方正文」 + +判据清单: + CASE_CARD_MISSING 事实账指向的案例证据卡不存在 + CASE_OFFICIAL_MISSING 官方正文副本不存在 + CASE_OFFICIAL_HASH_MISMATCH 官方正文副本的哈希 ≠ 卡片里声明的哈希(官方件被改) + CASE_VALUE_NOT_IN_OFFICIAL 事实里的金额/案号/日期在官方正文里找不到(字面) + CASE_NO_MISMATCH 卡片里的案号与官方正文里出现的案号对不上 + CASE_DATE_MISMATCH 卡片里的裁判日期与官方正文里的日期对不上 + CASE_CHAIN_BROKEN FactScribe v3 证据链断了(fact.source → runs//result.json → record.json) + +退出码沿用上游:0 绿 / 1 红 / 2 配置错 / 3 黄 +""" +import hashlib +import json +import os +import re + +from .verify import Finding, load_facts + +CASE_CARD_RE = re.compile(r"^runs/(?P[^/]+)/(?P.+)\.case\.card\.txt$") +NUM_RE = re.compile(r"^\d[\d,]*(\.\d+)?$") +# ⚠️ 必须覆盖事实值的实际写法:案例库元数据给的是 "2023.10.20"(点分隔), +# 若只认 YYYY-MM-DD,值会**静默落到字符串分支**按字面比 → 误报「找不到」。 +DATE_RE = re.compile(r"^\d{4}[-./]\d{1,2}[-./]\d{1,2}$") + + +def _sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _card_fields(path): + out = {} + with open(path, encoding="utf-8") as f: + for line in f: + if ":" in line and not line.startswith("#") and not line.startswith("---"): + k, v = line.split(":", 1) + out[k.strip()] = v.strip() + return out + + +def _norm_num(v): + return v.replace(",", "") + + +CN_DATE_RE = re.compile(r"(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日") + + +def _dates_in(text): + """把正文里的中文日期归一化成 YYYY-MM-DD 集合(卡片用 2023.10.20,正文写 2023年10月20日)""" + out = set() + for y, m, d in CN_DATE_RE.findall(text): + out.add(f"{int(y):04d}-{int(m):02d}-{int(d):02d}") + out.add(f"{int(y):04d}.{int(m):02d}.{int(d):02d}") + return out + + +def _date_present(value, official, dates): + if value in official: + return True + try: + y, m, d = re.split(r"[.\-/]", value) + norm = f"{int(y):04d}-{int(m):02d}-{int(d):02d}" + except Exception: # noqa: BLE001 + return False + return norm in dates + + +def verify_case(project_dir): + findings = [] + run_ids = set() + checked_cards = set() # 卡片级检查每张卡只做一次 + + for fact in load_facts(project_dir): + src = fact.get("source", "") + m = CASE_CARD_RE.match(src) + if not m: + continue + loc = f"{fact['_file']}:{fact.get('id', '?')}" + run = m.group("run") + slug = m.group("slug") + run_ids.add(run) + card_path = os.path.join(project_dir, src) + if not os.path.exists(card_path): + findings.append(Finding("CASE_CARD_MISSING", "red", loc, f"案例证据卡不存在:{src}")) + continue + fields = _card_fields(card_path) + if "OFFICIAL_TEXT_SHA256" not in fields: + continue # 不是案例卡 + + # ---- 官方正文副本:现算哈希,与卡片声明比对 ---- + off_path = os.path.join(project_dir, "runs", run, "official", f"{slug}.txt") + if not os.path.exists(off_path): + findings.append(Finding("CASE_OFFICIAL_MISSING", "red", loc, + f"官方正文副本不存在:runs/{run}/official/{slug}.txt")) + continue + actual = _sha256_file(off_path) + if actual != fields.get("OFFICIAL_TEXT_SHA256"): + findings.append(Finding("CASE_OFFICIAL_HASH_MISMATCH", "red", loc, + f"官方正文哈希与卡片声明不符:声明 {fields['OFFICIAL_TEXT_SHA256'][:16]}… " + f"实算 {actual[:16]}…(官方件被改)")) + continue + with open(off_path, encoding="utf-8") as f: + official = f.read() + dates = _dates_in(official) + + # ---- 事实的值必须真的在官方正文里(字面) ---- + val = str(fact.get("value", "")) + if NUM_RE.match(val): + if _norm_num(val) not in official.replace(",", ""): + findings.append(Finding("CASE_VALUE_NOT_IN_OFFICIAL", "red", loc, + f"金额 {val} 在官方正文里找不到")) + elif DATE_RE.match(val): + if not _date_present(val, official, dates): + findings.append(Finding("CASE_VALUE_NOT_IN_OFFICIAL", "red", loc, + f"日期 {val} 在官方正文里找不到")) + else: + if val and val not in official: + findings.append(Finding("CASE_VALUE_NOT_IN_OFFICIAL", "red", loc, + f"值 {val[:30]} 在官方正文里找不到")) + + # ---- 卡片级检查:每张卡只做一次(在 fact 循环里做会重复 N 遍)---- + card_key = (run, slug) + if card_key in checked_cards: + continue + checked_cards.add(card_key) + + # A. 卡片声明的每个金额必须能在官方正文里找到 + # (否则「改卡片 + 同步改账里的 source_sha256」只会被上游判**黄**,两层都不红) + amounts = [x.strip() for x in fields.get("AMOUNTS", "").split(",") if x.strip()] + for a in amounts: + if _norm_num(a) not in official.replace(",", ""): + findings.append(Finding("CASE_AMOUNT_MISMATCH", "red", loc, + f"卡片声明的金额 {a} 在官方正文里找不到" + "(卡片与官方件已脱钩)")) + # B. 卡片内嵌的正文段必须与 official/*.txt 逐字节相同 + marker = "--- OFFICIAL TEXT ---\n" + with open(card_path, encoding="utf-8") as fh: + card_text = fh.read() + if marker in card_text: + embedded = card_text.split(marker, 1)[1] + if embedded.rstrip("\n") != official.rstrip("\n"): + findings.append(Finding("CASE_CARD_TEXT_DIVERGED", "red", loc, + "卡片内嵌的正文与 official/*.txt 不一致" + "(卡片的正文副本被改过)")) + else: + findings.append(Finding("CASE_CARD_TEXT_DIVERGED", "red", loc, + "卡片里找不到 --- OFFICIAL TEXT --- 段")) + + # C. 案号一致性:卡片声明的案号必须在官方正文里出现 + case_no = fields.get("CASE_NO", "") + if case_no and case_no not in official: + findings.append(Finding("CASE_NO_MISMATCH", "red", loc, + f"卡片案号 {case_no} 在官方正文里不存在")) + jd = fields.get("JUDGE_DATE", "") + if jd and not _date_present(jd, official, dates): + findings.append(Finding("CASE_DATE_MISMATCH", "red", loc, + f"裁判日期 {jd} 在官方正文里不存在")) + + # ---- FactScribe v3 证据链:fact.source → runs//result.json → record.json ---- + for run in sorted(run_ids): + rdir = os.path.join(project_dir, "runs", run) + rj = os.path.join(rdir, "result.json") + cj = os.path.join(rdir, "record.json") + if not os.path.exists(rj) or not os.path.exists(cj): + findings.append(Finding("CASE_CHAIN_BROKEN", "red", f"runs/{run}", + "缺少 result.json 或 record.json(证据链断)")) + continue + try: + with open(rj, encoding="utf-8") as fh: + result = json.load(fh) + with open(cj, encoding="utf-8") as fh: + record = json.load(fh) + except Exception as e: # noqa: BLE001 + findings.append(Finding("CASE_CHAIN_BROKEN", "red", f"runs/{run}", f"回执读不了:{e}")) + continue + if result.get("run_id") != run or record.get("run_id") != run: + findings.append(Finding("CASE_CHAIN_BROKEN", "red", f"runs/{run}", + "run_id 对不上")) + continue + # 上游 FactScribe 的 record.json 里 facts[] 是**字符串数组** + rids = {str(x) for x in (record.get("facts") or [])} + for fact in load_facts(project_dir): + src = fact.get("source", "") + m = CASE_CARD_RE.match(src) + if not m or m.group("run") != run: + continue + fid = fact.get("id") + if fid not in rids: + findings.append(Finding("CASE_CHAIN_BROKEN", "red", + f"{fact['_file']}:{fid}", + f"record.json 的 facts[] 里没有 {fid}")) + + return findings + + +def render_case(findings): + red = [f for f in findings if f.severity == "red"] + yellow = [f for f in findings if f.severity == "yellow"] + lines = ["【第 5 层 · 中国案例维度】"] + if not findings: + lines.append(" ✓ 绿:案例官方正文哈希、金额、案号、日期、证据链全部一致") + for f in findings: + mark = "🔴" if f.severity == "red" else ("🟡" if f.severity == "yellow" else "🟢") + lines.append(f" {mark} [{f.code}] {f.location}") + lines.append(f" {f.message}") + lines.append(f" —— 红 {len(red)} / 黄 {len(yellow)}") + code = 1 if red else (3 if yellow else 0) + lines.append(f" 退出码 {code}") + return "\n".join(lines), code diff --git a/integrations/factscribe-legal/factscribe_legal/cli.py b/integrations/factscribe-legal/factscribe_legal/cli.py new file mode 100644 index 0000000..e312361 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/cli.py @@ -0,0 +1,124 @@ +"""factscribe-legal 命令行入口。 + + factscribe-legal fetch --corpus --project --nums L3121-27 ... + 把语料里的法条**物化**进 FactScribe 项目(连同可钉的哈希),并给出一段 + 可直接粘进事实账的 [[fact]] 片段。 + + factscribe-legal verify --project --corpus --date YYYY-MM-DD + 跑法律专项校验:法条存在?哈希未变?参考日生效?引用的数字真出自该法条? +""" +import argparse +import os +import sys + +from .provisions import load_corpus +from .verify import render, verify + + +def cmd_fetch(args): + """列出语料里这些法条的状态与可钉的哈希,并给出事实账片段。 + + 事实的 source 指向**证据卡**(派生层),卡里声明官方 XML 的哈希; + 权威层(官方字节)的哈希由本集成现算复核。 + """ + import hashlib + import os + corpus = load_corpus(args.corpus) + print(f"语料:{len(corpus)} 条({args.corpus})") + for num in args.nums: + prov = corpus.get(num) + if prov is None: + print(f" ! {num} 不在语料里") + continue + card = os.path.join(args.corpus, f"{num}.card.txt") + card_sha = "" + if os.path.isfile(card): + with open(card, "rb") as fh: + card_sha = hashlib.sha256(fh.read()).hexdigest() + print(f" ✓ {num} {prov.legiarti} {prov.etat} {prov.date_debut}→{prov.date_fin}") + print(f" 官方 XML {prov.xml_file} sha256 {prov.xml_sha256}") + if card_sha: + run = os.path.basename(args.corpus) + print(f' 事实账片段: source = "runs/{run}/{num}.card.txt"' + f' source_sha256 = "sha256:{card_sha}"') + + +def cmd_verify(args): + findings, corpus = verify(args.project, args.corpus, args.date, args.view) + text, code = render(findings, corpus) + print(text) + return code + + +def cmd_verify_cn(args): + from .cn_verify import render_cn, verify_cn + findings = verify_cn(args.project, args.catalog, args.date) + text, code = render_cn(findings) + print(text) + return code + + +def cmd_verify_case(args): + from .case_verify import render_case, verify_case + findings = verify_case(args.project) + text, code = render_case(findings) + print(text) + return code + + +def cmd_verify_it(args): + from .it_verify import render_it, verify_it + findings, index = verify_it(args.project, args.corpus, args.date) + text, code = render_it(findings, index) + print(text) + return code + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="factscribe-legal", + description="给 FactScribe 接上法律维度") + sub = ap.add_subparsers(dest="cmd", required=True) + + f = sub.add_parser("fetch", help="把法条物化进项目并给出事实账片段") + f.add_argument("--corpus", required=True, help="语料目录(provisions/)") + f.add_argument("--project", required=True) + f.add_argument("--nums", nargs="+", required=True) + f.set_defaults(func=cmd_fetch) + + v = sub.add_parser("verify", help="法律专项校验") + v.add_argument("--project", required=True) + v.add_argument("--corpus", required=True) + v.add_argument("--date", required=True, help="参考日 YYYY-MM-DD") + v.add_argument("--view", default="", help="可选:管线的现行版 JSONL,用于交叉验证") + v.set_defaults(func=cmd_verify) + + c = sub.add_parser("verify-cn", help="中国侧法律专项校验(国家法律法规数据库全库)") + c.add_argument("--project", required=True) + c.add_argument("--catalog", required=True, help="catalog.jsonl.gz(FLK 全库)") + c.add_argument("--date", required=True, help="参考日 YYYY-MM-DD") + c.set_defaults(func=cmd_verify_cn) + + k = sub.add_parser("verify-case", help="中国案例维度专项校验(官方入库案例正文)") + k.add_argument("--project", required=True) + k.set_defaults(func=cmd_verify_case) + + i = sub.add_parser("verify-it", help="意大利法条专项校验(Normattiva 官方 AKN)") + i.add_argument("--project", required=True) + i.add_argument("--corpus", required=True, help="语料目录(runs/-it/)") + i.add_argument("--date", required=True, help="参考日 YYYY-MM-DD") + i.set_defaults(func=cmd_verify_it) + + args = ap.parse_args(argv) + if args.cmd == "fetch": + return cmd_fetch(args) + if args.cmd == "verify-cn": + return cmd_verify_cn(args) + if args.cmd == "verify-case": + return cmd_verify_case(args) + if args.cmd == "verify-it": + return cmd_verify_it(args) + return cmd_verify(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/integrations/factscribe-legal/factscribe_legal/cn_corpus.py b/integrations/factscribe-legal/factscribe_legal/cn_corpus.py new file mode 100644 index 0000000..b43d238 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/cn_corpus.py @@ -0,0 +1,82 @@ +"""中文侧语料:国家法律法规数据库(flk.npc.gov.cn)全库 → 可钉哈希的本地目录。 + +与法国侧的结构差异(决定了判据不同): + 法国:条文有 `date_debut/date_fin` **区间**,官方 XML **含正文** + 中国:法规给 `sxx` **当前状态标志** + `gbrq/sxrq` 两个日期;详情 JSON 给**章→条目录树**,**不含条文正文** + +⇒ 中国侧可核的是: + ① 该法规在参考日是否现行有效(sxx) + ② 引用的**条文号是否真的存在于该法规的目录树里**(中国版的"出处核验") + ③ 官方详情字节的哈希是否未变 +""" +import gzip +import hashlib +import json +import os +import re + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _canon(obj): + return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def load_catalog(catalog_path): + """读 catalog.jsonl.gz → {bbbs: record}""" + out = {} + if not os.path.exists(catalog_path): + return out + with gzip.open(catalog_path, "rt", encoding="utf-8") as f: + for line in f: + r = json.loads(line) + out[r["bbbs"]] = r + return out + + +def index_records(catalog): + """按标题建索引(同名多版本时取现行有效的那一版,其次取最新公布日)。""" + by_title = {} + for bb, r in catalog.items(): + t = (r.get("title") or "").strip() + if not t: + continue + cur = by_title.get(t) + if cur is None or _prefer(r, cur): + by_title[t] = r + return by_title + + +def _prefer(a, b): + """a 是否比 b 更该作为代表:现行有效 > 已修改 > 其它;同则比较公布日。""" + order = {3: 3, 2: 2, 4: 1, 1: 0} + sa = order.get(a.get("sxx"), 0) + sb = order.get(b.get("sxx"), 0) + if sa != sb: + return sa > sb + return (a.get("gbrq") or "") > (b.get("gbrq") or "") + + +ART_RE = re.compile(r"^(第[一二三四五六七八九十百千零〇两]+条)") + + +def article_key(title): + """从目录树节点标题里取「第X条」;取不到返回 None。""" + t = (title or "").strip() + m = ART_RE.match(t) + return m.group(1) if m else None + + +def find_article(record, art_title): + """在法规的目录树里找某条;返回 (命中?, 条标题)""" + arts = record.get("articles") or [] + for a in arts: + if a.strip() == art_title.strip(): + return True, a + return False, None diff --git a/integrations/factscribe-legal/factscribe_legal/cn_verify.py b/integrations/factscribe-legal/factscribe_legal/cn_verify.py new file mode 100644 index 0000000..911095d --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/cn_verify.py @@ -0,0 +1,173 @@ +"""中国侧法律专项校验:把「引用的是哪部法规、哪一条、它现在有效吗、官方件有没有被动过」变成机械判定。 + +与法国侧的判据差异(因为官方材料形态不同): + 法国官方件 = 条文 XML(含正文 + 生效区间) ⇒ 可判「数字出自正文」「参考日唯一生效版本」 + 中国官方件 = 详情 JSON(目录树 + 元数据,**无正文**)⇒ 可判: + · 法规在参考日是否现行有效(sxx) + · 引用的「第X条」是否真的在该法规目录树里 + · 官方详情字节的哈希是否未变 + · 事实里的数字(条数/日期)是否与官方详情一致 + +退出码沿用上游:0 绿 / 1 红 / 2 配置错 / 3 黄 +""" +import hashlib +import os +import re + +from .cn_corpus import article_key, find_article, index_records, load_catalog +from .verify import Finding, load_citations, load_facts + +CARD_RE = re.compile(r"^(?P.+)/(?P[^/]+)\.cn\.card\.txt$") +ART_IN_TEXT = re.compile(r"第[一二三四五六七八九十百千零〇两]+条") + + +def _sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _card_fields(path): + out = {} + with open(path, encoding="utf-8") as f: + for line in f: + if ":" in line and not line.startswith("#") and not line.startswith("ARTICLE"): + k, v = line.split(":", 1) + out[k.strip()] = v.strip() + return out + + +def verify_cn(project_dir, catalog_path, reference_date): + findings = [] + catalog = load_catalog(catalog_path) + by_title = index_records(catalog) + cards = {} # slug → (path, fields, record) + + # ---- 事实账里指向中文证据卡的 fact ---- + for fact in load_facts(project_dir): + src = fact.get("source", "") + m = CARD_RE.match(src) + if not m: + continue + loc = f"{fact['_file']}:{fact.get('id', '?')}" + path = os.path.join(project_dir, src) + if not os.path.exists(path): + findings.append(Finding("CN_CARD_MISSING", "red", loc, f"证据卡不存在:{src}")) + continue + f = _card_fields(path) + if "BBBS" not in f or "OFFICIAL_DETAIL_SHA256" not in f: + # 不是中国证据卡(法国侧卡片同名不同后缀,这里双保险) + continue + title = f.get("TITLE", "") + rec = by_title.get(title) + if rec is None: + findings.append(Finding("CN_PROV_UNKNOWN", "red", loc, + f"全库里找不到《{title}》")) + continue + cards[m.group("slug")] = (path, f, rec) + + # ① 官方详情哈希:卡内声明 vs 全库现算 + declared = (f.get("OFFICIAL_DETAIL_SHA256") or "").lower() + actual = (rec.get("detail_sha256") or "").lower() + if not declared: + findings.append(Finding("CN_CARD_NO_HASH", "red", loc, + "证据卡里没有 OFFICIAL_DETAIL_SHA256 声明")) + elif declared != actual: + findings.append(Finding("CN_OFFICIAL_HASH_MISMATCH", "red", loc, + f"《{title}》官方详情哈希与证据卡声明不符" + f"(卡 {declared[:12]}… / 全库现算 {actual[:12]}…)——官方件被改过")) + + # ② 证据卡自身未被改(事实钉的哈希 vs 现算) + pinned = (fact.get("source_sha256") or "").removeprefix("sha256:").lower() + if pinned and pinned != _sha256_file(path): + findings.append(Finding("CN_CARD_SHA256_MISMATCH", "red", loc, + f"证据卡 {src} 自身被改过(事实钉的哈希与现算不符)")) + + # ③ 时效性:参考日当天是否现行有效 + sxx = rec.get("sxx") + if sxx != 3: + findings.append(Finding("CN_PROV_NOT_IN_FORCE", "red", loc, + f"《{title}》在参考日不是现行有效(sxx={sxx};" + f"1废止/2修改/3有效/4未生效)")) + + # ④ 事实的值必须与官方详情一致 + val = str(fact.get("value", "")).strip() + fid = str(fact.get("id", "")) + if fid.endswith("-N"): + if val != str(rec.get("n_articles")): + findings.append(Finding("CN_VALUE_MISMATCH", "red", loc, + f"条文条数与官方详情不符(账 {val} / 官方 {rec.get('n_articles')})")) + elif fid.endswith("-GBRQ"): + if val != (rec.get("gbrq") or ""): + findings.append(Finding("CN_VALUE_MISMATCH", "red", loc, + f"公布日期与官方详情不符(账 {val} / 官方 {rec.get('gbrq')})")) + elif fid.endswith("-SXRQ"): + if val != (rec.get("sxrq") or ""): + findings.append(Finding("CN_VALUE_MISMATCH", "red", loc, + f"施行日期与官方详情不符(账 {val} / 官方 {rec.get('sxrq')})")) + + # ---- 正文里的中文法规引用 ---- + for key, rel, line in load_citations(project_dir): + if not key.startswith("art-") or not re.search(r"[一-鿿]", key): + continue + title = key[4:] + rec = by_title.get(title) + loc = f"{rel}:{line}" + if rec is None: + findings.append(Finding("CN_PROV_UNKNOWN", "red", loc, + f"引用了全库里没有的法规《{title}》")) + continue + if rec.get("sxx") != 3: + findings.append(Finding("CN_PROV_NOT_IN_FORCE", "red", loc, + f"引用的《{title}》不是现行有效(sxx={rec.get('sxx')})")) + # 同一句里出现的「第X条」必须在该法规目录树里 + for art in set(ART_IN_TEXT.findall(_line_text(project_dir, rel, line))): + ok, _ = find_article(rec, art) + if not ok: + findings.append(Finding("CN_ARTICLE_NOT_FOUND", "red", loc, + f"《{title}》的目录树里没有「{art}」——引了不存在的条")) + + return findings + + +def _line_text(project_dir, rel, line): + path = os.path.join(project_dir, rel) + try: + with open(path, encoding="utf-8") as f: + for i, text in enumerate(f, 1): + if i == line: + return text + except OSError: + return "" + return "" + + +def render_cn(findings): + reds = [f for f in findings if f.severity == "red"] + yellows = [f for f in findings if f.severity == "yellow"] + lines = ["== factscribe-legal verify-cn =="] + if reds: + lines.append(f"[红] {len(reds)} 处(必须修)") + for i, f in enumerate(reds, 1): + lines.append(f" {i}. {f.code:28s} {f.location} → {f.message}") + else: + lines.append("[红] 0 处") + lines.append("") + if yellows: + lines.append(f"[黄] {len(yellows)} 处") + for i, f in enumerate(yellows, 1): + lines.append(f" {i}. {f.code:28s} {f.location} → {f.message}") + else: + lines.append("[黄] 0 处") + lines.append("") + if reds: + lines.append(f"结论:{len(reds)} 红 → 红(退出码 1)") + elif yellows: + lines.append(f"结论:0 红 / {len(yellows)} 黄 → 黄(退出码 3)") + else: + lines.append("结论:0 红 / 0 黄 → 绿(退出码 0)") + lines.append("注意:中国侧官方件不含条文正文 ⇒ 可核的是「法规现行有效」「条文号存在」「官方件未变」," + "不是「数字出自正文」。") + return "\n".join(lines), (1 if reds else (3 if yellows else 0)) diff --git a/integrations/factscribe-legal/factscribe_legal/facts_ledger.py b/integrations/factscribe-legal/factscribe_legal/facts_ledger.py new file mode 100644 index 0000000..8fd6199 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/facts_ledger.py @@ -0,0 +1,76 @@ +"""事实账维护工具:同值检测与 dup_ok 标注。 + +上游 FactScribe 的 R-04 规则:**同一个值挂在不同 claim 上**时会报 `DUPLICATE_VALUE`(黄), +确属同一个数(例如:法国侧参考日与中国侧参考日是同一天;某法公布日与施行日同为一天) +要显式写 `dup_ok = true` 承认同值。 + +本模块在写完事实账后扫一遍项目内所有 facts/*.toml, +给"同值且 claim 不同"的事实自动补 `dup_ok = true`(幂等)。 +""" +import os +import re + +FACT_BLOCK = re.compile(r"\[\[fact\]\]\n(.*?)(?=\n\[\[fact\]\]|\Z)", re.S) + + +def _fields(block): + out = {} + for m in re.finditer(r'^(\w+)\s*=\s*"(.*)"\s*$', block, re.M): + out[m.group(1)] = m.group(2) + return out + + +def scan_dupes(project_dir): + """返回 [(文件, id, value)]:同值且 claim 不同的事实。""" + facts_dir = os.path.join(project_dir, "facts") + by_value = {} + allfacts = [] + if not os.path.isdir(facts_dir): + return [] + for fn in sorted(os.listdir(facts_dir)): + if not fn.endswith(".toml"): + continue + path = os.path.join(facts_dir, fn) + with open(path, encoding="utf-8") as f: + text = f.read() + for m in FACT_BLOCK.finditer(text): + fl = _fields(m.group(1)) + if "id" in fl and "value" in fl: + rec = {"file": path, "id": fl["id"], "value": fl["value"], + "claim": fl.get("claim", ""), "block": m.group(1)} + allfacts.append(rec) + by_value.setdefault(fl["value"], []).append(rec) + dupes = [] + for val, group in by_value.items(): + if len(group) > 1 and len({g["claim"] for g in group}) > 1: + for g in group: + dupes.append((g["file"], g["id"], val)) + return dupes, allfacts + + +def mark_dup_ok(project_dir): + """给同值且 claim 不同的事实补 dup_ok = true(幂等)。返回被标注的 id 列表。""" + dupes, allfacts = scan_dupes(project_dir) + if not dupes: + return [] + ids = {d[1] for d in dupes} + by_file = {} + for path, fid, _v in dupes: + by_file.setdefault(path, set()).add(fid) + changed = [] + for path, want in by_file.items(): + with open(path, encoding="utf-8") as f: + text = f.read() + + def fix(m): + block = m.group(1) + fl = _fields(block) + if fl.get("id") in want and "dup_ok" not in block: + block = block.rstrip("\n") + "\ndup_ok = true\n" + changed.append(fl["id"]) + return "[[fact]]\n" + block + + new = FACT_BLOCK.sub(fix, text) + with open(path, "w", encoding="utf-8") as f: + f.write(new) + return changed diff --git a/integrations/factscribe-legal/factscribe_legal/it_verify.py b/integrations/factscribe-legal/factscribe_legal/it_verify.py new file mode 100644 index 0000000..2da788f --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/it_verify.py @@ -0,0 +1,231 @@ +"""意大利法条专项校验:把「事实的来源是意大利官方法条」变成机械判定。 + +上游 FactScribe 判的是:正文数字 → 事实账 → 材料哈希。 +本模块判的是**意大利法条这一层**(与法国闸、中国闸互不越界): + + 红 + IT_PROV_UNKNOWN 引用/来源的条文不在语料索引里 + IT_ARTICLE_NOT_IN_SOURCE 官方整件里已经找不到这个条文(切片与官方件脱钩) + IT_ARTICLE_HASH_MISMATCH 条文切片的哈希与索引/证据卡声明不符(条文被人动过) + IT_SOURCE_HASH_MISMATCH 官方整件的哈希与索引/证据卡声明不符(整件被人动过) + IT_CARD_NO_HASH 证据卡里缺必要的哈希声明 + IT_CARD_SHA256_MISMATCH 证据卡自身被改过(事实账钉的哈希与现算不符) + IT_CARD_FIELD_MISMATCH 证据卡声明的法件/条文/版本与索引对不上 + IT_QUOTE_MISMATCH 事实里的数值不真的出现在该条官方正文里 + 黄 + IT_VERSION_GAP 钉住的是另一个日期的时点版本,与本次参考日不一致 + +退出码沿用上游:0 绿 / 1 红 / 2 配置错 / 3 黄 +""" +import hashlib +import json +import os +import re + +from .verify import Finding, load_citations, load_facts + +CARD_MARK = re.compile(r"^ARTICLE_EID:\s*(.+)$", re.M) +CITE_RE = re.compile(r"^art-it-(art_\d+)$") +ART_RE = re.compile(rb'
') + + +def _sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _sha256_bytes(b): + return hashlib.sha256(b).hexdigest() + + +def _plain_text(xml_text): + s = re.sub(r"<[^>]+>", " ", xml_text) + s = s.replace("&", "&").replace(" ", " ") + return re.sub(r"\s+", " ", s).strip() + + +def _is_it_card(path): + """意大利证据卡的后缀是 .it.card.txt(与 .cn.card.txt / .case.card.txt 同级区分)。""" + return path.endswith(".it.card.txt") + + +def verify_it(project_dir, corpus_dir, reference_date): + findings = [] + idx_path = os.path.join(corpus_dir, "index.json") + if not os.path.exists(idx_path): + raise FileNotFoundError(f"找不到 {idx_path}") + with open(idx_path, encoding="utf-8") as fh: + index = json.load(fh) + articles = index.get("articles") or {} + official_rel = index.get("source_file") or "" + official_path = os.path.join(corpus_dir, official_rel) + official_sha = "" + official_raw = b"" + if os.path.exists(official_path): + with open(official_path, "rb") as fh: + official_raw = fh.read() + official_sha = _sha256_bytes(official_raw) + if official_sha != index.get("source_sha256"): + findings.append(Finding( + "IT_SOURCE_HASH_MISMATCH", "red", "corpus", + f"官方整件 {official_rel} 的哈希与索引不符" + f"(索引 {str(index.get('source_sha256'))[:12]}… / 现算 {official_sha[:12]}…)" + "——官方件被人动过")) + else: + findings.append(Finding("IT_SOURCE_HASH_MISMATCH", "red", "corpus", + f"官方整件 {official_rel} 不在语料目录里")) + # 官方整件里现存的条文(用于回查切片是否还属于官方件) + live_eids = {m.group(1).decode() for m in ART_RE.finditer(official_raw)} + + # ---- 1. 事实账里指向意大利证据卡的 fact ---- + for fact in load_facts(project_dir): + src = fact.get("source", "") + if not src.endswith(".it.card.txt"): + continue # 法国/中国/案例的卡,各归各闸 + card_path = os.path.join(project_dir, src) + loc = f"{fact['_file']}:{fact.get('id', '?')}" + if not os.path.exists(card_path): + findings.append(Finding("IT_CARD_MISSING", "red", loc, + f"意大利证据卡不存在:{src}")) + continue + with open(card_path, encoding="utf-8") as fh: + card = fh.read() + m_eid = CARD_MARK.search(card) + if not m_eid: + findings.append(Finding("IT_CARD_NO_HASH", "red", loc, + f"证据卡 {src} 里没有 ARTICLE_EID 声明")) + continue + eid = m_eid.group(1).strip() + meta = articles.get(eid) + if meta is None: + findings.append(Finding("IT_PROV_UNKNOWN", "red", loc, + f"条文 {eid} 不在语料索引里({corpus_dir})")) + continue + # 哈希声明 + decl = dict(re.findall(r"^(ARTICLE_SHA256|OFFICIAL_XML_SHA256|SOURCE_FILE|ACT_URN|VERSION_DATE):\s*(.*)$", + card, re.M)) + if not decl.get("ARTICLE_SHA256") or not decl.get("OFFICIAL_XML_SHA256"): + findings.append(Finding("IT_CARD_NO_HASH", "red", loc, + f"证据卡 {src} 里缺 ARTICLE_SHA256 / OFFICIAL_XML_SHA256 声明")) + continue + if decl["OFFICIAL_XML_SHA256"].strip() != official_sha: + findings.append(Finding( + "IT_SOURCE_HASH_MISMATCH", "red", loc, + f"证据卡声明的官方整件哈希与现算不符" + f"(卡 {decl['OFFICIAL_XML_SHA256'].strip()[:12]}… / 现算 {official_sha[:12]}…)")) + # 条文切片:文件现算 + 是否仍属于官方整件 + art_rel = meta.get("article_file") or f"official/{eid}.xml" + art_path = os.path.join(corpus_dir, art_rel) + if not os.path.exists(art_path): + findings.append(Finding("IT_ARTICLE_HASH_MISMATCH", "red", loc, + f"条文切片 {art_rel} 不在语料目录里")) + continue + with open(art_path, "rb") as fh: + art_raw = fh.read() + art_sha = _sha256_bytes(art_raw) + if art_sha != meta.get("article_sha256"): + findings.append(Finding( + "IT_ARTICLE_HASH_MISMATCH", "red", loc, + f"条文 {eid} 的切片哈希与索引不符" + f"(索引 {str(meta.get('article_sha256'))[:12]}… / 现算 {art_sha[:12]}…)")) + if decl["ARTICLE_SHA256"].strip() != art_sha: + findings.append(Finding( + "IT_ARTICLE_HASH_MISMATCH", "red", loc, + f"证据卡声明的条文哈希与现算不符" + f"(卡 {decl['ARTICLE_SHA256'].strip()[:12]}… / 现算 {art_sha[:12]}…)")) + if eid not in live_eids: + findings.append(Finding( + "IT_ARTICLE_NOT_IN_SOURCE", "red", loc, + f"官方整件里已经找不到 {eid}——切片与官方件脱钩(可能整件被换过)")) + else: + # 官方整件里同名条文的字节应当与切片一致 + m2 = re.search(rb'
(.*?)
', + official_raw, re.S) + if m2 and _sha256_bytes(m2.group(0)) != art_sha: + findings.append(Finding( + "IT_ARTICLE_HASH_MISMATCH", "red", loc, + f"切片与官方整件里的 {eid} 字节不一致")) + # 证据卡自身是否被改 + pinned = (fact.get("source_sha256") or "").removeprefix("sha256:").lower() + if pinned and pinned != _sha256_file(card_path): + findings.append(Finding( + "IT_CARD_SHA256_MISMATCH", "red", loc, + f"证据卡 {src} 自身被改过(事实账钉的哈希与现算不符)")) + # 卡里的字段与索引是否对得上 + if decl.get("ACT_URN", "").strip() and index.get("act_urn") and \ + decl["ACT_URN"].strip() != index["act_urn"]: + findings.append(Finding("IT_CARD_FIELD_MISMATCH", "red", loc, + f"证据卡声明的法件 {decl['ACT_URN'].strip()} 与索引 " + f"{index['act_urn']} 不一致")) + if decl.get("VERSION_DATE", "").strip() and index.get("version_date") and \ + decl["VERSION_DATE"].strip() != index["version_date"]: + findings.append(Finding("IT_CARD_FIELD_MISMATCH", "red", loc, + f"证据卡声明的版本 {decl['VERSION_DATE'].strip()} 与索引 " + f"{index['version_date']} 不一致")) + # 事实的数值是否真的出自该条正文 + val = fact.get("value") + if val is not None: + text = _plain_text(art_raw.decode("utf-8", "replace")) + if not re.search(r"(?.xml 官方条文 XML 原字节(被事实账钉哈希的对象) + +另可挂一份「视图」JSONL(我们管线的现行版),用来回答「某条文在参考日是否生效」—— +因为 index.json 里的 date_debut/date_fin 已经是权威字段,视图只是交叉验证。 +""" +import hashlib +import json +import os +import re +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field, fields + +# 法文数字词(0–99,含 alors/soixante-dix/quatre-vingt-dix 等 70–99 的复合) +_UNITS = { + "zero": 0, "une": 1, "un": 1, "deux": 2, "trois": 3, "quatre": 4, "cinq": 5, + "six": 6, "sept": 7, "huit": 8, "neuf": 9, "dix": 10, "onze": 11, "douze": 12, + "treize": 13, "quatorze": 14, "quinze": 15, "seize": 16, "dix-sept": 17, + "dix-huit": 18, "dix-neuf": 19, "vingt": 20, "trente": 30, "quarante": 40, + "cinquante": 50, "soixante": 60, +} +_TENS = {"vingt": 20, "trente": 30, "quarante": 40, "cinquante": 50, "soixante": 60} +_UNIT_WORDS = set(_UNITS) + + +def fr_number_to_int(s): + """把法文数字词转成整数:'trente-cinq' → 35;'quatre-vingt-dix' → 90。 + 认不出的返回 None。""" + if not s: + return None + s = s.strip().lower().replace(" ", "-") + if s in _UNITS: + return _UNITS[s] + m = re.fullmatch(r"(quatre-vingt)(s)?-([a-z]+)?", s) + if m: + base = 80 + rest = m.group(3) + if rest is None: + return base + if rest == "dix": + return 90 + return base + _UNITS.get(rest, 0) if rest in _UNITS else None + if "-" in s: + head, _, tail = s.partition("-") + if head in _TENS and tail in _UNIT_WORDS: + return _TENS[head] + _UNITS[tail] + # soixante-dix / soixante et onze … + if head == "soixante" and tail in _UNITS: + v = _UNITS[tail] + return 60 + v if v >= 10 else 60 + v + return None + + +def norm_text(el): + """与 Légifrance 管线一致的正文归一:
换行、空白归一、**不去重相邻重复行**。""" + parts = [] + + def rec(node): + if node.tag == "br": + parts.append("\n") + return + if node.text: + parts.append(node.text) + for c in node: + rec(c) + if c.tail: + parts.append(c.tail) + + rec(el) + lines = [] + for ln in "".join(parts).split("\n"): + s = re.sub(r"[ \t\u00a0\u202f]+", " ", ln).strip() + if s: + lines.append(s) + return "\n".join(lines) + + +@dataclass +class Provision: + """一条法条(官方 XML 的某一条版本)。""" + num: str + legiarti: str = "" + code_id: str = "" + etat: str = "" + date_debut: str = "" + date_fin: str = "" + xml_file: str = "" + xml_sha256: str = "" + text_sha256: str = "" + text: str = field(default="", repr=False) + xml_bytes: int = 0 + text_chars: int = 0 + extra: dict = field(default_factory=dict, repr=False) + + # ---------- 生效判定 ---------- + def in_force_at(self, date): + """date_debut <= date < date_fin 才算当天生效。 + ⚠️ 不能用 etat 判:etat=VIGUEUR 的版本可能只是「未来才生效」。""" + if not self.date_debut: + return False + if self.date_debut > date: + return False + if self.date_fin and self.date_fin <= date: + return False + return True + + def scheduled_at(self, date): + return bool(self.date_debut) and self.date_debut > date + + def repealed_at(self, date): + return bool(self.date_fin) and self.date_fin <= date + + # ---------- 正文查询 ---------- + def contains_number(self, value): + """事实的值是否真的出自这条法条。 + 数字既可能写成阿拉伯数字,也可能写成法文数字词('trente-cinq heures')。""" + if value is None: + return False + raw = str(value).strip().rstrip("%") + try: + n = int(float(raw)) + except ValueError: + return False + text = self.text + # 阿拉伯数字(带词边界,避免 3 命中 35) + if re.search(r"(? 99: + return [] + out = [] + if n < 20: + for k, v in _UNITS.items(): + if v == n and k not in ("zéro",): + out.append(k) + elif n % 10 == 0 and n in _TENS.values(): + for k, v in _TENS.items(): + if v == n: + out.append(k) + else: + tens = (n // 10) * 10 + unit = n % 10 + tk = next((k for k, v in _TENS.items() if v == tens), None) + uk = next((k for k, v in _UNITS.items() if v == unit), None) + if tens == 60 and unit >= 11: + base = next((k for k, v in _UNITS.items() if v == 10 + unit), None) + if base: + out.append(f"soixante-{base}") + out.append(f"soixante et {base.replace('-', ' ')}") + elif tens == 80: + rest = unit + if rest == 0: + out.append("quatre-vingts") + elif unit == 1: + out.append("quatre-vingt-un") + else: + rk = next((k for k, v in _UNITS.items() if v == rest), None) + if rk: + out.append(f"quatre-vingt-{rk}") + elif tk and uk: + out.append(f"{tk}-{uk}") + out.append(f"{tk} {uk}") + return out + + +def load_corpus(provisions_dir): + """读证据包 → {编号: Provision}""" + idx_path = os.path.join(provisions_dir, "index.json") + if not os.path.exists(idx_path): + raise FileNotFoundError(f"找不到 {idx_path}") + with open(idx_path, encoding="utf-8") as fh: + idx = json.load(fh) + out = {} + known = {f.name for f in fields(Provision)} + pool_asof = str(idx.get("pool_asof") or "").strip() + for num, meta in idx.get("provisions", {}).items(): + p = Provision(num=num, **{k: v for k, v in meta.items() + if k in known and k != "num"}) + # 索引里可能带额外字段(同编号的历史版本清单等),挂到 extra 上 + p.extra = {k: v for k, v in meta.items() if k not in known} + p.extra["pool_asof"] = pool_asof + xml_path = os.path.join(provisions_dir, meta.get("xml_file", f"{num}.xml")) + if os.path.exists(xml_path): + with open(xml_path, "rb") as fh: + raw = fh.read() + p.xml_bytes = len(raw) + p.xml_sha256 = hashlib.sha256(raw).hexdigest() + root = ET.fromstring(raw) + p.text = norm_text(root.find("BLOC_TEXTUEL")) + p.text_sha256 = hashlib.sha256(p.text.encode("utf-8")).hexdigest() + out[num] = p + return out + + +def load_view(path): + """管线的现行版视图 → {编号: record}(用于交叉验证生效状态)""" + if not path or not os.path.exists(path): + return {} + out = {} + opener = __import__("gzip").open if path.endswith(".gz") else open + with opener(path, "rt", encoding="utf-8") as f: + for line in f: + r = json.loads(line) + out.setdefault(r["num"], r) + return out diff --git a/integrations/factscribe-legal/factscribe_legal/verify.py b/integrations/factscribe-legal/factscribe_legal/verify.py new file mode 100644 index 0000000..1a45f55 --- /dev/null +++ b/integrations/factscribe-legal/factscribe_legal/verify.py @@ -0,0 +1,274 @@ +"""法律专项校验:把「事实的来源是法条」这件事变成机械判定。 + +上游 FactScribe 判的是:正文数字 → 事实账 → 材料哈希。 +本包判的是**法律这一层**: + + 红 + LEGAL_PROV_UNKNOWN 引用/来源的法条在语料里不存在 + LEGAL_PROV_HASH_MISMATCH 钉的哈希与官方 XML 现算不符(法条被人动过) + LEGAL_PROV_NOT_IN_FORCE 参考日当天该版本不生效(引用了旧版或未来版) + LEGAL_QUOTE_MISMATCH 事实里的值并不出现在该法条的官方正文里 + LEGAL_FACT_NOT_PROVISION 事实声称来源是法条,但 source 指向的不是 provisions/ + 黄 + LEGAL_PROV_SCHEDULED 引用的是已排期、尚未生效的版本 + LEGAL_PROV_REPEALED 引用的是已废止版本 + +退出码沿用上游:0 绿 / 1 红 / 2 配置错 / 3 黄 +""" +import hashlib +import os +import re + +from ._toml import load_toml +from .provisions import load_corpus, load_view + +CITE_RE = re.compile(r"\\cite[a-zA-Z]*\{([^}]*)\}") +# 事实的 source 可以是官方 XML 本体,也可以是「法条证据卡」(派生件,内含官方 XML 哈希声明) +PROV_RE = re.compile(r"^(?P.+)/(?P[^/]+?)(?:\.card\.txt|\.xml)$") +CARD_SHA_RE = re.compile(r"^OFFICIAL_XML_SHA256:\s*([0-9a-f]{64})\s*$", re.M) +CARD_FIELD_RE = re.compile(r"^(?P[A-Z_]+):\s*(?P.*)$", re.M) + + +def _sha256_file(path): + import hashlib + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _is_it_card(path): + """证据卡是不是意大利侧的(看卡内自己的标记字段,不靠目录名猜)。""" + try: + with open(path, encoding="utf-8") as fh: + head = fh.read(4096) + except OSError: + return False + return "ARTICLE_EID:" in head and "ACT_URN:" in head + + +class Finding: + def __init__(self, code, severity, location, message, detail=""): + self.code = code + self.severity = severity # red | yellow + self.location = location + self.message = message + self.detail = detail + + def __repr__(self): + return f"[{self.severity}] {self.code} {self.location} — {self.message}" + + +def load_facts(project_dir): + facts = [] + fdir = os.path.join(project_dir, "facts") + if not os.path.isdir(fdir): + return facts + for name in sorted(os.listdir(fdir)): + if not name.endswith(".toml"): + continue + data = load_toml(os.path.join(fdir, name)) + for fact in data.get("fact", []): + fact["_file"] = f"facts/{name}" + facts.append(fact) + return facts + + +def load_citations(project_dir): + """扫 .tex 里的 \\cite{...},返回 [(key, file, line)]""" + out = [] + for root, _dirs, files in os.walk(project_dir): + if any(p in root for p in ("/.git", "/audit", "/vendor")): + continue + for fn in files: + if not fn.endswith(".tex"): + continue + path = os.path.join(root, fn) + rel = os.path.relpath(path, project_dir) + with open(path, encoding="utf-8") as fh: + for i, line in enumerate(fh, 1): + for m in CITE_RE.finditer(line): + for key in m.group(1).split(","): + out.append((key.strip(), rel, i)) + return out + + +def verify(project_dir, provisions_dir, reference_date, view_path=None): + """跑法律专项校验,返回 findings 列表。""" + findings = [] + corpus = load_corpus(provisions_dir) + view = load_view(view_path) if view_path else {} + + # ---- 1. 事实账里指向法条的 fact ---- + for fact in load_facts(project_dir): + src = fact.get("source", "") + if src.endswith(".cn.card.txt"): + # 中国侧证据卡:不属法国语料(两侧共用一个项目,各判各的) + continue + if src.endswith(".case.card.txt"): + # 中国案例维度证据卡:归第 5 层 legal-case 判,这里跳过 + continue + if src.endswith(".it.card.txt"): + # 意大利证据卡:归意大利专闸(verify-it)判,这里跳过 + continue + m = PROV_RE.match(src) + if not m: + continue + num = m.group("num") + loc = f"{fact['_file']}:{fact.get('id', '?')}" + prov = corpus.get(num) + if prov is None: + findings.append(Finding("LEGAL_PROV_UNKNOWN", "red", loc, + f"法条 {num} 不在语料里({provisions_dir})")) + continue + # ---- 哈希现算比对 ---- + # source 直接指向官方 XML ⇒ 比对事实账钉的哈希 + # source 指向证据卡 ⇒ 比对卡片里声明的官方 XML 哈希与现算值(两层都不丢) + pinned = (fact.get("source_sha256") or "").removeprefix("sha256:").lower() + if src.endswith(".card.txt"): + card_path = os.path.join(project_dir, src) + declared = "" + if os.path.exists(card_path): + with open(card_path, encoding="utf-8") as fh: + card = fh.read() + cm = CARD_SHA_RE.search(card) + declared = (cm.group(1) if cm else "").lower() + if not declared: + findings.append(Finding( + "LEGAL_CARD_NO_HASH", "red", loc, + f"证据卡 {src} 里没有 OFFICIAL_XML_SHA256 声明")) + elif declared != prov.xml_sha256: + findings.append(Finding( + "LEGAL_PROV_HASH_MISMATCH", "red", loc, + f"法条 {num} 的官方 XML 哈希与证据卡声明不符" + f"(卡 {declared[:12]}… / 现算 {prov.xml_sha256[:12]}…)——材料被改过")) + elif pinned and pinned != _sha256_file(os.path.join(project_dir, src)): + findings.append(Finding( + "LEGAL_CARD_SHA256_MISMATCH", "red", loc, + f"证据卡 {src} 自身被改过(事实账钉的哈希与现算不符)")) + elif pinned and pinned != prov.xml_sha256: + findings.append(Finding( + "LEGAL_PROV_HASH_MISMATCH", "red", loc, + f"法条 {num} 的 XML 哈希与事实账不符" + f"(账 {pinned[:12]}… / 现算 {prov.xml_sha256[:12]}…)——材料被改过")) + # 生效判定 + if prov.scheduled_at(reference_date): + findings.append(Finding("LEGAL_PROV_SCHEDULED", "yellow", loc, + f"法条 {num} 到 {prov.date_debut} 才生效" + f"(参考日 {reference_date})")) + elif prov.repealed_at(reference_date): + findings.append(Finding("LEGAL_PROV_REPEALED", "yellow", loc, + f"法条 {num} 已于 {prov.date_fin} 失效")) + elif not prov.in_force_at(reference_date): + findings.append(Finding("LEGAL_PROV_NOT_IN_FORCE", "red", loc, + f"法条 {num} 在参考日 {reference_date} 不生效" + f"({prov.date_debut} → {prov.date_fin})")) + # 视图交叉验证 + if view: + v = view.get(num) + if v and v.get("id") != prov.legiarti: + findings.append(Finding( + "LEGAL_PROV_VIEW_MISMATCH", "yellow", loc, + f"法条 {num} 与现行视图不是同一个版本" + f"(语料 {prov.legiarti} / 视图 {v.get('id')})")) + # 事实的值是否真的出自该法条 + val = fact.get("value") + if val is not None and prov.text and not prov.contains_number(val): + findings.append(Finding( + "LEGAL_QUOTE_MISMATCH", "red", loc, + f"事实 {fact.get('id')} 的值 {val} 不出现在法条 {num} 的官方正文里")) + + # ---- 1b. 版本池覆盖度:池子比参考日落后几天 ---- + pool_asof = "" + for prov in corpus.values(): + pool_asof = prov.extra.get("pool_asof") or pool_asof + if pool_asof and reference_date > pool_asof: + try: + from datetime import date as _d + gap = (_d(*map(int, reference_date.split("-"))) - + _d(*map(int, pool_asof.split("-")))).days + except Exception: + gap = -1 + if gap > 0: + findings.append(Finding( + "LEGAL_COVERAGE_GAP", "yellow", "corpus", + f"版本池的数据截止日是 {pool_asof},比参考日 {reference_date} 落后 {gap} 天" + f"——这段时间内的法律变化不在池子里;引用仍是「池内最新」," + f"不是「今日最新」(要当日最新请先拉日更增量包)")) + + # ---- 1c. 参考日唯一性:同一编号在参考日有且只有一个生效版本 ---- + for num, prov in sorted(corpus.items()): + vers = prov.extra.get("versions") or [] + if not vers: + continue + live = [v for v in vers + if v.get("date_debut") and v["date_debut"] <= reference_date + and (not v.get("date_fin") or reference_date < v["date_fin"])] + if len(live) > 1: + findings.append(Finding( + "LEGAL_PROV_AMBIGUOUS", "yellow", f"corpus:{num}", + f"{num} 在参考日 {reference_date} 有 {len(live)} 个版本同时生效" + f"(数据异常,需人工看版本链)")) + + # ---- 2. 正文里的法条引用 ---- + for key, rel, line in load_citations(project_dir): + if re.search(r"[\u4e00-\u9fff]", key): + # 中文法规引用归中国闸管 + continue + if key.startswith("art-it-"): + # 意大利法条引用归意大利专闸(verify-it)判,这里跳过 + continue + if key.startswith("art:"): + num = key[4:] + elif key.startswith("art-"): + num = key[4:] + else: + continue + prov = corpus.get(num) + loc = f"{rel}:{line}" + if prov is None: + findings.append(Finding("LEGAL_PROV_UNKNOWN", "red", loc, + f"引用了语料里没有的法条 {num}")) + continue + if prov.scheduled_at(reference_date): + findings.append(Finding("LEGAL_PROV_SCHEDULED", "yellow", loc, + f"引用的 {num} 到 {prov.date_debut} 才生效")) + elif prov.repealed_at(reference_date): + findings.append(Finding("LEGAL_PROV_REPEALED", "yellow", loc, + f"引用的 {num} 已于 {prov.date_fin} 失效")) + elif not prov.in_force_at(reference_date): + findings.append(Finding("LEGAL_PROV_NOT_IN_FORCE", "red", loc, + f"引用的 {num} 在参考日 {reference_date} 不生效")) + + return findings, corpus + + +def render(findings, corpus=None): + reds = [f for f in findings if f.severity == "red"] + yellows = [f for f in findings if f.severity == "yellow"] + lines = ["== factscribe-legal verify =="] + if corpus: + lines.append(f"corpus : {len(corpus)} 条法条") + lines.append("") + if yellows: + lines.append(f"[黄] {len(yellows)} 处") + for i, f in enumerate(yellows, 1): + lines.append(f" {i}. {f.code:28s} {f.location} → {f.message}") + lines.append("") + if reds: + lines.append(f"[红] {len(reds)} 处(必须修)") + for i, f in enumerate(reds, 1): + lines.append(f" {i}. {f.code:28s} {f.location} → {f.message}") + else: + lines.append("[红] 0 处") + lines.append("") + total = len(reds) + len(yellows) + if reds: + lines.append(f"结论:{len(reds)} 红 / {len(yellows)} 黄 → 红(退出码 1)") + elif yellows: + lines.append(f"结论:0 红 / {len(yellows)} 黄 → 黄(退出码 3)") + else: + lines.append("结论:0 红 / 0 黄 → 绿(退出码 0)") + lines.append("注意:绿只代表「引用的法条真实存在、哈希未变、且在参考日生效」,不代表法条写得对。") + return "\n".join(lines), (1 if reds else (3 if yellows else 0)) diff --git a/integrations/factscribe-legal/tests/fixtures/facts_sample.toml b/integrations/factscribe-legal/tests/fixtures/facts_sample.toml new file mode 100644 index 0000000..38829e5 --- /dev/null +++ b/integrations/factscribe-legal/tests/fixtures/facts_sample.toml @@ -0,0 +1,28 @@ +# 事实账样本:覆盖本集成实际会写出的 TOML 子集。 +# 用来交叉校验「自带极简解析器」与「标准库 tomllib」对同一文件给出完全相同的结果。 +schema = "paperkit-fact/3.0" + +[[fact]] +id = "LBR-GBRQ" +claim = "《中华人民共和国劳动法》公布日期" +value = "2018-12-29" +source = "runs/run-20261114-cn/中华人民共和国劳动法_46d15a.cn.card.txt" +source_sha256 = "sha256:c58687bc12ac42749f359420368f850c66fc3d6e68154da76ea6bd779a03e4bc" +locator = "中华人民共和国劳动法(LEGISBBBS ff8080816f135f46016f20f16ee11737)" +confidence = "high" +derived_from = [] +note = "官方详情 gbrq" +dup_ok = true + +[[fact]] +id = "LBR-N" +claim = "《中华人民共和国劳动法》条文条数" +value = "109" +source = "runs/run-20261114-cn/中华人民共和国劳动法_46d15a.cn.card.txt" +confidence = "high" +derived_from = [] +count = 109 +ratio = 0.5 +flag = false +tags = ["a", "b"] +nested = [["x"], ["y", "z"]] diff --git a/integrations/factscribe-legal/tests/test_italy.py b/integrations/factscribe-legal/tests/test_italy.py new file mode 100644 index 0000000..32c2ddd --- /dev/null +++ b/integrations/factscribe-legal/tests/test_italy.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""意大利法条专闸(verify-it)的自测:标准库 unittest,不依赖上游。 + + python3 -m unittest discover -s integrations/factscribe-legal/tests -v +""" +import hashlib +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from factscribe_legal.it_verify import render_it, verify_it # noqa: E402 +from factscribe_legal.verify import verify as verify_fr # noqa: E402 + +def _read(path): + with open(path, encoding="utf-8") as fh: + return fh.read() + + +def _write(path, text): + with open(path, "w", encoding="utf-8") as fh: + fh.write(text) + +AKN = """ + + + + + + + + + +
Art. 29 +

I datori di lavoro che occupano fino a 50 lavoratori possono effettuare la + valutazione dei rischi sulla base delle procedure standardizzate.

+
+
Art. 35 +

Nelle aziende che occupano piu' di 15 lavoratori si indice almeno una + volta all'anno una riunione.

+
+
+
+
+""" + + +def sha(b): + return hashlib.sha256(b).hexdigest() + + +class TestItalyGate(unittest.TestCase): + """用一个迷你语料(两篇条文)把闸门的每条判据都跑一遍。""" + + def _corpus(self, root): + run = os.path.join(root, "runs", "run-test-it") + off = os.path.join(run, "official") + os.makedirs(off) + raw = AKN.encode("utf-8") + with open(os.path.join(off, "act.akn.xml"), "wb") as fh: + fh.write(raw) + articles = {} + for eid in ("art_29", "art_35"): + import re + m = re.search(rb'
.*?
', raw, re.S) + blob = m.group(0) + with open(os.path.join(off, f"{eid}.xml"), "wb") as fh: + fh.write(blob) + text = re.sub(r"<[^>]+>", " ", blob.decode("utf-8")) + import re as _re + text = _re.sub(r"\s+", " ", text).strip() + articles[eid] = { + "eid": eid, "num": eid.split("_")[1], + "article_file": f"official/{eid}.xml", + "article_sha256": sha(blob), "article_bytes": len(blob), + "text_sha256": sha(text.encode("utf-8")), "text_chars": len(text), + "card_file": f"{eid}.it.card.txt", "card_sha256": "", + } + index = { + "act_key": "DLGS81", + "act_urn": "urn:nir:stato:decreto.legislativo:2008-04-09;81", + "act_eli": "eli/id/2008/04/30/008G0104/CONSOLIDATED/20260407", + "act_title": "DECRETO LEGISLATIVO 9 aprile 2008, n. 81", + "source_file": "official/act.akn.xml", + "source_sha256": sha(raw), "source_bytes": len(raw), + "version_date": "2026-04-07", + "fetch_vigenza": "20261114", + "fetch_reference_date": "2026-11-14", + "reference_date": "2026-11-14", + "articles": articles, + } + with open(os.path.join(run, "index.json"), "w", encoding="utf-8") as fh: + json.dump(index, fh, ensure_ascii=False, indent=2) + + # 证据卡 + 事实账 + os.makedirs(os.path.join(root, "facts")) + facts = ['schema = "paperkit-fact/3.0"', ""] + for fid, eid, val in (("IT1", "art_29", "50"), ("IT2", "art_35", "15")): + card = "\n".join([ + "# 意大利法条证据卡(派生件)", + "ACT_URN: urn:nir:stato:decreto.legislativo:2008-04-09;81", + f"ARTICLE_EID: {eid}", + f"ARTICLE_NUM: {eid.split('_')[1]}", + "VERSION_DATE: 2026-04-07", + "FETCH_VIGENZA: 20261114", + "REFERENCE_DATE: 2026-11-14", + "SOURCE_FILE: official/act.akn.xml", + f"OFFICIAL_XML_SHA256: {sha(raw)}", + f"ARTICLE_SHA256: {articles[eid]['article_sha256']}", + "--- OFFICIAL TEXT ---", + "testo", + "", + ]) + with open(os.path.join(run, f"{eid}.it.card.txt"), "w", encoding="utf-8") as fh: + fh.write(card) + facts += [ + "[[fact]]", + f'id = "{fid}"', + f'claim = "claim {fid}"', + f'value = "{val}"', + f'source = "runs/run-test-it/{eid}.it.card.txt"', + f'source_sha256 = "sha256:{sha(card.encode("utf-8"))}"', + 'confidence = "high"', + "derived_from = []", + "", + ] + with open(os.path.join(root, "facts", "05-it-provisions.toml"), "w", + encoding="utf-8") as fh: + fh.write("\n".join(facts)) + return run + + def _codes(self, root, run, date="2026-11-14"): + findings, index = verify_it(root, run, date) + return [f.code for f in findings], findings, index + + def test_clean_corpus_is_green(self): + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + codes, findings, index = self._codes(tmp, run) + self.assertEqual(codes, [], f"应当全绿,实际:{[f.code for f in findings]}") + text, code = render_it(findings, index) + self.assertEqual(code, 0) + + def test_article_slice_tampered_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(run, "official", "art_29.xml") + s = _read(p).replace("50 lavoratori", "60 lavoratori") + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_ARTICLE_HASH_MISMATCH", codes) + + def test_official_file_tampered_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(run, "official", "act.akn.xml") + s = _read(p).replace("15 lavoratori", "25 lavoratori") + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_SOURCE_HASH_MISMATCH", codes) + + def test_card_tampered_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(run, "art_29.it.card.txt") + s = _read(p).replace("testo", "testo modificato") + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_CARD_SHA256_MISMATCH", codes) + + def test_value_not_in_official_text_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(tmp, "facts", "05-it-provisions.toml") + s = _read(p).replace('value = "50"', 'value = "999"') + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_QUOTE_MISMATCH", codes) + + def test_card_missing_is_red(self): + """事实指向的意大利卡不存在 ⇒ 判红,不能静默跳过(否则等于「无不一致即通过」)。""" + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(tmp, "facts", "05-it-provisions.toml") + s = _read(p).replace("art_29.it.card.txt", "art_999.it.card.txt") + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_CARD_MISSING", codes) + + def test_article_not_in_index_is_red(self): + """卡在、但条文不在索引里 ⇒ IT_PROV_UNKNOWN。""" + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + idx = os.path.join(run, "index.json") + with open(idx, encoding="utf-8") as fh: + d = json.load(fh) + d["articles"].pop("art_29") + with open(idx, "w", encoding="utf-8") as fh: + json.dump(d, fh, ensure_ascii=False) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_PROV_UNKNOWN", codes) + + def test_reference_date_mismatch_is_yellow(self): + """钉的是 2026-11-14 当天生效的版本,拿别的参考日来核 ⇒ 黄项,不是红项。""" + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + codes, _, _ = self._codes(tmp, run, date="2026-12-01") + self.assertIn("IT_VERSION_GAP", codes) + self.assertNotIn("IT_VERSION_GAP", [c for c in codes if c.startswith("IT_") and c != "IT_VERSION_GAP"] and [] or []) + + def test_article_removed_from_official_is_red(self): + """官方整件里那条被删了(切片还在)⇒ 必须判红,不能当作「哈希对得上就过」。""" + with tempfile.TemporaryDirectory() as tmp: + run = self._corpus(tmp) + p = os.path.join(run, "official", "act.akn.xml") + s = _read(p) + import re + s = re.sub(r'
.*?
', "", s, flags=re.S) + _write(p, s) + codes, _, _ = self._codes(tmp, run) + self.assertIn("IT_SOURCE_HASH_MISMATCH", codes) + + def test_french_gate_skips_italy_cards(self): + """意大利证据卡不能让法国闸误判红。""" + with tempfile.TemporaryDirectory() as tmp: + self._corpus(tmp) + fr_corpus = os.path.join(tmp, "runs", "run-test-fr") + os.makedirs(fr_corpus, exist_ok=True) + with open(os.path.join(fr_corpus, "index.json"), "w", encoding="utf-8") as fh: + json.dump({"provisions": {}}, fh) + findings, _corpus = verify_fr(tmp, fr_corpus, "2026-11-14") + self.assertEqual([f.code for f in findings], [], + f"法国闸不应因意大利卡报错:{[f.code for f in findings]}") + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/factscribe-legal/tests/test_legal.py b/integrations/factscribe-legal/tests/test_legal.py new file mode 100644 index 0000000..88ed9af --- /dev/null +++ b/integrations/factscribe-legal/tests/test_legal.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""factscribe_legal 的自测(标准库 unittest,不依赖上游)。 + + python3 -m unittest discover -s integrations/factscribe-legal/tests -v +""" +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from factscribe_legal.provisions import (Provision, fr_number_to_int, # noqa: E402 + norm_text) +from factscribe_legal.verify import verify # noqa: E402 + + +def _read(path): + with open(path, encoding="utf-8") as fh: + return fh.read() + + +def _write(path, text): + with open(path, "w", encoding="utf-8") as fh: + fh.write(text) + + +class TestFrenchNumbers(unittest.TestCase): + def test_simple(self): + self.assertEqual(fr_number_to_int("trente-cinq"), 35) + self.assertEqual(fr_number_to_int("quinze"), 15) + self.assertEqual(fr_number_to_int("soixante"), 60) + + def test_compound(self): + self.assertEqual(fr_number_to_int("quatre-vingt-dix"), 90) + self.assertEqual(fr_number_to_int("soixante-douze"), 72) + self.assertEqual(fr_number_to_int("vingt-et-un"), None) # 未收录写法 + + def test_unknown(self): + self.assertIsNone(fr_number_to_int("banane")) + + +class TestProvision(unittest.TestCase): + def _p(self, **kw): + base = dict(num="L3121-27", date_debut="2008-05-01", date_fin="2999-01-01") + base.update(kw) + return Provision(**base) + + def test_in_force(self): + p = self._p() + self.assertTrue(p.in_force_at("2026-11-14")) + self.assertFalse(p.in_force_at("2008-04-30")) # 生效前 + self.assertFalse(p.in_force_at("2999-01-01")) # 失效当天 + + def test_scheduled_and_repealed(self): + p = self._p(date_debut="2029-03-01", date_fin="2999-01-01") + self.assertTrue(p.scheduled_at("2026-11-14")) + self.assertFalse(p.in_force_at("2026-11-14")) + q = self._p(date_debut="2020-01-01", date_fin="2025-01-01") + self.assertTrue(q.repealed_at("2026-11-14")) + self.assertFalse(q.in_force_at("2026-11-14")) + + def test_contains_number_arabic(self): + p = self._p(text="La durée légale est fixée à 35 heures par semaine.") + self.assertTrue(p.contains_number("35")) + self.assertFalse(p.contains_number("3")) # 不能命中 35 里的 3 + + def test_contains_number_french_word(self): + p = self._p(text="La durée légale est fixée à trente-cinq heures par semaine.") + self.assertTrue(p.contains_number("35")) + self.assertFalse(p.contains_number("36")) + + def test_contains_number_not_in_text(self): + p = self._p(text="La durée légale est fixée à trente-cinq heures par semaine.") + self.assertFalse(p.contains_number("40")) + + +class TestVerify(unittest.TestCase): + def _project(self, tmp, fact_source="provisions/L3121-27.xml", + fact_sha=None, value="35", cite="art:L3121-27"): + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + os.makedirs(os.path.join(tmp, "sections"), exist_ok=True) + with open(os.path.join(tmp, "facts", "01.toml"), "w", encoding="utf-8") as f: + f.write(f'''[[fact]] +id = "P1" +claim = "法定正常工时" +value = "{value}" +source = "{fact_source}" +source_sha256 = "sha256:{fact_sha or '0' * 64}" +confidence = "high" +derived_from = [] +''') + with open(os.path.join(tmp, "sections", "01.tex"), "w", encoding="utf-8") as f: + f.write("\\section{X}\nCite \\cite{" + cite + "}.\n") + + def _corpus(self, tmp, etat="VIGUEUR", d0="2008-05-01", d1="2999-01-01"): + import hashlib + import json + cdir = os.path.join(tmp, "corpus") + os.makedirs(cdir, exist_ok=True) + raw = (f"
LEGIARTI000037329915" + f"L3121-27{etat}" + f"{d0}{d1}" + f"

La durée légale est fixée à trente-cinq heures par semaine." + f"

").encode("utf-8") + with open(os.path.join(cdir, "L3121-27.xml"), "wb") as f: + f.write(raw) + sha = hashlib.sha256(raw).hexdigest() + with open(os.path.join(cdir, "index.json"), "w", encoding="utf-8") as f: + json.dump({"code_id": "X", "provisions": { + "L3121-27": {"num": "L3121-27", "legiarti": "LEGIARTI000037329915", + "code_id": "X", "etat": etat, "date_debut": d0, + "date_fin": d1, "xml_file": "L3121-27.xml", + "xml_sha256": sha, "text_sha256": "", "xml_bytes": len(raw)}}}, f) + return cdir, sha + + def test_green(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + self._project(tmp, fact_sha=sha) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertEqual([f.code for f in findings if f.severity == "red"], []) + + def test_hash_mismatch_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, _sha = self._corpus(tmp) + self._project(tmp, fact_sha="f" * 64) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_PROV_HASH_MISMATCH", [f.code for f in findings]) + + def test_quote_mismatch_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + self._project(tmp, fact_sha=sha, value="40") + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_QUOTE_MISMATCH", [f.code for f in findings]) + + def test_unknown_provision_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + self._project(tmp, fact_sha=sha, cite="art:L9999-1") + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_PROV_UNKNOWN", [f.code for f in findings]) + + def test_not_in_force_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp, d0="2029-01-01") + self._project(tmp, fact_sha=sha) + findings, _ = verify(tmp, cdir, "2026-11-14") + codes = [f.code for f in findings] + self.assertIn("LEGAL_PROV_SCHEDULED", codes) + + def test_repealed_is_yellow(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp, d0="2008-05-01", d1="2025-01-01") + self._project(tmp, fact_sha=sha) + findings, _ = verify(tmp, cdir, "2026-11-14") + f = [x for x in findings if x.code == "LEGAL_PROV_REPEALED"] + self.assertTrue(f) + self.assertEqual(f[0].severity, "yellow") + + +class TestMultiLevelSourcePath(unittest.TestCase): + """回归:source 是 runs//.card.txt 这类多级路径时, + 事实不能被跳过(曾经因为正则只匹配一级目录而整批被跳过 ⇒ 假绿)。""" + + def _corpus(self, tmp): + import hashlib + import json + cdir = os.path.join(tmp, "corpus") + os.makedirs(os.path.join(cdir, "official"), exist_ok=True) + raw = (b"
LEGIARTI000037329915" + b"L3121-27VIGUEUR" + b"2008-05-012999-01-01" + b"

fixee a trente-cinq heures." + b"

") + with open(os.path.join(cdir, "official", "L3121-27.xml"), "wb") as f: + f.write(raw) + sha = hashlib.sha256(raw).hexdigest() + with open(os.path.join(cdir, "index.json"), "w", encoding="utf-8") as f: + json.dump({"provisions": {"L3121-27": { + "num": "L3121-27", "legiarti": "LEGIARTI000037329915", + "code_id": "X", "etat": "VIGUEUR", "date_debut": "2008-05-01", + "date_fin": "2999-01-01", "xml_file": "official/L3121-27.xml", + "xml_sha256": sha, "text_sha256": "", "xml_bytes": len(raw)}}}, f) + return cdir, sha + + def _project(self, tmp, value="35", declared=None): + run = os.path.join(tmp, "runs", "run-test") + os.makedirs(run, exist_ok=True) + card = ("NUM: L3121-27\nOFFICIAL_XML: official/L3121-27.xml\n" + f"OFFICIAL_XML_SHA256: {declared or self._sha}\n" + "--- OFFICIAL TEXT ---\ntrente-cinq heures\n") + with open(os.path.join(run, "L3121-27.card.txt"), "w", encoding="utf-8") as f: + f.write(card) + with open(os.path.join(tmp, "facts", "01.toml"), "w", encoding="utf-8") as f: + f.write(f'''[[fact]] +id = "P1" +claim = "c" +value = "{value}" +source = "runs/run-test/L3121-27.card.txt" +source_sha256 = "sha256:{self._sha}" +confidence = "high" +derived_from = [] +''') + + def setUp(self): + import hashlib + self._sha = hashlib.sha256(b"x").hexdigest() + + def test_multilevel_source_is_inspected(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + self._project(tmp, declared=sha) + findings, _ = verify(tmp, cdir, "2026-11-14") + # 事实被看到了(值 35 在正文里 ⇒ 不该报 quote mismatch) + self.assertEqual([f.code for f in findings if f.code == "LEGAL_QUOTE_MISMATCH"], []) + + def test_multilevel_source_bad_value_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + self._project(tmp, value="40", declared=sha) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_QUOTE_MISMATCH", [f.code for f in findings]) + + def test_card_declared_hash_mismatch_is_red(self): + with tempfile.TemporaryDirectory() as tmp: + cdir, sha = self._corpus(tmp) + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + self._project(tmp, declared="f" * 64) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_PROV_HASH_MISMATCH", [f.code for f in findings]) + + +class TestCoverageAndUniqueness(unittest.TestCase): + """版本池覆盖度与「参考日唯一生效版本」两条判据。""" + + def _make(self, tmp, pool_asof, versions): + import hashlib + import json + cdir = os.path.join(tmp, "corpus") + os.makedirs(cdir, exist_ok=True) + raw = (b"
LEGIARTI000037329915" + b"L3121-27VIGUEUR" + b"2008-05-012999-01-01" + b"

trente-cinq heures" + b"

") + with open(os.path.join(cdir, "L3121-27.xml"), "wb") as f: + f.write(raw) + sha = hashlib.sha256(raw).hexdigest() + with open(os.path.join(cdir, "index.json"), "w", encoding="utf-8") as f: + json.dump({"pool_asof": pool_asof, "provisions": {"L3121-27": { + "num": "L3121-27", "legiarti": "LEGIARTI000037329915", + "code_id": "X", "etat": "VIGUEUR", "date_debut": "2008-05-01", + "date_fin": "2999-01-01", "xml_file": "L3121-27.xml", + "xml_sha256": sha, "text_sha256": "", "xml_bytes": len(raw), + "versions": versions}}}, f) + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + return cdir + + def test_gap_is_yellow(self): + with tempfile.TemporaryDirectory() as tmp: + cdir = self._make(tmp, "2026-11-13", [ + {"legiarti": "A", "etat": "VIGUEUR", "date_debut": "2008-05-01", + "date_fin": "2999-01-01"}]) + findings, _ = verify(tmp, cdir, "2026-11-14") + f = [x for x in findings if x.code == "LEGAL_COVERAGE_GAP"] + self.assertTrue(f) + self.assertEqual(f[0].severity, "yellow") + self.assertIn("1 天", f[0].message) + + def test_no_gap_when_pool_covers(self): + with tempfile.TemporaryDirectory() as tmp: + cdir = self._make(tmp, "2026-11-14", [ + {"legiarti": "A", "etat": "VIGUEUR", "date_debut": "2008-05-01", + "date_fin": "2999-01-01"}]) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertEqual([x.code for x in findings if x.code == "LEGAL_COVERAGE_GAP"], []) + + def test_ambiguous_versions_is_yellow(self): + with tempfile.TemporaryDirectory() as tmp: + cdir = self._make(tmp, "2026-11-14", [ + {"legiarti": "A", "etat": "VIGUEUR", "date_debut": "2008-05-01", + "date_fin": "2999-01-01"}, + {"legiarti": "B", "etat": "VIGUEUR", "date_debut": "2020-01-01", + "date_fin": "2999-01-01"}]) + findings, _ = verify(tmp, cdir, "2026-11-14") + self.assertIn("LEGAL_PROV_AMBIGUOUS", [x.code for x in findings]) + + +class TestCaseDimension(unittest.TestCase): + """第 5 层(中国案例维度)的自测:闸门自己也要有测试。""" + + OFFICIAL = ("基本案情\n  张某于2015年4月1日入职某公司。同年3月,张某怀孕。\n" + "  一、某宝销售公司支付张某工资人民币6766.5元;\n" + "  二、某宝销售公司支付张某房屋销售佣金45102元;\n" + "  三、某宝销售公司支付张某违法解除劳动合同赔偿金146160元;\n" + "  重庆市第一中级人民法院于2023年10月20日作出(2023)渝01民终7708号民事判决。\n") + + def _project(self, tmp, official=None, card_overrides=None, record_ids=None): + import hashlib + import json + off = official if official is not None else self.OFFICIAL + run = os.path.join(tmp, "runs", "run-20261114-case") + offdir = os.path.join(run, "official") + os.makedirs(offdir, exist_ok=True) + slug = "张某诉某公司劳动争议案" + with open(os.path.join(offdir, slug + ".txt"), "w", encoding="utf-8") as f: + f.write(off) + fields = { + "CASE_NO": "(2023)渝01民终7708号", + "JUDGE_DATE": "2023.10.20", + "AMOUNTS": "6766.5, 45102, 146160", + "OFFICIAL_TEXT_SHA256": hashlib.sha256(off.encode("utf-8")).hexdigest(), + } + fields.update(card_overrides or {}) + card = "# 案例证据卡\n" + "".join(f"{k}: {v}\n" for k, v in fields.items()) + card += "--- OFFICIAL TEXT ---\n" + off + card_path = os.path.join(run, slug + ".case.card.txt") + with open(card_path, "w", encoding="utf-8") as f: + f.write(card) + os.makedirs(os.path.join(tmp, "facts"), exist_ok=True) + fact_src = f"runs/run-20261114-case/{slug}.case.card.txt" + sha = hashlib.sha256(card_path.encode("utf-8")).hexdigest() + toml = ('schema = "paperkit-fact/3.0"\n\n[[fact]]\nid = "CASE1-AMT-COMP"\n' + 'claim = "违法解除劳动合同赔偿金"\nvalue = "146160"\n' + f'source = "{fact_src}"\nsource_sha256 = "sha256:{sha}"\n' + 'locator = "测试"\nconfidence = "high"\nderived_from = []\n') + with open(os.path.join(tmp, "facts", "04-case.toml"), "w", encoding="utf-8") as f: + f.write(toml) + with open(os.path.join(run, "result.json"), "w", encoding="utf-8") as f: + json.dump({"run_id": "run-20261114-case", "artifacts": [fact_src]}, + f, ensure_ascii=False) + ids = record_ids if record_ids is not None else ["CASE1-AMT-COMP"] + with open(os.path.join(run, "record.json"), "w", encoding="utf-8") as f: + json.dump({"run_id": "run-20261114-case", "facts": ids}, f, ensure_ascii=False) + return tmp + + def test_clean_is_green(self): + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp) + findings = verify_case(tmp) + self.assertEqual([x.code for x in findings], [], findings) + + def test_official_text_tampered_is_red(self): + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp) + p = os.path.join(tmp, "runs", "run-20261114-case", "official", + "张某诉某公司劳动争议案.txt") + s = _read(p).replace("146160", "146161") + _write(p, s) + findings = verify_case(tmp) + self.assertIn("CASE_OFFICIAL_HASH_MISMATCH", [x.code for x in findings]) + + def test_card_amount_inflated_is_red(self): + """卡片里的金额被改大(且账里的哈希同步改)⇒ 必须判红,不能只黄。""" + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp) + p = os.path.join(tmp, "runs", "run-20261114-case", + "张某诉某公司劳动争议案.case.card.txt") + s = _read(p).replace("146160", "999999") + _write(p, s) + findings = verify_case(tmp) + self.assertIn("CASE_AMOUNT_MISMATCH", [x.code for x in findings]) + + def test_card_embedded_text_diverged_is_red(self): + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp) + p = os.path.join(tmp, "runs", "run-20261114-case", + "张某诉某公司劳动争议案.case.card.txt") + s = _read(p).replace("基本案情", "基本案由") + _write(p, s) + findings = verify_case(tmp) + self.assertIn("CASE_CARD_TEXT_DIVERGED", [x.code for x in findings]) + + def test_value_not_in_official_is_red(self): + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp) + f = os.path.join(tmp, "facts", "04-case.toml") + s = _read(f).replace('value = "146160"', 'value = "888888"') + _write(f, s) + findings = verify_case(tmp) + self.assertIn("CASE_VALUE_NOT_IN_OFFICIAL", [x.code for x in findings]) + + def test_date_normalisation_accepts_chinese_format(self): + """卡片写 2023.10.20,正文写 2023年10月20日 ⇒ 必须判为存在。""" + from factscribe_legal.case_verify import _date_present, _dates_in + d = _dates_in(self.OFFICIAL) + self.assertTrue(_date_present("2023.10.20", self.OFFICIAL, d)) + self.assertTrue(_date_present("2023-10-20", self.OFFICIAL, d)) + self.assertFalse(_date_present("2024.10.20", self.OFFICIAL, d)) + + def test_evidence_chain_broken_is_red(self): + from factscribe_legal.case_verify import verify_case + with tempfile.TemporaryDirectory() as tmp: + self._project(tmp, record_ids=["CASE1-NOPE"]) + findings = verify_case(tmp) + self.assertIn("CASE_CHAIN_BROKEN", [x.code for x in findings]) + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/factscribe-legal/tests/test_toml_compat.py b/integrations/factscribe-legal/tests/test_toml_compat.py new file mode 100644 index 0000000..d4bc38e --- /dev/null +++ b/integrations/factscribe-legal/tests/test_toml_compat.py @@ -0,0 +1,204 @@ +"""TOML 读取层的交叉校验。 + +背景:上游 paperkit 的 CI 矩阵含 Python 3.10,而标准库 `tomllib` 是 3.11 才有。 +本包用一个「优先复用上游、否则自带极简解析器」的读取层解决(见 `_toml.py`)。 + +风险在于:**两个解析器对同一文件给出不同结果** ⇒ 同一份事实账在不同机器上 +判出不同的门禁结论 ⇒ 不可复现。所以这里必须有交叉校验: +自带极简解析器 vs 标准库 tomllib vs 上游 factscribe.config.load_toml, +三者对同一份样本必须给出**完全相同**的 dict。 +""" +import os +import subprocess +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PKG_ROOT = HERE.parent +sys.path.insert(0, str(PKG_ROOT)) + +from factscribe_legal._toml import ( # noqa: E402 + TomlSubsetError, load_toml, mini_loads, parser_name, +) + +SAMPLE = HERE / "fixtures" / "facts_sample.toml" + + +def _upstream_on(text): + """用上游 factscribe 的解析器读一段 TOML 文本(拿不到就跳过)。""" + try: + from factscribe.config import _mini_toml + except Exception: + raise unittest.SkipTest("拿不到 factscribe") + return _mini_toml(text) + + + +class TestMiniParserMatchesStdlib(unittest.TestCase): + """自带极简解析器 vs 标准库 tomllib:必须逐字相同。""" + + def setUp(self): + try: + import tomllib # noqa: F401 + except ModuleNotFoundError: + self.skipTest("本解释器没有 tomllib(3.10),跳过对照") + + def test_same_result_on_sample(self): + import tomllib + text = SAMPLE.read_text(encoding="utf-8") + self.assertEqual(mini_loads(text), tomllib.loads(text)) + + def test_same_result_on_chinese_and_escapes(self): + import tomllib + text = ( + 'schema = "x"\n\n' + '[[fact]]\n' + 'id = "A"\n' + 'claim = "含\\"引号\\"与\\\\反斜杠的标题"\n' + 'value = "2018-12-29"\n' + 'note = "路径 runs/run-2026/中华人民共和国 劳动法.txt"\n' + 'n = -12\n' + 'f = 1.25\n' + 'b = true\n' + ) + self.assertEqual(mini_loads(text), tomllib.loads(text)) + + def test_comment_handling(self): + import tomllib + text = ( + "# 整行注释\n" + 'a = "有 # 号" # 行尾注释\n' + 'b = "另一个"\n' + ) + self.assertEqual(mini_loads(text), tomllib.loads(text)) + + +class TestMiniParserFailsClosed(unittest.TestCase): + """子集之外的写法必须报错,不许猜。""" + + def test_inline_table_rejected(self): + with self.assertRaises(TomlSubsetError): + mini_loads('a = {b = 1}\n') + + def test_unknown_value_rejected(self): + with self.assertRaises(TomlSubsetError): + mini_loads('a = 2026-11-15\n') + + def test_unclosed_string_rejected(self): + with self.assertRaises(TomlSubsetError): + mini_loads('a = "没闭合\n') + + def test_unparsable_line_rejected(self): + with self.assertRaises(TomlSubsetError): + mini_loads("这一行没有等号\n") + + +class TestLoaderDispatch(unittest.TestCase): + def test_load_toml_reads_sample(self): + data = load_toml(SAMPLE) + self.assertEqual(data["schema"], "paperkit-fact/3.0") + self.assertEqual(len(data["fact"]), 2) + self.assertEqual(data["fact"][0]["id"], "LBR-GBRQ") + self.assertIs(data["fact"][0]["dup_ok"], True) + + def test_forced_mini_env(self): + env = dict(os.environ, FACTSCRIBE_LEGAL_TOML="mini") + out = subprocess.run( + [sys.executable, "-c", + "import sys;sys.path.insert(0,%r);" + "from factscribe_legal._toml import parser_name,load_toml;" + "print(parser_name());" + "d=load_toml(%r);print(len(d['fact']))" % (str(PKG_ROOT), str(SAMPLE))], + env=env, capture_output=True, text=True, timeout=120, + ) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("mini", out.stdout) + self.assertIn("2", out.stdout) + + def test_mini_and_tomllib_give_same_verdict(self): + """3.10 兜底与 3.11+ 标准库必须读出**同一份**事实账(可复现性契约)。""" + import json + env = dict(os.environ, FACTSCRIBE_LEGAL_TOML="mini") + code = ("import sys,json;sys.path.insert(0,%r);" + "from factscribe_legal._toml import load_toml;" + "print(json.dumps(load_toml(%r), sort_keys=True, ensure_ascii=False))" + % (str(PKG_ROOT), str(SAMPLE))) + mini = subprocess.run([sys.executable, "-c", code], env=env, + capture_output=True, text=True, timeout=120) + self.assertEqual(mini.returncode, 0, mini.stderr) + std = subprocess.run([sys.executable, "-c", code], + capture_output=True, text=True, timeout=120) + self.assertEqual(std.returncode, 0, std.stderr) + self.assertEqual(json.loads(mini.stdout), json.loads(std.stdout)) + + def test_upstream_loader_agrees_on_supported_subset(self): + """上游 factscribe 的 load_toml 对**我们实际写出的子集**必须与 tomllib 一致。 + + 背景:本包没有直接复用上游解析器,因为实测上游那份 3.10 兜底 + (factscribe/config.py::_mini_toml)不认嵌套数组。这里锁住「上游在我们 + 真正用到的子集上与 tomllib 一致」这一事实 —— 若上游哪天改了方言, + 这条测试会先响。 + """ + try: + from factscribe.config import load_toml as upstream + except Exception: + self.skipTest("当前环境拿不到 factscribe(独立运行),跳过") + import tomllib + text = SAMPLE.read_text(encoding="utf-8") + # 只取我们事实账真正写出的形态:字符串 + 空数组 + 布尔 + 数字 + subset = ( + 'schema = "paperkit-fact/3.0"\n\n' + '[[fact]]\n' + 'id = "A"\n' + 'value = "2018-12-29"\n' + 'derived_from = []\n' + 'dup_ok = true\n' + ) + self.assertEqual(upstream(SAMPLE), tomllib.loads(text)) + self.assertEqual(upstream.__module__, "factscribe.config") + self.assertEqual(_upstream_on(subset), tomllib.loads(subset)) + + +class TestWithoutTomllib(unittest.TestCase): + """把 tomllib 从 import 里掐掉,包仍须可用(3.10 的真实处境)。""" + + def test_import_and_load_without_tomllib(self): + code = ( + "import sys\n" + "sys.modules['tomllib'] = None\n" + "sys.path.insert(0, %r)\n" + "from factscribe_legal.verify import load_facts\n" + "print('import-ok')\n" % str(PKG_ROOT) + ) + out = subprocess.run([sys.executable, "-c", code], + capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("import-ok", out.stdout) + + def test_reads_facts_without_tomllib(self): + import shutil + import tempfile + tmp = tempfile.mkdtemp() + try: + facts_dir = Path(tmp) / "facts" + facts_dir.mkdir() + shutil.copy(SAMPLE, facts_dir / "01-sample.toml") + code = ( + "import sys\n" + "sys.modules['tomllib'] = None\n" + "sys.path.insert(0, %r)\n" + "from factscribe_legal.verify import load_facts\n" + "f = load_facts(%r)\n" + "print(len(f), f[0]['id'])\n" % (str(PKG_ROOT), tmp) + ) + out = subprocess.run([sys.executable, "-c", code], + capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("2 LBR-GBRQ", out.stdout) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +if __name__ == "__main__": + unittest.main()