#!/usr/bin/env python3
"""账本无关的「国标八项字段面」检查 — 检查规范 + 适配器契约 + 三种账本读取。

## 为什么要把这件事从库里拆出来

原来的 standard_field_coverage.py 只能读我们自己的 ~/.governance/governance.db：
字段清单写死成 audit_log.agent_id 这样的物理名，判定 SQL 也直接绑在那些列上。
自己用没问题，但诊断这门生意卖的是「拿客户的账跑一遍」—— 客户的账不会长成我们的
schema，可能是一份 CSV，也可能是另一套表名列名的 SQLite。

于是把一件事拆成三层，任何一层单独变都不会污染另外两层：

  1. 检查规范（SPEC，本文件的 ITEMS）—— 只谈**逻辑字段**：身份要有主体、托付主体、
     授权承诺、模型工件；不談列叫什么。每项带适用行定义（applies）与非空率阈值。
  2. 适配器契约（Adapter）—— 一份 JSON，声明「客户账里的哪个表哪一列 = 哪个逻辑字段」。
     **映射不上就是无字段，不许猜**：没有映射的逻辑字段一律判 missing，不按名字相似度
     兜底，不用默认值填充，不做推断。
  3. 读取实现（Ledger）—— SQLite / CSV / JSONL 三种入口，统一落成一条 SQLite 连接，
     再走同一个查询与判定路径。三份读取器不各写一份判定逻辑。

## 三类判定（沿用，不发明第四类）

- `covered`    字段在、适用行上非空率达阈值 → 有字段可出示
- `unproven`   字段在，但非空率不到阈值（或适用行 0 行） → 有字段出示不了
- `missing`    缺字段（含未映射、整张表不存在） → 无字段

## 用法

    # 我们自己的库（恒等适配器）
    python3 evidence_ledger.py --ledger ~/.governance/governance.db \\
        --adapter scripts/adapters/governance-db.json --markdown

    # 客户的 CSV（列名完全不同，缺字段）
    python3 evidence_ledger.py --ledger tests/fixtures/foreign-ledger \\
        --adapter scripts/adapters/foreign-csv.example.json --grid

    # 只出契约表（八项 × 需要哪些证据 × 这份账本映射到什么 × 缺失时判什么）
    python3 evidence_ledger.py --ledger <...> --adapter <...> --contract

退出码：0 出表；1 --require-full 下有缺口；2 账本或适配器读不出来。
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import re
import sqlite3
import sys
from dataclasses import dataclass, field
from pathlib import Path

DEFAULT_WINDOW = 5000
DEFAULT_MIN_FILL = 0.90

# 视为「空」的字面值：schema 默认值就是这些，别把默认值当成有值
EMPTY_LITERALS: tuple[str, ...] = ("", "[]", "{}", "null", "none", "0")

_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")


class AdapterError(Exception):
    """适配器读不出来或声明非法 —— 一律终止，不做兜底猜测。"""


def _ident(name: str) -> str:
    """把表名/列名安全地引起来。适配器是外部输入，不做拼接注入。"""
    if not isinstance(name, str) or not _IDENT.match(name):
        raise AdapterError(f"非法标识符: {name!r}（只允许字母/数字/下划线）")
    return '"' + name + '"'


# ── 1. 检查规范 ─────────────────────────────────────────────────────────────


@dataclass(frozen=True)
class Pred:
    """逻辑谓词。写成结构而不是 SQL 字符串，才能通过适配器翻译到客户的列名上。

    op: eq / in / is_empty（空 = NULL 或默认字面值）
    """

    field: str
    op: str
    values: tuple[str, ...] = ()

    def label(self) -> str:
        if self.op == "eq":
            return f"{self.field} = {self.values[0]}"
        if self.op == "in":
            return f"{self.field} ∈ {{{', '.join(self.values)}}}"
        if self.op == "is_empty":
            return f"{self.field} 为空"
        return f"{self.field} {self.op}"


@dataclass(frozen=True)
class FieldSpec:
    table: str          # 逻辑实体
    column: str         # 逻辑字段
    needs_value: bool = True
    # 这一格对哪些行才有意义。分母错会把「这行不需要填」算成「填不出来」。
    applies_to: tuple[Pred, ...] = ()
    # 0 行适用时是否算「不适用即无需出示」（True）还是「拿不出」（False）
    na_when_empty: bool = False
    why: str = ""

    @property
    def ref(self) -> str:
        return f"{self.table}.{self.column}"

    def applies_label(self) -> str:
        return " 且 ".join(p.label() for p in self.applies_to) if self.applies_to else "全部行"


@dataclass(frozen=True)
class Item:
    code: int
    title: str
    fields: tuple[FieldSpec, ...]
    remedy: str
    # "row" = 逐行字段（按非空率判）；"event" = 事件型（要事件发生过且事件行有值）
    kind: str = "row"
    # 需要特殊度量方式的格子（父行+子行拼着才看得全的那种）
    special: str = ""
    # 交付给外部客户时的补齐建议：只谈逻辑字段与改动代价，不提我们的库、内部路径、
    # 内部历史与时间线。外来账本读到内部路径既是泄露也是噪音（AQ-20261027-457）。
    remedy_generic: str = ""


_EXECUTED_CLASSES = ("allow", "error", "timeout", "retry_exhausted")


ITEMS: tuple[Item, ...] = (
    Item(
        1,
        "身份标识",
        (
            FieldSpec("audit_log", "agent_id"),
            FieldSpec("audit_log", "subject_principal",
                      why="替谁执行 —— 委托人口径，任何动作都应该有"),
            FieldSpec("audit_log", "authority_commitment"),
            FieldSpec("audit_log", "model_artifact_source",
                      why="provider id / local；API 与自有权重路径都该有"),
            FieldSpec("audit_log", "model_artifact_revision",
                      why="决策当时使用的声明修订（通常 = model）"),
            FieldSpec("audit_log", "model_artifact_digest",
                      applies_to=(Pred("model_artifact_source", "eq", ("local",)),),
                      na_when_empty=True,
                      why="只在自有权重时才有；API 路径空是如实，不是缺陷"),
        ),
        "四路身份（主体 / 被代表主体 / 授权承诺 / 模型工件）已齐：2026-10-26 起写入端"
        "（adapter + observer）同一动作内同时落 subject_principal 与 artifact source/revision。"
        "权重摘要只在自有权重时要求 —— 语义见 models.py，别为 API 路径伪造摘要。",
        remedy_generic="四路身份（主体 / 被代表主体 / 授权承诺 / 模型工件）应齐。"
                       "权重摘要只在自有权重时才有要求：这一格为空时先确认部署是否使用自有权重，"
                       "API 路径为空是如实，不要为它伪造摘要。",
    ),
    Item(
        2,
        "系统权限调用",
        (
            FieldSpec("audit_log", "decision"),
            FieldSpec("audit_log", "scope_grant_id"),
            FieldSpec("scope_grants", "id", needs_value=False),
        ),
        "decision 只记了结论，没记依据。最少补齐：写入时把命中的 scope_grants.id 落进现有"
        " anomaly_flags 之外的独立字段（需一次 schema 变更），或在 decision_reason 里落 "
        "grant_id + 规则行号（零 schema 变更，可当场做）。",
        remedy_generic="决策字段若只记结论不记依据，两种补法：把命中的授权记录 id 落到一个独立字段"
                       "（需要一次 schema 变更），或把授权 id 与命中规则写进已有的原因字段"
                       "（零 schema 变更，改动最小）。",
    ),
    Item(
        3,
        "工具调用",
        (
            FieldSpec("audit_log", "tool_name"),
            FieldSpec("audit_log", "input_hash"),
            FieldSpec("audit_log", "output_hash",
                      applies_to=(Pred("parent_id", "is_empty"),
                                  Pred("outcome_class", "in", _EXECUTED_CLASSES)),
                      why="分母是真正执行过的调用（deny/not_invoked 无输出可言），"
                          "证据在配对子行；父行+子行拼着才算出示"),
        ),
        "无需补齐字段：工具名 + 输入/输出摘要三项齐全，且 2026-10-25 起已入 v2 哈希链。"
        "要盯的是输出摘要的**生产者覆盖率** —— 执行过却配不上子行的调用就是丢证据。",
        special="output_pairing",
        remedy_generic="三项齐全，无需补字段。要盯的是输出摘要的**生产者覆盖率** —— "
                       "已经执行、却配不上输出摘要的调用，就是丢证据。",
    ),
    Item(
        4,
        "数据收集使用",
        (
            FieldSpec("audit_log", "data_class"),
            FieldSpec("audit_log", "data_purpose"),
        ),
        "无数据分类与用途字段。最少补齐：compliance_tags 不收数据类别；建议先复用 "
        "compliance_tags 的标签语法写入 data:<类别>，把用途写进 decision_reason，"
        "避免为起草中的标准先做破坏性 schema 变更。",
        remedy_generic="缺数据分类与用途两列。最小改法：复用已有的标签字段写入 data:<类别>，"
                       "把用途写进已有的原因字段，不必为标准里的新要求先做破坏性 schema 变更。",
    ),
    Item(
        5,
        "高风险操作人工介入",
        (
            FieldSpec("audit_log", "approval_id",
                      applies_to=(Pred("decision", "in", ("step_up", "defer")),),
                      why="分母是升级到人审的调用 —— 没升级过的行不需要审批回指"),
            FieldSpec("approval_bindings", "approver"),
            FieldSpec("approval_bindings", "consumed_at", needs_value=False),
        ),
        "审批表存在但三个断点：运行账行没有 approval_id 回指、审批表没有 approver 字段、"
        "活库零行。最少补齐：先给审批表加 approver 与 approved_at 两列并让高风险调用"
        "强制写入，再加运行账回指列（一次 schema 变更，动的是链外字段）。"
        "零行先判因：审批登记只在 src/governance/plugin.py 的升级路径里被调用，"
        "活库 hook（~/.hermes/plugins/governance-agent）没接这条腿 → 管道未跑，不是确实没事件。",
        remedy_generic="三个断点：运行账行没有审批回指、审批表没有审批人字段、审批表零行。"
                       "补法：先给审批表加审批人与审批时间两列并让高风险调用强制写入，"
                       "再加运行账的回指列（一次 schema 变更，动的是链外字段）。"
                       "审批表为零行时先分清是「确实没发生人审」还是「登记链路没接到写入端」——"
                       "零行不等于零事件。",
    ),
    Item(
        6,
        "输入输出安全防护",
        (
            FieldSpec("audit_log", "input_guard"),
            FieldSpec("audit_log", "output_guard"),
            FieldSpec("audit_log", "anomaly_flags"),
        ),
        "只有哈希摘要（防篡改，不防不安全内容），没有防护判定字段。最少补齐：把筛查规则"
        "命中的 rule id 与判定写进 anomaly_flags（该字段已入 v2 链，零 schema 变更），"
        "语义从「异常」扩到「防护判定」需要在标签命名上先定契约。",
        remedy_generic="只有哈希摘要（防篡改，不防不安全内容），没有防护判定字段。"
                       "可把筛查规则命中的 rule id 与判定写进已有的标签字段（零 schema 变更），"
                       "但这等于把标签语义从「异常」扩到「防护判定」，先定命名契约再写。",
    ),
    Item(
        7,
        "日志留存与动态监测",
        (
            FieldSpec("audit_log", "timestamp"),
            FieldSpec("audit_log", "current_hash"),
            FieldSpec("audit_log", "retention_until"),
            FieldSpec("anomalies", "rule", needs_value=False),
        ),
        "时间戳与链值可出示，留存期限无字段、监测表活库零行。最少补齐：留存策略先落 "
        "governance_config（如 retention_days），运行账加 retention_until 派生列；"
        "监测侧先确认 anomalies 的写入路径是否还在跑。",
        remedy_generic="时间与链值可出示，缺的是留存期限字段与监测表。补法：留存策略先落配置表"
                       "（如 retention_days），运行账加一列由策略派生的到期时间；"
                       "监测表若为零行，先确认它的写入路径是否还在跑，再谈字段。",
    ),
    Item(
        8,
        "异常阻断与紧急关停",
        (
            FieldSpec("audit_log", "enforcement_action",
                      applies_to=(Pred("tool_name", "eq", ("governance.write_freeze",)),),
                      why="分母是关停/解冻动作行 —— 普通调用不需要有强制动作"),
            FieldSpec("kill_switch_events", "id"),
        ),
        "控制面（write_freeze）与运行账已打通：关停/解冻各写一行 tool_name="
        "governance.write_freeze、enforcement_action=freeze/unfreeze，同时落 kill_switch_events。"
        "事件型项要的是「至少一次关停落账且字段有值」，不是「每行都关停一次」。",
        kind="event",
        remedy_generic="事件型项要的是「至少一次关停落账，且那一行的字段有值」，"
                       "不是「每一行都关停一次」。控制面的关停动作与事件表要同时落到账上。",
    ),
)

# 逐行检查的实体：窗口只对它有意义（另几个是登记表，全表计数）
ROW_ENTITY = "audit_log"


# ── 2. 适配器契约 ───────────────────────────────────────────────────────────


@dataclass
class Adapter:
    """逻辑字段 → 客户账本物理位置的映射。

    map 里没有的键 = 无字段。identity=True 时物理位置恒等于逻辑位置（我们自己的库）。
    """

    name: str
    source: dict
    mapping: dict[str, tuple[str, str]]
    identity: bool = False
    notes: str = ""

    def resolve(self, table: str, column: str) -> tuple[str, str] | None:
        if self.identity:
            return (table, column)
        return self.mapping.get(f"{table}.{column}")

    def mapped(self, table: str, column: str) -> bool:
        return self.resolve(table, column) is not None

    def entities(self) -> set[str]:
        if self.identity:
            return set()
        return {k.split(".", 1)[0] for k in self.mapping}


def load_adapter(path: Path) -> Adapter:
    try:
        raw = json.loads(Path(path).read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise AdapterError(f"适配器读不出来 {path}: {exc}") from exc
    if not isinstance(raw, dict):
        raise AdapterError("适配器顶层必须是对象")
    source = raw.get("source") or {}
    if raw.get("map") == "identity":
        return Adapter(raw.get("name", Path(path).stem), source, {}, identity=True,
                       notes=raw.get("notes", ""))
    mapping: dict[str, tuple[str, str]] = {}
    for key, target in (raw.get("map") or {}).items():
        if "." not in key:
            raise AdapterError(f"映射键必须是 逻辑表.逻辑字段: {key!r}")
        if isinstance(target, str):
            table, column = key.split(".", 1)[0], target
        elif isinstance(target, dict):
            table = target.get("table") or key.split(".", 1)[0]
            column = target.get("column")
            if not column:
                raise AdapterError(f"映射 {key} 缺 column")
        else:
            raise AdapterError(f"映射 {key} 的值必须是列名字符串或 {{table,column}}")
        # 装载即校验标识符：适配器是外部输入，非法名一律当场拒，不留到查询期才炸
        _ident(table), _ident(column)
        mapping[key] = (table, column)
    return Adapter(raw.get("name", Path(path).stem), source, mapping,
                   notes=raw.get("notes", ""))


# ── 3. 读取实现 ─────────────────────────────────────────────────────────────


class Ledger:
    """一条 SQLite 连接 + 一份适配器。三种入口最后都落成这个形状。"""

    def __init__(self, conn: sqlite3.Connection, adapter: Adapter, label: str):
        self.conn = conn
        self.adapter = adapter
        self.label = label

    def close(self) -> None:
        self.conn.close()

    def __enter__(self) -> "Ledger":
        return self

    def __exit__(self, *exc) -> None:
        self.close()


def open_sqlite(path: Path, adapter: Adapter) -> Ledger:
    """外来 SQLite：只读打开，不写客户库。"""
    if not Path(path).exists():
        raise FileNotFoundError(str(path))
    conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
    return Ledger(conn, adapter, f"sqlite:{Path(path).name}")


def _columns(conn: sqlite3.Connection, table: str) -> set[str]:
    try:
        rows = conn.execute(f"PRAGMA table_info({_ident(table)})").fetchall()
    except (sqlite3.Error, AdapterError):
        return set()
    return {r[1] for r in rows}


def _load_rows(conn: sqlite3.Connection, table: str, rows: list[dict]) -> None:
    """把 CSV/JSONL 的行装进内存库。列按文件名如实建，不改名、不补列。"""
    if not rows:
        conn.execute(f"CREATE TABLE {_ident(table)} (__empty TEXT)")
        return
    cols: list[str] = []
    for row in rows:
        for k in row:
            if k not in cols:
                cols.append(k)
    for c in cols:
        _ident(c)  # 列名非法就直接拒（客户 CSV 里带空格/中文列名要显式改名）
    conn.execute(
        f"CREATE TABLE {_ident(table)} ({', '.join(f'{_ident(c)} TEXT' for c in cols)})"
    )
    conn.executemany(
        f"INSERT INTO {_ident(table)} ({', '.join(_ident(c) for c in cols)}) "
        f"VALUES ({','.join('?' * len(cols))})",
        [tuple(row.get(c) for c in cols) for row in rows],
    )
    conn.commit()


def _files_of(source: dict, adapter: Adapter) -> dict[str, str]:
    """source 里声明的 逻辑实体 → 文件名。允许单文件简写。"""
    if "files" in source:
        return dict(source["files"])
    path, table = source.get("path"), source.get("table")
    if not path or not table:
        raise AdapterError("csv/jsonl 适配器必须给 files 或 (path + table)")
    return {table: path}


def load_delimited(root: Path, adapter: Adapter, kind: str) -> Ledger:
    """CSV / JSONL 导入。每个文件装成一张表，表名由适配器指定。"""
    files = _files_of(adapter.source, adapter)
    conn = sqlite3.connect(":memory:")
    loaded = []
    for table, name in files.items():
        path = Path(name) if Path(name).is_absolute() else Path(root) / name
        if not path.exists():
            raise FileNotFoundError(str(path))
        if kind == "csv":
            with path.open(newline="", encoding="utf-8-sig") as fh:
                rows = [dict(r) for r in csv.DictReader(fh)]
        else:
            rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
        _load_rows(conn, table, rows)
        loaded.append(f"{table}←{path.name}({len(rows)})")
    return Ledger(conn, adapter, f"{kind}:{adapter.name} [{', '.join(loaded)}]")


def open_ledger(target: Path, adapter: Adapter, kind: str = "auto") -> Ledger:
    """按适配器声明（或文件后缀）选读取器。显式 --kind 优先于适配器声明 ——
    否则一份 csv 适配器配一个 sqlite 文件时，命令行给的 --kind sqlite 会被静默丢掉。"""
    declared = kind if kind != "auto" else adapter.source.get("kind", "auto")
    k = declared
    if k in ("auto", "", None):
        declared = "csv" if str(target).endswith(".csv") else (
            "jsonl" if str(target).endswith((".jsonl", ".ndjson")) else "sqlite")
    if declared == "sqlite":
        return open_sqlite(target, adapter)
    if declared in ("csv", "jsonl"):
        root = target if Path(target).is_dir() else Path(target).parent
        return load_delimited(root, adapter, declared)
    raise AdapterError(f"未知账本类型: {declared!r}")


# ── 4. 度量 ─────────────────────────────────────────────────────────────────


@dataclass
class FieldResult:
    table: str
    column: str
    exists: bool
    rows: int = 0
    non_empty: int = 0
    na: bool = False
    note: str = ""
    # 适配器把它映射到了哪里（None = 未映射 → 无字段）
    physical: str | None = None
    # 分母口径被降级（谓词里的字段没映射上）时必须显式标注，不能静默算错
    degraded: str = ""

    @property
    def fill(self) -> float | None:
        if not self.exists or not self.rows:
            return None
        return self.non_empty / self.rows


@dataclass
class ItemResult:
    code: int
    title: str
    verdict: str
    fields: list[FieldResult] = field(default_factory=list)
    remedy: str = ""
    kind: str = "row"
    # 交付件用这份：schema 无关、不含内部路径与内部历史
    remedy_generic: str = ""

    @property
    def present_columns(self) -> int:
        return sum(1 for f in self.fields if f.exists)


def _judge(fr: FieldResult, min_fill: float) -> str:
    if not fr.exists:
        return "missing"
    if fr.na:
        return "covered"
    if fr.fill is None:
        return "unproven"
    return "covered" if fr.fill >= min_fill else "unproven"


# 空值字面量是固定常量，直接内联成 SQL 字面值：一旦用占位符，父行/子行两处
# 各要 6 个参数，漏传一处就整条查询崩（2026-10-27 踩过）。常量内联不引入注入面。
_EMPTY_IN = ",".join("'" + v.replace("'", "''") + "'" for v in EMPTY_LITERALS)


def _has_value_sql(col: str) -> str:
    return (f"({col} IS NULL OR LOWER(TRIM(CAST({col} AS TEXT))) "
            f"NOT IN ({_EMPTY_IN}))")


def _pred_sql(preds: tuple[Pred, ...], adapter: Adapter, alias: str | None) -> tuple[str, list, str]:
    """把逻辑谓词编译成物理 SQL。返回 (SQL片段, 参数, 降级说明)。"""
    parts: list[str] = []
    params: list = []
    degraded: list[str] = []
    for pred in preds:
        target = adapter.resolve(ROW_ENTITY, pred.field)
        if target is None:
            degraded.append(pred.label())
            continue
        col = (alias + "." if alias else "") + _ident(target[1])
        if pred.op == "eq":
            parts.append(f"TRIM(CAST({col} AS TEXT)) = ?")
            params.append(pred.values[0])
        elif pred.op == "in":
            parts.append(f"TRIM(CAST({col} AS TEXT)) IN ({','.join('?' * len(pred.values))})")
            params.extend(pred.values)
        elif pred.op == "is_empty":
            parts.append(f"({col} IS NULL OR TRIM(CAST({col} AS TEXT)) IN ({_EMPTY_IN}))")
        else:
            raise AdapterError(f"未知谓词算子: {pred.op}")
    return " AND ".join(parts), params, "；".join(degraded)


def _events_table(adapter: Adapter) -> str | None:
    """逐行检查用哪个物理表 —— 由任一 audit_log 映射反推；无映射则视为无账本。"""
    if adapter.identity:
        return ROW_ENTITY
    for key, (table, _col) in adapter.mapping.items():
        if key.startswith(ROW_ENTITY + "."):
            return table
    return None


@dataclass
class Scope:
    """一次读数实际量了什么 —— 必须能被凭头部参数原样重建（AQ-20261028-001）。

    没有上界时，新行写入会把最老的行挤出 window，同一份活库、同一条命令隔几小时
    跑出三个不同的数。上界（timestamp 或 rowid）就是把这句「客户重跑拿到同一个数」
    变成真的那一步。rowids=None 表示没走逐行窗口（全表 / 读不出 rowid）。
    """

    table: str | None = None
    window: int = DEFAULT_WINDOW
    since: str | None = None
    until: str | None = None
    until_rowid: int | None = None
    rowids: list[int] | None = None
    # 上界过滤后、LIMIT 前的命中行数：用来区分「窗口装得下」和「装不下被截了」
    matched: int | None = None
    note: str = ""

    @property
    def lo(self) -> int | None:
        return min(self.rowids) if self.rowids else None

    @property
    def hi(self) -> int | None:
        return max(self.rowids) if self.rowids else None

    def params(self) -> str:
        """能原样贴回去重跑的参数串。没显式给上界时，把观测到的上界 rowid 钉进去 ——
        这样交付件里任何一次读数，都能凭这一行复算出同一个数（AQ-20261028-001）。"""
        out = [f"--window {self.window}", "--min-fill {min_fill}"]
        if self.since:
            out.append(f"--since {self.since}")
        if self.until:
            out.append(f"--until {self.until}")
        if self.until_rowid is not None:
            out.append(f"--until-rowid {self.until_rowid}")
        elif self.hi is not None:
            out.append(f"--until-rowid {self.hi}")
        return " ".join(out)

    def label(self) -> str:
        scope = f"最近 {self.window} 行" if self.window else "全表"
        parts = [scope]
        if self.since:
            parts.append(f"since={self.since}")
        if self.until:
            parts.append(f"until={self.until}")
        pin = self.until_rowid if self.until_rowid is not None else self.hi
        if pin is not None:
            parts.append(f"上界 rowid={pin}")
        if self.rowids:
            parts.append(f"rowid {self.lo}..{self.hi}（{len(self.rowids)} 行）")
            if self.matched is not None and self.matched > len(self.rowids):
                parts.append(f"上界内命中 {self.matched} 行，只取最新 {len(self.rowids)} 行")
        elif self.note:
            parts.append(self.note)
        return " · ".join(parts)

    @property
    def bounded(self) -> bool:
        return bool(self.since or self.until) or self.until_rowid is not None

    @property
    def sliding(self) -> bool:
        """读数会不会因为新行写入而变化。上界给了就不会；没给上界但窗口装得下全表、
        且来源是静态文件，也不会。"""
        if self.bounded or self.rowids is None:
            return False
        return self.matched is not None and self.matched > len(self.rowids)


def resolve_scope(ledger: Ledger, window: int, since: str | None = None,
                  until: str | None = None, until_rowid: int | None = None) -> Scope:
    """把窗口参数落成一份可记录、可复算的读数边界。"""
    adapter, conn = ledger.adapter, ledger.conn
    table = _events_table(adapter)
    sc = Scope(table=table, window=window, since=since, until=until,
               until_rowid=until_rowid)
    if not table:
        sc.note = "账本无 audit_log 实体 → 不做逐项窗口"
        return sc
    if _columns(conn, table) == set():
        sc.note = f"账本无 {ROW_ENTITY} 实体"
        return sc
    where, params = "", []
    for bound, op, key in ((since, ">=", "--since"), (until, "<=", "--until")):
        if not bound:
            continue
        ts = adapter.resolve(ROW_ENTITY, "timestamp")
        if ts is None:
            sc.note = f"{key} 需要 timestamp 映射；未映射 → 退回全表"
            return sc
        where += (" AND " if where else " WHERE ") + f"{_ident(ts[1])} {op} ?"
        params.append(bound)
    if until_rowid is not None:
        where += (" AND " if where else " WHERE ") + "rowid <= ?"
        params.append(int(until_rowid))
    if not window and not where:
        sc.note = "全表（未给窗口与上界）"
        return sc
    try:
        sc.matched = conn.execute(
            f"SELECT COUNT(*) FROM {_ident(table)}{where}", tuple(params)
        ).fetchone()[0]
        sql = f"SELECT rowid FROM {_ident(table)}{where} ORDER BY rowid DESC"
        args: tuple = tuple(params)
        if window:
            sql += " LIMIT ?"
            args = (*params, window)
        sc.rowids = [r[0] for r in conn.execute(sql, args)]
        return sc
    except sqlite3.Error as exc:  # WITHOUT ROWID 表 / 视图
        sc.note = f"窗口取不出 rowid({exc}) → 退回全表"
        return sc


def _scope(ledger: Ledger, window: int, since: str | None) -> tuple[list[int] | None, str]:
    """老调用面：只关心 (rowid 列表, 降级说明)。"""
    sc = resolve_scope(ledger, window, since)
    return sc.rowids, sc.note


def _count_window(conn, table: str, ids: list[int], spec: FieldSpec, adapter: Adapter,
                  alias: str | None = None) -> tuple[int, int, str]:
    phys = adapter.resolve(spec.table, spec.column)
    assert phys is not None
    pred_sql, pred_params, degraded = _pred_sql(spec.applies_to, adapter, alias)
    prefix = (alias + ".") if alias else ""
    where = f"{prefix}rowid IN ({','.join('?' * len(ids))})"
    if pred_sql:
        where += f" AND {pred_sql}"
    col = prefix + _ident(phys[1])
    total = conn.execute(
        (f"SELECT COUNT(*) FROM {_ident(table)} {alias} " if alias else
         f"SELECT COUNT(*) FROM {_ident(table)} ") + f"WHERE {where}",
        (*ids, *pred_params),
    ).fetchone()[0]
    non_empty = conn.execute(
        (f"SELECT COUNT(*) FROM {_ident(table)} {alias} " if alias else
         f"SELECT COUNT(*) FROM {_ident(table)} ") + f"WHERE {where} AND {_has_value_sql(col)}",
        (*ids, *pred_params),
    ).fetchone()[0]
    return total, non_empty, degraded


def _count_pairing(conn, table: str, ids: list[int], spec: FieldSpec, adapter: Adapter
                   ) -> tuple[int, int, str]:
    """工具调用项：父行 + 配对子行拼着才算出示。"""
    out = adapter.resolve(spec.table, "output_hash")
    parent = adapter.resolve(spec.table, "parent_id")
    ident = adapter.resolve(spec.table, "id")
    assert out is not None
    pred_sql, pred_params, degraded = _pred_sql(spec.applies_to, adapter, "p")
    where = f"p.rowid IN ({','.join('?' * len(ids))})"
    if pred_sql:
        where += f" AND {pred_sql}"
    total = conn.execute(
        f"SELECT COUNT(*) FROM {_ident(table)} p WHERE {where}", (*ids, *pred_params)
    ).fetchone()[0]
    col = _has_value_sql(f'p.{_ident(out[1])}')
    if parent is not None and ident is not None:
        child = (f"EXISTS (SELECT 1 FROM {_ident(table)} ch WHERE "
                 f"ch.{_ident(parent[1])} = p.{_ident(ident[1])} AND {_has_value_sql('ch.' + _ident(out[1]))})")
    else:
        child = "0"
        degraded = "；".join(x for x in (degraded,
                                         "父行/子行回指未映射 → 只认父行自带摘要") if x)
    non_empty = conn.execute(
        f"SELECT COUNT(*) FROM {_ident(table)} p WHERE {where} AND ({col} OR {child})",
        (*ids, *pred_params),
    ).fetchone()[0]
    return total, non_empty, degraded


def _count_table(conn, spec: FieldSpec, adapter: Adapter) -> tuple[bool, int, int]:
    """登记表类字段（scope_grants / approval_bindings / anomalies / kill_switch_events）。"""
    phys = adapter.resolve(spec.table, spec.column)
    if phys is None:
        return False, 0, 0
    cols = _columns(conn, phys[0])
    if phys[1] not in cols:
        return False, 0, 0
    total = conn.execute(f"SELECT COUNT(*) FROM {_ident(phys[0])}").fetchone()[0]
    non_empty = conn.execute(
        f"SELECT COUNT(*) FROM {_ident(phys[0])} WHERE {_has_value_sql(_ident(phys[1]))}",
    ).fetchone()[0]
    return True, total, non_empty


def measure(ledger: Ledger, window: int = DEFAULT_WINDOW, min_fill: float = DEFAULT_MIN_FILL,
            since: str | None = None, until: str | None = None,
            until_rowid: int | None = None) -> list[ItemResult]:
    """对任意账本逐项测量。未映射的字段一律 missing，不做名字相似度兜底。"""
    return measure_with_scope(ledger, window, min_fill, since, until, until_rowid)[0]


def measure_with_scope(ledger: Ledger, window: int = DEFAULT_WINDOW,
                       min_fill: float = DEFAULT_MIN_FILL, since: str | None = None,
                       until: str | None = None, until_rowid: int | None = None
                       ) -> tuple[list[ItemResult], Scope]:
    adapter, conn = ledger.adapter, ledger.conn
    scope = resolve_scope(ledger, window, since, until, until_rowid)
    ids = scope.rowids
    schema: dict[str, set[str]] = {}

    def cols_of(table: str) -> set[str]:
        if table not in schema:
            schema[table] = _columns(conn, table)
        return schema[table]

    out: list[ItemResult] = []
    for item in ITEMS:
        results: list[FieldResult] = []
        for spec in item.fields:
            phys = adapter.resolve(spec.table, spec.column)
            if phys is None:
                results.append(FieldResult(spec.table, spec.column, exists=False,
                                           note=spec.why, physical=None))
                continue
            # 必须先核对物理列真的存在：SQLite 对不存在的双引号标识符会退化成字符串
            # 字面值（legacy DQS），查询不报错、结果恒为「有值」—— 缺字段会被算成
            # 100% 可出示。这一条 2026-10-27 实测踩过。
            if phys[1] not in cols_of(phys[0]):
                results.append(FieldResult(
                    spec.table, spec.column, exists=False, note=spec.why,
                    physical=f"{phys[0]}.{phys[1]}",
                    degraded="映射到的列不存在",
                ))
                continue
            if spec.table == ROW_ENTITY and ids is not None:
                if item.special == "output_pairing" and spec.column == "output_hash":
                    total, non_empty, degraded = _count_pairing(conn, phys[0], ids, spec, adapter)
                else:
                    total, non_empty, degraded = _count_window(conn, phys[0], ids, spec, adapter)
                results.append(FieldResult(
                    spec.table, spec.column, True, total, non_empty,
                    na=(total == 0 and spec.na_when_empty), note=spec.why,
                    physical=f"{phys[0]}.{phys[1]}", degraded=degraded,
                ))
            else:
                exists, total, non_empty = _count_table(conn, spec, adapter)
                results.append(FieldResult(
                    spec.table, spec.column, exists, total, non_empty, note=spec.why,
                    physical=f"{phys[0]}.{phys[1]}",
                    degraded="" if exists else "映射到不存在的表/列",
                ))
        scores: list[str] = []
        for spec, fr in zip(item.fields, results):
            if spec.needs_value is False and fr.exists:
                scores.append("covered")   # 「只需存在」的格子不拿非空率判
            else:
                scores.append(_judge(fr, min_fill))
        if all(s == "covered" for s in scores):
            verdict = "covered"
        elif "missing" in scores:
            verdict = "missing"
        else:
            verdict = "unproven"
        out.append(ItemResult(item.code, item.title, verdict, results, item.remedy,
                              item.kind, item.remedy_generic))
    return out, scope


def scope_note(ledger: Ledger, window: int, since: str | None) -> str:
    return _scope(ledger, window, since)[1]


# ── 5. 渲染 ─────────────────────────────────────────────────────────────────

LABEL = {"covered": "有字段可出示", "unproven": "有字段出示不了", "missing": "无字段"}
VERDICT_RULE = {
    "covered": "全部格子 covered",
    "unproven": "无 missing，但至少一格非空率未达阈值",
    "missing": "至少一格无字段（未映射 / 表列不存在）",
}


def _lane_label(window: int, since: str | None) -> str:
    return Scope(window=window, since=since).label()


def cell_totals(results: list[ItemResult]) -> dict:
    """格级小计：项级判定是「任一字段缺即整项无字段」，会把「做到一部分」读成「什么都没做到」。

    项级结论不动，另给一格级事实：有多少格真的有行且有值。
    """
    t = {"cells": 0, "filled": 0, "empty_rows": 0, "zero_rows": 0, "unmapped": 0}
    for r in results:
        for f in r.fields:
            t["cells"] += 1
            if not f.exists:
                t["unmapped"] += 1
            elif f.rows == 0:
                t["zero_rows"] += 1
            elif f.non_empty == 0:
                t["empty_rows"] += 1
            else:
                t["filled"] += 1
    return t


def cell_line(results: list[ItemResult]) -> str:
    t = cell_totals(results)
    return (f"格级小计：**{t['filled']}/{t['cells']}** 格有行且有值 · "
            f"{t['empty_rows']} 格有行但全空 · {t['zero_rows']} 格零行（字段在、适用行 0） · "
            f"{t['unmapped']} 格无字段（未映射 / 表列不存在）")


def header_block(ledger_label: str, scope: Scope, min_fill: float,
                 adapter_label: str = "", command: str = "",
                 snapshot: str = "") -> list[str]:
    """交付件的四行头（账本 / 契约 / 命令 / 快照）+ 一行复算参数。

    全部由脚本按本次实参生成，不手写 —— 手写过的样例表与命令输出不是同一张表，
    「可复算」四个字就是空的（AQ-20261027-457）。
    """
    out = [f"账本：`{ledger_label}`"]
    if adapter_label:
        out.append(f"契约：`{adapter_label}`")
    if command:
        out.append(f"命令：`{command}`")
    stamp = f"快照：{snapshot} · " if snapshot else "快照："
    out.append(f"{stamp}窗口 {scope.label()} · 非空率阈值 {min_fill:.0%}")
    out.append(f"复算：`{scope.params().replace('{min_fill}', f'{min_fill:.2f}')}`")
    return out


def summarize(results: list[ItemResult]) -> dict:
    return {k: sum(1 for r in results if r.verdict == k)
            for k in ("covered", "unproven", "missing")}


def render_text(results: list[ItemResult], ledger_label: str, window: int,
                since: str | None = None) -> str:
    lines = [f"账本: {ledger_label}   窗口: {_lane_label(window, since)}", ""]
    for r in results:
        ok = sum(1 for f in r.fields if f.exists)
        lines.append(f"{r.code}. {r.title}: {LABEL[r.verdict]} ({ok}/{len(r.fields)} 字段在表里)")
        for f in r.fields:
            if not f.exists:
                lines.append(f"     {f.table}.{f.column}: 缺失")
                continue
            if f.na:
                lines.append(f"     {f.table}.{f.column}: 存在 不适用（0 行需要这一格）")
                continue
            fill = "—" if f.fill is None else f"{f.fill:.1%}"
            extra = f"  {f.non_empty}/{f.rows}" if f.rows else ""
            lines.append(f"     {f.table}.{f.column}: 存在 {fill}{extra}")
    c = summarize(results)
    lines += ["", f"合计 可出示 {c['covered']} / 出示不了 {c['unproven']} / 无字段 {c['missing']}"]
    return "\n".join(lines)


def render_markdown(results: list[ItemResult], ledger_label: str, window: int,
                    min_fill: float, since: str | None = None, *,
                    scope: Scope | None = None, adapter_label: str = "",
                    command: str = "", snapshot: str = "",
                    remedy_mode: str = "generic") -> str:
    """八行表。remedy_mode: generic（交付件，schema 无关）/ internal / none。"""
    c = summarize(results)
    sc = scope or Scope(window=window, since=since)
    out = header_block(ledger_label, sc, min_fill, adapter_label, command, snapshot)
    out.append("")
    with_remedy = remedy_mode != "none"
    head = "| # | 国标技术项 | 判定 | 字段（表.列，适用行非空率） |"
    rule = "|---|---|---|---|"
    if with_remedy:
        head += " 补齐方向 |"
        rule += "---|"
    out += [head, rule]
    for r in results:
        cells = []
        for f in r.fields:
            if not f.exists:
                cells.append(f"`{f.table}.{f.column}` 缺")
            elif f.na:
                cells.append(f"`{f.table}.{f.column}` 不适用")
            else:
                ratio = f" {f.non_empty}/{f.rows}" if f.rows else ""
                cells.append(f"`{f.table}.{f.column}` " + ("—" if f.fill is None else f"{f.fill:.0%}") + ratio)
        row = f"| {r.code} | {r.title} | **{LABEL[r.verdict]}** | {'；'.join(cells)} |"
        if with_remedy:
            text = r.remedy if remedy_mode == "internal" else (r.remedy_generic or r.remedy)
            row += f" {text} |"
        out.append(row)
    out.append("")
    out.append(
        f"合计：有字段可出示 **{c['covered']}** 项 / 有字段出示不了 **{c['unproven']}** 项 / "
        f"无字段 **{c['missing']}** 项。"
    )
    out.append(cell_line(results))
    out += [
        "",
        f"项级判定口径：`有字段可出示` = 全部格子有字段且适用行非空率达 {min_fill:.0%}；"
        "`有字段出示不了` = 没有缺字段，但至少一格非空率未达阈值；"
        "`无字段` = 至少一格映射不上或表列不存在。项级是「一格不满即整项不算可出示」，"
        "格级小计是逐格事实，两者不冲突。",
        f"格的分母只算**该字段适用的行**（见契约表），不是全部行；空值含 `''`/`[]`/`{{}}` 与 "
        "schema 默认值。映射不上一律判无字段，不按列名相似度猜、不用默认值填。",
    ]
    return "\n".join(out)


def render_grid(results: list[ItemResult], ledger_label: str, min_fill: float,
                adapter: Adapter | None = None, *, scope: Scope | None = None,
                window: int = DEFAULT_WINDOW, since: str | None = None,
                adapter_label: str = "", command: str = "",
                snapshot: str = "") -> str:
    """交付用：每格都写出分子/分母与物理位置，缺的格子写 0/0 + 未映射。"""
    c = summarize(results)
    sc = scope or Scope(window=window, since=since)
    out = header_block(ledger_label, sc, min_fill, adapter_label, command, snapshot)
    out += [
        "",
        "| # | 技术项 | 判定 | 逻辑字段 | 账本位置 | 分子/分母 | 空值率判据 |",
        "|---|---|---|---|---|---|---|",
    ]
    for r in results:
        for f in r.fields:
            if not f.exists:
                where = "未映射" if f.physical is None else f"`{f.physical}` 不存在"
                out.append(f"| {r.code} | {r.title} | **{LABEL[r.verdict]}** | "
                           f"`{f.table}.{f.column}` | {where} | 0/0 | 无字段 |")
                continue
            where = f"`{f.physical}`"
            ratio = f"{f.non_empty}/{f.rows}" if f.rows else "0/0"
            if f.na:
                judge = "不适用（0 行需要这一格）"
            elif f.rows == 0:
                judge = "字段在、零行 → 出示不了"
            else:
                judge = f"{f.fill:.0%} {'≥' if f.fill >= min_fill else '<'} {min_fill:.0%}"
            out.append(f"| {r.code} | {r.title} | **{LABEL[r.verdict]}** | "
                       f"`{f.table}.{f.column}` | {where} | {ratio} | {judge} |")
    out.append("")
    out.append(f"合计：可出示 **{c['covered']}** / 出示不了 **{c['unproven']}** / 无字段 **{c['missing']}**。")
    out.append(cell_line(results))
    return "\n".join(out)


def render_contract(adapter: Adapter, min_fill: float = DEFAULT_MIN_FILL) -> str:
    """契约表：八项 × 需要哪些证据 × 这份账本映射到哪里 × 缺失时判什么。"""
    out = [
        "# 契约表：八项技术项各要哪些字段",
        "",
        "这份表是判定规则的全文：左边是八项要求什么，中间是这份账本把它映射到了哪个物理列，"
        "右边是映射不上时判什么。你自己的账本照同一结构改 `map` 段，判定口径不会变。",
        "",
        f"## 适配器契约：`{adapter.name}`",
        "",
        f"来源：`{json.dumps(adapter.source, ensure_ascii=False)}`"
        + (f"　说明：{adapter.notes}" if adapter.notes else ""),
        "",
        "**规则：映射不上就是无字段，不许猜。** 没有映射的逻辑字段一律判 `missing`；"
        "不按列名相似度兜底、不用默认值填充、不从别的列推断。谓词里的字段没映射上时，"
        "分母退化为窗口全部行，并在输出里标注降级。",
        "",
        "| # | 技术项 | 需要的证据（逻辑字段） | 适用行 | 本账本映射 | 缺失时判定 | 非空率阈值 |",
        "|---|---|---|---|---|---|---|",
    ]
    for item in ITEMS:
        for spec in item.fields:
            phys = adapter.resolve(spec.table, spec.column)
            where = f"`{phys[0]}.{phys[1]}`" if phys else "**未映射 → 无字段**"
            if spec.needs_value is False:
                verdict = "字段不存在 → missing；存在即计入"
            elif spec.na_when_empty:
                verdict = "未映射 → missing；0 行适用 → covered（不适用）"
            else:
                verdict = f"未映射 → missing；非空率 <{min_fill:.0%} → unproven"
            out.append(
                f"| {item.code} | {item.title} | `{spec.ref}`"
                + (f"（{spec.why}）" if spec.why else "")
                + f" | {spec.applies_label()} | {where} | {verdict} | {min_fill:.0%} |"
            )
    out += [
        "",
        "### 每项的判定规则",
        "",
        *[f"- **{k}**（{LABEL[k]}）：{v}" for k, v in VERDICT_RULE.items()],
        "",
        f"### 缺字段统计：{sum(1 for i in ITEMS for f in i.fields if adapter.resolve(f.table, f.column) is None)}"
        f" / {sum(len(i.fields) for i in ITEMS)} 个逻辑字段在这份账本上没有落点",
    ]
    return "\n".join(out)


def render_json(results: list[ItemResult], ledger_label: str, adapter: Adapter,
                window: int, min_fill: float, since: str | None,
                *, scope: Scope | None = None, snapshot: str = "",
                command: str = "") -> str:
    sc = scope or Scope(window=window, since=since)
    return json.dumps({
        "ledger": ledger_label,
        "adapter": adapter.name,
        "window": window,
        "since": since,
        "until": sc.until,
        "until_rowid": sc.until_rowid,
        "rowid_range": [sc.lo, sc.hi] if sc.rowids else None,
        "rows_scoped": len(sc.rowids) if sc.rowids is not None else None,
        "rows_in_scope_before_limit": sc.matched,
        "snapshot": snapshot,
        "command": command,
        "min_fill": min_fill,
        "summary": summarize(results),
        "cell_totals": cell_totals(results),
        "items": [
            {
                "code": r.code,
                "title": r.title,
                "verdict": r.verdict,
                "label": LABEL[r.verdict],
                "kind": r.kind,
                "remedy": r.remedy,
                "remedy_generic": r.remedy_generic,
                "fields": [
                    {
                        "ref": f"{f.table}.{f.column}",
                        "logical_table": f.table,
                        "logical_column": f.column,
                        "physical": f.physical,
                        "mapped": f.physical is not None,
                        "exists": f.exists,
                        "rows": f.rows,
                        "non_empty": f.non_empty,
                        "fill": f.fill,
                        "na": f.na,
                        "degraded": f.degraded,
                        "note": f.note,
                    }
                    for f in r.fields
                ],
            }
            for r in results
        ],
    }, ensure_ascii=False, indent=2)


# ── 6. CLI ──────────────────────────────────────────────────────────────────


def _now_iso() -> str:
    from datetime import datetime
    return datetime.now().astimezone().replace(microsecond=0).isoformat()


def command_line(argv: list[str], snapshot: str) -> str:
    """把这次实际用的参数拼回一条可粘贴的命令。快照时刻也进命令 —— 否则
    「同一条命令跑出同一份文件」在时间戳那一行就不成立。"""
    kept: list[str] = []
    skip = False
    for a in argv:
        if skip:
            skip = False
            continue
        if a == "--snapshot-time":
            skip = True
            continue
        kept.append(a)
    prog = os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else "evidence_ledger.py"
    return f"python3 {prog} " + " ".join(
        [*kept, "--snapshot-time", snapshot]
    )


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="账本无关的国标八项字段面检查")
    ap.add_argument("--ledger", required=True, help="账本路径（SQLite 文件 / CSV / JSONL / 目录）")
    ap.add_argument("--adapter", required=True, help="适配器 JSON 路径")
    ap.add_argument("--window", type=int, default=DEFAULT_WINDOW)
    ap.add_argument("--min-fill", type=float, default=DEFAULT_MIN_FILL)
    ap.add_argument("--since", default=None, help="只看该时刻之后写的行（需 timestamp 映射）")
    ap.add_argument("--until", default=None,
                    help="只看该时刻及之前写的行（需 timestamp 映射）—— 窗口上界，复算用")
    ap.add_argument("--until-rowid", type=int, default=None, dest="until_rowid",
                    help="只看 rowid <= 该值的行 —— 窗口上界，最稳的复算钉子")
    ap.add_argument("--snapshot-time", default=None, dest="snapshot_time",
                    help="快照时刻（ISO8601，含时区）；不给则取当前时间，也可用环境变量 EVIDENCE_SNAPSHOT_TIME")
    ap.add_argument("--remedy", default="generic", choices=("generic", "internal", "none"),
                    help="补齐列口径：generic=交付用（schema 无关，默认）/ internal=我们自己的库 / none=不出")
    ap.add_argument("--no-remedy", action="store_true", help="只出四列，不带补齐列（等价 --remedy none）")
    ap.add_argument("--kind", default="auto", choices=("auto", "sqlite", "csv", "jsonl"))
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--markdown", action="store_true")
    ap.add_argument("--grid", action="store_true", help="交付用：每格分子/分母 + 物理位置")
    ap.add_argument("--contract", action="store_true", help="只出适配器契约表")
    ap.add_argument("--require-full", action="store_true")
    used = list(sys.argv[1:] if argv is None else argv)
    args = ap.parse_args(used)

    try:
        adapter = load_adapter(Path(args.adapter))
        if args.contract:
            print(render_contract(adapter, args.min_fill))
            return 0
        ledger = open_ledger(Path(args.ledger), adapter, args.kind)
    except (AdapterError, FileNotFoundError, sqlite3.Error) as exc:
        print(f"FAIL 账本/适配器读不出来: {exc}", file=sys.stderr)
        return 2
    try:
        results, scope = measure_with_scope(
            ledger, args.window, args.min_fill, args.since, args.until, args.until_rowid
        )
        if scope.note:
            print(f"NOTE {scope.note}", file=sys.stderr)
        if scope.sliding:
            print("NOTE 窗口在滑：未给上界（--until / --until-rowid），活库继续写入会把"
                  "最老的行挤出窗口，这次读数不可复算", file=sys.stderr)
        snapshot = args.snapshot_time or os.environ.get("EVIDENCE_SNAPSHOT_TIME") or _now_iso()
        # 命令行写成「能复现这份输出的那条命令」：没显式给上界时把观测到的 rowid 上界钉进去。
        # 这样交付件里的每一次读数都自带一个可执行的复算入口，而不是一句「应该能复算」。
        reproduced = list(used)
        if args.until_rowid is None and scope.hi is not None:
            reproduced += ["--until-rowid", str(scope.hi)]
        command = command_line(reproduced, snapshot)
        remedy_mode = "none" if args.no_remedy else args.remedy
        adapter_label = str(args.adapter)
        if args.json:
            print(render_json(results, ledger.label, adapter, args.window, args.min_fill,
                              args.since, scope=scope, snapshot=snapshot, command=command))
        elif args.grid:
            print(render_grid(results, ledger.label, args.min_fill, adapter, scope=scope,
                              adapter_label=adapter_label, command=command, snapshot=snapshot))
        elif args.markdown:
            print(render_markdown(results, ledger.label, args.window, args.min_fill, args.since,
                                  scope=scope, adapter_label=adapter_label, command=command,
                                  snapshot=snapshot, remedy_mode=remedy_mode))
        else:
            print(render_text(results, ledger.label, args.window, args.since))
    finally:
        ledger.close()

    if args.require_full and any(r.verdict != "covered" for r in results):
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
