#!/usr/bin/env python3 """Fail-closed consistency gates for active status docs vs door-percent contract.""" from __future__ import annotations import re import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] TRUNCATE_SEMANTICS = "truncate_current_high_pulse_immediately_after_synchronized_limit" PENDING_TIP_TD = "pending final tip TD" ACTIVITY_DOCS = ( "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md", "ACCEPTANCE_MATRIX.md", "OPEN_QUESTIONS.md", "PLAN.md", "docs/TD_USAGE.zh-CN.md", "docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md", ) PER_DOC_MARKERS = ( "百分比", "0x03", "0x83", ) CORPUS_REQUIRED = ( TRUNCATE_SEMANTICS, "permanent_high", "5000", "30", "CON104", "CON105", "CON106", "CON120", "CON12", "CON129", "GET_MOTOR_STATUS", "startup_complete", "latest-wins", ) STALE_AS_CURRENT = ( ( re.compile(r"(?i)P4_FIXED_MOTOR_STEPS"), "FIXED_MOTOR presented as current", ), ( re.compile(r"(?i)(?:进风(?:门)?默认\*?电磁铁\*?|intake_solenoid_out)"), "solenoid intake presented as active product path", ), ( re.compile( r"(?i)(?:X\s*限位[^\n]{0,40}CON68|Y\s*限位[^\n]{0,40}CON34)" ), "obsolete CON68/CON34 mapping presented as active probe", ), ) ROOT_RESIDUE = ( ".run_id", ".run_id_linux", "evidence-batch-summary.txt", ) def _read(rel: str) -> str: return (ROOT / rel).read_text(encoding="utf-8") class ActivityDocsTruthTests(unittest.TestCase): def test_activity_docs_exist(self) -> None: missing = [rel for rel in ACTIVITY_DOCS if not (ROOT / rel).is_file()] self.assertEqual(missing, [], f"missing activity docs: {missing}") def test_each_activity_doc_carries_percent_protocol_markers(self) -> None: for rel in ACTIVITY_DOCS: text = _read(rel) for marker in PER_DOC_MARKERS: self.assertIn(marker, text, f"{rel} missing {marker!r}") def test_activity_docs_agree_on_percent_corpus(self) -> None: corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS) for marker in CORPUS_REQUIRED: self.assertIn(marker, corpus, f"activity corpus missing {marker!r}") self.assertRegex(corpus, r"(?i)(?:X\s*/\s*Y\s*/\s*Z|三轴)") self.assertRegex(corpus, r"(?i)(?:六限位|six limits)") self.assertRegex(corpus, r"(?i)(?:Hardware|硬件)[^\n]{0,80}(?:NOT RUN|not_run)") self.assertRegex(corpus, r"(?i)(?:破坏性|全开|full open)") # Door 00 is full open under new contract (must warn), not old jog heartbeat. self.assertRegex(corpus, r"(?i)(?:00.*=.*全开|0\s*=\s*full open|全开)") # Must not claim old 450-step jog as active contract without negation. for line in corpus.splitlines(): if "450" in line and "jog" in line.lower(): self.assertRegex( line, r"(?i)(?:旧|legacy|historical|废弃|破坏|不再|not)", f"450 jog line not negated: {line!r}", ) def test_activity_docs_reject_stale_current_claims(self) -> None: for rel in ACTIVITY_DOCS: text = _read(rel) for pattern, message in STALE_AS_CURRENT: self.assertIsNone(pattern.search(text), f"{rel}: {message}") def test_final_delivery_mentions_pending_or_bound_td(self) -> None: text = _read("FINAL_DELIVERY_REPORT.md") self.assertTrue( PENDING_TIP_TD in text or "pending" in text.casefold() or "ARTIFACT-SOURCE" in text or "Bitstream SHA" in text or "intermediate" in text.casefold(), "FINAL_DELIVERY_REPORT must track TD bind / intermediate state", ) def test_activity_docs_reject_merge_dev_as_this_round_step(self) -> None: for rel in ("PLAN.md", "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md"): text = _read(rel) for line in text.splitlines(): if re.search(r"合入\s*(干净\s*)?`?dev`?", line) and not re.search( r"(?i)(?:不|勿|禁止|未|不要|等待|独立决策|not|never|no\b)", line, ): self.fail(f"{rel} presents merge-to-dev as active step: {line!r}") def test_activity_docs_reject_stale_in_progress_when_fixes_landed(self) -> None: corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS) # Must acknowledge P0/P1 landed or intermediate/TD-pending truth — not only "重构进行中". self.assertRegex( corpus, r"(?i)(?:已修|已落地|landed|P0/P1|intermediate|TD\s*(?:待|pending))", ) # If claiming final TD pass, must not still say 重构进行中 as the only status. if re.search(r"(?i)TD[^\n]{0,40}pass", corpus) and "9cd778" not in corpus: self.assertNotRegex(corpus, r"重构进行中") def test_root_runtime_residue_not_tracked_or_present(self) -> None: for name in ROOT_RESIDUE: self.assertFalse((ROOT / name).exists(), f"root residue still present: {name}") ignored = (ROOT / ".gitignore").read_text(encoding="utf-8") for token in (".run_id", ".run_id_linux", "evidence-batch-summary.txt"): self.assertIn(token, ignored) def test_cleanup_runtime_residue_helper_removes_root_probes(self) -> None: script = ROOT / "tools/cleanup_runtime_residue.py" self.assertTrue(script.is_file()) with tempfile.TemporaryDirectory(prefix="prod2u-residue-") as tmp: fake_root = Path(tmp) (fake_root / "AGENTS.md").write_text("x\n", encoding="utf-8") proj = fake_root / "projects" / "prod2u-door-temp" proj.mkdir(parents=True) (proj / "project.json").write_text("{}\n", encoding="utf-8") (fake_root / ".run_id").write_text("run\n", encoding="utf-8") (fake_root / ".run_id_linux").write_text("run\n", encoding="utf-8") (fake_root / "evidence-batch-summary.txt").write_text("old\n", encoding="utf-8") (fake_root / "td_20260804_probe.log").write_text("log\n", encoding="utf-8") nested = fake_root / "runs" / "td_20260804_probe.log" nested.parent.mkdir() nested.write_text("keep\n", encoding="utf-8") result = subprocess.run( ["python3", "-B", str(script), "--root", str(fake_root), "--json"], check=True, capture_output=True, text=True, ) self.assertIn('"count": 4', result.stdout) self.assertFalse((fake_root / ".run_id").exists()) self.assertTrue(nested.exists()) if __name__ == "__main__": unittest.main()