""" Sovereign Circuit Grading Rubric — reference implementation =========================================================== Version SCGR1 (rubric v1.0 draft) Status Draft for review. Not legally reviewed. Thresholds are not yet calibrated against real paired inspection data — see RUBRIC.md §9. WHAT THIS IS FOR ---------------- The Dual Attestation Protocol (SCDA1) settles a *price*. A price is only meaningful if both parties are pricing the same described object. This module produces that description, deterministically. The problem it exists to solve is stated by the R2v3 standard's own analysis: the cosmetic vocabulary contains terms — "minor scratches", "light scratches", "scratches" — that have no well-defined status. You cannot commit to an adjective. Two honest inspectors will produce different adjectives for the same laptop, and neither is lying. So this rubric never asks anyone for an adjective. It asks for counts and instrument readings, and then *derives* the category. Adjectives become an output, not an input. THE THREE AXES -------------- F Function — adopted from R2v3 REC, F1..F6 (plus F0, not functional) C Cosmetic — adopted from R2v3 REC, C0..C9 S Sovereign — new. R2 does not grade protectability at all. F and C use the certified-ITAD vocabulary verbatim so that a Sovereign Circuit grade is legible to any R2 facility. S is the axis this program adds, and it is the axis that decides which trust tier a unit may serve. THE MATERIALITY RULE -------------------- Two inspectors will disagree about whether that is three scratches or five. Almost always this does not change the derived grade at all. The rubric therefore does not reconcile *observations*; it reconciles *grades*. Divergence is escalated only when it is material — when the two observation vectors actually derive to different grades. When they do, `minimal_divergence_set` identifies the smallest set of fields responsible, so re-inspection is targeted at the handful of fields that matter rather than the whole sheet. MACHINE FIELDS ARE NOT OPINIONS ------------------------------- Fields read from the device — SMART counters, battery capacity, power-on hours, TPM version — are Class M. They are not averaged and not toleranced. If two parties report different values for a Class M field, that is not a disagreement about judgement; it is evidence that the device was altered between readings, that the wrong unit was read, or that a reading is fabricated. The correct response is to void and re-read, and this module refuses to grade rather than paper over it. Standard library only. No dependencies. Integers only — no floats anywhere, for the same reason the price protocol uses integer cents. """ from __future__ import annotations import hashlib import json from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Tuple # Reuse the protocol's canonicalizer so a grade token hashes identically # under both modules. If this import fails the module is being used outside # the reference tree; the local fallback is byte-identical. try: from attestation import canon except ImportError: # pragma: no cover def canon(obj) -> bytes: _reject_floats(obj) return json.dumps( obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode("utf-8") def _reject_floats(obj, path="$"): if isinstance(obj, float): raise TypeError(f"float at {path}: fields must be int or str") if isinstance(obj, dict): for k, v in obj.items(): _reject_floats(v, f"{path}.{k}") elif isinstance(obj, (list, tuple)): for i, v in enumerate(obj): _reject_floats(v, f"{path}[{i}]") TAG_RUBRIC = b"SCGR1|rubric|" TAG_GRADE = b"SCGR1|grade|" TAG_OBS = b"SCGR1|obs|" RUBRIC_VERSION = "SCGR1/1.0" def _h(tag: bytes, payload: bytes) -> str: return hashlib.sha256(tag + payload).hexdigest() # --------------------------------------------------------------------------- # Field registry # # Every observable field is declared here with its class and its tolerance. # Nothing may be observed that is not in this table, and the table is hashed # into the rubric_hash, so the sheet in the inspector's hand and the sheet the # grade was derived from are provably the same sheet. # # cls "M" machine-read. Exact match required. No tolerance. # cls "H" human-observed. Integer tolerance, or 0 for booleans/enums. # # `tol` is the maximum permitted absolute difference between two independent # observers before the field is considered divergent. It is NOT a claim that # differences within it are meaningless — it is the point past which we stop # assuming two careful people looking at the same scuff. # --------------------------------------------------------------------------- # name -> (class, kind, tolerance, description) FIELDS: Dict[str, Tuple[str, str, int, str]] = { # -- cosmetic, chassis ------------------------------------------------- "dents_ge_2mm": ("H", "int", 1, "Deformations >=2mm in any dimension"), "dents_ge_6mm": ("H", "int", 0, "Deformations >=6mm ('heavy')"), "scratches_ge_10mm": ("H", "int", 2, "External scratches >=10mm long"), "scratches_ge_25mm": ("H", "int", 1, "External scratches >=25mm long"), "discolored_zones_ge_10mm": ("H", "int", 1, "Faded/discolored areas >=10mm"), "label_residue_zones": ("H", "int", 1, "Adhesive or tag residue areas"), "housing_cracked": ("H", "bool", 0, "Any through-crack in the housing"), "hinge_play_mm": ("H", "int", 1, "Lid deflection at 90 degrees, mm"), "hinge_damaged": ("H", "bool", 0, "Hinge bent, seized or detached"), "latch_broken": ("H", "bool", 0, "Latch non-functional"), "missing_parts": ("H", "list", 0, "Bezels, feet, covers, panels, keys"), "critical_parts_missing": ("H", "bool", 0, "Parts required to operate"), "cleaned_labels_removed": ("H", "bool", 0, "Cleaned, non-original labels off"), "packaging": ("H", "enum", 0, "none | generic | original"), "unused": ("H", "bool", 0, "Never placed into service"), "restored_to_like_new": ("H", "bool", 0, "Cosmetically repaired, no blemishes"), "warranty_attached": ("H", "bool", 0, "Program warranty issued with unit"), # -- cosmetic, display ------------------------------------------------- "display_scratches_ge_5mm": ("H", "int", 1, "Panel scratches >=5mm, white field"), "display_dead_pixels": ("M", "int", 0, "Permanently unlit subpixels"), "display_stuck_pixels": ("M", "int", 0, "Permanently lit subpixels"), "display_delamination": ("H", "bool", 0, "Coating or bonding separation"), "backlight_uniform": ("H", "bool", 0, "No visible bleed or blotching"), # -- cosmetic, input --------------------------------------------------- "keys_missing": ("H", "int", 0, "Absent keycaps"), "keys_legend_worn": ("H", "int", 2, "Keycaps with illegible legends"), # -- function ---------------------------------------------------------- "posts": ("M", "bool", 0, "Completes power-on self test"), "key_functions_pass": ("M", "bool", 0, "R2v3 F3 key-function test set"), "all_hardware_pass": ("M", "bool", 0, "Full hardware test suite"), "ports_total": ("M", "int", 0, "Count of external ports"), "ports_failed": ("M", "int", 0, "Ports failing loopback or device test"), "wifi_pass": ("M", "bool", 0, "Associates and passes throughput test"), "bt_pass": ("M", "bool", 0, "Pairs and sustains a link"), "audio_pass": ("M", "bool", 0, "Output and input verified"), "camera_pass": ("M", "bool", 0, "Captures at rated resolution"), "trackpad_pass": ("M", "bool", 0, "Tracks across full surface"), "ram_test_pass": ("M", "bool", 0, "Full-pass memory test, no errors"), "thermal_throttle_observed": ("M", "bool", 0, "Throttled under 15-min load"), "os_licensed_configured": ("M", "bool", 0, "Licensed OS loaded, configured"), "oem_parts_only": ("H", "bool", 0, "All replacements OEM original"), "software_test_results_available": ("M", "bool", 0, "Test log retained"), # -- function, battery ------------------------------------------------- "battery_present": ("M", "bool", 0, "Battery installed"), "battery_design_mwh": ("M", "int", 0, "Rated capacity when new, mWh"), "battery_full_charge_mwh": ("M", "int", 0, "Present full-charge capacity, mWh"), "battery_cycles": ("M", "int", 0, "Reported charge cycles"), # -- function, storage ------------------------------------------------- "storage_present": ("M", "bool", 0, "Storage device installed"), "storage_type": ("M", "enum", 0, "none | hdd | sata_ssd | nvme"), "power_on_hours": ("M", "int", 0, "SMART 9"), "smart_5": ("M", "int", 0, "Reallocated sector count"), "smart_187": ("M", "int", 0, "Reported uncorrectable errors"), "smart_188": ("M", "int", 0, "Command timeout"), "smart_197": ("M", "int", 0, "Current pending sector count"), "smart_198": ("M", "int", 0, "Offline uncorrectable"), # -- sovereign --------------------------------------------------------- "tpm_version": ("M", "enum", 0, "none | 1.2 | 2.0"), "secure_boot_capable": ("M", "bool", 0, "Firmware supports Secure Boot"), "secure_boot_enabled": ("M", "bool", 0, "Secure Boot currently enforced"), "uefi_not_legacy": ("M", "bool", 0, "Boots UEFI, not legacy BIOS/CSM"), "iommu_present": ("M", "bool", 0, "VT-d / AMD-Vi present and enabled"), "ecc_memory": ("M", "bool", 0, "Error-correcting memory"), "dma_ports_lockable": ("M", "bool", 0, "DMA-capable ports can be disabled"), "firmware_latest_applied": ("M", "bool", 0, "Latest vendor firmware applied"), "vendor_support_active": ("M", "bool", 0, "Vendor still issues firmware fixes"), "cpu_microcode_current": ("M", "bool", 0, "Current microcode revision"), "supported_os_available": ("M", "bool", 0, "A vendor-supported OS will run"), "full_disk_encryption": ("M", "bool", 0, "FDE enabled at placement"), # -- sanitization ------------------------------------------------------ "wipe_standard": ("M", "enum", 0, "none | clear | purge (NIST SP 800-88r2)"), "wipe_verified": ("M", "bool", 0, "Sanitization independently verified"), "wipe_certificate_id": ("M", "str", 0, "Certificate identifier, or empty"), } _ENUMS = { "packaging": ("none", "generic", "original"), "storage_type": ("none", "hdd", "sata_ssd", "nvme"), "tpm_version": ("none", "1.2", "2.0"), "wipe_standard": ("none", "clear", "purge"), } # A blank sheet. Every field must be present in a submitted vector; defaults # describe a unit that is unremarkable, working and unsanitized, so that any # omission fails safe rather than flattering the unit. DEFAULTS: Dict[str, Any] = { "dents_ge_2mm": 0, "dents_ge_6mm": 0, "scratches_ge_10mm": 0, "scratches_ge_25mm": 0, "discolored_zones_ge_10mm": 0, "label_residue_zones": 0, "housing_cracked": False, "hinge_play_mm": 0, "hinge_damaged": False, "latch_broken": False, "missing_parts": [], "critical_parts_missing": False, "cleaned_labels_removed": False, "packaging": "none", "unused": False, "restored_to_like_new": False, "warranty_attached": False, "display_scratches_ge_5mm": 0, "display_dead_pixels": 0, "display_stuck_pixels": 0, "display_delamination": False, "backlight_uniform": True, "keys_missing": 0, "keys_legend_worn": 0, "posts": True, "key_functions_pass": True, "all_hardware_pass": False, "ports_total": 0, "ports_failed": 0, "wifi_pass": True, "bt_pass": True, "audio_pass": True, "camera_pass": True, "trackpad_pass": True, "ram_test_pass": True, "thermal_throttle_observed": False, "os_licensed_configured": False, "oem_parts_only": True, "software_test_results_available": False, "battery_present": True, "battery_design_mwh": 0, "battery_full_charge_mwh": 0, "battery_cycles": 0, "storage_present": True, "storage_type": "nvme", "power_on_hours": 0, "smart_5": 0, "smart_187": 0, "smart_188": 0, "smart_197": 0, "smart_198": 0, "tpm_version": "none", "secure_boot_capable": False, "secure_boot_enabled": False, "uefi_not_legacy": False, "iommu_present": False, "ecc_memory": False, "dma_ports_lockable": False, "firmware_latest_applied": False, "vendor_support_active": False, "cpu_microcode_current": False, "supported_os_available": False, "full_disk_encryption": False, "wipe_standard": "none", "wipe_verified": False, "wipe_certificate_id": "", } def blank_sheet() -> Dict[str, Any]: """A fresh observation vector with every field at its fail-safe default.""" import copy return copy.deepcopy(DEFAULTS) def validate(obs: Dict[str, Any]) -> None: """Reject a vector that is not gradeable. Raises ValueError. Deliberately strict. A partially filled sheet is not a weaker observation, it is an ungradeable one, and silently defaulting the gaps would let an inspector improve a grade by leaving boxes empty. """ unknown = set(obs) - set(FIELDS) if unknown: raise ValueError(f"unknown field(s): {sorted(unknown)}") missing = set(FIELDS) - set(obs) if missing: raise ValueError(f"missing field(s): {sorted(missing)}") for name, (_cls, kind, _tol, _desc) in FIELDS.items(): v = obs[name] if isinstance(v, float): raise ValueError(f"{name}: float not permitted") if kind == "int": if not isinstance(v, int) or isinstance(v, bool): raise ValueError(f"{name}: expected int, got {type(v).__name__}") if v < 0: raise ValueError(f"{name}: negative count") elif kind == "bool": if not isinstance(v, bool): raise ValueError(f"{name}: expected bool") elif kind == "enum": if v not in _ENUMS[name]: raise ValueError(f"{name}: {v!r} not in {_ENUMS[name]}") elif kind == "str": if not isinstance(v, str): raise ValueError(f"{name}: expected str") elif kind == "list": if not isinstance(v, list) or any(not isinstance(x, str) for x in v): raise ValueError(f"{name}: expected list of str") if obs["battery_present"]: if obs["battery_full_charge_mwh"] > obs["battery_design_mwh"] > 0: raise ValueError("battery full charge exceeds design capacity") if obs["ports_failed"] > obs["ports_total"]: raise ValueError("ports_failed exceeds ports_total") # --------------------------------------------------------------------------- # Derived measures # --------------------------------------------------------------------------- def battery_health_pct(obs: Dict[str, Any]) -> Optional[int]: """Full-charge capacity as a percentage of design capacity, half-up. Returns None when there is no battery or no design figure to divide by, which is different from 0 and must not be conflated with it. """ if not obs["battery_present"]: return None design = obs["battery_design_mwh"] if design <= 0: return None full = obs["battery_full_charge_mwh"] return (full * 100 * 2 + design) // (design * 2) def storage_suspect(obs: Dict[str, Any]) -> bool: """True when SMART shows any of the counters that actually correlate with impending failure. Backblaze's published analysis identifies SMART 5, 187, 188, 197 and 198 as the five that predict failure; any non-zero value in that set is treated as disqualifying rather than scored, because a drive that is beginning to fail is not a drive with a slightly lower grade.""" if not obs["storage_present"]: return False return any(obs[k] > 0 for k in ("smart_5", "smart_187", "smart_188", "smart_197", "smart_198")) def cosmetic_defect_load(obs: Dict[str, Any]) -> int: """A single integer summarising visible wear. Used only for reporting and for ordering units within a grade — never for deriving the grade itself, which uses explicit predicates so that it is inspectable.""" return (obs["dents_ge_2mm"] + 3 * obs["dents_ge_6mm"] + obs["scratches_ge_10mm"] + 2 * obs["scratches_ge_25mm"] + obs["discolored_zones_ge_10mm"] + obs["label_residue_zones"] + 2 * obs["display_scratches_ge_5mm"] + 3 * obs["keys_missing"] + obs["keys_legend_worn"] + 5 * len(obs["missing_parts"])) # --------------------------------------------------------------------------- # Cosmetic derivation — R2v3 C0..C9 # # Evaluated from the top. The unit receives the highest category whose # predicates it fully satisfies. Every predicate is a count against a defined # threshold, so two people with the same sheet always reach the same letter. # --------------------------------------------------------------------------- def _no_missing(obs) -> bool: return not obs["missing_parts"] and not obs["critical_parts_missing"] def _no_structural(obs) -> bool: return (not obs["housing_cracked"] and not obs["hinge_damaged"] and not obs["latch_broken"] and obs["hinge_play_mm"] <= 1) def _pristine(obs) -> bool: return (obs["dents_ge_2mm"] == 0 and obs["dents_ge_6mm"] == 0 and obs["scratches_ge_10mm"] == 0 and obs["scratches_ge_25mm"] == 0 and obs["discolored_zones_ge_10mm"] == 0 and obs["label_residue_zones"] == 0 and obs["display_scratches_ge_5mm"] == 0 and not obs["display_delamination"] and obs["keys_missing"] == 0 and obs["keys_legend_worn"] == 0 and _no_missing(obs) and _no_structural(obs)) def derive_cosmetic(obs: Dict[str, Any]) -> Tuple[int, str, List[str]]: """Return (code, label, reasons). Reasons explain the binding constraint — the thing that stopped it reaching the next category up. An inspector who disagrees with a grade needs to know which line to argue with.""" r: List[str] = [] if obs["housing_cracked"] or obs["critical_parts_missing"]: r.append("housing cracked or critical parts missing") return 1, "Damaged (for materials recovery)", r if obs["unused"] and _pristine(obs): if obs["packaging"] == "original": return 9, "New Open Box", ["unused, original packaging opened"] return 8, "Unused", ["unused, no signs of wear"] if obs["restored_to_like_new"] and _pristine(obs) and obs["warranty_attached"]: return 7, "Certified Pre-Owned", ["restored to like-new, warranty attached"] # C6 Used Excellent if (obs["dents_ge_2mm"] == 0 and obs["dents_ge_6mm"] == 0 and obs["scratches_ge_25mm"] == 0 and obs["scratches_ge_10mm"] <= 2 and obs["display_scratches_ge_5mm"] == 0 and not obs["display_delamination"] and obs["discolored_zones_ge_10mm"] == 0 and obs["keys_missing"] == 0 and obs["cleaned_labels_removed"] and obs["label_residue_zones"] == 0 and _no_missing(obs) and _no_structural(obs)): return 6, "Used Excellent", ["light wear only, cleaned, nothing missing"] # C5 Used Very Good if (obs["dents_ge_6mm"] == 0 and obs["dents_ge_2mm"] <= 2 and obs["scratches_ge_25mm"] <= 1 and obs["discolored_zones_ge_10mm"] <= 1 and obs["display_scratches_ge_5mm"] <= 1 and not obs["display_delamination"] and obs["keys_missing"] == 0 and _no_missing(obs) and _no_structural(obs)): return 5, "Used Very Good", ["minor wear, nothing missing, no damage"] # C4 Used Good if (obs["dents_ge_6mm"] == 0 and obs["dents_ge_2mm"] <= 5 and obs["keys_missing"] <= 1 and not obs["display_delamination"] and _no_missing(obs) and _no_structural(obs)): return 4, "Used Good", ["consistent-use wear, no damage, nothing missing"] # C3 Used Fair — wear plus some damage or non-critical missing parts if not obs["critical_parts_missing"] and obs["dents_ge_6mm"] <= 3: why = [] if obs["dents_ge_6mm"]: why.append(f"{obs['dents_ge_6mm']} heavy dent(s)") if obs["missing_parts"]: why.append("missing " + ", ".join(obs["missing_parts"])) if obs["hinge_damaged"] or obs["latch_broken"]: why.append("hinge or latch damage") if obs["keys_missing"]: why.append(f"{obs['keys_missing']} key(s) missing") if not why: why.append("wear beyond Used Good thresholds") return 3, "Used Fair", why r.append("heavy damage prevalent") return 2, "Used Poor", r # --------------------------------------------------------------------------- # Functional derivation — R2v3 F0..F6 # --------------------------------------------------------------------------- def derive_functional(obs: Dict[str, Any]) -> Tuple[int, str, List[str]]: if not obs["posts"]: return 0, "Not functional", ["does not complete power-on self test"] hardware_clean = ( obs["all_hardware_pass"] and obs["ports_failed"] == 0 and obs["wifi_pass"] and obs["bt_pass"] and obs["audio_pass"] and obs["camera_pass"] and obs["trackpad_pass"] and obs["ram_test_pass"] and not obs["thermal_throttle_observed"] and not storage_suspect(obs) and obs["display_dead_pixels"] == 0 and obs["display_stuck_pixels"] == 0 and not obs["critical_parts_missing"] and not obs["missing_parts"] ) if (hardware_clean and obs["os_licensed_configured"] and obs["software_test_results_available"] and obs["oem_parts_only"]): bh = battery_health_pct(obs) if not obs["battery_present"] or (bh is not None and bh >= 90): return 6, "Like New", ["zero defects, OEM parts, configured, tested"] return 5, "Refurbished", [ f"battery health {bh}% is below the 90% Like New floor"] if hardware_clean and obs["os_licensed_configured"] and obs["software_test_results_available"]: return 5, "Refurbished", ["all functions tested, licensed software configured"] if hardware_clean: return 4, "Hardware Functional", ["hardware verified, software not configured"] if obs["key_functions_pass"]: why = [] if obs["ports_failed"]: why.append(f"{obs['ports_failed']} of {obs['ports_total']} ports failed") if storage_suspect(obs): why.append("SMART failure indicators present") if obs["thermal_throttle_observed"]: why.append("throttles under sustained load") for k, lbl in (("wifi_pass", "wifi"), ("bt_pass", "bluetooth"), ("audio_pass", "audio"), ("camera_pass", "camera"), ("trackpad_pass", "trackpad"), ("ram_test_pass", "memory")): if not obs[k]: why.append(f"{lbl} failed") if obs["display_dead_pixels"] or obs["display_stuck_pixels"]: why.append("display pixel defects") if obs["missing_parts"]: why.append("missing " + ", ".join(obs["missing_parts"])) if not why: why.append("full hardware suite not run") return 3, "Key Functions Working", why return 0, "Not functional", ["key function test failed"] # --------------------------------------------------------------------------- # Sovereign derivation — S0..S4 # # This axis has no equivalent in R2v3, which grades condition and says nothing # about whether a machine can be defended. It is the axis that decides # placement, because in this program the protection does not descend with the # hardware — only the workload does. # --------------------------------------------------------------------------- def derive_sovereign(obs: Dict[str, Any]) -> Tuple[int, str, List[str]]: # Sanitization is a gate, not a grade. Nothing unsanitized is placeable at # any tier, in any condition, at any price. if obs["wipe_standard"] == "none" or not obs["wipe_verified"]: return 0, "Not placeable", [ "sanitization not performed or not verified (NIST SP 800-88r2)"] if not obs["supported_os_available"]: return 0, "Not placeable", [ "no vendor-supported operating system will run on this unit"] tpm2 = obs["tpm_version"] == "2.0" reasons: List[str] = [] if (tpm2 and obs["secure_boot_enabled"] and obs["uefi_not_legacy"] and obs["iommu_present"] and obs["dma_ports_lockable"] and obs["firmware_latest_applied"] and obs["vendor_support_active"] and obs["cpu_microcode_current"] and obs["full_disk_encryption"] and obs["wipe_standard"] == "purge"): return 4, "Sovereign Full", [ "TPM 2.0, Secure Boot enforced, IOMMU, DMA lockable, " "firmware current, vendor support active, purge-verified"] if (tpm2 and obs["secure_boot_capable"] and obs["uefi_not_legacy"] and obs["firmware_latest_applied"] and obs["full_disk_encryption"]): if not obs["vendor_support_active"]: reasons.append("vendor no longer issues firmware fixes") if not obs["iommu_present"]: reasons.append("no IOMMU") if not obs["dma_ports_lockable"]: reasons.append("DMA-capable ports cannot be disabled") if obs["wipe_standard"] != "purge": reasons.append("sanitized to Clear, not Purge") return 3, "Sovereign Standard", reasons or ["meets the standard envelope"] if obs["uefi_not_legacy"] and obs["secure_boot_capable"] and obs["full_disk_encryption"]: if not tpm2: reasons.append( f"TPM {obs['tpm_version']} — no hardware root of trust for " "measured boot; Microsoft treats TPM 1.2 as insufficient") if not obs["firmware_latest_applied"]: reasons.append("firmware not at latest available revision") return 2, "Sovereign Limited", reasons if not obs["uefi_not_legacy"]: reasons.append("legacy BIOS boot — no Secure Boot chain") if not obs["secure_boot_capable"]: reasons.append("firmware cannot enforce Secure Boot") if not obs["full_disk_encryption"]: reasons.append("full-disk encryption not enabled") return 1, "Contained Only", reasons # --------------------------------------------------------------------------- # Tier eligibility # # "Hardware is matched to the workload. Protection is not." # # The floor conditions below apply identically at every tier. They are the # operational meaning of that sentence: what descends the cascade is the # consequence of compromise, never the standard of defence. # --------------------------------------------------------------------------- FLOOR_CONDITIONS = ( ("wipe_verified", "sanitization verified"), ("full_disk_encryption", "full-disk encryption enabled"), ("supported_os_available", "vendor-supported OS available"), ) # Cosmetic condition does not choose a tier. A scuffed unit and an immaculate # one serve the same tier if their function and sovereign grades agree, and # that is deliberate — nobody is placed on worse-protected hardware because # their machine looks older. # # But C1 and C2 are not descriptions of appearance. C1 is a cracked or # structurally damaged housing, routed by R2v3 to materials recovery. C2 has # critical parts missing and prevalent latch, hinge and keyboard damage. Those # are durability and safety findings wearing cosmetic clothing, so they gate # placement where C3 and above do not. COSMETIC_PLACEMENT_FLOOR = 3 TIERS = ( ("A", "Business and agency", 4, 5), ("B", "Small business, nonprofit, congregation", 3, 4), ("C", "Household adults", 2, 4), ("D", "Children — homework and coding lab", 2, 3), ) def derive_tier(s_code: int, f_code: int, obs: Dict[str, Any]) -> Tuple[str, str, List[str]]: """Highest tier this unit may serve, and why it stops there.""" for key, why in FLOOR_CONDITIONS: if not obs[key]: return "R", "Recovery", [f"floor condition unmet: {why}"] if s_code == 0: return "R", "Recovery", ["S0 — not placeable"] c_code, c_label, _ = derive_cosmetic(obs) if c_code < COSMETIC_PLACEMENT_FLOOR: if c_code <= 1: return "R", "Recovery", [ f"C{c_code} {c_label} — structural damage, not placeable " f"regardless of function or sovereign grade"] return "P", "Repair before placement", [ f"C{c_code} {c_label} — must reach C{COSMETIC_PLACEMENT_FLOOR} " f"before it can be placed with anyone"] for name, label, s_min, f_min in TIERS: if s_code >= s_min and f_code >= f_min: nxt = {"B": "A", "C": "B", "D": "C"}.get(name) note = [] if nxt: nt = next(t for t in TIERS if t[0] == nxt) if s_code < nt[2]: note.append(f"S{s_code} below S{nt[2]} required for Tier {nxt}") if f_code < nt[3]: note.append(f"F{f_code} below F{nt[3]} required for Tier {nxt}") return name, label, note if s_code == 1: return "L", "Contained lab use only, not personal placement", [ "S1 units are not placed with households or children; " "firmware-level persistence cannot be excluded"] return "R", "Recovery", [f"S{s_code}/F{f_code} below the lowest placement tier"] # --------------------------------------------------------------------------- # Grade # --------------------------------------------------------------------------- @dataclass(frozen=True) class Grade: f: int c: int s: int f_label: str c_label: str s_label: str tier: str tier_label: str battery_health_pct: Optional[int] defect_load: int reasons: Dict[str, List[str]] = field(default_factory=dict) @property def code(self) -> str: return f"F{self.f}/C{self.c}/S{self.s}" def to_dict(self) -> Dict[str, Any]: return { "code": self.code, "f": self.f, "c": self.c, "s": self.s, "f_label": self.f_label, "c_label": self.c_label, "s_label": self.s_label, "tier": self.tier, "tier_label": self.tier_label, "battery_health_pct": self.battery_health_pct, "defect_load": self.defect_load, } def grade(obs: Dict[str, Any]) -> Grade: """Derive the full grade. Pure function of the observation vector.""" validate(obs) c, c_label, c_why = derive_cosmetic(obs) f, f_label, f_why = derive_functional(obs) s, s_label, s_why = derive_sovereign(obs) tier, tier_label, t_why = derive_tier(s, f, obs) return Grade( f=f, c=c, s=s, f_label=f_label, c_label=c_label, s_label=s_label, tier=tier, tier_label=tier_label, battery_health_pct=battery_health_pct(obs), defect_load=cosmetic_defect_load(obs), reasons={"cosmetic": c_why, "functional": f_why, "sovereign": s_why, "tier": t_why}, ) def rubric_hash() -> str: """Hash of the rubric itself: field registry, enums, tier table and floor conditions. Published before any observation window opens, exactly as policy_hash is published before any commit window opens. Changing a threshold changes this hash, so a rubric cannot be edited after the fact to move a unit into a different band.""" spec = { "version": RUBRIC_VERSION, "fields": {k: [v[0], v[1], v[2]] for k, v in sorted(FIELDS.items())}, "enums": {k: list(v) for k, v in sorted(_ENUMS.items())}, "tiers": [list(t) for t in TIERS], "floor": [list(x) for x in FLOOR_CONDITIONS], "cosmetic_placement_floor": COSMETIC_PLACEMENT_FLOOR, } return _h(TAG_RUBRIC, canon(spec)) def observation_hash(obs: Dict[str, Any], nonce: str) -> str: """Commitment over an observation vector. Same construction as the price commitment in SCDA1: the sheet plus a blinding nonce, so an inspector cannot adjust counts after seeing the other side's sheet.""" validate(obs) return _h(TAG_OBS, canon({"obs": obs, "nonce": nonce, "rubric": rubric_hash()})) def grade_token(obs: Dict[str, Any]) -> str: """The token that binds a grade into a price attestation. Committed over the *observations* and the rubric, not over the derived letters, because the derivation is deterministic and published — anyone holding the sheet can recompute the letters and check them. This is what makes a grade dispute reduce to an observation dispute, which is answerable with evidence rather than with seniority. """ g = grade(obs) return _h(TAG_GRADE, canon({"rubric": rubric_hash(), "obs": obs, "derived": g.to_dict()})) # --------------------------------------------------------------------------- # Reconciliation # --------------------------------------------------------------------------- @dataclass(frozen=True) class Reconciliation: status: str # "agreed" | "immaterial" | "material" | "void" grade_holder: Optional[Grade] grade_inspector: Optional[Grade] agreed_grade: Optional[Grade] machine_conflicts: List[str] out_of_tolerance: List[str] differing_fields: List[str] pivotal_fields: List[str] note: str def to_dict(self) -> Dict[str, Any]: return { "status": self.status, "grade_holder": self.grade_holder.to_dict() if self.grade_holder else None, "grade_inspector": self.grade_inspector.to_dict() if self.grade_inspector else None, "agreed_grade": self.agreed_grade.to_dict() if self.agreed_grade else None, "machine_conflicts": self.machine_conflicts, "out_of_tolerance": self.out_of_tolerance, "differing_fields": self.differing_fields, "pivotal_fields": self.pivotal_fields, "note": self.note, } def _diff_fields(a: Dict[str, Any], b: Dict[str, Any]) -> List[str]: return sorted(k for k in FIELDS if a[k] != b[k]) def minimal_divergence_set(holder: Dict[str, Any], inspector: Dict[str, Any]) -> List[str]: """The smallest set of fields responsible for a grade difference. Method: for each field on which the two sheets differ, substitute the inspector's value into the holder's sheet on its own and see whether the derived grade moves toward the inspector's. Fields that move it are pivotal. If no single field is pivotal the difference is produced by a combination, and the whole differing set is returned rather than a misleadingly small one — the honest answer to "which measurement decided this" is sometimes "several together". Only these fields need re-inspection. Everything else the two parties disagree about is, by construction, immaterial to the outcome. """ gh, gi = grade(holder), grade(inspector) if (gh.f, gh.c, gh.s) == (gi.f, gi.c, gi.s): return [] diffs = _diff_fields(holder, inspector) pivotal = [] for name in diffs: trial = dict(holder) trial[name] = inspector[name] gt = grade(trial) if (gt.f, gt.c, gt.s) != (gh.f, gh.c, gh.s): pivotal.append(name) return pivotal if pivotal else diffs def reconcile(holder: Dict[str, Any], inspector: Dict[str, Any]) -> Reconciliation: """Compare two independently produced observation vectors. Order of checks matters and is deliberate: 1. Class M conflicts void the round. A machine reading that differs between two parties is not a difference of opinion. 2. Class H fields outside tolerance are recorded, but do not by themselves stop anything — the materiality test decides. 3. Materiality. If both sheets derive to the same grade, the round proceeds on that grade regardless of how much the counts differ. 4. Only if the grades differ is anything escalated, and then only the pivotal fields. """ validate(holder) validate(inspector) machine_conflicts = [ k for k, (cls, *_rest) in FIELDS.items() if cls == "M" and holder[k] != inspector[k] ] if machine_conflicts: return Reconciliation( status="void", grade_holder=None, grade_inspector=None, agreed_grade=None, machine_conflicts=sorted(machine_conflicts), out_of_tolerance=[], differing_fields=_diff_fields(holder, inspector), pivotal_fields=[], note=("machine-read fields disagree; the unit must be re-read " "before it can be graded"), ) out_of_tol: List[str] = [] for name, (cls, kind, tol, _d) in FIELDS.items(): if cls != "H" or holder[name] == inspector[name]: continue if kind == "int": if abs(holder[name] - inspector[name]) > tol: out_of_tol.append(name) else: out_of_tol.append(name) gh, gi = grade(holder), grade(inspector) diffs = _diff_fields(holder, inspector) if (gh.f, gh.c, gh.s) == (gi.f, gi.c, gi.s): if not diffs: return Reconciliation( status="agreed", grade_holder=gh, grade_inspector=gi, agreed_grade=gh, machine_conflicts=[], out_of_tolerance=[], differing_fields=[], pivotal_fields=[], note="identical observations", ) return Reconciliation( status="immaterial", grade_holder=gh, grade_inspector=gi, agreed_grade=gh, machine_conflicts=[], out_of_tolerance=sorted(out_of_tol), differing_fields=diffs, pivotal_fields=[], note=(f"{len(diffs)} field(s) differ but both sheets derive to " f"{gh.code}; divergence is immaterial and the round proceeds"), ) pivotal = minimal_divergence_set(holder, inspector) return Reconciliation( status="material", grade_holder=gh, grade_inspector=gi, agreed_grade=None, machine_conflicts=[], out_of_tolerance=sorted(out_of_tol), differing_fields=diffs, pivotal_fields=pivotal, note=(f"sheets derive to {gh.code} and {gi.code}; re-inspect " f"{len(pivotal)} field(s): {', '.join(pivotal)}"), ) def conservative_merge(holder: Dict[str, Any], inspector: Dict[str, Any]) -> Dict[str, Any]: """Fallback used only when a material divergence survives re-inspection. Takes the worse value for every differing field, producing the lowest grade consistent with both sheets. This is not a fair-value estimate and is not presented as one — it is a deliberate tie-break against the party proposing the unit, applied when the parties cannot agree on what is physically in front of them. Its purpose is to make unresolved divergence unattractive rather than to be correct. """ validate(holder) validate(inspector) merged = dict(holder) for name, (_cls, kind, _tol, _d) in FIELDS.items(): a, b = holder[name], inspector[name] if a == b: continue if kind == "int": # Every integer field in this rubric counts a defect or a wear # measure except the battery/port/storage capacity figures, which # are Class M and cannot reach here. merged[name] = max(a, b) elif kind == "bool": good_when_true = name in ( "cleaned_labels_removed", "backlight_uniform", "oem_parts_only", "restored_to_like_new", "warranty_attached", "unused", ) merged[name] = (a and b) if good_when_true else (a or b) elif kind == "list": merged[name] = sorted(set(a) | set(b)) elif kind == "enum": order = _ENUMS[name] merged[name] = a if order.index(a) < order.index(b) else b elif kind == "str": merged[name] = "" if a != b else a return merged __all__ = [ "RUBRIC_VERSION", "FIELDS", "DEFAULTS", "TIERS", "FLOOR_CONDITIONS", "COSMETIC_PLACEMENT_FLOOR", "blank_sheet", "validate", "battery_health_pct", "storage_suspect", "cosmetic_defect_load", "derive_cosmetic", "derive_functional", "derive_sovereign", "derive_tier", "Grade", "grade", "rubric_hash", "observation_hash", "grade_token", "Reconciliation", "reconcile", "minimal_divergence_set", "conservative_merge", ]