debug_contract.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. #!/usr/bin/env python3
  2. """Debug-max event, bundle, and agent-analysis helpers."""
  3. from __future__ import annotations
  4. import csv
  5. import hashlib
  6. import json
  7. import shutil
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from typing import Any, Iterable
  11. from pid_contract_model import config_contract_summary
  12. from toolchain_probe import probe_toolchain
  13. DEBUG_EVENT_REQUIRED_FIELDS = [
  14. "timebase",
  15. "trace_seq",
  16. "event_type",
  17. "source_id",
  18. "channel",
  19. "sample_seq",
  20. "config_seq",
  21. "state",
  22. "fault_code",
  23. "reason",
  24. "temp_q",
  25. "target_q",
  26. "error_q",
  27. "ctrl_q",
  28. "ptc_duty",
  29. "ptc_pwm",
  30. "fan_duty",
  31. "tach_edges",
  32. "rpm_estimate",
  33. ]
  34. FAULT_CODE_OK = 0
  35. FAULT_CODE_HOST_DISABLED = 1
  36. FAULT_CODE_SENSOR_FAULT = 2
  37. FAULT_CODE_SENSOR_STALE = 3
  38. FAULT_CODE_HOST_TIMEOUT = 4
  39. FAULT_CODE_OVERTEMP = 5
  40. FAULT_CODE_INVALID_CHANNEL = 6
  41. FAULT_CODE_INTERLOCK = 7
  42. THERMAL_FALLBACK_FAULTS = {
  43. FAULT_CODE_SENSOR_FAULT,
  44. FAULT_CODE_SENSOR_STALE,
  45. FAULT_CODE_HOST_TIMEOUT,
  46. FAULT_CODE_OVERTEMP,
  47. }
  48. def _as_int(value: Any, default: int = 0) -> int:
  49. if isinstance(value, bool):
  50. return int(value)
  51. if isinstance(value, int):
  52. return value
  53. if value is None:
  54. return default
  55. try:
  56. return int(value)
  57. except (TypeError, ValueError):
  58. return default
  59. def _as_bool(value: Any) -> bool:
  60. if isinstance(value, bool):
  61. return value
  62. if isinstance(value, str):
  63. return value.strip().lower() in {"1", "true", "yes", "y", "on"}
  64. return bool(value)
  65. def normalize_replay_trace(trace: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
  66. """Convert replay trace rows into debug_event_v1 dictionaries."""
  67. events: list[dict[str, Any]] = []
  68. for row in trace:
  69. fault_code = _as_int(row.get("fault_code"))
  70. force_off = _as_bool(row.get("force_off"))
  71. if fault_code != FAULT_CODE_OK:
  72. event_type = "fault_raised"
  73. elif force_off:
  74. event_type = "force_off"
  75. else:
  76. event_type = "control_updated"
  77. event = {
  78. "timebase": "replay_sample",
  79. "trace_seq": _as_int(row.get("trace_seq"), len(events) + 1),
  80. "event_type": event_type,
  81. "source_id": _as_int(row.get("source_id")),
  82. "channel": _as_int(row.get("channel"), -1),
  83. "sample_seq": _as_int(row.get("sample_seq")),
  84. "config_seq": _as_int(row.get("config_seq")),
  85. "state": str(row.get("control_mode", row.get("state", "unknown"))),
  86. "fault_code": fault_code,
  87. "reason": str(row.get("reason", "unknown")),
  88. "temp_q": _as_int(row.get("temp_q")),
  89. "target_q": _as_int(row.get("target_q")),
  90. "error_q": _as_int(row.get("error_q")),
  91. "ctrl_q": _as_int(row.get("ctrl_q")),
  92. "ptc_duty": _as_int(row.get("ptc_duty", row.get("duty_or_level"))),
  93. "ptc_pwm": _as_int(row.get("ptc_pwm", row.get("ptc_pwm_out"))),
  94. "fan_duty": _as_int(row.get("fan_duty")),
  95. "tach_edges": _as_int(row.get("tach_window_edges", row.get("tach_edge_count"))),
  96. "rpm_estimate": _as_int(row.get("rpm_estimate")),
  97. "sensor_ready": _as_bool(row.get("sensor_ready", True)),
  98. "sensor_valid": _as_bool(row.get("sensor_valid", True)),
  99. "force_off": force_off,
  100. "host_enable": row.get("reason") != "host_disabled",
  101. "clamped": _as_bool(row.get("clamped", False)),
  102. "history_cleared": _as_bool(row.get("history_cleared", False)),
  103. "fan_pwm_drive_low": _as_int(row.get("fan_pwm_drive_low")),
  104. "fan_pwm_logic_high": _as_int(row.get("fan_pwm_logic_high")),
  105. "ptc_pwm_high_ticks": _as_int(row.get("ptc_pwm_high_ticks")),
  106. "ptc_pwm_period_ticks": _as_int(row.get("ptc_pwm_period_ticks")),
  107. "fan_pwm_high_ticks": _as_int(row.get("fan_pwm_high_ticks")),
  108. "fan_pwm_period_ticks": _as_int(row.get("fan_pwm_period_ticks")),
  109. }
  110. _ensure_required_fields(event)
  111. events.append(event)
  112. return events
  113. def _ensure_required_fields(event: dict[str, Any]) -> None:
  114. missing = [field for field in DEBUG_EVENT_REQUIRED_FIELDS if field not in event]
  115. if missing:
  116. raise ValueError(f"debug event missing required fields: {', '.join(missing)}")
  117. def check_debug_invariants(events: list[dict[str, Any]]) -> dict[str, Any]:
  118. checks: dict[str, dict[str, Any]] = {}
  119. ptc_violations = [
  120. event for event in events
  121. if _as_bool(event.get("force_off")) and _as_int(event.get("ptc_pwm")) != 0
  122. ]
  123. checks["ptc_off_when_force_off"] = {
  124. "pass": not ptc_violations,
  125. "violation_count": len(ptc_violations),
  126. "description": "force_off events must drive PTC PWM request low",
  127. }
  128. fan_violations = [
  129. event for event in events
  130. if _as_int(event.get("fault_code")) in THERMAL_FALLBACK_FAULTS
  131. and _as_int(event.get("fan_duty")) != 127
  132. ]
  133. checks["fan_fallback_on_thermal_fault"] = {
  134. "pass": not fan_violations,
  135. "violation_count": len(fan_violations),
  136. "description": "sensor/stale/timeout/overtemp faults must request fan fallback",
  137. }
  138. duty_violations = [
  139. event for event in events
  140. if not (0 <= _as_int(event.get("ptc_duty")) <= 127 and 0 <= _as_int(event.get("fan_duty")) <= 127)
  141. ]
  142. checks["pwm_duty_in_range"] = {
  143. "pass": not duty_violations,
  144. "violation_count": len(duty_violations),
  145. "description": "PTC and fan duty levels must stay in 0..127",
  146. }
  147. tach_violations = [
  148. event for event in events
  149. if _as_int(event.get("tach_edges")) < 0 or _as_int(event.get("rpm_estimate")) < 0
  150. ]
  151. checks["tach_rpm_non_negative"] = {
  152. "pass": not tach_violations,
  153. "violation_count": len(tach_violations),
  154. "description": "TACH edges and RPM estimates must not be negative",
  155. }
  156. host_disable_violations = [
  157. event for event in events
  158. if _as_int(event.get("fault_code")) == FAULT_CODE_HOST_DISABLED
  159. and _as_int(event.get("ptc_pwm")) != 0
  160. ]
  161. checks["host_disable_ptc_off"] = {
  162. "pass": not host_disable_violations,
  163. "violation_count": len(host_disable_violations),
  164. "description": "host disable must keep PTC off",
  165. }
  166. return {
  167. "schema": "pid-debug-invariants-v1",
  168. "status": "pass" if all(item["pass"] for item in checks.values()) else "fail",
  169. "checks": checks,
  170. }
  171. def build_debug_bundle(
  172. *,
  173. output_dir: Path,
  174. source: str,
  175. trace: list[dict[str, Any]],
  176. pipeline: dict[str, Any],
  177. register_dump: dict[str, Any],
  178. raw_files: dict[str, str] | None = None,
  179. raw_artifacts: list[Path] | None = None,
  180. scenario: dict[str, Any] | None = None,
  181. sim_results: dict[str, Any] | None = None,
  182. formal_results: dict[str, Any] | None = None,
  183. detector_selftest_results: dict[str, Any] | None = None,
  184. td_results: dict[str, Any] | None = None,
  185. hardware_observations: dict[str, Any] | None = None,
  186. toolchain: dict[str, Any] | None = None,
  187. ) -> dict[str, Any]:
  188. """Write an agent-readable debug bundle directory."""
  189. output_dir.mkdir(parents=True, exist_ok=True)
  190. raw_dir = output_dir / "raw"
  191. raw_dir.mkdir(exist_ok=True)
  192. for name, content in (raw_files or {}).items():
  193. safe_name = Path(name).name
  194. (raw_dir / safe_name).write_text(content, encoding="utf-8")
  195. _copy_raw_artifacts(raw_dir, raw_artifacts or [])
  196. raw_manifest = _raw_file_manifest(raw_dir)
  197. for event in trace:
  198. _ensure_required_fields(event)
  199. invariants = check_debug_invariants(trace)
  200. hardware_payload = _hardware_payload_for_source(source, hardware_observations, raw_manifest)
  201. manifest = {
  202. "schema": "pid-debug-bundle-v1",
  203. "source": source,
  204. "generated_at": datetime.now(timezone.utc).isoformat(),
  205. "event_count": len(trace),
  206. "agent_entrypoint": "agent_context.md",
  207. "trace_file": "trace.jsonl",
  208. "invariants_file": "invariants.json",
  209. "provenance_file": "provenance.json",
  210. "toolchain_file": "toolchain.json",
  211. "scenario_file": "scenario.json",
  212. "sim_results_file": "sim_results.json",
  213. "formal_results_file": "formal_results.json",
  214. "detector_selftest_results_file": "detector_selftest_results.json",
  215. "td_results_file": "td_results.json",
  216. "hardware_observations_file": "hardware_observations.json",
  217. "hardware_status": hardware_payload.get("status", "not_run"),
  218. "uart_status": hardware_payload.get("instruments", {}).get("uart_ttl", "not_run"),
  219. "raw_file_count": len(raw_manifest),
  220. "raw_files": raw_manifest,
  221. }
  222. provenance = {
  223. "schema": "pid-evidence-provenance-v1",
  224. "fact_classes": {
  225. "debug_bundle": "project_defined_strategy",
  226. "trace": "project_defined_strategy",
  227. "pipeline": "local_detected_fact" if pipeline.get("status") not in {None, "not_run"} else "not_verified",
  228. "register_dump": "local_detected_fact" if register_dump else "not_verified",
  229. "hardware_observations": (
  230. "local_detected_fact"
  231. if hardware_payload.get("status") in {"uart_manual_export_attached", "uart_board_sram_pass"}
  232. else "not_verified"
  233. ),
  234. "raw_artifacts": "local_detected_fact" if raw_manifest else "not_verified",
  235. },
  236. "authority_boundary": "This bundle is an analysis evidence package, not proof of real thermal closed-loop behavior.",
  237. }
  238. scenario_payload = scenario or {
  239. "schema": "pid-scenario-v1",
  240. "name": f"{source}_default",
  241. "source": source,
  242. "expected_invariants": list(invariants["checks"].keys()),
  243. }
  244. sim_payload = sim_results or {"status": "not_run", "reason": "No HDL simulator evidence supplied for this bundle."}
  245. formal_payload = formal_results or {"status": "not_run", "reason": "No formal evidence supplied for this bundle."}
  246. detector_selftest_payload = detector_selftest_results or {
  247. "status": "not_run",
  248. "reason": "No detector selftest evidence supplied for this bundle.",
  249. }
  250. td_payload = td_results or {"status": "not_run", "reason": "No TD evidence supplied for this bundle."}
  251. _write_json(output_dir / "manifest.json", manifest)
  252. _write_json(output_dir / "provenance.json", provenance)
  253. _write_json(output_dir / "toolchain.json", toolchain or probe_toolchain())
  254. _write_json(output_dir / "scenario.json", scenario_payload)
  255. _write_json(output_dir / "sim_results.json", sim_payload)
  256. _write_json(output_dir / "formal_results.json", formal_payload)
  257. _write_json(output_dir / "detector_selftest_results.json", detector_selftest_payload)
  258. _write_json(output_dir / "td_results.json", td_payload)
  259. _write_json(output_dir / "hardware_observations.json", hardware_payload)
  260. _write_json(output_dir / "pipeline.json", pipeline)
  261. _write_json(output_dir / "config.json", config_contract_summary())
  262. _write_json(output_dir / "register_dump.json", register_dump)
  263. _write_json(output_dir / "invariants.json", invariants)
  264. _write_jsonl(output_dir / "trace.jsonl", trace)
  265. _write_csv(output_dir / "events.csv", trace)
  266. _write_agent_context(output_dir / "agent_context.md", manifest, invariants)
  267. return {
  268. "status": invariants["status"],
  269. "path": str(output_dir),
  270. "manifest": manifest,
  271. "invariants": invariants,
  272. }
  273. def analyze_debug_bundle(bundle_dir: Path) -> dict[str, Any]:
  274. trace_path = bundle_dir / "trace.jsonl"
  275. invariants_path = bundle_dir / "invariants.json"
  276. events = [
  277. json.loads(line)
  278. for line in trace_path.read_text(encoding="utf-8").splitlines()
  279. if line.strip()
  280. ]
  281. invariants = json.loads(invariants_path.read_text(encoding="utf-8"))
  282. sim_results = _read_optional_json(bundle_dir / "sim_results.json")
  283. formal_results = _read_optional_json(bundle_dir / "formal_results.json")
  284. detector_selftest_results = _read_optional_json(bundle_dir / "detector_selftest_results.json")
  285. td_results = _read_optional_json(bundle_dir / "td_results.json")
  286. hardware_observations = _read_optional_json(bundle_dir / "hardware_observations.json")
  287. hints: list[str] = []
  288. trace_seqs = [_as_int(event.get("trace_seq")) for event in events]
  289. if trace_seqs:
  290. sorted_seqs = sorted(trace_seqs)
  291. for prev, current in zip(sorted_seqs, sorted_seqs[1:]):
  292. if current != prev + 1:
  293. hints.append(f"trace sequence gap between {prev} and {current}; inspect dropped debug events or recorder overflow.")
  294. break
  295. if any(not _as_bool(event.get("sensor_ready", True)) for event in events):
  296. hints.append("PID/control may be waiting because sensor_ready=0; inspect producer backpressure and source_select.")
  297. if any(not _as_bool(event.get("host_enable", True)) or event.get("reason") == "host_disabled" for event in events):
  298. hints.append("PTC/PID output is gated because host disabled control; inspect host_config enable/config_seq.")
  299. if any("safety" in str(event.get("reason", "")) for event in events):
  300. hints.append("Output is blocked by safety gate; inspect fault_code, interlock, stale, timeout, and overtemp fields.")
  301. if any(_as_int(event.get("fault_code")) == FAULT_CODE_OVERTEMP for event in events):
  302. hints.append("PTC force-off is explained by overtemp gate; inspect temp_q, target_q, and fault latch clear path.")
  303. if any(_as_int(event.get("fault_code")) == FAULT_CODE_HOST_DISABLED for event in events):
  304. hints.append("host disabled path is active; PTC must stay off until enable/config policy changes.")
  305. if any(_as_int(event.get("fault_code")) == FAULT_CODE_INVALID_CHANNEL for event in events):
  306. hints.append("Invalid channel event blocked output; inspect channel mapping before PID.")
  307. if any(_as_bool(event.get("force_off")) for event in events):
  308. hints.append("PTC/PWM force_off is asserted; inspect reason and force_off_reason before checking PWM wiring.")
  309. if any(_as_int(event.get("fan_duty")) == 127 for event in events):
  310. hints.append("fan fallback duty is active; inspect thermal fault or safety fallback policy.")
  311. if invariants["status"] != "pass":
  312. failed = [name for name, item in invariants["checks"].items() if not item["pass"]]
  313. hints.append("Invariant failure: " + ", ".join(failed))
  314. _append_tool_result_hints(hints, "HDL simulation", sim_results)
  315. _append_tool_result_hints(hints, "formal verification", formal_results)
  316. _append_tool_result_hints(hints, "detector selftest", detector_selftest_results)
  317. _append_tool_result_hints(hints, "TD build", td_results)
  318. _append_hardware_observation_hints(hints, hardware_observations)
  319. if not hints:
  320. hints.append("No root-cause hint triggered; inspect trace_seq ordering, UART transcript, and register dump evidence.")
  321. return {
  322. "schema": "pid-debug-analysis-v1",
  323. "status": "pass" if trace_path.is_file() and invariants_path.is_file() else "fail",
  324. "event_count": len(events),
  325. "invariants_status": invariants["status"],
  326. "hardware_status": hardware_observations.get("status", "not_run"),
  327. "root_cause_hints": hints,
  328. }
  329. def _read_optional_json(path: Path) -> dict[str, Any]:
  330. if not path.is_file():
  331. return {"status": "not_run", "reason": f"{path.name} is missing"}
  332. try:
  333. return json.loads(path.read_text(encoding="utf-8"))
  334. except json.JSONDecodeError as exc:
  335. return {"status": "fail", "reason": f"{path.name} is not valid JSON: {exc}"}
  336. def _append_tool_result_hints(hints: list[str], label: str, payload: dict[str, Any]) -> None:
  337. status = payload.get("status")
  338. if status == "blocked_missing_tool":
  339. missing = payload.get("missing_tools")
  340. if not missing:
  341. missing = []
  342. for item in _iter_result_items(payload, "results", "tests", "targets", "backend_results"):
  343. missing.extend(item.get("missing_tools", []))
  344. missing.extend(item.get("required_tools", []) if item.get("status") == "blocked_missing_tool" else [])
  345. missing_text = ", ".join(sorted(set(missing))) if missing else "unknown tool"
  346. hints.append(f"{label} did not run because external tool is missing: {missing_text}.")
  347. elif status == "fail":
  348. hints.append(f"{label} failed; inspect its result JSON for compile, lint, scoreboard, counterexample, or TD errors.")
  349. elif status == "partial":
  350. missing = []
  351. for item in _iter_result_items(payload, "results", "tests", "targets", "backend_results"):
  352. missing.extend(item.get("missing_tools", []))
  353. missing_text = ", ".join(sorted(set(missing))) if missing else "some external tools"
  354. hints.append(f"{label} partially ran; installed backends produced evidence, missing tools blocked the rest: {missing_text}.")
  355. def _append_hardware_observation_hints(hints: list[str], payload: dict[str, Any]) -> None:
  356. status = payload.get("status")
  357. instruments = payload.get("instruments", {})
  358. uart_status = instruments.get("uart_ttl")
  359. raw_files = payload.get("raw_files", [])
  360. raw_count = payload.get("raw_file_count", len(raw_files) if isinstance(raw_files, list) else 0)
  361. preflight_count = len([
  362. item
  363. for item in raw_files
  364. if isinstance(item, dict) and item.get("artifact_role") == "uart_preflight_artifact"
  365. ])
  366. if status == "uart_preflight_artifacts_attached":
  367. hints.append(
  368. f"UART preflight/build artifacts are archived under raw/ ({preflight_count or raw_count} file(s)), but no UART transcript/debug CSV/manual export is attached yet."
  369. )
  370. elif status == "uart_manual_export_missing" or uart_status == "manual_export_missing":
  371. hints.append(
  372. "UART manual export is missing; attach serial transcript, debug UART CSV/log, register dump, screenshot, or receipt files under raw/ or pass --raw-file/--raw-dir."
  373. )
  374. elif status == "uart_board_sram_pass" or uart_status == "board_sram_pass":
  375. hints.append(
  376. f"UART board SRAM evidence is attached under raw/ ({raw_count} file(s)); treat it as communication and software safety evidence, not proof of real thermal performance."
  377. )
  378. csv_summaries = [
  379. item.get("csv", {})
  380. for item in raw_files
  381. if isinstance(item, dict) and item.get("csv", {}).get("status") != "not_csv"
  382. ]
  383. if any(item.get("status") == "recognized_debug_event_fields" for item in csv_summaries):
  384. hints.append("At least one UART debug CSV has standard debug_event_v1 headers and can be compared with trace.jsonl fields.")
  385. elif csv_summaries:
  386. hints.append("UART CSV/log files are archived; inspect transcript hash and parser status in the receipt.")
  387. elif status == "uart_manual_export_attached" or uart_status == "manual_export_attached":
  388. hints.append(
  389. f"UART manual export is attached under raw/ ({raw_count} file(s)); treat it as communication/debug evidence, not proof of real thermal performance."
  390. )
  391. csv_summaries = [
  392. item.get("csv", {})
  393. for item in raw_files
  394. if isinstance(item, dict) and item.get("csv", {}).get("status") != "not_csv"
  395. ]
  396. if any(item.get("status") == "recognized_debug_event_fields" for item in csv_summaries):
  397. hints.append("At least one UART debug CSV has standard debug_event_v1 headers and can be compared with trace.jsonl fields.")
  398. elif csv_summaries:
  399. hints.append("UART CSV files are archived, but their headers do not map to the standard debug_event_v1 field set yet.")
  400. def _hardware_payload_for_source(
  401. source: str,
  402. hardware_observations: dict[str, Any] | None,
  403. raw_manifest: list[dict[str, Any]],
  404. ) -> dict[str, Any]:
  405. if hardware_observations is not None:
  406. payload = dict(hardware_observations)
  407. elif source == "uart":
  408. manual_attached = any(item.get("artifact_role") == "uart_transcript_or_debug_export" for item in raw_manifest)
  409. preflight_attached = bool(raw_manifest)
  410. if manual_attached:
  411. status = "uart_manual_export_attached"
  412. uart_ttl = "manual_export_attached"
  413. reason = "UART transcript/debug/register export files are attached under raw/."
  414. elif preflight_attached:
  415. status = "uart_preflight_artifacts_attached"
  416. uart_ttl = "manual_export_missing"
  417. reason = "UART preflight or build artifacts are attached under raw/, but no UART transcript/debug CSV/manual export is present."
  418. else:
  419. status = "uart_manual_export_missing"
  420. uart_ttl = "manual_export_missing"
  421. reason = "No UART transcript/debug/register manual export files were supplied."
  422. payload = {
  423. "schema": "pid-hardware-observations-v1",
  424. "status": status,
  425. "reason": reason,
  426. "authority_boundary": (
  427. "UART evidence proves transcript/debug/register observations only. It does not prove real PTC heating, real fan RPM, or full thermal performance."
  428. ),
  429. "instruments": {
  430. "multimeter": "not_run",
  431. "oscilloscope": "not_run",
  432. "logic_analyzer": "not_run",
  433. "uart_ttl": uart_ttl,
  434. "rs232_level_shifter": "not_run",
  435. "i2c_register_readback": "not_run",
  436. },
  437. }
  438. else:
  439. payload = {
  440. "status": "not_run",
  441. "reason": "No board, wiring, instrument, UART transcript, or register observation supplied.",
  442. "instruments": {
  443. "multimeter": "not_run",
  444. "oscilloscope": "not_run",
  445. "logic_analyzer": "not_run",
  446. "uart_ttl": "not_run",
  447. "rs232_level_shifter": "not_run",
  448. "i2c_register_readback": "not_run",
  449. },
  450. }
  451. payload["raw_file_count"] = len(raw_manifest)
  452. payload["raw_files"] = raw_manifest
  453. return payload
  454. def _copy_raw_artifacts(raw_dir: Path, artifacts: list[Path]) -> None:
  455. for artifact in artifacts:
  456. source = Path(artifact)
  457. if not source.exists():
  458. raise FileNotFoundError(f"raw artifact not found: {source}")
  459. if source.is_dir():
  460. try:
  461. if source.resolve() == raw_dir.resolve():
  462. continue
  463. except OSError:
  464. pass
  465. destination_root = _unique_destination(raw_dir / source.name)
  466. for child in sorted(source.rglob("*")):
  467. if not child.is_file():
  468. continue
  469. destination = destination_root / child.relative_to(source)
  470. _copy_raw_file(child, destination)
  471. elif source.is_file():
  472. _copy_raw_file(source, _unique_destination(raw_dir / source.name))
  473. def _copy_raw_file(source: Path, destination: Path) -> None:
  474. destination.parent.mkdir(parents=True, exist_ok=True)
  475. try:
  476. if source.resolve() == destination.resolve():
  477. return
  478. except OSError:
  479. pass
  480. shutil.copy2(source, destination)
  481. def _unique_destination(destination: Path) -> Path:
  482. if not destination.exists():
  483. return destination
  484. stem = destination.stem
  485. suffix = destination.suffix
  486. parent = destination.parent
  487. for index in range(1, 1000):
  488. candidate = parent / f"{stem}-{index}{suffix}"
  489. if not candidate.exists():
  490. return candidate
  491. raise FileExistsError(f"could not allocate unique raw artifact path for {destination}")
  492. def _raw_file_manifest(raw_dir: Path) -> list[dict[str, Any]]:
  493. files = []
  494. for path in sorted(raw_dir.rglob("*")):
  495. if not path.is_file():
  496. continue
  497. rel = path.relative_to(raw_dir).as_posix()
  498. files.append({
  499. "path": f"raw/{rel}",
  500. "size": path.stat().st_size,
  501. "sha256": _sha256(path),
  502. "artifact_role": _raw_artifact_role(path),
  503. "csv": _csv_summary(path),
  504. })
  505. return files
  506. def _raw_artifact_role(path: Path) -> str:
  507. suffix = path.suffix.lower()
  508. name = path.name.lower()
  509. if "preflight" in name:
  510. return "uart_preflight_artifact"
  511. if suffix == ".csv":
  512. return "uart_transcript_or_debug_export"
  513. if suffix in {".txt", ".log", ".jsonl"}:
  514. return "uart_transcript_or_debug_export"
  515. if suffix in {".png", ".jpg", ".jpeg", ".bmp"}:
  516. return "uart_transcript_or_debug_export"
  517. if suffix in {".json", ".rpt", ".logw"}:
  518. return "uart_preflight_artifact"
  519. if "uart" in name or "serial" in name or "com" in name:
  520. return "uart_preflight_artifact"
  521. return "unknown_raw_artifact"
  522. def _sha256(path: Path) -> str:
  523. digest = hashlib.sha256()
  524. with path.open("rb") as handle:
  525. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  526. digest.update(chunk)
  527. return digest.hexdigest()
  528. def _csv_summary(path: Path) -> dict[str, Any]:
  529. if path.suffix.lower() != ".csv":
  530. return {"status": "not_csv"}
  531. try:
  532. with path.open("r", encoding="utf-8-sig", newline="") as handle:
  533. reader = csv.reader(handle)
  534. headers = next(reader, [])
  535. except (OSError, UnicodeDecodeError, csv.Error) as exc:
  536. return {"status": "unreadable_csv", "error": str(exc)}
  537. normalized = [header.strip() for header in headers if header.strip()]
  538. recognized = [field for field in DEBUG_EVENT_REQUIRED_FIELDS if field in normalized]
  539. return {
  540. "status": "recognized_debug_event_fields" if set(DEBUG_EVENT_REQUIRED_FIELDS).issubset(normalized) else "unmapped_csv_headers",
  541. "field_count": len(normalized),
  542. "recognized_fields": recognized,
  543. }
  544. def _iter_result_items(payload: dict[str, Any], *keys: str) -> list[dict[str, Any]]:
  545. items: list[dict[str, Any]] = []
  546. for key in keys:
  547. value = payload.get(key, [])
  548. if isinstance(value, dict):
  549. iterable = value.values()
  550. elif isinstance(value, list):
  551. iterable = value
  552. else:
  553. iterable = []
  554. for item in iterable:
  555. if isinstance(item, dict):
  556. items.append(item)
  557. return items
  558. def _write_json(path: Path, payload: Any) -> None:
  559. path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  560. def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
  561. path.write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8")
  562. def _write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
  563. fieldnames = list(DEBUG_EVENT_REQUIRED_FIELDS)
  564. for row in rows:
  565. for key in row:
  566. if key not in fieldnames:
  567. fieldnames.append(key)
  568. with path.open("w", newline="", encoding="utf-8") as handle:
  569. writer = csv.DictWriter(handle, fieldnames=fieldnames)
  570. writer.writeheader()
  571. writer.writerows(rows)
  572. def _write_agent_context(path: Path, manifest: dict[str, Any], invariants: dict[str, Any]) -> None:
  573. failed = [name for name, item in invariants["checks"].items() if not item["pass"]]
  574. text = "\n".join([
  575. "# PID Debug Bundle Agent Context",
  576. "",
  577. "Read this file first, then parse `trace.jsonl` as JSONL.",
  578. "",
  579. f"- schema: `{manifest['schema']}`",
  580. f"- source: `{manifest['source']}`",
  581. f"- event_count: `{manifest['event_count']}`",
  582. f"- invariants: `{invariants['status']}`",
  583. f"- failed_checks: `{', '.join(failed) if failed else 'none'}`",
  584. "",
  585. "Primary files:",
  586. "- `trace.jsonl`: canonical debug_event_v1 stream.",
  587. "- `invariants.json`: machine-checkable safety/debug assertions.",
  588. "- `register_dump.json`: optional I2C/debug register readback.",
  589. "- `pipeline.json`: model/static/RTL/TD status when available.",
  590. "",
  591. "Do not infer real PTC/FAN electrical safety from this bundle unless hardware evidence is attached under `raw/`.",
  592. "",
  593. ])
  594. path.write_text(text, encoding="utf-8")