#!/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", ), ) # Round-12 tip authority must not appear as current (historical negation OK). MSE_STALE_AUTHORITY = ( ("8403e020", "Round-12 ARTIFACT-SOURCE"), ("e0cf1321", "Round-12 bitstream"), ("2893", "Round-12 LUT count as current"), ) 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}") @staticmethod def _stale_authority_lines(text: str) -> list[str]: bad: list[str] = [] for token, _label in MSE_STALE_AUTHORITY: for line in text.splitlines(): if token not in line: continue if re.search( r"(?i)(?:历史|historical|retired|superseded|不再|不是|" r"不把|当作当前|not\s+(?:current|active)|旧\s*Round-12)", line, ): continue bad.append(line) return bad def test_activity_docs_r7_r8_not_current_without_negation(self) -> None: entry = ( "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md", "ACCEPTANCE_MATRIX.md", "PLAN.md", "OPEN_QUESTIONS.md", ) negate = re.compile( r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|" r"将被|取代|not\s+current|stale" ) for rel in entry: text = _read(rel) for token in ( "mse-r7-20260812T132652Z", "21ed755ad2ddb6689bca88a9a037b391372a060e", "3177c2f0", ): for line in text.splitlines(): if token not in line: continue if negate.search(line): continue self.fail( f"{rel}: R7/R8 token presented as current without negation: {line!r}" ) def test_activity_docs_mse_a1_current_authority(self) -> None: """Activity entry docs must describe MSE A1, not Round-12 tip authority.""" entry = ( "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md", "ACCEPTANCE_MATRIX.md", "PLAN.md", "OPEN_QUESTIONS.md", ) corpus = "\n".join(_read(rel) for rel in entry) for marker in ( "MSE", "A1", "ff44128a", "4320", "preview/motor-shared-executor", "NOT RUN", ): self.assertIn(marker, corpus, f"MSE corpus missing {marker!r}") for rel in entry: bad = self._stale_authority_lines(_read(rel)) self.assertEqual(bad, [], f"{rel}: Round-12 presented as current: {bad!r}") def test_negative_fixture_round12_as_current_fails(self) -> None: """Temp copy restoring Round-12 tip as current authority must be rejected.""" poisoned = ( "# fake activity\n" "当前权威 tip = 8403e020 / bitstream e0cf1321 / LUT 2893 / DSP0\n" "Round-12 fixed-speed is the active baseline.\n" ) bad = self._stale_authority_lines(poisoned) self.assertTrue( bad, "negative fixture must detect 8403e020/e0cf1321/2893 as current authority", ) self.assertTrue(any("8403e020" in line for line in bad)) self.assertTrue(any("e0cf1321" in line for line in bad)) self.assertTrue(any("2893" in line for line in bad)) def test_activity_docs_reject_retired_tip_bits_as_current(self) -> None: """Round-9/10/11 tip bits may appear only as retired/historical, not as tip authority.""" for rel in ACTIVITY_DOCS: text = _read(rel) for bit_prefix, label in ( ("71a571a3", "Round-9 tip bit"), ("299ef1cf", "Round-10 tip bit"), ("4ce1dd7c", "Round-11 tip bit"), ): for line in text.splitlines(): if bit_prefix not in line.casefold() and bit_prefix not in line: continue if re.search( r"(?i)(?:历史|historical|retired|superseded|不得|勿|do not|not tip|非.*tip)", line, ): continue # Allow short-hash tables that clearly mark Round-N tip bit(历史) if re.search(r"(?i)Round-\d+.*历史|历史\)", line): continue self.fail(f"{rel}: {label} presented without historical negation: {line!r}") 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()) def test_package_authority_pointers_present(self) -> None: from tools.current_evidence import PACKAGE_AUTHORITY_POINTERS, STABLE_TD_MARKERS corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS) for pointer in PACKAGE_AUTHORITY_POINTERS: self.assertIn(pointer, corpus, f"missing package-authority pointer {pointer}") for marker in STABLE_TD_MARKERS: self.assertIn(marker, corpus, f"missing stable TD marker {marker}") def test_generic_stale_run_id_as_current_fails(self) -> None: from tools.current_evidence import stale_current_doc_failures poisoned = "当前软件矩阵 run = mse-r10-20260813T030321Z\n" failures = stale_current_doc_failures(poisoned) self.assertTrue(any("mse_run_id_as_current" in item for item in failures), failures) historical = "历史软件矩阵 run = mse-r10-20260813T030321Z(superseded)\n" self.assertEqual(stale_current_doc_failures(historical), []) def test_r12_final_delivery_fixture_fails(self) -> None: from tools.current_evidence import stale_current_doc_failures fixture = ( "# FINAL_DELIVERY_REPORT — MSE A1(Round-10 release/provenance closure)\n" "| matrix_verification_tip | `e3f23c2e1fcb2cc9481781680f66a5dc62c83375` |\n" "| software_verification_run_id | `mse-r10-20260813T030321Z` |\n" ) failures = stale_current_doc_failures(fixture) self.assertTrue(failures, "exact Round-12 stale current docs must FAIL") if __name__ == "__main__": unittest.main()