test_activity_docs_truth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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_r7_r8_not_current_without_negation(self) -> None:
  118. entry = (
  119. "README.zh-CN.md",
  120. "FINAL_DELIVERY_REPORT.md",
  121. "ACCEPTANCE_MATRIX.md",
  122. "PLAN.md",
  123. "OPEN_QUESTIONS.md",
  124. )
  125. negate = re.compile(
  126. r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|"
  127. r"将被|取代|not\s+current|stale"
  128. )
  129. for rel in entry:
  130. text = _read(rel)
  131. for token in (
  132. "mse-r7-20260812T132652Z",
  133. "21ed755ad2ddb6689bca88a9a037b391372a060e",
  134. "3177c2f0",
  135. ):
  136. for line in text.splitlines():
  137. if token not in line:
  138. continue
  139. if negate.search(line):
  140. continue
  141. self.fail(
  142. f"{rel}: R7/R8 token presented as current without negation: {line!r}"
  143. )
  144. def test_activity_docs_mse_a1_current_authority(self) -> None:
  145. """Activity entry docs must describe MSE A1, not Round-12 tip authority."""
  146. entry = (
  147. "README.zh-CN.md",
  148. "FINAL_DELIVERY_REPORT.md",
  149. "ACCEPTANCE_MATRIX.md",
  150. "PLAN.md",
  151. "OPEN_QUESTIONS.md",
  152. )
  153. corpus = "\n".join(_read(rel) for rel in entry)
  154. for marker in (
  155. "MSE",
  156. "A1",
  157. "ff44128a",
  158. "4320",
  159. "preview/motor-shared-executor",
  160. "NOT RUN",
  161. ):
  162. self.assertIn(marker, corpus, f"MSE corpus missing {marker!r}")
  163. for rel in entry:
  164. bad = self._stale_authority_lines(_read(rel))
  165. self.assertEqual(bad, [], f"{rel}: Round-12 presented as current: {bad!r}")
  166. def test_negative_fixture_round12_as_current_fails(self) -> None:
  167. """Temp copy restoring Round-12 tip as current authority must be rejected."""
  168. poisoned = (
  169. "# fake activity\n"
  170. "当前权威 tip = 8403e020 / bitstream e0cf1321 / LUT 2893 / DSP0\n"
  171. "Round-12 fixed-speed is the active baseline.\n"
  172. )
  173. bad = self._stale_authority_lines(poisoned)
  174. self.assertTrue(
  175. bad,
  176. "negative fixture must detect 8403e020/e0cf1321/2893 as current authority",
  177. )
  178. self.assertTrue(any("8403e020" in line for line in bad))
  179. self.assertTrue(any("e0cf1321" in line for line in bad))
  180. self.assertTrue(any("2893" in line for line in bad))
  181. def test_activity_docs_reject_retired_tip_bits_as_current(self) -> None:
  182. """Round-9/10/11 tip bits may appear only as retired/historical, not as tip authority."""
  183. for rel in ACTIVITY_DOCS:
  184. text = _read(rel)
  185. for bit_prefix, label in (
  186. ("71a571a3", "Round-9 tip bit"),
  187. ("299ef1cf", "Round-10 tip bit"),
  188. ("4ce1dd7c", "Round-11 tip bit"),
  189. ):
  190. for line in text.splitlines():
  191. if bit_prefix not in line.casefold() and bit_prefix not in line:
  192. continue
  193. if re.search(
  194. r"(?i)(?:历史|historical|retired|superseded|不得|勿|do not|not tip|非.*tip)",
  195. line,
  196. ):
  197. continue
  198. # Allow short-hash tables that clearly mark Round-N tip bit(历史)
  199. if re.search(r"(?i)Round-\d+.*历史|历史\)", line):
  200. continue
  201. self.fail(f"{rel}: {label} presented without historical negation: {line!r}")
  202. def test_final_delivery_mentions_pending_or_bound_td(self) -> None:
  203. text = _read("FINAL_DELIVERY_REPORT.md")
  204. self.assertTrue(
  205. PENDING_TIP_TD in text
  206. or "pending" in text.casefold()
  207. or "ARTIFACT-SOURCE" in text
  208. or "Bitstream SHA" in text
  209. or "intermediate" in text.casefold(),
  210. "FINAL_DELIVERY_REPORT must track TD bind / intermediate state",
  211. )
  212. def test_activity_docs_reject_merge_dev_as_this_round_step(self) -> None:
  213. for rel in ("PLAN.md", "README.zh-CN.md", "FINAL_DELIVERY_REPORT.md"):
  214. text = _read(rel)
  215. for line in text.splitlines():
  216. if re.search(r"合入\s*(干净\s*)?`?dev`?", line) and not re.search(
  217. r"(?i)(?:不|勿|禁止|未|不要|等待|独立决策|not|never|no\b)",
  218. line,
  219. ):
  220. self.fail(f"{rel} presents merge-to-dev as active step: {line!r}")
  221. def test_activity_docs_reject_stale_in_progress_when_fixes_landed(self) -> None:
  222. corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS)
  223. # Must acknowledge P0/P1 landed or intermediate/TD-pending truth — not only "重构进行中".
  224. self.assertRegex(
  225. corpus,
  226. r"(?i)(?:已修|已落地|landed|P0/P1|intermediate|TD\s*(?:待|pending))",
  227. )
  228. # If claiming final TD pass, must not still say 重构进行中 as the only status.
  229. if re.search(r"(?i)TD[^\n]{0,40}pass", corpus) and "9cd778" not in corpus:
  230. self.assertNotRegex(corpus, r"重构进行中")
  231. def test_root_runtime_residue_not_tracked_or_present(self) -> None:
  232. for name in ROOT_RESIDUE:
  233. self.assertFalse((ROOT / name).exists(), f"root residue still present: {name}")
  234. ignored = (ROOT / ".gitignore").read_text(encoding="utf-8")
  235. for token in (".run_id", ".run_id_linux", "evidence-batch-summary.txt"):
  236. self.assertIn(token, ignored)
  237. def test_cleanup_runtime_residue_helper_removes_root_probes(self) -> None:
  238. script = ROOT / "tools/cleanup_runtime_residue.py"
  239. self.assertTrue(script.is_file())
  240. with tempfile.TemporaryDirectory(prefix="prod2u-residue-") as tmp:
  241. fake_root = Path(tmp)
  242. (fake_root / "AGENTS.md").write_text("x\n", encoding="utf-8")
  243. proj = fake_root / "projects" / "prod2u-door-temp"
  244. proj.mkdir(parents=True)
  245. (proj / "project.json").write_text("{}\n", encoding="utf-8")
  246. (fake_root / ".run_id").write_text("run\n", encoding="utf-8")
  247. (fake_root / ".run_id_linux").write_text("run\n", encoding="utf-8")
  248. (fake_root / "evidence-batch-summary.txt").write_text("old\n", encoding="utf-8")
  249. (fake_root / "td_20260804_probe.log").write_text("log\n", encoding="utf-8")
  250. nested = fake_root / "runs" / "td_20260804_probe.log"
  251. nested.parent.mkdir()
  252. nested.write_text("keep\n", encoding="utf-8")
  253. result = subprocess.run(
  254. ["python3", "-B", str(script), "--root", str(fake_root), "--json"],
  255. check=True,
  256. capture_output=True,
  257. text=True,
  258. )
  259. self.assertIn('"count": 4', result.stdout)
  260. self.assertFalse((fake_root / ".run_id").exists())
  261. self.assertTrue(nested.exists())
  262. if __name__ == "__main__":
  263. unittest.main()