#!/usr/bin/env python3 """Debug-max event, bundle, and agent-analysis helpers.""" from __future__ import annotations import csv import hashlib import json import shutil from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable from pid_contract_model import config_contract_summary from toolchain_probe import probe_toolchain DEBUG_EVENT_REQUIRED_FIELDS = [ "timebase", "trace_seq", "event_type", "source_id", "channel", "sample_seq", "config_seq", "state", "fault_code", "reason", "temp_q", "target_q", "error_q", "ctrl_q", "ptc_duty", "ptc_pwm", "fan_duty", "tach_edges", "rpm_estimate", ] FAULT_CODE_OK = 0 FAULT_CODE_HOST_DISABLED = 1 FAULT_CODE_SENSOR_FAULT = 2 FAULT_CODE_SENSOR_STALE = 3 FAULT_CODE_HOST_TIMEOUT = 4 FAULT_CODE_OVERTEMP = 5 FAULT_CODE_INVALID_CHANNEL = 6 FAULT_CODE_INTERLOCK = 7 THERMAL_FALLBACK_FAULTS = { FAULT_CODE_SENSOR_FAULT, FAULT_CODE_SENSOR_STALE, FAULT_CODE_HOST_TIMEOUT, FAULT_CODE_OVERTEMP, } def _as_int(value: Any, default: int = 0) -> int: if isinstance(value, bool): return int(value) if isinstance(value, int): return value if value is None: return default try: return int(value) except (TypeError, ValueError): return default def _as_bool(value: Any) -> bool: if isinstance(value, bool): return value if isinstance(value, str): return value.strip().lower() in {"1", "true", "yes", "y", "on"} return bool(value) def normalize_replay_trace(trace: Iterable[dict[str, Any]]) -> list[dict[str, Any]]: """Convert replay trace rows into debug_event_v1 dictionaries.""" events: list[dict[str, Any]] = [] for row in trace: fault_code = _as_int(row.get("fault_code")) force_off = _as_bool(row.get("force_off")) if fault_code != FAULT_CODE_OK: event_type = "fault_raised" elif force_off: event_type = "force_off" else: event_type = "control_updated" event = { "timebase": "replay_sample", "trace_seq": _as_int(row.get("trace_seq"), len(events) + 1), "event_type": event_type, "source_id": _as_int(row.get("source_id")), "channel": _as_int(row.get("channel"), -1), "sample_seq": _as_int(row.get("sample_seq")), "config_seq": _as_int(row.get("config_seq")), "state": str(row.get("control_mode", row.get("state", "unknown"))), "fault_code": fault_code, "reason": str(row.get("reason", "unknown")), "temp_q": _as_int(row.get("temp_q")), "target_q": _as_int(row.get("target_q")), "error_q": _as_int(row.get("error_q")), "ctrl_q": _as_int(row.get("ctrl_q")), "ptc_duty": _as_int(row.get("ptc_duty", row.get("duty_or_level"))), "ptc_pwm": _as_int(row.get("ptc_pwm", row.get("ptc_pwm_out"))), "fan_duty": _as_int(row.get("fan_duty")), "tach_edges": _as_int(row.get("tach_window_edges", row.get("tach_edge_count"))), "rpm_estimate": _as_int(row.get("rpm_estimate")), "sensor_ready": _as_bool(row.get("sensor_ready", True)), "sensor_valid": _as_bool(row.get("sensor_valid", True)), "force_off": force_off, "host_enable": row.get("reason") != "host_disabled", "clamped": _as_bool(row.get("clamped", False)), "history_cleared": _as_bool(row.get("history_cleared", False)), "fan_pwm_drive_low": _as_int(row.get("fan_pwm_drive_low")), "fan_pwm_logic_high": _as_int(row.get("fan_pwm_logic_high")), "ptc_pwm_high_ticks": _as_int(row.get("ptc_pwm_high_ticks")), "ptc_pwm_period_ticks": _as_int(row.get("ptc_pwm_period_ticks")), "fan_pwm_high_ticks": _as_int(row.get("fan_pwm_high_ticks")), "fan_pwm_period_ticks": _as_int(row.get("fan_pwm_period_ticks")), } _ensure_required_fields(event) events.append(event) return events def _ensure_required_fields(event: dict[str, Any]) -> None: missing = [field for field in DEBUG_EVENT_REQUIRED_FIELDS if field not in event] if missing: raise ValueError(f"debug event missing required fields: {', '.join(missing)}") def check_debug_invariants(events: list[dict[str, Any]]) -> dict[str, Any]: checks: dict[str, dict[str, Any]] = {} ptc_violations = [ event for event in events if _as_bool(event.get("force_off")) and _as_int(event.get("ptc_pwm")) != 0 ] checks["ptc_off_when_force_off"] = { "pass": not ptc_violations, "violation_count": len(ptc_violations), "description": "force_off events must drive PTC PWM request low", } fan_violations = [ event for event in events if _as_int(event.get("fault_code")) in THERMAL_FALLBACK_FAULTS and _as_int(event.get("fan_duty")) != 127 ] checks["fan_fallback_on_thermal_fault"] = { "pass": not fan_violations, "violation_count": len(fan_violations), "description": "sensor/stale/timeout/overtemp faults must request fan fallback", } duty_violations = [ event for event in events if not (0 <= _as_int(event.get("ptc_duty")) <= 127 and 0 <= _as_int(event.get("fan_duty")) <= 127) ] checks["pwm_duty_in_range"] = { "pass": not duty_violations, "violation_count": len(duty_violations), "description": "PTC and fan duty levels must stay in 0..127", } tach_violations = [ event for event in events if _as_int(event.get("tach_edges")) < 0 or _as_int(event.get("rpm_estimate")) < 0 ] checks["tach_rpm_non_negative"] = { "pass": not tach_violations, "violation_count": len(tach_violations), "description": "TACH edges and RPM estimates must not be negative", } host_disable_violations = [ event for event in events if _as_int(event.get("fault_code")) == FAULT_CODE_HOST_DISABLED and _as_int(event.get("ptc_pwm")) != 0 ] checks["host_disable_ptc_off"] = { "pass": not host_disable_violations, "violation_count": len(host_disable_violations), "description": "host disable must keep PTC off", } return { "schema": "pid-debug-invariants-v1", "status": "pass" if all(item["pass"] for item in checks.values()) else "fail", "checks": checks, } def build_debug_bundle( *, output_dir: Path, source: str, trace: list[dict[str, Any]], pipeline: dict[str, Any], register_dump: dict[str, Any], raw_files: dict[str, str] | None = None, raw_artifacts: list[Path] | None = None, scenario: dict[str, Any] | None = None, sim_results: dict[str, Any] | None = None, formal_results: dict[str, Any] | None = None, detector_selftest_results: dict[str, Any] | None = None, td_results: dict[str, Any] | None = None, hardware_observations: dict[str, Any] | None = None, toolchain: dict[str, Any] | None = None, ) -> dict[str, Any]: """Write an agent-readable debug bundle directory.""" output_dir.mkdir(parents=True, exist_ok=True) raw_dir = output_dir / "raw" raw_dir.mkdir(exist_ok=True) for name, content in (raw_files or {}).items(): safe_name = Path(name).name (raw_dir / safe_name).write_text(content, encoding="utf-8") _copy_raw_artifacts(raw_dir, raw_artifacts or []) raw_manifest = _raw_file_manifest(raw_dir) for event in trace: _ensure_required_fields(event) invariants = check_debug_invariants(trace) hardware_payload = _hardware_payload_for_source(source, hardware_observations, raw_manifest) manifest = { "schema": "pid-debug-bundle-v1", "source": source, "generated_at": datetime.now(timezone.utc).isoformat(), "event_count": len(trace), "agent_entrypoint": "agent_context.md", "trace_file": "trace.jsonl", "invariants_file": "invariants.json", "provenance_file": "provenance.json", "toolchain_file": "toolchain.json", "scenario_file": "scenario.json", "sim_results_file": "sim_results.json", "formal_results_file": "formal_results.json", "detector_selftest_results_file": "detector_selftest_results.json", "td_results_file": "td_results.json", "hardware_observations_file": "hardware_observations.json", "hardware_status": hardware_payload.get("status", "not_run"), "uart_status": hardware_payload.get("instruments", {}).get("uart_ttl", "not_run"), "raw_file_count": len(raw_manifest), "raw_files": raw_manifest, } provenance = { "schema": "pid-evidence-provenance-v1", "fact_classes": { "debug_bundle": "project_defined_strategy", "trace": "project_defined_strategy", "pipeline": "local_detected_fact" if pipeline.get("status") not in {None, "not_run"} else "not_verified", "register_dump": "local_detected_fact" if register_dump else "not_verified", "hardware_observations": ( "local_detected_fact" if hardware_payload.get("status") in {"uart_manual_export_attached", "uart_board_sram_pass"} else "not_verified" ), "raw_artifacts": "local_detected_fact" if raw_manifest else "not_verified", }, "authority_boundary": "This bundle is an analysis evidence package, not proof of real thermal closed-loop behavior.", } scenario_payload = scenario or { "schema": "pid-scenario-v1", "name": f"{source}_default", "source": source, "expected_invariants": list(invariants["checks"].keys()), } sim_payload = sim_results or {"status": "not_run", "reason": "No HDL simulator evidence supplied for this bundle."} formal_payload = formal_results or {"status": "not_run", "reason": "No formal evidence supplied for this bundle."} detector_selftest_payload = detector_selftest_results or { "status": "not_run", "reason": "No detector selftest evidence supplied for this bundle.", } td_payload = td_results or {"status": "not_run", "reason": "No TD evidence supplied for this bundle."} _write_json(output_dir / "manifest.json", manifest) _write_json(output_dir / "provenance.json", provenance) _write_json(output_dir / "toolchain.json", toolchain or probe_toolchain()) _write_json(output_dir / "scenario.json", scenario_payload) _write_json(output_dir / "sim_results.json", sim_payload) _write_json(output_dir / "formal_results.json", formal_payload) _write_json(output_dir / "detector_selftest_results.json", detector_selftest_payload) _write_json(output_dir / "td_results.json", td_payload) _write_json(output_dir / "hardware_observations.json", hardware_payload) _write_json(output_dir / "pipeline.json", pipeline) _write_json(output_dir / "config.json", config_contract_summary()) _write_json(output_dir / "register_dump.json", register_dump) _write_json(output_dir / "invariants.json", invariants) _write_jsonl(output_dir / "trace.jsonl", trace) _write_csv(output_dir / "events.csv", trace) _write_agent_context(output_dir / "agent_context.md", manifest, invariants) return { "status": invariants["status"], "path": str(output_dir), "manifest": manifest, "invariants": invariants, } def analyze_debug_bundle(bundle_dir: Path) -> dict[str, Any]: trace_path = bundle_dir / "trace.jsonl" invariants_path = bundle_dir / "invariants.json" events = [ json.loads(line) for line in trace_path.read_text(encoding="utf-8").splitlines() if line.strip() ] invariants = json.loads(invariants_path.read_text(encoding="utf-8")) sim_results = _read_optional_json(bundle_dir / "sim_results.json") formal_results = _read_optional_json(bundle_dir / "formal_results.json") detector_selftest_results = _read_optional_json(bundle_dir / "detector_selftest_results.json") td_results = _read_optional_json(bundle_dir / "td_results.json") hardware_observations = _read_optional_json(bundle_dir / "hardware_observations.json") hints: list[str] = [] trace_seqs = [_as_int(event.get("trace_seq")) for event in events] if trace_seqs: sorted_seqs = sorted(trace_seqs) for prev, current in zip(sorted_seqs, sorted_seqs[1:]): if current != prev + 1: hints.append(f"trace sequence gap between {prev} and {current}; inspect dropped debug events or recorder overflow.") break if any(not _as_bool(event.get("sensor_ready", True)) for event in events): hints.append("PID/control may be waiting because sensor_ready=0; inspect producer backpressure and source_select.") if any(not _as_bool(event.get("host_enable", True)) or event.get("reason") == "host_disabled" for event in events): hints.append("PTC/PID output is gated because host disabled control; inspect host_config enable/config_seq.") if any("safety" in str(event.get("reason", "")) for event in events): hints.append("Output is blocked by safety gate; inspect fault_code, interlock, stale, timeout, and overtemp fields.") if any(_as_int(event.get("fault_code")) == FAULT_CODE_OVERTEMP for event in events): hints.append("PTC force-off is explained by overtemp gate; inspect temp_q, target_q, and fault latch clear path.") if any(_as_int(event.get("fault_code")) == FAULT_CODE_HOST_DISABLED for event in events): hints.append("host disabled path is active; PTC must stay off until enable/config policy changes.") if any(_as_int(event.get("fault_code")) == FAULT_CODE_INVALID_CHANNEL for event in events): hints.append("Invalid channel event blocked output; inspect channel mapping before PID.") if any(_as_bool(event.get("force_off")) for event in events): hints.append("PTC/PWM force_off is asserted; inspect reason and force_off_reason before checking PWM wiring.") if any(_as_int(event.get("fan_duty")) == 127 for event in events): hints.append("fan fallback duty is active; inspect thermal fault or safety fallback policy.") if invariants["status"] != "pass": failed = [name for name, item in invariants["checks"].items() if not item["pass"]] hints.append("Invariant failure: " + ", ".join(failed)) _append_tool_result_hints(hints, "HDL simulation", sim_results) _append_tool_result_hints(hints, "formal verification", formal_results) _append_tool_result_hints(hints, "detector selftest", detector_selftest_results) _append_tool_result_hints(hints, "TD build", td_results) _append_hardware_observation_hints(hints, hardware_observations) if not hints: hints.append("No root-cause hint triggered; inspect trace_seq ordering, UART transcript, and register dump evidence.") return { "schema": "pid-debug-analysis-v1", "status": "pass" if trace_path.is_file() and invariants_path.is_file() else "fail", "event_count": len(events), "invariants_status": invariants["status"], "hardware_status": hardware_observations.get("status", "not_run"), "root_cause_hints": hints, } def _read_optional_json(path: Path) -> dict[str, Any]: if not path.is_file(): return {"status": "not_run", "reason": f"{path.name} is missing"} try: return json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as exc: return {"status": "fail", "reason": f"{path.name} is not valid JSON: {exc}"} def _append_tool_result_hints(hints: list[str], label: str, payload: dict[str, Any]) -> None: status = payload.get("status") if status == "blocked_missing_tool": missing = payload.get("missing_tools") if not missing: missing = [] for item in _iter_result_items(payload, "results", "tests", "targets", "backend_results"): missing.extend(item.get("missing_tools", [])) missing.extend(item.get("required_tools", []) if item.get("status") == "blocked_missing_tool" else []) missing_text = ", ".join(sorted(set(missing))) if missing else "unknown tool" hints.append(f"{label} did not run because external tool is missing: {missing_text}.") elif status == "fail": hints.append(f"{label} failed; inspect its result JSON for compile, lint, scoreboard, counterexample, or TD errors.") elif status == "partial": missing = [] for item in _iter_result_items(payload, "results", "tests", "targets", "backend_results"): missing.extend(item.get("missing_tools", [])) missing_text = ", ".join(sorted(set(missing))) if missing else "some external tools" hints.append(f"{label} partially ran; installed backends produced evidence, missing tools blocked the rest: {missing_text}.") def _append_hardware_observation_hints(hints: list[str], payload: dict[str, Any]) -> None: status = payload.get("status") instruments = payload.get("instruments", {}) uart_status = instruments.get("uart_ttl") raw_files = payload.get("raw_files", []) raw_count = payload.get("raw_file_count", len(raw_files) if isinstance(raw_files, list) else 0) preflight_count = len([ item for item in raw_files if isinstance(item, dict) and item.get("artifact_role") == "uart_preflight_artifact" ]) if status == "uart_preflight_artifacts_attached": hints.append( 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." ) elif status == "uart_manual_export_missing" or uart_status == "manual_export_missing": hints.append( "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." ) elif status == "uart_board_sram_pass" or uart_status == "board_sram_pass": hints.append( 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." ) csv_summaries = [ item.get("csv", {}) for item in raw_files if isinstance(item, dict) and item.get("csv", {}).get("status") != "not_csv" ] if any(item.get("status") == "recognized_debug_event_fields" for item in csv_summaries): hints.append("At least one UART debug CSV has standard debug_event_v1 headers and can be compared with trace.jsonl fields.") elif csv_summaries: hints.append("UART CSV/log files are archived; inspect transcript hash and parser status in the receipt.") elif status == "uart_manual_export_attached" or uart_status == "manual_export_attached": hints.append( f"UART manual export is attached under raw/ ({raw_count} file(s)); treat it as communication/debug evidence, not proof of real thermal performance." ) csv_summaries = [ item.get("csv", {}) for item in raw_files if isinstance(item, dict) and item.get("csv", {}).get("status") != "not_csv" ] if any(item.get("status") == "recognized_debug_event_fields" for item in csv_summaries): hints.append("At least one UART debug CSV has standard debug_event_v1 headers and can be compared with trace.jsonl fields.") elif csv_summaries: hints.append("UART CSV files are archived, but their headers do not map to the standard debug_event_v1 field set yet.") def _hardware_payload_for_source( source: str, hardware_observations: dict[str, Any] | None, raw_manifest: list[dict[str, Any]], ) -> dict[str, Any]: if hardware_observations is not None: payload = dict(hardware_observations) elif source == "uart": manual_attached = any(item.get("artifact_role") == "uart_transcript_or_debug_export" for item in raw_manifest) preflight_attached = bool(raw_manifest) if manual_attached: status = "uart_manual_export_attached" uart_ttl = "manual_export_attached" reason = "UART transcript/debug/register export files are attached under raw/." elif preflight_attached: status = "uart_preflight_artifacts_attached" uart_ttl = "manual_export_missing" reason = "UART preflight or build artifacts are attached under raw/, but no UART transcript/debug CSV/manual export is present." else: status = "uart_manual_export_missing" uart_ttl = "manual_export_missing" reason = "No UART transcript/debug/register manual export files were supplied." payload = { "schema": "pid-hardware-observations-v1", "status": status, "reason": reason, "authority_boundary": ( "UART evidence proves transcript/debug/register observations only. It does not prove real PTC heating, real fan RPM, or full thermal performance." ), "instruments": { "multimeter": "not_run", "oscilloscope": "not_run", "logic_analyzer": "not_run", "uart_ttl": uart_ttl, "rs232_level_shifter": "not_run", "i2c_register_readback": "not_run", }, } else: payload = { "status": "not_run", "reason": "No board, wiring, instrument, UART transcript, or register observation supplied.", "instruments": { "multimeter": "not_run", "oscilloscope": "not_run", "logic_analyzer": "not_run", "uart_ttl": "not_run", "rs232_level_shifter": "not_run", "i2c_register_readback": "not_run", }, } payload["raw_file_count"] = len(raw_manifest) payload["raw_files"] = raw_manifest return payload def _copy_raw_artifacts(raw_dir: Path, artifacts: list[Path]) -> None: for artifact in artifacts: source = Path(artifact) if not source.exists(): raise FileNotFoundError(f"raw artifact not found: {source}") if source.is_dir(): try: if source.resolve() == raw_dir.resolve(): continue except OSError: pass destination_root = _unique_destination(raw_dir / source.name) for child in sorted(source.rglob("*")): if not child.is_file(): continue destination = destination_root / child.relative_to(source) _copy_raw_file(child, destination) elif source.is_file(): _copy_raw_file(source, _unique_destination(raw_dir / source.name)) def _copy_raw_file(source: Path, destination: Path) -> None: destination.parent.mkdir(parents=True, exist_ok=True) try: if source.resolve() == destination.resolve(): return except OSError: pass shutil.copy2(source, destination) def _unique_destination(destination: Path) -> Path: if not destination.exists(): return destination stem = destination.stem suffix = destination.suffix parent = destination.parent for index in range(1, 1000): candidate = parent / f"{stem}-{index}{suffix}" if not candidate.exists(): return candidate raise FileExistsError(f"could not allocate unique raw artifact path for {destination}") def _raw_file_manifest(raw_dir: Path) -> list[dict[str, Any]]: files = [] for path in sorted(raw_dir.rglob("*")): if not path.is_file(): continue rel = path.relative_to(raw_dir).as_posix() files.append({ "path": f"raw/{rel}", "size": path.stat().st_size, "sha256": _sha256(path), "artifact_role": _raw_artifact_role(path), "csv": _csv_summary(path), }) return files def _raw_artifact_role(path: Path) -> str: suffix = path.suffix.lower() name = path.name.lower() if "preflight" in name: return "uart_preflight_artifact" if suffix == ".csv": return "uart_transcript_or_debug_export" if suffix in {".txt", ".log", ".jsonl"}: return "uart_transcript_or_debug_export" if suffix in {".png", ".jpg", ".jpeg", ".bmp"}: return "uart_transcript_or_debug_export" if suffix in {".json", ".rpt", ".logw"}: return "uart_preflight_artifact" if "uart" in name or "serial" in name or "com" in name: return "uart_preflight_artifact" return "unknown_raw_artifact" def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _csv_summary(path: Path) -> dict[str, Any]: if path.suffix.lower() != ".csv": return {"status": "not_csv"} try: with path.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.reader(handle) headers = next(reader, []) except (OSError, UnicodeDecodeError, csv.Error) as exc: return {"status": "unreadable_csv", "error": str(exc)} normalized = [header.strip() for header in headers if header.strip()] recognized = [field for field in DEBUG_EVENT_REQUIRED_FIELDS if field in normalized] return { "status": "recognized_debug_event_fields" if set(DEBUG_EVENT_REQUIRED_FIELDS).issubset(normalized) else "unmapped_csv_headers", "field_count": len(normalized), "recognized_fields": recognized, } def _iter_result_items(payload: dict[str, Any], *keys: str) -> list[dict[str, Any]]: items: list[dict[str, Any]] = [] for key in keys: value = payload.get(key, []) if isinstance(value, dict): iterable = value.values() elif isinstance(value, list): iterable = value else: iterable = [] for item in iterable: if isinstance(item, dict): items.append(item) return items def _write_json(path: Path, payload: Any) -> None: path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8") def _write_csv(path: Path, rows: list[dict[str, Any]]) -> None: fieldnames = list(DEBUG_EVENT_REQUIRED_FIELDS) for row in rows: for key in row: if key not in fieldnames: fieldnames.append(key) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) def _write_agent_context(path: Path, manifest: dict[str, Any], invariants: dict[str, Any]) -> None: failed = [name for name, item in invariants["checks"].items() if not item["pass"]] text = "\n".join([ "# PID Debug Bundle Agent Context", "", "Read this file first, then parse `trace.jsonl` as JSONL.", "", f"- schema: `{manifest['schema']}`", f"- source: `{manifest['source']}`", f"- event_count: `{manifest['event_count']}`", f"- invariants: `{invariants['status']}`", f"- failed_checks: `{', '.join(failed) if failed else 'none'}`", "", "Primary files:", "- `trace.jsonl`: canonical debug_event_v1 stream.", "- `invariants.json`: machine-checkable safety/debug assertions.", "- `register_dump.json`: optional I2C/debug register readback.", "- `pipeline.json`: model/static/RTL/TD status when available.", "", "Do not infer real PTC/FAN electrical safety from this bundle unless hardware evidence is attached under `raw/`.", "", ]) path.write_text(text, encoding="utf-8")