Official Codebase of 3DCodeVerse
Python
judges: the judge reads the contact ledger, not interpenetration prose
gaoypengd6e417ac2493
diff --git a/harness/codeverse/judges/prompt_builder.py b/harness/codeverse/judges/prompt_builder.pyindex ee22396f..0fd14cf4 100644--- a/harness/codeverse/judges/prompt_builder.py+++ b/harness/codeverse/judges/prompt_builder.py@@ -27,6 +27,7 @@ from PIL import Image, ImageDrawfrom codeverse.config import get_settingsfrom codeverse.contracts.artifacts import (RENDER_MODES,+ GateFinding,GateReport,Judgment,Measurement,@@ -38,7 +39,8 @@ from codeverse.contracts.chat import ChatMessage, ImagePart, TextPartfrom codeverse.contracts.plan import AcceptanceItemfrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS, SCENE_VIEWS, ViewPreset-from codeverse.judges.rubrics import Rubric+from codeverse.judges.rubrics import VETO_PENETRATION_DEPTH_M, Rubric+from codeverse.spatial.connectivity import PENETRATION_ERROR_M, PENETRATION_WARN_Mfrom codeverse.spatial.measure import measure_summary_tablefrom codeverse.spatial.sheet import crop_region, load_font, montage_2x2@@ -467,45 +469,270 @@ def measurement_section(m: Measurement | None) -> str:return "MEASUREMENTS (harness, Y-up meters):\n" + _clip(str(measure_summary_table(m)), 6000)+#: MEASURED STRUCTURE clips. p90 of the 321 stored static_object rounds that report a+#: contact count is 26 contacts (2026-08-30, scratch corpus_ledger.py over bench/out); the+#: whole block has to stay near 500 tokens on such a round, so contacts and planned joins+#: are cut with an "… n more" rather than listed to the end.+LEDGER_MAX_CONTACTS = 24+LEDGER_MAX_JOINS = 20+#: Parts whose lowest vertex is within this of the object's lowest point are the ground-contact+#: candidates; only those get a floor gap in the prompt (a lamp shade is not "above the floor").+GROUND_BAND_MM = 10.0+#: A near-floor gap at or under this is a hairline: the corpus has a verdict writing "legs end+#: above the ground plane" on 0.3 mm, so the number is printed instead of the adjective.+GROUND_GAP_REPORT_MM = 0.5++_PASSED_FLOATING = (+ "CONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). "+ "A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any "+ "part as floating, hovering or disconnected, and do not mark the floating-part defect present; "+ "if a joint looks visually ugly, say so under craftsmanship."+)+++def contact_ledger(gates: list[GateReport]) -> tuple[GateReport, GateFinding] | None:+ """The connectivity gate's per-pair table — one INFO finding per report since 2026-08-30+ (``spatial.connectivity._ledger``) — with the report that carries it; ``None`` on a+ round recorded before it existed."""+ for g in gates:+ if g.gate != "connectivity":+ continue+ for f in g.findings:+ if f.severity == Severity.INFO and f.data.get("kind") == "ledger":+ return g, f+ return None++def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: int = 8) -> str:+ """The judge's gate facts. ERRORs are listed as recorded. With a contact ledger the+ connectivity WARNs are not prose any more: the audit of 420 judged static rounds+ (2026-08-30, docs/EVAL.md §6) found the judge marking interpenetration on every gate+ ERROR (69/69) and on 110 rounds whose only evidence was a WARN the rubric tells it to+ ignore — it read the gate's sentences, not the images (same images, gate text removed:+ 13 of 24 flags flipped). So the WARNs become one measured line and a MEASURED STRUCTURE+ block (contacts, planned joins contact/open, floor gaps) the judge can cite instead.+ Without a ledger (older rounds) the text is the pre-ledger text byte for byte, which is+ what keeps ``3dcv judge <old-slug>`` comparable with the verdict it stored."""if not gates:return "GATE FINDINGS: (no gates run)"- errs, warns = [], []- for g in gates:- for f in g.findings:- tgt = f" [{f.target}]" if f.target else ""- line = f"- {g.gate}{tgt}: {_clip(f.message, 220)}"- (errs if f.severity == Severity.ERROR else warns if f.severity == Severity.WARN else []).append(line)status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in gates)lines = [f"GATE FINDINGS (deterministic; treat as facts): {status}"]- if errs:- lines.append(f"errors ({len(errs)}):")- lines.extend(errs[:max_errors])- if len(errs) > max_errors:- lines.append(f"- … {len(errs) - max_errors} more errors")- if warns:- lines.append(f"warnings ({len(warns)}):")- lines.extend(warns[:max_warns])- if len(warns) > max_warns:- lines.append(f"- … {len(warns) - max_warns} more warnings")- if not errs and not warns:+ errs = [_finding_line(g, f) for g in gates for f in g.findings if f.severity == Severity.ERROR]+ found = contact_ledger(gates)+ if found is None:+ warns = [_finding_line(g, f) for g in gates for f in g.findings if f.severity == Severity.WARN]+ lines += _capped("errors", errs, max_errors) + _capped("warnings", warns, max_warns)+ if not errs and not warns:+ lines.append("no errors or warnings — parts are connected and contracts hold.")+ if any(g.gate == "connectivity" and g.passed for g in gates):+ # The connectivity gate MEASURES mesh-to-mesh contact; a VLM reads shading. Measured+ # 2026-08-26 (fancy_v1 gas_street_lamp, plan-pinned pair): on a lamp whose gate said+ # "all 9 parts connected, gap <= 2 mm", the judge called the dark seam under the+ # pedestal "floating in mid-air, a clear daylight gap" — CRITICAL — and scored+ # structure_plausibility 0.4 against 1.0 for the near-identical sibling. A measured+ # contact outranks a shadow (CLAUDE.md law 3); the seam is at most a craftsmanship note.+ lines.append(_PASSED_FLOATING)+ return "\n".join(lines)+ conn, ledger = found+ d = ledger.data+ lines += _capped("errors", errs, max_errors)+ lines += _structure_block(conn, d)+ overlap = _overlap_line(conn, d)+ if overlap:+ lines.append(overlap)+ rest = [(g, f) for g in gates for f in g.findings+ if f.severity == Severity.WARN and not (g.gate == "connectivity" and f.data.get("kind") == "penetration")]+ lines += _grouped_warnings(rest, max_warns)+ if not errs and not any(f.severity == Severity.WARN for g in gates for f in g.findings):lines.append("no errors or warnings — parts are connected and contracts hold.")- if any(g.gate == "connectivity" and g.passed for g in gates):- # The connectivity gate MEASURES mesh-to-mesh contact; a VLM reads shading. Measured- # 2026-08-26 (fancy_v1 gas_street_lamp, plan-pinned pair): on a lamp whose gate said- # "all 9 parts connected, gap <= 2 mm", the judge called the dark seam under the- # pedestal "floating in mid-air, a clear daylight gap" — CRITICAL — and scored- # structure_plausibility 0.4 against 1.0 for the near-identical sibling. A measured- # contact outranks a shadow (CLAUDE.md law 3); the seam is at most a craftsmanship note.- lines.append(- "CONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). "- "A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any "- "part as floating, hovering or disconnected, and do not mark the floating-part defect present; "- "if a joint looks visually ugly, say so under craftsmanship."- )+ n_parts = len(d.get("parts") or [])+ if conn.passed and n_parts >= 2:+ lines.append(_passed_paragraph(n_parts, len(d.get("contacts") or []), float(d.get("contact_gap_mm") or 0.0),+ list(d.get("overlaps") or [])))return "\n".join(lines)+def _finding_line(g: GateReport, f: GateFinding) -> str:+ tgt = f" [{f.target}]" if f.target else ""+ return f"- {g.gate}{tgt}: {_clip(f.message, 220)}"+++def _capped(label: str, items: list[str], cap: int) -> list[str]:+ if not items:+ return []+ out = [f"{label} ({len(items)}):", *items[:cap]]+ if len(items) > cap:+ out.append(f"- … {len(items) - cap} more {label}")+ return out+++def _structure_block(conn: GateReport, d: dict) -> list[str]:+ """N parts / E contacts / floating / overlaps, the contact graph, the plan's joins measured+ contact or OPEN, and the floor gap of the parts that could be standing on the floor."""+ parts = list(d.get("parts") or [])+ contacts = list(d.get("contacts") or [])+ gap = float(d.get("contact_gap_mm") or 0.0)+ floating = sum(1 for f in conn.findings if f.severity == Severity.ERROR and f.data.get("kind") == "floating")+ lines = [+ f"MEASURED STRUCTURE (connectivity gate, exact mesh-to-mesh distances): {len(parts)} part{'s' if len(parts) != 1 else ''}, "+ f"{len(contacts)} contacts (gap ≤ {gap:g} mm), {floating} floating, {len(d.get('overlaps') or [])} overlapping pairs."+ ]+ planned = list(d.get("planned") or [])+ if planned:+ lines.append("- " + _planned_line(planned, gap))+ # the planned joins already list their contacts pair by pair; the adjacency adds what the+ # plan did not ask for (an apron touching a stretcher) instead of repeating it+ planned_pairs = {frozenset((str(a), str(b))) for a, b, _g, st in planned if st == "contact"}+ other = [c for c in contacts if frozenset((str(c[0]), str(c[1]))) not in planned_pairs]+ if other:+ label = "other contacts, not in the plan" if planned_pairs else "contacts"+ lines.append(f"- {label} (gap in mm where not 0): " + _adjacency(other, LEDGER_MAX_CONTACTS))+ unresolved = list(d.get("planned_unresolved") or [])+ if unresolved:+ lines.append(f"- plan parts not found in the mesh: {', '.join(unresolved[:8])}" + (" …" if len(unresolved) > 8 else ""))+ ground = _ground_line(d.get("ground_gap_mm") or {})+ if ground:+ lines.append("- " + ground)+ return lines+++def _gap(mm: float) -> str:+ """A contact's gap: nothing when it rounds to 0.0 mm (most do), else the number —+ 26 "0.0" tokens were a fifth of the block on the p90 round."""+ return f" {mm:.1f}" if round(mm, 1) else ""+++def _adjacency(contacts: list, cap: int) -> str:+ by_a: dict[str, list[str]] = {}+ for a, b, gap in contacts[:cap]:+ by_a.setdefault(str(a), []).append(f"{b}{_gap(float(gap))}")+ text = " · ".join(f"{a}: {', '.join(bs)}" for a, bs in by_a.items())+ if len(contacts) > cap:+ text += f" · … {len(contacts) - cap} more"+ return text+++def _planned_line(planned: list, gap_mm: float) -> str:+ """OPEN joins first so the clip never hides one: they are the assembly_fit signal."""+ rows = [(str(a), str(b), float(g), str(st)) for a, b, g, st in planned]+ open_rows = [r for r in rows if r[3] != "contact"]+ contact_rows = [r for r in rows if r[3] == "contact"]+ shown = (open_rows + contact_rows)[:LEDGER_MAX_JOINS]+ bits = [f"PLANNED JOINS (the plan's attach_to pairs, measured; contact = gap ≤ {gap_mm:g} mm): "+ f"{len(contact_rows)}/{len(rows)} in contact."]+ if any(r[3] != "contact" for r in shown):+ bits.append("OPEN: " + "; ".join(f"{a}→{b} {g:.1f} mm" for a, b, g, st in shown if st != "contact") + ".")+ if any(r[3] == "contact" for r in shown):+ bits.append("CONTACT (gap in mm where not 0): " + ", ".join(f"{a}→{b}{_gap(g)}" for a, b, g, st in shown if st == "contact") + ".")+ if len(rows) > len(shown):+ bits.append(f"… {len(rows) - len(shown)} more.")+ return " ".join(bits)+++def _ground_line(ground: dict) -> str:+ if not ground:+ return ""+ low_name, low = min(((str(n), float(g)) for n, g in ground.items()), key=lambda kv: kv[1])+ band = [(str(n), float(g)) for n, g in ground.items() if float(g) - low <= GROUND_BAND_MM]+ up = [(n, g) for n, g in band if g > GROUND_GAP_REPORT_MM]+ if low > GROUND_GAP_REPORT_MM:+ head = f"ground: lowest point {low:.1f} mm above the floor ({low_name}) — nothing touches it"+ elif low < -GROUND_GAP_REPORT_MM:+ head = f"ground: lowest point {-low:.1f} mm below the floor ({low_name})"+ else:+ head = f"ground: lowest point {low:.1f} mm ({low_name}) — floor contact"+ if up:+ head += (f"; parts within {GROUND_BAND_MM:g} mm of the floor: "+ + ", ".join(f"{n} {g:.1f} mm" for n, g in up[:8]) + (" …" if len(up) > 8 else ""))+ else:+ head += f"; every other near-floor part is within {GROUND_GAP_REPORT_MM:g} mm of the floor"+ return head+++def _overlap_line(conn: GateReport, d: dict) -> str:+ """The measured replacement for the interpenetration WARN prose. The gate's ERROR+ pairs are already listed under errors; every other overlapping pair is a weld by the+ gate's own rule (depth ≤ 10 mm; the through-ratio is a fact, not a severity), and the+ rubric says a weld is not the defect — the judge marked it anyway on 110 WARN-only rounds.+ A pair reaching half-way or more through its partner is named as a measurement: the ratio+ saturates at the mid-plane and cannot tell "ends inside" from "out the far side", so that+ reading is left to the geometry montage."""+ over = list(d.get("overlaps") or [])+ if not over:+ return ""+ error_pairs = {(f.target, f.data.get("other")) for f in conn.findings+ if f.severity == Severity.ERROR and f.data.get("kind") == "penetration"}+ rest = [r for r in over if (str(r[0]), str(r[1])) not in error_pairs]+ # classified by MEASURED depth, never by severity: the gate keeps a deep overlap a WARN when+ # only a sliver of surface is inside (a stile 17 mm through a seat), and calling that a+ # "weld under the ERROR line" would hand the judge a false fact (skeptic 2026-08-30)+ deep = [r for r in rest if float(r[2]) > PENETRATION_ERROR_M * 1000]+ welds = [r for r in rest if float(r[2]) <= PENETRATION_ERROR_M * 1000]+ text = f"connectivity measured {len(over)} mating overlaps"+ if welds:+ a, b, depth, through = max(welds, key=lambda r: float(r[2]))+ text += f" (deepest weld {float(depth):.1f} mm {a}/{b}, through-ratio {float(through):.2f})"+ text += f"; weld allowance {PENETRATION_WARN_M * 1000:g} mm, ERROR line {PENETRATION_ERROR_M * 1000:g} mm; "+ if error_pairs:+ text += f"{len(error_pairs)} pair(s) above it are listed under errors; "+ text += f"{len(welds)} weld(s) under it are NOT the interpenetration defect."+ if deep:+ text += (f" {len(deep)} overlap(s) deeper than the ERROR line kept WARN because only a sliver of either "+ "surface is inside — a continuous member through a slab reads like this; the montage decides: "+ + "; ".join(f"{a}/{b} {float(dp):.1f} mm (through-ratio {float(t):.2f})" for a, b, dp, t in deep[:3])+ + ("" if len(deep) <= 3 else f"; … {len(deep) - 3} more") + ".")+ mid = [r for r in welds if float(r[3]) >= 0.5] # the gate names the ratio in its message from 0.5 up+ if mid:+ text += (" Measured, not a defect claim: "+ + "; ".join(f"{a}/{b} reaches {min(float(t), 1.0):.0%} of the way to its partner's mid-plane ({float(dp):.1f} mm)"+ for a, b, dp, t in mid[:3])+ + " — the far side is for the GEOMETRY montage.")+ return text+++def _grouped_warnings(rest: list[tuple[GateReport, GateFinding]], max_warns: int) -> list[str]:+ """One line per (gate, kind), ``max_warns`` findings each — 8 flat lines used to cut a+ 15-WARN round (p90) mid-list, dropping every contract WARN behind the connectivity ones."""+ if not rest:+ return []+ groups: dict[str, list[GateFinding]] = {}+ for g, f in rest:+ kind = f.data.get("kind") if isinstance(f.data.get("kind"), str) else ""+ groups.setdefault(f"{g.gate}/{kind}" if kind else g.gate, []).append(f)+ lines = [f"warnings ({len(rest)}), grouped by kind:"]+ for key, fs in groups.items():+ items = [(f"[{f.target}] " if f.target else "") + _clip(f.message, 160) for f in fs[:max_warns]]+ line = f"- {key} ×{len(fs)}: " + "; ".join(items)+ if len(fs) > max_warns:+ line += f"; … {len(fs) - max_warns} more"+ lines.append(line)+ return lines+++def _passed_paragraph(n_parts: int, n_contacts: int, gap_mm: float, overlaps: list) -> str:+ # Same voice as the legacy paragraph (2026-08-26 gas_street_lamp seam), now with the+ # measurement it rests on and the interpenetration half. The injunction against the+ # interpenetration tick is only made when the veto will honour it: every overlap under+ # VETO_PENETRATION_DEPTH_M (rubrics._rule_gates_clean). A deeper WARN — a stile through a+ # seat, a rod to a plate's mid-plane — is named as a measurement and the picture decides.+ head = (+ f"CONNECTIVITY PASSED: all {n_parts} parts are in measured contact ({n_contacts} contacts, gap <= {gap_mm:g} mm). "+ "A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any "+ "part as floating, hovering or disconnected, and do not mark the floating-part defect present. "+ )+ deep = [r for r in overlaps if float(r[2]) >= VETO_PENETRATION_DEPTH_M * 1000]+ if not deep:+ tail = (f"All {len(overlaps)} overlaps measured, none over {VETO_PENETRATION_DEPTH_M * 1000:g} mm: do NOT mark "+ "the interpenetration defect present either — those overlaps are welds. ")+ else:+ tail = (f"All {len(overlaps)} overlaps measured; {len(deep)} reach {VETO_PENETRATION_DEPTH_M * 1000:g} mm or more ("+ + "; ".join(f"{a}/{b} {float(dp):.1f} mm" for a, b, dp, _t in deep[:3])+ + ("" if len(deep) <= 3 else f"; … {len(deep) - 3} more")+ + "): mark interpenetration only if a part VISIBLY passes through another in a render; "+ "a hidden overlap is a weld. ")+ return head + tail + "If a joint looks visually ugly, say so under craftsmanship."++def previous_section(prev: Judgment | None, round_index: int) -> str:if prev is None:return ""diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.pyindex ab975d41..e4e5e871 100644--- a/harness/tests/judges/test_prompt_builder.py+++ b/harness/tests/judges/test_prompt_builder.py@@ -182,3 +182,186 @@ def test_a_passed_connectivity_gate_tells_the_judge_a_seam_is_not_daylight():GateFinding(gate="connectivity", severity=Severity.ERROR, target="Seat", message="part 'Seat' floats 12 mm above 'Leg'")])assert "CONNECTIVITY PASSED" not in gates_section([failed]), "a real floating part is still reported as one"assert "CONNECTIVITY PASSED" not in gates_section([GateReport(gate="contract", passed=True)]), "only the contact gate earns it"+++# ===================================================================== the contact ledger (2026-08-30)+#: the connectivity gate's ledger for a real p90 round — bench/out/codex_tiers_v3/cells/+#: cmp_hard_violin/harness_codex_gpt-5.6-sol r00 (16 parts, 26 contacts), re-run through+#: ``check_connectivity(planned_edges=planned_joins(plan, measurement))`` on 2026-08-30.+#: 23 overlaps, one open planned join (the tailpiece never reaches the endpin button).+LEDGER_VIOLIN = {"parts": ["Chinrest", "Strings", "Tailpiece", "Bridge", "TuningPegs_3", "TuningPegs_2", "TuningPegs_1", "TuningPegs_0", "PegboxAndScroll", "Nut", "Fingerboard", "NeckRoot", "EndpinButton", "TopPlate", "RibStructure", "BackPlate"], "contact_gap_mm": 2.0, "contacts": [["Chinrest", "TopPlate", 0.0], ["Chinrest", "RibStructure", 0.0], ["Strings", "Tailpiece", 0.0], ["Strings", "Bridge", 0.8], ["Strings", "TuningPegs_2", 0.0], ["Strings", "TuningPegs_1", 0.6], ["Strings", "PegboxAndScroll", 0.0], ["Strings", "Nut", 0.0], ["Strings", "NeckRoot", 0.0], ["Tailpiece", "TopPlate", 0.0], ["Bridge", "TopPlate", 0.0], ["TuningPegs_3", "PegboxAndScroll", 0.0], ["TuningPegs_2", "PegboxAndScroll", 0.0], ["TuningPegs_1", "PegboxAndScroll", 0.0], ["TuningPegs_0", "PegboxAndScroll", 0.0], ["PegboxAndScroll", "Nut", 0.0], ["PegboxAndScroll", "Fingerboard", 0.0], ["PegboxAndScroll", "NeckRoot", 0.0], ["Nut", "Fingerboard", 0.0], ["Nut", "NeckRoot", 0.0], ["Fingerboard", "NeckRoot", 0.0], ["NeckRoot", "TopPlate", 0.0], ["NeckRoot", "RibStructure", 0.0], ["EndpinButton", "RibStructure", 0.0], ["TopPlate", "RibStructure", 0.0], ["RibStructure", "BackPlate", 0.0]], "overlaps": [["Chinrest", "TopPlate", 1.8, 0.08], ["Strings", "Tailpiece", 3.1, 0.02], ["Strings", "TuningPegs_2", 2.4, 0.02], ["Strings", "PegboxAndScroll", 5.1, 0.0], ["Strings", "Nut", 0.4, 0.02], ["Strings", "NeckRoot", 1.5, 0.02], ["Tailpiece", "TopPlate", 1.7, 0.23], ["Bridge", "TopPlate", 1.5, 0.36], ["TuningPegs_3", "PegboxAndScroll", 6.6, 0.17], ["TuningPegs_2", "PegboxAndScroll", 9.0, 0.33], ["TuningPegs_1", "PegboxAndScroll", 8.3, 0.27], ["TuningPegs_0", "PegboxAndScroll", 3.9, 0.19], ["PegboxAndScroll", "Nut", 2.5, 0.11], ["PegboxAndScroll", "Fingerboard", 2.7, 0.1], ["PegboxAndScroll", "NeckRoot", 4.1, 0.2], ["Nut", "Fingerboard", 1.0, 0.23], ["Nut", "NeckRoot", 1.0, 0.07], ["Fingerboard", "NeckRoot", 8.4, 0.55], ["NeckRoot", "TopPlate", 1.0, 0.0], ["NeckRoot", "RibStructure", 0.1, 0.0], ["EndpinButton", "RibStructure", 3.0, 0.0], ["TopPlate", "RibStructure", 1.6, 0.05], ["RibStructure", "BackPlate", 2.5, 0.07]], "ground_gap_mm": {"Chinrest": 33.0, "Strings": 43.0, "Tailpiece": 37.0, "Bridge": 37.5, "TuningPegs_3": 55.0, "TuningPegs_2": 45.0, "TuningPegs_1": 45.0, "TuningPegs_0": 55.0, "PegboxAndScroll": 33.0, "Nut": 51.0, "Fingerboard": 44.2, "NeckRoot": 21.3, "EndpinButton": 14.0, "TopPlate": 31.0, "RibStructure": 3.0, "BackPlate": 0.0}, "planned": [["RibStructure", "BackPlate", 0.0, "contact"], ["TopPlate", "RibStructure", 0.0, "contact"], ["EndpinButton", "RibStructure", 0.0, "contact"], ["NeckRoot", "RibStructure", 0.0, "contact"], ["Fingerboard", "NeckRoot", 0.0, "contact"], ["Nut", "Fingerboard", 0.0, "contact"], ["PegboxAndScroll", "NeckRoot", 0.0, "contact"], ["TuningPegs_3", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_2", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_1", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_0", "PegboxAndScroll", 0.0, "contact"], ["Bridge", "TopPlate", 0.0, "contact"], ["Tailpiece", "EndpinButton", 24.9, "open"], ["Strings", "Bridge", 0.8, "contact"], ["Chinrest", "TopPlate", 0.0, "contact"]], "planned_unresolved": []}+++def _pen(a: str, b: str, depth_mm: float, through: float, severity: Severity = Severity.WARN) -> GateFinding:+ return GateFinding(gate="connectivity", severity=severity, target=a,+ message=f"'{a}' and '{b}' interpenetrate by ≈{depth_mm:.1f} mm (4% of surface samples inside, 30% where they meet)",+ data={"kind": "penetration", "other": b, "depth_m": depth_mm / 1000, "through_ratio": through})+++def _ledger_report(ledger: dict | None = None, *, passed: bool = True, extra: list[GateFinding] = ()) -> GateReport:+ d = ledger or LEDGER_VIOLIN+ findings = [_pen(a, b, depth, through) for a, b, depth, through in d["overlaps"] if depth > 2.0] + list(extra)+ findings.append(GateFinding(gate="connectivity", severity=Severity.INFO,+ message=f"all {len(d['parts'])} parts are connected ({len(d['contacts'])} contacts, gap ≤ 2 mm)"))+ findings.append(GateFinding(gate="connectivity", severity=Severity.INFO, target="",+ message=f"contact ledger: {len(d['parts'])} parts, {len(d['contacts'])} contacts, {len(d['overlaps'])} overlaps", data={"kind": "ledger", **d}))+ return GateReport(gate="connectivity", passed=passed, findings=findings)+++def _ledger_lines(text: str) -> str:+ return "\n".join(line for line in text.splitlines()+ if line.startswith(("MEASURED", "- ", "connectivity measured", "CONNECTIVITY PASSED")))+++CONTRACT_FAIL = GateReport(gate="contract", passed=False, findings=[+ GateFinding(gate="contract", severity=Severity.ERROR, target="Bridge", message="'Bridge' bbox extents off by 0.03 m"),+ GateFinding(gate="contract", severity=Severity.WARN, target="Nut", message="'Nut' centre off by 4 mm")])+++def test_ledger_turns_penetration_warn_prose_into_one_measured_line():+ """The audit (docs/EVAL.md §6): 110 of 237 interpenetration flags cited only WARNs the rubric+ says to ignore; same images with the gate text removed flipped 13 of 24. The eleven+ 'interpenetrate by' sentences of this round become one measured line, ERRORs stay."""+ from codeverse.judges.prompt_builder import gates_section++ rep = _ledger_report()+ assert sum("interpenetrate" in f.message for f in rep.findings) == 13 # one WARN sentence per overlap over the weld line+ text = gates_section([rep, CONTRACT_FAIL, GateReport(gate="budget", passed=True)])+ assert "interpenetrate" not in text+ assert ("connectivity measured 23 mating overlaps (deepest weld 9.0 mm TuningPegs_2/PegboxAndScroll, through-ratio 0.33); "+ "weld allowance 2 mm, ERROR line 10 mm; 23 weld(s) under it are NOT the interpenetration defect.") in text+ # ≥ 0.5 of the way through: named as a measurement, left to the geometry montage+ assert "Measured, not a defect claim: Fingerboard/NeckRoot reaches 55% of the way to its partner's mid-plane (8.4 mm)" in text+ assert "errors (1):" in text and "- contract [Bridge]: 'Bridge' bbox extents off by 0.03 m" in text+ assert "warnings (1), grouped by kind:" in text and "- contract ×1: [Nut] 'Nut' centre off by 4 mm" in text+ assert "MEASURED STRUCTURE (connectivity gate, exact mesh-to-mesh distances): 16 parts, 26 contacts (gap ≤ 2 mm), 0 floating, 23 overlapping pairs." in text+ assert "PLANNED JOINS (the plan's attach_to pairs, measured; contact = gap ≤ 2 mm): 14/15 in contact. OPEN: Tailpiece→EndpinButton 24.9 mm." in text+ assert "Strings→Bridge 0.8," in text and "TuningPegs_3→PegboxAndScroll," in text+ # a planned contact is not repeated in the adjacency; the unplanned ones are+ assert "- other contacts, not in the plan (gap in mm where not 0): Chinrest: RibStructure · Strings: Tailpiece, TuningPegs_2, TuningPegs_1 0.6," in text+ assert "TuningPegs_3: PegboxAndScroll" not in text+ assert "- ground: lowest point 0.0 mm (BackPlate) — floor contact; parts within 10 mm of the floor: RibStructure 3.0 mm" in text+ assert ("CONNECTIVITY PASSED: all 16 parts are in measured contact (26 contacts, gap <= 2 mm)." in text+ and "Do NOT report any part as floating" in text)+ # five overlaps reach 5 mm (the veto's line): no injunction against the interpenetration tick,+ # the measurement is named and the picture decides — the prompt and rubrics._rule_gates_clean agree+ assert "All 23 overlaps measured; 5 reach 5 mm or more (" in text+ assert "mark interpenetration only if a part VISIBLY passes through another in a render" in text+ assert "do NOT mark the interpenetration defect" not in text+ assert text.index("errors (1)") < text.index("MEASURED STRUCTURE") < text.index("connectivity measured") < text.index("warnings (1)")+++def test_ledger_block_stays_near_500_tokens_on_the_p90_round():+ """chars/4 is this module's own token convention (``TEXT_BUDGET_CHARS = 24_000 ≈ 6k``)."""+ from codeverse.judges.prompt_builder import LEDGER_MAX_CONTACTS, LEDGER_MAX_JOINS, gates_section++ text = gates_section([_ledger_report(), GateReport(gate="contract", passed=True)])+ assert len(_ledger_lines(text)) / 4 <= 500+ # the clips: 40 unplanned contacts and 30 planned joins are cut with a count, not listed to the end+ big = dict(LEDGER_VIOLIN)+ big["parts"] = [f"Part{i}" for i in range(41)]+ big["contacts"] = [[f"Part{i}", f"Part{i + 1}", 0.0] for i in range(40)]+ big["planned"] = [[f"Part{i}", f"Part{i + 1}", 0.0, "contact"] for i in range(30)]+ big["ground_gap_mm"] = {f"Part{i}": 0.0 for i in range(41)}+ text = gates_section([_ledger_report(big)])+ assert f"… {30 - LEDGER_MAX_JOINS} more." in text+ assert "Part30: Part31" in text and "Part39: Part40" in text and " more\n" not in text # the 10 unplanned contacts fit+ assert len(_ledger_lines(text)) / 4 <= 500+ big["planned"] = []+ text = gates_section([_ledger_report(big)])+ assert "- contacts (gap in mm where not 0): Part0: Part1 · " in text and f"· … {40 - LEDGER_MAX_CONTACTS} more" in text+ assert len(_ledger_lines(text)) / 4 <= 500+++def test_ledger_error_pairs_are_errors_not_welds_and_a_failed_gate_earns_no_passed_paragraph():+ from codeverse.judges.prompt_builder import gates_section++ d = {"parts": ["Arm", "Post", "Seat", "Leg"], "contact_gap_mm": 2.0, "contacts": [["Arm", "Post", 0.0], ["Post", "Leg", 0.0]],+ "overlaps": [["Arm", "Post", 14.0, 1.2], ["Post", "Leg", 1.1, 0.05], ["Seat", "Leg", 0.3, 0.01]],+ "ground_gap_mm": {"Arm": 400.0, "Post": 0.0, "Seat": 412.0, "Leg": 0.0}, "planned": [["Seat", "Leg", 12.0, "open"]], "planned_unresolved": ["Cushion"]}+ floating = GateFinding(gate="connectivity", severity=Severity.ERROR, target="Seat",+ message="part 'Seat' is floating: nearest supported part is 'Leg' at 12.0 mm", data={"kind": "floating", "nearest": "Leg", "gap_m": 0.012})+ rep = _ledger_report(d, passed=False, extra=[_pen("Arm", "Post", 14.0, 1.2, Severity.ERROR), floating])+ text = gates_section([rep])+ assert "errors (2):" in text and "- connectivity [Arm]: 'Arm' and 'Post' interpenetrate by ≈14.0 mm" in text and "[Seat]: part 'Seat' is floating" in text+ assert "4 parts, 2 contacts (gap ≤ 2 mm), 1 floating, 3 overlapping pairs." in text+ assert "1 pair(s) above it are listed under errors; 2 weld(s) under it are NOT the interpenetration defect." in text+ assert "(deepest weld 1.1 mm Post/Leg, through-ratio 0.05)" in text # the ERROR pair is not the deepest weld+ assert "OPEN: Seat→Leg 12.0 mm." in text and "- plan parts not found in the mesh: Cushion" in text+ assert "CONNECTIVITY PASSED" not in text and "no errors or warnings" not in text+++def test_ledger_ground_line_and_single_part_and_grouped_warnings():+ from codeverse.judges.prompt_builder import gates_section++ hover = dict(LEDGER_VIOLIN, parts=["Top", "Leg_0", "Leg_1", "Leg_2"], contacts=[], overlaps=[], planned=[],+ ground_gap_mm={"Top": 700.0, "Leg_0": 3.1, "Leg_1": 3.1, "Leg_2": 0.3})+ text = gates_section([_ledger_report(hover)])+ # the corpus verdict wrote "legs end above the ground plane" on 0.3 mm: the number is printed, the far parts are not+ assert "- ground: lowest point 0.3 mm (Leg_2) — floor contact; parts within 10 mm of the floor: Leg_0 3.1 mm, Leg_1 3.1 mm" in text+ assert "Top 700" not in text+ hover["ground_gap_mm"] = {"Top": 700.0, "Leg_0": 3.1, "Leg_1": 3.1, "Leg_2": 3.1}+ assert "lowest point 3.1 mm above the floor (Leg_0) — nothing touches it; parts within 10 mm of the floor: Leg_0 3.1 mm, Leg_1 3.1 mm, Leg_2 3.1 mm" in gates_section([_ledger_report(hover)])+ hover["ground_gap_mm"] = {"Top": 700.0, "Leg_0": -2.0, "Leg_1": 0.2, "Leg_2": 0.2}+ assert "lowest point 2.0 mm below the floor (Leg_0); every other near-floor part is within 0.5 mm of the floor" in gates_section([_ledger_report(hover)])+ # one part has nothing to be connected to: no CONNECTIVITY PASSED paragraph+ single = dict(LEDGER_VIOLIN, parts=["Body"], contacts=[], overlaps=[], planned=[], ground_gap_mm={"Body": 0.0})+ text = gates_section([_ledger_report(single)])+ assert "1 part, 0 contacts" in text and "CONNECTIVITY PASSED" not in text+ # the remaining WARNs group by (gate, kind) instead of cutting the list at 8+ islands = [GateFinding(gate="connectivity", severity=Severity.WARN, target=f"P{i}", message=f"part 'P{i}' contains 1 tiny disconnected island(s)",+ data={"islands": 2, "tiny_islands": 1}) for i in range(2)]+ contract = GateReport(gate="contract", passed=True, findings=[+ GateFinding(gate="contract", severity=Severity.WARN, target=f"C{i}", message=f"'C{i}' centre off by {i} mm", data={"kind": "center"}) for i in range(10)])+ text = gates_section([_ledger_report(extra=islands), contract])+ assert "warnings (12), grouped by kind:" in text+ assert "- connectivity ×2: [P0] part 'P0' contains 1 tiny disconnected island(s); [P1] part 'P1'" in text+ assert "- contract/center ×10: [C0] 'C0' centre off by 0 mm;" in text and "[C7] 'C7' centre off by 7 mm; … 2 more" in text+ assert "[C8]" not in text+++def test_gates_section_without_a_ledger_is_byte_identical_to_the_pre_ledger_text():+ """A recorded round has no ledger finding: ``3dcv judge <old-slug>`` must build the exact text+ the stored verdict saw. Expected strings were captured from ``gates_section`` at 4ddde32,+ before the ledger path existed (scratch capture_baseline.py, 2026-08-30)."""+ from codeverse.judges.prompt_builder import gates_section++ C = "connectivity"+ def F(sev, msg, target=None, gate=C, data=None):+ return GateFinding(gate=gate, severity=sev, target=target, message=msg, data=data or {})+ assert gates_section([]) == 'GATE FINDINGS: (no gates run)'+ passed = [GateReport(gate=C, passed=True, findings=[F(Severity.INFO, "all 9 parts are connected (12 contacts, gap ≤ 2 mm)")])]+ assert gates_section(passed) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=pass\nno errors or warnings — parts are connected and contracts hold.\nCONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any part as floating, hovering or disconnected, and do not mark the floating-part defect present; if a joint looks visually ugly, say so under craftsmanship.'+ mixed = [+ GateReport(gate=C, passed=True, findings=[+ F(Severity.WARN, "'Strings' and 'Tailpiece' interpenetrate by ≈2.5 mm (2% of surface samples inside, 30% where they meet)", "Strings",+ data={"kind": "penetration", "other": "Tailpiece", "depth_m": 0.0025, "through_ratio": 0.1}),+ F(Severity.WARN, "part 'Seat' contains 2 tiny disconnected island(s) (< 5% of the part size) — stray geometry", "Seat", data={"islands": 3, "tiny_islands": 2}),+ F(Severity.INFO, "all 16 parts are connected (26 contacts, gap ≤ 2 mm)")]),+ GateReport(gate="contract", passed=False, findings=[F(Severity.ERROR, "'Bridge' bbox extents off by 0.03 m", "Bridge", gate="contract"),+ F(Severity.WARN, "'Nut' centre off by 4 mm", "Nut", gate="contract")]),+ GateReport(gate="budget", passed=True)]+ assert gates_section(mixed) == "GATE FINDINGS (deterministic; treat as facts): connectivity=pass, contract=FAIL, budget=pass\nerrors (1):\n- contract [Bridge]: 'Bridge' bbox extents off by 0.03 m\nwarnings (3):\n- connectivity [Strings]: 'Strings' and 'Tailpiece' interpenetrate by ≈2.5 mm (2% of surface samples inside, 30% where they meet)\n- connectivity [Seat]: part 'Seat' contains 2 tiny disconnected island(s) (< 5% of the part size) — stray geometry\n- contract [Nut]: 'Nut' centre off by 4 mm\nCONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any part as floating, hovering or disconnected, and do not mark the floating-part defect present; if a joint looks visually ugly, say so under craftsmanship."+ failed = [GateReport(gate=C, passed=False, findings=[+ F(Severity.ERROR, "part 'Seat' is floating: nearest supported part is 'Leg' at 12.0 mm", "Seat", data={"kind": "floating", "nearest": "Leg", "gap_m": 0.012}),+ F(Severity.ERROR, "'Arm' and 'Post' interpenetrate by ≈14.0 mm (30% of surface samples inside, 80% where they meet) — 'Arm' reaches 120% of the way through 'Post' (10 mm)", "Arm",+ data={"kind": "penetration", "other": "Post", "depth_m": 0.014, "through_ratio": 1.2})])]+ assert gates_section(failed) == "GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (2):\n- connectivity [Seat]: part 'Seat' is floating: nearest supported part is 'Leg' at 12.0 mm\n- connectivity [Arm]: 'Arm' and 'Post' interpenetrate by ≈14.0 mm (30% of surface samples inside, 80% where they meet) — 'Arm' reaches 120% of the way through 'Post' (10 mm)"+ many = [GateReport(gate=C, passed=False, findings=[F(Severity.ERROR, f"error {i}", f"P{i}") for i in range(14)] + [F(Severity.WARN, f"warn {i}", f"W{i}") for i in range(11)])]+ assert gates_section(many) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- connectivity [P3]: error 3\n- connectivity [P4]: error 4\n- connectivity [P5]: error 5\n- connectivity [P6]: error 6\n- connectivity [P7]: error 7\n- connectivity [P8]: error 8\n- connectivity [P9]: error 9\n- connectivity [P10]: error 10\n- connectivity [P11]: error 11\n- … 2 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- connectivity [W2]: warn 2\n- connectivity [W3]: warn 3\n- connectivity [W4]: warn 4\n- connectivity [W5]: warn 5\n- connectivity [W6]: warn 6\n- connectivity [W7]: warn 7\n- … 3 more warnings'+ assert gates_section(many, max_errors=3, max_warns=2) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- … 11 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- … 9 more warnings'+++def test_judge_prompt_hash_does_not_cover_the_per_run_gate_text():+ """The ledger block rides on v1's hash: ``judge_prompt_hash`` covers the system prompt, the+ rig rules and the wire schema only, so a paired re-judge, not the hash, is what measures it."""+ from codeverse.judges.prompt_builder import judge_prompt_hash++ h = judge_prompt_hash(R)+ import codeverse.judges.prompt_builder as pb+ original = pb.gates_section+ try:+ pb.gates_section = lambda gates, **kw: "NOT THE SAME TEXT"+ assert judge_prompt_hash(R) == h+ finally:+ pb.gates_section = original