test_activity_docs_truth.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #!/usr/bin/env python3
  2. """Fail-closed consistency gates for active status docs vs door-percent contract."""
  3. from __future__ import annotations
  4. import re
  5. import subprocess
  6. import tempfile
  7. import unittest
  8. from pathlib import Path
  9. ROOT = Path(__file__).resolve().parents[2]
  10. TRUNCATE_SEMANTICS = "truncate_current_high_pulse_immediately_after_synchronized_limit"
  11. PENDING_TIP_TD = "pending final tip TD"
  12. ACTIVITY_DOCS = (
  13. "README.zh-CN.md",
  14. "FINAL_DELIVERY_REPORT.md",
  15. "ACCEPTANCE_MATRIX.md",
  16. "OPEN_QUESTIONS.md",
  17. "PLAN.md",
  18. "docs/TD_USAGE.zh-CN.md",
  19. "docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md",
  20. )
  21. PER_DOC_MARKERS = (
  22. "百分比",
  23. "0x03",
  24. "0x83",
  25. )
  26. CORPUS_REQUIRED = (
  27. TRUNCATE_SEMANTICS,
  28. "permanent_high",
  29. "5000",
  30. "30",
  31. "CON104",
  32. "CON105",
  33. "CON106",
  34. "CON120",
  35. "CON12",
  36. "CON129",
  37. "GET_MOTOR_STATUS",
  38. "startup_complete",
  39. "latest-wins",
  40. )
  41. STALE_AS_CURRENT = (
  42. (
  43. re.compile(r"(?i)P4_FIXED_MOTOR_STEPS"),
  44. "FIXED_MOTOR presented as current",
  45. ),
  46. (
  47. re.compile(r"(?i)(?:进风(?:门)?默认\*?电磁铁\*?|intake_solenoid_out)"),
  48. "solenoid intake presented as active product path",
  49. ),
  50. (
  51. re.compile(
  52. r"(?i)(?:X\s*限位[^\n]{0,40}CON68|Y\s*限位[^\n]{0,40}CON34)"
  53. ),
  54. "obsolete CON68/CON34 mapping presented as active probe",
  55. ),
  56. )
  57. # Round-12 tip authority must not appear as current (historical negation OK).
  58. MSE_STALE_AUTHORITY = (
  59. ("8403e020", "Round-12 ARTIFACT-SOURCE"),
  60. ("e0cf1321", "Round-12 bitstream"),
  61. ("2893", "Round-12 LUT count as current"),
  62. )
  63. ROOT_RESIDUE = (
  64. ".run_id",
  65. ".run_id_linux",
  66. "evidence-batch-summary.txt",
  67. )
  68. def _read(rel: str) -> str:
  69. return (ROOT / rel).read_text(encoding="utf-8")
  70. class ActivityDocsTruthTests(unittest.TestCase):
  71. def test_activity_docs_exist(self) -> None:
  72. missing = [rel for rel in ACTIVITY_DOCS if not (ROOT / rel).is_file()]
  73. self.assertEqual(missing, [], f"missing activity docs: {missing}")
  74. def test_each_activity_doc_carries_percent_protocol_markers(self) -> None:
  75. for rel in ACTIVITY_DOCS:
  76. text = _read(rel)
  77. for marker in PER_DOC_MARKERS:
  78. self.assertIn(marker, text, f"{rel} missing {marker!r}")
  79. def test_activity_docs_agree_on_percent_corpus(self) -> None:
  80. corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS)
  81. for marker in CORPUS_REQUIRED:
  82. self.assertIn(marker, corpus, f"activity corpus missing {marker!r}")
  83. self.assertRegex(corpus, r"(?i)(?:X\s*/\s*Y\s*/\s*Z|三轴)")
  84. self.assertRegex(corpus, r"(?i)(?:六限位|six limits)")
  85. self.assertRegex(corpus, r"(?i)(?:Hardware|硬件)[^\n]{0,80}(?:NOT RUN|not_run)")
  86. self.assertRegex(corpus, r"(?i)(?:破坏性|全开|full open)")
  87. # Door 00 is full open under new contract (must warn), not old jog heartbeat.
  88. self.assertRegex(corpus, r"(?i)(?:00.*=.*全开|0\s*=\s*full open|全开)")
  89. # Must not claim old 450-step jog as active contract without negation.
  90. for line in corpus.splitlines():
  91. if "450" in line and "jog" in line.lower():
  92. self.assertRegex(
  93. line,
  94. r"(?i)(?:旧|legacy|historical|废弃|破坏|不再|not)",
  95. f"450 jog line not negated: {line!r}",
  96. )
  97. def test_activity_docs_reject_stale_current_claims(self) -> None:
  98. for rel in ACTIVITY_DOCS:
  99. text = _read(rel)
  100. for pattern, message in STALE_AS_CURRENT:
  101. self.assertIsNone(pattern.search(text), f"{rel}: {message}")
  102. @staticmethod
  103. def _stale_authority_lines(text: str) -> list[str]:
  104. bad: list[str] = []
  105. for token, _label in MSE_STALE_AUTHORITY:
  106. for line in text.splitlines():
  107. if token not in line:
  108. continue
  109. if re.search(
  110. r"(?i)(?:历史|historical|retired|superseded|不再|不是|"
  111. r"不把|当作当前|not\s+(?:current|active)|旧\s*Round-12)",
  112. line,
  113. ):
  114. continue
  115. bad.append(line)
  116. return bad
  117. def test_activity_docs_mse_a1_current_authority(self) -> None:
  118. """Activity entry docs must describe MSE A1, not Round-12 tip authority."""
  119. entry = (
  120. "README.zh-CN.md",
  121. "FINAL_DELIVERY_REPORT.md",
  122. "ACCEPTANCE_MATRIX.md",
  123. "PLAN.md",
  124. "OPEN_QUESTIONS.md",
  125. )
  126. corpus = "\n".join(_read(rel) for rel in entry)
  127. for marker in (
  128. "MSE",
  129. "A1",
  130. "ff44128a",
  131. "4320",
  132. "preview/motor-shared-executor",
  133. "NOT RUN",
  134. ):
  135. self.assertIn(marker, corpus, f"MSE corpus missing {marker!r}")
  136. for rel in entry:
  137. bad = self._stale_authority_lines(_read(rel))
  138. self.assertEqual(bad, [], f"{rel}: Round-12 presented as current: {bad!r}")
  139. def test_negative_fixture_round12_as_current_fails(self) -> None:
  140. """Temp copy restoring Round-12 tip as current authority must be rejected."""
  141. poisoned = (
  142. "# fake activity\n"
  143. "当前权威 tip = 8403e020 / bitstream e0cf1321 / LUT 2893 / DSP0\n"
  144. "Round-12 fixed-speed is the active baseline.\n"
  145. )
  146. bad = self._stale_authority_lines(poisoned)
  147. self.assertTrue(
  148. bad,
  149. "negative fixture must detect 8403e020/e0cf1321/2893 as current authority",
  150. )
  151. self.assertTrue(any("8403e020" in line for line in bad))
  152. self.assertTrue(any("e0cf1321" in line for line in bad))
  153. self.assertTrue(any("2893" in line for line in bad))
  154. def test_activity_docs_reject_retired_tip_bits_as_current(self) -> None:
  155. """Round-9/10/11 tip bits may appear only as retired/historical, not as tip authority."""
  156. for rel in ACTIVITY_DOCS:
  157. text = _read(rel)
  158. for bit_prefix, label in (
  159. ("71a571a3", "Round-9 tip bit"),
  160. ("299ef1cf", "Round-10 tip bit"),
  161. ("4ce1dd7c", "Round-11 tip bit"),
  162. ):
  163. for line in text.splitlines():
  164. if bit_prefix not in line.casefold() and bit_prefix not in line:
  165. continue
  166. if re.search(
  167. r"(?i)(?:历史|historical|retired|superseded|不得|勿|do not|not tip|非.*tip)",
  168. line,
  169. ):
  170. continue
  171. # Allow short-hash tables that clearly mark Round-N tip bit(历史)
  172. if re.search(r"(?i)Round-\d+.*历史|历史\)", line):
  173. continue
  174. self.fail(f"{rel}: {label} presented without historical negation: {line!r}")
  175. def test_final_delivery_mentions_pending_or_bound_td(self) -> None:
  176. text = _read("FINAL_DELIVERY_REPORT.md")
  177. self.assertTrue(
  178. PENDING_TIP_TD in text
  179. or "pending" in text.casefold()
  180. or "ARTIFACT-SOURCE" in text
  181. or "Bitstream SHA" in text
  182. or "intermediate" in text.casefold(),
  183. "FINAL_DELIVERY_REPORT must track TD bind / intermediate state",
  184. )
  185. def test_activity_docs_reject_merge_dev_as_this_round_step(self) -> None:
  186. for rel in ("PLAN.md", "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md"):
  187. text = _read(rel)
  188. for line in text.splitlines():
  189. if re.search(r"合入\s*(干净\s*)?`?dev`?", line) and not re.search(
  190. r"(?i)(?:不|勿|禁止|未|不要|等待|独立决策|not|never|no\b)",
  191. line,
  192. ):
  193. self.fail(f"{rel} presents merge-to-dev as active step: {line!r}")
  194. def test_activity_docs_reject_stale_in_progress_when_fixes_landed(self) -> None:
  195. corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS)
  196. # Must acknowledge P0/P1 landed or intermediate/TD-pending truth — not only "重构进行中".
  197. self.assertRegex(
  198. corpus,
  199. r"(?i)(?:已修|已落地|landed|P0/P1|intermediate|TD\s*(?:待|pending))",
  200. )
  201. # If claiming final TD pass, must not still say 重构进行中 as the only status.
  202. if re.search(r"(?i)TD[^\n]{0,40}pass", corpus) and "9cd778" not in corpus:
  203. self.assertNotRegex(corpus, r"重构进行中")
  204. def test_root_runtime_residue_not_tracked_or_present(self) -> None:
  205. for name in ROOT_RESIDUE:
  206. self.assertFalse((ROOT / name).exists(), f"root residue still present: {name}")
  207. ignored = (ROOT / ".gitignore").read_text(encoding="utf-8")
  208. for token in (".run_id", ".run_id_linux", "evidence-batch-summary.txt"):
  209. self.assertIn(token, ignored)
  210. def test_cleanup_runtime_residue_helper_removes_root_probes(self) -> None:
  211. script = ROOT / "tools/cleanup_runtime_residue.py"
  212. self.assertTrue(script.is_file())
  213. with tempfile.TemporaryDirectory(prefix="prod2u-residue-") as tmp:
  214. fake_root = Path(tmp)
  215. (fake_root / "AGENTS.md").write_text("x\n", encoding="utf-8")
  216. proj = fake_root / "projects" / "prod2u-door-temp"
  217. proj.mkdir(parents=True)
  218. (proj / "project.json").write_text("{}\n", encoding="utf-8")
  219. (fake_root / ".run_id").write_text("run\n", encoding="utf-8")
  220. (fake_root / ".run_id_linux").write_text("run\n", encoding="utf-8")
  221. (fake_root / "evidence-batch-summary.txt").write_text("old\n", encoding="utf-8")
  222. (fake_root / "td_20260804_probe.log").write_text("log\n", encoding="utf-8")
  223. nested = fake_root / "runs" / "td_20260804_probe.log"
  224. nested.parent.mkdir()
  225. nested.write_text("keep\n", encoding="utf-8")
  226. result = subprocess.run(
  227. ["python3", "-B", str(script), "--root", str(fake_root), "--json"],
  228. check=True,
  229. capture_output=True,
  230. text=True,
  231. )
  232. self.assertIn('"count": 4', result.stdout)
  233. self.assertFalse((fake_root / ".run_id").exists())
  234. self.assertTrue(nested.exists())
  235. if __name__ == "__main__":
  236. unittest.main()