diff --git a/backend/tests/test_evidence_coverage.py b/backend/tests/test_evidence_coverage.py index 1bf509a..fc91d22 100644 --- a/backend/tests/test_evidence_coverage.py +++ b/backend/tests/test_evidence_coverage.py @@ -9,6 +9,7 @@ """ from __future__ import annotations +import importlib.util import json import tomllib from pathlib import Path @@ -19,10 +20,20 @@ PROFILES_DIR = REPO_ROOT / "community" / "profiles" EVIDENCE_DIR = REPO_ROOT / "docs" / "evidence" LEDGER_PATH = EVIDENCE_DIR / "coverage.toml" +PACK_VALIDATOR_PATH = REPO_ROOT / "scripts" / "validate_evidence_packs.py" MARKER = "needs verification" VALID_STATUS = {"gap", "evidence"} +def _load_pack_validator(): + spec = importlib.util.spec_from_file_location( + "validate_evidence_packs", PACK_VALIDATOR_PATH) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) # type: ignore[union-attr] + return mod + + def _collect_markers() -> set[tuple[str, str]]: """(profile_id, param_id) for every live marker; '*' = profile-level.""" out: set[tuple[str, str]] = set() @@ -94,6 +105,7 @@ def test_gap_entries_reference_defined_gaps(ledger): def test_evidence_entries_reference_real_packs(ledger): + pack_validator = _load_pack_validator() for e in ledger.get("entry", []): if e.get("status") == "evidence": pack = EVIDENCE_DIR / e.get("evidence", "") @@ -102,6 +114,20 @@ def test_evidence_entries_reference_real_packs(ledger): f"{e.get('evidence')!r} not found in docs/evidence/" ) json.loads(pack.read_text(encoding="utf-8")) # must parse + # Promotion discipline: a marker flips to evidence only on a + # real-car pass for that exact parameter — never on a fail or + # inconclusive capture, and never at the profile level ("*") + # where no single pack can prove a whole profile. + assert e["param"] != "*", ( + f"{e['profile']}/*: profile-level markers are removed once " + "core params carry evidence, not promoted via one pack" + ) + assert pack_validator.pack_has_passing_record( + pack, e["profile"], e["param"] + ), ( + f"{e['profile']}/{e['param']}: pack {e.get('evidence')!r} " + "holds no result=pass record for this parameter" + ) def test_gap_definitions_are_actionable(ledger): diff --git a/backend/tests/test_evidence_packs.py b/backend/tests/test_evidence_packs.py new file mode 100644 index 0000000..cb03b2f --- /dev/null +++ b/backend/tests/test_evidence_packs.py @@ -0,0 +1,148 @@ +"""Tests for scripts/validate_evidence_packs.py. + +The validator is the enforced half of the docs/evidence/ contracts +(schema.json for CAN broadcast packs, schema-uds.json for UDS DID packs). +These tests exercise the validator against in-test fixtures and validate +whatever real packs ship in docs/evidence/. +""" +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT_PATH = REPO_ROOT / "scripts" / "validate_evidence_packs.py" + + +@pytest.fixture(scope="module") +def validator(): + spec = importlib.util.spec_from_file_location( + "validate_evidence_packs", SCRIPT_PATH) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) # type: ignore[union-attr] + return mod + + +@pytest.fixture(scope="module") +def profiles(validator): + return validator.load_profiles() + + +def _good_uds_record() -> dict: + """A valid UDS record for b58/hpfp_rail (did:44F0, u16_tenths). + + 0x044C = 1100 -> u16_tenths -> 110.0 bar. Fixture only; not a real + capture and never shipped under docs/evidence/. + """ + return { + "profile": "b58", + "param": "hpfp_rail", + "did": "0x44F0", + "decode": "u16_tenths", + "request": "22 44 F0", + "response": [0x62, 0x44, 0xF0, 0x04, 0x4C], + "expected": {"value": 110.0, "unit": "bar"}, + "result": "pass", + "vehicle": {"chassis": "G20", "engine": "B58"}, + "firmware": {"sw": "08.14", "integration_level": "F020-21-03-500"}, + "adapter": {"kind": "enet"}, + "source": "validator fixture", + "captured_at": "2026-11-29T00:00:00Z", + } + + +def _uds_errors(validator, profiles, records): + return validator.validate_uds_records(records, "fixture.uds.json", profiles) + + +def test_repo_packs_are_valid(validator): + errors = validator.validate_repo_packs() + assert not errors, f"docs/evidence/ packs fail validation: {errors}" + + +def test_good_uds_record_passes(validator, profiles): + assert _uds_errors(validator, profiles, [_good_uds_record()]) == [] + + +def test_missing_required_field_is_caught(validator, profiles): + rec = _good_uds_record() + del rec["adapter"] + errors = _uds_errors(validator, profiles, [rec]) + assert any("adapter" in e for e in errors) + + +def test_decode_must_match_profile(validator, profiles): + rec = _good_uds_record() + rec["decode"] = "u16" + errors = _uds_errors(validator, profiles, [rec]) + assert any("decode" in e for e in errors) + + +def test_did_must_match_profile_query(validator, profiles): + rec = _good_uds_record() + rec["did"] = "0x44F1" + rec["response"] = [0x62, 0x44, 0xF1, 0x04, 0x4C] + errors = _uds_errors(validator, profiles, [rec]) + assert any("disagrees with profile query" in e for e in errors) + + +def test_pass_requires_positive_response(validator, profiles): + rec = _good_uds_record() + del rec["response"] + errors = _uds_errors(validator, profiles, [rec]) + assert any("result=pass requires" in e for e in errors) + + +def test_response_echo_must_match_did(validator, profiles): + rec = _good_uds_record() + rec["response"] = [0x62, 0x44, 0xF1, 0x04, 0x4C] + errors = _uds_errors(validator, profiles, [rec]) + assert any("DID echo" in e for e in errors) + + +def test_nrc_only_record_is_valid_evidence_of_failure(validator, profiles): + rec = _good_uds_record() + del rec["response"] + rec["nrc"] = "0x31" + rec["result"] = "fail" + assert _uds_errors(validator, profiles, [rec]) == [] + + +def test_expected_requires_unit(validator, profiles): + rec = _good_uds_record() + rec["expected"] = {"value": 110.0} + errors = _uds_errors(validator, profiles, [rec]) + assert any("unit" in e for e in errors) + + +def test_unknown_profile_is_caught(validator, profiles): + rec = _good_uds_record() + rec["profile"] = "w12" + errors = _uds_errors(validator, profiles, [rec]) + assert any("unknown profile" in e for e in errors) + + +def test_obd_param_rejected_in_uds_pack(validator, profiles): + rec = _good_uds_record() + rec["profile"] = "n52" + rec["param"] = "fuel_rate_lh" + rec["did"] = "0x005E" + rec["decode"] = "u16_fiftieths" + rec["response"] = [0x62, 0x00, 0x5E, 0x01, 0x90] + errors = _uds_errors(validator, profiles, [rec]) + assert any("did: query" in e for e in errors) + + +def test_pack_has_passing_record(validator, tmp_path): + pack = tmp_path / "b58.uds.json" + pack.write_text(json.dumps([_good_uds_record()]), encoding="utf-8") + assert validator.pack_has_passing_record(pack, "b58", "hpfp_rail") + assert not validator.pack_has_passing_record(pack, "b58", "maf") + fail_only = _good_uds_record() + fail_only["result"] = "fail" + pack.write_text(json.dumps([fail_only]), encoding="utf-8") + assert not validator.pack_has_passing_record(pack, "b58", "hpfp_rail") diff --git a/docs/evidence/README.md b/docs/evidence/README.md index 621a9dd..b4d98d9 100644 --- a/docs/evidence/README.md +++ b/docs/evidence/README.md @@ -71,13 +71,50 @@ whose marker disappears fails, so the ledger cannot silently rot. Today every entry is a named gap — no profile DID has a real-car capture yet (`n55.example.json` is a simulator baseline for the CAN -broadcast decoders, adjacent but not DID validation). The gap -definitions name the record form that closes them: for UDS parameters, -a `.uds.json` pack of DID request, raw positive-response -payload, expected decoded value and provenance; the schema extension -for that form is part of the January beat. To close a gap: land the -capture, flip the entry to `status = "evidence"`, and only then remove -the marker from the profile label. +broadcast decoders, adjacent but not DID validation). To close a gap: +land the capture, flip the entry to `status = "evidence"`, and only +then remove the marker from the profile label. The coverage guard +enforces the promotion discipline: an evidence entry must point at a +pack holding a `result = "pass"` record for that exact parameter — +a fail or inconclusive capture keeps the marker on, and profile-level +(`*`) markers are never promoted by a single pack. + +## UDS DID packs + +CAN broadcast packs (above) validate the decoders; UDS packs validate +the polled parameters that carry the `[needs verification]` markers. +One file per engine family: `docs/evidence/.uds.json`, an array +of DID read records per `schema-uds.json`: + +```json +[ + { + "profile": "b58", + "param": "hpfp_rail", + "did": "0x44F0", + "decode": "u16_tenths", + "request": "22 44 F0", + "response": [98, 68, 240, 4, 76], + "expected": { "value": 110.0, "unit": "bar" }, + "result": "pass", + "vehicle": { "chassis": "G20", "engine": "B58" }, + "firmware": { "sw": "08.14", "integration_level": "F020-21-03-500" }, + "adapter": { "kind": "enet" }, + "source": "real-car capture via ENET, cross-checked against ISTA", + "captured_at": "2026-12-14T10:30:00Z" + } +] +``` + +Every record identifies chassis, firmware, adapter, parameter, units +and result — the update-3 identity contract. `did` and `decode` must +match the profile's own claims; `response` is the full raw positive +response including the `0x62` service byte and DID echo. A DID the car +refuses is evidence too: record the `nrc` with `result = "fail"` — it +keeps the marker on with proof instead of silence. +`scripts/validate_evidence_packs.py` checks all of this, cross-references +each record against the profile it claims, and runs in CI via +`backend/tests/test_evidence_packs.py`. ## Security diff --git a/docs/evidence/schema-uds.json b/docs/evidence/schema-uds.json new file mode 100644 index 0000000..a6df1ef --- /dev/null +++ b/docs/evidence/schema-uds.json @@ -0,0 +1,109 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://beemuu.com/evidence/schema-uds.json", + "title": "Beemuu UDS Evidence Pack", + "description": "Real-car UDS readDataByIdentifier capture with expected decoder output, for the v0.22 evidence program (update 3). One file per engine family: docs/evidence/.uds.json. The companion CAN broadcast format lives in schema.json; this schema covers polled DID reads, the shape that retires [needs verification] markers in community/profiles/*.toml.", + "type": "array", + "items": { + "type": "object", + "required": ["profile", "param", "did", "decode", "expected", "result", "vehicle", "firmware", "adapter", "source", "captured_at"], + "properties": { + "profile": { + "type": "string", + "pattern": "^[a-z0-9_]+$", + "description": "Community profile id the parameter belongs to (e.g. b58). Must match a community/profiles/.toml profile." + }, + "param": { + "type": "string", + "pattern": "^[a-z0-9_]+$", + "description": "Parameter id within that profile (e.g. hpfp_rail)." + }, + "did": { + "type": "string", + "pattern": "^0x[0-9A-Fa-f]{4}$", + "description": "The DID read, as a hex string (e.g. 0x44F0). Must equal the profile param's did: query." + }, + "decode": { + "type": "string", + "minLength": 2, + "description": "Decode function the record claims (e.g. u16_tenths). Must equal the profile param's decode." + }, + "request": { + "type": "string", + "description": "Human-readable request bytes sent (e.g. \"22 44 F0\"). Optional context; response is the normative capture." + }, + "response": { + "type": "array", + "items": { "type": "integer", "minimum": 0, "maximum": 255 }, + "minItems": 4, + "description": "Full raw positive response, including the 0x62 service byte and DID echo (e.g. [0x62, 0x44, 0xF0, 0x01, 0x2C]). Required when result is pass." + }, + "nrc": { + "type": "string", + "pattern": "^0x[0-9A-Fa-f]{2}$", + "description": "Negative response code instead of a positive response (e.g. 0x31 requestOutOfRange). A DID the car refuses is evidence too — record it with result fail or inconclusive." + }, + "expected": { + "type": "object", + "required": ["value", "unit"], + "properties": { + "value": { "type": ["number", "boolean", "string"] }, + "unit": { "type": "string", "minLength": 0 } + }, + "description": "Decoded value the profile's decode MUST produce from this payload, and its unit. Units are part of the claim: a record without a unit cannot retire a marker." + }, + "result": { + "type": "string", + "enum": ["pass", "fail", "inconclusive"], + "description": "pass = car answered and decoded value matched the known-good reference. fail = car refused the DID or the decode disagreed with the reference (keeps the marker on). inconclusive = captured but no trustworthy reference at capture time." + }, + "vehicle": { + "type": "object", + "required": ["chassis"], + "properties": { + "vin": { "type": "string", "minLength": 17, "maxLength": 17 }, + "wmi": { "type": "string", "minLength": 3, "maxLength": 3 }, + "serial_last6": { "type": "string", "minLength": 6, "maxLength": 6 }, + "engine": { "type": "string" }, + "chassis": { "type": "string", "minLength": 2 } + }, + "description": "Vehicle identification. Chassis is required (e.g. G20); VIN preferred, WMI+serial_last6 acceptable for privacy." + }, + "firmware": { + "type": "object", + "minProperties": 1, + "properties": { + "ecu": { "type": "string" }, + "hw": { "type": "string" }, + "sw": { "type": "string" }, + "integration_level": { "type": "string" } + }, + "description": "Firmware identity of the answering ECU — at least one of sw / hw / integration_level. DID applicability can change across integration levels; a record without firmware identity cannot be reproduced." + }, + "adapter": { + "type": "object", + "required": ["kind"], + "properties": { + "kind": { "type": "string", "enum": ["enet", "kdcan"] }, + "cable": { "type": "string" }, + "latency_timer_ms": { "type": "integer", "minimum": 1 } + }, + "description": "Capture path. kind is required; K+DCAN records should carry latency_timer_ms (the repo invariant is 1 ms)." + }, + "source": { + "type": "string", + "minLength": 5, + "description": "Provenance: who captured, with what tool, cross-checked against what reference (e.g. ISTA, INPA, known-good scanner)." + }, + "captured_at": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp of the capture." + }, + "notes": { + "type": "string", + "description": "Capture conditions (engine warm/cold, idle/load) and anything a reviewer needs to reproduce." + } + } + } +} diff --git a/docs/product_calendar.md b/docs/product_calendar.md index a367b42..0c7c4eb 100644 --- a/docs/product_calendar.md +++ b/docs/product_calendar.md @@ -32,7 +32,7 @@ |---|---|---| | Nov 30 – Dec 6 | Update 2 close-out: physical adapter health probe design note; real-cable recovery checklist (K+DCAN on E70, ENET on F/G) — both landed early (Nov 28, `docs/adapter-health-probe.md` + checklist staged) | Done Nov 28 — all eleven polling paths have a stated freshness story in `docs/connection-recovery.md` | | Dec 7 – 13 | Update 2 real-cable recovery pass on the bench car | Reconnect after cable pull recovers without app restart, or the failure is documented and surfaced | -| Dec 14 – 20 | Update 3 open: hardware validation and coverage — evidence-record schema (chassis, firmware, adapter, parameter, units, result) | Schema reviewed against the existing `docs/evidence/` skeleton; no unverified coverage promoted | +| Dec 14 – 20 | Update 3 open: hardware validation and coverage — evidence-record schema (chassis, firmware, adapter, parameter, units, result) — landed early (Nov 29, `docs/evidence/schema-uds.json` + validator + CI guard) | Schema reviewed against the existing `docs/evidence/` skeleton; no unverified coverage promoted | | Dec 21 – Jan 4 | Holiday pause. Community call for N52/N54/N62 bench reports (`docs/validation/n5x-real-car.md`, `n62-real-car.md`) | At least the call posted; reports are opportunistic, not gated | **Release candidate:** none. Update 2 closes into whatever version the diff --git a/scripts/validate_evidence_packs.py b/scripts/validate_evidence_packs.py new file mode 100644 index 0000000..c6a0ad0 --- /dev/null +++ b/scripts/validate_evidence_packs.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Validate docs/evidence/ packs against their format contracts. + +Two pack families live in docs/evidence/: + + - CAN broadcast packs (schema.json): any *.json that is not a schema and + does not end in .uds.json. Frame records {id, data, expected, source, + captured_at}. + - UDS DID packs (schema-uds.json): *.uds.json. DID read records keyed to a + community profile parameter, cross-checked here against the profile + itself (DID and decode must match the profile's claims). + +The JSON Schema documents are the human-readable contract; this script is +the enforced one (the repo runs stdlib-only Python, no jsonschema +dependency). CI exercises it via backend/tests/test_evidence_packs.py. + +Usage: python scripts/validate_evidence_packs.py (exit 1 on any error) +""" +from __future__ import annotations + +import json +import re +import sys +import tomllib +from datetime import datetime +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +EVIDENCE_DIR = REPO_ROOT / "docs" / "evidence" +PROFILES_DIR = REPO_ROOT / "community" / "profiles" + +CAN_ID_RE = re.compile(r"^0x[0-9A-Fa-f]{1,4}$") +DID_RE = re.compile(r"^0x[0-9A-Fa-f]{4}$") +NRC_RE = re.compile(r"^0x[0-9A-Fa-f]{2}$") +UDS_RESULTS = {"pass", "fail", "inconclusive"} +ADAPTER_KINDS = {"enet", "kdcan"} + +UDS_REQUIRED = [ + "profile", "param", "did", "decode", "expected", "result", + "vehicle", "firmware", "adapter", "source", "captured_at", +] + + +def _is_iso8601(value: object) -> bool: + if not isinstance(value, str): + return False + try: + datetime.fromisoformat(value.replace("Z", "+00:00")) + return True + except ValueError: + return False + + +def _is_byte_list(value: object, n: int | None = None) -> bool: + if not isinstance(value, list): + return False + if n is not None and len(value) != n: + return False + return all(isinstance(b, int) and 0 <= b <= 255 for b in value) + + +def load_profiles() -> dict[str, dict[str, dict]]: + """profile id -> {param id -> {query, decode}} for shipped profiles.""" + out: dict[str, dict[str, dict]] = {} + for path in sorted(PROFILES_DIR.glob("*.toml")): + data = tomllib.loads(path.read_text(encoding="utf-8")) + for prof in data.get("profile", []): + pid = prof.get("id", "") + if pid.startswith("test"): + continue + out[pid] = { + p.get("id", ""): {"query": p.get("query", ""), + "decode": p.get("decode", "")} + for p in prof.get("param", []) + } + return out + + +def validate_can_records(records: object, name: str) -> list[str]: + errors: list[str] = [] + if not isinstance(records, list): + return [f"{name}: top level must be an array"] + for i, r in enumerate(records): + tag = f"{name}[{i}]" + if not isinstance(r, dict): + errors.append(f"{tag}: record must be an object") + continue + if not (isinstance(r.get("id"), str) and CAN_ID_RE.match(r["id"])): + errors.append(f"{tag}: id must match 0x.. hex form, got {r.get('id')!r}") + if not _is_byte_list(r.get("data"), 8): + errors.append(f"{tag}: data must be exactly 8 bytes (0-255)") + if not isinstance(r.get("expected"), dict) or not r["expected"]: + errors.append(f"{tag}: expected must be a non-empty object") + if not (isinstance(r.get("source"), str) and len(r["source"]) >= 5): + errors.append(f"{tag}: source (provenance) missing or too short") + if not _is_iso8601(r.get("captured_at")): + errors.append(f"{tag}: captured_at must be ISO 8601, got {r.get('captured_at')!r}") + return errors + + +def validate_uds_records(records: object, name: str, + profiles: dict[str, dict[str, dict]]) -> list[str]: + errors: list[str] = [] + if not isinstance(records, list): + return [f"{name}: top level must be an array"] + for i, r in enumerate(records): + tag = f"{name}[{i}]" + if not isinstance(r, dict): + errors.append(f"{tag}: record must be an object") + continue + missing = [f for f in UDS_REQUIRED if f not in r] + if missing: + # Deeper checks assume the required keys exist. + errors.append(f"{tag}: missing required field(s): {', '.join(missing)}") + continue + + pid, param = r["profile"], r["param"] + prof = profiles.get(pid) + if prof is None: + errors.append(f"{tag}: unknown profile {pid!r}") + continue + spec = prof.get(param) + if spec is None: + errors.append(f"{tag}: profile {pid!r} has no param {param!r}") + continue + + query = spec["query"] + if not query.startswith("did:"): + errors.append( + f"{tag}: param {pid}/{param} is {query!r} in the profile; " + "UDS evidence requires a did: query") + else: + want_did = "0x" + query[4:].upper() + if not (isinstance(r.get("did"), str) and DID_RE.match(r["did"])): + errors.append(f"{tag}: did must match 0xXXXX form, got {r.get('did')!r}") + elif r["did"].upper() != want_did.upper(): + errors.append( + f"{tag}: did {r['did']} disagrees with profile query " + f"{query} ({want_did})") + if r.get("decode") != spec["decode"]: + errors.append( + f"{tag}: decode {r.get('decode')!r} disagrees with profile " + f"decode {spec['decode']!r}") + + expected = r.get("expected", {}) + if not isinstance(expected, dict) or "value" not in expected or "unit" not in expected: + errors.append(f"{tag}: expected must carry value and unit") + + result = r.get("result") + if result not in UDS_RESULTS: + errors.append(f"{tag}: result must be one of {sorted(UDS_RESULTS)}") + + response, nrc = r.get("response"), r.get("nrc") + if response is not None and not _is_byte_list(response): + errors.append(f"{tag}: response must be a byte array") + if nrc is not None and not (isinstance(nrc, str) and NRC_RE.match(nrc)): + errors.append(f"{tag}: nrc must match 0xNN form, got {nrc!r}") + if result == "pass": + if not response: + errors.append(f"{tag}: result=pass requires a positive response") + elif isinstance(response, list) and len(response) >= 3: + if response[0] != 0x62: + errors.append(f"{tag}: positive response must start with 0x62") + elif isinstance(r.get("did"), str) and DID_RE.match(r["did"]): + want = int(r["did"], 16) + if [response[1], response[2]] != [want >> 8, want & 0xFF]: + errors.append(f"{tag}: response DID echo does not match did") + elif response is None and nrc is None: + errors.append(f"{tag}: non-pass record still needs response or nrc") + + vehicle = r.get("vehicle", {}) + if not isinstance(vehicle, dict) or not vehicle.get("chassis"): + errors.append(f"{tag}: vehicle.chassis is required") + firmware = r.get("firmware", {}) + if not isinstance(firmware, dict) or not firmware: + errors.append(f"{tag}: firmware must carry at least one identity field") + adapter = r.get("adapter", {}) + if not isinstance(adapter, dict) or adapter.get("kind") not in ADAPTER_KINDS: + errors.append(f"{tag}: adapter.kind must be one of {sorted(ADAPTER_KINDS)}") + if not (isinstance(r.get("source"), str) and len(r["source"]) >= 5): + errors.append(f"{tag}: source (provenance) missing or too short") + if not _is_iso8601(r.get("captured_at")): + errors.append(f"{tag}: captured_at must be ISO 8601, got {r.get('captured_at')!r}") + return errors + + +def pack_has_passing_record(pack_path: Path, profile: str, param: str) -> bool: + """True if the UDS pack holds a result=pass record for profile/param. + + The coverage ledger uses this: a [needs verification] entry may flip to + status = "evidence" only when the referenced pack proves the parameter + on a real car — never on a fail or inconclusive capture. + """ + try: + records = json.loads(pack_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + if not isinstance(records, list): + return False + return any( + isinstance(r, dict) + and r.get("profile") == profile + and r.get("param") == param + and r.get("result") == "pass" + for r in records + ) + + +def validate_repo_packs(root: Path = REPO_ROOT) -> list[str]: + evidence = root / "docs" / "evidence" + profiles = load_profiles() + errors: list[str] = [] + for path in sorted(evidence.glob("*.json")): + if path.stem in ("schema", "schema-uds"): + continue + name = path.name + try: + records = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + errors.append(f"{name}: invalid JSON: {exc}") + continue + if name.endswith(".uds.json"): + errors += validate_uds_records(records, name, profiles) + else: + errors += validate_can_records(records, name) + return errors + + +def main() -> int: + errors = validate_repo_packs() + if errors: + print(f"FAIL — {len(errors)} evidence pack problem(s):") + for e in errors: + print(f" {e}") + return 1 + print("OK — evidence packs valid") + return 0 + + +if __name__ == "__main__": + sys.exit(main())