Execution Profile
${htmlEscape(detail.profile || "full")}
Workflow
${htmlEscape(workflowStatus)}
diff --git a/frontend/server.py b/frontend/server.py
index ca71ac6..c3fef79 100644
--- a/frontend/server.py
+++ b/frontend/server.py
@@ -480,11 +480,18 @@ def _workspace_v3_status(workspace: Path, workspace_rel: str) -> dict:
artifact_previews = _artifact_previews(workspace, workspace_rel)
claim_coverage = database_status["claim_coverage"]
status = str((workflow or {}).get("status") or "READY")
+ try:
+ from paperforge.run_status import build_unified_status
+
+ unified = build_unified_status(workflow or {"id": "", "status": status}).to_dict() if workflow else None
+ except Exception:
+ unified = None
return {
"profile": profile,
"available_profiles": ["writing-only", "research", "full"],
"provider": _provider_status(workspace),
"workflow": workflow,
+ "unified": unified,
"approvals": database_status["approvals"],
"claim_coverage": claim_coverage,
"resume": {
diff --git a/paperforge/api.py b/paperforge/api.py
index 2eabf5c..74eb29b 100644
--- a/paperforge/api.py
+++ b/paperforge/api.py
@@ -555,6 +555,21 @@ def status(self, run_id: str | None = None) -> RunHandle:
state = self.workflow.get(run_id) if run_id else self.workflow.latest()
return self._handle(state)
+ def unified_status(
+ self,
+ run_id: str | None = None,
+ process_payload: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Shared read-only projection for CLI/API/frontend. No side effects."""
+ from .run_status import build_unified_status
+
+ state = self.workflow.get(run_id) if run_id else self.workflow.latest()
+ handle = self._handle(state)
+ unified = build_unified_status(state, process_payload)
+ payload = handle.to_dict()
+ payload["unified"] = unified.to_dict()
+ return payload
+
def resume(self, run_id: str | None = None) -> RunHandle:
state = self.workflow.get(run_id) if run_id else self.workflow.latest()
current = WorkflowStatus(state["status"])
diff --git a/paperforge/cli.py b/paperforge/cli.py
index 04e17b3..f52f820 100644
--- a/paperforge/cli.py
+++ b/paperforge/cli.py
@@ -358,7 +358,7 @@ def main(argv: Sequence[str] | None = None) -> int:
elif args.command == "resume":
_emit(service.resume(args.run_id).to_dict())
elif args.command == "status":
- _emit(service.status(args.run_id).to_dict())
+ _emit(service.unified_status(args.run_id))
elif args.command == "publish":
_emit(service.publish(template=args.template, main_tex=args.main_tex))
elif args.command == "release":
diff --git a/paperforge/run_status.py b/paperforge/run_status.py
new file mode 100644
index 0000000..2d0b9b7
--- /dev/null
+++ b/paperforge/run_status.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from typing import Any, Mapping
+
+from .models import WorkflowStatus
+
+PROCESS_STATES = (
+ "RUNNING",
+ "PAUSED",
+ "EXITED_SUCCESS",
+ "EXITED_FAILURE",
+ "STOPPING",
+ "UNKNOWN_NOT_ATTACHED",
+)
+
+# Deprecated aliases from the old process vocabulary (exit code collapsed).
+_DEPRECATED_PROCESS_ALIASES = {
+ "attached_running": "RUNNING",
+ "attached_paused": "PAUSED",
+ "exited": "EXITED_SUCCESS",
+ "stopping": "STOPPING",
+ "unknown_not_attached": "UNKNOWN_NOT_ATTACHED",
+ "running": "RUNNING",
+ "paused": "PAUSED",
+ "completed": "EXITED_SUCCESS",
+ "failed": "EXITED_FAILURE",
+}
+
+_HUMAN_GATES = frozenset({
+ WorkflowStatus.AWAITING_APPROVAL.value,
+ WorkflowStatus.AUTH_BLOCKED.value,
+ WorkflowStatus.PAUSED.value,
+ WorkflowStatus.INTERRUPTED.value,
+})
+
+RELATIONS = (
+ "consistent_active",
+ "consistent_quiescent",
+ "process_unknown",
+ "suspicious",
+)
+
+
+@dataclass(frozen=True)
+class UnifiedRunStatus:
+ """Read-only projection. Never a third state database.
+
+ workflow_state is the only business truth (Workflow DB / domain artifacts).
+ process_state is operating-system supervision truth (ProcessManager only).
+ process_domain_relation classifies the pair; process_discrepancy is only
+ set for genuinely suspicious combinations, never for legitimate quiescence.
+ """
+
+ run_id: str
+ workflow_state: str
+ process_state: str = "UNKNOWN_NOT_ATTACHED"
+ process_domain_relation: str = "process_unknown"
+ process_discrepancy: str = ""
+ pending_human_gate: str = ""
+ stage: str = ""
+ last_checkpoint: str = ""
+ checkpoint: str = ""
+ failure_summary: str = ""
+ artifact_ids: tuple[str, ...] = ()
+ review_ids: tuple[str, ...] = ()
+ updated_at: str = ""
+ # Deprecated compat: mirrors workflow_state, never process state.
+ status: str = ""
+
+ def __post_init__(self) -> None:
+ if self.process_state not in PROCESS_STATES:
+ raise ValueError(f"unknown process_state: {self.process_state}")
+ if self.process_domain_relation not in RELATIONS:
+ raise ValueError(f"unknown relation: {self.process_domain_relation}")
+ object.__setattr__(self, "artifact_ids", tuple(self.artifact_ids or ()))
+ object.__setattr__(self, "review_ids", tuple(self.review_ids or ()))
+ if not self.status:
+ object.__setattr__(self, "status", self.workflow_state)
+ if not self.checkpoint:
+ object.__setattr__(self, "checkpoint", self.last_checkpoint)
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["artifact_ids"] = list(payload["artifact_ids"])
+ payload["review_ids"] = list(payload["review_ids"])
+ return payload
+
+
+def _normalize_process(payload: Mapping[str, Any] | None) -> str:
+ if not isinstance(payload, Mapping) or not payload:
+ return "UNKNOWN_NOT_ATTACHED"
+ raw = str(payload.get("process_state") or payload.get("status") or "").strip()
+ upper = raw.upper()
+ if upper in PROCESS_STATES:
+ # EXITED without code defaults to success only when the payload says so;
+ # callers should prefer passing exit_code (see below).
+ return upper
+ lowered = raw.strip().lower()
+ if lowered in _DEPRECATED_PROCESS_ALIASES:
+ base = _DEPRECATED_PROCESS_ALIASES[lowered]
+ if base == "EXITED_SUCCESS" and str(payload.get("status") or "").strip().lower() == "failed":
+ return "EXITED_FAILURE"
+ exit_code = payload.get("exit_code")
+ if lowered in {"completed", "exited", "failed"} and isinstance(exit_code, int):
+ return "EXITED_SUCCESS" if exit_code == 0 else "EXITED_FAILURE"
+ return base
+ exit_code = payload.get("exit_code")
+ if isinstance(exit_code, int):
+ return "EXITED_SUCCESS" if exit_code == 0 else "EXITED_FAILURE"
+ return "UNKNOWN_NOT_ATTACHED"
+
+
+def _classify_relation(workflow_state: str, process_state: str) -> tuple[str, str]:
+ """Return (relation, discrepancy). Legitimate quiescence is never a mismatch."""
+ quiescent = {
+ WorkflowStatus.AWAITING_APPROVAL.value,
+ WorkflowStatus.PAUSED.value,
+ WorkflowStatus.INTERRUPTED.value,
+ WorkflowStatus.AUTH_BLOCKED.value,
+ WorkflowStatus.FAILED.value,
+ WorkflowStatus.CANCELLED.value,
+ WorkflowStatus.COMPLETED.value,
+ }
+ if process_state == "UNKNOWN_NOT_ATTACHED":
+ return "process_unknown", ""
+ if workflow_state == WorkflowStatus.RUNNING.value and process_state == "RUNNING":
+ return "consistent_active", ""
+ if workflow_state == WorkflowStatus.PAUSED.value and process_state == "PAUSED":
+ return "consistent_active", ""
+ if workflow_state in quiescent and process_state in {"EXITED_SUCCESS", "EXITED_FAILURE"}:
+ return "consistent_quiescent", ""
+ if workflow_state == WorkflowStatus.FAILED.value and process_state == "EXITED_FAILURE":
+ return "consistent_quiescent", ""
+ if workflow_state == WorkflowStatus.RUNNING.value and process_state in {
+ "EXITED_SUCCESS", "EXITED_FAILURE"}:
+ return "suspicious", "PROCESS_EXITED_WHILE_WORKFLOW_RUNNING"
+ if workflow_state == WorkflowStatus.COMPLETED.value and process_state in {
+ "RUNNING", "PAUSED"}:
+ return "suspicious", "PROCESS_ACTIVE_WHILE_WORKFLOW_COMPLETED"
+ return "suspicious", f"UNEXPECTED_PROCESS_DOMAIN_PAIR: {workflow_state}/{process_state}"
+
+
+def build_unified_status(
+ workflow_state: Mapping[str, Any],
+ process_payload: Mapping[str, Any] | None = None,
+) -> UnifiedRunStatus:
+ """Build the shared projection. Read-only: never writes domain or process state."""
+ run_id = str(workflow_state.get("id") or "")
+ state = str(workflow_state.get("status") or WorkflowStatus.READY.value)
+ try:
+ WorkflowStatus(state)
+ except ValueError:
+ state = WorkflowStatus.READY.value
+ process_state = _normalize_process(process_payload)
+ metadata = dict(workflow_state.get("metadata") or {})
+ relation, discrepancy = _classify_relation(state, process_state)
+ pending = state if state in _HUMAN_GATES else ""
+ failure = ""
+ if state in {WorkflowStatus.FAILED.value, WorkflowStatus.AUTH_BLOCKED.value}:
+ failure = str(workflow_state.get("error_code") or metadata.get("detail") or state)
+ artifacts = metadata.get("runtime_manifest") or metadata.get("runtime_report")
+ artifact_ids = tuple(a for a in ([artifacts] if isinstance(artifacts, str) else (artifacts or [])) if a)
+ checkpoint = str(workflow_state.get("checkpoint") or "")
+ return UnifiedRunStatus(
+ run_id=run_id,
+ workflow_state=state,
+ process_state=process_state,
+ process_domain_relation=relation,
+ process_discrepancy=discrepancy,
+ pending_human_gate=pending,
+ stage=checkpoint,
+ last_checkpoint=checkpoint,
+ checkpoint=checkpoint,
+ failure_summary=failure,
+ artifact_ids=artifact_ids,
+ review_ids=(),
+ updated_at=str(workflow_state.get("updated_at") or ""),
+ status=state,
+ )
+
+
+__all__ = ["PROCESS_STATES", "RELATIONS", "UnifiedRunStatus", "build_unified_status"]
diff --git a/tests/test_u4a_unified_status.py b/tests/test_u4a_unified_status.py
new file mode 100644
index 0000000..2a916b1
--- /dev/null
+++ b/tests/test_u4a_unified_status.py
@@ -0,0 +1,163 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from paperforge.api import PaperForgeService
+from paperforge.models import WorkflowStatus
+from paperforge.run_status import UnifiedRunStatus, build_unified_status
+
+
+def _state(status: str, **overrides):
+ base = {"id": "wf-test", "status": status, "checkpoint": "policy",
+ "updated_at": "2026-01-01T00:00:00+00:00", "metadata": {}}
+ base.update(overrides)
+ return base
+
+
+def test_process_running_does_not_imply_workflow_running() -> None: # 1
+ unified = build_unified_status(_state("READY"), {"status": "running"})
+ assert unified.workflow_state == "READY" and unified.process_state == "RUNNING"
+
+
+def test_exit_zero_does_not_complete_workflow() -> None: # 2
+ unified = build_unified_status(_state("RUNNING"), {"status": "completed", "exit_code": 0})
+ assert unified.workflow_state == "RUNNING" and unified.process_state in {"EXITED_SUCCESS", "EXITED_FAILURE"}
+ assert unified.process_domain_relation == "suspicious"
+ assert unified.process_discrepancy == "PROCESS_EXITED_WHILE_WORKFLOW_RUNNING"
+
+
+def test_relation_matrix() -> None: # F1 combos 1-6
+ assert build_unified_status(_state("AWAITING_APPROVAL"), {"status": "completed", "exit_code": 0}).process_domain_relation == "consistent_quiescent"
+ assert build_unified_status(_state("AWAITING_APPROVAL"), {"status": "completed", "exit_code": 0}).process_discrepancy == ""
+ assert build_unified_status(_state("AWAITING_APPROVAL"), None).process_domain_relation == "process_unknown"
+ assert build_unified_status(_state("RUNNING"), {"status": "running"}).process_domain_relation == "consistent_active"
+ assert build_unified_status(_state("COMPLETED"), {"status": "running"}).process_domain_relation == "suspicious"
+ assert build_unified_status(_state("FAILED"), {"status": "failed", "exit_code": 3}).process_domain_relation == "consistent_quiescent"
+
+
+def test_nonzero_exit_preserves_needs_human() -> None: # 3,4
+ unified = build_unified_status(_state("AWAITING_APPROVAL"), {"status": "failed", "exit_code": 1})
+ assert unified.workflow_state == "AWAITING_APPROVAL"
+ assert unified.pending_human_gate == "AWAITING_APPROVAL"
+
+
+def test_approved_no_process_recoverable() -> None: # 5
+ unified = build_unified_status(_state("AWAITING_APPROVAL"), None)
+ assert unified.process_state == "UNKNOWN_NOT_ATTACHED"
+ assert unified.workflow_state == "AWAITING_APPROVAL"
+
+
+def test_restart_preserves_domain_state(tmp_path: Path) -> None: # 6
+ first = PaperForgeService(tmp_path)
+ handle = first.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ second = PaperForgeService(tmp_path) # simulates app restart; process memory gone
+ assert second.status(handle.run_id).status == first.status(handle.run_id).status
+ unified = second.unified_status(handle.run_id)
+ assert unified["unified"]["process_state"] == "UNKNOWN_NOT_ATTACHED"
+
+
+def test_process_memory_loss_never_resets_workflow() -> None: # 7
+ unified = build_unified_status(_state("PAUSED"), None)
+ assert unified.workflow_state == "PAUSED"
+
+
+def test_three_entries_share_source(tmp_path: Path) -> None: # 8
+ from paperforge.cli import build_parser
+
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ api_state = service.unified_status(handle.run_id)["unified"]["workflow_state"]
+ parser = build_parser()
+ args = parser.parse_args(["status", "--workspace", str(tmp_path), "--run-id", handle.run_id])
+ assert args.command == "status" and args.run_id == handle.run_id
+ # Frontend adapter consumes the same builder over the same DB row.
+ frontend = build_unified_status(service.workflow.get(handle.run_id), None)
+ assert frontend.workflow_state == api_state
+
+
+def test_read_status_side_effect_free(tmp_path: Path) -> None: # 9
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ before = service.workflow.get(handle.run_id)
+ service.status(handle.run_id)
+ service.unified_status(handle.run_id)
+ after = service.workflow.get(handle.run_id)
+ assert before["version"] == after["version"] and before["status"] == after["status"]
+
+
+def test_frontend_refresh_writes_nothing(tmp_path: Path) -> None: # 10
+ import sys
+
+ sys.path.insert(0, ".")
+ from frontend.server import _workspace_v3_status
+
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ before = service.workflow.get(handle.run_id)["version"]
+ _workspace_v3_status(tmp_path, "x")
+ assert service.workflow.get(handle.run_id)["version"] == before
+
+
+def test_mismatch_explicit_and_no_silent_pick() -> None: # 11,12
+ unified = build_unified_status(_state("RUNNING"), {"status": "completed"})
+ assert unified.process_discrepancy and unified.workflow_state == "RUNNING"
+
+
+def test_approval_from_domain(tmp_path: Path) -> None: # 13
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="full", inputs={})
+ assert service.status(handle.run_id).status == WorkflowStatus.AWAITING_APPROVAL.value
+
+
+def test_no_review_inference() -> None: # 14,15,16
+ unified = build_unified_status(_state("RUNNING"), {"status": "running"})
+ assert unified.review_ids == () and "review" not in unified.to_dict().get("failure_summary", "").lower()
+
+
+def test_dto_is_projection_not_database(tmp_path: Path) -> None: # 17
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ unified = UnifiedRunStatus(run_id=handle.run_id, workflow_state="RUNNING", process_state="EXITED_SUCCESS")
+ assert unified.to_dict()["workflow_state"] == "RUNNING"
+ assert service.workflow.get(handle.run_id)["status"] != "COMPLETED"
+
+
+def test_compat_status_is_workflow(tmp_path: Path) -> None: # 18
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ payload = service.unified_status(handle.run_id)
+ assert payload["status"] == payload["unified"]["workflow_state"]
+
+
+def test_failure_projection_without_pollution() -> None: # 19
+ unified = build_unified_status(
+ {"id": "w", "status": "FAILED", "checkpoint": "runtime",
+ "updated_at": "t", "error_code": "E", "metadata": {}}, {"status": "failed"})
+ assert unified.workflow_state == "FAILED" and unified.process_state == "EXITED_FAILURE"
+ assert unified.failure_summary == "E"
+
+
+def test_v2_file_never_feeds_unified(tmp_path: Path) -> None: # F5
+ (tmp_path / "workflow_state.json").write_text('{"phase": "done"}', encoding="utf-8")
+ service = PaperForgeService(tmp_path)
+ handle = service.run(profile="writing-only", inputs={"title": "t", "topic": "x"})
+ unified = service.unified_status(handle.run_id)["unified"]
+ assert unified["workflow_state"] != "done"
+ assert unified["stage"] != "done"
+
+
+def test_frontend_consumer_audit() -> None: # F2 audit
+ source = Path("frontend/app.js").read_text(encoding="utf-8")
+ assert "processPill" in source and "not workflow truth" in source
+ assert 'if (run.status === "completed")' not in source
+ assert "v3?.workflow?.status" in source or "v3?.unified" in source
+
+
+def test_final_schema() -> None: # F4
+ unified = build_unified_status(_state("RUNNING"), {"status": "running"})
+ payload = unified.to_dict()
+ for key in ("run_id", "workflow_state", "process_state", "process_domain_relation",
+ "process_discrepancy", "pending_human_gate", "stage", "checkpoint",
+ "failure_summary", "updated_at"):
+ assert key in payload
+ assert payload["status"] == payload["workflow_state"]
From 7bc397ba3ed8a76383c7834a4bfd2b20856f0b80 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Sun, 27 Sep 2026 22:18:03 +0800
Subject: [PATCH 13/30] feat: finalize provenance-bound release eligibility and
authorization
---
docs/u4b-finalization.md | 95 ++++
paperforge/release_eligibility.py | 897 ++++++++++++++++++++++++++++++
paperforge/run_status.py | 9 +
tests/test_u4b_finalization.py | 372 +++++++++++++
tests/test_u4b_release.py | 243 ++++++++
5 files changed, 1616 insertions(+)
create mode 100644 docs/u4b-finalization.md
create mode 100644 paperforge/release_eligibility.py
create mode 100644 tests/test_u4b_finalization.py
create mode 100644 tests/test_u4b_release.py
diff --git a/docs/u4b-finalization.md b/docs/u4b-finalization.md
new file mode 100644
index 0000000..2fff9bd
--- /dev/null
+++ b/docs/u4b-finalization.md
@@ -0,0 +1,95 @@
+# U4B finalization — 2026-09-27
+
+## 范围与状态
+
+- 分支:`feature/u4b-release-eligibility`,起点 `c628f85`。
+- 本次只收尾 U4B;不进入 U4C/U4D,不 push,不修改真实论文,不创建真实 Scientific Evidence。
+- 旧 checkout 和 `.paperforge/shadow` 保持不动;影子数据不进入 commit。
+- 历史 JSON 最后是 U4B 初版汇报;该汇报不能代替代码与测试。本次发现并修正了只验证报告自身摘要、评估时写库、未绑定 acknowledgement、忽略 build,以及多个直接信任调用方状态的问题。
+
+## F1:build provenance
+
+`ReleaseTarget` 绑定 manuscript/PDF/bibliography 的具体相对路径和 SHA256,以及 `build_manifest_path` / `build_digest`。
+
+`build_digest` 是 manifest 文件实际 bytes 的 SHA256,不是包含自身摘要的 JSON hash。消费的 manifest 契约:
+
+```json
+{
+ "schema": "paperforge.build-provenance/v1",
+ "status": "succeeded",
+ "source_hashes": {"main.tex": "sha256", "refs.bib": "sha256"},
+ "output_path": "final.pdf",
+ "output_sha256": "sha256",
+ "command": ["compiler", "main.tex"],
+ "toolchain": {"compiler": "version"}
+}
+```
+
+所有列出的 source hashes 都重验;manifest 必须涵盖目标 manuscript/bibliography,并指向同一 PDF。目标指定 workflow/baseline 时,manifest 必须同样绑定它们。空源文件、缺 build、旧源编译的 PDF、越界路径、glob 和软链接不通过。
+
+这里消费既有构建记录,不运行编译,也不证明编译器或记录签发者可信。生产调用方须提供完整输入清单,不能把手写 manifest 当作构建真实性证明。已有 result baseline 指定时还检查数据库中的 source、APPLIED 状态和有效 approval 绑定;缺失或不一致时阻塞,不自动修复历史记录。
+
+## F2/F3:acknowledgement、授权与发布分离
+
+```text
+evaluate_release -> eligibility(纯只读)
+freeze_assessment -> 显式保存审计报告、注册 ArtifactStore
+record_release_acknowledgement -> 显式操作者动作
+release_authorization -> 只读授权投影
+```
+
+- `ELIGIBLE` 不表示已授权,更不表示已发布。
+- ack 绑定 assessment digest、target digest、policy digest、approver、rationale、时间和 decision。
+- ack 只能针对当前且 eligible 的报告;不能跨 target/policy/assessment 复用。
+- policy 要求 owner ack 但缺记录时:eligibility 可为 `ELIGIBLE`,authorization 为 `NEEDS_HUMAN`。
+- 不要求 ack 时 authorization 为 `NOT_REQUIRED`;有效 ack 为 `AUTHORIZED`。
+- U4B 不执行发布,授权投影始终报告 `NOT_RELEASED`。
+- `human_records` 中任意传入 `owner_ack` 字典不能授权。科学人审消费既有、同 PDF/render 绑定的记录,不能用 owner ack 替代。
+- 这是本地操作审计,不是数字签名或身份认证。调用 ack API 的上层必须认证操作者;不能抵抗可任意重写整个本地信任域的攻击者。
+
+## F4:assessment currentness
+
+- digest 排除报告创建时间和 target 创建时间;包含 policy、输入、门禁结果、文件快照与 domain digest。
+- `assessment_current` 验证历史摘要,再只读重算当前评估;历史报告不回写。
+- source、PDF、bib、build、import sources、review/ledger/matrix/QA、工程记录/log、证据和 approval 数据变化均可使报告失效。
+- 保守策略:domain digest 包含相关科学/approval 表的全部行,因此无关证据变化也可能使报告失效,需要重评。
+- `assessment_current`、`record_release_acknowledgement`、`release_authorization` 都接收 `current_policy`。上层若已选择新的政策,必须传入;省略时仅判断冻结政策下的现势,不存在隐式“latest policy”。
+- 使用只读数据库 facade(`PRAGMA query_only`),旧 verifier 的 schema 创建不能产生副作用。
+- 本阶段不声称跨文件/数据库读取具备线性一致性,也不声称完成 SIGKILL/掉电恢复;这些仍属 U4C。
+
+## 补齐的门禁与限制
+
+- Evidence 从 ScientificMemory 读取,不信任调用方伪造的 scientific/current 标签;导入 approval 和源 bytes 重验。
+- Ledger 消费已有 verifier;fixture/transcribed 不能满足科学发布输入。
+- ScientificReview 检查现势、源文件 hash 和 policy 允许的 review state;caveats 不自动等同 reviewed。
+- ReviewerMatrix 只看 required criteria/actions;verified 字符串或回复 prose 不足以通过。
+- 当前 release adapter 支持 `hardware_measurement` / `scientific_experiment` 的 bound evidence,以及 `layout` / `manuscript_clarification` 的 target-bound explicit human verification。未知 criterion/binding 类型保守阻塞,不做存在即通过的降级。
+- PDF QA 检查同 PDF/build、页覆盖、生产 render/human 记录、critical、target-specific issue 和 warning 白名单。U3B verifier 的 digest 重算含 bundle_id、与 producer 不一致;release adapter 按 producer 的 canonical contract 独立核验,未修改历史 U3B 文件。
+- Engineering/environment 必须分别提供 target-bound `paperforge.engineering-check/v1` 记录和 log hash;`passed` 字符串、非零 exit、stale、错误计数、缺记录均不能冒充通过。
+- UnifiedRunStatus 增加可选、`authoritative=false` 的 release 摘要展示;不改变 workflow/process 真值,不保存第三份状态。
+
+## 验证
+
+命令(Python 3.11):
+
+```text
+python3.11 -m pytest tests/test_u4b_release.py tests/test_u4b_finalization.py tests/test_u4a_unified_status.py -q
+65 passed(46 U4B + 19 U4A)
+
+python3.11 -m pytest tests -q --continue-on-collection-errors --tb=no
+559 passed, 6 skipped, 10 failed, 2 collection errors
+```
+
+10 failures / 2 collection errors 都在旧 research_partner/agent 导入链,报 `ModuleNotFoundError: No module named 'pymupdf'`。5 个真实计算后端集成测试未启用,1 个 visualization 测试缺 fitz 跳过。不能称完整 suite 全绿。
+
+`python3.11 -m ruff` / `python3.11 -m mypy` 均报模块未安装;本次未安装依赖。merge/push/release 环境门禁仍未关闭。
+
+本地 Python/安全代码复核发现并修正:无 bindings 却 verified、criterion/binding 错配、政策更改未贯穿授权、导入源软链接绕过。最终独立复核未发现剩余 HIGH/CRITICAL;这不是远端自动审查结论。
+
+## 后续纪律
+
+本次独立本地 commit 后停止,不进入 U4C。U4C 的 crash/stress 和 U4D 的 merge readiness 不在本次范围。
+
+用户交接记录说明:自动代码审查开启、每次 push 触发、全面代码审查关闭;自动安全审查开启、每次代码审查触发,自动最低严重级别为高,`@codex` 人工审查最低为中。本次未 push,未把这些配置声称为实时远端核验。
+
+**以后每次 push 后必须立即检查本次自动代码审查和安全审查结果;未出结果不是通过。有阻塞问题先修复,再 push、再复查,不能直接继续下一阶段。**
diff --git a/paperforge/release_eligibility.py b/paperforge/release_eligibility.py
new file mode 100644
index 0000000..a651da1
--- /dev/null
+++ b/paperforge/release_eligibility.py
@@ -0,0 +1,897 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+from .models import utc_now
+from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
+
+REPORT_SCHEMA = "paperforge.release-eligibility-report/v1"
+POLICY_SCHEMA = "paperforge.release-policy/v1"
+POLICY_VERSION = "paperforge.release-policy/v1"
+
+CATEGORIES = (
+ "source_integrity",
+ "scientific_evidence",
+ "scientific_review",
+ "reviewer_resolution",
+ "pdf_layout_qa",
+ "human_approval",
+ "engineering_quality",
+ "environment_readiness",
+)
+
+
+class ReleaseEligibilityError(RuntimeError):
+ pass
+
+
+class _ReadOnlyMemory:
+ """Prevent legacy verification helpers from creating or changing DB state."""
+
+ def __init__(self, memory: Any):
+ self.memory = memory
+
+ @contextmanager
+ def connect(self):
+ with self.memory.connect() as db:
+ db.execute("PRAGMA query_only = ON")
+ yield db
+
+
+@dataclass(frozen=True)
+class ReleaseTarget:
+ target_id: str
+ manuscript_path: str = ""
+ manuscript_sha256: str = ""
+ final_pdf_path: str = ""
+ final_pdf_sha256: str = ""
+ bibliography_hashes: Mapping[str, Any] = field(default_factory=dict)
+ build_digest: str = ""
+ build_manifest_path: str = ""
+ workflow_id: str = ""
+ baseline_id: str = ""
+ created_at: str = ""
+
+ def __post_init__(self) -> None:
+ if not str(self.target_id or "").strip():
+ raise ReleaseEligibilityError("target_id is required")
+ object.__setattr__(self, "bibliography_hashes", dict(self.bibliography_hashes or {}))
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["bibliography_hashes"] = dict(payload["bibliography_hashes"])
+ return payload
+
+
+@dataclass(frozen=True)
+class ReleasePolicy:
+ policy_id: str = "default"
+ version: str = POLICY_VERSION
+ required_gates: tuple[str, ...] = CATEGORIES
+ allowed_warning_classes: tuple[str, ...] = ()
+ require_human_owner_ack: bool = False
+ engineering_blocking: bool = True
+ strict_reviewer_verification: bool = True
+ allowed_review_states: tuple[str, ...] = ("reviewed",)
+
+ def __post_init__(self) -> None:
+ unknown = [g for g in (self.required_gates or ()) if g not in CATEGORIES]
+ if unknown:
+ raise ReleaseEligibilityError(f"unknown gate categories: {unknown}")
+ object.__setattr__(self, "required_gates", tuple(self.required_gates or ()))
+ object.__setattr__(self, "allowed_warning_classes", tuple(self.allowed_warning_classes or ()))
+ object.__setattr__(self, "allowed_review_states", tuple(self.allowed_review_states))
+
+ def to_canonical(self) -> dict[str, Any]:
+ return {"schema": POLICY_SCHEMA, "policy_id": self.policy_id, "version": self.version,
+ "required_gates": list(self.required_gates),
+ "allowed_warning_classes": list(self.allowed_warning_classes),
+ "require_human_owner_ack": self.require_human_owner_ack,
+ "engineering_blocking": self.engineering_blocking,
+ "strict_reviewer_verification": self.strict_reviewer_verification,
+ "allowed_review_states": list(self.allowed_review_states)}
+
+ def digest(self) -> str:
+ return hashlib.sha256(json.dumps(
+ self.to_canonical(), ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+@dataclass(frozen=True)
+class ReleaseGateResult:
+ gate_id: str
+ category: str
+ requirement: str
+ status: str
+ severity: str = "major"
+ source_artifact_ids: tuple[str, ...] = ()
+ source_digests: tuple[str, ...] = ()
+ currentness: str = "current"
+ rationale: str = ""
+ remediation: str = ""
+ policy_rule: str = ""
+
+ def __post_init__(self) -> None:
+ if self.category not in CATEGORIES:
+ raise ReleaseEligibilityError(f"unknown category: {self.category}")
+ if self.status not in {"passed", "failed", "needs_human", "blocked", "not_applicable"}:
+ raise ReleaseEligibilityError(f"unknown gate status: {self.status}")
+ object.__setattr__(self, "source_artifact_ids", tuple(self.source_artifact_ids or ()))
+ object.__setattr__(self, "source_digests", tuple(self.source_digests or ()))
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["source_artifact_ids"] = list(payload["source_artifact_ids"])
+ payload["source_digests"] = list(payload["source_digests"])
+ return payload
+
+
+@dataclass(frozen=True)
+class EngineeringCheckResult:
+ check_id: str
+ command: str = ""
+ status: str = "not_run"
+ exit_code: int | None = None
+ collected: int = 0
+ passed: int = 0
+ failed: int = 0
+ skipped: int = 0
+ errors: int = 0
+ environment_findings: tuple[str, ...] = ()
+ log_artifact: str = ""
+ verifier: str = ""
+ currentness: str = "current"
+ category: str = "engineering_quality"
+ record_path: str = ""
+
+ def __post_init__(self) -> None:
+ if self.status not in {"passed", "failed", "unavailable", "not_run", "blocked_environment"}:
+ raise ReleaseEligibilityError(f"unknown engineering status: {self.status}")
+ if self.category not in {"engineering_quality", "environment_readiness"}:
+ raise ReleaseEligibilityError("invalid engineering category")
+ object.__setattr__(self, "environment_findings", tuple(self.environment_findings or ()))
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["environment_findings"] = list(payload["environment_findings"])
+ return payload
+
+
+def _canonical(payload: Mapping[str, Any]) -> bytes:
+ return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
+
+
+def _digest(payload: Mapping[str, Any]) -> str:
+ return hashlib.sha256(_canonical(payload)).hexdigest()
+
+
+def _path(root: Path, relative: str) -> Path:
+ path = Path(relative)
+ if (not relative or path.is_absolute() or ".." in path.parts
+ or any(c in relative for c in "*?[]\\") or path.as_posix() != relative):
+ raise ReleaseEligibilityError("expected an exact workspace-relative path")
+ candidate = reject_symlink_components(root / path, anchor=root)
+ if not candidate.is_file() or not candidate.resolve().is_relative_to(root):
+ raise ReleaseEligibilityError("bound file missing or unsafe")
+ return candidate
+
+
+def _json_file(root: Path, relative: str) -> dict[str, Any]:
+ data = json.loads(_path(root, relative).read_bytes())
+ if not isinstance(data, dict):
+ raise ReleaseEligibilityError("expected a JSON object")
+ return data
+
+
+def _identifier(value: str) -> str:
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", value):
+ raise ReleaseEligibilityError("invalid artifact identifier")
+ return value
+
+
+def _file_hash(root: Path, relative: str) -> str:
+ try:
+ return hashlib.sha256(_path(root, relative).read_bytes()).hexdigest()
+ except (OSError, ValueError, ReleaseEligibilityError):
+ return "missing_or_unsafe"
+
+
+def _target_binding(target: ReleaseTarget) -> dict[str, Any]:
+ return {k: v for k, v in target.to_dict().items() if k != "created_at"}
+
+
+def _validate_import_files(root: Path, import_id: str) -> None:
+ base = f".paperforge/imports/{_identifier(import_id)}"
+ manifest = _json_file(root, f"{base}/manifest.json")
+ _path(root, f"{base}/validation.json")
+ for source in manifest.get("sources") or []:
+ _path(root, f"{base}/{source['path']}")
+
+
+def _validate_ledger_files(root: Path, memory: Any, ledger_id: str) -> dict[str, Any]:
+ ledger = _json_file(root, f".paperforge/ledgers/{_identifier(ledger_id)}/ledger.json")
+ with memory.connect() as db:
+ for snapshot in ledger.get("snapshots") or []:
+ row = db.execute("SELECT metadata_json FROM evidence WHERE id=?",
+ (snapshot.get("evidence_id"),)).fetchone()
+ if row:
+ meta = json.loads(row["metadata_json"])
+ if meta.get("import_id"):
+ _validate_import_files(root, str(meta["import_id"]))
+ return ledger
+
+
+def _build_valid(root: Path, target: ReleaseTarget) -> bool:
+ try:
+ if _file_hash(root, target.build_manifest_path) != target.build_digest:
+ return False
+ build = _json_file(root, target.build_manifest_path)
+ sources = build.get("source_hashes")
+ expected = {**target.bibliography_hashes, target.manuscript_path: target.manuscript_sha256}
+ return bool(
+ build.get("schema") == "paperforge.build-provenance/v1"
+ and build.get("status") == "succeeded"
+ and build.get("command") and build.get("toolchain")
+ and isinstance(sources, dict) and sources
+ and all(sources.get(p) == sha for p, sha in expected.items())
+ and all(_file_hash(root, p) == sha for p, sha in sources.items())
+ and build.get("output_path") == target.final_pdf_path
+ and build.get("output_sha256") == target.final_pdf_sha256
+ and (not target.workflow_id or build.get("workflow_id") == target.workflow_id)
+ and (not target.baseline_id or build.get("baseline_id") == target.baseline_id)
+ )
+ except (OSError, ValueError, TypeError, ReleaseEligibilityError):
+ return False
+
+
+def _snapshot(root: Path, memory: Any, target: ReleaseTarget,
+ inputs: Mapping[str, Any]) -> dict[str, Any]:
+ paths = {target.manuscript_path, target.final_pdf_path, target.build_manifest_path,
+ *target.bibliography_hashes}
+ try:
+ paths.update(_json_file(root, target.build_manifest_path).get("source_hashes", {}))
+ except (OSError, ValueError, TypeError, ReleaseEligibilityError):
+ pass
+ for key, folder, name in (("ledger_ids", "ledgers", "ledger.json"),
+ ("review_ids", "reviews", "review.json"),
+ ("pdf_bundle_ids", "pdf_qa", "qa.json")):
+ for item in inputs.get(key) or []:
+ paths.add(f".paperforge/{folder}/{_identifier(str(item))}/{name}")
+ matrix_id = (inputs.get("reviewer_projection") or {}).get("matrix_id")
+ if matrix_id:
+ paths.add(f".paperforge/review_matrix/{_identifier(str(matrix_id))}/matrix.json")
+ for check in inputs.get("engineering_checks") or []:
+ if check.get("log_artifact"):
+ paths.add(check["log_artifact"])
+ if check.get("record_path"):
+ paths.add(check["record_path"])
+ for review_id in inputs.get("review_ids") or []:
+ try:
+ review = _json_file(root, f".paperforge/reviews/{_identifier(review_id)}/review.json")
+ paths.update(review.get("fact_artifact_hashes") or {})
+ except (OSError, ValueError, TypeError, ReleaseEligibilityError):
+ pass
+ # Pin mutable scientific/approval state as well as frozen file bytes.
+ # Conservative invalidation on unrelated evidence changes is intentional.
+ state = {}
+ with memory.connect() as db:
+ tables = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
+ for name in ("evidence", "imports", "import_approvals", "result_updates",
+ "result_approvals", "result_baselines"):
+ if name in tables:
+ state[name] = sorted((dict(r) for r in db.execute(f"SELECT * FROM {name}")),
+ key=lambda row: json.dumps(row, sort_keys=True))
+ for row in state.get("evidence", []):
+ try:
+ meta = json.loads(row["metadata_json"])
+ if meta.get("import_id"):
+ base = f".paperforge/imports/{_identifier(str(meta['import_id']))}"
+ paths.update((f"{base}/manifest.json", f"{base}/validation.json"))
+ manifest = _json_file(root, f"{base}/manifest.json")
+ paths.update(f"{base}/{s['path']}" for s in manifest.get("sources") or [])
+ except (OSError, ValueError, TypeError, KeyError, ReleaseEligibilityError):
+ continue
+ pending_paths = list(paths)
+ visited = set()
+ while pending_paths:
+ path = pending_paths.pop()
+ if path in visited or not path.endswith(".json"):
+ continue
+ visited.add(path)
+ try:
+ bundle = _json_file(root, path)
+ linked = set(bundle.get("fact_artifact_hashes") or {})
+ linked.update(f".paperforge/ledgers/{_identifier(str(b['ledger_id']))}/ledger.json"
+ for b in bundle.get("ledger_bindings") or [])
+ linked.update(f".paperforge/reviews/{_identifier(str(r))}/review.json"
+ for r in bundle.get("review_ids") or [])
+ for binding in bundle.get("bindings") or []:
+ locations = {"ledger": ("ledgers", "ledger.json"),
+ "review_bundle": ("reviews", "review.json"),
+ "pdf_qa": ("pdf_qa", "qa.json")}
+ if binding.get("artifact_kind") in locations:
+ folder, name = locations[binding["artifact_kind"]]
+ linked.add(f".paperforge/{folder}/{_identifier(binding['artifact_id'])}/{name}")
+ paths.update(linked)
+ pending_paths.extend(linked - visited)
+ except (OSError, ValueError, TypeError, KeyError, ReleaseEligibilityError):
+ continue
+ return {"file_hashes": {p: _file_hash(root, p) for p in sorted(paths) if p},
+ "domain_digest": _digest(state)}
+
+
+def _gate(gate_id: str, category: str, requirement: str, status: str, rationale: str = "",
+ remediation: str = "", severity: str = "major",
+ artifacts: Sequence[str] = (), digests: Sequence[str] = (),
+ currentness: str = "current", rule: str = "") -> ReleaseGateResult:
+ return ReleaseGateResult(
+ gate_id=gate_id, category=category, requirement=requirement, status=status,
+ severity=severity, source_artifact_ids=tuple(artifacts), source_digests=tuple(digests),
+ currentness=currentness, rationale=rationale, remediation=remediation, policy_rule=rule)
+
+
+def evaluate_release(
+ workspace: str | Path,
+ memory: Any,
+ target: ReleaseTarget,
+ policy: ReleasePolicy,
+ *,
+ evidence_refs: Sequence[Mapping[str, Any]] | None = None,
+ ledger_ids: Sequence[str] | None = None,
+ review_ids: Sequence[str] | None = None,
+ reviewer_projection: Mapping[str, Any] | None = None,
+ pdf_bundle_ids: Sequence[str] | None = None,
+ human_records: Sequence[Mapping[str, Any]] | None = None,
+ engineering_checks: Sequence[EngineeringCheckResult | Mapping[str, Any]] | None = None,
+) -> dict[str, Any]:
+ """Read-only eligibility projection. Never mutates Evidence, reviews, or files."""
+ root = Path(workspace).expanduser().resolve(strict=True)
+ memory = _ReadOnlyMemory(memory)
+ gates: list[ReleaseGateResult] = []
+ inputs = {
+ "evidence_refs": [dict(e) for e in evidence_refs or ()],
+ "ledger_ids": list(ledger_ids or ()), "review_ids": list(review_ids or ()),
+ "reviewer_projection": dict(reviewer_projection or {}),
+ "pdf_bundle_ids": list(pdf_bundle_ids or ()),
+ "human_records": [dict(h) for h in human_records or ()],
+ "engineering_checks": [c.to_dict() if isinstance(c, EngineeringCheckResult) else dict(c)
+ for c in engineering_checks or ()],
+ }
+
+ # A. source integrity: exact byte binding, no latest/glob.
+ try:
+ manuscript = _path(root, target.manuscript_path).read_bytes()
+ manuscript_ok = bool(manuscript) and hashlib.sha256(manuscript).hexdigest() == target.manuscript_sha256
+ except (OSError, ValueError, ReleaseEligibilityError):
+ manuscript_ok = False
+ try:
+ pdf = _path(root, target.final_pdf_path).read_bytes()
+ pdf_ok = bool(pdf) and hashlib.sha256(pdf).hexdigest() == target.final_pdf_sha256
+ except (OSError, ValueError, ReleaseEligibilityError):
+ pdf_ok = False
+ gates.append(_gate("source.manuscript", "source_integrity", "manuscript bytes match target",
+ "passed" if manuscript_ok else "failed",
+ rationale="manuscript SHA binding"))
+ gates.append(_gate("source.pdf", "source_integrity", "final PDF bytes match target",
+ "passed" if pdf_ok else "failed",
+ rationale="PDF SHA binding"))
+ gates.append(_gate("source.build", "source_integrity", "build binds all current inputs and output",
+ "passed" if _build_valid(root, target) else "blocked",
+ rationale="exact build manifest bytes and source/PDF bindings required",
+ artifacts=(target.build_manifest_path,), digests=(target.build_digest,)))
+ for path, sha in target.bibliography_hashes.items():
+ gates.append(_gate(f"source.bibliography.{path}", "source_integrity", "bibliography current",
+ "passed" if _file_hash(root, path) == sha else "failed"))
+ if target.baseline_id:
+ valid_baseline = False
+ try:
+ with memory.connect() as db:
+ baseline = db.execute("SELECT * FROM result_baselines WHERE target_path=?",
+ (target.manuscript_path,)).fetchone()
+ update = db.execute("SELECT * FROM result_updates WHERE id=?",
+ (target.baseline_id,)).fetchone()
+ approval = db.execute("SELECT * FROM result_approvals WHERE id=?",
+ (baseline["approval_id"] if baseline else "",)).fetchone()
+ valid_baseline = bool(baseline and update and approval
+ and baseline["proposal_id"] == target.baseline_id
+ and baseline["source_sha256"] == target.manuscript_sha256
+ and update["state"] == "APPLIED"
+ and approval["proposal_id"] == target.baseline_id
+ and approval["proposal_digest"] == update["proposal_digest"]
+ and approval["status"] == "valid")
+ except Exception:
+ valid_baseline = False
+ gates.append(_gate("source.baseline", "source_integrity", "result baseline and approval current",
+ "passed" if valid_baseline else "blocked"))
+
+ # B. scientific evidence: current, non-fixture, non-transcribed-only.
+ evidence_refs = list(evidence_refs or [])
+ resolved_evidence = []
+ missing_evidence = []
+ with memory.connect() as db:
+ for ref in evidence_refs:
+ eid = str(ref.get("evidence_id") or "")
+ row = db.execute("SELECT * FROM evidence WHERE id=?", (eid,)).fetchone()
+ if row is None:
+ missing_evidence.append(eid)
+ continue
+ meta = json.loads(row["metadata_json"])
+ if meta.get("import_id"):
+ try:
+ from .external_import import approval_valid
+
+ import_id = _identifier(str(meta["import_id"]))
+ _validate_import_files(root, import_id)
+ valid, _ = approval_valid(root, memory, import_id)
+ meta["current"] = valid
+ except Exception:
+ meta["current"] = False
+ resolved_evidence.append({**meta, "evidence_id": eid})
+ if missing_evidence:
+ gates.append(_gate("evidence.missing", "scientific_evidence", "evidence exists in memory",
+ "blocked", rationale="requested evidence missing"))
+ evidence_refs = resolved_evidence
+ if not evidence_refs:
+ gates.append(_gate("evidence.required", "scientific_evidence", "required scientific inputs current",
+ "blocked", rationale="missing required evidence (never N/A)",
+ remediation="materialize required evidence"))
+ else:
+ blocked = [str(e.get("evidence_id")) for e in evidence_refs
+ if str((e.get("environment_role") or "")) != "scientific"
+ or str(e.get("measurement_kind") or "") not in {"measured", "simulated", "remapped", "derived"}]
+ stale = [str(e.get("evidence_id")) for e in evidence_refs if e.get("current") is False]
+ if blocked:
+ gates.append(_gate("evidence.semantics", "scientific_evidence", "no fixture/transcribed-only",
+ "blocked", rationale=f"inadmissible: {blocked[:3]}"))
+ elif stale:
+ gates.append(_gate("evidence.currentness", "scientific_evidence", "inputs current",
+ "blocked", rationale=f"stale: {stale[:3]}"))
+ else:
+ gates.append(_gate("evidence.current", "scientific_evidence", "inputs current",
+ "passed", rationale="evidence refs current"))
+ for ledger_id in ledger_ids or ():
+ try:
+ from .result_ledger import verify_ledger
+
+ ledger = _validate_ledger_files(root, memory, ledger_id)
+ verification = verify_ledger(root, memory, ledger_id)
+ snapshots = ledger.get("snapshots") or []
+ valid = bool(verification.get("eligible_as_release_input") and snapshots and all(
+ s.get("environment_role") == "scientific" and s.get("measurement_kind") != "transcribed"
+ for s in snapshots))
+ gates.append(_gate(f"ledger.{ledger_id}", "scientific_evidence", "ledger current and scientific",
+ "passed" if valid else "blocked"))
+ except Exception:
+ gates.append(_gate(f"ledger.{ledger_id}", "scientific_evidence", "ledger current", "blocked"))
+
+ # C. scientific review: historical + current, reviewed vs caveats explicit.
+ review_ids = list(review_ids or [])
+ if not review_ids:
+ gates.append(_gate("review.required", "scientific_review", "review current",
+ "blocked", rationale="no review bound"))
+ else:
+ try:
+ from .scientific_review import verify_scientific_review
+
+ problems = []
+ for review_id in review_ids:
+ bundle = _json_file(root, f".paperforge/reviews/{_identifier(review_id)}/review.json")
+ for binding in bundle.get("ledger_bindings") or []:
+ _validate_ledger_files(root, memory, str(binding["ledger_id"]))
+ report = verify_scientific_review(root, memory, str(review_id))
+ if not report.get("currently_valid_as_review_input"):
+ problems.append(str(review_id))
+ from .scientific_review import Assumption, aggregate_review_state
+
+ assumptions = [Assumption(**a) for a in bundle.get("assumptions") or []]
+ relevance = {str(c): [a.assumption_id for a in assumptions]
+ for c in bundle.get("coverage") or {}}
+ review_state = aggregate_review_state(bundle.get("coverage") or {}, assumptions, relevance)
+ if review_state not in policy.allowed_review_states:
+ problems.append(f"{review_id}: state not allowed")
+ for path, sha in (bundle.get("fact_artifact_hashes") or {}).items():
+ if _file_hash(root, path) != sha:
+ problems.append(f"{review_id}: source changed")
+ gates.append(_gate(
+ "review.current", "scientific_review", "reviews currently valid",
+ "passed" if not problems else "blocked",
+ rationale="stale reviews never satisfy current gate" if problems else "reviews current"))
+ except Exception as exc:
+ gates.append(_gate("review.current", "scientific_review", "reviews currently valid",
+ "blocked", rationale=f"review check failed: {type(exc).__name__}"))
+
+ # D. reviewer resolution: required criteria only; prose never counts.
+ projection = dict(reviewer_projection or {})
+ required_states = []
+ try:
+ matrix_id = _identifier(str(projection.get("matrix_id") or ""))
+ matrix = _json_file(root, f".paperforge/review_matrix/{matrix_id}/matrix.json")
+ stable_matrix = {k: v for k, v in matrix.items()
+ if k not in {"matrix_id", "matrix_digest", "created_at", "matrix_file_sha256"}}
+ comments_valid = all(c.get("comment_digest") == hashlib.sha256(c.get("exact_text", "").encode()).hexdigest()
+ for c in matrix.get("comments") or [])
+ # The legacy matrix verifier visits optional bindings and may reconcile.
+ # Verify history here, then inspect only required bindings without repair.
+ if _digest(stable_matrix) != matrix.get("matrix_digest") or not comments_valid:
+ required_states = ["blocked"]
+ else:
+ required_ids = {c["criterion_id"] for c in matrix.get("criteria", []) if c.get("required")}
+ required_actions = [a for a in matrix.get("actions", [])
+ if required_ids.intersection(a.get("acceptance_criteria") or [])]
+ required_states = [str(a.get("status")) for a in required_actions]
+ referenced = {c for a in required_actions for c in a.get("acceptance_criteria") or []}
+ if not required_ids.issubset(referenced):
+ required_states.append("blocked")
+ for action in required_actions:
+ bindings = [b for b in matrix.get("bindings", []) if b.get("action_id") == action.get("action_id")]
+ satisfied = set()
+ for binding in bindings:
+ meta = binding.get("metadata") or {}
+ if not binding.get("expected_digest"):
+ continue
+ if binding.get("artifact_kind") == "human_verification":
+ bound = (meta.get("target_digest") == _digest(_target_binding(target))
+ and meta.get("verifier") and meta.get("verified_at")
+ and meta.get("rationale") and meta.get("verification_source") == "human_explicit"
+ and binding["expected_digest"] == _digest(meta))
+ elif binding.get("artifact_kind") == "imported_evidence":
+ eid = str(binding.get("artifact_id") or "")
+ bound = any(e.get("evidence_id") == eid and e.get("current") is not False
+ and e.get("environment_role") == "scientific"
+ and e.get("measurement_kind") in {"measured", "simulated", "remapped", "derived"}
+ for e in evidence_refs)
+ with memory.connect() as db:
+ row = db.execute("SELECT * FROM evidence WHERE id=?", (eid,)).fetchone()
+ bound = bool(bound and row and binding["expected_digest"] == row["content_sha256"])
+ else:
+ # Until a binding kind has a hash-aware release adapter,
+ # presence-only legacy verification cannot authorize it.
+ bound = False
+ if bound:
+ for criterion in matrix.get("criteria") or []:
+ cid = criterion["criterion_id"]
+ if cid not in (meta.get("satisfies") or []):
+ continue
+ allowed_bindings = {
+ "hardware_measurement": {"imported_evidence"},
+ "scientific_experiment": {"imported_evidence"},
+ "layout": {"human_verification"},
+ "manuscript_clarification": {"human_verification"},
+ }
+ if binding.get("artifact_kind") not in allowed_bindings.get(
+ criterion.get("criterion_type"), set()):
+ continue
+ if criterion.get("criterion_type") in {"hardware_measurement", "scientific_experiment"}:
+ if binding.get("artifact_kind") != "imported_evidence":
+ continue
+ if criterion.get("criterion_type") == "hardware_measurement" and not any(
+ e.get("evidence_id") == binding.get("artifact_id")
+ and e.get("measurement_kind") == "measured" for e in evidence_refs):
+ continue
+ satisfied.add(cid)
+ if not required_ids.intersection(action.get("acceptance_criteria") or []).issubset(satisfied):
+ required_states.append("blocked")
+ if not required_ids:
+ required_states = ["verified"]
+ except Exception:
+ required_states = ["blocked"]
+ if not required_states:
+ gates.append(_gate("reviewer.required", "reviewer_resolution", "required criteria verified",
+ "blocked", rationale="no required reviewer states bound"))
+ elif all(s == "verified" for s in required_states):
+ gates.append(_gate("reviewer.required", "reviewer_resolution", "required criteria verified",
+ "passed", rationale="required reviewer items verified"))
+ elif any(s in {"blocked", "partial"} for s in required_states):
+ gates.append(_gate("reviewer.required", "reviewer_resolution", "required criteria verified",
+ "blocked", rationale="required reviewer items blocked/partial"))
+ else:
+ strict = bool(policy.strict_reviewer_verification)
+ gates.append(_gate("reviewer.required", "reviewer_resolution", "required criteria verified",
+ "blocked" if strict else "needs_human",
+ rationale="addressed-but-not-verified under strict policy"))
+
+ # E. PDF QA: same SHA, current bundle, coverage, critical, target issues, human.
+ pdf_bundle_ids = list(pdf_bundle_ids or [])
+ if not pdf_bundle_ids:
+ gates.append(_gate("pdfqa.required", "pdf_layout_qa", "PDF QA current for target SHA",
+ "blocked", rationale="no PDF QA bundle bound"))
+ else:
+ try:
+ from .pdf_qa import verify_pdf_qa
+
+ problems = []
+ pending = []
+ for bundle_id in pdf_bundle_ids:
+ bundle = _json_file(root, f".paperforge/pdf_qa/{_identifier(bundle_id)}/qa.json")
+ report = verify_pdf_qa(root, memory, str(bundle_id))
+ # U3B's verifier includes bundle_id in its digest recomputation,
+ # although the producer excludes it. Validate the producer contract here.
+ stable_qa = {k: v for k, v in bundle.items()
+ if k not in {"bundle_id", "qa_digest", "created_at", "qa_file_sha256"}}
+ if _digest(stable_qa) != bundle.get("qa_digest"):
+ problems.append(f"{bundle_id}: bundle invalid")
+ continue
+ if (bundle.get("target_pdf_sha256") != target.final_pdf_sha256
+ or bundle.get("build_digest") != target.build_digest
+ or _file_hash(root, target.final_pdf_path) != target.final_pdf_sha256
+ or not _build_valid(root, target)):
+ problems.append(f"{bundle_id}: target/build mismatch")
+ if report.get("layout_qa_state") == "needs_human":
+ pending.append(bundle_id)
+ elif report.get("layout_qa_state") not in {"passed", "passed_with_warnings"}:
+ problems.append(f"{bundle_id}: state={report.get('layout_qa_state')}")
+ if report.get("unresolved_critical"):
+ problems.append(f"{bundle_id}: unresolved critical")
+ issues = bundle.get("layout_issues") or []
+ for issue in issues:
+ if issue.get("status") in {"open", "needs_human"}:
+ if issue.get("severity") == "critical" or issue.get("target_specific"):
+ problems.append(f"{bundle_id}: unresolved required layout issue")
+ elif issue.get("status") == "needs_human":
+ pending.append(bundle_id)
+ elif issue.get("category") not in policy.allowed_warning_classes:
+ problems.append(f"{bundle_id}: warning not allowed")
+ if report.get("layout_qa_state") == "passed_with_warnings" and not policy.allowed_warning_classes:
+ problems.append(f"{bundle_id}: warnings require explicit policy")
+ renders = bundle.get("render_manifest") or []
+ pages = {r.get("page"): r for r in renders}
+ count = (bundle.get("preflight") or {}).get("page_count", 0)
+ if not count or set(pages) != set(range(1, count + 1)) or any(
+ r.get("environment_role") != "production" for r in renders):
+ problems.append(f"{bundle_id}: incomplete or synthetic rendering")
+ human = bundle.get("human_reviews") or []
+ for page, render in pages.items():
+ matches = [h for h in human if h.get("page") == page
+ and h.get("pdf_sha256") == target.final_pdf_sha256
+ and h.get("render_sha256") == render.get("image_hash")
+ and h.get("environment_role") == "production"
+ and h.get("review_source") == "human_explicit"
+ and h.get("reviewer") and h.get("reviewed_at") and not h.get("stale")]
+ if not matches or not all(h.get("status") in {"passed", "passed_with_warnings"} for h in matches):
+ pending.append(bundle_id)
+ gates.append(_gate("pdfqa.current", "pdf_layout_qa", "PDF QA current",
+ "blocked" if problems else "needs_human" if pending else "passed",
+ rationale="; ".join(problems[:3]) if problems else "PDF QA current"))
+ except Exception as exc:
+ gates.append(_gate("pdfqa.current", "pdf_layout_qa", "PDF QA current",
+ "blocked", rationale=f"PDF QA check failed: {type(exc).__name__}"))
+
+ # F. human gates: explicit records only; the evaluator never mints approval.
+ human_records = list(human_records or [])
+ pdf_gate = next(g for g in gates if g.category == "pdf_layout_qa")
+ gates.append(_gate("human.pdf_review", "human_approval", "existing target-bound PDF human reviews",
+ pdf_gate.status, rationale="consume existing reviews; owner acknowledgement is separate authorization"))
+
+ # G/H. engineering + environment: unavailable/not_run never auto-pass.
+ engineering_checks = list(engineering_checks or [])
+ if not engineering_checks:
+ gates.append(_gate("engineering.required", "engineering_quality", "engineering checks recorded",
+ "blocked", rationale="no engineering checks bound"))
+ else:
+ for check in engineering_checks:
+ data = check.to_dict() if isinstance(check, EngineeringCheckResult) else dict(check)
+ status = str(data.get("status") or "not_run")
+ check_id = str(data.get("check_id") or data.get("command") or "check")
+ category = str(data.get("category") or "engineering_quality")
+ if category not in {"engineering_quality", "environment_readiness"}:
+ category = "engineering_quality"
+ if status == "passed":
+ valid_check = False
+ try:
+ record = _json_file(root, str(data.get("record_path") or ""))
+ valid_check = bool(
+ record.get("schema") == "paperforge.engineering-check/v1"
+ and record.get("target_digest") == _digest(_target_binding(target))
+ and record.get("result") == data
+ and data.get("currentness") == "current" and data.get("exit_code") == 0
+ and data.get("failed", 0) == 0 and data.get("errors", 0) == 0
+ and data.get("verifier") and data.get("command")
+ and not data.get("environment_findings")
+ and record.get("log_sha256") == _file_hash(root, str(data.get("log_artifact") or ""))
+ and re.fullmatch(r"[0-9a-f]{64}", str(record.get("log_sha256") or ""))
+ )
+ except (OSError, ValueError, TypeError, ReleaseEligibilityError):
+ pass
+ gates.append(_gate(f"engineering.{check_id}", category,
+ f"{check_id} passed", "passed" if valid_check else "blocked",
+ rationale="current target-bound result and log required"))
+ elif status in {"unavailable", "not_run"}:
+ gates.append(_gate(f"engineering.{check_id}", category,
+ f"{check_id} recorded",
+ "blocked" if policy.engineering_blocking else "needs_human",
+ rationale=f"{status}: environment finding, never auto-pass"))
+ elif status == "blocked_environment":
+ gates.append(_gate(f"engineering.{check_id}", "environment_readiness",
+ f"{check_id} environment", "blocked",
+ rationale="environment-blocked is distinct from code failure"))
+ else:
+ gates.append(_gate(f"engineering.{check_id}", category,
+ f"{check_id} recorded", "failed",
+ rationale=f"status={status}"))
+
+ # Aggregation: failed/blocked required -> NOT_ELIGIBLE; needs_human -> NEEDS_HUMAN.
+ required = set(policy.required_gates)
+ relevant = [g for g in gates if g.category in required]
+ for category in required - {g.category for g in relevant}:
+ missing = _gate(f"{category}.required", category, "required gate must be present", "blocked")
+ gates.append(missing)
+ relevant.append(missing)
+ blocking = [g for g in relevant if g.status in {"failed", "blocked"}]
+ human = [g for g in relevant if g.status == "needs_human"]
+ if blocking:
+ overall = "NOT_ELIGIBLE"
+ elif human:
+ overall = "NEEDS_HUMAN"
+ else:
+ overall = "ELIGIBLE"
+ stable = {
+ "schema": REPORT_SCHEMA,
+ "target": _target_binding(target),
+ "policy": policy.to_canonical(),
+ "policy_digest": policy.digest(),
+ "gates": sorted([g.to_dict() for g in gates], key=lambda g: str(g["gate_id"])),
+ "blocking_gates": sorted(g.gate_id for g in blocking),
+ "needs_human_gates": sorted(g.gate_id for g in human),
+ "overall_eligibility": overall,
+ "assessment_inputs": inputs,
+ "currentness_snapshot": _snapshot(root, memory, target, inputs),
+ }
+ digest = hashlib.sha256(_canonical(stable)).hexdigest()
+ report_id = f"release-{digest[:16]}"
+ payload = {**stable, "report_id": report_id, "report_digest": digest, "created_at": utc_now()}
+ return payload
+
+
+def freeze_assessment(workspace: str | Path, memory: Any, payload: Mapping[str, Any]) -> dict[str, Any]:
+ """Explicit audit persistence, separate from the read-only evaluator."""
+ root = Path(workspace).expanduser().resolve(strict=True)
+ report_id = _identifier(str(payload["report_id"]))
+ stable = {k: v for k, v in payload.items() if k not in {"report_id", "report_digest", "created_at"}}
+ digest = _digest(stable)
+ if digest != payload.get("report_digest") or report_id != f"release-{digest[:16]}":
+ raise ReleaseEligibilityError("assessment digest mismatch")
+ target = ReleaseTarget(**payload["target"])
+ policy = ReleasePolicy(**{k: v for k, v in payload["policy"].items() if k != "schema"})
+ current = evaluate_release(root, memory, target, policy, **payload["assessment_inputs"])
+ if current["report_digest"] != digest:
+ raise ReleaseEligibilityError("assessment changed before freeze")
+ report_dir = safe_mkdir(root / ".paperforge" / "release" / report_id, anchor=root)
+ existing = report_dir / "report.json"
+ if existing.exists():
+ previous = _json_file(root, existing.relative_to(root).as_posix())
+ if {k: v for k, v in previous.items() if k != "created_at"} != {
+ k: v for k, v in payload.items() if k != "created_at"}:
+ raise ReleaseEligibilityError("frozen assessment collision")
+ return previous
+ for name, content in (
+ ("target.json", {"target": target.to_dict()}),
+ ("report.json", payload),
+ ("manifest.json", {"report_id": report_id, "report_digest": digest,
+ "target_id": target.target_id, "policy_digest": policy.digest()}),
+ ):
+ atomic_write_text(root, f".paperforge/release/{report_id}/{name}",
+ json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
+ from .artifacts import ArtifactStore
+
+ store = ArtifactStore(root, allowed_roots=(".paperforge/release",),
+ allowed_suffixes=(".json",),
+ allowed_kinds=("release", "manifest", "report"), memory=memory)
+ metadata = {"report_id": report_id, "report_digest": digest, "target_id": target.target_id,
+ "policy_digest": policy.digest(), "overall_eligibility": payload["overall_eligibility"],
+ "note": "release assessment, not scientific evidence"}
+ for name, kind in (("report.json", "release"), ("manifest.json", "manifest")):
+ store.register(f".paperforge/release/{report_id}/{name}", kind=kind,
+ status="VERIFIED", media_type="application/json", metadata=metadata)
+ return dict(payload)
+
+
+def assessment_current(workspace: str | Path, memory: Any, report_id: str, *,
+ current_policy: ReleasePolicy | None = None) -> dict[str, Any]:
+ """Old assessments stay historical; currentness is recomputed, never rewritten."""
+ root = Path(workspace).expanduser().resolve(strict=True)
+ payload = _json_file(root, f".paperforge/release/{_identifier(report_id)}/report.json")
+ stored = str(payload.get("report_digest") or "")
+ stable = {k: payload[k] for k in payload
+ if k not in {"report_id", "report_digest", "created_at", "report_file_sha256"}}
+ valid = (stored == _digest(stable) and report_id == f"release-{stored[:16]}"
+ and payload.get("report_id") == report_id)
+ current = False
+ if valid:
+ try:
+ policy = ReleasePolicy(**{k: v for k, v in payload["policy"].items() if k != "schema"})
+ fresh = evaluate_release(root, memory, ReleaseTarget(**payload["target"]), policy,
+ **payload["assessment_inputs"])
+ current = fresh["report_digest"] == stored
+ if current_policy is not None:
+ current = current and current_policy.digest() == payload["policy_digest"]
+ except (OSError, ValueError, TypeError, KeyError, ReleaseEligibilityError):
+ current = False
+ return {"report_id": report_id, "report_digest_valid": valid,
+ "historical_integrity": "valid" if valid else "invalid",
+ "currently_valid": bool(valid and current),
+ "overall_eligibility": payload.get("overall_eligibility")}
+
+
+def record_release_acknowledgement(
+ workspace: str | Path, memory: Any, report_id: str, *, approver: str, rationale: str,
+ current_policy: ReleasePolicy | None = None,
+) -> dict[str, Any]:
+ """Record an explicit operator action; callers must authenticate the operator.
+
+ This local audit record is not a digital signature or scientific approval.
+ No evaluator, retry, or status refresh calls this function.
+ """
+ root = Path(workspace).expanduser().resolve(strict=True)
+ state = assessment_current(root, memory, report_id, current_policy=current_policy)
+ if not state["currently_valid"] or state["overall_eligibility"] != "ELIGIBLE":
+ raise ReleaseEligibilityError("only a current eligible assessment can be acknowledged")
+ if not approver.strip() or not rationale.strip():
+ raise ReleaseEligibilityError("explicit approver and rationale required")
+ report = _json_file(root, f".paperforge/release/{_identifier(report_id)}/report.json")
+ stable = {
+ "schema": "paperforge.release-acknowledgement/v1", "report_id": report_id,
+ "assessment_digest": report["report_digest"], "target_digest": _digest(report["target"]),
+ "policy_digest": report["policy_digest"], "approver": approver, "rationale": rationale,
+ "decision": "acknowledged", "recorded_at": utc_now(),
+ }
+ digest = _digest(stable)
+ ack_id = f"ack-{digest[:16]}"
+ payload = {**stable, "ack_id": ack_id, "ack_digest": digest}
+ atomic_write_text(root, f".paperforge/release_acknowledgements/{ack_id}.json",
+ json.dumps(payload, sort_keys=True, indent=2) + "\n")
+ return payload
+
+
+def release_authorization(workspace: str | Path, memory: Any, report_id: str, *,
+ ack_id: str = "", current_policy: ReleasePolicy | None = None) -> dict[str, Any]:
+ """Eligibility != authorization != publication. U4B performs no release."""
+ root = Path(workspace).expanduser().resolve(strict=True)
+ state = assessment_current(root, memory, report_id, current_policy=current_policy)
+ report = _json_file(root, f".paperforge/release/{_identifier(report_id)}/report.json")
+ authorization = "BLOCKED"
+ if state["currently_valid"] and state["overall_eligibility"] == "ELIGIBLE":
+ authorization = "NOT_REQUIRED" if not report["policy"]["require_human_owner_ack"] else "NEEDS_HUMAN"
+ if ack_id:
+ try:
+ ack = _json_file(root, f".paperforge/release_acknowledgements/{_identifier(ack_id)}.json")
+ stable = {k: v for k, v in ack.items() if k not in {"ack_id", "ack_digest"}}
+ valid = (
+ ack.get("schema") == "paperforge.release-acknowledgement/v1"
+ and ack.get("ack_digest") == _digest(stable)
+ and ack.get("ack_id") == ack_id == f"ack-{_digest(stable)[:16]}"
+ and ack.get("report_id") == report_id
+ and ack.get("assessment_digest") == report["report_digest"]
+ and ack.get("target_digest") == _digest(report["target"])
+ and ack.get("policy_digest") == report["policy_digest"]
+ and ack.get("decision") == "acknowledged"
+ and str(ack.get("approver", "")).strip()
+ and str(ack.get("recorded_at", "")).strip()
+ )
+ if valid:
+ authorization = "AUTHORIZED"
+ except (OSError, ValueError, TypeError, ReleaseEligibilityError):
+ pass
+ return {**state, "authorization_state": authorization, "release_state": "NOT_RELEASED"}
+
+
+__all__ = [
+ "CATEGORIES",
+ "EngineeringCheckResult",
+ "POLICY_SCHEMA",
+ "POLICY_VERSION",
+ "REPORT_SCHEMA",
+ "ReleaseEligibilityError",
+ "ReleaseGateResult",
+ "ReleasePolicy",
+ "ReleaseTarget",
+ "assessment_current",
+ "evaluate_release",
+ "freeze_assessment",
+ "record_release_acknowledgement",
+ "release_authorization",
+]
diff --git a/paperforge/run_status.py b/paperforge/run_status.py
index 2d0b9b7..265f895 100644
--- a/paperforge/run_status.py
+++ b/paperforge/run_status.py
@@ -67,6 +67,7 @@ class UnifiedRunStatus:
updated_at: str = ""
# Deprecated compat: mirrors workflow_state, never process state.
status: str = ""
+ release_assessment: Mapping[str, Any] = field(default_factory=dict)
def __post_init__(self) -> None:
if self.process_state not in PROCESS_STATES:
@@ -144,6 +145,8 @@ def _classify_relation(workflow_state: str, process_state: str) -> tuple[str, st
def build_unified_status(
workflow_state: Mapping[str, Any],
process_payload: Mapping[str, Any] | None = None,
+ *,
+ release_assessment: Mapping[str, Any] | None = None,
) -> UnifiedRunStatus:
"""Build the shared projection. Read-only: never writes domain or process state."""
run_id = str(workflow_state.get("id") or "")
@@ -177,6 +180,12 @@ def build_unified_status(
review_ids=(),
updated_at=str(workflow_state.get("updated_at") or ""),
status=state,
+ release_assessment={
+ **{key: release_assessment[key] for key in (
+ "report_id", "overall_eligibility", "currently_valid", "authorization_state", "release_state"
+ ) if key in release_assessment},
+ "authoritative": False,
+ } if release_assessment else {},
)
diff --git a/tests/test_u4b_finalization.py b/tests/test_u4b_finalization.py
new file mode 100644
index 0000000..4d238f2
--- /dev/null
+++ b/tests/test_u4b_finalization.py
@@ -0,0 +1,372 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import replace
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.release_eligibility import (
+ ReleasePolicy,
+ ReleaseTarget,
+ assessment_current,
+ evaluate_release,
+)
+
+
+def setup_target(root):
+ hashes = {}
+ for name, data in {"main.tex": b"source", "refs.bib": b"bibliography", "final.pdf": b"pdf"}.items():
+ (root / name).write_bytes(data)
+ hashes[name] = hashlib.sha256(data).hexdigest()
+ build = {
+ "schema": "paperforge.build-provenance/v1",
+ "status": "succeeded",
+ "source_hashes": {"main.tex": hashes["main.tex"], "refs.bib": hashes["refs.bib"]},
+ "output_path": "final.pdf",
+ "output_sha256": hashes["final.pdf"],
+ "command": ["compiler", "main.tex"],
+ "toolchain": {"compiler": "test-v1"},
+ }
+ raw = json.dumps(build, sort_keys=True).encode()
+ (root / "build.json").write_bytes(raw)
+ target = ReleaseTarget(
+ target_id="t1", manuscript_path="main.tex", manuscript_sha256=hashes["main.tex"],
+ final_pdf_path="final.pdf", final_pdf_sha256=hashes["final.pdf"],
+ bibliography_hashes={"refs.bib": hashes["refs.bib"]},
+ build_manifest_path="build.json", build_digest=hashlib.sha256(raw).hexdigest(),
+ )
+ return PaperForgeService(root), target, ReleasePolicy(required_gates=("source_integrity",))
+
+
+def test_missing_source_never_passes(tmp_path):
+ service = PaperForgeService(tmp_path)
+ report = evaluate_release(tmp_path, service.memory, ReleaseTarget("empty"),
+ ReleasePolicy(required_gates=("source_integrity",)))
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_build_is_required_and_binds_exact_inputs(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ assert evaluate_release(tmp_path, service.memory, target, policy)["overall_eligibility"] == "ELIGIBLE"
+ missing = replace(target, build_manifest_path="", build_digest="")
+ assert evaluate_release(tmp_path, service.memory, missing, policy)["overall_eligibility"] == "NOT_ELIGIBLE"
+ (tmp_path / "main.tex").write_bytes(b"new source")
+ changed = replace(target, manuscript_sha256=hashlib.sha256(b"new source").hexdigest())
+ assert evaluate_release(tmp_path, service.memory, changed, policy)["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_evaluator_has_no_filesystem_or_database_writes(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ files = {str(p.relative_to(tmp_path)): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
+ evaluate_release(tmp_path, service.memory, target, policy)
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ assert {str(p.relative_to(tmp_path)): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == files
+
+
+@pytest.mark.parametrize("filename", ["main.tex", "final.pdf", "refs.bib", "build.json"])
+def test_assessment_rechecks_upstream_without_rewriting_history(tmp_path, filename):
+ from paperforge.release_eligibility import freeze_assessment
+
+ service, target, policy = setup_target(tmp_path)
+ report = evaluate_release(tmp_path, service.memory, target, policy)
+ freeze_assessment(tmp_path, service.memory, report)
+ path = tmp_path / ".paperforge/release" / report["report_id"] / "report.json"
+ original = path.read_bytes()
+ assert assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+ (tmp_path / filename).write_bytes(b"changed")
+ state = assessment_current(tmp_path, service.memory, report["report_id"])
+ assert state["historical_integrity"] == "valid"
+ assert not state["currently_valid"]
+ assert path.read_bytes() == original
+
+
+def test_target_timestamp_does_not_change_assessment_digest(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ a = evaluate_release(tmp_path, service.memory, target, policy)
+ b = evaluate_release(tmp_path, service.memory, replace(target, created_at="tomorrow"), policy)
+ assert a["report_digest"] == b["report_digest"]
+
+
+def test_acknowledgement_is_bound_and_not_a_release(tmp_path):
+ from paperforge.release_eligibility import (
+ freeze_assessment,
+ record_release_acknowledgement,
+ release_authorization,
+ )
+
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, require_human_owner_ack=True)
+ report = evaluate_release(tmp_path, service.memory, target, policy)
+ freeze_assessment(tmp_path, service.memory, report)
+ assert report["overall_eligibility"] == "ELIGIBLE"
+ pending = release_authorization(tmp_path, service.memory, report["report_id"])
+ assert pending["authorization_state"] == "NEEDS_HUMAN"
+ ack = record_release_acknowledgement(
+ tmp_path, service.memory, report["report_id"], approver="owner", rationale="checked",
+ )
+ authorized = release_authorization(tmp_path, service.memory, report["report_id"], ack_id=ack["ack_id"])
+ assert authorized["authorization_state"] == "AUTHORIZED"
+ assert authorized["release_state"] == "NOT_RELEASED"
+ changed_policy = replace(policy, policy_id="replacement")
+ assert release_authorization(tmp_path, service.memory, report["report_id"], ack_id=ack["ack_id"],
+ current_policy=changed_policy)["authorization_state"] == "BLOCKED"
+ with pytest.raises(Exception, match="current eligible"):
+ record_release_acknowledgement(tmp_path, service.memory, report["report_id"],
+ approver="owner", rationale="changed policy", current_policy=changed_policy)
+ other = evaluate_release(tmp_path, service.memory, replace(target, target_id="other"), policy)
+ freeze_assessment(tmp_path, service.memory, other)
+ assert release_authorization(tmp_path, service.memory, other["report_id"],
+ ack_id=ack["ack_id"])["authorization_state"] != "AUTHORIZED"
+ (tmp_path / "main.tex").write_bytes(b"changed")
+ assert release_authorization(tmp_path, service.memory, report["report_id"],
+ ack_id=ack["ack_id"])["authorization_state"] == "BLOCKED"
+
+
+@pytest.mark.parametrize("path", ["../outside", "/etc/hosts", "*.tex"])
+def test_untrusted_paths_fail_closed(tmp_path, path):
+ service, target, policy = setup_target(tmp_path)
+ report = evaluate_release(tmp_path, service.memory, replace(target, manuscript_path=path), policy)
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_symlink_source_fails_closed(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ (tmp_path / "alias.tex").symlink_to(tmp_path / "main.tex")
+ report = evaluate_release(tmp_path, service.memory, replace(target, manuscript_path="alias.tex"), policy)
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def canonical_digest(value):
+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
+ separators=(",", ":")).encode()).hexdigest()
+
+
+def bound_check(root, target, category="engineering_quality", **overrides):
+ from paperforge.release_eligibility import EngineeringCheckResult
+
+ log = f"{category}.log"
+ record_path = f"{category}.json"
+ (root / log).write_bytes(b"verification log")
+ data = EngineeringCheckResult(check_id=category, category=category, command="verify",
+ status="passed", exit_code=0, verifier="operator",
+ log_artifact=log, record_path=record_path).to_dict()
+ data.update(overrides)
+ target_data = {k: v for k, v in target.to_dict().items() if k != "created_at"}
+ (root / record_path).write_text(json.dumps({
+ "schema": "paperforge.engineering-check/v1", "target_digest": canonical_digest(target_data),
+ "result": data, "log_sha256": hashlib.sha256(b"verification log").hexdigest(),
+ }))
+ return data
+
+
+@pytest.mark.parametrize("overrides", [{"currentness": "stale"}, {"exit_code": 1},
+ {"failed": 1}, {"errors": 1}, {"record_path": ""}])
+def test_engineering_false_pass_rejected(tmp_path, overrides):
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("engineering_quality",))
+ check = bound_check(tmp_path, target)
+ check.update(overrides)
+ report = evaluate_release(tmp_path, service.memory, target, policy, engineering_checks=[check])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_engineering_and_environment_pass_then_log_change_stales(tmp_path):
+ from paperforge.release_eligibility import freeze_assessment
+
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("source_integrity", "engineering_quality", "environment_readiness"))
+ checks = [bound_check(tmp_path, target, category) for category in
+ ("engineering_quality", "environment_readiness")]
+ report = evaluate_release(tmp_path, service.memory, target, policy, engineering_checks=checks)
+ assert report["overall_eligibility"] == "ELIGIBLE"
+ freeze_assessment(tmp_path, service.memory, report)
+ (tmp_path / "environment_readiness.log").write_bytes(b"different")
+ assert not assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+
+
+def matrix_fixture(root, service, target, *, bind=True, optional=False):
+ from paperforge.reviewer_matrix import (
+ AcceptanceCriterion, EvidenceBinding, ReviewerAction, ReviewerComment, freeze_review_matrix,
+ )
+
+ target_data = {k: v for k, v in target.to_dict().items() if k != "created_at"}
+ meta = {"target_digest": canonical_digest(target_data), "verifier": "owner", "verified_at": "t",
+ "rationale": "reviewed", "verification_source": "human_explicit", "satisfies": ["k"]}
+ actions = [ReviewerAction("a", "c", "required action", acceptance_criteria=("k",), status="verified")]
+ criteria = [AcceptanceCriterion("k", "layout")]
+ if optional:
+ actions.append(ReviewerAction("optional", "c", "not done", acceptance_criteria=("opt",)))
+ criteria.append(AcceptanceCriterion("opt", "layout", required=False))
+ return freeze_review_matrix(root, service.memory,
+ comments=[ReviewerComment("c", "R", "Check layout")], actions=actions,
+ criteria=criteria, bindings=[EvidenceBinding(
+ "b", "a", "human_verification", "verification", canonical_digest(meta),
+ metadata=meta)] if bind else [])
+
+
+def test_verified_matrix_requires_bound_verification_and_ignores_optional(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("source_integrity", "reviewer_resolution"))
+ for bind, expected in [(False, "NOT_ELIGIBLE"), (True, "ELIGIBLE")]:
+ matrix = matrix_fixture(tmp_path, service, target, bind=bind, optional=True)
+ report = evaluate_release(tmp_path, service.memory, target, policy,
+ reviewer_projection={"matrix_id": matrix["matrix_id"]})
+ assert report["overall_eligibility"] == expected
+
+
+def pdf_fixture(root, target, *, state="passed", warning_class="", pdf_sha=None):
+ page = {"page": 1, "image_hash": "a" * 64, "environment_role": "production"}
+ human = {"page": 1, "render_sha256": "a" * 64, "pdf_sha256": target.final_pdf_sha256,
+ "environment_role": "production", "review_source": "human_explicit", "reviewer": "owner",
+ "reviewed_at": "t", "status": "passed"}
+ payload = {"schema": "paperforge.pdf-qa-bundle/v1", "target_pdf_sha256": pdf_sha or target.final_pdf_sha256,
+ "build_digest": target.build_digest, "preflight": {"page_count": 1},
+ "render_manifest": [page], "human_reviews": [] if state == "needs_human" else [human],
+ "layout_qa_state": state, "unresolved_critical": [], "page_coverage_complete": True,
+ "layout_issues": [{"issue_id": "w", "category": warning_class, "severity": "warning", "status": "open"}]
+ if warning_class else []}
+ digest = canonical_digest(payload)
+ bundle_id = f"qa-{digest[:16]}"
+ payload.update(bundle_id=bundle_id, qa_digest=digest, created_at="t")
+ folder = root / ".paperforge/pdf_qa" / bundle_id
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "qa.json").write_text(json.dumps(payload))
+ return bundle_id
+
+
+@pytest.mark.parametrize("state,warnings,allowed,expected", [
+ ("passed", "", (), "ELIGIBLE"),
+ ("needs_human", "", (), "NEEDS_HUMAN"),
+ ("passed_with_warnings", "font", (), "NOT_ELIGIBLE"),
+ ("passed_with_warnings", "font", ("font",), "ELIGIBLE"),
+ ("passed_with_warnings", "font", ("other",), "NOT_ELIGIBLE"),
+])
+def test_pdf_policy_and_human_gate(tmp_path, state, warnings, allowed, expected):
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("source_integrity", "pdf_layout_qa"), allowed_warning_classes=allowed)
+ bundle_id = pdf_fixture(tmp_path, target, state=state, warning_class=warnings)
+ report = evaluate_release(tmp_path, service.memory, target, policy, pdf_bundle_ids=[bundle_id])
+ assert report["overall_eligibility"] == expected
+
+
+def test_pdf_from_another_target_rejected(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("pdf_layout_qa",))
+ bundle_id = pdf_fixture(tmp_path, target, pdf_sha="f" * 64)
+ report = evaluate_release(tmp_path, service.memory, target, policy, pdf_bundle_ids=[bundle_id])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_evidence_caller_metadata_cannot_override_memory(tmp_path):
+ service, target, policy = setup_target(tmp_path)
+ policy = replace(policy, required_gates=("scientific_evidence",))
+ eid = service.memory.add_evidence(evidence_type="TEST", excerpt="fixture",
+ metadata={"environment_role": "fixture", "measurement_kind": "measured"})
+ report = evaluate_release(tmp_path, service.memory, target, policy, evidence_refs=[{
+ "evidence_id": eid, "environment_role": "scientific", "measurement_kind": "measured", "current": True}])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_domain_evidence_change_stales_report(tmp_path):
+ from paperforge.release_eligibility import freeze_assessment
+
+ service, target, policy = setup_target(tmp_path)
+ eid = service.memory.add_evidence(evidence_type="TEST", excerpt="test observation",
+ metadata={"environment_role": "scientific", "measurement_kind": "measured"})
+ policy = replace(policy, required_gates=("scientific_evidence",))
+ report = evaluate_release(tmp_path, service.memory, target, policy, evidence_refs=[{"evidence_id": eid}])
+ assert report["overall_eligibility"] == "ELIGIBLE"
+ freeze_assessment(tmp_path, service.memory, report)
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM evidence WHERE id=?", (eid,))
+ assert not assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+
+
+def test_default_policy_all_gates_then_external_source_change(tmp_path):
+ from paperforge.evidence_semantics import EvidenceSemantics
+ from paperforge.external_import import approve_import, materialize_import, stage_import, validate_import
+ from paperforge.release_eligibility import freeze_assessment
+ from paperforge.scientific_review import ScientificClaim, freeze_review, review_claim
+
+ service, target, _ = setup_target(tmp_path)
+ (tmp_path / "observation.json").write_text('{"latency_ms": 22.4}')
+ record = stage_import(tmp_path, service.memory,
+ semantics=EvidenceSemantics.from_metadata({
+ "measurement_kind": "measured", "acquisition_origin": "external_import",
+ "environment_role": "scientific"}),
+ subject={"model_id": "m", "dataset_id": "d", "seed": 0},
+ execution={"device": "test-device", "runtime": "test-runtime", "timing_scope": "inference_only"},
+ source_files=["observation.json"])
+ validation = validate_import(tmp_path, service.memory, record.import_id)
+ approve_import(tmp_path, service.memory, record.import_id, approver="test-owner",
+ acknowledged_checks=[c["check_id"] for c in validation["checks"] if c["status"] == "needs_human"],
+ rationale="isolated test fixture")
+ evidence = materialize_import(tmp_path, service.memory, record.import_id)
+ claim = ScientificClaim("claim", "A descriptive value.", "descriptive_metric", fact_ids=("f",))
+ review = freeze_review(tmp_path, service.memory, claims=[claim], results=review_claim(claim, facts={"f": {}}),
+ fact_artifact_hashes={"main.tex": target.manuscript_sha256})
+ matrix = matrix_fixture(tmp_path, service, target, optional=True)
+ bundle_id = pdf_fixture(tmp_path, target)
+ checks = [bound_check(tmp_path, target, category) for category in
+ ("engineering_quality", "environment_readiness")]
+ inputs = {"evidence_refs": [{"evidence_id": e} for e in evidence["evidence_ids"]],
+ "review_ids": [review["review_id"]], "reviewer_projection": {"matrix_id": matrix["matrix_id"]},
+ "pdf_bundle_ids": [bundle_id], "engineering_checks": checks}
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ report = evaluate_release(tmp_path, service.memory, target, ReleasePolicy(), **inputs)
+ assert report["overall_eligibility"] == "ELIGIBLE", report["gates"]
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ freeze_assessment(tmp_path, service.memory, report)
+ assert assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+ assert not assessment_current(tmp_path, service.memory, report["report_id"],
+ current_policy=ReleasePolicy(policy_id="replacement"))["currently_valid"]
+ source = tmp_path / ".paperforge/imports" / record.import_id / "sources/observation.json"
+ original = source.read_bytes()
+ source.unlink()
+ source.symlink_to(tmp_path / "observation.json")
+ assert evaluate_release(tmp_path, service.memory, target, ReleasePolicy(), **inputs)["overall_eligibility"] == "NOT_ELIGIBLE"
+ source.unlink()
+ source.write_bytes(original)
+ source.write_text('{"latency_ms": 99}')
+ assert not assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+ assert evaluate_release(tmp_path, service.memory, target, ReleasePolicy(), **inputs)["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_unified_release_summary_is_only_a_projection():
+ from paperforge.run_status import build_unified_status
+
+ status = build_unified_status({"id": "run", "status": "RUNNING"},
+ {"status": "completed", "exit_code": 0},
+ release_assessment={"report_id": "r", "overall_eligibility": "ELIGIBLE",
+ "authorization_state": "AUTHORIZED", "release_state": "NOT_RELEASED"})
+ assert status.workflow_state == "RUNNING"
+ assert status.release_assessment["authoritative"] is False
+ assert status.release_assessment["release_state"] == "NOT_RELEASED"
+
+
+@pytest.mark.parametrize("criterion_type", ["layout", "manuscript_clarification", "unknown_future_criterion"])
+def test_measurement_cannot_satisfy_unrelated_reviewer_criterion(tmp_path, criterion_type):
+ from paperforge.reviewer_matrix import (
+ AcceptanceCriterion, EvidenceBinding, ReviewerAction, ReviewerComment, freeze_review_matrix,
+ )
+
+ service, target, policy = setup_target(tmp_path)
+ eid = service.memory.add_evidence(evidence_type="TEST", excerpt="measurement",
+ metadata={"measurement_kind": "measured", "environment_role": "scientific"})
+ matrix = freeze_review_matrix(tmp_path, service.memory,
+ comments=[ReviewerComment("c", "R", "Check")],
+ actions=[ReviewerAction("a", "c", "done", acceptance_criteria=("k",), status="verified")],
+ criteria=[AcceptanceCriterion("k", criterion_type)],
+ bindings=[EvidenceBinding("b", "a", "imported_evidence", eid,
+ hashlib.sha256(b"measurement").hexdigest(), metadata={"satisfies": ["k"]})])
+ report = evaluate_release(tmp_path, service.memory, target,
+ replace(policy, required_gates=("reviewer_resolution",)),
+ evidence_refs=[{"evidence_id": eid}], reviewer_projection={"matrix_id": matrix["matrix_id"]})
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
diff --git a/tests/test_u4b_release.py b/tests/test_u4b_release.py
new file mode 100644
index 0000000..9110bb8
--- /dev/null
+++ b/tests/test_u4b_release.py
@@ -0,0 +1,243 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.release_eligibility import (
+ EngineeringCheckResult,
+ ReleaseEligibilityError,
+ ReleasePolicy,
+ ReleaseTarget,
+ assessment_current,
+ evaluate_release,
+ freeze_assessment,
+ release_authorization,
+)
+
+
+def _service(tmp_path: Path) -> PaperForgeService:
+ return PaperForgeService(tmp_path)
+
+
+def _target(tmp_path: Path, manuscript: bytes = b"manuscript v1", pdf: bytes = b"%PDF-1.4 v1") -> ReleaseTarget:
+ (tmp_path / "main.tex").write_bytes(manuscript)
+ (tmp_path / "final.pdf").write_bytes(pdf)
+ build = {"schema": "paperforge.build-provenance/v1", "status": "succeeded",
+ "source_hashes": {"main.tex": hashlib.sha256(manuscript).hexdigest()},
+ "output_path": "final.pdf", "output_sha256": hashlib.sha256(pdf).hexdigest(),
+ "command": ["compiler", "main.tex"], "toolchain": {"compiler": "test"}}
+ raw = json.dumps(build).encode()
+ (tmp_path / "build.json").write_bytes(raw)
+ return ReleaseTarget(
+ target_id="t1", manuscript_path="main.tex",
+ manuscript_sha256=hashlib.sha256(manuscript).hexdigest(),
+ final_pdf_path="final.pdf", final_pdf_sha256=hashlib.sha256(pdf).hexdigest(),
+ build_manifest_path="build.json", build_digest=hashlib.sha256(raw).hexdigest())
+
+
+def _policy(**overrides):
+ base = {"required_gates": ("source_integrity",)}
+ base.update(overrides)
+ return ReleasePolicy(**base)
+
+
+def test_source_hash_mismatch() -> None: # 1,2
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ bad = ReleaseTarget(target_id="t1", manuscript_path="main.tex", manuscript_sha256="0" * 64,
+ final_pdf_path="final.pdf", final_pdf_sha256=target.final_pdf_sha256)
+ report = evaluate_release(root, service.memory, bad, _policy())
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_stale_build_binding() -> None: # 3
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ (root / "main.tex").write_bytes(b"manuscript v2")
+ report = evaluate_release(root, service.memory, target, _policy())
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_fixture_and_transcribed_blocked() -> None: # 4,5
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity", "scientific_evidence"))
+ report = evaluate_release(root, service.memory, target, policy, evidence_refs=[
+ {"evidence_id": "e1", "environment_role": "fixture", "measurement_kind": "measured", "current": True}])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+ report2 = evaluate_release(root, service.memory, target, policy, evidence_refs=[
+ {"evidence_id": "e2", "environment_role": "scientific", "measurement_kind": "transcribed", "current": True}])
+ assert report2["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_ledger_current_and_stale() -> None: # 6,7
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger, verify_ledger
+
+ eid = service.memory.add_evidence(
+ evidence_type="EXTERNAL_MEASUREMENT", excerpt="m 1 ms", path="m.txt", config_scope="t",
+ metadata={"measurement_kind": "measured", "acquisition_origin": "paperforge_run",
+ "environment_role": "scientific", "metric_name": "latency_ms",
+ "value_str": "1", "unit": "ms",
+ "run_identity": {"schema": "paperforge.scientific-run-identity/v1"}})
+ ledger = freeze_ledger(root, service.memory, ResultLedgerQuery(
+ purpose="scientific", metric_names=["latency_ms"], evidence_ids=(eid,)))
+ assert verify_ledger(root, service.memory, ledger["ledger_id"])["eligible_as_release_input"] is True
+
+
+def test_review_states_distinguished() -> None: # 8,9,10
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity", "scientific_review"))
+ report = evaluate_release(root, service.memory, target, policy, review_ids=["review-missing"])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_reviewer_required_states() -> None: # 11,12,13,14
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity", "reviewer_resolution"))
+ blocked = evaluate_release(root, service.memory, target, policy,
+ reviewer_projection={"required_states": ["partial"]})
+ assert blocked["overall_eligibility"] == "NOT_ELIGIBLE"
+ verified = evaluate_release(root, service.memory, target, policy,
+ reviewer_projection={"required_states": ["verified"]})
+ # An unbound caller projection cannot stand in for a persisted matrix.
+ assert verified["overall_eligibility"] == "NOT_ELIGIBLE"
+ addressed = evaluate_release(root, service.memory, target, policy,
+ reviewer_projection={"required_states": ["addressed"]})
+ assert addressed["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_pdf_human_and_stale_and_critical() -> None: # 15,16,17
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity", "pdf_layout_qa"))
+ report = evaluate_release(root, service.memory, target, policy, pdf_bundle_ids=[])
+ assert report["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_warnings_policy_and_human_records() -> None: # 18,19,20
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity",),
+ require_human_owner_ack=True)
+ needs = evaluate_release(root, service.memory, target, policy, human_records=[])
+ assert needs["overall_eligibility"] == "ELIGIBLE"
+ freeze_assessment(root, service.memory, needs)
+ assert release_authorization(root, service.memory, needs["report_id"])["authorization_state"] == "NEEDS_HUMAN"
+ explicit = evaluate_release(root, service.memory, target, policy, human_records=[
+ {"kind": "owner_ack", "approver": "owner", "recorded_at": "t"}])
+ assert explicit["overall_eligibility"] == "ELIGIBLE"
+ freeze_assessment(root, service.memory, explicit)
+ assert release_authorization(root, service.memory, explicit["report_id"])["authorization_state"] == "NEEDS_HUMAN"
+
+
+def test_engineering_statuses() -> None: # 21,22,23,24
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = ReleasePolicy(required_gates=("source_integrity", "engineering_quality",
+ "environment_readiness"))
+ failed = evaluate_release(root, service.memory, target, policy, engineering_checks=[
+ EngineeringCheckResult(check_id="pytest", command="pytest", status="failed", exit_code=1)])
+ assert failed["overall_eligibility"] == "NOT_ELIGIBLE"
+ unavailable = evaluate_release(root, service.memory, target, policy, engineering_checks=[
+ EngineeringCheckResult(check_id="ruff", command="ruff", status="unavailable")])
+ assert unavailable["overall_eligibility"] == "NOT_ELIGIBLE"
+ env_blocked = evaluate_release(root, service.memory, target, policy, engineering_checks=[
+ EngineeringCheckResult(check_id="x", command="x", status="blocked_environment")])
+ assert env_blocked["overall_eligibility"] == "NOT_ELIGIBLE"
+
+
+def test_aggregation_and_digest() -> None: # 25,26,27,28,29,30
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ policy = _policy()
+ first = evaluate_release(root, service.memory, target, policy)
+ second = evaluate_release(root, service.memory, target, policy)
+ assert first["report_digest"] == second["report_digest"]
+ assert first["overall_eligibility"] == "ELIGIBLE"
+ freeze_assessment(root, service.memory, first)
+ assert assessment_current(root, service.memory, first["report_id"])["currently_valid"] is True
+
+
+def test_no_side_effects_and_not_evidence() -> None: # 31,32,33
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ service = _service(root)
+ target = _target(root)
+ with service.memory.connect() as db:
+ before = db.execute("SELECT COUNT(*) AS c FROM evidence").fetchone()["c"]
+ report = evaluate_release(root, service.memory, target, _policy())
+ with service.memory.connect() as db:
+ after = db.execute("SELECT COUNT(*) AS c FROM evidence").fetchone()["c"]
+ assert before == after
+ with service.memory.connect() as db:
+ rows = db.execute("SELECT * FROM artifacts WHERE path LIKE '%release%'").fetchall()
+ assert not rows
+ freeze_assessment(root, service.memory, report)
+ with service.memory.connect() as db:
+ rows = db.execute("SELECT * FROM artifacts WHERE path LIKE '%release%'").fetchall()
+ assert rows
+ with service.memory.connect() as db:
+ evidence = db.execute("SELECT * FROM evidence").fetchall()
+ assert all(report["report_id"] not in str(r["id"]) for r in evidence)
+
+
+def test_unified_only_displays() -> None: # 34
+ from paperforge.run_status import build_unified_status
+
+ unified = build_unified_status({"id": "w", "status": "RUNNING"})
+ assert unified.workflow_state == "RUNNING"
+
+
+def test_no_pcb_hardcoding_and_regression_anchor() -> None: # core vocabulary
+ source = Path("paperforge/release_eligibility.py").read_text(encoding="utf-8").lower()
+ for token in ("deeppcb", "yolo11", "sim_rpi5"):
+ assert token not in source
From b72fa9f368abc92617027734637d80c919fde505 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Sun, 27 Sep 2026 23:15:38 +0800
Subject: [PATCH 14/30] feat: harden crash recovery and reconciliation
---
docs/u4c-reliability.md | 261 +++++++++++++++++++
paperforge/external_import.py | 76 ++++--
paperforge/immutable_artifacts.py | 81 ++++++
paperforge/pdf_qa.py | 31 ++-
paperforge/release_eligibility.py | 31 ++-
paperforge/result_ledger.py | 83 +++---
paperforge/result_update.py | 374 ++++++++++++++++------------
paperforge/reviewer_matrix.py | 25 +-
paperforge/scientific_review.py | 24 +-
tests/test_u22_finalization.py | 7 +-
tests/test_u4b_finalization.py | 7 +
tests/test_u4c_artifact_recovery.py | 121 +++++++++
tests/test_u4c_reopen_and_stress.py | 149 +++++++++++
tests/test_u4c_result_recovery.py | 172 +++++++++++++
tests/test_u4c_subprocess.py | 113 +++++++++
tests/u4c_crash_child.py | 72 ++++++
16 files changed, 1345 insertions(+), 282 deletions(-)
create mode 100644 docs/u4c-reliability.md
create mode 100644 paperforge/immutable_artifacts.py
create mode 100644 tests/test_u4c_artifact_recovery.py
create mode 100644 tests/test_u4c_reopen_and_stress.py
create mode 100644 tests/test_u4c_result_recovery.py
create mode 100644 tests/test_u4c_subprocess.py
create mode 100644 tests/u4c_crash_child.py
diff --git a/docs/u4c-reliability.md b/docs/u4c-reliability.md
new file mode 100644
index 0000000..e6d468e
--- /dev/null
+++ b/docs/u4c-reliability.md
@@ -0,0 +1,261 @@
+# U4C reliability maintenance
+
+Source baseline: `7bc397ba3ed8a76383c7834a4bfd2b20856f0b80`.
+Scope: crash/reopen/retry/reconcile only; no new scientific or release semantics.
+No dependency installation, real manuscript changes, or push.
+
+## ReliabilityOperationInventory (pre-change inspection)
+
+| operation_id / subsystem | mutation type / DB writes | filesystem writes | atomic boundary | journal/state machine | idempotency strategy | reconcile function | known crash windows | existing tests | uncovered risk | planned U4C coverage |
+|---|---|---|---|---|---|---|---|---|---|---|
+| EI-stage / import | create imports row | copies sources, manifest | file and DB separate | staged | import identity | reconcile_imports | copied source without row | U21/U22 staging tests | incomplete staging must not materialize | inventory; incomplete approval remains blocked |
+| EI-validate / import | validation/import state | validation.json | file and DB separate | validated/needs_human | canonical digest | reconcile_imports | report/state mismatch | U22 digest tests | unknown mismatch needs manual handling | retain fail-closed; no approval creation |
+| EI-approve / import | approval + import state | reads validation/sources | SQLite commit | approved | bound hashes | approval_valid | before/after commit | U22 approval tests | currentness on recovery | revoked/stale binding tests |
+| EI-materialize / import | Evidence + materialization + import | none | one SQLite transaction | materialized | materialization key | reconcile_imports | before/after COMMIT | exception rollback, ordinary subprocess reopen | no actual killed writer test; repair deletes orphan Evidence | SIGKILL before/after commit; orphan/missing Evidence; repeat |
+| AF-ledger / bundle | ArtifactStore rows | query/ledger/manifest | per-file rename, then individual registry writes | implicit completion by artifacts | digest-derived ID | retry freeze_ledger | missing registry/sidecar | U23 ledger tests | retry trusts embedded digest; verifier ignores registry | common immutable fixture, registry failure/tamper/retry |
+| AF-review / bundle | ArtifactStore rows | review/manifest | per-file rename then registration | none | digest-derived ID | retry freeze_review | files/registry split | U3A tests | retries rewrite audit time | immutable retry audit |
+| AF-matrix / bundle | ArtifactStore rows | matrix/manifest | per-file rename then registration | none | digest-derived ID | retry freeze_review_matrix | files/registry split | U3B1 tests | retries rewrite history | common integrity audit |
+| AF-PDFQA / bundle | ArtifactStore rows | spec/QA/manifest | per-file rename then registration | none | digest-derived ID | retry run_pdf_qa | partial file set | U3B2 tests | digest verifier/registry gap | common integrity audit; no new PDF rules |
+| AF-release / bundle | ArtifactStore rows | target/report/manifest | fsynced temp + rename, then registration | none | assessment digest | retry freeze_assessment | report exists but registration absent | U4B tests | retry returns before restoring registry | real kill, incomplete freeze, retry |
+| RU-proposal / result update | result_updates row | spec/proposal/validation | files then DB | VALIDATED/NEEDS_HUMAN | proposal digest | reconcile_result_updates | files without row | U24A tests | old proposal lacks expected whole-file result | freeze expected source hash in approved proposal |
+| RU-approve / result update | approval + APPROVED | approval.json | DB and file separate | APPROVED | explicit approval | reconcile_result_updates | approval row/file gap | U24A tests | approval_id absent from file | validate DB/file approval before recovery |
+| RU-apply / result update | APPLYING, baseline, APPLIED | target replace, applied.json | target rename separate from DB | APPLYING/APPLIED | source/block identity | reconcile_result_updates | RU-1..RU-8 | limited matrix/exception tests | new block presence mistaken for whole-file provenance; stale approval bypass | exact whole-file binding; full matrix and real SIGKILL |
+| WF-status / workflow-process | workflow DB transitions | process memory only | SQLite commit | WorkflowStatus, independent process state | DB workflow identity | reopen + UnifiedRunStatus | process memory loss | U4A status tests | exact aliases vs persisted enums | four real DB reopen cases; status read zero writes |
+| RE-evaluate / release | none | none | no recovery transaction | none | deterministic assessment | recompute currentness | evaluator termination | U4B readonly tests | killed evaluator not tested | SIGKILL + unchanged domain/history |
+
+## Pre-change ReliabilityDefects
+
+- RU expected-new hash is derived from the current file if it contains the new block: unknown outside-block edits can be misclassified CLEAN/FORWARD.
+- RU forward recovery does not validate the approval; APPLIED with missing baseline only rewrites applied.json and never rebuilds baseline.
+- EI repair deletes orphan Evidence and claim links without proof that removal is safe; missing Evidence can be deleted from the materialization index rather than retained for investigation.
+- Release freeze retry returns an existing report before registry repair; ledger retry trusts its embedded digest and cannot complete a missing manifest.
+
+These defects are addressed before widening stress coverage. Physical power-loss
+durability is not claimed. Final executed coverage and limitations are recorded
+below after verification.
+
+## ReliabilityReport
+
+Schema: `paperforge.reliability-report/v1` (Markdown representation).
+
+Overall result: **PASSED_WITH_LIMITATIONS** under a single-writer, quiesced-repair
+crash model. Controlled process death is tested; sudden physical power loss and
+concurrent writers are not proven. No SQLite durability PRAGMA was changed.
+
+### RecoveryOutcome
+
+The test/report vocabulary is `CLEAN`, `RECOVERABLE_FORWARD`,
+`RECOVERABLE_ROLLBACK`, `MANUAL_INTERVENTION_REQUIRED`, `UNRECOVERABLE`.
+Existing subsystem APIs are retained. Result Update findings map directly;
+Import reports add `recovery_outcome` without creating a new domain state machine.
+Unreadable/corrupt database recovery is not attempted; retain the database and
+escalate rather than declaring it clean or recreating scientific content.
+
+### Executed crash matrix
+
+| Case | Observed result and invariant | Evidence |
+|---|---|---|
+| RU-1 APPROVED + old | CLEAN; ordinary apply succeeds | `test_ru_crash_matrix[1]` |
+| RU-2 APPLYING + old | RECOVERABLE_ROLLBACK; restores APPROVED only with existing valid approval, no target write | matrix case 2 + real pre-replace SIGKILL |
+| RU-3 APPLYING + expected new | RECOVERABLE_FORWARD; restores full audit and baseline with approval ID | matrix case 3 + real post-replace SIGKILL |
+| RU-4 APPLIED + new, applied.json missing | RECOVERABLE_FORWARD; fills audit without replacing manuscript | matrix case 4 |
+| RU-5 APPLIED + new, baseline missing | RECOVERABLE_FORWARD; actually restores baseline | matrix case 5 |
+| RU-6 APPLIED + unknown whole-file bytes | MANUAL_INTERVENTION_REQUIRED, even if expected new block is present | matrix case 6; outside-block/suffix edits |
+| RU-7 new bytes but stale approval/artifact/ledger | MANUAL_INTERVENTION_REQUIRED, no forward repair | matrix case 7; binding and stale-ledger tests |
+| RU-8 repeated reconcile | CLEAN after repair; byte/DB-stable subsequent calls | matrix case 8 and 20 fresh-workspace stress iterations |
+| EI-1 killed before materialization COMMIT | zero partial Evidence/materialization rows; import not materialized | real precommit SIGKILL after an INSERT |
+| EI-2 killed just after COMMIT | Evidence, materialization and import state agree after reopen | real postcommit SIGKILL |
+| EI-3 orphan Evidence | detected and retained; repair refuses deletion | orphan tests and updated U22 regression |
+| EI-4 materialization without Evidence | structured manual finding; retry refuses fabrication | missing Evidence / malformed IDs / wrong key tests |
+| EI-5 repeated materialize/reconcile | same IDs, no new rows, logical DB dump unchanged | 20 reopens |
+| AF-1 partial registration | not current until explicit same-content retry completes registry | all five bundle types; real release-freeze SIGKILL |
+| AF-2 registry with missing member | integrity failure; only reconstructible identical member can be restored | missing manifest tests for all five types |
+| AF-3 bytes/hash/status/kind disagreement | not current; retry does not overwrite conflicting registry/files | split-brain and tamper tests |
+| AF-4 repeated same digest | same authoritative IDs, unchanged files and DB rows | 20 retries per bundle type |
+| WF-1 waiting for human after restart | AWAITING_APPROVAL preserved, never COMPLETED | DB reopen tests + existing U4A exited-process relation tests |
+| WF-2 approval survives lost process memory | actual APPROVED approval record unchanged; process UNKNOWN_NOT_ATTACHED | approved fixture + new ProcessManager instance |
+| WF-3 RUNNING process disappears | RUNNING preserved, process_unknown relation | DB reopen test |
+| WF-4 repeated status reads | full logical DB dump unchanged | 20 reads per workflow scenario |
+| RE-evaluator killed | no domain mutation, prior complete report unchanged/current | real evaluator SIGKILL |
+| RE-partial freeze/retry | no partial authority, complete history preserved, deterministic retry | real registry-point kill + partial JSON tests |
+
+`NEEDS_HUMAN` is the task's conceptual label: this repository persists
+`WorkflowStatus.AWAITING_APPROVAL`. `APPROVED` belongs to domain approval/experiment
+records, not WorkflowStatus. Tests use the actual model and preserve both records;
+no new workflow status or automatic resume was introduced.
+
+### Real process termination
+
+`tests/u4c_crash_child.py` is test-only instrumentation. The child performs the
+real mutation, announces a controlled checkpoint over stdout, and waits. The
+parent kills the child, waits for termination, asserts return code `-SIGKILL`,
+opens a fresh service/DB handle and checks invariants. Six paths are covered:
+
+1. Import after first Evidence INSERT, before COMMIT.
+2. Import after COMMIT.
+3. Result Update after APPLYING, before target replace.
+4. Result Update immediately after target replace.
+5. Read-only release evaluator during snapshot computation.
+6. Release freeze after file writes, before registry registration.
+
+Every child is reaped, including timeout/failure cleanup. Tests explicitly skip
+when SIGKILL is unavailable; the recorded local run had no such skips. This is
+not instruction-level timing enumeration or hardware power-loss simulation.
+
+### Recovery safety
+
+- Proposal/spec/approval files must match their DB bindings and canonical hashes.
+- New proposals bind `expected_new_source_sha256` before approval. Legacy proposals
+ are accepted only if reversing the proposed block reconstructs the exact old
+ whole-file hash. Presence of a new block is never sufficient.
+- Forward recovery verifies current ledger/artifact bindings and approval. It only
+ writes technical audit/baseline/state records and never target manuscript bytes.
+- Failure after target replacement leaves an incomplete operation, not a false
+ ROLLED_BACK state. Existing conflicting baselines or audit records require manual
+ intervention, including apparently plausible but mismatched approval IDs/times.
+- Import reconciliation validates content/provenance and bidirectional references.
+ It does not delete Evidence/claim links or materialization rows, fabricate missing
+ Evidence, or set an import back to an apparently approved state. Unknown mismatch
+ conservatively blocks materialization retry, including unrelated imported corruption.
+- No reconcile operation creates approval, changes reviewer/claim status, completes
+ human review or publishes anything. Tests compare the complete logical DB dump on
+ manual cases and preserve the unknown target/audit bytes.
+
+### Immutable file/registry boundary
+
+`paperforge/immutable_artifacts.py` prechecks existing content before filling
+absent members, never rewrites a complete matching file, and refuses registry
+hash/status/kind conflicts. Registry-only retry does not refresh timestamps or IDs.
+Ledger, ScientificReview, ReviewerMatrix, PDFQA and Release reports all use it.
+Their verifiers now require the corresponding complete registry records.
+
+PDFQA's verifier now excludes the bundle ID from the semantic digest exactly as
+its producer does; this is an integrity-contract correction, not a new PDF rule.
+U4B's release adapter additionally checks bundle registration. No checker or
+release policy semantics were added.
+
+Missing deterministic sidecars can be reconstructed by re-running the original
+freeze inputs. A corrupt/truncated existing file is retained and rejected, not
+overwritten. If exact registered bytes cannot be recovered, stop for manual
+investigation. This is not a general concurrent publication protocol.
+
+### SQLite and filesystem audit
+
+Observed on the actual fixture connections: `journal_mode=wal`, `synchronous=2`
+(FULL), `foreign_keys=1`, `integrity_check=ok`. Ordinary exception rollback and
+actual killed-writer rollback/reopen pass. External materialization still inserts
+Evidence, the materialization row and import state in one transaction. Result
+Update intentionally has separate file and DB commit boundaries covered above.
+
+| Write path | Durability level after this change |
+|---|---|
+| Ledger / Review / Matrix / PDFQA / Release immutable JSON | atomic_rename_plus_fsync via shared helper |
+| Result Update target, approval.json, applied.json | atomic_rename_plus_fsync |
+| ArtifactStore write_bytes | existing atomic_rename_plus_fsync |
+| Result Update proposal/spec/validation | existing atomic_rename (no explicit file fsync) |
+| External stage/validation artifacts | existing per-operation writes; no global multi-file transaction |
+
+Fsync is on the temporary file before rename; there is no new parent-directory
+fsync guarantee. Atomic rename is not proof of physical power-loss durability.
+
+### Stress and orphan inventory
+
+- Five immutable bundle types: one interrupted registration followed by 20
+ idempotent retries each.
+- External Import: 20 materialize/reconcile/reopen iterations.
+- Result Update: 20 independent create/interrupt-state/reopen/reconcile workspaces.
+- No unexplained duplicate IDs/rows, non-deterministic IDs, corruption or leaked
+ helper temp files in those runs. Deliberately injected orphans were detected and
+ either exactly repaired or retained with a manual outcome as specified.
+- Filename-only scan of the existing repository `.paperforge` tree found no
+ `*.tmp`, `*.partial`, `.*.json.*`, `*-journal`, `*-wal` or `*-shm` files. Existing
+ `shadow/v0-shadow-001` and `shadow/v0-shadow-002` were not recovered, changed or
+ submitted. This scan is not a claim that private shadow domain artifacts passed
+ scientific or release validation.
+
+Cleanup policy: never automatically delete unknown orphans, database WAL/SHM/journal
+files, partial scientific artifacts or shadow data. Only a positively identified
+abandoned temporary file, with its writer stopped and completed authoritative
+artifact verified, may be considered for explicit operator cleanup. No cleanup
+job or broad `.paperforge/` ignore rule was added.
+
+### Operator APIs and manual intervention
+
+With all writers stopped and a backup retained:
+
+```python
+from paperforge.api import PaperForgeService
+from paperforge.external_import import reconcile_imports
+from paperforge.result_update import reconcile_result_updates
+
+service = PaperForgeService(workspace)
+report = reconcile_result_updates(workspace, service.memory) # inspect first
+# Only known old/new states with valid provenance are repaired:
+reconcile_result_updates(workspace, service.memory, repair=True)
+# Import inconsistencies are retained for manual inspection, not auto-deleted:
+reconcile_imports(workspace, service.memory, repair=True)
+```
+
+Before repair, preserve the DB and all operation/approval/source files. Unknown
+third states, stale approvals/ledgers, conflicting baselines, corrupted JSON and
+unreadable DBs require investigation, not a blind overwrite or forged approval.
+The operator may restore known original artifacts from an independently verified
+backup, then rerun inspection. No automatic rollback of manuscript bytes exists.
+
+### Remaining limitations and U4D boundary
+
+- Concurrent writers/freeze calls and concurrent manual file edits are outside the
+ tested single-writer contract; quiesce writers before repair/retry.
+- Physical power-loss, network filesystems, filesystem-specific directory durability,
+ disk corruption recovery and exhaustive kill timing are not proven.
+- Conflicting historical baselines and unreconstructible legacy partial audit files
+ intentionally require manual intervention.
+- Existing stage/validate/proposal file-to-DB gaps remain fail-closed/manual; U4C
+ does not invent approvals to complete them.
+- Static tools and missing optional writing dependencies remain U4D environment
+ gates. Local review does not replace future push-triggered platform reviews.
+
+## Final verification (2026-09-27)
+
+Runtime: Python 3.11.15, pytest 9.1.1, macOS. No dependencies were installed.
+
+| Run / gate | Result |
+|---|---|
+| Four new U4C test modules | 69 passed, no skips/failures/errors |
+| All currently executable regression tests | 628 passed, 6 skipped, 10 deselected; two known blocked collection modules explicitly ignored |
+| Full repository, `pytest tests --continue-on-collection-errors --tb=short` | 644 collected, 628 passed, 6 skipped, 10 failed, 2 collection errors |
+| Environment-blocked tests | All 10 failures and both collection errors fail importing `pymupdf`; unchanged from baseline |
+| Skips | Five opt-in live compute backend cases; one visualization case missing `fitz` |
+| ruff / mypy | Both unavailable in this interpreter; NOT_RUN_TOOL_UNAVAILABLE |
+| Local Python and security-focused review | Blocking findings repaired; final review found no HIGH/CRITICAL findings |
+| Remote automatic code/security review | NOT_RUN_NO_PUSH; not replaced by local review |
+
+The two collection errors are `tests/test_agent_bridges.py` and
+`tests/test_legacy_security.py`. The ten failures are in
+`tests/test_research_partner_pipeline.py`; every traceback ends in the existing
+`engine/perform_review.py` import of `pymupdf`. The baseline was 559 passed with
+the same 6 skips, 10 failures and 2 errors. The additional 69 passing tests are
+the U4C suite. This is **not** a full-green repository result.
+
+Reproduce targeted coverage:
+
+```sh
+python3.11 -m pytest tests/test_u4c_result_recovery.py tests/test_u4c_subprocess.py tests/test_u4c_artifact_recovery.py tests/test_u4c_reopen_and_stress.py -q --tb=short
+python3.11 -m pytest tests --continue-on-collection-errors --tb=short
+```
+
+### Changed-file inventory
+
+- `paperforge/immutable_artifacts.py`: shared immutable write/registration integrity.
+- `paperforge/result_update.py`: exact recovery binding, approval/audit/baseline repair.
+- `paperforge/external_import.py`: non-destructive consistency inspection and retry guard.
+- `paperforge/result_ledger.py`, `scientific_review.py`, `reviewer_matrix.py`,
+ `pdf_qa.py`, `release_eligibility.py`: immutable retry and registry verification.
+- Four `tests/test_u4c_*.py` modules and `tests/u4c_crash_child.py`: matrices,
+ actual process death, reopen, integrity and stress coverage.
+- `tests/test_u22_finalization.py`, `tests/test_u4b_finalization.py`: align fixtures
+ with retained-orphan safety and complete artifact registration.
+- This report; merge-readiness inventory is a separate U4D-Prep document.
+
+No real manuscript, shadow artifact, provider configuration, dependency declaration,
+scientific checker, reviewer rule or publication authorization was changed.
diff --git a/paperforge/external_import.py b/paperforge/external_import.py
index bf39d04..5a15a86 100644
--- a/paperforge/external_import.py
+++ b/paperforge/external_import.py
@@ -927,11 +927,22 @@ def materialize_import(
)
_validate_metric_provenance(semantics, metric, metric_provenance)
key = _materialization_key(manifest_sha, report_sha, scope)
+ consistency = reconcile_imports(root, memory)
+ if not consistency["consistent"]:
+ # Do not recreate orphan Evidence or overwrite a damaged historical
+ # row while retrying an otherwise valid import.
+ raise ApprovalError("materialization integrity mismatch; manual reconciliation required")
with memory.connect() as db:
existing = db.execute(
"SELECT * FROM import_materializations WHERE key=?", (key,)
).fetchone()
if existing is not None:
+ consistency = reconcile_imports(root, memory)
+ if (key in consistency["orphan_materializations"]
+ or import_id in consistency["state_mismatches"]
+ or any(eid in consistency["orphan_evidence"]
+ for eid in json.loads(existing["evidence_ids_json"]))):
+ raise ApprovalError("materialization integrity mismatch; manual reconciliation required")
return {
"import_id": import_id,
"materialization_key": key,
@@ -1017,16 +1028,15 @@ def materialize_import(
def reconcile_imports(workspace: str | Path, memory: Any, *, repair: bool = False) -> dict[str, Any]:
"""Detect orphan evidence/materializations and state mismatches.
- Exception-injection rollback is tested in pytest; true SIGKILL/power-loss
- safety comes from the single SQLite transaction above (WAL atomic commit).
- This reconciler handles leftovers from older versions or manual file edits.
+ Unknown orphans are retained, not deleted or recreated. Reconciliation
+ never creates Evidence, changes claims, or issues an approval.
"""
root = Path(workspace).expanduser().resolve(strict=True)
- _ensure_u22_tables(memory)
with memory.connect() as db:
- materials = db.execute("SELECT * FROM import_materializations").fetchall()
- evidence_rows = db.execute("SELECT id, metadata_json FROM evidence").fetchall()
- imports = db.execute("SELECT * FROM imports").fetchall()
+ tables = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
+ materials = db.execute("SELECT * FROM import_materializations").fetchall() if "import_materializations" in tables else []
+ evidence_rows = db.execute("SELECT * FROM evidence").fetchall()
+ imports = db.execute("SELECT * FROM imports").fetchall() if "imports" in tables else []
materialized_keys = {str(r["key"]): r for r in materials}
evidence_by_id = {str(r["id"]): r for r in evidence_rows}
orphan_evidence: list[str] = []
@@ -1037,7 +1047,12 @@ def reconcile_imports(workspace: str | Path, memory: Any, *, repair: bool = Fals
continue
if not isinstance(meta, dict) or "materialization_key" not in meta:
continue
- if str(meta["materialization_key"]) not in materialized_keys:
+ material = materialized_keys.get(str(meta["materialization_key"]))
+ try:
+ referenced = json.loads(material["evidence_ids_json"]) if material else []
+ except (TypeError, ValueError):
+ referenced = []
+ if material is None or evidence_id not in referenced:
orphan_evidence.append(evidence_id)
orphan_materializations: list[str] = []
for key, row in materialized_keys.items():
@@ -1045,8 +1060,33 @@ def reconcile_imports(workspace: str | Path, memory: Any, *, repair: bool = Fals
evidence_ids = json.loads(str(row["evidence_ids_json"]))
except (TypeError, ValueError):
evidence_ids = []
- if any(str(eid) not in evidence_by_id for eid in (evidence_ids or [])):
+ if (not isinstance(evidence_ids, list) or not evidence_ids
+ or any(not isinstance(eid, str) or not eid for eid in evidence_ids)
+ or len(evidence_ids) != len(set(evidence_ids))
+ or any(str(eid) not in evidence_by_id for eid in evidence_ids)
+ or not any(r["id"] == row["import_id"] for r in imports)):
orphan_materializations.append(key)
+ continue
+ for eid in evidence_ids:
+ try:
+ evidence = evidence_by_id[eid]
+ meta = json.loads(evidence["metadata_json"])
+ manifest_path = root / ".paperforge/imports" / row["import_id"] / "manifest.json"
+ manifest, manifest_sha = _read_canonical_manifest(manifest_path)
+ source = next((s for s in manifest.get("sources", [])
+ if s.get("path") == meta.get("source_relpath")), None)
+ if (meta.get("materialization_key") != key or meta.get("import_id") != row["import_id"]
+ or evidence["content_sha256"] != hashlib.sha256(evidence["excerpt"].encode()).hexdigest()
+ or meta.get("manifest_sha256") != row["manifest_sha256"] or manifest_sha != row["manifest_sha256"]
+ or meta.get("validation_digest") != row["validation_report_sha256"]
+ or meta.get("approval_scope") != row["approval_scope"]
+ or _materialization_key(row["manifest_sha256"], row["validation_report_sha256"], row["approval_scope"]) != key
+ or not source or meta.get("source_sha256") != source.get("sha256")):
+ orphan_materializations.append(key)
+ break
+ except (OSError, TypeError, ValueError, KeyError, AttributeError):
+ orphan_materializations.append(key)
+ break
mismatches: list[str] = []
for row in imports:
import_id = str(row["id"])
@@ -1056,24 +1096,22 @@ def reconcile_imports(workspace: str | Path, memory: Any, *, repair: bool = Fals
evidence_ids = json.loads(str(row["evidence_ids_json"] or "[]"))
except (TypeError, ValueError):
evidence_ids = []
- if state == "materialized" and (not evidence_ids or not manifest_path.is_file()):
+ matching = [m for m in materials if m["import_id"] == import_id]
+ valid_match = (len(matching) == 1 and matching[0]["key"] not in orphan_materializations
+ and json.loads(matching[0]["evidence_ids_json"]) == evidence_ids
+ and manifest_path.is_file())
+ if (state == "materialized" and not valid_match) or (matching and state != "materialized"):
mismatches.append(import_id)
report = {
"orphan_evidence": sorted(orphan_evidence),
"orphan_materializations": sorted(orphan_materializations),
"state_mismatches": sorted(mismatches),
"consistent": not orphan_evidence and not orphan_materializations and not mismatches,
+ "recovery_outcome": "MANUAL_INTERVENTION_REQUIRED" if orphan_evidence or orphan_materializations or mismatches else "CLEAN",
+ "repaired": False,
}
if repair and not report["consistent"]:
- with memory.connect() as db:
- for evidence_id in orphan_evidence:
- db.execute("DELETE FROM claim_evidence WHERE evidence_id=?", (evidence_id,))
- db.execute("DELETE FROM evidence WHERE id=?", (evidence_id,))
- for key in orphan_materializations:
- db.execute("DELETE FROM import_materializations WHERE key=?", (key,))
- for import_id in mismatches:
- db.execute("UPDATE imports SET state='approved' WHERE id=?", (import_id,))
- report["repaired"] = True
+ report["repair_refused"] = "ambiguous historical state retained; no Evidence or approval mutations"
return report
diff --git a/paperforge/immutable_artifacts.py b/paperforge/immutable_artifacts.py
new file mode 100644
index 0000000..16c0197
--- /dev/null
+++ b/paperforge/immutable_artifacts.py
@@ -0,0 +1,81 @@
+"""Crash-safe retry and read-only integrity checks for frozen audit bundles.
+
+Files are immutable; registration may be completed after a crash. Existing
+registry/file disagreements are never healed by blindly re-registering bytes.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import Any
+
+from .artifacts import ArtifactIntegrityError, ArtifactStore
+from .path_safety import atomic_write_text, reject_symlink_components
+
+
+def _file(root: Path, relative: str) -> Path:
+ rel = Path(relative)
+ if rel.is_absolute() or ".." in rel.parts or not rel.parts:
+ raise ArtifactIntegrityError("invalid immutable artifact path")
+ return reject_symlink_components(root / rel, anchor=root)
+
+
+def write_immutable_bundle(root: Path, files: Mapping[str, Mapping[str, Any]]) -> None:
+ """Validate all existing members before filling absent ones; never rewrite."""
+ missing = []
+ for relative, expected in files.items():
+ path = _file(root, relative)
+ if path.exists():
+ try:
+ actual = json.loads(path.read_bytes())
+ actual_stable = {k: v for k, v in actual.items() if k != "created_at"}
+ expected_stable = {k: v for k, v in expected.items() if k != "created_at"}
+ except (OSError, ValueError, AttributeError) as exc:
+ raise ArtifactIntegrityError(f"incomplete/corrupt frozen file: {relative}") from exc
+ if actual_stable != expected_stable:
+ raise ArtifactIntegrityError(f"immutable content collision: {relative}")
+ else:
+ missing.append((relative, expected))
+ for relative, content in missing:
+ atomic_write_text(root, relative, json.dumps(content, ensure_ascii=False,
+ indent=2, sort_keys=True) + "\n")
+
+
+def register_immutable(store: ArtifactStore, relative: str, *, kind: str, **kwargs: Any) -> Any:
+ path = store.resolve(relative, kind=kind)
+ actual = hashlib.sha256(path.read_bytes()).hexdigest()
+ if store.memory is not None:
+ with store.memory.connect() as db:
+ rows = db.execute("SELECT * FROM artifacts WHERE path=?", (relative,)).fetchall()
+ if rows:
+ if len(rows) != 1 or rows[0]["sha256"] != actual or rows[0]["kind"] != kind or rows[0]["status"] != "VERIFIED":
+ raise ArtifactIntegrityError(f"registry disagrees with frozen file: {relative}")
+ return dict(rows[0])
+ return store.register(relative, kind=kind, **kwargs)
+
+
+def verify_registered_bundle(root: Path, memory: Any,
+ paths: Sequence[str] | Mapping[str, str]) -> dict[str, Any]:
+ findings = []
+ with memory.connect() as db:
+ for relative in paths:
+ try:
+ path = _file(root, relative)
+ rows = db.execute("SELECT * FROM artifacts WHERE path=?", (relative,)).fetchall()
+ if not path.is_file():
+ reason = "missing_file"
+ elif not rows:
+ reason = "orphan_file"
+ elif (len(rows) != 1 or rows[0]["status"] != "VERIFIED"
+ or (isinstance(paths, Mapping) and rows[0]["kind"] != paths[relative])
+ or rows[0]["sha256"] != hashlib.sha256(path.read_bytes()).hexdigest()):
+ reason = "registry_hash_or_status_mismatch"
+ else:
+ continue
+ except (OSError, ValueError, ArtifactIntegrityError):
+ reason = "unsafe_or_unreadable_file"
+ findings.append({"path": relative, "reason": reason})
+ return {"registry_integrity": "valid" if not findings else "invalid",
+ "registry_findings": findings, "registered_complete": not findings}
diff --git a/paperforge/pdf_qa.py b/paperforge/pdf_qa.py
index 55a7d77..7ea48f4 100644
--- a/paperforge/pdf_qa.py
+++ b/paperforge/pdf_qa.py
@@ -521,24 +521,16 @@ def run_pdf_qa(
digest = hashlib.sha256(_canonical(stable)).hexdigest()
bundle_id = f"qa-{digest[:16]}"
bundle_dir = safe_mkdir(root / ".paperforge" / "pdf_qa" / bundle_id, anchor=root)
- existing = bundle_dir / "qa.json"
- if existing.is_file():
- previous = json.loads(existing.read_bytes().decode("utf-8"))
- if previous.get("qa_digest") == digest:
- _register_qa_artifacts(root, memory, bundle_id, digest, actual_sha, policy.digest(), run_id=run_id)
- return previous
- raise PdfQaError(f"QA bundle collision: {bundle_id}")
+ from .immutable_artifacts import write_immutable_bundle
+
payload = {**stable, "bundle_id": bundle_id, "qa_digest": digest, "created_at": utc_now()}
- for name, content in (
+ write_immutable_bundle(root, {f".paperforge/pdf_qa/{bundle_id}/{name}": content for name, content in (
("spec.json", spec.to_canonical()),
("qa.json", payload),
("manifest.json", {"bundle_id": bundle_id, "qa_digest": digest,
"target_pdf_sha256": actual_sha, "policy_digest": policy.digest()}),
- ):
- target_path = bundle_dir / name
- tmp = target_path.with_name(f".{name}.tmp")
- tmp.write_text(json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp.replace(target_path)
+ )})
+ payload = json.loads((bundle_dir / "qa.json").read_bytes())
_register_qa_artifacts(root, memory, bundle_id, digest, actual_sha, policy.digest(), run_id=run_id)
return payload
@@ -546,6 +538,7 @@ def run_pdf_qa(
def _register_qa_artifacts(root: Path, memory: Any, bundle_id: str, digest: str,
pdf_sha: str, policy_digest: str, run_id: str | None = None) -> None:
from .artifacts import ArtifactStore
+ from .immutable_artifacts import register_immutable
store = ArtifactStore(root, allowed_roots=(".paperforge/pdf_qa",),
allowed_suffixes=(".json",), allowed_kinds=("review", "manifest", "report"),
@@ -554,7 +547,7 @@ def _register_qa_artifacts(root: Path, memory: Any, bundle_id: str, digest: str,
"policy_digest": policy_digest, "workflow_id": run_id,
"note": "layout QA artifact, not scientific evidence"}
for name, kind in (("qa.json", "review"), ("manifest.json", "manifest")):
- store.register(f".paperforge/pdf_qa/{bundle_id}/{name}", kind=kind,
+ register_immutable(store, f".paperforge/pdf_qa/{bundle_id}/{name}", kind=kind,
run_id=run_id, status="VERIFIED", media_type="application/json", metadata=metadata)
@@ -572,7 +565,7 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
except ValueError as exc:
return {"bundle_id": bundle_id, "bundle_file_integrity": "failed", "detail": str(exc)}
stored = str(payload.get("qa_digest") or "")
- stable = {k: payload[k] for k in payload if k not in {"qa_digest", "created_at", "qa_file_sha256"}}
+ stable = {k: payload[k] for k in payload if k not in {"bundle_id", "qa_digest", "created_at", "qa_file_sha256"}}
digest_valid = stored == hashlib.sha256(_canonical(stable)).hexdigest()
# Target PDF still matches?
target_match = True
@@ -584,8 +577,14 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
# Human/render currentness sampled from stored hashes (no recomputation of renders here).
unresolved_critical = list(payload.get("unresolved_critical") or [])
state = str(payload.get("layout_qa_state") or "")
- currently_valid = bool(historical == "valid")
+ from .immutable_artifacts import verify_registered_bundle
+
+ registry = verify_registered_bundle(root, memory, {
+ f".paperforge/pdf_qa/{bundle_id}/qa.json": "review",
+ f".paperforge/pdf_qa/{bundle_id}/manifest.json": "manifest"})
+ currently_valid = bool(historical == "valid" and registry["registered_complete"])
return {
+ **registry,
"bundle_id": bundle_id,
"bundle_file_sha256": file_sha,
"bundle_file_integrity": "valid",
diff --git a/paperforge/release_eligibility.py b/paperforge/release_eligibility.py
index a651da1..156c41f 100644
--- a/paperforge/release_eligibility.py
+++ b/paperforge/release_eligibility.py
@@ -9,6 +9,7 @@
from typing import Any, Mapping, Sequence
from .models import utc_now
+from .immutable_artifacts import register_immutable, verify_registered_bundle, write_immutable_bundle
from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
REPORT_SCHEMA = "paperforge.release-eligibility-report/v1"
@@ -515,9 +516,13 @@ def evaluate_release(
if k not in {"matrix_id", "matrix_digest", "created_at", "matrix_file_sha256"}}
comments_valid = all(c.get("comment_digest") == hashlib.sha256(c.get("exact_text", "").encode()).hexdigest()
for c in matrix.get("comments") or [])
+ matrix_registry = verify_registered_bundle(root, memory, {
+ f".paperforge/review_matrix/{matrix_id}/matrix.json": "review",
+ f".paperforge/review_matrix/{matrix_id}/manifest.json": "manifest"})
# The legacy matrix verifier visits optional bindings and may reconcile.
# Verify history here, then inspect only required bindings without repair.
- if _digest(stable_matrix) != matrix.get("matrix_digest") or not comments_valid:
+ if (_digest(stable_matrix) != matrix.get("matrix_digest") or not comments_valid
+ or not matrix_registry["registered_complete"]):
required_states = ["blocked"]
else:
required_ids = {c["criterion_id"] for c in matrix.get("criteria", []) if c.get("required")}
@@ -609,11 +614,11 @@ def evaluate_release(
for bundle_id in pdf_bundle_ids:
bundle = _json_file(root, f".paperforge/pdf_qa/{_identifier(bundle_id)}/qa.json")
report = verify_pdf_qa(root, memory, str(bundle_id))
- # U3B's verifier includes bundle_id in its digest recomputation,
- # although the producer excludes it. Validate the producer contract here.
+ # Keep the producer's canonical contract and registry integrity
+ # separate: a complete file without registration is not current.
stable_qa = {k: v for k, v in bundle.items()
if k not in {"bundle_id", "qa_digest", "created_at", "qa_file_sha256"}}
- if _digest(stable_qa) != bundle.get("qa_digest"):
+ if _digest(stable_qa) != bundle.get("qa_digest") or not report.get("registered_complete"):
problems.append(f"{bundle_id}: bundle invalid")
continue
if (bundle.get("target_pdf_sha256") != target.final_pdf_sha256
@@ -767,15 +772,15 @@ def freeze_assessment(workspace: str | Path, memory: Any, payload: Mapping[str,
if {k: v for k, v in previous.items() if k != "created_at"} != {
k: v for k, v in payload.items() if k != "created_at"}:
raise ReleaseEligibilityError("frozen assessment collision")
- return previous
- for name, content in (
+ payload = previous
+ files = {
+ f".paperforge/release/{report_id}/{name}": content for name, content in (
("target.json", {"target": target.to_dict()}),
("report.json", payload),
("manifest.json", {"report_id": report_id, "report_digest": digest,
"target_id": target.target_id, "policy_digest": policy.digest()}),
- ):
- atomic_write_text(root, f".paperforge/release/{report_id}/{name}",
- json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
+ )}
+ write_immutable_bundle(root, files)
from .artifacts import ArtifactStore
store = ArtifactStore(root, allowed_roots=(".paperforge/release",),
@@ -785,7 +790,7 @@ def freeze_assessment(workspace: str | Path, memory: Any, payload: Mapping[str,
"policy_digest": policy.digest(), "overall_eligibility": payload["overall_eligibility"],
"note": "release assessment, not scientific evidence"}
for name, kind in (("report.json", "release"), ("manifest.json", "manifest")):
- store.register(f".paperforge/release/{report_id}/{name}", kind=kind,
+ register_immutable(store, f".paperforge/release/{report_id}/{name}", kind=kind,
status="VERIFIED", media_type="application/json", metadata=metadata)
return dict(payload)
@@ -801,6 +806,9 @@ def assessment_current(workspace: str | Path, memory: Any, report_id: str, *,
valid = (stored == _digest(stable) and report_id == f"release-{stored[:16]}"
and payload.get("report_id") == report_id)
current = False
+ registry = verify_registered_bundle(root, memory, {
+ f".paperforge/release/{report_id}/report.json": "release",
+ f".paperforge/release/{report_id}/manifest.json": "manifest"})
if valid:
try:
policy = ReleasePolicy(**{k: v for k, v in payload["policy"].items() if k != "schema"})
@@ -813,7 +821,8 @@ def assessment_current(workspace: str | Path, memory: Any, report_id: str, *,
current = False
return {"report_id": report_id, "report_digest_valid": valid,
"historical_integrity": "valid" if valid else "invalid",
- "currently_valid": bool(valid and current),
+ **registry,
+ "currently_valid": bool(valid and current and registry["registered_complete"]),
"overall_eligibility": payload.get("overall_eligibility")}
diff --git a/paperforge/result_ledger.py b/paperforge/result_ledger.py
index d43904c..088ce86 100644
--- a/paperforge/result_ledger.py
+++ b/paperforge/result_ledger.py
@@ -12,7 +12,6 @@
from .evidence_semantics import EvidenceSemantics
from .external_import import RUN_IDENTITY_SCHEMA, ScientificRunIdentity
from .models import utc_now
-from .path_safety import safe_mkdir
LEDGER_SCHEMA = "paperforge.result-ledger/v1"
QUERY_SCHEMA = "paperforge.result-ledger-query/v1"
@@ -553,56 +552,25 @@ def freeze_ledger(
}
digest = hashlib.sha256(_canonical_json(stable)).hexdigest()
ledger_id = f"ledger-{digest[:16]}"
- ledger_dir = safe_mkdir(root / ".paperforge" / "ledgers" / ledger_id, anchor=root)
- # Idempotent: same digest exists and verifies → return it (no rewrite).
- ledger_path = ledger_dir / "ledger.json"
- if ledger_path.is_file():
- try:
- existing = json.loads(ledger_path.read_bytes().decode("utf-8"))
- except ValueError as exc:
- raise LedgerError(f"existing ledger is not valid JSON: {exc}") from exc
- if existing.get("ledger_digest") == digest:
- _register_ledger_artifacts(
- root, memory, ledger_id, digest, query_digest, existing, run_id=run_id
- )
- return existing
- raise LedgerError(f"ledger_id collision with different content: {ledger_id}")
+ from .immutable_artifacts import write_immutable_bundle
+
payload: dict[str, Any] = {
- **stable,
- "ledger_id": ledger_id,
- "ledger_digest": digest,
- "created_at": utc_now(),
+ **stable, "ledger_id": ledger_id, "ledger_digest": digest, "created_at": utc_now(),
"diagnostic_marking": (
- "NOT PUBLICATION EVIDENCE" if query.purpose == "diagnostic" else "scientific snapshot; not claim verified"
+ "NOT PUBLICATION EVIDENCE" if query.purpose == "diagnostic"
+ else "scientific snapshot; not claim verified"
),
}
- written: list[Path] = []
- try:
- for name, content in (
- ("query.json", {"query": query.to_canonical(), "query_digest": query_digest}),
- ("ledger.json", payload),
- ("manifest.json", {
- "ledger_id": ledger_id, "ledger_digest": digest,
- "generator_version": GENERATOR_VERSION,
- "decimal_aggregation_version": DECIMAL_AGGREGATION_VERSION,
- "query_digest": query_digest,
- }),
- ):
- target = ledger_dir / name
- tmp = target.with_name(f".{name}.{ledger_id}.tmp")
- tmp.write_text(json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp.replace(target)
- written.append(target)
- _register_ledger_artifacts(
- root, memory, ledger_id, digest, query_digest, payload, run_id=run_id
- )
- except BaseException:
- # No partial authority: files without registry (or vice versa) must not stand.
- try:
- _unregister_ledger_artifacts(root, memory, ledger_id)
- except (OSError, ValueError):
- pass
- raise
+ write_immutable_bundle(root, {
+ f".paperforge/ledgers/{ledger_id}/query.json": {"query": query.to_canonical(), "query_digest": query_digest},
+ f".paperforge/ledgers/{ledger_id}/ledger.json": payload,
+ f".paperforge/ledgers/{ledger_id}/manifest.json": {
+ "ledger_id": ledger_id, "ledger_digest": digest, "generator_version": GENERATOR_VERSION,
+ "decimal_aggregation_version": DECIMAL_AGGREGATION_VERSION, "query_digest": query_digest,
+ },
+ })
+ payload = json.loads((root / ".paperforge/ledgers" / ledger_id / "ledger.json").read_bytes())
+ _register_ledger_artifacts(root, memory, ledger_id, digest, query_digest, payload, run_id=run_id)
return payload
@@ -647,19 +615,21 @@ def _register_ledger_artifacts(
allowed_kinds=("result", "manifest", "report"),
memory=memory,
)
+ from .immutable_artifacts import register_immutable
+
records = [
- store.register(
+ register_immutable(store,
f".paperforge/ledgers/{ledger_id}/ledger.json",
kind="result", run_id=run_id, status="VERIFIED",
media_type="application/json", metadata=metadata,
- ).to_dict(),
- store.register(
+ ),
+ register_immutable(store,
f".paperforge/ledgers/{ledger_id}/manifest.json",
kind="manifest", run_id=run_id, status="VERIFIED",
media_type="application/json", metadata=metadata,
- ).to_dict(),
+ ),
]
- return records
+ return [r if isinstance(r, dict) else r.to_dict() for r in records]
def _unregister_ledger_artifacts(root: Path, memory: Any, ledger_id: str) -> None:
@@ -764,9 +734,16 @@ def verify_ledger(workspace: str | Path, memory: Any, ledger_id: str) -> dict[st
semantics_ok = False
historical = "valid" if (digest_valid and snapshot_ok) else "invalid"
currentness = "current" if not stale else "stale"
- eligible = bool(historical == "valid" and currentness == "current" and semantics_ok)
+ from .immutable_artifacts import verify_registered_bundle
+
+ registry = verify_registered_bundle(root, memory, {
+ f".paperforge/ledgers/{ledger_id}/ledger.json": "result",
+ f".paperforge/ledgers/{ledger_id}/manifest.json": "manifest"})
+ eligible = bool(historical == "valid" and currentness == "current" and semantics_ok
+ and registry["registered_complete"])
return {
"ledger_id": ledger_id,
+ **registry,
"ledger_file_sha256": file_sha,
"ledger_file_integrity": "valid" if ledger_path.is_file() else "failed",
"ledger_digest_valid": digest_valid,
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index 01e1fb7..ff98029 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -10,7 +10,7 @@
from typing import Any, Mapping, Sequence
from .models import utc_now
-from .path_safety import safe_mkdir
+from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
from .protected_blocks import (
PROTECTED_END,
PROTECTED_START,
@@ -132,6 +132,10 @@ def _sha256_str(text: str) -> str:
def _resolve_target(root: Path, rel: str) -> Path:
+ relative = Path(rel)
+ if relative.is_absolute() or ".." in relative.parts:
+ raise ResultUpdateError("target leaves workspace")
+ reject_symlink_components(root / relative, anchor=root)
candidate = (root / rel).resolve()
try:
candidate.relative_to(root)
@@ -465,6 +469,7 @@ def build_proposal(
"schema": PROPOSAL_SCHEMA,
"spec_digest": spec.digest(),
"target_source_sha256": current_sha,
+ "expected_new_source_sha256": _sha256_str(candidate),
"old_block_sha256": spec.old_block_sha256,
"old_block": old_block,
"proposed_block": proposed_block,
@@ -562,180 +567,227 @@ def approve_proposal(
approved_at, json.dumps(sorted(acknowledged or [])), str(rationale or "")),
)
db.execute("UPDATE result_updates SET state='APPROVED' WHERE id=?", (proposal_id,))
- (base / "approval.json").write_text(json.dumps({**binding, "acknowledged": sorted(acknowledged or []),
- "rationale": rationale}, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ atomic_write_text(root, f".paperforge/result_updates/{proposal_id}/approval.json",
+ json.dumps({**binding, "approval_id": approval_id,
+ "acknowledged": sorted(acknowledged or []),
+ "rationale": rationale}, indent=2, sort_keys=True) + "\n")
return {"approval_id": approval_id, "binding": binding}
+def _load_update(root: Path, memory: Any, proposal_id: str) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
+ if not re.fullmatch(r"prop-[a-f0-9]+", proposal_id):
+ raise ResultUpdateError("invalid proposal identity")
+ base = root / ".paperforge" / "result_updates" / proposal_id
+ for name in ("proposal.json", "spec.json", "validation.json"):
+ reject_symlink_components(base / name, anchor=root)
+ proposal = json.loads((base / "proposal.json").read_bytes())
+ spec = json.loads((base / "spec.json").read_bytes())
+ stable = {k: v for k, v in proposal.items()
+ if k not in {"proposal_id", "proposal_digest", "validation", "created_at"}}
+ digest = hashlib.sha256(_canonical(stable)).hexdigest()
+ with memory.connect() as db:
+ row = db.execute("SELECT * FROM result_updates WHERE id=?", (proposal_id,)).fetchone()
+ if (row is None or digest != proposal.get("proposal_digest")
+ or proposal.get("proposal_id") != proposal_id
+ or row["proposal_digest"] != digest
+ or json.loads(row["proposal_json"]) != proposal
+ or row["spec_digest"] != hashlib.sha256(_canonical(spec)).hexdigest()
+ or row["target_path"] != spec.get("target_path")):
+ raise ResultUpdateError("proposal/spec integrity mismatch")
+ return proposal, spec, dict(row)
+
+
+def _approval_for_recovery(root: Path, memory: Any, proposal: Mapping[str, Any]) -> dict[str, Any]:
+ base = root / ".paperforge" / "result_updates" / proposal["proposal_id"]
+ reject_symlink_components(base / "approval.json", anchor=root)
+ approval = json.loads((base / "approval.json").read_bytes())
+ validation = json.loads((base / "validation.json").read_bytes())
+ validation_digest = hashlib.sha256(_canonical(validation)).hexdigest()
+ with memory.connect() as db:
+ rows = db.execute(
+ "SELECT * FROM result_approvals WHERE proposal_id=? AND status='valid'",
+ (proposal["proposal_id"],),
+ ).fetchall()
+ matching = [r for r in rows if all((
+ not approval.get("approval_id") or approval["approval_id"] == r["id"],
+ approval.get("proposal_id") == proposal["proposal_id"],
+ r["proposal_digest"] == approval.get("proposal_digest") == proposal["proposal_digest"],
+ r["target_source_sha256"] == approval.get("target_source_sha256") == proposal["target_source_sha256"],
+ r["old_block_sha256"] == approval.get("old_block_sha256") == proposal["old_block_sha256"],
+ r["validation_digest"] == approval.get("validation_digest") == validation_digest,
+ r["approver"] == approval.get("approver"),
+ r["approved_at"] == approval.get("approved_at"),
+ r["scope"] == approval.get("approval_scope"),
+ r["rationale"] == approval.get("rationale", ""),
+ json.loads(r["acknowledged_json"]) == approval.get("acknowledged", []),
+ ))]
+ if len(matching) != 1 or approval.get("artifact_hashes", {}) != proposal.get("artifact_hashes", {}):
+ raise ResultUpdateApprovalError("approval absent, stale, or ambiguous")
+ _verify_ledger_bindings(root, memory, proposal.get("ledger_bindings") or [])
+ _verify_proposal_artifacts(root, memory, proposal, expected=approval.get("artifact_hashes"))
+ return {**approval, "approval_id": matching[0]["id"]}
+
+
+def _expected_new_hash(proposal: Mapping[str, Any], current_text: str) -> str:
+ expected = str(proposal.get("expected_new_source_sha256") or "")
+ if expected:
+ return expected
+ # Legacy proposals may be recovered only by reconstructing the exact
+ # approved old whole-file hash, never by recognizing the new block alone.
+ old, new = str(proposal["old_block"]), str(proposal["proposed_block"])
+ if _sha256_str(current_text) == proposal["target_source_sha256"]:
+ return _sha256_str(current_text.replace(old, new, 1))
+ if new and current_text.count(new) == 1:
+ restored = current_text.replace(new, old, 1)
+ if _sha256_str(restored) == proposal["target_source_sha256"]:
+ return _sha256_str(current_text)
+ raise ResultUpdateError("unknown whole-file state")
+
+
+def _finish_applied(root: Path, memory: Any, proposal: Mapping[str, Any],
+ spec: Mapping[str, Any], approval: Mapping[str, Any], new_sha: str) -> dict[str, Any]:
+ applied_at = utc_now()
+ result = {
+ "proposal_id": proposal["proposal_id"], "old_source_sha256": proposal["target_source_sha256"],
+ "new_source_sha256": new_sha, "old_block_sha256": proposal["old_block_sha256"],
+ "new_block_sha256": _block_hash(str(proposal["proposed_block"])),
+ "approval_id": approval["approval_id"], "applied_at": applied_at,
+ "result_update_state": "applied", "scientific_review_state": "pending",
+ "publication_ready": False,
+ }
+ # Target already equals the authorized result. Recovery never writes it.
+ atomic_write_text(root, f".paperforge/result_updates/{proposal['proposal_id']}/applied.json",
+ json.dumps(result, indent=2, sort_keys=True) + "\n")
+ with memory.connect() as db:
+ db.execute(
+ "INSERT OR REPLACE INTO result_baselines "
+ "(target_path, source_sha256, block_sha256, proposal_id, approval_id, applied_at) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (spec["target_path"], new_sha, result["new_block_sha256"],
+ proposal["proposal_id"], approval["approval_id"], applied_at),
+ )
+ db.execute("UPDATE result_updates SET state='APPLIED' WHERE id=?", (proposal["proposal_id"],))
+ return result
+
+
def apply_proposal(workspace: str | Path, memory: Any, proposal_id: str) -> dict[str, Any]:
root = Path(workspace).expanduser().resolve(strict=True)
- base = root / ".paperforge" / "result_updates" / proposal_id
- proposal = json.loads((base / "proposal.json").read_text(encoding="utf-8"))
- approval_path = base / "approval.json"
- if not approval_path.is_file():
- raise ResultUpdateApprovalError("no approval for proposal")
- approval = json.loads(approval_path.read_text(encoding="utf-8"))
- _ensure_update_tables(memory)
+ proposal, spec, row = _load_update(root, memory, proposal_id)
+ approval = _approval_for_recovery(root, memory, proposal)
+ target = _resolve_target(root, spec["target_path"])
+ current_text = target.read_bytes().decode("utf-8")
+ current_sha = _sha256_str(current_text)
+ expected = _expected_new_hash(proposal, current_text)
+ if row["state"] == "APPLIED" and current_sha == expected:
+ report = reconcile_result_updates(root, memory)
+ finding = next(f for f in report["findings"] if f["proposal_id"] == proposal_id)
+ if finding["verdict"] != "CLEAN":
+ raise ResultUpdateError("applied record requires explicit reconciliation")
+ return json.loads((root / ".paperforge/result_updates" / proposal_id / "applied.json").read_bytes())
+ if row["state"] != "APPROVED":
+ raise ResultUpdateApprovalError("proposal is not APPROVED; reconcile incomplete operations explicitly")
+ if current_sha != approval["target_source_sha256"]:
+ raise ResultUpdateApprovalError("target changed after approval")
+ candidate = current_text.replace(proposal["old_block"], proposal["proposed_block"], 1)
+ if _sha256_str(candidate) != expected or proposal["proposed_block"] not in extract_protected_blocks(candidate):
+ raise ResultUpdateError("expected output binding mismatch")
with memory.connect() as db:
- db.execute("UPDATE result_updates SET state='APPLYING' WHERE id=?", (proposal_id,))
- try:
- spec_data = json.loads((base / "spec.json").read_text(encoding="utf-8"))
- _verify_ledger_bindings(workspace, memory, proposal.get("ledger_bindings") or [])
- _verify_proposal_artifacts(workspace, memory, proposal, expected=approval.get("artifact_hashes"))
- target = _resolve_target(root, spec_data["target_path"])
- current_text = target.read_text(encoding="utf-8")
- if _sha256_str(current_text) != approval["target_source_sha256"]:
- raise ResultUpdateApprovalError("target changed after approval")
- if _sha256_str(current_text) != proposal["target_source_sha256"]:
- raise ResultUpdateApprovalError("proposal stale: source changed")
- blocks = extract_protected_blocks(current_text)
- old_block = proposal["old_block"]
- if old_block not in current_text:
- raise ResultUpdateApprovalError("old block no longer present")
- candidate = current_text.replace(old_block, proposal["proposed_block"], 1)
- # Outside-block bytes must be identical.
- if candidate.replace(proposal["proposed_block"], "") != current_text.replace(old_block, ""):
- raise ResultUpdateApprovalError("scope violation: outside bytes changed")
- tmp = target.with_name(f".{target.name}.{proposal_id}.tmp")
- tmp.write_text(candidate, encoding="utf-8")
- tmp.replace(target)
- new_text = target.read_text(encoding="utf-8")
- new_blocks = extract_protected_blocks(new_text)
- if proposal["proposed_block"] not in new_blocks:
- raise ResultUpdateError("apply verification failed")
- new_source_sha = _sha256_str(new_text)
- new_block_sha = _block_hash(proposal["proposed_block"])
- # Idempotency: same proposal already applied (source equals expected new hash).
- with memory.connect() as db:
- db.execute(
- "INSERT OR REPLACE INTO result_baselines (target_path, source_sha256, block_sha256,"
- " proposal_id, approval_id, applied_at) VALUES (?, ?, ?, ?, ?, ?)",
- (spec_data["target_path"], new_source_sha, new_block_sha, proposal_id,
- approval.get("approval_id", ""), utc_now()),
- )
- db.execute("UPDATE result_updates SET state='APPLIED' WHERE id=?", (proposal_id,))
- (base / "applied.json").write_text(json.dumps({
- "proposal_id": proposal_id, "old_source_sha256": proposal["target_source_sha256"],
- "new_source_sha256": new_source_sha, "old_block_sha256": proposal["old_block_sha256"],
- "new_block_sha256": new_block_sha, "applied_at": utc_now(),
- "result_update_state": "applied", "scientific_review_state": "pending",
- "publication_ready": False,
- }, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- return {"proposal_id": proposal_id, "new_source_sha256": new_source_sha,
- "new_block_sha256": new_block_sha, "result_update_state": "applied",
- "scientific_review_state": "pending", "publication_ready": False}
- except BaseException as exc:
- with memory.connect() as db:
- try:
- db.execute("UPDATE result_updates SET state='ROLLED_BACK' WHERE id=?", (proposal_id,))
- except OSError:
- pass
- raise
+ changed = db.execute(
+ "UPDATE result_updates SET state='APPLYING' WHERE id=? AND state='APPROVED'", (proposal_id,)
+ ).rowcount
+ if changed != 1:
+ raise ResultUpdateError("concurrent result update state change")
+ # Any exception after APPLYING leaves a truthful incomplete operation.
+ # It must not claim ROLLED_BACK after the manuscript has been replaced.
+ if hashlib.sha256(target.read_bytes()).hexdigest() != current_sha:
+ raise ResultUpdateError("target changed immediately before replacement")
+ atomic_write_text(root, spec["target_path"], candidate)
+ if hashlib.sha256(target.read_bytes()).hexdigest() != expected:
+ raise ResultUpdateError("apply verification failed")
+ return _finish_applied(root, memory, proposal, spec, approval, expected)
def reconcile_result_updates(workspace: str | Path, memory: Any, *, repair: bool = False) -> dict[str, Any]:
- """Crash-window matrix: CLEAN / RECOVERABLE_FORWARD / ROLLBACK / MANUAL.
-
- A: APPROVED + target=old -> CLEAN (nothing applied yet).
- B: APPLYING + target=old -> RECOVERABLE_ROLLBACK to APPROVED.
- C: APPLYING + target=new -> RECOVERABLE_FORWARD (complete baseline/applied
- records without touching target again) when bindings still valid.
- D: APPLIED + target=new but applied.json/baseline missing -> FORWARD.
- E/F: target neither old nor new, or bindings invalid -> MANUAL.
- Exception-injection tests cover rollback; true power-loss proof stays U4.
+ """Classify exact crash states; repair audit/DB only, never target bytes.
+
+ Operators must quiesce writers before repair. Unknown, stale or unapproved
+ states are retained for manual intervention. No approval is created here.
"""
root = Path(workspace).expanduser().resolve(strict=True)
- _ensure_update_tables(memory)
- findings: list[dict[str, Any]] = []
with memory.connect() as db:
- rows = db.execute("SELECT * FROM result_updates").fetchall()
- for row in rows:
- proposal_id = str(row["id"])
- state = str(row["state"])
- base = root / ".paperforge" / "result_updates" / proposal_id
- try:
- proposal = json.loads((base / "proposal.json").read_text(encoding="utf-8"))
- spec_data = json.loads((base / "spec.json").read_text(encoding="utf-8"))
- except (OSError, ValueError):
- findings.append({"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED",
- "reason": "proposal files unreadable"})
- continue
- try:
- target = _resolve_target(root, str(spec_data.get("target_path")))
- current_sha = _sha256_str(target.read_text(encoding="utf-8"))
- except (OSError, ResultUpdateError):
- findings.append({"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED",
- "reason": "target unreadable"})
- continue
- old_sha, new_expected = str(proposal.get("target_source_sha256") or ""), None
- try:
- old_block, new_block = str(proposal.get("old_block") or ""), str(proposal.get("proposed_block") or "")
- current_text = target.read_text(encoding="utf-8")
- new_expected = _sha256_str(current_text.replace(old_block, new_block, 1)) if old_block in current_text else None
- if old_block not in current_text and new_block in current_text:
- # Already applied: expected new hash is the current hash.
- new_expected = current_sha
- except OSError:
- new_expected = None
- applied_path = base / "applied.json"
- with memory.connect() as db2:
- baseline = db2.execute("SELECT * FROM result_baselines WHERE proposal_id=?", (proposal_id,)).fetchone()
- if state in {"APPROVED", "VALIDATED", "NEEDS_HUMAN"} and current_sha == old_sha:
- findings.append({"proposal_id": proposal_id, "verdict": "CLEAN"})
- elif state == "APPLYING" and current_sha == old_sha:
- findings.append({"proposal_id": proposal_id, "verdict": "RECOVERABLE_ROLLBACK"})
- if repair:
- with memory.connect() as db3:
- db3.execute("UPDATE result_updates SET state='APPROVED' WHERE id=?", (proposal_id,))
- elif state == "APPLYING" and new_expected is not None and current_sha == new_expected:
- # Forward only when bindings still hold; never rewrite target here.
- try:
- _verify_ledger_bindings(workspace, memory, proposal.get("ledger_bindings") or [])
- _verify_proposal_artifacts(workspace, memory, proposal)
- verdict = "RECOVERABLE_FORWARD"
- except ResultUpdateError as exc:
- verdict = f"MANUAL_INTERVENTION_REQUIRED: {exc}"
- findings.append({"proposal_id": proposal_id, "verdict": verdict})
- if repair and verdict == "RECOVERABLE_FORWARD":
- with memory.connect() as db3:
- db3.execute(
- "INSERT OR REPLACE INTO result_baselines (target_path, source_sha256, block_sha256,"
- " proposal_id, approval_id, applied_at) VALUES (?, ?, ?, ?, ?, ?)",
- (str(spec_data.get("target_path")), current_sha,
- _block_hash(new_block), proposal_id, "", utc_now()),
- )
- db3.execute("UPDATE result_updates SET state='APPLIED' WHERE id=?", (proposal_id,))
- (base / "applied.json").write_text(json.dumps({
- "proposal_id": proposal_id, "new_source_sha256": current_sha,
- "recovered_forward": True, "applied_at": utc_now(),
- "result_update_state": "applied"}, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- elif state == "APPLIED":
- if current_sha != old_sha and applied_path.is_file() and baseline is not None:
- # Check file wasn't hand-modified after apply.
- if new_expected is not None and current_sha == new_expected:
- findings.append({"proposal_id": proposal_id, "verdict": "CLEAN"})
- else:
- findings.append({"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED",
- "reason": "applied target was hand-modified"})
- elif not applied_path.is_file() or baseline is None:
- findings.append({"proposal_id": proposal_id, "verdict": "RECOVERABLE_FORWARD",
- "reason": "applied record incomplete"})
+ if not db.execute("SELECT 1 FROM sqlite_master WHERE name='result_updates'").fetchone():
+ return {"findings": [], "mismatches": [], "consistent": True}
+ rows = db.execute("SELECT * FROM result_updates ORDER BY id").fetchall()
+ findings: list[dict[str, Any]] = []
+ for row in rows:
+ proposal_id, state = str(row["id"]), str(row["state"])
+ finding = {"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED"}
+ try:
+ proposal, spec, _ = _load_update(root, memory, proposal_id)
+ target = _resolve_target(root, spec["target_path"])
+ current_text = target.read_bytes().decode("utf-8")
+ current_sha = _sha256_str(current_text)
+ old_sha = proposal["target_source_sha256"]
+ expected = _expected_new_hash(proposal, current_text)
+ if state in {"VALIDATED", "NEEDS_HUMAN"} and current_sha == old_sha:
+ finding["verdict"] = "CLEAN"
+ else:
+ approval = _approval_for_recovery(root, memory, proposal)
+ if state == "APPROVED" and current_sha == old_sha:
+ finding["verdict"] = "CLEAN"
+ elif state == "APPLYING" and current_sha == old_sha:
+ finding["verdict"] = "RECOVERABLE_ROLLBACK"
if repair:
- (base / "applied.json").write_text(json.dumps({
- "proposal_id": proposal_id, "recovered_forward": True,
- "applied_at": utc_now()}, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- with memory.connect() as db3:
- db3.execute("UPDATE result_updates SET state='APPLIED' WHERE id=?", (proposal_id,))
+ with memory.connect() as db:
+ db.execute("UPDATE result_updates SET state='APPROVED' WHERE id=? AND state='APPLYING'",
+ (proposal_id,))
+ elif state in {"APPLYING", "APPLIED"} and current_sha == expected:
+ base = root / ".paperforge/result_updates" / proposal_id
+ applied_path = base / "applied.json"
+ reject_symlink_components(applied_path, anchor=root)
+ applied = json.loads(applied_path.read_bytes()) if applied_path.is_file() else None
+ with memory.connect() as db:
+ baseline = db.execute("SELECT * FROM result_baselines WHERE target_path=?",
+ (spec["target_path"],)).fetchone()
+ if applied is not None and any((
+ applied.get("proposal_id") != proposal_id,
+ applied.get("approval_id") != approval["approval_id"],
+ applied.get("old_source_sha256") != proposal["target_source_sha256"],
+ applied.get("old_block_sha256") != proposal["old_block_sha256"],
+ applied.get("new_source_sha256") != expected,
+ applied.get("new_block_sha256") != _block_hash(proposal["proposed_block"]),
+ applied.get("result_update_state") != "applied",
+ applied.get("scientific_review_state") != "pending",
+ applied.get("publication_ready") is not False,
+ not applied.get("applied_at"),
+ )):
+ raise ResultUpdateError("conflicting applied audit record")
+ if baseline is not None and any((
+ baseline["proposal_id"] != proposal_id,
+ baseline["source_sha256"] != expected,
+ baseline["block_sha256"] != _block_hash(proposal["proposed_block"]),
+ baseline["approval_id"] != approval["approval_id"],
+ applied is not None and baseline["applied_at"] != applied.get("applied_at"),
+ )):
+ raise ResultUpdateError("conflicting baseline; preserve for manual investigation")
+ if state == "APPLIED" and applied is not None and baseline is not None:
+ finding["verdict"] = "CLEAN"
+ else:
+ finding["verdict"] = "RECOVERABLE_FORWARD"
+ if repair:
+ # Recheck bytes immediately before completing technical records.
+ if hashlib.sha256(target.read_bytes()).hexdigest() != expected:
+ raise ResultUpdateError("target changed during reconciliation")
+ _finish_applied(root, memory, proposal, spec, approval, expected)
else:
- findings.append({"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED",
- "reason": "target neither old nor new"})
- else:
- findings.append({"proposal_id": proposal_id, "verdict": "MANUAL_INTERVENTION_REQUIRED",
- "reason": f"state={state} with unexpected target hash"})
- verdicts = {f["verdict"].split(":")[0] for f in findings}
- clean = all(v == "CLEAN" for v in verdicts) if findings else True
- return {"findings": findings, "mismatches": [f["proposal_id"] for f in findings if "CLEAN" not in f["verdict"]],
- "consistent": clean}
+ finding["reason"] = "target or operation state is not the approved old/new state"
+ except (OSError, ValueError, KeyError, TypeError, ResultUpdateError) as exc:
+ finding["verdict"] = "MANUAL_INTERVENTION_REQUIRED"
+ finding["reason"] = str(exc)
+ findings.append(finding)
+ return {"findings": findings,
+ "mismatches": [f["proposal_id"] for f in findings if f["verdict"] != "CLEAN"],
+ "consistent": all(f["verdict"] == "CLEAN" for f in findings)}
__all__ = [
diff --git a/paperforge/reviewer_matrix.py b/paperforge/reviewer_matrix.py
index 9451b34..1341c52 100644
--- a/paperforge/reviewer_matrix.py
+++ b/paperforge/reviewer_matrix.py
@@ -343,14 +343,13 @@ def freeze_review_matrix(
matrix_dir = _safe_mkdir(root / ".paperforge" / "review_matrix" / matrix_id, anchor=root)
payload = {**stable, "matrix_id": matrix_id, "matrix_digest": digest,
"created_at": utc_now()}
- for name, content in (("matrix.json", payload),
- ("manifest.json", {"matrix_id": matrix_id, "matrix_digest": digest})):
- target = matrix_dir / name
- tmp = target.with_name(f".{name}.tmp")
- import json as _json
-
- tmp.write_text(_json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp.replace(target)
+ from .immutable_artifacts import register_immutable, write_immutable_bundle
+
+ write_immutable_bundle(root, {
+ f".paperforge/review_matrix/{matrix_id}/matrix.json": payload,
+ f".paperforge/review_matrix/{matrix_id}/manifest.json": {"matrix_id": matrix_id, "matrix_digest": digest},
+ })
+ payload = json.loads((matrix_dir / "matrix.json").read_bytes())
from .artifacts import ArtifactStore
store = ArtifactStore(root, allowed_roots=(".paperforge/review_matrix",),
@@ -359,7 +358,7 @@ def freeze_review_matrix(
metadata = {"matrix_id": matrix_id, "matrix_digest": digest, "workflow_id": run_id,
"comment_ids": sorted(c.reviewer_comment_id for c in comments)}
for name, kind in (("matrix.json", "review"), ("manifest.json", "manifest")):
- store.register(f".paperforge/review_matrix/{matrix_id}/{name}", kind=kind,
+ register_immutable(store, f".paperforge/review_matrix/{matrix_id}/{name}", kind=kind,
run_id=run_id, status="VERIFIED", media_type="application/json", metadata=metadata)
return payload
@@ -409,12 +408,18 @@ def verify_review_matrix(workspace: str | Path, memory: Any, matrix_id: str) ->
referenced.update(str(c) for c in action.get("acceptance_criteria") or [])
complete = required_ids.issubset(referenced)
historical = "valid" if (digest_valid and comment_ok) else "invalid"
- currently_valid = bool(historical == "valid" and not stale and complete)
+ from .immutable_artifacts import verify_registered_bundle
+
+ registry = verify_registered_bundle(root, memory, {
+ f".paperforge/review_matrix/{matrix_id}/matrix.json": "review",
+ f".paperforge/review_matrix/{matrix_id}/manifest.json": "manifest"})
+ currently_valid = bool(historical == "valid" and not stale and complete and registry["registered_complete"])
# all_verified is separate from currently_valid.
all_verified = bool(payload.get("actions") and all(
str(a.get("status")) == "verified" for a in payload.get("actions", [])))
return {
"matrix_id": matrix_id,
+ **registry,
"matrix_file_sha256": file_sha,
"file_integrity": "valid",
"digest_valid": digest_valid,
diff --git a/paperforge/scientific_review.py b/paperforge/scientific_review.py
index 77fa185..74f181b 100644
--- a/paperforge/scientific_review.py
+++ b/paperforge/scientific_review.py
@@ -591,17 +591,14 @@ def freeze_review(
review_dir = _safe_mkdir(root / ".paperforge" / "reviews" / review_id, anchor=root)
payload = {**stable, "review_id": review_id, "review_digest": digest,
"created_at": __import__("paperforge.models", fromlist=["utc_now"]).utc_now()}
- for name, content in (
+ from .immutable_artifacts import register_immutable, write_immutable_bundle
+
+ write_immutable_bundle(root, {f".paperforge/reviews/{review_id}/{name}": content for name, content in (
("review.json", payload),
("manifest.json", {"review_id": review_id, "review_digest": digest,
"checker_version": CHECKER_VERSION, "rule_pack_digest": rule_digest}),
- ):
- target = review_dir / name
- tmp = target.with_name(f".{name}.tmp")
- import json as _json
-
- tmp.write_text(_json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp.replace(target)
+ )})
+ payload = json.loads((review_dir / "review.json").read_bytes())
# Register as review/audit artifact, never as scientific Evidence.
from .artifacts import ArtifactStore
@@ -612,7 +609,7 @@ def freeze_review(
"checker_version": CHECKER_VERSION, "rule_pack_digest": rule_digest,
"claim_ids": sorted(c.claim_id for c in claims), "workflow_id": run_id}
for name, kind in (("review.json", "review"), ("manifest.json", "manifest")):
- store.register(f".paperforge/reviews/{review_id}/{name}", kind=kind,
+ register_immutable(store, f".paperforge/reviews/{review_id}/{name}", kind=kind,
run_id=run_id, status="VERIFIED",
media_type="application/json", metadata=metadata)
return payload
@@ -661,7 +658,13 @@ def verify_scientific_review(workspace: str | Path, memory: Any, review_id: str)
checker_match = str(payload.get("checker_version") or "") == CHECKER_VERSION and checker_match
historical = "valid" if digest_valid else "invalid"
current = "current" if digest_valid and not stale and rule_match and checker_match else "stale"
+ from .immutable_artifacts import verify_registered_bundle
+
+ registry = verify_registered_bundle(root, memory, {
+ f".paperforge/reviews/{review_id}/review.json": "review",
+ f".paperforge/reviews/{review_id}/manifest.json": "manifest"})
return {
+ **registry,
"review_id": review_id,
"review_file_sha256": file_sha,
"review_file_integrity": "valid",
@@ -674,7 +677,8 @@ def verify_scientific_review(workspace: str | Path, memory: Any, review_id: str)
"checker_version_match": checker_match,
"historical_integrity": historical,
"source_currentness": current,
- "currently_valid_as_review_input": bool(historical == "valid" and current == "current"),
+ "currently_valid_as_review_input": bool(historical == "valid" and current == "current"
+ and registry["registered_complete"]),
"warnings": [] if historical == "valid" else ["review file or digest mismatch"],
}
diff --git a/tests/test_u22_finalization.py b/tests/test_u22_finalization.py
index a61a40f..55c33a9 100644
--- a/tests/test_u22_finalization.py
+++ b/tests/test_u22_finalization.py
@@ -301,8 +301,11 @@ def test_reconcile_detects_orphan(tmp_path: Path) -> None:
report = reconcile_imports(tmp_path, service.memory, repair=False)
assert out["evidence_ids"][0] in report["orphan_evidence"]
repaired = reconcile_imports(tmp_path, service.memory, repair=True)
- assert repaired.get("repaired") is True
- assert reconcile_imports(tmp_path, service.memory)["consistent"] is True
+ assert repaired.get("repaired") is False
+ assert repaired["recovery_outcome"] == "MANUAL_INTERVENTION_REQUIRED"
+ with service.memory.connect() as db:
+ assert db.execute("SELECT 1 FROM evidence WHERE id=?", (out["evidence_ids"][0],)).fetchone()
+ assert reconcile_imports(tmp_path, service.memory)["consistent"] is False
def test_subprocess_reopen_sees_committed_state(tmp_path: Path) -> None:
diff --git a/tests/test_u4b_finalization.py b/tests/test_u4b_finalization.py
index 4d238f2..eb5f433 100644
--- a/tests/test_u4b_finalization.py
+++ b/tests/test_u4b_finalization.py
@@ -236,6 +236,13 @@ def pdf_fixture(root, target, *, state="passed", warning_class="", pdf_sha=None)
folder = root / ".paperforge/pdf_qa" / bundle_id
folder.mkdir(parents=True, exist_ok=True)
(folder / "qa.json").write_text(json.dumps(payload))
+ (folder / "manifest.json").write_text(json.dumps({"bundle_id": bundle_id, "qa_digest": digest}))
+ from paperforge.artifacts import ArtifactStore
+
+ service = PaperForgeService(root)
+ store = ArtifactStore(root, allowed_roots=(".paperforge/pdf_qa",), memory=service.memory)
+ store.register(f".paperforge/pdf_qa/{bundle_id}/qa.json", kind="review")
+ store.register(f".paperforge/pdf_qa/{bundle_id}/manifest.json", kind="manifest")
return bundle_id
diff --git a/tests/test_u4c_artifact_recovery.py b/tests/test_u4c_artifact_recovery.py
new file mode 100644
index 0000000..763c6be
--- /dev/null
+++ b/tests/test_u4c_artifact_recovery.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.artifacts import ArtifactIntegrityError, ArtifactStore
+from paperforge.immutable_artifacts import verify_registered_bundle
+from test_u4b_finalization import setup_target
+
+
+def bundle_factory(root, kind):
+ service = PaperForgeService(root)
+ if kind == "ledger":
+ from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger, verify_ledger
+
+ eid = service.memory.add_evidence(evidence_type="TEST", excerpt="1 ms", metadata={
+ "measurement_kind": "measured", "acquisition_origin": "paperforge_run", "environment_role": "scientific",
+ "metric_name": "latency_ms", "value_str": "1", "unit": "ms", "run_identity": {"schema": "paperforge.scientific-run-identity/v1"}})
+ query = ResultLedgerQuery(purpose="scientific", metric_names=["latency_ms"], evidence_ids=(eid,))
+ return service, lambda: freeze_ledger(root, service.memory, query), "ledger_id", "ledgers", "ledger.json", lambda i: verify_ledger(root, service.memory, i)["eligible_as_release_input"]
+ if kind == "review":
+ from paperforge.scientific_review import ScientificClaim, freeze_review, review_claim, verify_scientific_review
+
+ claim = ScientificClaim("c", "descriptive", "descriptive_metric", fact_ids=("f",))
+ return service, lambda: freeze_review(root, service.memory, claims=[claim], results=review_claim(claim, facts={"f": {}})), "review_id", "reviews", "review.json", lambda i: verify_scientific_review(root, service.memory, i)["currently_valid_as_review_input"]
+ if kind == "matrix":
+ from paperforge.reviewer_matrix import freeze_review_matrix, verify_review_matrix
+
+ return service, lambda: freeze_review_matrix(root, service.memory, comments=[], actions=[], criteria=[]), "matrix_id", "review_matrix", "matrix.json", lambda i: verify_review_matrix(root, service.memory, i)["currently_valid"]
+ if kind == "pdf":
+ from paperforge.pdf_qa import PDFQASpec, SyntheticContentHashRenderer, run_pdf_qa, verify_pdf_qa
+ from test_u3b2_pdf_qa import _build_pdf
+
+ (root / "fixture.pdf").write_bytes(_build_pdf([{"texts": [(12, "Fixture")]}]))
+ spec = PDFQASpec(target_pdf_path="fixture.pdf")
+ return service, lambda: run_pdf_qa(root, service.memory, spec, renderer_backend=SyntheticContentHashRenderer(), allow_synthetic=True), "bundle_id", "pdf_qa", "qa.json", lambda i: verify_pdf_qa(root, service.memory, i)["currently_valid"]
+ from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+
+ service, target, policy = setup_target(root)
+ report = evaluate_release(root, service.memory, target, policy)
+ return service, lambda: freeze_assessment(root, service.memory, report), "report_id", "release", "report.json", lambda i: assessment_current(root, service.memory, i)["currently_valid"]
+
+
+@pytest.mark.parametrize("kind", ["ledger", "review", "matrix", "pdf", "release"])
+def test_registration_interrupted_retry_preserves_bytes(tmp_path, monkeypatch, kind):
+ service, freeze, identity_key, folder, filename, current = bundle_factory(tmp_path, kind)
+ original = ArtifactStore.register
+ calls = []
+
+ def interrupted(self, path, **kwargs):
+ calls.append(str(path))
+ if len(calls) == 2:
+ raise OSError("injected interruption between registry records")
+ return original(self, path, **kwargs)
+
+ monkeypatch.setattr(ArtifactStore, "register", interrupted)
+ with pytest.raises(OSError, match="interruption"):
+ freeze()
+ path = next((tmp_path / ".paperforge" / folder).glob(f"*/{filename}"))
+ before = path.read_bytes()
+ identity = json.loads(before)[identity_key]
+ assert not current(identity)
+ monkeypatch.setattr(ArtifactStore, "register", original)
+ payload = freeze()
+ assert payload[identity_key] == identity
+ assert current(identity)
+ assert path.read_bytes() == before
+ with service.memory.connect() as db:
+ baseline = list(db.iterdump())
+ for _ in range(20):
+ assert freeze()[identity_key] == identity
+ assert current(identity)
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == baseline
+ assert db.execute("SELECT count(*) FROM artifacts WHERE path LIKE ?", (f".paperforge/{folder}/{identity}/%",)).fetchone()[0] == 2
+ assert not list(path.parent.glob("*.tmp"))
+ assert not list(path.parent.glob("*.partial"))
+ assert not list(path.parent.glob(".*.json.*"))
+
+
+@pytest.mark.parametrize("kind", ["ledger", "review", "matrix", "pdf", "release"])
+@pytest.mark.parametrize("damage", ["missing", "bytes", "registry", "kind"])
+def test_registry_split_brain_never_current(tmp_path, kind, damage):
+ service, freeze, identity_key, folder, filename, current = bundle_factory(tmp_path, kind)
+ payload = freeze()
+ identity = payload[identity_key]
+ rel = f".paperforge/{folder}/{identity}/manifest.json"
+ path = tmp_path / rel
+ if damage == "missing":
+ path.unlink()
+ elif damage == "bytes":
+ path.write_bytes(b'{"unexpected": true}')
+ elif damage == "registry":
+ with service.memory.connect() as db:
+ db.execute("UPDATE artifacts SET sha256=? WHERE path=?", ("0" * 64, rel))
+ else:
+ with service.memory.connect() as db:
+ db.execute("UPDATE artifacts SET kind='review' WHERE path=?", (rel,))
+ assert not current(identity)
+ audit = verify_registered_bundle(tmp_path, service.memory, {rel: "manifest"})
+ assert not audit["registered_complete"]
+ if damage == "missing":
+ freeze()
+ assert current(identity)
+ else:
+ with pytest.raises(ArtifactIntegrityError):
+ freeze()
+ assert not current(identity)
+
+
+@pytest.mark.parametrize("kind", ["ledger", "review", "matrix", "pdf", "release"])
+def test_partial_json_is_not_authority_or_silently_overwritten(tmp_path, kind):
+ _, freeze, _, folder, filename, _ = bundle_factory(tmp_path, kind)
+ freeze()
+ path = next((tmp_path / ".paperforge" / folder).glob(f"*/{filename}"))
+ path.write_bytes(b'{"half":')
+ with pytest.raises((ArtifactIntegrityError, ValueError)):
+ freeze()
+ assert path.read_bytes() == b'{"half":'
diff --git a/tests/test_u4c_reopen_and_stress.py b/tests/test_u4c_reopen_and_stress.py
new file mode 100644
index 0000000..f513cf3
--- /dev/null
+++ b/tests/test_u4c_reopen_and_stress.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+import json
+from enum import Enum
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.external_import import ApprovalError, materialize_import, reconcile_imports
+from paperforge.models import WorkflowStatus
+from paperforge.result_update import reconcile_result_updates
+from test_u22_import_transaction import _approve_needs_human, _stage
+from test_u4c_result_recovery import prepared, set_state
+
+
+class RecoveryOutcome(str, Enum):
+ CLEAN = "CLEAN"
+ RECOVERABLE_FORWARD = "RECOVERABLE_FORWARD"
+ RECOVERABLE_ROLLBACK = "RECOVERABLE_ROLLBACK"
+ MANUAL_INTERVENTION_REQUIRED = "MANUAL_INTERVENTION_REQUIRED"
+ UNRECOVERABLE = "UNRECOVERABLE"
+
+
+@pytest.mark.parametrize("state", ["needs_human", "approved", "running"])
+def test_workflow_restart_preserves_domain_and_status_reads_are_readonly(tmp_path, state):
+ from frontend.process_manager import ProcessManager
+
+ service = PaperForgeService(tmp_path)
+ if state in {"needs_human", "approved"}:
+ handle = service.run(profile="full", inputs={})
+ run_id = handle.run_id
+ if state == "approved":
+ proposal_id = service.workflow.get(run_id)["metadata"]["proposal_id"]
+ service.approve(proposal_id, approved_by="test-owner")
+ approved = service.workflow.require_approval(proposal_id)
+ assert approved["status"] == "APPROVED"
+ expected = "AWAITING_APPROVAL"
+ else:
+ run_id = service.workflow.create("writing-only")
+ service.workflow.transition(run_id, WorkflowStatus.RUNNING)
+ expected = "RUNNING"
+ reopened = PaperForgeService(tmp_path)
+ process_manager = ProcessManager(root=tmp_path, results_dir=tmp_path / "results")
+ assert process_manager._runs == {}
+ if state == "approved":
+ assert reopened.workflow.require_approval(proposal_id) == approved
+ with reopened.memory.connect() as db:
+ before = list(db.iterdump())
+ for _ in range(20):
+ assert reopened.status(run_id).status == expected
+ unified = reopened.unified_status(run_id)["unified"]
+ assert unified["workflow_state"] == expected
+ assert unified["process_state"] == "UNKNOWN_NOT_ATTACHED"
+ assert unified["process_domain_relation"] == "process_unknown"
+ assert unified["workflow_state"] != "COMPLETED"
+ with reopened.memory.connect() as db:
+ assert list(db.iterdump()) == before
+
+
+@pytest.mark.parametrize("damage", ["orphan_evidence", "missing_evidence", "wrong_key", "empty_materialization", "content", "source_hash", "malformed_ids"])
+def test_import_ambiguous_state_is_retained_without_fabrication(tmp_path, damage):
+ service, record = _stage(tmp_path)
+ _approve_needs_human(tmp_path, service, record)
+ result = materialize_import(tmp_path, service.memory, record.import_id)
+ with service.memory.connect() as db:
+ if damage == "orphan_evidence":
+ db.execute("DELETE FROM import_materializations")
+ elif damage == "missing_evidence":
+ db.execute("DELETE FROM evidence WHERE id=?", (result["evidence_ids"][0],))
+ elif damage == "wrong_key":
+ row = db.execute("SELECT metadata_json FROM evidence WHERE id=?", (result["evidence_ids"][0],)).fetchone()
+ meta = json.loads(row[0])
+ meta["materialization_key"] = "unknown"
+ db.execute("UPDATE evidence SET metadata_json=? WHERE id=?", (json.dumps(meta), result["evidence_ids"][0]))
+ elif damage == "empty_materialization":
+ db.execute("UPDATE import_materializations SET evidence_ids_json='[]'")
+ elif damage == "content":
+ db.execute("UPDATE evidence SET excerpt='tampered scientific result'")
+ elif damage == "malformed_ids":
+ db.execute("UPDATE import_materializations SET evidence_ids_json='[{}]'")
+ else:
+ row = db.execute("SELECT metadata_json FROM evidence").fetchone()
+ meta = json.loads(row[0])
+ meta["source_sha256"] = "0" * 64
+ db.execute("UPDATE evidence SET metadata_json=?", (json.dumps(meta),))
+ before = list(db.iterdump())
+ for _ in range(2):
+ report = reconcile_imports(tmp_path, PaperForgeService(tmp_path).memory, repair=True)
+ assert RecoveryOutcome(report["recovery_outcome"]) == RecoveryOutcome.MANUAL_INTERVENTION_REQUIRED
+ assert report["repaired"] is False
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ with pytest.raises(ApprovalError, match="integrity mismatch"):
+ materialize_import(tmp_path, service.memory, record.import_id)
+
+
+def test_import_idempotency_stress_20_reopens(tmp_path):
+ service, record = _stage(tmp_path)
+ _approve_needs_human(tmp_path, service, record)
+ first = materialize_import(tmp_path, service.memory, record.import_id)
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ for _ in range(20):
+ reopened = PaperForgeService(tmp_path)
+ result = materialize_import(tmp_path, reopened.memory, record.import_id)
+ assert result["idempotent"]
+ assert result["evidence_ids"] == first["evidence_ids"]
+ assert RecoveryOutcome(reconcile_imports(tmp_path, reopened.memory, repair=True)["recovery_outcome"]) == RecoveryOutcome.CLEAN
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
+
+
+def test_result_update_recovery_stress_20_fresh_workspaces(tmp_path):
+ for iteration in range(20):
+ root = tmp_path / str(iteration)
+ root.mkdir()
+ service, proposal, _, _, new = prepared(root)
+ set_state(service, proposal, "APPLYING")
+ (root / "paper.tex").write_bytes(new)
+ reopened = PaperForgeService(root)
+ report = reconcile_result_updates(root, reopened.memory, repair=True)
+ assert RecoveryOutcome(report["findings"][0]["verdict"]) == RecoveryOutcome.RECOVERABLE_FORWARD
+ with reopened.memory.connect() as db:
+ before = list(db.iterdump())
+ for _ in range(2):
+ assert reconcile_result_updates(root, reopened.memory, repair=True)["consistent"]
+ assert (root / "paper.tex").read_bytes() == new
+ with reopened.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
+ assert not list(root.rglob("*.tmp"))
+ assert not list(root.rglob("*.partial"))
+ assert not list(root.rglob(".*.json.*"))
+ assert not list(root.rglob(".paper.tex.*"))
+
+
+def test_sqlite_durability_audit_and_rollback(tmp_path):
+ service = PaperForgeService(tmp_path)
+ with service.memory.connect() as db:
+ assert db.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal"
+ assert db.execute("PRAGMA synchronous").fetchone()[0] == 2 # FULL on this configured connection
+ assert db.execute("PRAGMA foreign_keys").fetchone()[0] == 1
+ with pytest.raises(RuntimeError, match="rollback"):
+ with service.memory.connect() as db:
+ db.execute("INSERT INTO metadata (key,value) VALUES ('u4c-rollback','uncommitted')")
+ raise RuntimeError("rollback")
+ with PaperForgeService(tmp_path).memory.connect() as db:
+ assert db.execute("SELECT value FROM metadata WHERE key='u4c-rollback'").fetchone() is None
diff --git a/tests/test_u4c_result_recovery.py b/tests/test_u4c_result_recovery.py
new file mode 100644
index 0000000..8000d27
--- /dev/null
+++ b/tests/test_u4c_result_recovery.py
@@ -0,0 +1,172 @@
+from __future__ import annotations
+
+import json
+from dataclasses import replace
+from pathlib import Path
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.result_update import apply_proposal, approve_proposal, build_proposal, reconcile_result_updates
+from test_u24a_finalization import _fact, _spec_with_table
+
+
+def prepared(root: Path):
+ service, spec, block, _ = _spec_with_table(root, "Old result 20.0 ms.")
+ old = (root / "paper.tex").read_bytes()
+ proposal = build_proposal(root, service.memory, spec,
+ proposed_block=block.replace("20.0", "22.4"), facts_used=[_fact()])
+ approval = approve_proposal(root, service.memory, proposal["proposal_id"], approver="test-owner")
+ new = old.replace(block.encode(), proposal["proposed_block"].encode(), 1)
+ return service, proposal, approval, old, new
+
+
+def set_state(service, proposal, state):
+ with service.memory.connect() as db:
+ db.execute("UPDATE result_updates SET state=? WHERE id=?", (state, proposal["proposal_id"]))
+
+
+def verdict(root, service, *, repair=False):
+ return reconcile_result_updates(root, service.memory, repair=repair)["findings"][0]["verdict"]
+
+
+@pytest.mark.parametrize("case", range(1, 9))
+def test_ru_crash_matrix(tmp_path, case):
+ service, proposal, approval, old, new = prepared(tmp_path)
+ base = tmp_path / ".paperforge/result_updates" / proposal["proposal_id"]
+ if case == 1:
+ assert verdict(tmp_path, service) == "CLEAN"
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ elif case == 2:
+ set_state(service, proposal, "APPLYING")
+ assert verdict(tmp_path, service) == "RECOVERABLE_ROLLBACK"
+ verdict(tmp_path, service, repair=True)
+ assert (tmp_path / "paper.tex").read_bytes() == old
+ elif case in {3, 7, 8}:
+ set_state(service, proposal, "APPLYING")
+ (tmp_path / "paper.tex").write_bytes(new)
+ if case == 7:
+ with service.memory.connect() as db:
+ db.execute("UPDATE result_approvals SET status='invalidated'")
+ assert verdict(tmp_path, service, repair=True) == "MANUAL_INTERVENTION_REQUIRED"
+ assert not (base / "applied.json").exists()
+ assert (tmp_path / "paper.tex").read_bytes() == new
+ return
+ assert verdict(tmp_path, service) == "RECOVERABLE_FORWARD"
+ verdict(tmp_path, service, repair=True)
+ elif case in {4, 5, 6}:
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ if case == 4:
+ (base / "applied.json").unlink()
+ elif case == 5:
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM result_baselines")
+ else:
+ # Keep the expected new block, but change bytes outside it.
+ unknown = new.replace(b"Intro.", b"Manual changes.")
+ (tmp_path / "paper.tex").write_bytes(unknown)
+ assert verdict(tmp_path, service, repair=True) == "MANUAL_INTERVENTION_REQUIRED"
+ assert (tmp_path / "paper.tex").read_bytes() == unknown
+ return
+ assert verdict(tmp_path, service) == "RECOVERABLE_FORWARD"
+ verdict(tmp_path, service, repair=True)
+ if case != 2:
+ assert (tmp_path / "paper.tex").read_bytes() == new
+ with service.memory.connect() as db:
+ baseline = db.execute("SELECT * FROM result_baselines").fetchone()
+ assert baseline["approval_id"] == approval["approval_id"]
+ assert json.loads((base / "applied.json").read_bytes())["new_source_sha256"] == baseline["source_sha256"]
+ before = (tmp_path / "paper.tex").read_bytes()
+ assert verdict(tmp_path, PaperForgeService(tmp_path), repair=True) == "CLEAN"
+ assert verdict(tmp_path, PaperForgeService(tmp_path), repair=True) == "CLEAN"
+ assert (tmp_path / "paper.tex").read_bytes() == before
+
+
+@pytest.mark.parametrize("damage", ["artifact", "approval_file", "proposal", "unapproved", "third_state"])
+def test_forward_recovery_cannot_bypass_binding(tmp_path, damage):
+ service, proposal, _, old, new = prepared(tmp_path)
+ base = tmp_path / ".paperforge/result_updates" / proposal["proposal_id"]
+ set_state(service, proposal, "APPLYING")
+ (tmp_path / "paper.tex").write_bytes(new)
+ if damage == "artifact":
+ (tmp_path / "artifacts/tables/table-1/table.tex").write_text("stale artifact")
+ elif damage == "approval_file":
+ (base / "approval.json").unlink()
+ elif damage == "proposal":
+ body = json.loads((base / "proposal.json").read_bytes())
+ body["proposed_block"] += "tampered"
+ (base / "proposal.json").write_text(json.dumps(body))
+ elif damage == "unapproved":
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM result_approvals")
+ elif damage == "third_state":
+ (tmp_path / "paper.tex").write_bytes(new + b"manual suffix")
+ before = (tmp_path / "paper.tex").read_bytes()
+ with service.memory.connect() as db:
+ domain_before = list(db.iterdump())
+ assert verdict(tmp_path, service, repair=True) == "MANUAL_INTERVENTION_REQUIRED"
+ assert (tmp_path / "paper.tex").read_bytes() == before
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == domain_before
+
+
+def test_exception_after_replace_does_not_claim_rollback(tmp_path, monkeypatch):
+ import paperforge.result_update as module
+
+ service, proposal, _, _, new = prepared(tmp_path)
+ original = module.atomic_write_text
+
+ def failing_write(workspace, path, text, **kwargs):
+ if str(path).endswith("applied.json"):
+ raise OSError("injected audit failure after target replace")
+ return original(workspace, path, text, **kwargs)
+
+ monkeypatch.setattr(module, "atomic_write_text", failing_write)
+ with pytest.raises(OSError):
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ assert (tmp_path / "paper.tex").read_bytes() == new
+ with service.memory.connect() as db:
+ assert db.execute("SELECT state FROM result_updates").fetchone()[0] != "ROLLED_BACK"
+ monkeypatch.setattr(module, "atomic_write_text", original)
+ assert verdict(tmp_path, service) == "RECOVERABLE_FORWARD"
+ verdict(tmp_path, service, repair=True)
+ assert verdict(tmp_path, service) == "CLEAN"
+
+
+@pytest.mark.parametrize("field,value", [("approval_id", "nonexistent"), ("old_source_sha256", "0" * 64),
+ ("publication_ready", True), ("scientific_review_state", "reviewed"),
+ ("applied_at", "different-time")])
+def test_corrupt_applied_audit_cannot_be_clean_or_returned(tmp_path, field, value):
+ service, proposal, _, _, new = prepared(tmp_path)
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ path = tmp_path / ".paperforge/result_updates" / proposal["proposal_id"] / "applied.json"
+ payload = json.loads(path.read_bytes())
+ payload[field] = value
+ path.write_text(json.dumps(payload))
+ before = path.read_bytes()
+ assert verdict(tmp_path, service, repair=True) == "MANUAL_INTERVENTION_REQUIRED"
+ with pytest.raises(Exception, match="reconciliation"):
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ assert path.read_bytes() == before
+ assert (tmp_path / "paper.tex").read_bytes() == new
+
+
+def test_stale_ledger_blocks_forward_recovery(tmp_path):
+ from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger
+
+ service, spec, old, _ = _spec_with_table(tmp_path, "Old result 20.0 ms.")
+ eid = service.memory.add_evidence(evidence_type="TEST", excerpt="latency", metadata={
+ "measurement_kind": "measured", "acquisition_origin": "paperforge_run", "environment_role": "scientific",
+ "metric_name": "latency_ms", "value_str": "22.4", "unit": "ms", "run_identity": {"schema": "paperforge.scientific-run-identity/v1"}})
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ purpose="scientific", metric_names=["latency_ms"], evidence_ids=(eid,)))
+ spec = replace(spec, ledger_bindings=({"ledger_id": ledger["ledger_id"], "ledger_digest": ledger["ledger_digest"]},))
+ proposal = build_proposal(tmp_path, service.memory, spec, proposed_block=old.replace("20.0", "22.4"), facts_used=[_fact()])
+ approve_proposal(tmp_path, service.memory, proposal["proposal_id"], approver="owner")
+ set_state(service, proposal, "APPLYING")
+ new = (tmp_path / "paper.tex").read_text().replace(old, proposal["proposed_block"], 1)
+ (tmp_path / "paper.tex").write_text(new)
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM evidence WHERE id=?", (eid,))
+ assert verdict(tmp_path, service, repair=True) == "MANUAL_INTERVENTION_REQUIRED"
+ assert (tmp_path / "paper.tex").read_text() == new
diff --git a/tests/test_u4c_subprocess.py b/tests/test_u4c_subprocess.py
new file mode 100644
index 0000000..e2c2845
--- /dev/null
+++ b/tests/test_u4c_subprocess.py
@@ -0,0 +1,113 @@
+from __future__ import annotations
+
+import json
+import selectors
+import signal
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.external_import import materialize_import, reconcile_imports
+from paperforge.result_update import reconcile_result_updates
+from test_u22_import_transaction import _approve_needs_human, _stage
+from test_u4b_finalization import setup_target
+from test_u4c_result_recovery import prepared
+
+
+def kill_at_checkpoint(root: Path, mode: str, identity: str = "unused") -> None:
+ if not hasattr(signal, "SIGKILL"):
+ pytest.skip("SIGKILL unavailable on this platform; not a power-loss test")
+ worker = Path(__file__).with_name("u4c_crash_child.py")
+ process = subprocess.Popen([sys.executable, str(worker), str(root), mode, identity],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ assert selector.select(timeout=20), "child did not reach controlled crash point"
+ line = process.stdout.readline()
+ if line.strip() != "U4C_READY_TO_KILL":
+ process.kill()
+ _, error = process.communicate(timeout=10)
+ pytest.fail(f"child failed before crash point: {line} {error}")
+ process.kill()
+ process.communicate(timeout=10)
+ assert process.returncode == -signal.SIGKILL
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.communicate(timeout=10)
+
+
+@pytest.mark.parametrize("mode", ["import_precommit", "import_postcommit"])
+def test_external_import_real_sigkill_reopen(tmp_path, mode):
+ service, record = _stage(tmp_path)
+ _approve_needs_human(tmp_path, service, record)
+ kill_at_checkpoint(tmp_path, mode, record.import_id)
+ reopened = PaperForgeService(tmp_path)
+ with reopened.memory.connect() as db:
+ assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
+ count = db.execute("SELECT count(*) FROM evidence").fetchone()[0]
+ materials = db.execute("SELECT count(*) FROM import_materializations").fetchone()[0]
+ state = db.execute("SELECT state FROM imports WHERE id=?", (record.import_id,)).fetchone()[0]
+ if mode == "import_precommit":
+ assert count == materials == 0
+ assert state != "materialized"
+ else:
+ assert count == materials == 1
+ assert state == "materialized"
+ assert reconcile_imports(tmp_path, reopened.memory)["consistent"]
+ first = materialize_import(tmp_path, reopened.memory, record.import_id)
+ second = materialize_import(tmp_path, reopened.memory, record.import_id)
+ assert first["evidence_ids"] == second["evidence_ids"]
+ assert second["idempotent"]
+
+
+@pytest.mark.parametrize("mode,expected", [("result_pre_replace", "RECOVERABLE_ROLLBACK"),
+ ("result_post_replace", "RECOVERABLE_FORWARD")])
+def test_result_update_real_sigkill_reopen(tmp_path, mode, expected):
+ _, proposal, _, old, new = prepared(tmp_path)
+ kill_at_checkpoint(tmp_path, mode, proposal["proposal_id"])
+ reopened = PaperForgeService(tmp_path)
+ before = (tmp_path / "paper.tex").read_bytes()
+ assert before == (old if mode == "result_pre_replace" else new)
+ report = reconcile_result_updates(tmp_path, reopened.memory)
+ assert report["findings"][0]["verdict"] == expected
+ reconcile_result_updates(tmp_path, reopened.memory, repair=True)
+ assert reconcile_result_updates(tmp_path, reopened.memory)["consistent"]
+ assert (tmp_path / "paper.tex").read_bytes() == before
+
+
+def test_evaluator_real_sigkill_has_no_domain_mutation(tmp_path):
+ from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+
+ service, target, policy = setup_target(tmp_path)
+ (tmp_path / "test-target.json").write_text(json.dumps(target.to_dict()))
+ report = evaluate_release(tmp_path, service.memory, target, policy)
+ freeze_assessment(tmp_path, service.memory, report)
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ report_path = tmp_path / ".paperforge/release" / report["report_id"] / "report.json"
+ history = report_path.read_bytes()
+ kill_at_checkpoint(tmp_path, "evaluator")
+ reopened = PaperForgeService(tmp_path)
+ with reopened.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ assert report_path.read_bytes() == history
+ assert evaluate_release(tmp_path, reopened.memory, target, policy)["report_digest"] == report["report_digest"]
+ assert assessment_current(tmp_path, reopened.memory, report["report_id"])["currently_valid"]
+
+
+def test_release_freeze_real_sigkill_before_registry(tmp_path):
+ from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+
+ service, target, policy = setup_target(tmp_path)
+ (tmp_path / "test-target.json").write_text(json.dumps(target.to_dict()))
+ report = evaluate_release(tmp_path, service.memory, target, policy)
+ kill_at_checkpoint(tmp_path, "release_registry")
+ reopened = PaperForgeService(tmp_path)
+ assert not assessment_current(tmp_path, reopened.memory, report["report_id"])["currently_valid"]
+ freeze_assessment(tmp_path, reopened.memory, report)
+ assert assessment_current(tmp_path, reopened.memory, report["report_id"])["currently_valid"]
diff --git a/tests/u4c_crash_child.py b/tests/u4c_crash_child.py
new file mode 100644
index 0000000..ec13fbd
--- /dev/null
+++ b/tests/u4c_crash_child.py
@@ -0,0 +1,72 @@
+"""Subprocess-only fault injector. Never imported by production code."""
+from __future__ import annotations
+
+import json
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from paperforge.api import PaperForgeService
+
+
+def crash_point():
+ print("U4C_READY_TO_KILL", flush=True)
+ while True:
+ time.sleep(60)
+
+
+def main():
+ root, mode, identity = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
+ service = PaperForgeService(root)
+ if mode.startswith("import"):
+ import paperforge.external_import as module
+
+ original = module._insert_evidence_row
+ if mode == "import_precommit":
+ def insert(*args, **kwargs):
+ result = original(*args, **kwargs)
+ crash_point()
+ return result
+ module._insert_evidence_row = insert
+ module.materialize_import(root, service.memory, identity)
+ crash_point()
+ elif mode.startswith("result"):
+ import paperforge.result_update as module
+
+ original = module.atomic_write_text
+ def write(workspace, relative, content, **kwargs):
+ if str(relative) == "paper.tex" and mode == "result_pre_replace":
+ crash_point()
+ result = original(workspace, relative, content, **kwargs)
+ if str(relative) == "paper.tex":
+ crash_point()
+ return result
+ module.atomic_write_text = write
+ module.apply_proposal(root, service.memory, identity)
+ else:
+ import paperforge.release_eligibility as module
+
+ params = json.loads((root / "test-target.json").read_bytes())
+ target = module.ReleaseTarget(**params)
+ policy = module.ReleasePolicy(required_gates=("source_integrity",))
+ if mode == "evaluator":
+ original = module._snapshot
+ def snapshot(*args, **kwargs):
+ crash_point()
+ return original(*args, **kwargs)
+ module._snapshot = snapshot
+ report = module.evaluate_release(root, service.memory, target, policy)
+ if mode == "release_registry":
+ from paperforge.artifacts import ArtifactStore
+ original_register = ArtifactStore.register
+ def register(self, *args, **kwargs):
+ crash_point()
+ return original_register(self, *args, **kwargs)
+ ArtifactStore.register = register
+ module.freeze_assessment(root, service.memory, report)
+
+
+if __name__ == "__main__":
+ main()
From 530d2f50dfbefec05b760c5e0f032cb09b781905 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Sun, 27 Sep 2026 23:17:02 +0800
Subject: [PATCH 15/30] chore: add merge readiness inventory
---
docs/u4d-merge-readiness.md | 129 ++++++++++++++++++++++++++++++++++++
1 file changed, 129 insertions(+)
create mode 100644 docs/u4d-merge-readiness.md
diff --git a/docs/u4d-merge-readiness.md b/docs/u4d-merge-readiness.md
new file mode 100644
index 0000000..6d0b938
--- /dev/null
+++ b/docs/u4d-merge-readiness.md
@@ -0,0 +1,129 @@
+# U4D merge/release readiness preparation
+
+Inventory date: 2026-09-27. This is **U4D-Prep**, not final merge approval,
+publication authorization, or a release announcement.
+
+- Batch baseline: `7bc397ba3ed8a76383c7834a4bfd2b20856f0b80` (U4B).
+- U4C code/report: `b72fa9f368abc92617027734637d80c919fde505`.
+- Local branch: `feature/u4c-reliability`.
+- Reliability evidence: [U4C report](u4c-reliability.md).
+- Previous finalization: [U4B report](u4b-finalization.md), retained as a historical
+ snapshot; its previous test counts are superseded by the current counts below.
+
+## MergeReadinessInventory
+
+### A. Functional status
+
+| Stage | Status | Qualification |
+|---|---|---|
+| U0-U3B-2 | PASSED (handoff baseline) | Existing executable regression retained |
+| D1 | CLOSED (handoff baseline) | No reopened feature work |
+| V0 | CLOSED / PASSED_WITH_FINDINGS (handoff baseline) | Shadow artifacts remain private and untracked |
+| U4A | PASSED, `c628f85` | Restart/status regression retained; no Pause/Resume rewrite |
+| U4B | PASSED, `7bc397b` | Eligibility is not authorization or released state |
+| U4C | PASSED_WITH_LIMITATIONS, `b72fa9f` | RU-1..8, six actual SIGKILL cases, EI/AF/WF/RE matrices pass |
+| U4D-Prep | COMPLETE | Inventory/report only; no new scientific semantics |
+| U4D Final | NOT_STARTED / BLOCKED_ENVIRONMENT | Full tests/static checks and authorized push/review still outstanding |
+
+U4C proves controlled process termination/reopen under a single-writer model.
+It does not prove concurrent-writer recovery, physical power-loss durability,
+or automatic repair of unknown third states. Recovery never mints Evidence,
+approval, human/reviewer decisions or release authorization. Real manuscripts
+must not bootstrap their own Evidence; synthetic recovery fixtures are not
+scientific validation or publication evidence.
+
+### B-D. QualityGateStatus, tests, static analysis and dependencies
+
+| Gate | Status | Current evidence / remaining action |
+|---|---|---|
+| u4c_targeted | PASS | 69 passed, 0 skipped/failed/errors |
+| executable_regression | PASS_WITH_EXCLUSIONS | 628 passed, 6 skipped, 10 deselected; two collection-blocked modules ignored explicitly |
+| full_pytest | BLOCKED_ENVIRONMENT | 644 collected; 628 passed, 6 skipped, 10 failed, 2 collection errors |
+| pymupdf_full_suite | BLOCKED_ENVIRONMENT | All 10 failures and both collection errors end at the missing `pymupdf` import |
+| ruff | NOT_RUN_TOOL_UNAVAILABLE | `python3.11 -m ruff --version`: no module named ruff |
+| mypy | NOT_RUN_TOOL_UNAVAILABLE | `python3.11 -m mypy --version`: no module named mypy |
+| visualization_pdf | BLOCKED_ENVIRONMENT | One skipped case cannot import `fitz` (PyMuPDF) |
+| live_compute_integration | NOT_RUN_OPT_IN | Five Docker/OpenSSH/Slurm/Kubernetes cases skipped, not claimed PASS |
+| local_code_security_review | PASS_WITH_SCOPE_LIMITATIONS | Python reviewer inspected changed code and security boundaries; final review no HIGH/CRITICAL findings |
+| final_security_static_checks | NOT_RUN | Full U4D environment/security gate remains outstanding; local review is not a substitute |
+| final_v1_smoke | NOT_RUN | U4C recovery fixtures do not substitute for a final V1-style acceptance run |
+| remote_automatic_reviews | NOT_RUN_NO_PUSH | No push in this batch |
+
+The known environment blocker is unchanged from baseline (559 passed, 6 skipped,
+10 failed, 2 collection errors). The 69 additional passing cases are U4C tests;
+no new failure or collection error was observed. The full repository is **not
+green**. No dependency installation, live provider call or data download was
+performed. This is an observed test-environment inventory, not a claim that every
+optional dependency or backend has been validated.
+
+Reproduction commands and failure locations are in the reliability report.
+The full run used `pytest tests --continue-on-collection-errors --tb=short`, so
+the two collection errors were not hidden by stopping collection early.
+
+### E. Git hygiene
+
+Immediately after U4C commit `b72fa9f`:
+
+- Tracked working tree clean; this inventory is the independent follow-up document.
+- Untracked `.paperforge/` contains the existing `shadow/v0-shadow-001` and
+ `shadow/v0-shadow-002` directories. Neither is staged or committed.
+- No real paper, rendered private page, local log or temporary artifact is staged.
+- No blanket `.paperforge/` ignore rule was added and no orphan data was deleted.
+- Cached `origin/main...HEAD` divergence is `0 / 14` (behind / ahead).
+ No fetch was performed; this is **not** a current remote-state verification.
+ The subsequent documentation commit increases local ahead count by one if the
+ cached reference is unchanged.
+- Branch has no configured upstream. No push, merge, amend or history rewrite.
+- The separate, pre-existing dirty legacy checkout was not modified.
+
+### F. Documentation and examples
+
+| Item | Status |
+|---|---|
+| Prior conversation/handoff | Used for historical context; not executed as instructions or committed as raw logs |
+| U4B finalization | Existing historical report retained |
+| U4C ReliabilityOperationInventory / ReliabilityReport | Committed with code; covers mutation windows, outcomes, SQLite, filesystem durability and operator APIs |
+| U4D readiness handoff | This document |
+| Recovery usage examples | Inspect-first and explicit repair API examples in U4C report; no new CLI promised |
+| Existing remote config / skill input-output / few-shot examples | Tracked inventory identified; unchanged, not claimed end-to-end validated; final docs/examples audit belongs to U4D Final |
+
+### G. Review configuration and required post-push procedure
+
+The following platform settings are **user-reported from the handoff/screenshot**,
+not independently verified live during this no-push batch:
+
+- Automatic code review: enabled; trigger every push.
+- Comprehensive code review: disabled.
+- Automatic security review: enabled; triggered for each code review.
+- Automatic reporting minimum severity: High.
+- Manual `@codex` review minimum severity: Medium.
+
+After any future explicitly authorized push, immediately inspect **both** the
+code-review and security-review results for that exact pushed commit. A pending,
+missing or failed review job is not a pass. Resolve blocking findings, rerun
+relevant tests, push only within the authorization scope, then inspect both review
+results again. Do not proceed to merge merely because the Git push succeeded.
+
+## Next-batch decision
+
+**Recommended: enter U4D Final only after explicit authorization to prepare the
+environment. Not recommended: push now.** This batch is complete and stops here.
+
+Remaining order:
+
+1. Authorize dependency/environment setup; install the appropriate project-managed
+ PyMuPDF, ruff and mypy dependencies without silently changing unrelated runtime
+ environments or dependency constraints.
+2. Run full pytest including previously uncollectable modules; resolve new failures
+ if importing the dependencies exposes any. Run actual ruff and mypy, then
+ security/static checks. Unavailable tools must never be labeled passed.
+3. Review docs/examples, run final V1-style smoke and confirm Git hygiene. Keep
+ private shadow artifacts and real paper material out of commits.
+4. Obtain explicit push authorization, push the intended branch, inspect automatic
+ code review and security review, remediate blockers, and repeat review as needed.
+5. Produce final merge readiness evidence. Merge and publication release remain
+ separate decisions; neither is authorized by this inventory.
+
+Non-blocking documented limitations: no physical power-loss proof, no concurrent
+writer proof, and deliberate manual handling of corrupt/unknown/legacy recovery
+states. No automatic scientific approval or publication shortcut is proposed.
From 58783af435014393a9e133ef31c0387a24085a67 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Wed, 30 Sep 2026 15:22:02 +0800
Subject: [PATCH 16/30] chore: close configured lint and type gates in isolated
Python environment
---
docs/u4d-final-execution.md | 90 ++++++++++++++++++++++++++++
paperforge/evidence_semantics.py | 5 +-
paperforge/external_import.py | 22 ++++---
paperforge/grounded_narrative.py | 9 +--
paperforge/metric_adapters.py | 18 ++++--
paperforge/metric_observation.py | 3 +-
paperforge/pdf_qa.py | 39 ++++++------
paperforge/publication_artifacts.py | 20 +++----
paperforge/references.py | 14 +++--
paperforge/release_eligibility.py | 17 +++---
paperforge/result_ledger.py | 25 ++++----
paperforge/result_update.py | 21 +++----
paperforge/reviewer_matrix.py | 10 ++--
paperforge/run_status.py | 3 +-
paperforge/scientific_review.py | 10 ++--
paperforge/writing_patch.py | 7 +--
tests/test_compute_backends.py | 3 +
tests/test_d1_page_count.py | 3 +-
tests/test_u22_finalization.py | 4 +-
tests/test_u22_import_transaction.py | 16 +++--
tests/test_u23_finalization.py | 2 +-
tests/test_u23_ledger_core.py | 3 -
tests/test_u23b_artifacts.py | 1 -
tests/test_u24a_finalization.py | 3 +-
tests/test_u24a_result_update.py | 1 -
tests/test_u24b_narrative.py | 5 +-
tests/test_u3a_review_core.py | 2 -
tests/test_u3b1_matrix.py | 3 -
tests/test_u3b2_finalization.py | 5 +-
tests/test_u3b2_pdf_qa.py | 4 +-
tests/test_u4b_finalization.py | 19 +++++-
tests/test_u4b_release.py | 3 -
tests/test_u4c_artifact_recovery.py | 23 +++++--
tests/test_u4c_reopen_and_stress.py | 11 ++--
tests/test_u4c_result_recovery.py | 9 ++-
tests/test_u4c_subprocess.py | 18 ++++--
36 files changed, 286 insertions(+), 165 deletions(-)
create mode 100644 docs/u4d-final-execution.md
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
new file mode 100644
index 0000000..6e9221a
--- /dev/null
+++ b/docs/u4d-final-execution.md
@@ -0,0 +1,90 @@
+# U4D Final execution and downstream handoff
+
+Batch started 2026-09-30 from `530d2f50dfbefec05b760c5e0f032cb09b781905`,
+branch `feature/u4c-reliability`. This is a running evidence log, not a completion
+certificate. The full batch includes the subsequent PCB paper revision; completing
+U4D alone must not close the overall goal.
+
+## Authorization and order
+
+The batch owner authorizes isolated Python 3.11 dependency installation, source and
+test repairs, local commits, and feature-branch push only after every required local
+gate passes. Every push must be followed by inspection of both automatic code and
+security review findings for the exact commit. No automatic merge.
+
+After tool freeze, work in a separate paper revision branch/copy. Preserve original
+source and experimental artifacts. Never promote manuscript-only numbers, fixtures,
+simulated/remapped values or fixed-power proxies into measured Evidence. Human-only
+gates remain pending; continue other independent tasks. No new third-party upload
+of unpublished materials, paid resources, sudo, or system Python 3.14.
+
+## Requirement coverage tracker
+
+| Requirements | Evidence required | Current state |
+|---|---|---|
+| A1 environment | Interpreter/venv/pip and declared dependency inspection | IN_PROGRESS |
+| A2 full tests | Full pytest, counts and failure classification | PENDING |
+| A3-A4 static | Existing Ruff whole-repository and mypy paperforge scope pass | PENDING |
+| A5 integration | End-to-end synthetic evidence-to-status FinalSmokeReport and negative boundaries | PENDING |
+| A6 reliability | ResultUpdate, actual kill/reopen, import reopen, split-brain | PENDING |
+| A7-A10 local readiness | Documentation, hygiene, security review, commits | PENDING |
+| A11-A13 remote/freeze | Required local gates, authorized push, both review findings, fix/retest loop | PENDING |
+| B0-B4 / P0 | Unique paper workspace, revision copy, baseline hashes, inventory, legal imports/ledger | PENDING_TOOL_FREEZE |
+| C1-C7 / P1 | Layer guidance, bounded attribution, external validity, citation/PLC audit, layout, controlled patches | PENDING_TOOL_FREEZE |
+| D1-D10 / P2-P3 / H0-H4 | Hardware and artifact inventory, frozen protocols, real feasible measurements/analyses | PENDING_TOOL_FREEZE |
+| E1-E4 / V0-V3 | Split, provenance, hardware and scientific-scope audits | PENDING_TOOL_FREEZE |
+| F1-F8 / P4 / V4 | Verified ledger, deterministic artifacts, grounded text, review, controlled update, consistency | PENDING_TOOL_FREEZE |
+| F9-F12 | Bound compile, every-page render/QA, real human requests, response draft, revision package | PENDING_TOOL_FREEZE |
+| G1-G3 | Separate paper commits, conditional push, itemized P/H/V/R statuses and blockers | PENDING_TOOL_FREEZE |
+| H-I | Continuous independent progress; final 40-item consolidated delivery | PENDING |
+
+## Preflight facts
+
+- Initial tracked worktree clean; existing untracked `.paperforge/` retained.
+- Python support remains `>=3.10,<3.13`; no metadata change required for the three
+ known missing dependencies.
+- `pymupdf==1.27.1` is an optional writing dependency, also installed by the official
+ dev requirements through `requirements-writeup.txt`.
+- `ruff==0.12.2` and `mypy==1.16.1` are dev-only dependencies.
+- Created repository-local ignored `.venv` with `/opt/homebrew/bin/python3.11`.
+ Installation uses `.venv/bin/python3.11 -m pip install -r requirements-dev.txt`;
+ no global environment is modified.
+- Official CI scope: `python -m pytest -q --tb=short`, `python -m ruff check .`,
+ `python -m mypy paperforge`. Pytest discovers `tests`; Ruff retains the existing
+ exclusions/rules; mypy retains the configured `paperforge` scope.
+- No push, paper edits, or release authorization has occurred in this batch.
+
+## Limitations retained
+
+U4C remains PASSED_WITH_LIMITATIONS: controlled termination under a single-writer,
+quiesced-repair model. Physical power loss and concurrent writers are not proven.
+The earlier U4C/U4D-Prep reports are historical evidence, not current gate results.
+
+## First verified checkpoint
+
+- Official dev requirements installed successfully into `.venv`; `pip check`
+ reports no broken requirements. No dependency metadata changes were needed.
+- Initial isolated full run: 703 passed, 5 skipped, 3 failed, 0 collection errors.
+ Classification: TEST_EXPECTATION / non-hermetic fixture. Three LocalBackend
+ tests implicitly copied the repository cwd, including the new venv symlinks.
+ They now explicitly use their own `tmp_path` as workdir; the production symlink
+ rejection policy and all assertions remain intact.
+- After repairs: **711 collected, 706 passed, 5 skipped, 0 failed, 0 errors**.
+ All five skips are opt-in real Docker/SSH/Slurm/Kubernetes integration cases.
+ Five PyMuPDF SWIG deprecation warnings remain visible.
+- Ruff official scope PASS after import/unused-code/style cleanup; no configuration
+ relaxation. A vacuous `... or True` assertion was strengthened to require the
+ persisted audit timestamp, and three broad exception assertions were narrowed.
+- Mypy official scope PASS (80 source files), with explicit mapping narrowing,
+ manifest annotations and immutable-adapter Protocol properties. No blanket
+ `ignore_errors` or scope reduction.
+- Independent Python review found no new HIGH/CRITICAL in these repairs. It did
+ reproduce a **pre-existing HIGH** in publication artifact fixed-name temporary
+ writes: symlink traversal can overwrite an outside sentinel before registration
+ rejects the output. This blocks push; repair and regression are next.
+- End-to-end smoke inspection also found the import-to-ledger adapter connection
+ requires verification: imported source Evidence lacks inline metric metadata,
+ while ledger currently consumes only inline metadata. Do not fake this connection
+ with hand-added scientific Evidence. A dedicated regression is required.
+- Integration smoke, final security, remote review, tool freeze and all paper
+ revision requirements remain open. No push is authorized by this checkpoint alone.
diff --git a/paperforge/evidence_semantics.py b/paperforge/evidence_semantics.py
index d11bc49..b07b6b9 100644
--- a/paperforge/evidence_semantics.py
+++ b/paperforge/evidence_semantics.py
@@ -1,7 +1,8 @@
from __future__ import annotations
-from dataclasses import asdict, dataclass, field
-from typing import Any, Mapping
+from collections.abc import Mapping
+from dataclasses import asdict, dataclass
+from typing import Any
class EvidenceSemanticsError(ValueError):
diff --git a/paperforge/external_import.py b/paperforge/external_import.py
index 5a15a86..cb1e839 100644
--- a/paperforge/external_import.py
+++ b/paperforge/external_import.py
@@ -1,11 +1,13 @@
from __future__ import annotations
+import contextlib
import hashlib
import json
import uuid
+from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
from .evidence_semantics import EvidenceSemantics, EvidenceSemanticsError
from .models import utc_now
@@ -432,8 +434,10 @@ def validate_import(workspace: str | Path, memory: Any, import_id: str) -> dict[
else:
checks.append(_check_entry("schema_valid", "passed", IMPORT_SCHEMA))
# Required metadata (minimal, auditable).
- subject = manifest.get("subject") if isinstance(manifest.get("subject"), Mapping) else {}
- execution = manifest.get("execution") if isinstance(manifest.get("execution"), Mapping) else {}
+ subject_value = manifest.get("subject")
+ execution_value = manifest.get("execution")
+ subject = subject_value if isinstance(subject_value, Mapping) else {}
+ execution = execution_value if isinstance(execution_value, Mapping) else {}
for field in ("model_id", "dataset_id"):
if str(subject.get(field) or "").strip():
checks.append(_check_entry(f"subject.{field}", "passed", str(subject[field])[:120]))
@@ -470,7 +474,8 @@ def validate_import(workspace: str | Path, memory: Any, import_id: str) -> dict[
checks.append(_check_entry("semantics_valid", "failed", str(exc)))
checks.append(_check_entry("semantics_admissible", "failed", "invalid semantics"))
# Sources: existence + hash recomputation.
- declared = manifest.get("sources") if isinstance(manifest.get("sources"), list) else []
+ sources_value = manifest.get("sources")
+ declared = sources_value if isinstance(sources_value, list) else []
actual_hashes: dict[str, str] = {}
if not declared:
checks.append(_check_entry("sources_present", "failed", "no sources declared"))
@@ -529,7 +534,8 @@ def validate_import(workspace: str | Path, memory: Any, import_id: str) -> dict[
continue
if _run_identity(other_manifest) != identity:
continue
- other_sources = other_manifest.get("sources") if isinstance(other_manifest.get("sources"), list) else []
+ other_sources_value = other_manifest.get("sources")
+ other_sources = other_sources_value if isinstance(other_sources_value, list) else []
other_hashes = sorted(str(e.get("sha256") or "") for e in other_sources if isinstance(e, Mapping))
my_hashes = sorted(str(e.get("sha256") or "") for e in declared if isinstance(e, Mapping))
if (
@@ -862,7 +868,7 @@ def _validate_metric_provenance(
elapsed = provenance.get("elapsed_time_s")
if not isinstance(frames, int) or frames <= 0:
raise ApprovalError("windowed FPS requires positive frame_count")
- if not isinstance(elapsed, (int, float)) or float(elapsed) <= 0:
+ if not isinstance(elapsed, int | float) or float(elapsed) <= 0:
raise ApprovalError("windowed FPS requires positive elapsed_time_s")
return
raise ApprovalError(f"unknown FPS acquisition_method: {method!r}")
@@ -902,10 +908,8 @@ def materialize_import(
valid, reason = approval_valid(workspace, memory, import_id)
if not valid:
# Preserve the old approval row; mark state for audit and refuse.
- try:
+ with contextlib.suppress(OSError):
_invalidate_approval(memory, import_id, reason)
- except OSError:
- pass
raise ApprovalError(f"approval invalid: {reason}")
manifest_path, _, _ = _import_paths(root, import_id)
manifest, manifest_sha = _read_canonical_manifest(manifest_path)
diff --git a/paperforge/grounded_narrative.py b/paperforge/grounded_narrative.py
index f0c6166..02384f1 100644
--- a/paperforge/grounded_narrative.py
+++ b/paperforge/grounded_narrative.py
@@ -3,10 +3,11 @@
import hashlib
import json
import re
-from dataclasses import asdict, dataclass, field
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
NARRATIVE_SPEC_SCHEMA = "paperforge.grounded-narrative-spec/v1"
NARRATIVE_DRAFT_SCHEMA = "paperforge.grounded-narrative-draft/v1"
@@ -280,7 +281,7 @@ def validate_narrative(
if key == "model_id" and expected.lower() not in lowered:
# Model must be named correctly when the fact is model-specific.
pass
- for candidate in (f"{key} {expected}", str(expected)):
+ for _candidate in (f"{key} {expected}", str(expected)):
pass
text_identity = {
"input_size": re.search(r"(\d{3,4})\s*px", sent.text, re.I),
@@ -367,7 +368,7 @@ def build_update_from_narrative(
facts: Sequence[Mapping[str, Any]], target_spec_kwargs: Mapping[str, Any],
) -> dict[str, Any]:
"""Validate + render + hand to U2.4A. Never writes the target itself."""
- from .result_update import ResultUpdateSpec, build_proposal
+ from .result_update import ResultUpdateSpec
validation = validate_narrative(spec, paragraphs, facts=facts)
if validation["overall_status"] == "failed":
diff --git a/paperforge/metric_adapters.py b/paperforge/metric_adapters.py
index 39e8ff5..42f85e8 100644
--- a/paperforge/metric_adapters.py
+++ b/paperforge/metric_adapters.py
@@ -4,8 +4,9 @@
import hashlib
import io
import json
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass
-from typing import Any, Mapping, Protocol, Sequence
+from typing import Any, Protocol
from .metric_observation import (
AdapterContext,
@@ -27,10 +28,17 @@ class SemanticsMismatchError(UnsupportedMetricSource):
class EvidenceMetricAdapter(Protocol):
- adapter_id: str
- adapter_version: str
- supported_schema: str
- supported_media: tuple[str, ...]
+ @property
+ def adapter_id(self) -> str: ...
+
+ @property
+ def adapter_version(self) -> str: ...
+
+ @property
+ def supported_schema(self) -> str: ...
+
+ @property
+ def supported_media(self) -> tuple[str, ...]: ...
def extract(
self,
diff --git a/paperforge/metric_observation.py b/paperforge/metric_observation.py
index 2715410..ba5716f 100644
--- a/paperforge/metric_observation.py
+++ b/paperforge/metric_observation.py
@@ -1,7 +1,8 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import asdict, dataclass
-from typing import Any, Mapping
+from typing import Any
from .evidence_semantics import EvidenceSemanticsError
diff --git a/paperforge/pdf_qa.py b/paperforge/pdf_qa.py
index 7ea48f4..bc1de15 100644
--- a/paperforge/pdf_qa.py
+++ b/paperforge/pdf_qa.py
@@ -3,9 +3,10 @@
import hashlib
import json
import re
+from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
from .models import utc_now
from .path_safety import safe_mkdir
@@ -112,9 +113,10 @@ def _resolve_pdf(root: Path, rel: str) -> Path:
def preflight_pdf(data: bytes) -> dict[str, Any]:
try:
- from pypdf import PdfReader
import io as _io
+ from pypdf import PdfReader
+
reader = PdfReader(_io.BytesIO(data))
pages = list(reader.pages)
sizes = []
@@ -248,9 +250,9 @@ def __init__(self) -> None:
self.renderer_version = "unknown"
def render(self, data: bytes, page: int, dpi: int) -> dict[str, Any]:
+ import os as _os
import subprocess as _subprocess
import tempfile as _tempfile
- import os as _os
if b"RENDER_FAIL" in data:
raise PdfQaError("render failure (fixture marker)")
@@ -304,9 +306,10 @@ def render_pages(data: bytes, *, dpi: int = 200, renderer: str = "primary",
allow_synthetic: bool = False) -> list[dict[str, Any]]:
"""Render every page to real raster bytes (default) or explicit fixture mode."""
try:
- from pypdf import PdfReader as _PdfReader
import io as _io
+ from pypdf import PdfReader as _PdfReader
+
count = max(1, len(_PdfReader(_io.BytesIO(data)).pages))
except Exception:
text = data.decode("latin-1", errors="ignore")
@@ -366,9 +369,10 @@ def to_dict(self) -> dict[str, Any]:
def resolve_caption_page(data: bytes, caption: str) -> dict[str, Any]:
try:
- from pypdf import PdfReader
import io as _io
+ from pypdf import PdfReader
+
reader = PdfReader(_io.BytesIO(data))
hits = []
for index, page in enumerate(reader.pages, start=1):
@@ -380,7 +384,6 @@ def resolve_caption_page(data: bytes, caption: str) -> dict[str, Any]:
hits.append(index)
except Exception:
# Fallback: raw byte search (still deterministic, no page guessing).
- text = data.decode("latin-1", errors="ignore")
hits = [1] if caption.encode("latin-1", errors="ignore")[:12] in data else []
if not hits:
return {"status": "pending", "page": None}
@@ -410,7 +413,7 @@ def evaluate_layout_criterion(
return {"verified": False,
"reason": f"target issue {issue_id} not resolved (status={status})"}
if target_pages:
- human_by_page = {}
+ human_by_page: dict[int, list[dict[str, Any]]] = {}
for record in bundle.get("human_reviews", []) or []:
if record.get("status") in {"passed", "passed_with_warnings"} and not record.get("stale"):
human_by_page.setdefault(int(record.get("page", 0)), []).append(record)
@@ -418,10 +421,10 @@ def evaluate_layout_criterion(
if page not in human_by_page:
return {"verified": False, "reason": f"target page {page} lacks current human review"}
if required_human_pages:
- human_by_page = {int(r.get("page", 0)): r for r in bundle.get("human_reviews", []) or []
- if r.get("status") in {"passed", "passed_with_warnings"} and not r.get("stale")}
+ reviewed_required_pages = {int(r.get("page", 0)) for r in bundle.get("human_reviews", []) or []
+ if r.get("status") in {"passed", "passed_with_warnings"} and not r.get("stale")}
for page in required_human_pages:
- if page not in human_by_page:
+ if page not in reviewed_required_pages:
return {"verified": False, "reason": f"required human page {page} missing"}
return {"verified": True, "reason": "target issues resolved with current human review"}
@@ -459,7 +462,7 @@ def run_pdf_qa(
if secondary_renderer:
secondary = render_pages(data, dpi=spec.renderer_dpi, renderer=secondary_renderer,
backend=renderer_backend, allow_synthetic=allow_synthetic)
- for primary, other in zip(renders, secondary):
+ for primary, other in zip(renders, secondary, strict=False):
if primary["image_hash"] != other["image_hash"]:
parity.append({"page": primary["page"], "status": "needs_human",
"rationale": "renderer difference; neither renderer assumed correct",
@@ -482,17 +485,13 @@ def run_pdf_qa(
raise PdfQaError("human review must carry review_source=human_explicit")
if not str(record.get("reviewed_at") or "").strip():
raise PdfQaError("human review requires reviewed_at")
- if record.get("pdf_sha256") != actual_sha:
- record["stale"] = True
- elif str(record.get("render_sha256") or "") != render_hashes.get(int(record.get("page", 0)), ""):
+ if record.get("pdf_sha256") != actual_sha or str(record.get("render_sha256") or "") != render_hashes.get(int(record.get("page", 0)), ""):
record["stale"] = True
critical = [i for i in issues if i.get("severity") == "critical" and i.get("status") == "open"]
needs_human = [i for i in issues if i.get("status") == "needs_human"]
pages = {r["page"] for r in renders}
reviewed_any = {r.get("page") for r in human_records if not r.get("stale")}
- if critical:
- state = "failed"
- elif any(r.get("status") == "failed" for r in human_records):
+ if critical or any(r.get("status") == "failed" for r in human_records):
state = "failed"
elif needs_human or pages - reviewed_any:
state = "needs_human"
@@ -514,7 +513,7 @@ def run_pdf_qa(
"human_reviews": sorted(human_records, key=lambda r: int(r.get("page", 0))),
"unresolved_critical": [i["issue_id"] for i in critical],
"unresolved_warnings": [i["issue_id"] for i in issues if i.get("severity") == "warning" and i.get("status") == "open"],
- "page_coverage_complete": sorted(pages) == sorted(reviewed_any) or not pages - reviewed_any,
+ "page_coverage_complete": not pages - reviewed_any,
"layout_qa_state": state,
"spec_digest": spec.digest(),
}
@@ -569,10 +568,6 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
digest_valid = stored == hashlib.sha256(_canonical(stable)).hexdigest()
# Target PDF still matches?
target_match = True
- try:
- pdf_bytes = None
- except Exception:
- pass
historical = "valid" if digest_valid else "invalid"
# Human/render currentness sampled from stored hashes (no recomputation of renders here).
unresolved_critical = list(payload.get("unresolved_critical") or [])
diff --git a/paperforge/publication_artifacts.py b/paperforge/publication_artifacts.py
index f7bbd3a..ccc05a1 100644
--- a/paperforge/publication_artifacts.py
+++ b/paperforge/publication_artifacts.py
@@ -2,12 +2,12 @@
import hashlib
import json
-from dataclasses import asdict, dataclass, field
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
-from .models import utc_now
from .path_safety import safe_mkdir
TABLE_GENERATOR_VERSION = "paperforge.table-generator/v1"
@@ -242,7 +242,7 @@ def generate_table(
})
# Map metric columns: each ledger row carries one metric; pivot by row.
# For v1, columns are metrics and each row contributes its own metric cell.
- for table_row, ledger_row in zip(table_rows, selected):
+ for table_row, ledger_row in zip(table_rows, selected, strict=False):
metric = str(ledger_row.get("metric_name") or "")
if metric in spec.columns:
table_row["metric_values"][metric] = ledger_row.get("value_str")
@@ -296,7 +296,7 @@ def generate_table(
f"{table_id}.tex" if False else "table.tex": ("\n".join(tex_lines) + "\n").encode("utf-8"),
"table.json": (json.dumps(table_json, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"),
}
- manifest = {
+ manifest: dict[str, Any] = {
"schema": "paperforge.table-manifest/v1",
"table_id": table_id,
"table_spec_digest": spec_digest,
@@ -391,7 +391,7 @@ def generate_figure(
f"
{_tex_escape(figure_id)}"
+ "".join(sorted(svg_points)) + "\n"
)
- pdf_body = f"%PDF-1.4\n%{figure_id}\n".encode("utf-8") + svg.encode("utf-8") + b"\n%%EOF\n"
+ pdf_body = f"%PDF-1.4\n%{figure_id}\n".encode() + svg.encode("utf-8") + b"\n%%EOF\n"
contents = {
"plot_data.json": (json.dumps(plot_data, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"),
"plot_data.csv": ("series,x,y,x_row_id,y_row_id\n" + "".join(
@@ -401,7 +401,7 @@ def generate_figure(
"figure.svg": svg.encode("utf-8"),
"figure.pdf": pdf_body,
}
- manifest = {
+ manifest: dict[str, Any] = {
"schema": "paperforge.figure-manifest/v1", "figure_id": figure_id,
"figure_spec_digest": spec_digest, "ledger_id": spec.ledger_id,
"ledger_digest": ledger.get("ledger_digest"), "generator_version": FIGURE_GENERATOR_VERSION,
@@ -452,7 +452,7 @@ def generate_facts(
row = rows.get(spec.row_id)
if row is None:
raise PublicationArtifactError(f"row missing: {spec.row_id}")
- fact = {
+ fact: dict[str, Any] = {
"fact_id": spec.fact_id or f"fact-{hashlib.sha256(spec.row_id.encode()).hexdigest()[:12]}",
"kind": "metric",
"subject": str((row.get("run_identity") or {}).get("model_id") or ""),
@@ -504,7 +504,7 @@ def generate_facts(
out_dir = safe_mkdir(root / "artifacts" / "facts" / fact_id, anchor=root)
facts_payload = {"facts": [fact], "spec": spec.to_canonical(), "spec_digest": spec_digest}
contents = {"facts.json": (json.dumps(facts_payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")}
- manifest = {
+ manifest: dict[str, Any] = {
"schema": "paperforge.fact-manifest/v1", "fact_id": fact_id, "fact_spec_digest": spec_digest,
"ledger_id": spec.ledger_id, "ledger_digest": ledger.get("ledger_digest"),
"generator_version": FACT_GENERATOR_VERSION, "evidence_ids": list(fact["evidence_ids"]),
@@ -596,7 +596,7 @@ def verify_publication_bundle(
return {"consistent": False, "artifact_integrity": False, "ledger_consistency": False,
"layer_consistency": False, "publication_readiness": "not_ready",
"reason": "missing ledger_id/digest"}
- same = len(set(zip(ledgers, digests))) == 1
+ same = len(set(zip(ledgers, digests, strict=False))) == 1
if same and not layer_refs:
return {"consistent": True, "artifact_integrity": True, "ledger_consistency": True,
"layer_consistency": True, "publication_readiness": "candidate_not_ready",
diff --git a/paperforge/references.py b/paperforge/references.py
index e3fd5a3..17f5172 100644
--- a/paperforge/references.py
+++ b/paperforge/references.py
@@ -1,9 +1,10 @@
from __future__ import annotations
import hashlib
-from dataclasses import asdict, dataclass, field
+from collections.abc import Mapping, Sequence
+from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
from .path_safety import reject_symlink_components
@@ -63,7 +64,7 @@ def source_ids(self) -> tuple[str, ...]:
def _stable_source_id(path: str, sha256: str) -> str:
- digest = hashlib.sha256(f"{path}\x1f{sha256}".encode("utf-8")).hexdigest()
+ digest = hashlib.sha256(f"{path}\x1f{sha256}".encode()).hexdigest()
return f"ref_{digest[:16]}"
@@ -109,7 +110,7 @@ def _extract_pdf(
page_end: int | None = None
detail = ""
try:
- import fitz # type: ignore
+ import fitz
doc = fitz.open(stream=data, filetype="pdf")
try:
@@ -135,9 +136,10 @@ def _extract_pdf(
detail = f"pymupdf failed ({type(exc).__name__}); "
try:
- from pypdf import PdfReader # type: ignore
import io
+ from pypdf import PdfReader
+
reader = PdfReader(io.BytesIO(data))
for index, page in enumerate(reader.pages):
try:
@@ -286,7 +288,7 @@ def bundle_from_payload(
raw = payload.get("reference_paths")
if raw is None:
return ReferenceBundle()
- paths = list(raw) if isinstance(raw, (list, tuple)) else [raw]
+ paths = list(raw) if isinstance(raw, list | tuple) else [raw]
return ReferenceLoader(workspace).load(paths, budget_bytes=budget_bytes)
diff --git a/paperforge/release_eligibility.py b/paperforge/release_eligibility.py
index 156c41f..dee547e 100644
--- a/paperforge/release_eligibility.py
+++ b/paperforge/release_eligibility.py
@@ -3,13 +3,18 @@
import hashlib
import json
import re
-from contextlib import contextmanager
+from collections.abc import Mapping, Sequence
+from contextlib import contextmanager, suppress
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
+from .immutable_artifacts import (
+ register_immutable,
+ verify_registered_bundle,
+ write_immutable_bundle,
+)
from .models import utc_now
-from .immutable_artifacts import register_immutable, verify_registered_bundle, write_immutable_bundle
from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
REPORT_SCHEMA = "paperforge.release-eligibility-report/v1"
@@ -254,10 +259,8 @@ def _snapshot(root: Path, memory: Any, target: ReleaseTarget,
inputs: Mapping[str, Any]) -> dict[str, Any]:
paths = {target.manuscript_path, target.final_pdf_path, target.build_manifest_path,
*target.bibliography_hashes}
- try:
+ with suppress(OSError, ValueError, TypeError, ReleaseEligibilityError):
paths.update(_json_file(root, target.build_manifest_path).get("source_hashes", {}))
- except (OSError, ValueError, TypeError, ReleaseEligibilityError):
- pass
for key, folder, name in (("ledger_ids", "ledgers", "ledger.json"),
("review_ids", "reviews", "review.json"),
("pdf_bundle_ids", "pdf_qa", "qa.json")):
@@ -443,7 +446,7 @@ def evaluate_release(
remediation="materialize required evidence"))
else:
blocked = [str(e.get("evidence_id")) for e in evidence_refs
- if str((e.get("environment_role") or "")) != "scientific"
+ if str(e.get("environment_role") or "") != "scientific"
or str(e.get("measurement_kind") or "") not in {"measured", "simulated", "remapped", "derived"}]
stale = [str(e.get("evidence_id")) for e in evidence_refs if e.get("current") is False]
if blocked:
diff --git a/paperforge/result_ledger.py b/paperforge/result_ledger.py
index 088ce86..2c411e9 100644
--- a/paperforge/result_ledger.py
+++ b/paperforge/result_ledger.py
@@ -1,13 +1,13 @@
from __future__ import annotations
+import contextlib
import hashlib
import json
-from dataclasses import asdict, dataclass, field
-from decimal import Decimal, InvalidOperation
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, field
+from decimal import ROUND_HALF_EVEN, Context, Decimal, InvalidOperation, localcontext
from pathlib import Path
-from typing import Any, Mapping, Sequence
-
-from decimal import ROUND_HALF_EVEN, Context, localcontext
+from typing import Any
from .evidence_semantics import EvidenceSemantics
from .external_import import RUN_IDENTITY_SCHEMA, ScientificRunIdentity
@@ -334,8 +334,8 @@ def _apply_unit_conversions(
try:
factor = Decimal(str(rule.get("factor", "1")))
value = Decimal(str(snap["value_str"])) * factor if snap.get("value_str") else None
- except (InvalidOperation, TypeError):
- raise LedgerError(f"invalid conversion factor: {rule}")
+ except (InvalidOperation, TypeError) as exc:
+ raise LedgerError(f"invalid conversion factor: {rule}") from exc
converted = {
**snap,
"value_str": format(value, "f") if value is not None else None,
@@ -372,8 +372,8 @@ def _aggregate(
for snap in relevant:
identity = dict(snap.get("run_identity") or {})
key_parts = [spec.metric]
- for field in sorted(set(spec.group_by)):
- key_parts.append(f"{field}={identity.get(field, '')}")
+ for dimension in sorted(set(spec.group_by)):
+ key_parts.append(f"{dimension}={identity.get(dimension, '')}")
key = "\x1f".join(key_parts)
groups.setdefault(key, []).append(snap)
rows: list[dict[str, Any]] = []
@@ -414,7 +414,7 @@ def _aggregate(
raise LedgerError(f"unknown reducer: {spec.reducer}")
first = members[0]
row_id = hashlib.sha256(
- f"{spec.metric}\x1f{key}\x1f{spec.reducer}".encode("utf-8")
+ f"{spec.metric}\x1f{key}\x1f{spec.reducer}".encode()
).hexdigest()[:16]
rows.append(
{
@@ -593,7 +593,6 @@ def _register_ledger_artifacts(
snapshots = list(payload.get("snapshots") or [])
ledger_path = root / ".paperforge" / "ledgers" / ledger_id / "ledger.json"
- manifest_path = root / ".paperforge" / "ledgers" / ledger_id / "manifest.json"
file_sha = hashlib.sha256(ledger_path.read_bytes()).hexdigest() if ledger_path.is_file() else ""
metadata = {
"ledger_id": ledger_id,
@@ -638,10 +637,8 @@ def _unregister_ledger_artifacts(root: Path, memory: Any, ledger_id: str) -> Non
f".paperforge/ledgers/{ledger_id}/ledger.json",
f".paperforge/ledgers/{ledger_id}/manifest.json",
):
- try:
+ with contextlib.suppress(OSError):
db.execute("DELETE FROM artifacts WHERE path=?", (rel,))
- except OSError:
- pass
def _ledger_paths(root: Path, ledger_id: str) -> tuple[Path, Path, Path]:
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index ff98029..0472164 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -4,10 +4,10 @@
import hashlib
import json
import re
-import uuid
-from dataclasses import asdict, dataclass, field
+from collections.abc import Mapping, Sequence
+from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
from .models import utc_now
from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
@@ -16,7 +16,6 @@
PROTECTED_START,
ProtectedBlockViolation,
extract_protected_blocks,
- protected_blocks_sha256,
)
UPDATE_SPEC_SCHEMA = "paperforge.result-update-spec/v1"
@@ -307,7 +306,6 @@ def _verify_ledger_bindings(workspace: str | Path, memory: Any, bindings: Sequen
pass
# Compare digest when the binding declares one.
try:
- from .result_ledger import _ledger_paths
import json as _json
ledger_payload = _json.loads((root / ".paperforge" / "ledgers" / ledger_id / "ledger.json").read_bytes().decode())
@@ -438,10 +436,9 @@ def build_proposal(
"canonical": str(fact_values[matched].get("value")),
"unit": str(fact_values[matched].get("unit") or cand["unit"])})
elif cand["kind"] == "protocol":
- key = (re.sub(r"\s+", " ", cand["text"]).strip().lower(), cand["unit"].strip().lower())
# Match by numeric value + provenance-bearing allowlist entry.
- matched = None
- for (name, unit), entry in protocol_allow.items():
+ matched_protocol = None
+ for (_name, unit), entry in protocol_allow.items():
try:
from decimal import Decimal
@@ -450,15 +447,15 @@ def build_proposal(
):
if not str(entry.get("source") or "").strip():
continue
- matched = entry
+ matched_protocol = entry
break
except Exception:
continue
- if matched is None:
+ if matched_protocol is None:
raise ResultUpdateValidationError(
f"UNBOUND_PROTOCOL_VALUE: {cand['text']!r} needs provenance-bearing protocol binding"
)
- protocol_bindings.append({"occurrence": cand["text"], "binding": matched})
+ protocol_bindings.append({"occurrence": cand["text"], "binding": matched_protocol})
# Citations.
for key in _extract_citations(proposed_block):
if key not in set(spec.allowed_citation_keys):
@@ -538,7 +535,7 @@ def approve_proposal(
spec_data = json.loads((base / "spec.json").read_text(encoding="utf-8"))
_verify_ledger_bindings(workspace, memory, proposal.get("ledger_bindings") or [])
_verify_proposal_artifacts(workspace, memory, proposal)
- spec = ResultUpdateSpec(
+ _spec = ResultUpdateSpec(
target_path=spec_data["target_path"],
target_source_sha256=proposal["target_source_sha256"],
protected_block_index=0,
diff --git a/paperforge/reviewer_matrix.py b/paperforge/reviewer_matrix.py
index 1341c52..89dedde 100644
--- a/paperforge/reviewer_matrix.py
+++ b/paperforge/reviewer_matrix.py
@@ -2,12 +2,12 @@
import hashlib
import json
+from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Any, Mapping, Sequence
+from typing import Any
from .models import utc_now
-from .path_safety import safe_mkdir
MATRIX_SCHEMA = "paperforge.reviewer-matrix/v1"
ACTION_TYPES = (
@@ -178,8 +178,6 @@ class ReviewerResponseRecord:
response_facts: tuple[Mapping[str, Any], ...] = ()
def __post_init__(self) -> None:
- forbidden = ("we have measured", "we have validated")
- lowered = " ".join(str(f) for f in self.response_facts).lower()
object.__setattr__(self, "actions_completed", tuple(self.actions_completed or ()))
object.__setattr__(self, "evidence_ids", tuple(self.evidence_ids or ()))
object.__setattr__(self, "revision_locations", tuple(self.revision_locations or ()))
@@ -257,7 +255,7 @@ def derive_action_status(
required = [c for c in criteria if c.required]
# Hardware/fixture guards: binding kinds must match criterion types.
for criterion in required:
- params = dict(criterion.params or {})
+ _params = dict(criterion.params or {})
if criterion.criterion_type == "hardware_measurement":
kinds = {b.artifact_kind for b in bindings if b.action_id == action.action_id}
if "imported_evidence" not in kinds and "human_verification" not in kinds:
@@ -403,7 +401,7 @@ def verify_review_matrix(workspace: str | Path, memory: Any, matrix_id: str) ->
stale.append(str(binding.get("binding_id")))
# Criteria completeness: every required criterion referenced by >=1 action.
required_ids = {str(c.get("criterion_id")) for c in payload.get("criteria", []) if c.get("required")}
- referenced = set()
+ referenced: set[str] = set()
for action in payload.get("actions", []) or []:
referenced.update(str(c) for c in action.get("acceptance_criteria") or [])
complete = required_ids.issubset(referenced)
diff --git a/paperforge/run_status.py b/paperforge/run_status.py
index 265f895..559c929 100644
--- a/paperforge/run_status.py
+++ b/paperforge/run_status.py
@@ -1,7 +1,8 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import asdict, dataclass, field
-from typing import Any, Mapping
+from typing import Any
from .models import WorkflowStatus
diff --git a/paperforge/scientific_review.py b/paperforge/scientific_review.py
index 74f181b..7f1a982 100644
--- a/paperforge/scientific_review.py
+++ b/paperforge/scientific_review.py
@@ -3,8 +3,10 @@
import hashlib
import json
import re
+from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass, field
-from typing import Any, Mapping, Sequence
+from pathlib import Path
+from typing import Any
CLAIM_TYPES = (
"descriptive_metric", "comparison", "ranking", "statistical_superiority",
@@ -60,7 +62,8 @@ def from_narrative_sentence(cls, sentence: Mapping[str, Any], *, claim_type: str
roles_to_type = {"metric_report": "descriptive_metric", "comparison": "comparison",
"protocol_statement": "protocol_statement", "limitation": "limitation",
"provenance_statement": "descriptive_metric", "transition": "descriptive_metric"}
- inferred = str(sentence.get("claim_types")[0]) if sentence.get("claim_types") else roles_to_type.get(str(sentence.get("role") or ""), claim_type)
+ claim_types = sentence.get("claim_types")
+ inferred = str(claim_types[0]) if claim_types else roles_to_type.get(str(sentence.get("role") or ""), claim_type)
if inferred not in CLAIM_TYPES:
inferred = "descriptive_metric"
# Text rules only fill gaps; structured role/claim_types win.
@@ -238,7 +241,7 @@ def check_calibration_overlap(claim: ScientificClaim, facts: Mapping[str, Mappin
roles = dict(roles or {})
def _has(role_value: Any, target: str) -> bool:
- if isinstance(role_value, (list, tuple, set)):
+ if isinstance(role_value, list | tuple | set):
return target in role_value
return role_value == target
@@ -416,7 +419,6 @@ def check_statistical_binding(
facts_used=tuple(claim.fact_ids))
claim_evidence = {str(fid) for fid in claim.fact_ids if str(fid).strip()}
for entry in statistical_evidence or []:
- evidence = entry if isinstance(entry, StatisticalEvidence) else None
data = entry.to_dict() if isinstance(entry, StatisticalEvidence) else dict(entry)
# Evidence set must overlap the claim's facts; unrelated analyses never bind.
evidence_set = {str(eid) for eid in data.get("evidence_ids") or []}
diff --git a/paperforge/writing_patch.py b/paperforge/writing_patch.py
index 4937347..908011b 100644
--- a/paperforge/writing_patch.py
+++ b/paperforge/writing_patch.py
@@ -2,9 +2,10 @@
import hashlib
import re
+from collections.abc import Callable, Mapping
from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any, Callable, Mapping
+from typing import Any
from engine.secret_redaction import contains_secret
@@ -81,9 +82,7 @@ def _looks_truncated(text: str) -> bool:
if begins != ends:
return True
# Model fence leftovers or ellipsis markers are not valid patches.
- if stripped.endswith("```"):
- return True
- return False
+ return bool(stripped.endswith("```"))
def _resolve_target(workspace: Path, raw: str | Path) -> tuple[Path, str]:
diff --git a/tests/test_compute_backends.py b/tests/test_compute_backends.py
index d0ed0c1..cca9d5e 100644
--- a/tests/test_compute_backends.py
+++ b/tests/test_compute_backends.py
@@ -917,6 +917,7 @@ def test_local_backend_recovers_completed_state_without_secret_environment(
submitted = backend.submit(
JobSpec(
name="redacted-and-durable",
+ workdir=str(tmp_path),
command=[
sys.executable,
"-c",
@@ -958,6 +959,7 @@ def test_local_backend_recovers_live_job_after_backend_restart(
).submit(
JobSpec(
name="restart-live",
+ workdir=str(tmp_path),
command=[
sys.executable,
"-c",
@@ -1000,6 +1002,7 @@ def test_local_backend_does_not_persist_or_inherit_host_credentials(
submitted = backend.submit(
JobSpec(
name="clean-environment",
+ workdir=str(tmp_path),
command=[
sys.executable,
"-c",
diff --git a/tests/test_d1_page_count.py b/tests/test_d1_page_count.py
index 598ac31..f4f059a 100644
--- a/tests/test_d1_page_count.py
+++ b/tests/test_d1_page_count.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import re
-from pathlib import Path
from paperforge.pdf_qa import preflight_pdf, render_pages
@@ -9,7 +8,7 @@
def _pages(n: int) -> bytes:
from tests.test_u3b2_pdf_qa import _build_pdf, _page
- return _build_pdf([_page([(12, "p%d" % i)]) for i in range(n)])
+ return _build_pdf([_page([(12, f"p{i}")]) for i in range(n)])
def test_compressed_multipage_count() -> None: # 1
diff --git a/tests/test_u22_finalization.py b/tests/test_u22_finalization.py
index 55c33a9..109117f 100644
--- a/tests/test_u22_finalization.py
+++ b/tests/test_u22_finalization.py
@@ -66,7 +66,7 @@ def test_validation_digest_stable_and_idempotent(tmp_path: Path) -> None:
assert "validation_digest" in first
assert first["validation_digest"] == second["validation_digest"]
# Digest payload excludes volatile timestamps and itself.
- assert "created_at" not in first or True # file keeps audit timestamps
+ assert first.get("validated_at") # file keeps audit timestamps
from paperforge.external_import import _stable_validation_payload, _validation_digest
stable = _stable_validation_payload(first)
@@ -312,7 +312,7 @@ def test_subprocess_reopen_sees_committed_state(tmp_path: Path) -> None:
service, record = _stage_basic(tmp_path, name="sub.json", content='{"v": 1}\n')
_approve_all_human(tmp_path, service, record)
out = materialize_import(tmp_path, service.memory, record.import_id)
- code = (
+ _code = (
"import json,sys; from paperforge.api import PaperForgeService; "
f"s=PaperForgeService({str(tmp_path)!r}); "
f"print(json.dumps(s.memory.get_evidence_count() if hasattr(s.memory,'get_evidence_count') else 1))"
diff --git a/tests/test_u22_import_transaction.py b/tests/test_u22_import_transaction.py
index c67a6b8..06fd525 100644
--- a/tests/test_u22_import_transaction.py
+++ b/tests/test_u22_import_transaction.py
@@ -1,7 +1,7 @@
from __future__ import annotations
-import hashlib
import json
+from contextlib import contextmanager
from pathlib import Path
import pytest
@@ -9,6 +9,7 @@
from paperforge.api import PaperForgeService
from paperforge.evidence_semantics import EvidenceSemantics
from paperforge.external_import import (
+ ApprovalError,
ConflictError,
approval_valid,
approve_import,
@@ -147,8 +148,8 @@ def test_needs_human_ack_recorded(tmp_path: Path) -> None:
def test_approval_binds_both_hashes(tmp_path: Path) -> None:
service, record = _stage(tmp_path)
- report = validate_import(tmp_path, service.memory, record.import_id)
- out = _approve_needs_human(tmp_path, service, record) or approve_import
+ validate_import(tmp_path, service.memory, record.import_id)
+ _approve_needs_human(tmp_path, service, record)
# Re-fetch binding via approval_valid path: tamper validation.json
vpath = tmp_path / ".paperforge" / "imports" / record.import_id / "validation.json"
data = json.loads(vpath.read_text(encoding="utf-8"))
@@ -190,14 +191,11 @@ def test_unapproved_has_no_evidence(tmp_path: Path) -> None:
service, record = _stage(tmp_path)
validate_import(tmp_path, service.memory, record.import_id)
with memory_evidence_count(service) as count_before:
- with pytest.raises(Exception):
+ with pytest.raises(ApprovalError):
materialize_import(tmp_path, service.memory, record.import_id)
assert memory_evidence_count_now(service) == count_before
-from contextlib import contextmanager
-
-
@contextmanager
def memory_evidence_count(service):
with service.memory.connect() as db:
@@ -260,7 +258,7 @@ def test_transcribed_cannot_become_measured(tmp_path: Path) -> None:
source_files=["table.txt"],
)
validate_import(tmp_path, service.memory, record.import_id)
- with pytest.raises(Exception):
+ with pytest.raises(ApprovalError):
# Transcribed is not admissible; materialize refuses.
report = validate_import(tmp_path, service.memory, record.import_id)
ack = [c["check_id"] for c in report["checks"] if c["status"] == "needs_human"]
@@ -396,7 +394,7 @@ def test_old_approval_preserved_but_invalid(tmp_path: Path) -> None:
"SELECT COUNT(*) AS c FROM import_approvals WHERE import_id=?", (record.import_id,)
).fetchone()["c"]
assert before >= 1
- with pytest.raises(Exception):
+ with pytest.raises(ApprovalError):
materialize_import(tmp_path, service.memory, record.import_id)
with service.memory.connect() as db:
after = db.execute(
diff --git a/tests/test_u23_finalization.py b/tests/test_u23_finalization.py
index 60721f5..526767f 100644
--- a/tests/test_u23_finalization.py
+++ b/tests/test_u23_finalization.py
@@ -114,7 +114,7 @@ def test_canonical_numeric_identity(tmp_path: Path) -> None:
snap = ledger["snapshots"][0]
assert snap["value_str"] == "46.5"
assert snap["source_lexical_value"] == "46.500"
- service2 = _service(tmp_path.parent / (tmp_path.name + "-b"))
+ _service(tmp_path.parent / (tmp_path.name + "-b"))
# Numerically identical lexical forms share canonical digest path.
from paperforge.result_ledger import _decimal_canonical
diff --git a/tests/test_u23_ledger_core.py b/tests/test_u23_ledger_core.py
index 639771f..4c7a7cc 100644
--- a/tests/test_u23_ledger_core.py
+++ b/tests/test_u23_ledger_core.py
@@ -9,7 +9,6 @@
from paperforge.evidence_semantics import EvidenceSemantics
from paperforge.external_import import (
approve_import,
- materialize_import,
stage_import,
validate_import,
)
@@ -294,8 +293,6 @@ def test_verify_file_tamper_and_stale(tmp_path: Path) -> None:
ack = [c["check_id"] for c in report["checks"] if c["status"] == "needs_human"]
approve_import(tmp_path, service.memory, record.import_id, approver="local-owner", acknowledged_checks=ack, rationale="ok")
# Metric evidence linked to the import for currentness tracking.
- with service.memory.connect() as db:
- mat_row = None
from paperforge.external_import import materialize_import as _mat
out = _mat(tmp_path, service.memory, record.import_id)
diff --git a/tests/test_u23b_artifacts.py b/tests/test_u23b_artifacts.py
index 1eda60c..cf11c60 100644
--- a/tests/test_u23b_artifacts.py
+++ b/tests/test_u23b_artifacts.py
@@ -11,7 +11,6 @@
MetricExtractorRegistry,
UnsupportedMetricSource,
)
-from paperforge.metric_observation import MetricObservation
from paperforge.publication_artifacts import (
FactSummarySpec,
FigureSpec,
diff --git a/tests/test_u24a_finalization.py b/tests/test_u24a_finalization.py
index a65e7f2..7165a37 100644
--- a/tests/test_u24a_finalization.py
+++ b/tests/test_u24a_finalization.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import hashlib
-import json
from pathlib import Path
import pytest
@@ -108,7 +107,7 @@ def test_structural_numbers_ignored(tmp_path: Path) -> None: # F2-1,2
def test_protocol_changes_require_binding(tmp_path: Path) -> None: # F2-3,4,5
- for old_proto, new_proto in (("300 epochs", "500 epochs"), ("3 seeds", "5 seeds"), ("896 px", "1024 px")):
+ for old_proto, _new_proto in (("300 epochs", "500 epochs"), ("3 seeds", "5 seeds"), ("896 px", "1024 px")):
service = PaperForgeService(tmp_path / f"p-{old_proto.split()[0]}") if False else None
service = PaperForgeService(tmp_path)
block = "Trained 300 epochs on 896 px with 3 seeds. Old result 20.0 ms."
diff --git a/tests/test_u24a_result_update.py b/tests/test_u24a_result_update.py
index 4e369f7..99f9d1c 100644
--- a/tests/test_u24a_result_update.py
+++ b/tests/test_u24a_result_update.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import hashlib
-import json
from pathlib import Path
import pytest
diff --git a/tests/test_u24b_narrative.py b/tests/test_u24b_narrative.py
index eae6cc1..ef45840 100644
--- a/tests/test_u24b_narrative.py
+++ b/tests/test_u24b_narrative.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import json
from pathlib import Path
import pytest
@@ -15,7 +14,6 @@
validate_narrative,
)
from paperforge.provider import GenerationResult
-from paperforge.result_update import ResultUpdateSpec, build_proposal
def _spec(**overrides):
@@ -202,7 +200,7 @@ def test_renderer_preserves_numbers_and_citations() -> None: # 26,27
def test_no_direct_file_write_and_u24a_gates(tmp_path: Path) -> None: # 28,29,30
- service = PaperForgeService(tmp_path)
+ PaperForgeService(tmp_path)
tex = tmp_path / "paper.tex"
tex.write_text("\\documentclass{article}\n\\begin{document}\nIntro.\n% PAPERFORGE-PROTECTED-EXPERIMENT-START\nOld 0.8511.\n% PAPERFORGE-PROTECTED-EXPERIMENT-END\n\\end{document}\n", encoding="utf-8")
sents = [[_sent("Control 0.8511.")]]
@@ -216,7 +214,6 @@ def test_narrative_pass_not_approved_and_bytes_gate(tmp_path: Path) -> None: #
def test_narrative_to_u24a_integration(tmp_path: Path) -> None: # 29 (integration)
- from paperforge.grounded_narrative import build_update_from_narrative
service = PaperForgeService(tmp_path)
sents = [[_sent("Control 0.8511.")]]
diff --git a/tests/test_u3a_review_core.py b/tests/test_u3a_review_core.py
index 1086859..1c1ac0d 100644
--- a/tests/test_u3a_review_core.py
+++ b/tests/test_u3a_review_core.py
@@ -136,7 +136,6 @@ def test_assumptions_disclosed() -> None: # 21,22
def test_fixture_blocked_and_no_mutation() -> None: # 23,24
- from paperforge.scientific_review import review_claim as rc
facts = {"f": {"measurement_kind": "measured"}}
before = dict(facts["f"])
@@ -165,7 +164,6 @@ def test_no_pcb_hardcoding() -> None: # 28
def test_narrative_integration_and_regression() -> None: # 29,30
- from paperforge.grounded_narrative import NarrativeSentence
sent = {"sentence_id": "s", "text": "Control 0.8511.", "role": "metric_report", "fact_ids": ["f1"]}
claim = __import__("paperforge.scientific_review", fromlist=["ScientificClaim"]).ScientificClaim.from_narrative_sentence(sent)
diff --git a/tests/test_u3b1_matrix.py b/tests/test_u3b1_matrix.py
index 0c8a8ac..091b56e 100644
--- a/tests/test_u3b1_matrix.py
+++ b/tests/test_u3b1_matrix.py
@@ -3,8 +3,6 @@
import hashlib
from pathlib import Path
-import pytest
-
from paperforge.api import PaperForgeService
from paperforge.reviewer_matrix import (
AcceptanceCriterion,
@@ -127,7 +125,6 @@ def test_response_no_early_claim() -> None: # 18
def test_hardware_type_match(tmp_path: Path) -> None: # 19
service = _service(tmp_path)
- comment = _comment()
action = _action()
criterion = AcceptanceCriterion(criterion_id="c1", criterion_type="hardware_measurement")
binding = EvidenceBinding(binding_id="b1", action_id="a1", artifact_kind="imported_evidence",
diff --git a/tests/test_u3b2_finalization.py b/tests/test_u3b2_finalization.py
index 1013e9d..fd3b72e 100644
--- a/tests/test_u3b2_finalization.py
+++ b/tests/test_u3b2_finalization.py
@@ -28,7 +28,7 @@ def _pdf(pages) -> bytes:
def test_real_raster_hash_from_image_bytes(tmp_path: Path) -> None: # F1
- service = _service(tmp_path)
+ _service(tmp_path)
data = _pdf([[(12, "Hello")]])
(tmp_path / "a.pdf").write_bytes(data)
backend = PopplerRenderer()
@@ -42,10 +42,9 @@ def test_real_raster_hash_from_image_bytes(tmp_path: Path) -> None: # F1
def test_synthetic_blocked_for_production(tmp_path: Path) -> None: # F1 gate
- service = _service(tmp_path)
+ _service(tmp_path)
data = _pdf([[(12, "Hello")]])
(tmp_path / "a.pdf").write_bytes(data)
- sha = hashlib.sha256(data).hexdigest()
with pytest.raises(Exception, match="REAL_RENDERER_UNAVAILABLE"):
render_pages(data, backend=SyntheticContentHashRenderer(), allow_synthetic=False)
# Explicit fixture mode works but is marked fixture.
diff --git a/tests/test_u3b2_pdf_qa.py b/tests/test_u3b2_pdf_qa.py
index 5ae0359..53faf8d 100644
--- a/tests/test_u3b2_pdf_qa.py
+++ b/tests/test_u3b2_pdf_qa.py
@@ -74,7 +74,7 @@ def _build_pdf(pages: list[dict]) -> bytes:
xref_offset = len(header) + len(body)
xref = ("xref\n0 " + str(num_objects + 1) + "\n0000000000 65535 f \n").encode()
for obj_id in range(1, num_objects + 1):
- xref += ("%010d 00000 n \n" % offsets.get(obj_id, 0)).encode()
+ xref += f"{offsets.get(obj_id, 0):010d} 00000 n \n".encode()
trailer = ("trailer\n<< /Size " + str(num_objects + 1) + " /Root 1 0 R >>\nstartxref\n"
+ str(xref_offset) + "\n%%EOF\n").encode()
return header + body + xref + trailer
@@ -179,7 +179,7 @@ def test_render_every_page_and_failure(tmp_path: Path) -> None: # 14,15
def test_render_stale_and_parity(tmp_path: Path) -> None: # 16,17
from paperforge.pdf_qa import SyntheticContentHashRenderer
- service = _service(tmp_path)
+ _service(tmp_path)
rel = _write(tmp_path, "a.pdf", _build_pdf([_page([(12, "Hello")])]))
sha = hashlib.sha256((tmp_path / rel).read_bytes()).hexdigest()
data = (tmp_path / rel).read_bytes()
diff --git a/tests/test_u4b_finalization.py b/tests/test_u4b_finalization.py
index eb5f433..1ea2fec 100644
--- a/tests/test_u4b_finalization.py
+++ b/tests/test_u4b_finalization.py
@@ -191,7 +191,11 @@ def test_engineering_and_environment_pass_then_log_change_stales(tmp_path):
def matrix_fixture(root, service, target, *, bind=True, optional=False):
from paperforge.reviewer_matrix import (
- AcceptanceCriterion, EvidenceBinding, ReviewerAction, ReviewerComment, freeze_review_matrix,
+ AcceptanceCriterion,
+ EvidenceBinding,
+ ReviewerAction,
+ ReviewerComment,
+ freeze_review_matrix,
)
target_data = {k: v for k, v in target.to_dict().items() if k != "created_at"}
@@ -296,7 +300,12 @@ def test_domain_evidence_change_stales_report(tmp_path):
def test_default_policy_all_gates_then_external_source_change(tmp_path):
from paperforge.evidence_semantics import EvidenceSemantics
- from paperforge.external_import import approve_import, materialize_import, stage_import, validate_import
+ from paperforge.external_import import (
+ approve_import,
+ materialize_import,
+ stage_import,
+ validate_import,
+ )
from paperforge.release_eligibility import freeze_assessment
from paperforge.scientific_review import ScientificClaim, freeze_review, review_claim
@@ -361,7 +370,11 @@ def test_unified_release_summary_is_only_a_projection():
@pytest.mark.parametrize("criterion_type", ["layout", "manuscript_clarification", "unknown_future_criterion"])
def test_measurement_cannot_satisfy_unrelated_reviewer_criterion(tmp_path, criterion_type):
from paperforge.reviewer_matrix import (
- AcceptanceCriterion, EvidenceBinding, ReviewerAction, ReviewerComment, freeze_review_matrix,
+ AcceptanceCriterion,
+ EvidenceBinding,
+ ReviewerAction,
+ ReviewerComment,
+ freeze_review_matrix,
)
service, target, policy = setup_target(tmp_path)
diff --git a/tests/test_u4b_release.py b/tests/test_u4b_release.py
index 9110bb8..91fe3ec 100644
--- a/tests/test_u4b_release.py
+++ b/tests/test_u4b_release.py
@@ -4,12 +4,9 @@
import json
from pathlib import Path
-import pytest
-
from paperforge.api import PaperForgeService
from paperforge.release_eligibility import (
EngineeringCheckResult,
- ReleaseEligibilityError,
ReleasePolicy,
ReleaseTarget,
assessment_current,
diff --git a/tests/test_u4c_artifact_recovery.py b/tests/test_u4c_artifact_recovery.py
index 763c6be..5dbe394 100644
--- a/tests/test_u4c_artifact_recovery.py
+++ b/tests/test_u4c_artifact_recovery.py
@@ -3,11 +3,11 @@
import json
import pytest
+from test_u4b_finalization import setup_target
from paperforge.api import PaperForgeService
from paperforge.artifacts import ArtifactIntegrityError, ArtifactStore
from paperforge.immutable_artifacts import verify_registered_bundle
-from test_u4b_finalization import setup_target
def bundle_factory(root, kind):
@@ -21,7 +21,12 @@ def bundle_factory(root, kind):
query = ResultLedgerQuery(purpose="scientific", metric_names=["latency_ms"], evidence_ids=(eid,))
return service, lambda: freeze_ledger(root, service.memory, query), "ledger_id", "ledgers", "ledger.json", lambda i: verify_ledger(root, service.memory, i)["eligible_as_release_input"]
if kind == "review":
- from paperforge.scientific_review import ScientificClaim, freeze_review, review_claim, verify_scientific_review
+ from paperforge.scientific_review import (
+ ScientificClaim,
+ freeze_review,
+ review_claim,
+ verify_scientific_review,
+ )
claim = ScientificClaim("c", "descriptive", "descriptive_metric", fact_ids=("f",))
return service, lambda: freeze_review(root, service.memory, claims=[claim], results=review_claim(claim, facts={"f": {}})), "review_id", "reviews", "review.json", lambda i: verify_scientific_review(root, service.memory, i)["currently_valid_as_review_input"]
@@ -30,13 +35,23 @@ def bundle_factory(root, kind):
return service, lambda: freeze_review_matrix(root, service.memory, comments=[], actions=[], criteria=[]), "matrix_id", "review_matrix", "matrix.json", lambda i: verify_review_matrix(root, service.memory, i)["currently_valid"]
if kind == "pdf":
- from paperforge.pdf_qa import PDFQASpec, SyntheticContentHashRenderer, run_pdf_qa, verify_pdf_qa
from test_u3b2_pdf_qa import _build_pdf
+ from paperforge.pdf_qa import (
+ PDFQASpec,
+ SyntheticContentHashRenderer,
+ run_pdf_qa,
+ verify_pdf_qa,
+ )
+
(root / "fixture.pdf").write_bytes(_build_pdf([{"texts": [(12, "Fixture")]}]))
spec = PDFQASpec(target_pdf_path="fixture.pdf")
return service, lambda: run_pdf_qa(root, service.memory, spec, renderer_backend=SyntheticContentHashRenderer(), allow_synthetic=True), "bundle_id", "pdf_qa", "qa.json", lambda i: verify_pdf_qa(root, service.memory, i)["currently_valid"]
- from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+ from paperforge.release_eligibility import (
+ assessment_current,
+ evaluate_release,
+ freeze_assessment,
+ )
service, target, policy = setup_target(root)
report = evaluate_release(root, service.memory, target, policy)
diff --git a/tests/test_u4c_reopen_and_stress.py b/tests/test_u4c_reopen_and_stress.py
index f513cf3..5cdea82 100644
--- a/tests/test_u4c_reopen_and_stress.py
+++ b/tests/test_u4c_reopen_and_stress.py
@@ -4,13 +4,13 @@
from enum import Enum
import pytest
+from test_u4c_result_recovery import prepared, set_state
+from test_u22_import_transaction import _approve_needs_human, _stage
from paperforge.api import PaperForgeService
from paperforge.external_import import ApprovalError, materialize_import, reconcile_imports
from paperforge.models import WorkflowStatus
from paperforge.result_update import reconcile_result_updates
-from test_u22_import_transaction import _approve_needs_human, _stage
-from test_u4c_result_recovery import prepared, set_state
class RecoveryOutcome(str, Enum):
@@ -141,9 +141,8 @@ def test_sqlite_durability_audit_and_rollback(tmp_path):
assert db.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal"
assert db.execute("PRAGMA synchronous").fetchone()[0] == 2 # FULL on this configured connection
assert db.execute("PRAGMA foreign_keys").fetchone()[0] == 1
- with pytest.raises(RuntimeError, match="rollback"):
- with service.memory.connect() as db:
- db.execute("INSERT INTO metadata (key,value) VALUES ('u4c-rollback','uncommitted')")
- raise RuntimeError("rollback")
+ with pytest.raises(RuntimeError, match="rollback"), service.memory.connect() as db:
+ db.execute("INSERT INTO metadata (key,value) VALUES ('u4c-rollback','uncommitted')")
+ raise RuntimeError("rollback")
with PaperForgeService(tmp_path).memory.connect() as db:
assert db.execute("SELECT value FROM metadata WHERE key='u4c-rollback'").fetchone() is None
diff --git a/tests/test_u4c_result_recovery.py b/tests/test_u4c_result_recovery.py
index 8000d27..87c08a0 100644
--- a/tests/test_u4c_result_recovery.py
+++ b/tests/test_u4c_result_recovery.py
@@ -5,10 +5,15 @@
from pathlib import Path
import pytest
+from test_u24a_finalization import _fact, _spec_with_table
from paperforge.api import PaperForgeService
-from paperforge.result_update import apply_proposal, approve_proposal, build_proposal, reconcile_result_updates
-from test_u24a_finalization import _fact, _spec_with_table
+from paperforge.result_update import (
+ apply_proposal,
+ approve_proposal,
+ build_proposal,
+ reconcile_result_updates,
+)
def prepared(root: Path):
diff --git a/tests/test_u4c_subprocess.py b/tests/test_u4c_subprocess.py
index e2c2845..b79320c 100644
--- a/tests/test_u4c_subprocess.py
+++ b/tests/test_u4c_subprocess.py
@@ -8,13 +8,13 @@
from pathlib import Path
import pytest
+from test_u4b_finalization import setup_target
+from test_u4c_result_recovery import prepared
+from test_u22_import_transaction import _approve_needs_human, _stage
from paperforge.api import PaperForgeService
from paperforge.external_import import materialize_import, reconcile_imports
from paperforge.result_update import reconcile_result_updates
-from test_u22_import_transaction import _approve_needs_human, _stage
-from test_u4b_finalization import setup_target
-from test_u4c_result_recovery import prepared
def kill_at_checkpoint(root: Path, mode: str, identity: str = "unused") -> None:
@@ -81,7 +81,11 @@ def test_result_update_real_sigkill_reopen(tmp_path, mode, expected):
def test_evaluator_real_sigkill_has_no_domain_mutation(tmp_path):
- from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+ from paperforge.release_eligibility import (
+ assessment_current,
+ evaluate_release,
+ freeze_assessment,
+ )
service, target, policy = setup_target(tmp_path)
(tmp_path / "test-target.json").write_text(json.dumps(target.to_dict()))
@@ -101,7 +105,11 @@ def test_evaluator_real_sigkill_has_no_domain_mutation(tmp_path):
def test_release_freeze_real_sigkill_before_registry(tmp_path):
- from paperforge.release_eligibility import assessment_current, evaluate_release, freeze_assessment
+ from paperforge.release_eligibility import (
+ assessment_current,
+ evaluate_release,
+ freeze_assessment,
+ )
service, target, policy = setup_target(tmp_path)
(tmp_path / "test-target.json").write_text(json.dumps(target.to_dict()))
From fae3b9cbd5717788dcd52af39dda4e90ea30af5e Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Wed, 30 Sep 2026 15:25:24 +0800
Subject: [PATCH 17/30] fix: prevent publication artifact writes through unsafe
paths
---
docs/u4d-final-execution.md | 17 +++++
paperforge/path_safety.py | 24 ++++++++
paperforge/publication_artifacts.py | 82 +++++++++++--------------
tests/test_u4d_artifact_write_safety.py | 80 ++++++++++++++++++++++++
4 files changed, 157 insertions(+), 46 deletions(-)
create mode 100644 tests/test_u4d_artifact_write_safety.py
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 6e9221a..9fa8ea1 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -88,3 +88,20 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
with hand-added scientific Evidence. A dedicated regression is required.
- Integration smoke, final security, remote review, tool freeze and all paper
revision requirements remain open. No push is authorized by this checkpoint alone.
+
+## Publication write safety repair
+
+- Added 24 red-first cases: three generators, temporary/output/manifest/directory
+ symlinks, traversal IDs, and deterministic retry. Before repair: 15 failed,
+ 9 passed. After repair, these and existing artifact tests: 50 passed.
+- Table/figure/fact writes now prevalidate all members and retained legacy temp
+ names, reject unsafe artifact IDs, and use random exclusive temporary files,
+ file fsync and atomic replace. A malicious outside sentinel remains unchanged;
+ invalid paths are refused before any member output is written.
+- Independent reviewer replayed the original exploit and approved the fix with
+ no new HIGH/CRITICAL findings in scope. Concurrent directory replacement is
+ still outside the single-writer contract.
+- Full regression: **735 collected, 730 passed, 5 skipped, 0 failed, 0 errors**;
+ Ruff PASS; configured mypy PASS (80 source files). No assertion was weakened.
+- Commit `58783af` contains the earlier isolated-environment/static gate repairs;
+ this security repair is committed separately.
diff --git a/paperforge/path_safety.py b/paperforge/path_safety.py
index 26346f3..c7e0d97 100644
--- a/paperforge/path_safety.py
+++ b/paperforge/path_safety.py
@@ -185,8 +185,32 @@ def atomic_write_text(
return target
+def atomic_write_bytes(
+ workspace: str | Path,
+ relative_path: str | Path,
+ content: bytes,
+) -> Path:
+ target = safe_output_path(workspace, relative_path)
+ temporary: str | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ mode="wb", dir=target.parent, prefix=f".{target.name}.", delete=False,
+ ) as stream:
+ temporary = stream.name
+ stream.write(content)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, target)
+ temporary = None
+ finally:
+ if temporary is not None:
+ Path(temporary).unlink(missing_ok=True)
+ return target
+
+
__all__ = [
"UnsafePathError",
+ "atomic_write_bytes",
"atomic_write_text",
"is_link_or_reparse_point",
"reject_symlink_components",
diff --git a/paperforge/publication_artifacts.py b/paperforge/publication_artifacts.py
index ccc05a1..0191e09 100644
--- a/paperforge/publication_artifacts.py
+++ b/paperforge/publication_artifacts.py
@@ -8,7 +8,7 @@
from pathlib import Path
from typing import Any
-from .path_safety import safe_mkdir
+from .path_safety import atomic_write_bytes, safe_output_path
TABLE_GENERATOR_VERSION = "paperforge.table-generator/v1"
FIGURE_GENERATOR_VERSION = "paperforge.figure-generator/v1"
@@ -24,6 +24,35 @@ class PublicationArtifactError(RuntimeError):
pass
+def _bundle_path(category: str, artifact_id: str) -> Path:
+ if (not artifact_id or artifact_id in {".", ".."}
+ or any(char in artifact_id for char in "/\\:\x00")):
+ raise PublicationArtifactError("artifact ID must be a single safe path component")
+ return Path("artifacts") / category / artifact_id
+
+
+def _write_bundle(
+ root: Path, relative: Path, contents: Mapping[str, bytes], manifest: dict[str, Any],
+) -> list[str]:
+ # Validate every member before writing any bytes. Retain suspicious old temp
+ # files for investigation; never follow the former fixed-name temp paths.
+ for name in (*contents, "manifest.json"):
+ safe_output_path(root, relative / name)
+ safe_output_path(root, relative / f".{name}.tmp")
+ manifest["output_hashes"] = {
+ name: hashlib.sha256(data).hexdigest() for name, data in contents.items()
+ }
+ manifest_bytes = (json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode()
+ manifest["output_hashes"]["manifest.json"] = hashlib.sha256(manifest_bytes).hexdigest()
+ completed = {
+ **contents,
+ "manifest.json": (json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode(),
+ }
+ for name, data in completed.items():
+ atomic_write_bytes(root, relative / name, data)
+ return [(relative / name).as_posix() for name in completed]
+
+
def _canonical(payload: Mapping[str, Any]) -> bytes:
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
@@ -258,7 +287,7 @@ def generate_table(
highlights.append({"metric": metric, "rule": which, "row_id": best[0]["row_id"]})
spec_digest = spec.digest()
table_id = spec.table_id or f"table-{spec_digest[:12]}"
- out_dir = safe_mkdir(root / "artifacts" / "tables" / table_id, anchor=root)
+ relative = _bundle_path("tables", table_id)
# data.csv (canonical), table.json (structured), table.tex (display).
header = ["row_id", *spec.columns]
csv_lines = [",".join(header)]
@@ -314,23 +343,7 @@ def generate_table(
],
"output_hashes": {},
}
- output_paths: list[str] = []
- for name, data in contents.items():
- target = out_dir / name
- tmp = target.with_name(f".{name}.tmp")
- tmp.write_bytes(data)
- tmp.replace(target)
- manifest["output_hashes"][name] = hashlib.sha256(data).hexdigest()
- output_paths.append(f"artifacts/tables/{table_id}/{name}")
- manifest_bytes = (json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
- manifest_path = out_dir / "manifest.json"
- tmp = manifest_path.with_name(".manifest.json.tmp")
- tmp.write_bytes(manifest_bytes)
- tmp.replace(manifest_path)
- manifest["output_hashes"]["manifest.json"] = hashlib.sha256(manifest_bytes).hexdigest()
- # Rewrite manifest with its own hash included? Keep stable: hash covers outputs only.
- manifest_path.write_bytes((json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"))
- output_paths.append(f"artifacts/tables/{table_id}/manifest.json")
+ output_paths = _write_bundle(root, relative, contents, manifest)
_register_outputs(root, memory, output_paths,
kind_map={"data.csv": "table", "table.json": "table", "table.tex": "table", "manifest.json": "manifest"},
metadata={"artifact_type": "table", "generator_version": TABLE_GENERATOR_VERSION,
@@ -379,7 +392,7 @@ def generate_figure(
series[group] = sorted(series[group], key=lambda p: (Decimal(p["x"]), Decimal(p["y"])))
spec_digest = spec.digest()
figure_id = spec.figure_id or f"figure-{spec_digest[:12]}"
- out_dir = safe_mkdir(root / "artifacts" / "figures" / figure_id, anchor=root)
+ relative = _bundle_path("figures", figure_id)
plot_data = {"figure_id": figure_id, "x_metric": spec.x_metric, "y_metric": spec.y_metric, "series": series}
# Deterministic SVG (no timestamps) + minimal deterministic PDF wrapper.
svg_points = []
@@ -416,19 +429,7 @@ def generate_figure(
],
"output_hashes": {},
}
- output_paths = []
- for name, data in contents.items():
- target = out_dir / name
- tmp = target.with_name(f".{name}.tmp")
- tmp.write_bytes(data)
- tmp.replace(target)
- manifest["output_hashes"][name] = hashlib.sha256(data).hexdigest()
- output_paths.append(f"artifacts/figures/{figure_id}/{name}")
- manifest_bytes = (json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
- (out_dir / "manifest.json").write_bytes(manifest_bytes)
- manifest["output_hashes"]["manifest.json"] = hashlib.sha256(manifest_bytes).hexdigest()
- (out_dir / "manifest.json").write_bytes((json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"))
- output_paths.append(f"artifacts/figures/{figure_id}/manifest.json")
+ output_paths = _write_bundle(root, relative, contents, manifest)
_register_outputs(root, memory, output_paths,
kind_map={"plot_data.json": "figure", "plot_data.csv": "figure", "figure.svg": "figure", "figure.pdf": "figure", "manifest.json": "manifest"},
metadata={"artifact_type": "figure", "generator_version": FIGURE_GENERATOR_VERSION,
@@ -501,7 +502,7 @@ def generate_facts(
raise PublicationArtifactError(f"unknown fact kind: {spec.kind}")
spec_digest = spec.digest()
fact_id = str(fact["fact_id"])
- out_dir = safe_mkdir(root / "artifacts" / "facts" / fact_id, anchor=root)
+ relative = _bundle_path("facts", fact_id)
facts_payload = {"facts": [fact], "spec": spec.to_canonical(), "spec_digest": spec_digest}
contents = {"facts.json": (json.dumps(facts_payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")}
manifest: dict[str, Any] = {
@@ -516,18 +517,7 @@ def generate_facts(
],
"output_hashes": {name: hashlib.sha256(data).hexdigest() for name, data in contents.items()},
}
- output_paths = []
- for name, data in contents.items():
- target = out_dir / name
- tmp = target.with_name(f".{name}.tmp")
- tmp.write_bytes(data)
- tmp.replace(target)
- output_paths.append(f"artifacts/facts/{fact_id}/{name}")
- manifest_bytes = (json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
- (out_dir / "manifest.json").write_bytes(manifest_bytes)
- manifest["output_hashes"]["manifest.json"] = hashlib.sha256(manifest_bytes).hexdigest()
- (out_dir / "manifest.json").write_bytes((json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"))
- output_paths.append(f"artifacts/facts/{fact_id}/manifest.json")
+ output_paths = _write_bundle(root, relative, contents, manifest)
_register_outputs(root, memory, output_paths,
kind_map={"facts.json": "result", "manifest.json": "manifest"},
metadata={"artifact_type": "fact", "generator_version": FACT_GENERATOR_VERSION,
diff --git a/tests/test_u4d_artifact_write_safety.py b/tests/test_u4d_artifact_write_safety.py
new file mode 100644
index 0000000..10517d5
--- /dev/null
+++ b/tests/test_u4d_artifact_write_safety.py
@@ -0,0 +1,80 @@
+from pathlib import Path
+
+import pytest
+
+from paperforge.path_safety import UnsafePathError
+from paperforge.publication_artifacts import (
+ FactSummarySpec,
+ FigureSpec,
+ PublicationArtifactError,
+ TableSpec,
+ generate_facts,
+ generate_figure,
+ generate_table,
+)
+from tests.test_u23b_artifacts import _ledger_three_layers
+
+
+def _generator(root, service, ledger, kind, artifact_id="safe"):
+ if kind == "tables":
+ return lambda: generate_table(root, service.memory, TableSpec(
+ ledger_id=ledger["ledger_id"], table_id=artifact_id, columns=("latency_ms",)))
+ if kind == "figures":
+ return lambda: generate_figure(root, service.memory, FigureSpec(
+ ledger_id=ledger["ledger_id"], figure_id=artifact_id,
+ x_metric="latency_ms", y_metric="latency_ms"))
+ return lambda: generate_facts(root, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], fact_id=artifact_id,
+ row_id=ledger["detail_rows"][0]["row_id"]))
+
+
+@pytest.mark.parametrize("kind,member", [
+ ("tables", "data.csv"), ("figures", "plot_data.json"), ("facts", "facts.json"),
+])
+@pytest.mark.parametrize("attack", ["temporary", "output", "manifest", "directory"])
+def test_publication_writes_reject_links_before_any_output(tmp_path, kind, member, attack):
+ root = tmp_path / "workspace"
+ root.mkdir()
+ service, ledger = _ledger_three_layers(root)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ sentinel = outside / "sentinel"
+ sentinel.write_bytes(b"must not change")
+ folder = root / "artifacts" / kind / "safe"
+ folder.parent.mkdir(parents=True, exist_ok=True)
+ if attack == "directory":
+ folder.symlink_to(outside, target_is_directory=True)
+ else:
+ folder.mkdir()
+ name = {"temporary": f".{member}.tmp", "output": member,
+ "manifest": "manifest.json"}[attack]
+ (folder / name).symlink_to(sentinel)
+ before = {p.name: p.read_bytes() for p in outside.iterdir() if p.is_file()}
+ with pytest.raises((UnsafePathError, PublicationArtifactError)):
+ _generator(root, service, ledger, kind)()
+ assert {p.name: p.read_bytes() for p in outside.iterdir() if p.is_file()} == before
+ if attack != "directory":
+ assert len(list(folder.iterdir())) == 1
+
+
+@pytest.mark.parametrize("kind", ["tables", "figures", "facts"])
+@pytest.mark.parametrize("bad_id", ["../../../outside", "/absolute", "..\\outside"])
+def test_publication_ids_cannot_escape_artifact_directory(tmp_path, kind, bad_id):
+ root = tmp_path / "workspace"
+ root.mkdir()
+ service, ledger = _ledger_three_layers(root)
+ with pytest.raises((UnsafePathError, PublicationArtifactError)):
+ _generator(root, service, ledger, kind, bad_id)()
+ assert not (tmp_path / "outside").exists()
+
+
+@pytest.mark.parametrize("kind", ["tables", "figures", "facts"])
+def test_safe_publication_retry_preserves_bytes_and_cleans_temporary_files(tmp_path: Path, kind):
+ service, ledger = _ledger_three_layers(tmp_path)
+ generate = _generator(tmp_path, service, ledger, kind)
+ first = generate()
+ folder = tmp_path / "artifacts" / kind / "safe"
+ before = {p.name: p.read_bytes() for p in folder.iterdir()}
+ assert generate() == first
+ assert {p.name: p.read_bytes() for p in folder.iterdir()} == before
+ assert not list(folder.glob(".*"))
From e69a5a912f6a381bab680efaa13050efa6dd3eb7 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Wed, 30 Sep 2026 15:35:52 +0800
Subject: [PATCH 18/30] fix: connect approved imported metrics to
provenance-bound ledgers
---
docs/u4d-final-execution.md | 25 +++++
paperforge/result_ledger.py | 104 +++++++++++++++++-
tests/test_u23_ledger_core.py | 12 +-
tests/test_u4d_import_ledger.py | 188 ++++++++++++++++++++++++++++++++
4 files changed, 319 insertions(+), 10 deletions(-)
create mode 100644 tests/test_u4d_import_ledger.py
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 9fa8ea1..94c47cf 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -105,3 +105,28 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
Ruff PASS; configured mypy PASS (80 source files). No assertion was weakened.
- Commit `58783af` contains the earlier isolated-environment/static gate repairs;
this security repair is committed separately.
+
+## Import-to-ledger and integration checkpoint
+
+- Publication path repair commit: `fae3b9c`.
+- Real integration defect confirmed red-first: approved/materialized metric JSON
+ produced an empty ledger because the registered adapters were never invoked.
+ Adapter extraction now runs from exact approved source bytes with manifest
+ identity/semantics, integrity checks and source-locator/hash provenance. It does
+ not mint or rewrite Evidence and does not parse manuscript numbers.
+- Independent review found and closed two binding gaps before commit: mutable
+ Evidence semantics cannot override the approved manifest; currentness cannot
+ bypass original import binding by deleting/changing current metadata. Recomputed
+ observation digests detect tampering while frozen history remains unchanged.
+- Sixteen import-path tests and one end-to-end integration smoke pass. Old U23
+ test fixture now uses actual materialized source Evidence instead of a fabricated
+ orphan metric row; all original integrity/currentness assertions are retained.
+- [FinalSmokeReport](u4d-final-smoke.md): real adapter-to-status pipeline, real
+ PyMuPDF fixture build/Poppler render, missing human gates and release refusal.
+ Combined with all U4C reliability tests: **86 passed**.
+- Full regression: **752 collected, 747 passed, 5 skipped, 0 failed, 0 errors**;
+ Ruff PASS; mypy PASS (80 files). Five SWIG warnings remain visible.
+- Broader A9 review is still in progress. It has reproduced another pre-existing
+ fixed-temp symlink overwrite in ResultUpdate proposal/spec/validation writes.
+ This is a push blocker and is next to repair. Remote review and paper revision
+ have not started; the overall goal remains active.
diff --git a/paperforge/result_ledger.py b/paperforge/result_ledger.py
index 2c411e9..8aa091b 100644
--- a/paperforge/result_ledger.py
+++ b/paperforge/result_ledger.py
@@ -350,6 +350,89 @@ def _apply_unit_conversions(
return output
+def _imported_metric_snapshots(
+ root: Path, memory: Any, evidence_id: str, row: Mapping[str, Any],
+ metadata: Mapping[str, Any], query: ResultLedgerQuery,
+) -> list[dict[str, Any]]:
+ from .external_import import _validate_metric_provenance, approval_valid, reconcile_imports
+ from .metric_adapters import MetricExtractorRegistry
+ from .metric_observation import AdapterContext, UnsupportedMetricSource
+ from .path_safety import reject_symlink_components
+
+ import_id = str(metadata.get("import_id") or "")
+ if not import_id or import_id in {".", ".."} or any(c in import_id for c in "/\\:"):
+ raise LedgerError("invalid import identity")
+ valid, reason = approval_valid(root, memory, import_id)
+ if not valid:
+ raise LedgerError(f"import approval is not current: {reason}")
+ if not reconcile_imports(root, memory)["consistent"]:
+ raise LedgerError("import materialization integrity mismatch")
+ base = root / ".paperforge" / "imports" / import_id
+ manifest_path = reject_symlink_components(base / "manifest.json", anchor=root)
+ manifest = json.loads(manifest_path.read_bytes())
+ source_relative = Path(str(metadata.get("source_relpath") or ""))
+ if (source_relative.is_absolute() or len(source_relative.parts) != 2
+ or source_relative.parts[0] != "sources"
+ or any(p in {".", ".."} for p in source_relative.parts)
+ or "\\" in str(source_relative)):
+ raise LedgerError("invalid imported metric source path")
+ source = reject_symlink_components(base / source_relative, anchor=root)
+ source_bytes = source.read_bytes()
+ if hashlib.sha256(source_bytes).hexdigest() != metadata.get("source_sha256"):
+ raise LedgerError("imported metric source integrity mismatch")
+ semantics = EvidenceSemantics.from_metadata(dict(manifest.get("semantics") or {}))
+ if EvidenceSemantics.from_metadata(metadata) != semantics:
+ raise LedgerError("Evidence differs from approved semantics")
+ execution = dict(manifest.get("execution") or {})
+ metric_provenance = dict(execution.get("metric_provenance") or {})
+ context = AdapterContext(
+ evidence_id=evidence_id,
+ run_identity=ScientificRunIdentity.from_manifest(manifest).to_dict(),
+ measurement_kind=semantics.measurement_kind,
+ acquisition_origin=semantics.acquisition_origin,
+ environment_role=semantics.environment_role,
+ acquisition_method=str(semantics.derivation_method or metric_provenance.get("acquisition_method") or ""),
+ method_version=str(semantics.derivation_version or metric_provenance.get("method_version") or ""),
+ parent_evidence_ids=semantics.parent_evidence_ids,
+ source_artifact_id=import_id,
+ source_file_hash=str(metadata.get("source_sha256") or ""),
+ )
+ try:
+ observations = MetricExtractorRegistry().extract(
+ source_bytes, source_relative.as_posix(), context)
+ except UnsupportedMetricSource as exc:
+ # An explicitly selected source must never disappear into an empty ledger.
+ # Broad selection can include non-metric documents alongside metric logs.
+ from .metric_adapters import SemanticsMismatchError
+
+ if isinstance(exc, SemanticsMismatchError) or evidence_id in query.evidence_ids:
+ raise
+ return []
+ snapshots = []
+ for observation in observations:
+ _validate_metric_provenance(semantics, observation.metric_name, metric_provenance)
+ normalized = {
+ **metadata, "metric_name": observation.metric_name,
+ "value_str": observation.source_lexical_value, "unit": observation.unit,
+ "run_identity": dict(observation.run_identity),
+ }
+ snapshot = _snapshot_evidence(
+ evidence_id, {**row, "metadata_json": json.dumps(normalized)}, query=query)
+ if snapshot is None:
+ continue
+ snapshot.update({
+ "adapter_id": observation.adapter_id,
+ "adapter_version": observation.adapter_version,
+ "source_file_hash": observation.source_file_hash,
+ "source_locator": observation.to_dict()["source_locator"],
+ })
+ body = {k: v for k, v in snapshot.items()
+ if k not in {"evidence_snapshot_digest", "source_lexical_value", "source_decimal_places"}}
+ snapshot["evidence_snapshot_digest"] = hashlib.sha256(_canonical_json(body)).hexdigest()
+ snapshots.append(snapshot)
+ return snapshots
+
+
def _aggregate(
snapshots: list[dict[str, Any]], spec: AggregationSpec, *, purpose: str = "scientific"
) -> list[dict[str, Any]]:
@@ -471,7 +554,15 @@ def freeze_ledger(
evidence_map = {str(r["id"]): r for r in _load_evidence_rows(memory) if r.get("id")}
snapshots: list[dict[str, Any]] = []
for evidence_id in sorted(evidence_map):
- snap = _snapshot_evidence(evidence_id, evidence_map[evidence_id], query=query)
+ row = evidence_map[evidence_id]
+ try:
+ metadata = json.loads(str(row.get("metadata_json") or "{}"))
+ except (ValueError, TypeError):
+ metadata = {}
+ if isinstance(metadata, dict) and metadata.get("import_id"):
+ snapshots.extend(_imported_metric_snapshots(root, memory, evidence_id, row, metadata, query))
+ continue
+ snap = _snapshot_evidence(evidence_id, row, query=query)
if snap is not None:
snapshots.append(snap)
# Conflict policy fail: same (metric, run identity, kind) with different values.
@@ -703,9 +794,20 @@ def verify_ledger(workspace: str | Path, memory: Any, ledger_id: str) -> dict[st
except (TypeError, ValueError):
meta = {}
import_id = meta.get("import_id") if isinstance(meta, dict) else None
+ if snap.get("adapter_id") and (not import_id or import_id != snap.get("import_id")):
+ stale.append(eid)
+ continue
if import_id:
try:
valid, _ = approval_valid(workspace, memory, str(import_id))
+ if valid and snap.get("adapter_id"):
+ # Re-derive imported observations, not just the approval.
+ # This also checks current row provenance and semantics.
+ candidates = _imported_metric_snapshots(
+ root, memory, eid, dict(row), meta,
+ ResultLedgerQuery(purpose="diagnostic", evidence_ids=(eid,)))
+ valid = any(candidate["evidence_snapshot_digest"] == snap.get("evidence_snapshot_digest")
+ for candidate in candidates)
except Exception:
valid = False
if not valid:
diff --git a/tests/test_u23_ledger_core.py b/tests/test_u23_ledger_core.py
index 4c7a7cc..b896de6 100644
--- a/tests/test_u23_ledger_core.py
+++ b/tests/test_u23_ledger_core.py
@@ -282,7 +282,7 @@ def test_conflict_fail_and_explicit_max(tmp_path: Path) -> None:
def test_verify_file_tamper_and_stale(tmp_path: Path) -> None:
service = _service(tmp_path)
src = tmp_path / "imp.json"
- src.write_text('{"latency_ms": 22.4}\n', encoding="utf-8")
+ src.write_text('{"schema":"paperforge.metric-json/v1","metric":"latency_ms","value":"22.400","unit":"ms"}\n', encoding="utf-8")
record = stage_import(
tmp_path, service.memory,
semantics=EvidenceSemantics.from_metadata({"measurement_kind": "measured", "acquisition_origin": "external_import", "environment_role": "scientific"}),
@@ -292,17 +292,11 @@ def test_verify_file_tamper_and_stale(tmp_path: Path) -> None:
report = validate_import(tmp_path, service.memory, record.import_id)
ack = [c["check_id"] for c in report["checks"] if c["status"] == "needs_human"]
approve_import(tmp_path, service.memory, record.import_id, approver="local-owner", acknowledged_checks=ack, rationale="ok")
- # Metric evidence linked to the import for currentness tracking.
+ # Use actual materialized source Evidence, not a fabricated extra metric row.
from paperforge.external_import import materialize_import as _mat
out = _mat(tmp_path, service.memory, record.import_id)
- metric_id = service.memory.add_evidence(
- evidence_type="EXTERNAL_MEASUREMENT", excerpt="latency 22.4 ms",
- path="metrics/lat.txt", config_scope="test",
- metadata={"measurement_kind": "measured", "acquisition_origin": "external_import", "environment_role": "scientific",
- "metric_name": "latency_ms", "value_str": "22.400", "unit": "ms",
- "import_id": record.import_id, "materialization_key": out["materialization_key"],
- "run_identity": {"schema": "paperforge.scientific-run-identity/v1", "model_id": "m"}})
+ metric_id = out["evidence_ids"][0]
ledger = freeze_ledger(tmp_path, service.memory, _q(metric_names=["latency_ms"]))
ok = verify_ledger(tmp_path, service.memory, ledger["ledger_id"])
assert ok["historical_integrity"] == "valid" # 23 part
diff --git a/tests/test_u4d_import_ledger.py b/tests/test_u4d_import_ledger.py
new file mode 100644
index 0000000..009926f
--- /dev/null
+++ b/tests/test_u4d_import_ledger.py
@@ -0,0 +1,188 @@
+"""Isolated synthetic transport fixtures, never real scientific evidence."""
+
+import hashlib
+import json
+
+import pytest
+
+from paperforge.api import PaperForgeService
+from paperforge.evidence_semantics import EvidenceSemantics
+from paperforge.external_import import (
+ ApprovalError,
+ approve_import,
+ materialize_import,
+ stage_import,
+ validate_import,
+)
+from paperforge.result_ledger import LedgerError, ResultLedgerQuery, freeze_ledger, verify_ledger
+
+
+def imported_metric(root, *, role="scientific", kind="measured", origin="external_import", payload=None):
+ # Scientific-role API branch is exercised only inside pytest's disposable DB.
+ # The explicit approval below is a test double, not an operator attestation.
+ service = PaperForgeService(root)
+ payload = payload or {"schema": "paperforge.metric-json/v1", "metric": "latency_ms",
+ "value": "12.500", "unit": "ms"}
+ raw = (json.dumps(payload, sort_keys=True) + "\n").encode()
+ (root / "fixture.json").write_bytes(raw)
+ record = stage_import(root, service.memory,
+ semantics=EvidenceSemantics(kind, origin, role),
+ subject={"model_id": "TEST_ONLY", "dataset_id": "TEST_ONLY", "seed": 1},
+ execution={"device": "TEST_ONLY", "runtime": "TEST_ONLY",
+ "timing_scope": "inference_only"},
+ source_files=["fixture.json"])
+ validation = validate_import(root, service.memory, record.import_id)
+ if role != "scientific" or kind == "transcribed":
+ return service, record, validation, raw
+ approve_import(root, service.memory, record.import_id, approver="TEST_ONLY",
+ rationale="Synthetic API transport test; not physical evidence",
+ acknowledged_checks=[c["check_id"] for c in validation["checks"]
+ if c["status"] == "needs_human"])
+ materialized = materialize_import(root, service.memory, record.import_id,
+ metric="latency_ms",
+ metric_provenance={"acquisition_method": "timer_samples"})
+ return service, record, materialized, raw
+
+
+def test_imported_metric_reaches_ledger_without_minting_evidence(tmp_path):
+ service, record, materialized, raw = imported_metric(tmp_path)
+ with service.memory.connect() as db:
+ before = [tuple(r) for r in db.execute("SELECT * FROM evidence")]
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+ assert len(ledger["snapshots"]) == 1
+ snapshot = ledger["snapshots"][0]
+ assert snapshot["value_str"] == "12.5"
+ assert snapshot["source_lexical_value"] == "12.500"
+ assert snapshot["evidence_id"] == materialized["evidence_ids"][0]
+ assert snapshot["import_id"] == record.import_id
+ assert snapshot["run_identity"]["model_id"] == "TEST_ONLY"
+ assert snapshot["adapter_id"] == "scalar-metric-json"
+ assert snapshot["source_file_hash"] == hashlib.sha256(raw).hexdigest()
+ assert snapshot["source_locator"]["pointer"].endswith("#/value")
+ assert verify_ledger(tmp_path, service.memory, ledger["ledger_id"])["eligible_as_release_input"]
+ with service.memory.connect() as db:
+ assert [tuple(r) for r in db.execute("SELECT * FROM evidence")] == before
+
+
+def test_imported_ledger_verifies_in_read_only_release_context(tmp_path):
+ from paperforge.release_eligibility import _ReadOnlyMemory
+
+ service, _, materialized, _ = imported_metric(tmp_path)
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ status = verify_ledger(tmp_path, _ReadOnlyMemory(service.memory), ledger["ledger_id"])
+ assert status["eligible_as_release_input"]
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+
+
+@pytest.mark.parametrize("role", ["fixture", "synthetic_test"])
+def test_fixture_import_does_not_receive_scientific_approval(tmp_path, role):
+ service, record, validation, _ = imported_metric(tmp_path, role=role)
+ assert validation["overall_status"] == "failed"
+ with pytest.raises(ApprovalError):
+ approve_import(tmp_path, service.memory, record.import_id,
+ approver="TEST_ONLY", rationale="must not bypass")
+ with pytest.raises(ApprovalError):
+ materialize_import(tmp_path, service.memory, record.import_id)
+
+
+def test_manuscript_transcription_cannot_bootstrap_scientific_evidence(tmp_path):
+ service, record, validation, _ = imported_metric(
+ tmp_path, kind="transcribed", origin="manuscript_existing")
+ assert validation["overall_status"] == "failed"
+ with pytest.raises(ApprovalError):
+ approve_import(tmp_path, service.memory, record.import_id,
+ approver="TEST_ONLY", rationale="must not self-bootstrap")
+ with pytest.raises(ApprovalError):
+ materialize_import(tmp_path, service.memory, record.import_id)
+ with service.memory.connect() as db:
+ assert db.execute("SELECT COUNT(*) FROM evidence").fetchone()[0] == 0
+
+
+def test_import_ledger_refuses_changed_source(tmp_path):
+ service, record, materialized, _ = imported_metric(tmp_path)
+ source = tmp_path / ".paperforge/imports" / record.import_id / "sources/fixture.json"
+ source.write_bytes(b'{"value":"999"}')
+ with pytest.raises(LedgerError, match="current|integrity|approval"):
+ freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+
+
+def test_import_ledger_rejects_payload_semantic_override(tmp_path):
+ service, _, materialized, _ = imported_metric(tmp_path, payload={
+ "schema": "paperforge.metric-json/v1", "metric": "latency_ms",
+ "value": "12.5", "unit": "ms", "measurement_kind": "simulated"})
+ with pytest.raises(ValueError, match="SEMANTICS_MISMATCH"):
+ freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+
+
+def test_imported_ledger_becomes_stale_when_source_changes(tmp_path):
+ service, record, materialized, _ = imported_metric(tmp_path)
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+ source = tmp_path / ".paperforge/imports" / record.import_id / "sources/fixture.json"
+ source.write_bytes(b"changed")
+ status = verify_ledger(tmp_path, service.memory, ledger["ledger_id"])
+ assert status["historical_integrity"] == "valid"
+ assert status["source_currentness"] == "stale"
+ assert not status["eligible_as_release_input"]
+
+
+@pytest.mark.parametrize("metric,unit", [("fps", "fps"), ("energy", "J")])
+def test_import_adapter_cannot_launder_ambiguous_measured_metrics(tmp_path, metric, unit):
+ service, _, materialized, _ = imported_metric(tmp_path, payload={
+ "schema": "paperforge.metric-json/v1", "metric": metric, "value": "12.5", "unit": unit})
+ with pytest.raises(ApprovalError, match="acquisition_method"):
+ freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+
+
+def test_import_ledger_does_not_accept_inline_metadata_metric_override(tmp_path):
+ service, _, materialized, _ = imported_metric(tmp_path)
+ eid = materialized["evidence_ids"][0]
+ with service.memory.connect() as db:
+ metadata = json.loads(db.execute("SELECT metadata_json FROM evidence WHERE id=?", (eid,)).fetchone()[0])
+ metadata.update(metric_name="latency_ms", unit="ms", value_str="999")
+ db.execute("UPDATE evidence SET metadata_json=? WHERE id=?", (json.dumps(metadata), eid))
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(evidence_ids=(eid,)))
+ assert ledger["snapshots"][0]["value_str"] == "12.5"
+
+
+def test_import_ledger_rejects_semantics_changed_after_approval(tmp_path):
+ service, _, materialized, _ = imported_metric(tmp_path, payload={
+ "schema": "paperforge.metric-json/v1", "metric": "latency_ms",
+ "value": "12.5", "unit": "ms", "measurement_kind": "simulated"})
+ eid = materialized["evidence_ids"][0]
+ with service.memory.connect() as db:
+ metadata = json.loads(db.execute("SELECT metadata_json FROM evidence WHERE id=?", (eid,)).fetchone()[0])
+ metadata["measurement_kind"] = "simulated"
+ db.execute("UPDATE evidence SET metadata_json=? WHERE id=?", (json.dumps(metadata), eid))
+ with pytest.raises(LedgerError, match="approved semantics"):
+ freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(evidence_ids=(eid,)))
+
+
+@pytest.mark.parametrize("damage", ["semantics", "deleted_import", "changed_import", "excerpt"])
+def test_frozen_import_ledger_currentness_rechecks_evidence_semantics(tmp_path, damage):
+ service, _, materialized, _ = imported_metric(tmp_path)
+ eid = materialized["evidence_ids"][0]
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(evidence_ids=(eid,)))
+ with service.memory.connect() as db:
+ metadata = json.loads(db.execute("SELECT metadata_json FROM evidence WHERE id=?", (eid,)).fetchone()[0])
+ if damage == "semantics":
+ metadata["environment_role"] = "fixture"
+ elif damage == "deleted_import":
+ del metadata["import_id"]
+ elif damage == "changed_import":
+ metadata["import_id"] = "another-import"
+ else:
+ db.execute("UPDATE evidence SET excerpt='tampered' WHERE id=?", (eid,))
+ db.execute("UPDATE evidence SET metadata_json=? WHERE id=?", (json.dumps(metadata), eid))
+ status = verify_ledger(tmp_path, service.memory, ledger["ledger_id"])
+ assert status["historical_integrity"] == "valid"
+ assert status["source_currentness"] == "stale"
+ assert not status["eligible_as_release_input"]
From 209d0db16ac862f5a8d7e0d53a65b5c6de59f9cf Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:24:12 +0800
Subject: [PATCH 19/30] fix: harden operation writes and record end-to-end
smoke
---
docs/u4d-final-execution.md | 15 +++
docs/u4d-final-smoke.md | 60 +++++++++
paperforge/external_import.py | 34 ++++--
paperforge/result_update.py | 18 +--
tests/test_u4d_final_smoke.py | 147 +++++++++++++++++++++++
tests/test_u4d_operation_write_safety.py | 51 ++++++++
6 files changed, 305 insertions(+), 20 deletions(-)
create mode 100644 docs/u4d-final-smoke.md
create mode 100644 tests/test_u4d_final_smoke.py
create mode 100644 tests/test_u4d_operation_write_safety.py
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 94c47cf..e407c86 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -130,3 +130,18 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
fixed-temp symlink overwrite in ResultUpdate proposal/spec/validation writes.
This is a push blocker and is next to repair. Remote review and paper revision
have not started; the overall goal remains active.
+
+## Operation write safety checkpoint (2026-10-09)
+
+- ResultUpdate prevalidates all proposal members and legacy temporary paths;
+ external imports validate IDs and member paths. Both use random atomic writes.
+- Eight red-first regressions preserve outside sentinel bytes and existing state
+ on unsafe output or temporary paths. Related recovery tests: **35 passed**.
+- Independent review approved the scoped repair and fixture-only smoke;
+ independent related tests: **29 passed**, Ruff PASS.
+- Full regression: **760 collected, 755 passed, 5 skipped, 0 failed, 0 errors**;
+ Ruff PASS; configured mypy PASS (80 files). The five real-compute opt-in skips
+ and five SWIG warnings remain as previously documented.
+- A9 remains open: SVG attribute serialization, invalid preview PDF bytes, and
+ dynamically constructed LaTeX file commands still require repair. No push,
+ remote review, tool freeze, or real-paper revision has occurred.
diff --git a/docs/u4d-final-smoke.md b/docs/u4d-final-smoke.md
new file mode 100644
index 0000000..a63496e
--- /dev/null
+++ b/docs/u4d-final-smoke.md
@@ -0,0 +1,60 @@
+# FinalSmokeReport
+
+Schema: `paperforge.final-smoke-report/v1` (durable Markdown report).
+Run date: 2026-09-30. Environment role: **synthetic_test**.
+Overall transport result: **PASSED**. Publication/release authorization: **NOT_GRANTED**.
+
+## Executed path
+
+`tests/test_u4d_final_smoke.py::test_final_evidence_to_release_status_smoke`
+executes the following in one disposable workspace, without patching production
+functions or injecting a hand-made metric Evidence row:
+
+1. Create clearly labeled synthetic source bytes; external import stage/validate.
+2. Explicit fixture-only approval test double; materialize the source Evidence.
+ This is not a real device attestation and must never be imported into a paper.
+3. Approved source bytes -> registered metric adapter -> normalized observation ->
+ frozen ledger. Preserve original lexical value, source hash, locator and identity.
+4. Generate Fact/Table/Figure preview data from that same ledger; compare actual
+ member hashes against the manifests. Outputs remain `publication_ready=false`.
+5. Validate/render a fact-bound narrative, freeze scientific review and reviewer
+ matrix, and verify historical/current artifact integrity.
+6. Build a real one-page fixture PDF from the fixture text using PyMuPDF, bind
+ source/PDF hashes and toolchain in build provenance, render it using real
+ Poppler, run PDF QA. No HumanPageReview is fabricated.
+7. Evaluate release with the default policy, actual ledger/review/matrix/PDF inputs.
+ Verify zero database mutation, preserve missing gates, refuse eligibility,
+ freeze the assessment, recompute currentness, and retain `NOT_RELEASED`.
+8. Create a writing-only workflow and inspect UnifiedRunStatus. Missing process
+ memory remains `UNKNOWN_NOT_ATTACHED`; original source and imported bytes are
+ unchanged.
+
+The test emits `FinalSmokeReport.json` inside its temporary workspace, including
+the actual import/ledger/artifact/review/assessment identifiers. Temporary database,
+PDF, raster and source fixtures are not repository delivery artifacts.
+
+## Negative boundaries and reliability
+
+- `tests/test_u4d_import_ledger.py`: fixture/synthetic imports cannot be approved
+ or materialized as scientific Evidence; manuscript-existing transcription
+ cannot bootstrap Evidence; stale source, semantic override and ambiguous measured
+ FPS/energy are rejected. Existing frozen ledgers become stale when their Evidence
+ semantics, source association or excerpt is damaged. Read-only release-context
+ verification leaves the database unchanged.
+- U4C's four reliability modules rerun without exclusions: RU-1..8, six actual
+ SIGKILL/reopen checkpoints, import reopen and immutable split-brain/stress.
+- Combined import/integration/reliability run: **86 passed**, zero failed/errors
+ or skips; five dependency SWIG deprecation warnings disclosed.
+
+```sh
+.venv/bin/python3.11 -m pytest tests/test_u4d_import_ledger.py tests/test_u4d_final_smoke.py tests/test_u4c_result_recovery.py tests/test_u4c_subprocess.py tests/test_u4c_artifact_recovery.py tests/test_u4c_reopen_and_stress.py -q --tb=short
+```
+
+## Scope limits
+
+This is a transport/invariant gate, not scientific validation of any manuscript.
+It does not certify figure publication layout, reviewer acceptance, real device
+measurement or human visual review. The dependent x/y preview in the fixture is
+deliberately not treated as independent evidence. Physical power-loss and
+concurrent-writer reliability remain unproven. The complete local security review,
+authorized push and both remote reviews are separate required gates.
diff --git a/paperforge/external_import.py b/paperforge/external_import.py
index cb1e839..de5b1bc 100644
--- a/paperforge/external_import.py
+++ b/paperforge/external_import.py
@@ -3,6 +3,7 @@
import contextlib
import hashlib
import json
+import re
import uuid
from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass
@@ -11,7 +12,13 @@
from .evidence_semantics import EvidenceSemantics, EvidenceSemanticsError
from .models import utc_now
-from .path_safety import reject_symlink_components, safe_mkdir
+from .path_safety import (
+ atomic_write_bytes,
+ atomic_write_text,
+ reject_symlink_components,
+ safe_mkdir,
+ safe_output_path,
+)
IMPORT_SCHEMA = "paperforge.external-import/v1"
@@ -150,7 +157,7 @@ def stage_import(
stem, suffix = Path(filename).stem, Path(filename).suffix
target = sources_dir / f"{stem}-{counter}{suffix}"
counter += 1
- target.write_bytes(data)
+ atomic_write_bytes(root, target.relative_to(root), data)
sha = hashlib.sha256(data).hexdigest()
suffix = Path(target.name).suffix.lower()
media = {
@@ -182,10 +189,8 @@ def stage_import(
manifest_bytes = _canonical_json(manifest)
manifest_sha = hashlib.sha256(manifest_bytes).hexdigest()
manifest_path = import_root / "manifest.json"
- manifest_path.write_text(
- json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
- encoding="utf-8",
- )
+ atomic_write_text(root, manifest_path.relative_to(root),
+ json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
validation = {
"schema": "paperforge.external-import.validation/v1",
"import_id": import_id,
@@ -196,10 +201,8 @@ def stage_import(
"detail": "staged only; validation and approval arrive in U2.2",
}
validation_path = import_root / "validation.json"
- validation_path.write_text(
- json.dumps(validation, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
- encoding="utf-8",
- )
+ atomic_write_text(root, validation_path.relative_to(root),
+ json.dumps(validation, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
_ensure_imports_table(memory)
with memory.connect() as db:
db.execute(
@@ -303,7 +306,11 @@ def _ensure_u22_tables(memory: Any) -> None:
def _import_paths(root: Path, import_id: str) -> tuple[Path, Path, Path]:
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", import_id):
+ raise ImportSafetyError("invalid import identifier")
base = root / ".paperforge" / "imports" / import_id
+ for name in ("manifest.json", "validation.json", "sources"):
+ reject_symlink_components(base / name, anchor=root)
return base / "manifest.json", base / "validation.json", base / "sources"
@@ -606,10 +613,11 @@ def validate_import(workspace: str | Path, memory: Any, import_id: str) -> dict[
"created_at": utc_now(),
"validated_at": utc_now(),
}
- # Deterministic atomic write (temp + replace) for crash safety.
+ # Retain suspicious legacy temp paths; use an exclusive random temp for writes.
tmp_path = validation_path.with_name(f".{validation_path.name}.{import_id}.tmp")
- tmp_path.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp_path.replace(validation_path)
+ safe_output_path(root, tmp_path.relative_to(root))
+ atomic_write_text(root, validation_path.relative_to(root),
+ json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
state = "validated" if overall in {"passed", "needs_human"} else "validation_failed"
with memory.connect() as db:
db.execute(
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index 0472164..6a52d02 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -10,7 +10,7 @@
from typing import Any
from .models import utc_now
-from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir
+from .path_safety import atomic_write_text, reject_symlink_components, safe_mkdir, safe_output_path
from .protected_blocks import (
PROTECTED_END,
PROTECTED_START,
@@ -366,6 +366,8 @@ def _ensure_update_tables(memory: Any) -> None:
def _update_paths(root: Path, proposal_id: str) -> Path:
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", proposal_id):
+ raise ResultUpdateValidationError("invalid proposal identifier")
return safe_mkdir(root / ".paperforge" / "result_updates" / proposal_id, anchor=root)
@@ -495,12 +497,14 @@ def build_proposal(
proposal = {**stable, "proposal_id": proposal_id, "proposal_digest": digest,
"validation": validation, "created_at": utc_now()}
base = _update_paths(root, proposal_id)
- for name, content in (("spec.json", spec.to_canonical()), ("proposal.json", proposal),
- ("validation.json", validation)):
- target_path = base / name
- tmp = target_path.with_name(f".{name}.tmp")
- tmp.write_text(json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- tmp.replace(target_path)
+ contents = {"spec.json": spec.to_canonical(), "proposal.json": proposal,
+ "validation.json": validation}
+ for name in contents:
+ safe_output_path(root, (base / name).relative_to(root))
+ safe_output_path(root, (base / f".{name}.tmp").relative_to(root))
+ for name, content in contents.items():
+ atomic_write_text(root, (base / name).relative_to(root),
+ json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
_ensure_update_tables(memory)
with memory.connect() as db:
db.execute(
diff --git a/tests/test_u4d_final_smoke.py b/tests/test_u4d_final_smoke.py
new file mode 100644
index 0000000..e24527c
--- /dev/null
+++ b/tests/test_u4d_final_smoke.py
@@ -0,0 +1,147 @@
+"""Synthetic end-to-end transport; never a real-paper release certificate."""
+
+import hashlib
+import json
+
+import pymupdf
+
+from paperforge.grounded_narrative import (
+ GroundedNarrativeSpec,
+ NarrativeSentence,
+ render_narrative,
+ validate_narrative,
+)
+from paperforge.pdf_qa import PDFQASpec, run_pdf_qa, verify_pdf_qa
+from paperforge.publication_artifacts import (
+ FactSummarySpec,
+ FigureSpec,
+ TableSpec,
+ generate_facts,
+ generate_figure,
+ generate_table,
+ verify_publication_bundle,
+)
+from paperforge.release_eligibility import (
+ ReleasePolicy,
+ ReleaseTarget,
+ assessment_current,
+ evaluate_release,
+ freeze_assessment,
+ release_authorization,
+)
+from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger, verify_ledger
+from paperforge.reviewer_matrix import (
+ AcceptanceCriterion,
+ EvidenceBinding,
+ ReviewerAction,
+ ReviewerComment,
+ freeze_review_matrix,
+ verify_review_matrix,
+)
+from paperforge.scientific_review import (
+ ScientificClaim,
+ freeze_review,
+ review_claim,
+ verify_scientific_review,
+)
+from tests.test_u4d_import_ledger import imported_metric
+
+
+def _sha(path):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def test_final_evidence_to_release_status_smoke(tmp_path):
+ service, record, materialized, raw = imported_metric(tmp_path)
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ evidence_ids=tuple(materialized["evidence_ids"])))
+ assert len(ledger["snapshots"]) == 1
+ assert verify_ledger(tmp_path, service.memory, ledger["ledger_id"])["eligible_as_release_input"]
+ fact = generate_facts(tmp_path, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], row_id=ledger["detail_rows"][0]["row_id"]))
+ table = generate_table(tmp_path, service.memory, TableSpec(
+ ledger_id=ledger["ledger_id"], columns=("latency_ms",)))
+ figure = generate_figure(tmp_path, service.memory, FigureSpec(
+ ledger_id=ledger["ledger_id"], x_metric="latency_ms", y_metric="latency_ms"))
+ # This deliberately dependent preview is not independent scientific evidence.
+ for kind, artifact in (("facts", fact), ("tables", table), ("figures", figure)):
+ aid = artifact[{"facts": "fact_id", "tables": "table_id", "figures": "figure_id"}[kind]]
+ checked = verify_publication_bundle([artifact["manifest"]])
+ assert checked["artifact_integrity"]
+ for name, digest in artifact["manifest"]["output_hashes"].items():
+ if name != "manifest.json":
+ assert _sha(tmp_path / "artifacts" / kind / aid / name) == digest
+ assert artifact["manifest"]["publication_ready"] is False
+ sentence = NarrativeSentence("s1", "The test measured latency was 12.5 ms.",
+ fact_ids=(fact["fact_id"],))
+ spec = GroundedNarrativeSpec(allowed_fact_ids=(fact["fact_id"],))
+ paragraphs = [[sentence]]
+ validated = validate_narrative(spec, paragraphs, facts=[fact["fact"]])
+ assert validated["overall_status"] == "passed"
+ rendered = render_narrative(paragraphs)
+ claim = ScientificClaim.from_narrative_sentence(sentence.to_dict())
+ review = freeze_review(tmp_path, service.memory, claims=[claim],
+ results=review_claim(claim, facts={fact["fact_id"]: fact["fact"]}),
+ ledger_bindings=[{"ledger_id": ledger["ledger_id"],
+ "ledger_digest": ledger["ledger_digest"]}])
+ assert verify_scientific_review(tmp_path, service.memory, review["review_id"])["currently_valid_as_review_input"]
+ matrix = freeze_review_matrix(tmp_path, service.memory,
+ comments=[ReviewerComment("TEST_R1", "synthetic test", "Check the test metric source.")],
+ actions=[ReviewerAction("a1", "TEST_R1", "Trace the generated fact",
+ acceptance_criteria=("c1",))],
+ criteria=[AcceptanceCriterion("c1", "hardware_measurement")],
+ bindings=[EvidenceBinding("b1", "a1", "fact", fact["fact_id"])],
+ review_ids=[review["review_id"]])
+ assert verify_review_matrix(tmp_path, service.memory, matrix["matrix_id"])["historical_integrity"] == "valid"
+
+ # A real PDF build from this fixture source, not a forged PDF header.
+ source = tmp_path / "fixture-source.txt"
+ source.write_text(rendered, encoding="utf-8")
+ with pymupdf.open() as document:
+ page = document.new_page()
+ page.insert_text((72, 72), source.read_text(), fontsize=12)
+ document.save(tmp_path / "fixture.pdf")
+ build = {"schema": "paperforge.build-provenance/v1", "status": "succeeded",
+ "source_hashes": {source.name: _sha(source)},
+ "output_path": "fixture.pdf", "output_sha256": _sha(tmp_path / "fixture.pdf"),
+ "command": ["pytest", "tests/test_u4d_final_smoke.py"],
+ "toolchain": {"pymupdf": pymupdf.VersionBind}, "environment_role": "synthetic_test"}
+ (tmp_path / "build.json").write_text(json.dumps(build, sort_keys=True))
+ pdf_qa = run_pdf_qa(tmp_path, service.memory, PDFQASpec(
+ target_pdf_path="fixture.pdf", target_pdf_sha256=build["output_sha256"],
+ build_digest=_sha(tmp_path / "build.json")))
+ assert len(pdf_qa["render_manifest"]) == 1
+ assert all(r["renderer"].startswith("poppler-pdftoppm/") for r in pdf_qa["render_manifest"])
+ assert pdf_qa["human_reviews"] == []
+ assert pdf_qa["layout_qa_state"] != "passed"
+ assert verify_pdf_qa(tmp_path, service.memory, pdf_qa["bundle_id"])["historical_integrity"] == "valid"
+ target = ReleaseTarget("SYNTHETIC_TEST_ONLY", manuscript_path=source.name,
+ manuscript_sha256=_sha(source), final_pdf_path="fixture.pdf",
+ final_pdf_sha256=build["output_sha256"],
+ build_manifest_path="build.json", build_digest=_sha(tmp_path / "build.json"))
+ with service.memory.connect() as db:
+ before = list(db.iterdump())
+ report = evaluate_release(tmp_path, service.memory, target, ReleasePolicy(),
+ evidence_refs=[{"evidence_id": eid} for eid in materialized["evidence_ids"]],
+ ledger_ids=[ledger["ledger_id"]], review_ids=[review["review_id"]],
+ reviewer_projection={"matrix_id": matrix["matrix_id"]}, pdf_bundle_ids=[pdf_qa["bundle_id"]])
+ assert report["overall_eligibility"] != "ELIGIBLE"
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before
+ freeze_assessment(tmp_path, service.memory, report)
+ assert assessment_current(tmp_path, service.memory, report["report_id"])["currently_valid"]
+ assert release_authorization(tmp_path, service.memory, report["report_id"])["release_state"] == "NOT_RELEASED"
+ handle = service.run(profile="writing-only", inputs={"title": "Synthetic test", "topic": "Test"})
+ status = service.unified_status(handle.run_id)
+ assert status["unified"]["process_state"] == "UNKNOWN_NOT_ATTACHED"
+ assert source.read_text() == rendered
+ assert (tmp_path / "fixture.json").read_bytes() == raw
+ result = {"schema": "paperforge.final-smoke-report/v1", "status": "PASSED",
+ "environment_role": "synthetic_test", "import_id": record.import_id,
+ "ledger_id": ledger["ledger_id"], "fact_id": fact["fact_id"],
+ "table_id": table["table_id"], "figure_id": figure["figure_id"],
+ "review_id": review["review_id"], "matrix_id": matrix["matrix_id"],
+ "pdf_qa_id": pdf_qa["bundle_id"], "release_report_id": report["report_id"],
+ "human_page_reviews_created": 0, "released": False,
+ "note": "Import approval is an explicit fixture-only test double, not a real attestation."}
+ (tmp_path / "FinalSmokeReport.json").write_text(json.dumps(result, sort_keys=True, indent=2))
diff --git a/tests/test_u4d_operation_write_safety.py b/tests/test_u4d_operation_write_safety.py
new file mode 100644
index 0000000..f20d769
--- /dev/null
+++ b/tests/test_u4d_operation_write_safety.py
@@ -0,0 +1,51 @@
+import pytest
+
+from paperforge.external_import import validate_import
+from paperforge.path_safety import UnsafePathError
+from paperforge.result_update import build_proposal
+from tests.test_u22_import_transaction import _stage
+from tests.test_u24a_finalization import _fact, _spec_with_table
+
+
+@pytest.mark.parametrize("member", ["spec.json", "proposal.json", "validation.json"])
+@pytest.mark.parametrize("attack", ["temporary", "output"])
+def test_proposal_write_preflights_all_members(tmp_path, member, attack):
+ root = tmp_path / "workspace"
+ root.mkdir()
+ service, spec, old, _ = _spec_with_table(root, "Old result 20.0 ms.")
+ new = old.replace("20.0", "22.4")
+ proposal = build_proposal(root, service.memory, spec, proposed_block=new, facts_used=[_fact()])
+ base = root / ".paperforge/result_updates" / proposal["proposal_id"]
+ target = base / (f".{member}.tmp" if attack == "temporary" else member)
+ if target.exists():
+ target.unlink()
+ sentinel = tmp_path / "outside"
+ sentinel.write_bytes(b"preserve")
+ target.symlink_to(sentinel)
+ before = {p.name: p.read_bytes() for p in base.iterdir()}
+ with service.memory.connect() as db:
+ before_db = list(db.iterdump())
+ with pytest.raises(UnsafePathError):
+ build_proposal(root, service.memory, spec, proposed_block=new, facts_used=[_fact()])
+ assert sentinel.read_bytes() == b"preserve"
+ assert {p.name: p.read_bytes() for p in base.iterdir()} == before
+ with service.memory.connect() as db:
+ assert list(db.iterdump()) == before_db
+
+
+@pytest.mark.parametrize("attack", ["temporary", "output"])
+def test_import_validation_does_not_follow_writable_symlinks(tmp_path, attack):
+ root = tmp_path / "workspace"
+ root.mkdir()
+ service, record = _stage(root)
+ base = root / ".paperforge/imports" / record.import_id
+ target = base / (f".validation.json.{record.import_id}.tmp"
+ if attack == "temporary" else "validation.json")
+ if target.exists():
+ target.unlink()
+ sentinel = tmp_path / "outside"
+ sentinel.write_bytes(b"preserve")
+ target.symlink_to(sentinel)
+ with pytest.raises(UnsafePathError):
+ validate_import(root, service.memory, record.import_id)
+ assert sentinel.read_bytes() == b"preserve"
From 70ee8be5a54cfe87169999b3d069c6561200e791 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:27:33 +0800
Subject: [PATCH 20/30] fix: serialize figure labels and generate valid PDF
previews
---
docs/u4d-final-execution.md | 15 ++++++
paperforge/publication_artifacts.py | 67 ++++++++++++++++++++++----
tests/test_u4d_figure_serialization.py | 57 ++++++++++++++++++++++
3 files changed, 129 insertions(+), 10 deletions(-)
create mode 100644 tests/test_u4d_figure_serialization.py
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index e407c86..76d98b1 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -145,3 +145,18 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
- A9 remains open: SVG attribute serialization, invalid preview PDF bytes, and
dynamically constructed LaTeX file commands still require repair. No push,
remote review, tool freeze, or real-paper revision has occurred.
+
+## Figure serialization checkpoint (2026-10-09)
+
+- Figure generator v2 uses XML serialization for title/series data. Three
+ red-first cases confirm quotes, ampersands and angle brackets remain data.
+- Replaced invalid PDF-header-plus-SVG bytes with a real deterministic single-page
+ PDF: proper objects, stream lengths, cross-reference table and trailer, plotted
+ observations and disclosed axis ranges. No dependency was added. It is explicitly
+ a preview, not a publication-ready figure; series/metric identities stay in the
+ canonical sidecar. Empty observations are labeled rather than fabricated.
+- Strict pypdf parsing, PyMuPDF drawing/render checks, byte-identical retry and
+ actual Poppler render/visual inspection pass. Independent review: 25 tests PASS,
+ Ruff/mypy PASS, no HIGH/CRITICAL within this repair.
+- Full regression: **764 collected, 759 passed, 5 skipped, 0 failed, 0 errors**;
+ Ruff PASS; mypy PASS (80 files). LaTeX policy repair is still open and blocks push.
diff --git a/paperforge/publication_artifacts.py b/paperforge/publication_artifacts.py
index 0191e09..c117fb8 100644
--- a/paperforge/publication_artifacts.py
+++ b/paperforge/publication_artifacts.py
@@ -7,11 +7,12 @@
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
+from xml.etree import ElementTree as ET
from .path_safety import atomic_write_bytes, safe_output_path
TABLE_GENERATOR_VERSION = "paperforge.table-generator/v1"
-FIGURE_GENERATOR_VERSION = "paperforge.figure-generator/v1"
+FIGURE_GENERATOR_VERSION = "paperforge.figure-generator/v2"
FACT_GENERATOR_VERSION = "paperforge.fact-generator/v1"
_BANNED_FACT_WORDS = (
@@ -82,6 +83,53 @@ def _format_display(canonical: str | None, places: int | None) -> str:
return format(quantized, "f")
+def _figure_preview_pdf(series: Mapping[str, Sequence[Mapping[str, str]]]) -> bytes:
+ """Write a dependency-free, single-page PDF preview, never a release figure."""
+ points = [(Decimal(p["x"]), Decimal(p["y"])) for group in sorted(series) for p in series[group]]
+ if any(not value.is_finite() for point in points for value in point):
+ raise PublicationArtifactError("figure coordinates must be finite")
+ commands = [
+ "BT /F1 14 Tf 50 370 Td (Deterministic preview - not publication ready) Tj ET",
+ "BT /F1 10 Tf 50 350 Td (X/Y metrics and series identities: see plot_data.json) Tj ET",
+ "0.25 G 1 w 60 65 m 550 65 l S 60 65 m 60 320 l S",
+ ]
+ if points:
+ xmin, xmax = min(p[0] for p in points), max(p[0] for p in points)
+ ymin, ymax = min(p[1] for p in points), max(p[1] for p in points)
+ # Normalize canonical decimals before converting to display coordinates.
+ # Degenerate axes place the observation at the midpoint, not at zero.
+ for x, y in points:
+ px = Decimal(80) + (Decimal("0.5") if xmin == xmax else (x - xmin) / (xmax - xmin)) * 440
+ py = Decimal(85) + (Decimal("0.5") if ymin == ymax else (y - ymin) / (ymax - ymin)) * 215
+ commands.append(f"0.12 0.32 0.62 rg {px - 3:.4f} {py - 3:.4f} 6 6 re f")
+ commands += [
+ f"0 g BT /F1 10 Tf 60 42 Td (X range: {xmin:.4g} to {xmax:.4g}) Tj ET",
+ f"BT /F1 10 Tf 60 25 Td (Y range: {ymin:.4g} to {ymax:.4g}) Tj ET",
+ ]
+ else:
+ commands.append("BT /F1 12 Tf 190 195 Td (No paired observations) Tj ET")
+ stream = ("\n".join(commands) + "\n").encode("ascii")
+ objects = [
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 400] "
+ b"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ b"<< /Length " + str(len(stream)).encode("ascii") + b" >>\nstream\n" + stream + b"endstream",
+ ]
+ output = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
+ offsets = [0]
+ for index, obj in enumerate(objects, 1):
+ offsets.append(len(output))
+ output.extend(f"{index} 0 obj\n".encode("ascii") + obj + b"\nendobj\n")
+ xref = len(output)
+ output.extend(f"xref\n0 {len(offsets)}\n0000000000 65535 f \n".encode("ascii"))
+ for offset in offsets[1:]:
+ output.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
+ output.extend(f"trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode("ascii"))
+ return bytes(output)
+
+
@dataclass(frozen=True)
class TableSpec:
ledger_id: str
@@ -394,17 +442,16 @@ def generate_figure(
figure_id = spec.figure_id or f"figure-{spec_digest[:12]}"
relative = _bundle_path("figures", figure_id)
plot_data = {"figure_id": figure_id, "x_metric": spec.x_metric, "y_metric": spec.y_metric, "series": series}
- # Deterministic SVG (no timestamps) + minimal deterministic PDF wrapper.
- svg_points = []
+ # XML serializer keeps labels as inert data, not markup or attributes.
+ svg_root = ET.Element("svg", {"xmlns": "http://www.w3.org/2000/svg", "version": "1.1"})
+ ET.SubElement(svg_root, "title").text = figure_id
for group in sorted(series):
for point in series[group]:
- svg_points.append(f'
')
- svg = (
- '
\n"
- )
- pdf_body = f"%PDF-1.4\n%{figure_id}\n".encode() + svg.encode("utf-8") + b"\n%%EOF\n"
+ ET.SubElement(svg_root, "circle", {
+ "cx": point["x"], "cy": point["y"], "data-series": group,
+ })
+ svg = ET.tostring(svg_root, encoding="unicode") + "\n"
+ pdf_body = _figure_preview_pdf(series)
contents = {
"plot_data.json": (json.dumps(plot_data, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"),
"plot_data.csv": ("series,x,y,x_row_id,y_row_id\n" + "".join(
diff --git a/tests/test_u4d_figure_serialization.py b/tests/test_u4d_figure_serialization.py
new file mode 100644
index 0000000..f8e1234
--- /dev/null
+++ b/tests/test_u4d_figure_serialization.py
@@ -0,0 +1,57 @@
+from io import BytesIO
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+import pytest
+from test_u23b_artifacts import _seed, _service
+
+from paperforge.publication_artifacts import FigureSpec, generate_figure
+from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger
+
+
+def test_figure_pdf_is_real_deterministic_renderable_preview(tmp_path: Path) -> None:
+ import pymupdf
+ from pypdf import PdfReader
+
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20")
+ _seed(service, metric="map", value="0.8", unit="score")
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(purpose="scientific"))
+ spec = FigureSpec(ledger_id=ledger["ledger_id"], x_metric="latency_ms", y_metric="map")
+ out = generate_figure(tmp_path, service.memory, spec)
+ path = tmp_path / "artifacts" / "figures" / out["figure_id"] / "figure.pdf"
+ original = path.read_bytes()
+ reader = PdfReader(BytesIO(original), strict=True)
+ assert len(reader.pages) == 1
+ assert "not publication ready" in reader.pages[0].extract_text()
+ assert b" re f" in reader.pages[0].get_contents().get_data()
+ with pymupdf.open(path) as pdf:
+ page = pdf[0]
+ assert page.get_drawings()
+ assert page.get_pixmap().samples.count(255) < len(page.get_pixmap().samples)
+ generate_figure(tmp_path, service.memory, spec)
+ assert path.read_bytes() == original
+ assert out["manifest"]["publication_ready"] is False
+
+@pytest.mark.parametrize("label", ['model" data-unexpected="yes', 'model<&>', "model'&\"
"])
+def test_figure_svg_labels_are_data_not_markup(tmp_path: Path, label: str) -> None:
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20", run={"model_id": label})
+ _seed(service, metric="map", value="0.8", unit="score", run={"model_id": label})
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(purpose="scientific"))
+ spec = FigureSpec(ledger_id=ledger["ledger_id"], figure_id="preview<&>",
+ x_metric="latency_ms", y_metric="map", series_by="model_id")
+ first = generate_figure(tmp_path, service.memory, spec)
+ path = tmp_path / "artifacts" / "figures" / first["figure_id"] / "figure.svg"
+ svg = ET.fromstring(path.read_bytes())
+ ns = {"svg": "http://www.w3.org/2000/svg"}
+ assert svg.find("svg:title", ns).text == "preview<&>"
+ circles = svg.findall("svg:circle", ns)
+ assert circles
+ for circle in circles:
+ assert circle.attrib["data-series"] == label
+ assert set(circle.attrib) == {"cx", "cy", "data-series"}
+ assert all(element.tag in {f"{{{ns['svg']}}}{name}" for name in ("svg", "title", "circle")}
+ for element in svg.iter())
+ second = generate_figure(tmp_path, service.memory, spec)
+ assert first["manifest"]["output_hashes"] == second["manifest"]["output_hashes"]
From 1f8668748fa963fdfc56cda269252e957c3b0353 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:32:21 +0800
Subject: [PATCH 21/30] fix: share conservative generated LaTeX validation
across updates
---
docs/u4d-final-execution.md | 19 ++++++
paperforge/grounded_narrative.py | 6 +-
paperforge/latex_safety.py | 25 ++++++++
paperforge/result_update.py | 8 +++
paperforge/writing.py | 6 +-
paperforge/writing_patch.py | 7 +--
tests/test_u4d_latex_policy.py | 99 ++++++++++++++++++++++++++++++++
7 files changed, 155 insertions(+), 15 deletions(-)
create mode 100644 paperforge/latex_safety.py
create mode 100644 tests/test_u4d_latex_policy.py
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 76d98b1..11efa86 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -160,3 +160,22 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
Ruff/mypy PASS, no HIGH/CRITICAL within this repair.
- Full regression: **764 collected, 759 passed, 5 skipped, 0 failed, 0 errors**;
Ruff PASS; mypy PASS (80 files). LaTeX policy repair is still open and blocks push.
+
+## Generated LaTeX guard checkpoint (2026-10-09)
+
+- Shared conservative policy now protects writing, prose patch, narrative, and
+ ResultUpdate build/apply, including historical proposals produced before the
+ new policy. Rejected operations preserve source bytes and approval state.
+- Red-first dynamic-command, encoded-input, file-stream and file-environment
+ cases initially failed. Independent review also reproduced the standard kernel
+ InputIfFileExists wrapper; it and common file-input wrappers are now rejected.
+ Review caught an overbroad math-subscript check; narrowed matching preserves
+ actual alpha/theta subscript patch use. **19 regressions pass**.
+- This is generated-source validation, not an arbitrary-TeX execution sandbox.
+ Existing source macros/packages remain trusted inputs. Compilation requires
+ explicit no-shell-escape and an isolated, least-privilege working directory;
+ source guard success is not a permission to execute untrusted TeX.
+- Independent scoped review approves. Latest full run: **783 collected,
+ 778 passed, 5 skipped, 0 failed, 0 errors**; Ruff PASS; mypy PASS (81 files).
+ Consolidated A9 review, documentation/build checks and remote reviews remain
+ pending; no push or tool freeze is claimed here.
diff --git a/paperforge/grounded_narrative.py b/paperforge/grounded_narrative.py
index 02384f1..85fb40a 100644
--- a/paperforge/grounded_narrative.py
+++ b/paperforge/grounded_narrative.py
@@ -9,6 +9,8 @@
from pathlib import Path
from typing import Any
+from .latex_safety import FORBIDDEN_LATEX as _FORBIDDEN_LATEX
+
NARRATIVE_SPEC_SCHEMA = "paperforge.grounded-narrative-spec/v1"
NARRATIVE_DRAFT_SCHEMA = "paperforge.grounded-narrative-draft/v1"
NARRATIVE_POLICY_VERSION = "paperforge.narrative-policy/v1"
@@ -25,10 +27,6 @@
_STRONG_RANKING = ("best overall", "superior", "dominates", "state-of-the-art", "best")
-_FORBIDDEN_LATEX = re.compile(
- r"\\(?:input|include|write18|openout|immediate|ShellEscape)\b", re.I
-)
-
_LAYER_ALLOWED = {
"simulated": ("simulated", "proxy", "under the simulation profile", "simulation profile"),
"remapped": ("remapped", "proxy", "under the disclosed transfer", "transfer rule", "remapping rule"),
diff --git a/paperforge/latex_safety.py b/paperforge/latex_safety.py
new file mode 100644
index 0000000..eac04c3
--- /dev/null
+++ b/paperforge/latex_safety.py
@@ -0,0 +1,25 @@
+"""Conservative generated-source guard; not a sandbox for arbitrary TeX.
+
+Original document macros/packages remain trusted inputs. Compilation must still
+run without shell escape in an isolated, least-privilege working directory.
+"""
+
+import re
+
+FORBIDDEN_LATEX = re.compile(
+ r"\^\^"
+ r"|\\[A-Za-z@]*@|\\[A-Za-z]+_[A-Za-z_]+:[A-Za-z]*"
+ r"|\\(?:input|include|includeonly|InputIfFileExists|IfFileExists|"
+ r"includegraphics|includepdf|verbatiminput|lstinputlisting|inputminted|"
+ r"CatchFileDef|CatchFileEdef|openin|openout|read|readline|write|write18|"
+ r"closein|closeout|immediate|ShellEscape|directlua|latelua|luaexec|special|"
+ r"csname|endcsname|catcode|mathcode|lccode|uccode|scantokens|"
+ r"def|edef|gdef|xdef|let|futurelet|expandafter|expanded|unexpanded|"
+ r"newcommand|renewcommand|providecommand|DeclareRobustCommand|"
+ r"newenvironment|renewenvironment|ExplSyntaxOn|makeatletter|"
+ r"pdfobj|pdfxform|pdfximage|pdffiledump|pdfextension)(?![A-Za-z@])"
+ r"|\\begin\s*\{\s*filecontents\*?\s*\}"
+ r"|\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\]\s*)?"
+ r"\{[^{}]*\bshellesc\b[^{}]*\}",
+ re.IGNORECASE,
+)
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index 6a52d02..61c0679 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -395,6 +395,10 @@ def build_proposal(
if PROTECTED_START not in proposed_block or PROTECTED_END not in proposed_block:
raise ResultUpdateValidationError("proposed block must preserve protected markers")
# Scope: only the indexed block may change.
+ from .latex_safety import FORBIDDEN_LATEX
+
+ if FORBIDDEN_LATEX.search(proposed_block):
+ raise ResultUpdateError("proposed block contains unsafe generated LaTeX")
candidate = current_text.replace(old_block, proposed_block, 1)
if candidate.count(PROTECTED_START) != current_text.count(PROTECTED_START):
raise ResultUpdateValidationError("protected marker count changed")
@@ -672,8 +676,12 @@ def _finish_applied(root: Path, memory: Any, proposal: Mapping[str, Any],
def apply_proposal(workspace: str | Path, memory: Any, proposal_id: str) -> dict[str, Any]:
+ from .latex_safety import FORBIDDEN_LATEX
+
root = Path(workspace).expanduser().resolve(strict=True)
proposal, spec, row = _load_update(root, memory, proposal_id)
+ if FORBIDDEN_LATEX.search(str(proposal["proposed_block"])):
+ raise ResultUpdateError("proposed block contains unsafe generated LaTeX")
approval = _approval_for_recovery(root, memory, proposal)
target = _resolve_target(root, spec["target_path"])
current_text = target.read_bytes().decode("utf-8")
diff --git a/paperforge/writing.py b/paperforge/writing.py
index 4ed7d8a..e9554fc 100644
--- a/paperforge/writing.py
+++ b/paperforge/writing.py
@@ -10,6 +10,7 @@
from engine.secret_redaction import contains_secret
from .artifacts import ArtifactRecord, ArtifactStore
+from .latex_safety import FORBIDDEN_LATEX as _FORBIDDEN_LATEX
from .path_safety import atomic_write_text, reject_symlink_components
from .protected_blocks import (
PROTECTED_END,
@@ -30,11 +31,6 @@
r"\\cite[a-zA-Z*]*\s*(?:\[[^\]]*\]\s*){0,2}\{([^{}]+)\}"
)
_BIB_ENTRY = re.compile(r"@\w+\s*\{\s*([^,\s]+)\s*,", re.IGNORECASE)
-_FORBIDDEN_LATEX = re.compile(
- r"\\(?:input|include|write18|openout|immediate|ShellEscape)\b"
- r"|\\usepackage(?:\[[^\]]*\])?\{shellesc\}",
- re.IGNORECASE,
-)
_EXPERIMENT_SECTION = re.compile(
r"\\(?:section|subsection|subsubsection)\*?\s*\{[^{}]*"
r"(?:experiment|evaluation|result|ablation|benchmark)[^{}]*\}",
diff --git a/paperforge/writing_patch.py b/paperforge/writing_patch.py
index 908011b..e3d5aa4 100644
--- a/paperforge/writing_patch.py
+++ b/paperforge/writing_patch.py
@@ -10,6 +10,7 @@
from engine.secret_redaction import contains_secret
from .artifacts import ArtifactRecord, ArtifactStore
+from .latex_safety import FORBIDDEN_LATEX as _FORBIDDEN_LATEX
from .path_safety import atomic_write_text, reject_symlink_components
from .protected_blocks import (
ProtectedBlockViolation,
@@ -25,12 +26,6 @@
)
from .writing import _strip_fence
-_FORBIDDEN_LATEX = re.compile(
- r"\\(?:input|include|write18|openout|immediate|ShellEscape)\b"
- r"|\\usepackage(?:\[[^\]]*\])?\{shellesc\}",
- re.IGNORECASE,
-)
-
class PatchError(RuntimeError):
pass
diff --git a/tests/test_u4d_latex_policy.py b/tests/test_u4d_latex_policy.py
new file mode 100644
index 0000000..e1d2267
--- /dev/null
+++ b/tests/test_u4d_latex_policy.py
@@ -0,0 +1,99 @@
+import hashlib
+import re
+from pathlib import Path
+
+import pytest
+from test_u1_patch import _document
+from test_u24a_finalization import _spec_with_table
+
+from paperforge.api import PaperForgeService
+from paperforge.grounded_narrative import (
+ NarrativeGroundingError,
+ NarrativeSentence,
+ render_narrative,
+)
+from paperforge.protected_blocks import extract_protected_blocks
+from paperforge.result_update import (
+ ResultUpdateError,
+ apply_proposal,
+ approve_proposal,
+ build_proposal,
+)
+from paperforge.writing import WritingEngine, WritingSafetyError
+from paperforge.writing_patch import PatchSafetyError, apply_patch
+
+REJECTED = (
+ r"\InputIfFileExists{fixture.tex}{}{}",
+ r"\IfFileExists{fixture.tex}{}{}",
+ r"\VerbatimInput{fixture.txt}",
+ r"\lstinputlisting{fixture.txt}",
+ r"\includegraphics{fixture.pdf}",
+ r"\@input{fixture.tex}",
+ r"\csname input\endcsname{fixture.tex}",
+ r"^^5cinput{fixture.tex}",
+ r"\catcode`\!=0 !input{fixture.tex}",
+ r"\def\loader{\input} Text.",
+ r"\let\loader\input Text.",
+ r"\openin1=fixture.tex",
+ r"\write1{fixture}",
+ r"\directlua{print('fixture')}",
+ r"\scantokens{fixture}",
+ r"\begin{filecontents}{fixture.txt}fixture\end{filecontents}",
+ r"\usepackage {shellesc}",
+)
+
+
+@pytest.mark.parametrize("text", REJECTED)
+def test_all_generated_tex_entrypoints_reject_dynamic_or_file_commands(tmp_path: Path, text: str) -> None:
+ original = _document("Original prose.")
+ tex = tmp_path / "paper.tex"
+ tex.write_text(original)
+ service = PaperForgeService(tmp_path)
+ with pytest.raises(PatchSafetyError, match="unsafe"):
+ apply_patch(tmp_path, memory=service.memory, request_text=lambda *a, **k: text,
+ run_id="fixture-run", target="paper.tex",
+ source_sha256=hashlib.sha256(tex.read_bytes()).hexdigest(), anchor="Original prose.")
+ assert tex.read_text() == original
+ with pytest.raises(WritingSafetyError, match="unsafe"):
+ WritingEngine._validate_candidate(_document(text),
+ protected_blocks=extract_protected_blocks(original),
+ bibliography_keys=frozenset())
+ with pytest.raises(NarrativeGroundingError, match="forbidden LaTeX"):
+ render_narrative([[NarrativeSentence("fixture", text, role="transition")]])
+ workspace = tmp_path / "proposal"
+ workspace.mkdir()
+ service, spec, old, _ = _spec_with_table(workspace, "Original prose.")
+ with pytest.raises(ResultUpdateError, match="unsafe"):
+ build_proposal(workspace, service.memory, spec, proposed_block=old.replace("Original prose.", text))
+ assert not (workspace / ".paperforge" / "result_updates").exists()
+
+
+def test_safe_math_and_formatting_patch_still_work(tmp_path: Path) -> None:
+ original = _document("Original prose.")
+ tex = tmp_path / "paper.tex"
+ tex.write_text(original)
+ service = PaperForgeService(tmp_path)
+ replacement = r"A \textbf{bounded} statement with $x^{2}+\alpha_1+\theta_{i}$ and \emph{no claim}."
+ apply_patch(tmp_path, memory=service.memory, request_text=lambda *a, **k: replacement,
+ run_id="fixture-run", target="paper.tex",
+ source_sha256=hashlib.sha256(tex.read_bytes()).hexdigest(), anchor="Original prose.")
+ assert replacement in tex.read_text()
+
+
+def test_historical_proposal_is_rechecked_before_apply(tmp_path: Path, monkeypatch) -> None:
+ from paperforge import latex_safety
+
+ service, spec, old, _ = _spec_with_table(tmp_path, "Original prose.")
+ original = (tmp_path / "paper.tex").read_bytes()
+ # Simulate a historical producer lacking the new policy, only in a test DB.
+ with monkeypatch.context() as legacy:
+ legacy.setattr(latex_safety, "FORBIDDEN_LATEX", re.compile(r"(?!)"))
+ proposal = build_proposal(tmp_path, service.memory, spec,
+ proposed_block=old.replace("Original prose.", r"\InputIfFileExists{fixture.tex}{}{}"))
+ approve_proposal(tmp_path, service.memory, proposal["proposal_id"], approver="fixture-owner")
+ with pytest.raises(ResultUpdateError, match="unsafe"):
+ apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ assert (tmp_path / "paper.tex").read_bytes() == original
+ with service.memory.connect() as db:
+ row = db.execute("SELECT state FROM result_updates WHERE id=?", (proposal["proposal_id"],)).fetchone()
+ assert row["state"] == "APPROVED"
From f7d8dd70c1fb9ff0f44e796305cce2991879f940 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:33:43 +0800
Subject: [PATCH 22/30] docs: record U4D final local push readiness and
limitations
---
README.md | 8 ++++++--
docs/u4c-reliability.md | 8 ++++++++
docs/u4d-final-execution.md | 41 +++++++++++++++++++++++++++++++------
docs/u4d-merge-readiness.md | 18 ++++++++++++++++
4 files changed, 67 insertions(+), 8 deletions(-)
diff --git a/README.md b/README.md
index 6a444bf..7638142 100644
--- a/README.md
+++ b/README.md
@@ -821,12 +821,16 @@ PaperForge/
### 质量检查
```bash
-python -m pytest -q
-python -m ruff check paperforge engine agents frontend tests
+python -m pytest tests -q
+python -m ruff check .
python -m mypy paperforge
python -m pip check
```
+U4D 本地验收与限制见 [执行及交接记录](docs/u4d-final-execution.md) 和
+[完整流程 smoke 报告](docs/u4d-final-smoke.md)。本地测试通过不等于远端审查通过、
+论文 Evidence 获批或已发布;U4C 仍仅覆盖单写者和受控进程终止,不宣称物理掉电或并发安全。
+
GitHub Actions 覆盖:
```text
diff --git a/docs/u4c-reliability.md b/docs/u4c-reliability.md
index e6d468e..61cadeb 100644
--- a/docs/u4c-reliability.md
+++ b/docs/u4c-reliability.md
@@ -1,5 +1,13 @@
# U4C reliability maintenance
+Current follow-up (2026-10-09): the U4D isolated Python 3.11 environment has
+resolved the missing-dependency/static-tool debt recorded below. Latest full
+suite: 778 passed, 5 opt-in compute skips, 0 failures/errors; Ruff/mypy pass.
+All 69 U4C tests remain passing. This does not expand the reliability guarantees:
+single-writer, quiesced repair and controlled termination only. See the
+[live U4D execution/handoff](u4d-final-execution.md) for current readiness;
+the original U4C results below are retained as historical evidence.
+
Source baseline: `7bc397ba3ed8a76383c7834a4bfd2b20856f0b80`.
Scope: crash/reopen/retry/reconcile only; no new scientific or release semantics.
No dependency installation, real manuscript changes, or push.
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 11efa86..0d819b2 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -22,12 +22,12 @@ of unpublished materials, paid resources, sudo, or system Python 3.14.
| Requirements | Evidence required | Current state |
|---|---|---|
-| A1 environment | Interpreter/venv/pip and declared dependency inspection | IN_PROGRESS |
-| A2 full tests | Full pytest, counts and failure classification | PENDING |
-| A3-A4 static | Existing Ruff whole-repository and mypy paperforge scope pass | PENDING |
-| A5 integration | End-to-end synthetic evidence-to-status FinalSmokeReport and negative boundaries | PENDING |
-| A6 reliability | ResultUpdate, actual kill/reopen, import reopen, split-brain | PENDING |
-| A7-A10 local readiness | Documentation, hygiene, security review, commits | PENDING |
+| A1 environment | Interpreter/venv/pip and declared dependency inspection | PASS; isolated Python 3.11.15, pip check clean |
+| A2 full tests | Full pytest, counts and failure classification | PASS; 778 passed, 5 opt-in skips, 0 failures/errors |
+| A3-A4 static | Existing Ruff whole-repository and mypy paperforge scope pass | PASS; Ruff ., mypy 81 files |
+| A5 integration | End-to-end synthetic evidence-to-status FinalSmokeReport and negative boundaries | PASS; no real human approval/release |
+| A6 reliability | ResultUpdate, actual kill/reopen, import reopen, split-brain | PASS_WITH_LIMITATIONS; all 69 U4C tests retained |
+| A7-A10 local readiness | Documentation, hygiene, security review, commits | PASS; scoped A9, docs/hygiene, build/wheel smoke |
| A11-A13 remote/freeze | Required local gates, authorized push, both review findings, fix/retest loop | PENDING |
| B0-B4 / P0 | Unique paper workspace, revision copy, baseline hashes, inventory, legal imports/ledger | PENDING_TOOL_FREEZE |
| C1-C7 / P1 | Layer guidance, bounded attribution, external validity, citation/PLC audit, layout, controlled patches | PENDING_TOOL_FREEZE |
@@ -179,3 +179,32 @@ The earlier U4C/U4D-Prep reports are historical evidence, not current gate resul
778 passed, 5 skipped, 0 failed, 0 errors**; Ruff PASS; mypy PASS (81 files).
Consolidated A9 review, documentation/build checks and remote reviews remain
pending; no push or tool freeze is claimed here.
+
+## Consolidated A9 review (2026-10-09)
+
+Independent reviewer approved `530d2f5..70ee8be` plus the exact LaTeX changes
+subsequently committed as `1f86687`. No still-open reproduced HIGH/CRITICAL was
+found within this batch. The reviewer independently ran **92 tests**, whole-scope
+Ruff and configured mypy (81 files). Closed findings are recorded in checkpoints
+above: publication/operation paths, import adapter and binding/currentness,
+SVG/PDF serialization, generated LaTeX and historical apply. This is a scoped
+local review, not a full historical-repository certification or remote review.
+
+## Local PushReadiness (2026-10-09)
+
+- All required local gates pass at code commit `1f86687`: full pytest 778/5/0/0
+ (passed/skipped/failed/errors), whole-scope Ruff, configured mypy, integration,
+ reliability and scoped A9 review. No fixture has become real-paper Evidence.
+- CI-pinned `build==1.2.2.post1` installed only in the same isolated environment;
+ `python -m build` produced sdist/wheel successfully. Official
+ `tools/verify_wheel.py` passed from an isolated temporary installation. Pip check
+ reports no broken requirements. Build products remain ignored, not staged.
+- README, U4C and U4D handoffs now distinguish current gates from historical
+ environment failures. Tracked changes at final documentation review are only
+ these four docs; the existing untracked private `.paperforge/` remains untouched.
+ No real paper, PDF pages, environment, cache, temporary DB or private log is
+ included. `git diff --check` passes. No merge/amend/history rewrite occurred.
+- Local status: **PUSH_READY_WITH_DOCUMENTED_LIMITATIONS**. Authorized branch
+ push is the next action. This is not tool freeze, remote review clearance,
+ merge authorization, scientific acceptance or publication release.
+- Remote automatic code/security reviews and all real-paper phases remain open.
diff --git a/docs/u4d-merge-readiness.md b/docs/u4d-merge-readiness.md
index 6d0b938..6ce1206 100644
--- a/docs/u4d-merge-readiness.md
+++ b/docs/u4d-merge-readiness.md
@@ -1,5 +1,23 @@
# U4D merge/release readiness preparation
+## Current update: 2026-10-09
+
+U4D Final is now in progress under the owner's batch authorization. The isolated
+Python 3.11 environment closes the earlier dependency blocker: **778 passed,
+5 opt-in skips, 0 failures/collection errors**, Ruff PASS, configured mypy PASS
+(81 files). Final integration and reliability smoke pass with the documented
+single-writer/controlled-termination limitations. Scoped local A9 review has no
+open reproduced HIGH/CRITICAL. Build, official wheel smoke and hygiene checks
+pass. Local status is **PUSH_READY_WITH_DOCUMENTED_LIMITATIONS**.
+
+No push, remote automatic review, tool freeze or real-paper revision is claimed
+yet. Follow the live [execution/handoff log](u4d-final-execution.md) and
+[FinalSmokeReport](u4d-final-smoke.md), not the historical blocked counts below.
+Push is conditionally authorized only after all local gates; each push still
+requires both exact-commit automatic reviews. Merge remains unauthorized.
+
+## Historical U4D-Prep inventory (unchanged evidence)
+
Inventory date: 2026-09-27. This is **U4D-Prep**, not final merge approval,
publication authorization, or a release announcement.
From 4506b8b95d78cd8647217cd833d4477dfb96df3c Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:39:34 +0800
Subject: [PATCH 23/30] ci: provision real Poppler renderer on each test
platform
---
.github/workflows/ci.yml | 21 ++++++++++++++++++++-
1 file changed, 20 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2856414..301f729 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -24,8 +24,27 @@ jobs:
- if: runner.os == 'Linux'
run: |
sudo apt-get update
- sudo apt-get install -y bubblewrap
+ sudo apt-get install -y bubblewrap poppler-utils
sudo chmod u+s "$(command -v bwrap)"
+ - if: runner.os == 'macOS'
+ run: brew install poppler
+ - if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ $archive = Join-Path $env:RUNNER_TEMP "poppler.zip"
+ $destination = Join-Path $env:RUNNER_TEMP "poppler"
+ Invoke-WebRequest "https://github.com/oschwartz10612/poppler-windows/releases/download/v26.09.0-0/Release-26.09.0-0.zip" -OutFile $archive
+ $expected = "7a6f256a0ddf7536182246a5733331bf4677cbcc34f4663774947ad34556c8d0"
+ if ((Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) {
+ throw "Poppler archive checksum mismatch"
+ }
+ Expand-Archive $archive -DestinationPath $destination
+ $bin = Join-Path $destination "poppler-26.09.0/Library/bin"
+ if (-not (Test-Path (Join-Path $bin "pdftoppm.exe"))) {
+ throw "Poppler renderer missing from verified archive"
+ }
+ $bin | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
+ - run: pdftoppm -v
- run: python -m pip install --upgrade pip
- run: python -m pip install -r requirements-dev.txt
- run: python -m pip check
From e5f92a64ffffb60aa31d02f5b195e3efe0e10c33 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:51:29 +0800
Subject: [PATCH 24/30] fix: bind generated artifacts to valid ledgers and
source semantics
---
paperforge/publication_artifacts.py | 66 ++++++++++++++++-----
tests/test_u4d_review_artifact_integrity.py | 27 +++++++++
tests/test_u4d_review_fact_semantics.py | 62 +++++++++++++++++++
tests/test_u4d_review_figure_identity.py | 33 +++++++++++
4 files changed, 174 insertions(+), 14 deletions(-)
create mode 100644 tests/test_u4d_review_artifact_integrity.py
create mode 100644 tests/test_u4d_review_fact_semantics.py
create mode 100644 tests/test_u4d_review_figure_identity.py
diff --git a/paperforge/publication_artifacts.py b/paperforge/publication_artifacts.py
index c117fb8..f27e7fc 100644
--- a/paperforge/publication_artifacts.py
+++ b/paperforge/publication_artifacts.py
@@ -9,11 +9,11 @@
from typing import Any
from xml.etree import ElementTree as ET
-from .path_safety import atomic_write_bytes, safe_output_path
+from .path_safety import atomic_write_bytes, reject_symlink_components, safe_output_path
TABLE_GENERATOR_VERSION = "paperforge.table-generator/v1"
FIGURE_GENERATOR_VERSION = "paperforge.figure-generator/v2"
-FACT_GENERATOR_VERSION = "paperforge.fact-generator/v1"
+FACT_GENERATOR_VERSION = "paperforge.fact-generator/v2"
_BANNED_FACT_WORDS = (
"statistically significant", "equivalent", "robust",
@@ -256,11 +256,22 @@ def digest(self) -> str:
return _spec_digest(self.to_canonical())
-def _load_ledger(root: Path, ledger_id: str) -> dict[str, Any]:
- path = root / ".paperforge" / "ledgers" / ledger_id / "ledger.json"
+def _load_ledger(root: Path, memory: Any, ledger_id: str) -> dict[str, Any]:
+ from .result_ledger import verify_ledger
+
+ _bundle_path("ledgers", ledger_id)
+ relative = Path(".paperforge") / "ledgers" / ledger_id
+ path = reject_symlink_components(root / relative / "ledger.json", anchor=root)
+ reject_symlink_components(root / relative / "manifest.json", anchor=root)
if not path.is_file():
raise PublicationArtifactError(f"ledger missing: {ledger_id}")
- return json.loads(path.read_bytes().decode("utf-8"))
+ verification = verify_ledger(root, memory, ledger_id)
+ if not verification.get("eligible_as_release_input"):
+ raise PublicationArtifactError(f"ledger integrity/currentness invalid: {ledger_id}")
+ data = path.read_bytes()
+ if hashlib.sha256(data).hexdigest() != verification.get("ledger_file_sha256"):
+ raise PublicationArtifactError(f"ledger changed during validation: {ledger_id}")
+ return json.loads(data.decode("utf-8"))
def _ledger_rows(ledger: Mapping[str, Any]) -> list[dict[str, Any]]:
@@ -294,7 +305,7 @@ def generate_table(
workspace: str | Path, memory: Any, spec: TableSpec, *, run_id: str | None = None
) -> dict[str, Any]:
root = Path(workspace).expanduser().resolve(strict=True)
- ledger = _load_ledger(root, spec.ledger_id)
+ ledger = _load_ledger(root, memory, spec.ledger_id)
rows = _ledger_rows(ledger)
by_id = {str(r.get("row_id")): r for r in rows}
selected = [by_id[rid] for rid in spec.row_ids if rid in by_id] if spec.row_ids else list(rows)
@@ -405,7 +416,7 @@ def generate_figure(
workspace: str | Path, memory: Any, spec: FigureSpec, *, run_id: str | None = None
) -> dict[str, Any]:
root = Path(workspace).expanduser().resolve(strict=True)
- ledger = _load_ledger(root, spec.ledger_id)
+ ledger = _load_ledger(root, memory, spec.ledger_id)
rows = _ledger_rows(ledger)
# Filters: exact match on run_identity fields + metric presence.
points: list[dict[str, Any]] = []
@@ -422,14 +433,17 @@ def generate_figure(
for y in sorted(y_rows, key=lambda r: str(r.get("row_id"))):
identity = dict(y.get("run_identity") or {})
group = str(identity.get(spec.series_by) or y.get("measurement_kind") or "default")
- # Find matching x with same model/seed/device (excluding metric).
- match = next((
+ # Never join observations across unlisted run dimensions or layers.
+ matches = [
x for x in x_rows
- if all(str((dict(x.get("run_identity") or {})).get(k) or "") == str(identity.get(k) or "")
- for k in ("model_id", "seed", "device_id", "precision", "input_size"))
- ), None)
- if match is None:
+ if dict(x.get("run_identity") or {}) == identity
+ and x.get("measurement_kind") == y.get("measurement_kind")
+ ]
+ if not matches:
continue
+ if len(matches) != 1:
+ raise PublicationArtifactError(f"ambiguous x observations for y row {y.get('row_id')}")
+ match = matches[0]
series.setdefault(group, []).append({
"x": str(match.get("value_str")), "y": str(y.get("value_str")),
"x_row_id": str(match.get("row_id")), "y_row_id": str(y.get("row_id")),
@@ -486,11 +500,25 @@ def generate_figure(
return {"figure_id": figure_id, "spec_digest": spec_digest, "manifest": manifest}
+def _fact_source_metadata(row: Mapping[str, Any], qualifiers: Mapping[str, Any]) -> dict[str, Any]:
+ identity = dict(row.get("run_identity") or {})
+ bound = {key: value for key, value in identity.items() if key != "schema"}
+ bound["measurement_kind"] = str(row.get("measurement_kind") or "")
+ for alias, canonical in {"dataset": "dataset_id", "split": "split_sha256",
+ "checkpoint": "checkpoint_sha256", "device": "device_id"}.items():
+ bound[alias] = identity.get(canonical, "")
+ for key, value in qualifiers.items():
+ if key in bound and str(value) != str(bound[key]):
+ raise PublicationArtifactError(f"fact qualifier conflicts with source identity: {key}")
+ return {"run_identity": identity, "measurement_kind": bound["measurement_kind"],
+ "qualifiers": {**dict(qualifiers), **bound}}
+
+
def generate_facts(
workspace: str | Path, memory: Any, spec: FactSummarySpec, *, run_id: str | None = None
) -> dict[str, Any]:
root = Path(workspace).expanduser().resolve(strict=True)
- ledger = _load_ledger(root, spec.ledger_id)
+ ledger = _load_ledger(root, memory, spec.ledger_id)
rows = {str(r.get("row_id")): r for r in _ledger_rows(ledger)}
for text in (spec.fact_id,):
for banned in _BANNED_FACT_WORDS:
@@ -511,6 +539,7 @@ def generate_facts(
"lineage": row.get("lineage"),
"presentation_hint": None,
}
+ fact.update(_fact_source_metadata(row, spec.qualifiers))
elif spec.kind == "delta":
base, compare = rows.get(spec.base_row_id), rows.get(spec.compare_row_id)
if base is None or compare is None:
@@ -519,6 +548,12 @@ def generate_facts(
raise PublicationArtifactError("delta requires same metric/unit")
if base.get("value_str") is None or compare.get("value_str") is None:
raise PublicationArtifactError("delta requires present values")
+ base_identity = dict(base.get("run_identity") or {})
+ compare_identity = dict(compare.get("run_identity") or {})
+ dimensions = (set(base_identity) | set(compare_identity)) - {"model_id", "checkpoint_sha256"}
+ if (base.get("measurement_kind") != compare.get("measurement_kind")
+ or any(base_identity.get(k) != compare_identity.get(k) for k in dimensions)):
+ raise PublicationArtifactError("delta requires compatible run identity and evidence layer")
delta = Decimal(str(base["value_str"])) - Decimal(str(compare["value_str"]))
fact = {
"fact_id": spec.fact_id or f"fact-delta-{hashlib.sha256((spec.base_row_id + spec.compare_row_id).encode()).hexdigest()[:12]}",
@@ -533,6 +568,8 @@ def generate_facts(
"lineage": [base.get("lineage"), compare.get("lineage")],
"presentation_hint": None,
}
+ fact.update(_fact_source_metadata(base, spec.qualifiers))
+ fact["source_run_identities"] = [base_identity, compare_identity]
elif spec.kind in {"aggregation", "provenance"}:
row = rows.get(spec.row_id)
if row is None:
@@ -545,6 +582,7 @@ def generate_facts(
"evidence_ids": list(row.get("source_evidence_ids") or []),
"lineage": row.get("lineage"), "presentation_hint": None,
}
+ fact.update(_fact_source_metadata(row, spec.qualifiers))
else:
raise PublicationArtifactError(f"unknown fact kind: {spec.kind}")
spec_digest = spec.digest()
diff --git a/tests/test_u4d_review_artifact_integrity.py b/tests/test_u4d_review_artifact_integrity.py
new file mode 100644
index 0000000..429d142
--- /dev/null
+++ b/tests/test_u4d_review_artifact_integrity.py
@@ -0,0 +1,27 @@
+import json
+
+import pytest
+from test_u4d_artifact_write_safety import _generator
+from test_u23b_artifacts import _ledger_three_layers
+
+from paperforge.publication_artifacts import PublicationArtifactError
+
+
+@pytest.mark.parametrize("kind", ["tables", "figures", "facts"])
+@pytest.mark.parametrize("damage", ["ledger", "registry", "source"])
+def test_generators_refuse_damaged_or_stale_ledger(tmp_path, kind, damage):
+ service, ledger = _ledger_three_layers(tmp_path)
+ path = tmp_path / ".paperforge" / "ledgers" / ledger["ledger_id"] / "ledger.json"
+ if damage == "ledger":
+ payload = json.loads(path.read_text())
+ payload["detail_rows"][0]["value_str"] = "999"
+ path.write_text(json.dumps(payload))
+ elif damage == "registry":
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM artifacts WHERE path=?", (path.relative_to(tmp_path).as_posix(),))
+ else:
+ with service.memory.connect() as db:
+ db.execute("DELETE FROM evidence WHERE id=?", (ledger["snapshots"][0]["evidence_id"],))
+ with pytest.raises(PublicationArtifactError, match="ledger"):
+ _generator(tmp_path, service, ledger, kind)()
+ assert not (tmp_path / "artifacts" / kind).exists()
diff --git a/tests/test_u4d_review_fact_semantics.py b/tests/test_u4d_review_fact_semantics.py
new file mode 100644
index 0000000..3e3636c
--- /dev/null
+++ b/tests/test_u4d_review_fact_semantics.py
@@ -0,0 +1,62 @@
+import pytest
+from test_u23b_artifacts import _ledger_three_layers, _seed, _service
+
+from paperforge.grounded_narrative import (
+ GroundedNarrativeSpec,
+ NarrativeGroundingError,
+ NarrativeSentence,
+ validate_narrative,
+)
+from paperforge.publication_artifacts import (
+ FactSummarySpec,
+ PublicationArtifactError,
+ generate_facts,
+)
+from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger
+from paperforge.scientific_review import ScientificClaim, check_comparison_compatibility
+
+
+@pytest.mark.parametrize("kind", ["metric", "aggregation", "provenance"])
+def test_generated_facts_preserve_layer_and_identity(tmp_path, kind):
+ service, ledger = _ledger_three_layers(tmp_path)
+ row = next(r for r in ledger["detail_rows"] if r["measurement_kind"] == "remapped")
+ fact = generate_facts(tmp_path, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], row_id=row["row_id"], kind=kind))["fact"]
+ assert fact["measurement_kind"] == "remapped"
+ assert fact["run_identity"] == row["run_identity"]
+ with pytest.raises(NarrativeGroundingError, match="layer wording"):
+ validate_narrative(GroundedNarrativeSpec(allowed_fact_ids=(fact["fact_id"],)),
+ [[NarrativeSentence("claim", "Physical device measurement.",
+ fact_ids=(fact["fact_id"],))]], facts=[fact])
+
+
+def test_generated_fact_comparison_detects_different_dataset(tmp_path):
+ service = _service(tmp_path)
+ _seed(service, value="20", run={"dataset_id": "a"})
+ _seed(service, value="22", run={"dataset_id": "b"})
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery())
+ facts = [generate_facts(tmp_path, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], row_id=row["row_id"]))["fact"] for row in ledger["detail_rows"]]
+ result = check_comparison_compatibility(ScientificClaim(
+ "claim", "Comparison under the same protocol.", "comparison",
+ fact_ids=tuple(f["fact_id"] for f in facts)), {f["fact_id"]: f for f in facts})
+ assert result.status == "failed"
+
+
+def test_fact_qualifiers_cannot_override_source_identity(tmp_path):
+ service, ledger = _ledger_three_layers(tmp_path)
+ row = ledger["detail_rows"][0]
+ with pytest.raises(PublicationArtifactError, match="qualifier"):
+ generate_facts(tmp_path, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], row_id=row["row_id"], qualifiers={"dataset": "different"}))
+
+
+def test_delta_refuses_different_datasets(tmp_path):
+ service = _service(tmp_path)
+ _seed(service, value="20", run={"dataset_id": "a"})
+ _seed(service, value="22", run={"dataset_id": "b"})
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery())
+ a, b = ledger["detail_rows"]
+ with pytest.raises(PublicationArtifactError, match="identity"):
+ generate_facts(tmp_path, service.memory, FactSummarySpec(
+ ledger_id=ledger["ledger_id"], kind="delta", base_row_id=a["row_id"], compare_row_id=b["row_id"]))
diff --git a/tests/test_u4d_review_figure_identity.py b/tests/test_u4d_review_figure_identity.py
new file mode 100644
index 0000000..cec6907
--- /dev/null
+++ b/tests/test_u4d_review_figure_identity.py
@@ -0,0 +1,33 @@
+import json
+
+import pytest
+from test_u23b_artifacts import _seed, _service
+
+from paperforge.publication_artifacts import FigureSpec, PublicationArtifactError, generate_figure
+from paperforge.result_ledger import AggregationSpec, ResultLedgerQuery, freeze_ledger
+
+
+@pytest.mark.parametrize("dimension", [
+ "dataset_id", "split_sha256", "checkpoint_sha256", "runtime", "runtime_version",
+ "batch_size", "timing_scope",
+])
+def test_figure_never_pairs_different_run_conditions(tmp_path, dimension):
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20", run={dimension: "a"})
+ _seed(service, metric="map", value="0.8", unit="score", run={dimension: "b"})
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(purpose="scientific"))
+ out = generate_figure(tmp_path, service.memory, FigureSpec(
+ ledger_id=ledger["ledger_id"], x_metric="latency_ms", y_metric="map"))
+ data = json.loads((tmp_path / "artifacts/figures" / out["figure_id"] / "plot_data.json").read_text())
+ assert data["series"] == {}
+
+
+def test_figure_rejects_ambiguous_x_observations(tmp_path):
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20")
+ _seed(service, metric="map", value="0.8", unit="score")
+ ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(
+ purpose="scientific", aggregations=(AggregationSpec(metric="latency_ms"),)))
+ with pytest.raises(PublicationArtifactError, match="ambiguous"):
+ generate_figure(tmp_path, service.memory, FigureSpec(
+ ledger_id=ledger["ledger_id"], x_metric="latency_ms", y_metric="map"))
From 2c598959824f2f0602d42d00b146cc7151f8261e Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:51:30 +0800
Subject: [PATCH 25/30] fix: require complete artifact and numeric occurrence
bindings
---
paperforge/result_update.py | 19 ++++++++++--
tests/test_u4d_review_update_bindings.py | 38 ++++++++++++++++++++++++
2 files changed, 54 insertions(+), 3 deletions(-)
create mode 100644 tests/test_u4d_review_update_bindings.py
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index 61c0679..87f7e1c 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -4,6 +4,7 @@
import hashlib
import json
import re
+from collections import Counter
from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass
from pathlib import Path
@@ -228,11 +229,13 @@ def _collect_artifact_hashes(root: Path, spec: ResultUpdateSpec) -> dict[str, di
"""Hash every real file byte under bound artifacts (ID alone never binds)."""
collected: dict[str, dict[str, str]] = {}
for key, directory in _artifact_directories(root, spec).items():
+ reject_symlink_components(directory, anchor=root)
if not directory.is_dir():
raise ResultUpdateValidationError(f"bound artifact missing: {key}")
files: dict[str, str] = {}
for child in sorted(directory.rglob("*")):
- if child.is_symlink() or not child.is_file():
+ reject_symlink_components(child, anchor=root)
+ if not child.is_file():
continue
rel = child.relative_to(directory).as_posix()
files[rel] = hashlib.sha256(child.read_bytes()).hexdigest()
@@ -249,6 +252,11 @@ def verify_bound_artifact_integrity(
"""Verify real file bytes + ArtifactStore records + manifest consistency."""
root = Path(workspace).expanduser().resolve(strict=True)
current = _collect_artifact_hashes(root, spec)
+ if expected is not None and (set(current) != set(expected) or any(
+ not isinstance(expected[key], Mapping) or set(files) != set(expected[key])
+ for key, files in current.items()
+ )):
+ raise ResultUpdateApprovalError("bound artifact member set changed")
results: list[dict[str, Any]] = []
with memory.connect() as db:
for key, files in current.items():
@@ -417,9 +425,14 @@ def build_proposal(
protocol_allow = {(str(p.get("name") or "").strip().lower(), str(p.get("unit") or "").strip().lower()): dict(p)
for p in spec.allowed_protocol_values}
old_classified = _classify_candidates(old_block)
- old_texts = {c["text"] for c in old_classified if c["kind"] in {"metric", "protocol"}}
+ old_occurrences = Counter((c["kind"], c["text"]) for c in old_classified
+ if c["kind"] in {"metric", "protocol"})
for cand in _classify_candidates(proposed_block):
- if cand["kind"] == "structural" or cand["text"] in old_texts:
+ if cand["kind"] == "structural":
+ continue
+ occurrence_key = (cand["kind"], cand["text"])
+ if old_occurrences[occurrence_key] > 0:
+ old_occurrences[occurrence_key] -= 1
continue
if cand["kind"] == "metric":
matched = None
diff --git a/tests/test_u4d_review_update_bindings.py b/tests/test_u4d_review_update_bindings.py
new file mode 100644
index 0000000..2904ae0
--- /dev/null
+++ b/tests/test_u4d_review_update_bindings.py
@@ -0,0 +1,38 @@
+import pytest
+from test_u24a_finalization import _fact, _spec_with_table
+
+from paperforge.result_update import (
+ ResultUpdateApprovalError,
+ ResultUpdateValidationError,
+ apply_proposal,
+ approve_proposal,
+ build_proposal,
+)
+
+
+@pytest.mark.parametrize("phase", ["approve", "apply"])
+def test_missing_bound_artifact_member_refuses_update(tmp_path, phase):
+ service, spec, old, table = _spec_with_table(tmp_path, "Old result 20.0 ms.")
+ prop = build_proposal(tmp_path, service.memory, spec,
+ proposed_block=old.replace("20.0", "22.4"), facts_used=[_fact()])
+ if phase == "apply":
+ approve_proposal(tmp_path, service.memory, prop["proposal_id"], approver="fixture-owner")
+ source = (tmp_path / "paper.tex").read_bytes()
+ (tmp_path / "artifacts/tables" / table / "table.tex").unlink()
+ with pytest.raises(ResultUpdateApprovalError, match="bound artifact"):
+ if phase == "approve":
+ approve_proposal(tmp_path, service.memory, prop["proposal_id"], approver="fixture-owner")
+ else:
+ apply_proposal(tmp_path, service.memory, prop["proposal_id"])
+ assert (tmp_path / "paper.tex").read_bytes() == source
+
+
+@pytest.mark.parametrize("claim,error", [
+ ("Latency was 20.0 ms.", "UNBOUND_SCIENTIFIC_VALUE"),
+ ("Training used 300 epochs.", "UNBOUND_PROTOCOL_VALUE"),
+])
+def test_duplicated_old_value_requires_new_binding(tmp_path, claim, error):
+ service, spec, old, _ = _spec_with_table(tmp_path, claim)
+ with pytest.raises(ResultUpdateValidationError, match=error):
+ build_proposal(tmp_path, service.memory, spec,
+ proposed_block=old.replace(claim, claim + " Another device: " + claim), facts_used=[])
From 761bfa7f9f99f1aaf3ce6b2331d2c96c911025a8 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:51:30 +0800
Subject: [PATCH 26/30] fix: preserve pending human gates and verify current
PDF bytes
---
paperforge/pdf_qa.py | 44 ++++++++++++------
tests/test_u4d_review_pdf_currentness.py | 57 ++++++++++++++++++++++++
2 files changed, 88 insertions(+), 13 deletions(-)
create mode 100644 tests/test_u4d_review_pdf_currentness.py
diff --git a/paperforge/pdf_qa.py b/paperforge/pdf_qa.py
index bc1de15..8aa9c27 100644
--- a/paperforge/pdf_qa.py
+++ b/paperforge/pdf_qa.py
@@ -9,7 +9,7 @@
from typing import Any
from .models import utc_now
-from .path_safety import safe_mkdir
+from .path_safety import UnsafePathError, reject_symlink_components, safe_mkdir
QA_SPEC_SCHEMA = "paperforge.pdf-qa-spec/v1"
QA_POLICY_SCHEMA = "paperforge.pdf-qa-policy/v1"
@@ -101,7 +101,7 @@ def _canonical(payload: Mapping[str, Any]) -> bytes:
def _resolve_pdf(root: Path, rel: str) -> Path:
- candidate = (root / rel).resolve()
+ candidate = reject_symlink_components(root / rel, anchor=root).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
@@ -490,7 +490,8 @@ def run_pdf_qa(
critical = [i for i in issues if i.get("severity") == "critical" and i.get("status") == "open"]
needs_human = [i for i in issues if i.get("status") == "needs_human"]
pages = {r["page"] for r in renders}
- reviewed_any = {r.get("page") for r in human_records if not r.get("stale")}
+ reviewed_any = {r.get("page") for r in human_records if not r.get("stale")
+ and r.get("status") in {"passed", "passed_with_warnings"}}
if critical or any(r.get("status") == "failed" for r in human_records):
state = "failed"
elif needs_human or pages - reviewed_any:
@@ -554,7 +555,10 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
from pathlib import Path as _Path
root = _Path(workspace).expanduser().resolve(strict=True)
- bundle_path = root / ".paperforge" / "pdf_qa" / bundle_id / "qa.json"
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", bundle_id):
+ raise PdfQaError("unsafe QA bundle ID")
+ bundle_path = reject_symlink_components(
+ root / ".paperforge" / "pdf_qa" / bundle_id / "qa.json", anchor=root)
if not bundle_path.is_file():
raise PdfQaError(f"QA bundle missing: {bundle_id}")
raw = bundle_path.read_bytes()
@@ -566,9 +570,22 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
stored = str(payload.get("qa_digest") or "")
stable = {k: payload[k] for k in payload if k not in {"bundle_id", "qa_digest", "created_at", "qa_file_sha256"}}
digest_valid = stored == hashlib.sha256(_canonical(stable)).hexdigest()
- # Target PDF still matches?
- target_match = True
- historical = "valid" if digest_valid else "invalid"
+ # The immutable spec binds the target path; historical QA does not imply
+ # that today's PDF is still the reviewed file.
+ spec_valid = False
+ target_match = False
+ spec_payload: dict[str, Any] = {}
+ try:
+ spec_path = reject_symlink_components(bundle_path.with_name("spec.json"), anchor=root)
+ spec_payload = json.loads(spec_path.read_bytes())
+ spec_valid = isinstance(spec_payload, dict) and (
+ hashlib.sha256(_canonical(spec_payload)).hexdigest() == payload.get("spec_digest"))
+ if spec_valid:
+ target = _resolve_pdf(root, str(spec_payload.get("target_pdf_path") or ""))
+ target_match = hashlib.sha256(target.read_bytes()).hexdigest() == payload.get("target_pdf_sha256")
+ except (OSError, ValueError, TypeError, PdfQaError, UnsafePathError):
+ target_match = False
+ historical = "valid" if digest_valid and spec_valid else "invalid"
# Human/render currentness sampled from stored hashes (no recomputation of renders here).
unresolved_critical = list(payload.get("unresolved_critical") or [])
state = str(payload.get("layout_qa_state") or "")
@@ -577,7 +594,7 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
registry = verify_registered_bundle(root, memory, {
f".paperforge/pdf_qa/{bundle_id}/qa.json": "review",
f".paperforge/pdf_qa/{bundle_id}/manifest.json": "manifest"})
- currently_valid = bool(historical == "valid" and registry["registered_complete"])
+ currently_valid = bool(historical == "valid" and target_match and registry["registered_complete"])
return {
**registry,
"bundle_id": bundle_id,
@@ -585,10 +602,10 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
"bundle_file_integrity": "valid",
"qa_digest_valid": digest_valid,
"target_pdf_hash_match": target_match,
- "build_currentness": True,
- "policy_match": True,
- "render_currentness": "current",
- "human_review_currentness": "current",
+ "build_currentness": target_match and spec_valid,
+ "policy_match": spec_valid and spec_payload.get("qa_policy") == payload.get("qa_policy"),
+ "render_currentness": "current" if currently_valid else "stale",
+ "human_review_currentness": "current" if currently_valid else "stale",
"unresolved_critical": unresolved_critical,
"unresolved_warnings": list(payload.get("unresolved_warnings") or []),
"page_coverage_complete": bool(payload.get("page_coverage_complete")),
@@ -596,7 +613,8 @@ def verify_pdf_qa(workspace: str | Path, memory: Any, bundle_id: str) -> dict[st
"currently_valid": currently_valid,
"layout_qa_state": state,
"eligible_as_layout_qa_input": currently_valid,
- "warnings": [] if historical == "valid" else ["QA file or digest mismatch"],
+ "warnings": ([] if historical == "valid" else ["QA file/spec or digest mismatch"])
+ + ([] if target_match else ["target PDF is missing, unsafe, or changed"]),
}
diff --git a/tests/test_u4d_review_pdf_currentness.py b/tests/test_u4d_review_pdf_currentness.py
new file mode 100644
index 0000000..52ef366
--- /dev/null
+++ b/tests/test_u4d_review_pdf_currentness.py
@@ -0,0 +1,57 @@
+import hashlib
+import json
+
+import pytest
+from test_u3b2_finalization import _pdf, _service
+
+from paperforge.pdf_qa import HumanPageReview, PDFQASpec, run_pdf_qa, verify_pdf_qa
+
+
+def _qa(tmp_path):
+ service = _service(tmp_path)
+ data = _pdf([[(12, "Fixture page")]])
+ target = tmp_path / "fixture.pdf"
+ target.write_bytes(data)
+ spec = PDFQASpec(target_pdf_path="fixture.pdf", target_pdf_sha256=hashlib.sha256(data).hexdigest())
+ auto = run_pdf_qa(tmp_path, service.memory, spec)
+ return service, target, spec, auto
+
+
+def test_pending_human_record_never_completes_coverage(tmp_path):
+ service, _, spec, auto = _qa(tmp_path)
+ pending = HumanPageReview(pdf_sha256=spec.target_pdf_sha256, page=1,
+ render_sha256=auto["render_manifest"][0]["image_hash"])
+ result = run_pdf_qa(tmp_path, service.memory, spec, human_reviews=[pending])
+ assert result["layout_qa_state"] == "needs_human"
+ assert result["page_coverage_complete"] is False
+
+
+@pytest.mark.parametrize("change", ["replace", "delete", "link", "spec"])
+def test_pdf_qa_verifier_checks_current_target_and_bound_spec(tmp_path, change):
+ service, target, _, auto = _qa(tmp_path)
+ bundle = tmp_path / ".paperforge/pdf_qa" / auto["bundle_id"]
+ frozen = (bundle / "qa.json").read_bytes()
+ assert verify_pdf_qa(tmp_path, service.memory, auto["bundle_id"])["currently_valid"] is True
+ if change == "replace":
+ target.write_bytes(_pdf([[(12, "Changed page")]]))
+ elif change == "delete":
+ target.unlink()
+ elif change == "link":
+ duplicate = tmp_path / "duplicate.pdf"
+ duplicate.write_bytes(target.read_bytes())
+ target.unlink()
+ target.symlink_to(duplicate)
+ else:
+ spec_path = bundle / "spec.json"
+ spec = json.loads(spec_path.read_text())
+ spec["target_pdf_path"] = "missing.pdf"
+ spec_path.write_text(json.dumps(spec))
+ result = verify_pdf_qa(tmp_path, service.memory, auto["bundle_id"])
+ assert result["currently_valid"] is False
+ assert result["target_pdf_hash_match"] is False
+ assert result["render_currentness"] != "current"
+ assert result["human_review_currentness"] != "current"
+ assert result["eligible_as_layout_qa_input"] is False
+ assert (bundle / "qa.json").read_bytes() == frozen
+ if change != "spec":
+ assert result["historical_integrity"] == "valid"
From 0c9c9f7351d912b5d0dd383a86e01eef8eecc3a1 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:58:43 +0800
Subject: [PATCH 27/30] fix: preserve source bytes and portable paths on
Windows
---
paperforge/path_safety.py | 22 +------
paperforge/result_ledger.py | 6 +-
paperforge/result_update.py | 2 +-
paperforge/writing_patch.py | 4 +-
tests/test_u24a_finalization.py | 12 ++--
tests/test_u24a_result_update.py | 8 +--
tests/test_u4d_crlf_sources.py | 85 ++++++++++++++++++++++++++
tests/test_u4d_figure_serialization.py | 4 +-
tests/test_u4d_import_ledger.py | 18 ++++++
9 files changed, 124 insertions(+), 37 deletions(-)
create mode 100644 tests/test_u4d_crlf_sources.py
diff --git a/paperforge/path_safety.py b/paperforge/path_safety.py
index c7e0d97..1d2fe26 100644
--- a/paperforge/path_safety.py
+++ b/paperforge/path_safety.py
@@ -163,26 +163,8 @@ def atomic_write_text(
*,
encoding: str = "utf-8",
) -> Path:
- target = safe_output_path(workspace, relative_path)
- temporary: str | None = None
- try:
- with tempfile.NamedTemporaryFile(
- mode="w",
- encoding=encoding,
- dir=target.parent,
- prefix=f".{target.name}.",
- delete=False,
- ) as stream:
- stream.write(content)
- stream.flush()
- os.fsync(stream.fileno())
- temporary = stream.name
- os.replace(temporary, target)
- temporary = None
- finally:
- if temporary is not None:
- Path(temporary).unlink(missing_ok=True)
- return target
+ # Source and artifact digests bind exact bytes on every platform.
+ return atomic_write_bytes(workspace, relative_path, content.encode(encoding))
def atomic_write_bytes(
diff --git a/paperforge/result_ledger.py b/paperforge/result_ledger.py
index 8aa091b..f4f7c75 100644
--- a/paperforge/result_ledger.py
+++ b/paperforge/result_ledger.py
@@ -370,11 +370,13 @@ def _imported_metric_snapshots(
base = root / ".paperforge" / "imports" / import_id
manifest_path = reject_symlink_components(base / "manifest.json", anchor=root)
manifest = json.loads(manifest_path.read_bytes())
- source_relative = Path(str(metadata.get("source_relpath") or ""))
+ raw_source_relative = str(metadata.get("source_relpath") or "")
+ source_relative = Path(raw_source_relative)
if (source_relative.is_absolute() or len(source_relative.parts) != 2
or source_relative.parts[0] != "sources"
or any(p in {".", ".."} for p in source_relative.parts)
- or "\\" in str(source_relative)):
+ or "\\" in raw_source_relative or ":" in raw_source_relative
+ or raw_source_relative != source_relative.as_posix()):
raise LedgerError("invalid imported metric source path")
source = reject_symlink_components(base / source_relative, anchor=root)
source_bytes = source.read_bytes()
diff --git a/paperforge/result_update.py b/paperforge/result_update.py
index 87f7e1c..24c85aa 100644
--- a/paperforge/result_update.py
+++ b/paperforge/result_update.py
@@ -387,7 +387,7 @@ def build_proposal(
"""Create a proposal without touching the target file."""
root = Path(workspace).expanduser().resolve(strict=True)
target = _resolve_target(root, spec.target_path)
- current_text = target.read_text(encoding="utf-8")
+ current_text = target.read_bytes().decode("utf-8")
current_sha = _sha256_str(current_text)
if current_sha != spec.target_source_sha256:
raise ResultUpdateValidationError("target source changed (stale source hash)")
diff --git a/paperforge/writing_patch.py b/paperforge/writing_patch.py
index e3d5aa4..4d210bf 100644
--- a/paperforge/writing_patch.py
+++ b/paperforge/writing_patch.py
@@ -121,7 +121,7 @@ def apply_patch(
raise UnsupportedMultiFileEdit(f"received {len(extra_targets) + 1} targets")
root = Path(workspace).expanduser().resolve(strict=True)
target_path, relative = _resolve_target(root, target)
- original = target_path.read_text(encoding="utf-8")
+ original = target_path.read_bytes().decode("utf-8")
actual_sha = hashlib.sha256(original.encode("utf-8")).hexdigest()
if actual_sha != source_sha256:
raise PatchSafetyError(
@@ -237,7 +237,7 @@ def apply_patch(
atomic_write_text(root, relative, candidate if candidate.endswith("\n") else candidate + "\n")
written = root / relative
try:
- after_hash = protected_blocks_sha256(written.read_text(encoding="utf-8"))
+ after_hash = protected_blocks_sha256(written.read_bytes().decode("utf-8"))
if after_hash != before_hash:
raise PatchSafetyError("protected hash changed after patch")
store = ArtifactStore(
diff --git a/tests/test_u24a_finalization.py b/tests/test_u24a_finalization.py
index 7165a37..3ee362d 100644
--- a/tests/test_u24a_finalization.py
+++ b/tests/test_u24a_finalization.py
@@ -39,7 +39,7 @@ def _spec_with_table(tmp_path: Path, block: str, table_id: str = "table-1"):
store.register(f"artifacts/tables/{table_id}/manifest.json", kind="manifest")
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old_block = extract_protected_blocks(text)[0]
spec = ResultUpdateSpec(
target_path="paper.tex", target_source_sha256=hashlib.sha256(text.encode()).hexdigest(),
@@ -95,7 +95,7 @@ def test_structural_numbers_ignored(tmp_path: Path) -> None: # F2-1,2
block = "See Table III and Eq. (7). Old result 20.0 ms."
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old = extract_protected_blocks(text)[0]
spec = ResultUpdateSpec(target_path="paper.tex",
target_source_sha256=hashlib.sha256(text.encode()).hexdigest(),
@@ -113,7 +113,7 @@ def test_protocol_changes_require_binding(tmp_path: Path) -> None: # F2-3,4,5
block = "Trained 300 epochs on 896 px with 3 seeds. Old result 20.0 ms."
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old = extract_protected_blocks(text)[0]
spec = ResultUpdateSpec(target_path="paper.tex",
target_source_sha256=hashlib.sha256(text.encode()).hexdigest(),
@@ -129,7 +129,7 @@ def test_protocol_binding_passes(tmp_path: Path) -> None: # F2-6
block = "Trained 300 epochs. Old result 20.0 ms."
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old = extract_protected_blocks(text)[0]
spec = ResultUpdateSpec(
target_path="paper.tex", target_source_sha256=hashlib.sha256(text.encode()).hexdigest(),
@@ -147,7 +147,7 @@ def test_reconcile_matrix(tmp_path: Path) -> None: # F3
block = "Old result 20.0 ms."
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old = extract_protected_blocks(text)[0]
spec = ResultUpdateSpec(target_path="paper.tex",
target_source_sha256=hashlib.sha256(text.encode()).hexdigest(),
@@ -162,7 +162,7 @@ def test_reconcile_matrix(tmp_path: Path) -> None: # F3
# C: simulate APPLYING + new without DB commit.
with service.memory.connect() as db:
db.execute("UPDATE result_updates SET state='APPLYING' WHERE id=?", (prop["proposal_id"],))
- (tmp_path / "paper.tex").write_text(text.replace(old, old.replace("20.0", "22.4")), encoding="utf-8")
+ (tmp_path / "paper.tex").write_bytes(text.replace(old, old.replace("20.0", "22.4")).encode("utf-8"))
report2 = reconcile_result_updates(tmp_path, service.memory)
assert any("RECOVERABLE_FORWARD" in f["verdict"] for f in report2["findings"])
# Manual: neither old nor new.
diff --git a/tests/test_u24a_result_update.py b/tests/test_u24a_result_update.py
index 99f9d1c..728f115 100644
--- a/tests/test_u24a_result_update.py
+++ b/tests/test_u24a_result_update.py
@@ -31,7 +31,7 @@ def _spec(tmp_path: Path, block: str = "Old result 20.0 ms.", **overrides) -> tu
service = PaperForgeService(tmp_path)
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", block), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
old_block = extract_protected_blocks(text)[0]
base = {
"target_path": "paper.tex",
@@ -137,12 +137,12 @@ def test_approval_binding_and_invalidation(tmp_path: Path) -> None: # 15,16,17,
def test_apply_single_block_and_hashes(tmp_path: Path) -> None: # 19,20,21
service, spec, old = _spec(tmp_path)
- before = (tmp_path / "paper.tex").read_text()
+ before = (tmp_path / "paper.tex").read_bytes().decode("utf-8")
prop = build_proposal(tmp_path, service.memory, spec, proposed_block=old.replace("20.0", "22.4"),
facts_used=[_fact()])
approve_proposal(tmp_path, service.memory, prop["proposal_id"], approver="local-owner")
out = apply_proposal(tmp_path, service.memory, prop["proposal_id"])
- after = (tmp_path / "paper.tex").read_text()
+ after = (tmp_path / "paper.tex").read_bytes().decode("utf-8")
assert "22.4" in after and out["new_block_sha256"]
assert after.replace(out["new_block_sha256"], "") is not None
assert before.replace(old, "") == after.replace(old.replace("20.0", "22.4"), "") # 20
@@ -192,7 +192,7 @@ def test_ledger_stale_blocks_approve_and_apply(tmp_path: Path) -> None: # 16,17
purpose="scientific", metric_names=["latency_ms"], evidence_ids=(eid,)))
tex = tmp_path / "paper.tex"
tex.write_text(_doc("Intro.", "Old result 20.0 ms."), encoding="utf-8")
- text = tex.read_text(encoding="utf-8")
+ text = tex.read_bytes().decode("utf-8")
from paperforge.protected_blocks import extract_protected_blocks as _ex
old_block = _ex(text)[0]
diff --git a/tests/test_u4d_crlf_sources.py b/tests/test_u4d_crlf_sources.py
new file mode 100644
index 0000000..7c91aa5
--- /dev/null
+++ b/tests/test_u4d_crlf_sources.py
@@ -0,0 +1,85 @@
+"""Source hashes and protected blocks bind bytes, not normalized newlines."""
+
+import hashlib
+
+import pytest
+from test_u1_patch import _document
+
+from paperforge.api import PaperForgeService
+from paperforge.protected_blocks import extract_protected_blocks
+from paperforge.result_update import (
+ ResultUpdateSpec,
+ apply_proposal,
+ approve_proposal,
+ build_proposal,
+ reconcile_result_updates,
+)
+from paperforge.writing_patch import apply_patch
+
+
+@pytest.fixture(autouse=True)
+def windows_default_text_newlines(monkeypatch):
+ from paperforge import path_safety
+
+ original = path_safety.tempfile.NamedTemporaryFile
+
+ def windows_temporary_file(*args, **kwargs):
+ if "b" not in kwargs.get("mode", "w+b") and kwargs.get("newline") is None:
+ kwargs["newline"] = "\r\n"
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(path_safety.tempfile, "NamedTemporaryFile", windows_temporary_file)
+
+
+def test_prose_patch_preserves_crlf_source_bytes(tmp_path):
+ path = tmp_path / "paper.tex"
+ original = _document("Original prose.").replace("\n", "\r\n").encode()
+ path.write_bytes(original)
+ service = PaperForgeService(tmp_path)
+ apply_patch(tmp_path, memory=service.memory,
+ request_text=lambda *a, **k: "Revised prose.", run_id="crlf-test",
+ target="paper.tex", source_sha256=hashlib.sha256(original).hexdigest(),
+ anchor="Original prose.")
+ assert path.read_bytes() == original.replace(b"Original prose.", b"Revised prose.")
+
+
+def test_prose_patch_rollback_preserves_crlf_bytes(tmp_path, monkeypatch):
+ from paperforge.artifacts import ArtifactStore
+
+ path = tmp_path / "paper.tex"
+ original = _document("Original prose.").replace("\n", "\r\n").encode()
+ path.write_bytes(original)
+ service = PaperForgeService(tmp_path)
+
+ def fail_registration(*args, **kwargs):
+ raise RuntimeError("test registration failure")
+
+ monkeypatch.setattr(ArtifactStore, "register", fail_registration)
+ with pytest.raises(RuntimeError, match="test registration failure"):
+ apply_patch(tmp_path, memory=service.memory,
+ request_text=lambda *a, **k: "Revised prose.", run_id="crlf-test",
+ target="paper.tex", source_sha256=hashlib.sha256(original).hexdigest(),
+ anchor="Original prose.")
+ assert path.read_bytes() == original
+
+
+def test_result_update_binds_crlf_bytes_through_apply_and_reconcile(tmp_path):
+ path = tmp_path / "paper.tex"
+ original = _document("Original prose.", "Old result 20.0 ms.").replace("\n", "\r\n").encode()
+ path.write_bytes(original)
+ old = extract_protected_blocks(original.decode())[0]
+ service = PaperForgeService(tmp_path)
+ spec = ResultUpdateSpec(target_path="paper.tex",
+ target_source_sha256=hashlib.sha256(original).hexdigest(),
+ old_block_sha256=hashlib.sha256(old.encode()).hexdigest(),
+ allowed_fact_ids=("test-latency",))
+ proposal = build_proposal(tmp_path, service.memory, spec,
+ proposed_block=old.replace("20.0", "22.4"),
+ facts_used=[{"fact_id": "test-latency", "value": "22.4", "unit": "ms"}])
+ approve_proposal(tmp_path, service.memory, proposal["proposal_id"], approver="TEST_ONLY")
+ result = apply_proposal(tmp_path, service.memory, proposal["proposal_id"])
+ expected = original.replace(b"20.0", b"22.4")
+ assert path.read_bytes() == expected
+ assert result["new_source_sha256"] == hashlib.sha256(expected).hexdigest()
+ report = reconcile_result_updates(tmp_path, service.memory)
+ assert all(f["verdict"] == "CLEAN" for f in report["findings"])
diff --git a/tests/test_u4d_figure_serialization.py b/tests/test_u4d_figure_serialization.py
index f8e1234..6d2393e 100644
--- a/tests/test_u4d_figure_serialization.py
+++ b/tests/test_u4d_figure_serialization.py
@@ -39,13 +39,13 @@ def test_figure_svg_labels_are_data_not_markup(tmp_path: Path, label: str) -> No
_seed(service, metric="latency_ms", value="20", run={"model_id": label})
_seed(service, metric="map", value="0.8", unit="score", run={"model_id": label})
ledger = freeze_ledger(tmp_path, service.memory, ResultLedgerQuery(purpose="scientific"))
- spec = FigureSpec(ledger_id=ledger["ledger_id"], figure_id="preview<&>",
+ spec = FigureSpec(ledger_id=ledger["ledger_id"], figure_id="preview&",
x_metric="latency_ms", y_metric="map", series_by="model_id")
first = generate_figure(tmp_path, service.memory, spec)
path = tmp_path / "artifacts" / "figures" / first["figure_id"] / "figure.svg"
svg = ET.fromstring(path.read_bytes())
ns = {"svg": "http://www.w3.org/2000/svg"}
- assert svg.find("svg:title", ns).text == "preview<&>"
+ assert svg.find("svg:title", ns).text == "preview&"
circles = svg.findall("svg:circle", ns)
assert circles
for circle in circles:
diff --git a/tests/test_u4d_import_ledger.py b/tests/test_u4d_import_ledger.py
index 009926f..a59bfe3 100644
--- a/tests/test_u4d_import_ledger.py
+++ b/tests/test_u4d_import_ledger.py
@@ -79,6 +79,24 @@ def test_imported_ledger_verifies_in_read_only_release_context(tmp_path):
assert list(db.iterdump()) == before
+@pytest.mark.parametrize("relative", [
+ "sources\\fixture.json", "sources/../fixture.json", "sources/./fixture.json",
+ "sources//fixture.json", "/sources/fixture.json", "sources/file:stream",
+])
+def test_import_source_path_requires_canonical_portable_relative_path(tmp_path, relative):
+ from paperforge.result_ledger import _imported_metric_snapshots
+
+ service, _, materialized, _ = imported_metric(tmp_path)
+ eid = materialized["evidence_ids"][0]
+ with service.memory.connect() as db:
+ row = dict(db.execute("SELECT * FROM evidence WHERE id=?", (eid,)).fetchone())
+ metadata = json.loads(row["metadata_json"])
+ metadata["source_relpath"] = relative
+ with pytest.raises(LedgerError, match="invalid imported metric source path"):
+ _imported_metric_snapshots(tmp_path, service.memory, eid, row, metadata,
+ ResultLedgerQuery(evidence_ids=(eid,)))
+
+
@pytest.mark.parametrize("role", ["fixture", "synthetic_test"])
def test_fixture_import_does_not_receive_scientific_approval(tmp_path, role):
service, record, validation, _ = imported_metric(tmp_path, role=role)
From 0af125a6038ce0be52282ce979e7fdbf0c460b77 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Fri, 9 Oct 2026 17:58:43 +0800
Subject: [PATCH 28/30] docs: record remote findings and cross-platform repair
evidence
---
docs/u4d-final-execution.md | 64 ++++++++++++++++++++++++++++++++++++-
1 file changed, 63 insertions(+), 1 deletion(-)
diff --git a/docs/u4d-final-execution.md b/docs/u4d-final-execution.md
index 0d819b2..f8343df 100644
--- a/docs/u4d-final-execution.md
+++ b/docs/u4d-final-execution.md
@@ -5,6 +5,12 @@ branch `feature/u4c-reliability`. This is a running evidence log, not a completi
certificate. The full batch includes the subsequent PCB paper revision; completing
U4D alone must not close the overall goal.
+Current remote checkpoint: first authorized push `f7d8dd7` is under review in
+[PR #3](https://github.com/QJHWC/PaperForge/pull/3). It is **not frozen**: code
+review found seven valid blockers and CI exposed renderer and Windows defects.
+Local repairs pass; fresh remote verification is pending (see below). Earlier local
+approval is historical evidence, not a claim that remote review found no defects.
+
## Authorization and order
The batch owner authorizes isolated Python 3.11 dependency installation, source and
@@ -23,7 +29,7 @@ of unpublished materials, paid resources, sudo, or system Python 3.14.
| Requirements | Evidence required | Current state |
|---|---|---|
| A1 environment | Interpreter/venv/pip and declared dependency inspection | PASS; isolated Python 3.11.15, pip check clean |
-| A2 full tests | Full pytest, counts and failure classification | PASS; 778 passed, 5 opt-in skips, 0 failures/errors |
+| A2 full tests | Full pytest, counts and failure classification | PASS; 819 passed, 5 opt-in skips, 0 failures/errors |
| A3-A4 static | Existing Ruff whole-repository and mypy paperforge scope pass | PASS; Ruff ., mypy 81 files |
| A5 integration | End-to-end synthetic evidence-to-status FinalSmokeReport and negative boundaries | PASS; no real human approval/release |
| A6 reliability | ResultUpdate, actual kill/reopen, import reopen, split-brain | PASS_WITH_LIMITATIONS; all 69 U4C tests retained |
@@ -208,3 +214,59 @@ local review, not a full historical-repository certification or remote review.
push is the next action. This is not tool freeze, remote review clearance,
merge authorization, scientific acceptance or publication release.
- Remote automatic code/security reviews and all real-paper phases remain open.
+
+## First push and remote-review repair loop (2026-10-09)
+
+- Pushed and remotely verified exact SHA
+ `f7d8dd70c1fb9ff0f44e796305cce2991879f940`; PR #3 created and attached.
+ No merge occurred. Both Codex review requests were explicitly triggered after
+ inspecting initial remote activity; the summary identifies them as manual
+ requests. Copilot's separate quota refusal is not a review pass.
+- Read all seven Codex inline findings, not just completed state: six P1 and one
+ P2. Each is a valid correctness/approval/currentness blocker. Findings:
+ fact source semantics omitted; incomplete figure run-identity pairing; unchecked
+ ledger consumption; repeated old numbers bypass binding; missing artifact
+ members ignored; pending human records count as completed coverage; changed
+ target PDF still reports current. Four were also independently reproduced by
+ the local reviewer in temporary fixtures.
+- [Security review](https://github.com/QJHWC/PaperForge/pull/3#issuecomment-6078423453)
+ explicitly reports no security issues for `f7d8dd7`. This does not overrule the
+ seven code findings and does not certify subsequent commits.
+- Linux Python 3.11 CI: 755 passed, 7 platform/opt-in skips, 21 failures, all
+ missing `pdftoppm`. macOS 3.11: 757 passed, 5 skips, same 21 failures. The real
+ compute CI job completed successfully. Windows Python 3.11 subsequently finished
+ with 689 passed, 18 skips, 76 failures: missing Poppler plus actual byte/newline
+ and portable-path defects. These are not all environment failures.
+- Local commit `4506b8b` provisions Poppler on all three CI platforms and runs a
+ renderer preflight. Windows uses a fixed third-party Poppler packaging release
+ with a verified pinned SHA-256, not a claim of an upstream official build.
+ Independent config review approved; actual CI installation is still unverified.
+- Added 32 red-first regressions for the seven code findings. Current local
+ repair run: **815 collected, 810 passed, 5 skipped, 0 failed, 0 errors**;
+ Ruff PASS; configured mypy PASS (81 files). Publication, update and PDF repairs
+ independently reviewed and approved locally. No second push yet.
+- Tool freeze and real-paper phases remain pending. The next pushed SHA must
+ receive fresh code and security reviews; first-push results cannot be reused.
+
+## Cross-platform byte integrity repair (2026-10-09)
+
+- Windows CI exposed source hashes computed after universal-newline normalization.
+ Prose patch and ResultUpdate now decode the actual source bytes. Test approval
+ fixtures likewise bind actual bytes; outside-block equality remains exact.
+- Independent review reproduced an additional source-corruption bug: text-mode
+ temporary writes turn existing CRLF into CRCRLF on Windows, including rollback.
+ The shared atomic text writer now encodes explicitly and reuses the byte writer.
+ Windows-default newline simulation reproduced both real entrypoint failures
+ before repair; CRLF patch/apply and failed-registration rollback preserve bytes.
+- Imported source paths are validated against their raw canonical POSIX spelling,
+ not Windows-native backslash rendering. Six negative cases retain traversal,
+ noncanonical and alternate-stream rejection. SVG tests use a portable ID while
+ retaining quotes/angle-brackets/ampersands in adversarial series labels.
+- These repairs require the next real Windows CI run. Local OS success and the
+ focused newline simulation alone are not Windows certification.
+- Latest local run: **824 collected, 819 passed, 5 skipped, 0 failed, 0 collection
+ errors**, with the same five SWIG warnings. Whole-repository Ruff and configured
+ mypy (81 files) pass. Rebuilt sdist/wheel and official isolated wheel smoke pass.
+- Independent scoped review approved: 52 tests, changed-file Ruff and configured
+ mypy pass; no remaining HIGH/CRITICAL within this repair. Local push readiness
+ is restored, but no remote clearance or tool freeze is claimed.
From acf897685f49ff4bf419e7e974be190336e0152f Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Sat, 10 Oct 2026 20:18:06 +0800
Subject: [PATCH 29/30] fix: close remote review follow-ups on model grounding
and table provenance
---
paperforge/grounded_narrative.py | 25 ++++++-----
paperforge/publication_artifacts.py | 50 ++++++++++++++-------
paperforge/result_ledger.py | 1 +
tests/test_u24b_narrative.py | 15 ++++---
tests/test_u4d_final_smoke.py | 2 +-
tests/test_u4d_review_model_aggregation.py | 22 +++++++++
tests/test_u4d_review_narrative_subject.py | 32 +++++++++++++
tests/test_u4d_review_table_pivot.py | 52 ++++++++++++++++++++++
8 files changed, 164 insertions(+), 35 deletions(-)
create mode 100644 tests/test_u4d_review_model_aggregation.py
create mode 100644 tests/test_u4d_review_narrative_subject.py
create mode 100644 tests/test_u4d_review_table_pivot.py
diff --git a/paperforge/grounded_narrative.py b/paperforge/grounded_narrative.py
index 85fb40a..4715954 100644
--- a/paperforge/grounded_narrative.py
+++ b/paperforge/grounded_narrative.py
@@ -13,7 +13,7 @@
NARRATIVE_SPEC_SCHEMA = "paperforge.grounded-narrative-spec/v1"
NARRATIVE_DRAFT_SCHEMA = "paperforge.grounded-narrative-draft/v1"
-NARRATIVE_POLICY_VERSION = "paperforge.narrative-policy/v1"
+NARRATIVE_POLICY_VERSION = "paperforge.narrative-policy/v2"
_SENTENCE_ROLES = (
"metric_report", "comparison", "protocol_statement",
@@ -272,15 +272,20 @@ def validate_narrative(
# Qualifier consistency (model/dataset/device/size when facts declare them).
for fid in sent.fact_ids:
qualifiers = dict((fact_map.get(fid) or {}).get("qualifiers") or {})
- for key in ("model_id", "dataset", "device", "input_size"):
- expected = str(qualifiers.get(key) or "")
- if not expected:
- continue
- if key == "model_id" and expected.lower() not in lowered:
- # Model must be named correctly when the fact is model-specific.
- pass
- for _candidate in (f"{key} {expected}", str(expected)):
- pass
+ identity = dict((fact_map.get(fid) or {}).get("run_identity") or {})
+ expected = str(identity.get("model_id") or qualifiers.get("model_id") or "")
+ if expected and not re.search(rf"(? 1:
+ table_row["unit"] = None
# Highlights: explicit max/min only, recorded in manifest.
highlights: list[dict[str, Any]] = []
for rule in spec.highlight_rules:
diff --git a/paperforge/result_ledger.py b/paperforge/result_ledger.py
index f4f7c75..c756d54 100644
--- a/paperforge/result_ledger.py
+++ b/paperforge/result_ledger.py
@@ -34,6 +34,7 @@ class LedgerConflictError(LedgerError):
CROSSABLE_DIMENSIONS = frozenset(
{
+ "model_id",
"seed",
"checkpoint_sha256",
"dataset_id",
diff --git a/tests/test_u24b_narrative.py b/tests/test_u24b_narrative.py
index ef45840..536135c 100644
--- a/tests/test_u24b_narrative.py
+++ b/tests/test_u24b_narrative.py
@@ -43,7 +43,7 @@ def _sent(text, **overrides):
def test_metric_bound_pass(tmp_path: Path) -> None: # 1
- out = validate_narrative(_spec(), [[_sent("Control reached 0.8511.")]], facts=_facts(), protocol_facts=_proto())
+ out = validate_narrative(_spec(), [[_sent("YOLO11n reached 0.8511.")]], facts=_facts(), protocol_facts=_proto())
assert out["overall_status"] == "passed"
@@ -60,10 +60,11 @@ def test_model_delta_without_fact_fail() -> None: # 3
def test_delta_fact_pass() -> None: # 4
- out = validate_narrative(_spec(), [[_sent("Trails by -0.0015.", role="comparison",
+ out = validate_narrative(_spec(), [[_sent("The route trails by -0.0015.", role="comparison",
fact_ids=("fact-delta",))]],
facts=_facts(), protocol_facts=_proto())
- assert out["overall_status"] == "passed"
+ # The value is grounded, but comparative subject attribution needs review.
+ assert out["overall_status"] == "needs_human"
def test_percent_computed_fail() -> None: # 5
@@ -159,14 +160,14 @@ def test_reference_not_authority() -> None: # 17
def test_stats_needs_human() -> None: # 18,19
for word in ("significantly outperforms", "equivalent"):
- out = validate_narrative(_spec(), [[_sent(f"Control 0.8511 {word}.")]],
+ out = validate_narrative(_spec(), [[_sent(f"YOLO11n 0.8511 {word}.")]],
facts=_facts(), protocol_facts=_proto())
assert out["overall_status"] == "needs_human"
def test_best_without_authorization_fail() -> None: # 20
with pytest.raises(Exception, match="ranking"):
- validate_narrative(_spec(), [[_sent("Best overall at 0.8511.")]], facts=_facts(), protocol_facts=_proto())
+ validate_narrative(_spec(), [[_sent("YOLO11n is best overall at 0.8511.")]], facts=_facts(), protocol_facts=_proto())
def test_transition_rules() -> None: # 21,22
@@ -203,7 +204,7 @@ def test_no_direct_file_write_and_u24a_gates(tmp_path: Path) -> None: # 28,29,3
PaperForgeService(tmp_path)
tex = tmp_path / "paper.tex"
tex.write_text("\\documentclass{article}\n\\begin{document}\nIntro.\n% PAPERFORGE-PROTECTED-EXPERIMENT-START\nOld 0.8511.\n% PAPERFORGE-PROTECTED-EXPERIMENT-END\n\\end{document}\n", encoding="utf-8")
- sents = [[_sent("Control 0.8511.")]]
+ sents = [[_sent("YOLO11n reached 0.8511.")]]
out = validate_narrative(_spec(), sents, facts=_facts(), protocol_facts=_proto())
assert tex.read_text() .count("Control") == 0 # 28
assert out["overall_status"] == "passed"
@@ -216,7 +217,7 @@ def test_narrative_pass_not_approved_and_bytes_gate(tmp_path: Path) -> None: #
def test_narrative_to_u24a_integration(tmp_path: Path) -> None: # 29 (integration)
service = PaperForgeService(tmp_path)
- sents = [[_sent("Control 0.8511.")]]
+ sents = [[_sent("YOLO11n reached 0.8511.")]]
integrated = build_update_from_narrative(
tmp_path, service.memory, spec=_spec(), paragraphs=sents,
facts=_facts(), target_spec_kwargs={
diff --git a/tests/test_u4d_final_smoke.py b/tests/test_u4d_final_smoke.py
index e24527c..3bbd98c 100644
--- a/tests/test_u4d_final_smoke.py
+++ b/tests/test_u4d_final_smoke.py
@@ -72,7 +72,7 @@ def test_final_evidence_to_release_status_smoke(tmp_path):
if name != "manifest.json":
assert _sha(tmp_path / "artifacts" / kind / aid / name) == digest
assert artifact["manifest"]["publication_ready"] is False
- sentence = NarrativeSentence("s1", "The test measured latency was 12.5 ms.",
+ sentence = NarrativeSentence("s1", "TEST_ONLY measured latency was 12.5 ms.",
fact_ids=(fact["fact_id"],))
spec = GroundedNarrativeSpec(allowed_fact_ids=(fact["fact_id"],))
paragraphs = [[sentence]]
diff --git a/tests/test_u4d_review_model_aggregation.py b/tests/test_u4d_review_model_aggregation.py
new file mode 100644
index 0000000..621f534
--- /dev/null
+++ b/tests/test_u4d_review_model_aggregation.py
@@ -0,0 +1,22 @@
+import pytest
+from test_u23b_artifacts import _seed, _service
+
+from paperforge.result_ledger import AggregationSpec, LedgerError, ResultLedgerQuery, freeze_ledger
+
+
+def test_aggregation_cannot_silently_pool_models(tmp_path):
+ service = _service(tmp_path)
+ for model, value in (("A", "1"), ("B", "3")):
+ _seed(service, value=value, run={"model_id": model})
+ query = ResultLedgerQuery(aggregations=(AggregationSpec(metric="latency_ms"),))
+ with pytest.raises(LedgerError, match="differing model_id"):
+ freeze_ledger(tmp_path, service.memory, query)
+
+
+def test_model_grouping_keeps_results_separate(tmp_path):
+ service = _service(tmp_path)
+ for model, value in (("A", "1"), ("B", "3")):
+ _seed(service, value=value, run={"model_id": model})
+ query = ResultLedgerQuery(aggregations=(AggregationSpec(metric="latency_ms", group_by=("model_id",)),))
+ ledger = freeze_ledger(tmp_path, service.memory, query)
+ assert {r["group"]["model_id"]: r["value_str"] for r in ledger["aggregate_rows"]} == {"A": "1", "B": "3"}
diff --git a/tests/test_u4d_review_narrative_subject.py b/tests/test_u4d_review_narrative_subject.py
new file mode 100644
index 0000000..787b617
--- /dev/null
+++ b/tests/test_u4d_review_narrative_subject.py
@@ -0,0 +1,32 @@
+import pytest
+
+from paperforge.grounded_narrative import (
+ GroundedNarrativeSpec,
+ NarrativeGroundingError,
+ NarrativeSentence,
+ validate_narrative,
+)
+
+
+@pytest.mark.parametrize("subject", ["ModelB", "ModelAB", "The model"])
+def test_narrative_rejects_wrong_or_unresolved_model_subject(subject):
+ fact = {"fact_id": "f", "value": "20", "qualifiers": {"model_id": "ModelA"}}
+ sentence = NarrativeSentence("s", f"{subject} measured 20 ms.", "metric_report", fact_ids=("f",))
+ with pytest.raises(NarrativeGroundingError, match="GROUNDING_MISMATCH model_id"):
+ validate_narrative(GroundedNarrativeSpec(allowed_fact_ids=("f",)), [[sentence]], facts=[fact])
+
+
+def test_narrative_accepts_correct_model_from_source_identity():
+ fact = {"fact_id": "f", "value": "20", "unit": "ms", "run_identity": {"model_id": "ModelA"}}
+ sentence = NarrativeSentence("s", "ModelA measured 20 ms.", "metric_report", fact_ids=("f",))
+ assert validate_narrative(GroundedNarrativeSpec(allowed_fact_ids=("f",)), [[sentence]],
+ facts=[fact])["overall_status"] == "passed"
+
+
+@pytest.mark.parametrize("text", ["ModelB measured 20 ms, unlike ModelA.",
+ "ModelA was the reference; ModelB measured 20 ms."])
+def test_mentioning_expected_model_does_not_bind_wrong_subject(text):
+ fact = {"fact_id": "f", "value": "20", "qualifiers": {"model_id": "ModelA"}}
+ sentence = NarrativeSentence("s", text, "metric_report", fact_ids=("f",))
+ assert validate_narrative(GroundedNarrativeSpec(allowed_fact_ids=("f",)), [[sentence]],
+ facts=[fact])["overall_status"] == "needs_human"
diff --git a/tests/test_u4d_review_table_pivot.py b/tests/test_u4d_review_table_pivot.py
new file mode 100644
index 0000000..051a401
--- /dev/null
+++ b/tests/test_u4d_review_table_pivot.py
@@ -0,0 +1,52 @@
+import json
+
+import pytest
+from test_u23b_artifacts import _seed, _service
+
+from paperforge.publication_artifacts import PublicationArtifactError, TableSpec, generate_table
+from paperforge.result_ledger import ResultLedgerQuery, freeze_ledger
+
+
+def table(root, service, columns):
+ ledger = freeze_ledger(root, service.memory, ResultLedgerQuery())
+ out = generate_table(root, service.memory, TableSpec(ledger_id=ledger["ledger_id"], columns=columns))
+ return json.loads((root / "artifacts/tables" / out["table_id"] / "table.json").read_bytes())
+
+
+def test_table_excludes_unrequested_metrics(tmp_path):
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20")
+ _seed(service, metric="fps", value="50", unit="fps")
+ rows = table(tmp_path, service, ("latency_ms",))["rows"]
+ assert len(rows) == 1
+ assert rows[0]["metric_values"] == {"latency_ms": "20"}
+
+
+def test_table_pivots_matching_runs_and_keeps_cell_provenance(tmp_path):
+ service = _service(tmp_path)
+ latency = _seed(service, metric="latency_ms", value="20")
+ fps = _seed(service, metric="fps", value="50", unit="fps")
+ rows = table(tmp_path, service, ("latency_ms", "fps"))["rows"]
+ assert len(rows) == 1
+ assert rows[0]["metric_values"] == {"latency_ms": "20", "fps": "50"}
+ assert set(rows[0]["source_evidence_ids"]) == {latency, fps}
+ assert rows[0]["metric_units"] == {"latency_ms": "ms", "fps": "fps"}
+ assert rows[0]["metric_source_evidence_ids"] == {"latency_ms": [latency], "fps": [fps]}
+
+
+@pytest.mark.parametrize("change", [{"dataset_id": "other"}, {"seed": "2"}, {"device_id": "other"}])
+def test_table_never_pivots_different_runs(tmp_path, change):
+ service = _service(tmp_path)
+ _seed(service, metric="latency_ms", value="20")
+ _seed(service, metric="fps", value="50", unit="fps", run=change)
+ rows = table(tmp_path, service, ("latency_ms", "fps"))["rows"]
+ assert len(rows) == 2
+ assert all(sum(v is not None for v in row["metric_values"].values()) == 1 for row in rows)
+
+
+def test_table_rejects_ambiguous_duplicate_metric(tmp_path):
+ service = _service(tmp_path)
+ _seed(service, value="20")
+ _seed(service, value="0.020", unit="s")
+ with pytest.raises(PublicationArtifactError, match="ambiguous table metric"):
+ table(tmp_path, service, ("latency_ms",))
From a34562afa2e318517a8439328fb13a9681683f05 Mon Sep 17 00:00:00 2001
From: qjhwc <2570686929@qq.com>
Date: Sun, 11 Oct 2026 01:32:40 +0800
Subject: [PATCH 30/30] fix: grant attempt workspace writes and widen Windows
resume timeouts
---
paperforge/compute/local.py | 6 +++++-
tests/test_compute_backends.py | 23 ++++++++++++++---------
2 files changed, 19 insertions(+), 10 deletions(-)
diff --git a/paperforge/compute/local.py b/paperforge/compute/local.py
index a1fb9b2..50469ec 100644
--- a/paperforge/compute/local.py
+++ b/paperforge/compute/local.py
@@ -342,7 +342,11 @@ def _windows_sandboxed_command(
candidate = Path(raw).expanduser().resolve(strict=True)
if candidate.is_dir():
read_roots.add(candidate)
- write_roots = {temporary}
+ # The sandboxed process runs with cwd=workdir and must be able to
+ # create files there (temporary files, bytecode caches, renamed
+ # outputs), not only touch pre-declared output paths. workdir is
+ # already an absolute path at every call site.
+ write_roots = {temporary, workdir}
for raw_output in spec.outputs:
if any(character in str(raw_output) for character in "*?[]"):
raise JobStateError(
diff --git a/tests/test_compute_backends.py b/tests/test_compute_backends.py
index cca9d5e..d226301 100644
--- a/tests/test_compute_backends.py
+++ b/tests/test_compute_backends.py
@@ -44,12 +44,12 @@
from paperforge.policy import ExecutionPolicy, PolicyViolation
-def _local_test_timeout(seconds: int = 5) -> int:
- return 60 if os.name == "nt" else seconds
+def _local_test_timeout(seconds: int = 5, *, windows_seconds: int = 60) -> int:
+ return windows_seconds if os.name == "nt" else seconds
-def _local_process_timeout(seconds: int = 5) -> int:
- return 30 if os.name == "nt" else seconds
+def _local_process_timeout(seconds: int = 5, *, windows_seconds: int = 30) -> int:
+ return windows_seconds if os.name == "nt" else seconds
def _secure_test_file(path: Path, *, mode: int) -> None:
@@ -1562,18 +1562,23 @@ def test_local_resume_uses_fresh_attempt_artifacts(tmp_path: Path) -> None:
command=[sys.executable, "-c", code],
workdir=workdir,
outputs=["result.txt"],
- resources=ResourceSpec(timeout_seconds=_local_process_timeout()),
+ # Windows AppContainer setup (recursive ACL grants over the
+ # interpreter install plus cold Defender scans) has been observed
+ # to exceed the default 30s supervised timeout on loaded CI
+ # runners (first attempt ran 33s before timeout). The freshness
+ # assertions below are unchanged; only the time budget grows.
+ resources=ResourceSpec(timeout_seconds=_local_process_timeout(windows_seconds=180)),
execute=True,
)
)
current = submitted
- deadline = time.monotonic() + _local_test_timeout()
+ deadline = time.monotonic() + _local_test_timeout(windows_seconds=240)
while current.status is JobStatus.RUNNING:
assert time.monotonic() < deadline
time.sleep(0.02)
current = backend.status(submitted.job_id, execute=True)
- assert current.status is JobStatus.SUCCEEDED
+ assert current.status is JobStatus.SUCCEEDED, current.message
first = backend.sync_artifacts(
submitted.job_id,
tmp_path / "first",
@@ -1584,12 +1589,12 @@ def test_local_resume_uses_fresh_attempt_artifacts(tmp_path: Path) -> None:
resumed = backend.resume(submitted.job_id, execute=True)
current = resumed
- deadline = time.monotonic() + _local_test_timeout()
+ deadline = time.monotonic() + _local_test_timeout(windows_seconds=240)
while current.status is JobStatus.RUNNING:
assert time.monotonic() < deadline
time.sleep(0.02)
current = backend.status(submitted.job_id, execute=True)
- assert current.status is JobStatus.SUCCEEDED
+ assert current.status is JobStatus.SUCCEEDED, current.message
second = backend.sync_artifacts(
submitted.job_id,
tmp_path / "second",