Loading files
"""Stage 3a: holding the converted board to the fab's silkscreen floors.
This is a platform fix, not a check: it runs on every board, so it has to be
exactly right and it has to be idempotent. The one thing worse than silkscreen
that will not print is a rewriter that corrupts the board — an earlier draft
matched across a `(stroke (width N))` wrapper, ate its closing paren, and
produced a file kicad-cli refused to load at all. That case is pinned below.
"""
from __future__ import annotations
import re
from pathlib import Path
from circuitpy.fab import get_profile
from circuitpy.kicad_normalize import _balanced_spans, normalize_for_fab
PROFILE = get_profile("jlcpcb")
def _write(tmp_path: Path, body: str) -> Path:
path = tmp_path / "board.kicad_pcb"
path.write_text(f'(kicad_pcb\n (setup\n )\n{body}\n)\n', encoding="utf-8")
return path
SMALL_TEXT = """ (footprint "R_0402"
(fp_text
reference
"R1"
(at 0 -1.22 0)
(layer F.SilkS)
(effects
(font
(size 0.26666666666666666 0.26666666666666666)
)
)
)
)"""
THIN_MODERN_STROKE = """ (fp_line
(start -4.4 1.25)
(end -4.4 -0.61)
(stroke
(width 0.1)
(type default)
)
(layer F.SilkS)
)"""
THIN_LEGACY_STROKE = """ (gr_line
(start 0 0)
(end 1 0)
(width 0.05)
(layer "F.Silkscreen")
)"""
COPPER_LINE = """ (gr_line
(start 0 0)
(end 1 0)
(width 0.05)
(layer "F.Cu")
)"""
def _balanced(text: str) -> bool:
depth = 0
for char in text:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
if depth < 0:
return False
return depth == 0
def test_text_below_the_floor_is_raised_to_it(tmp_path):
path = _write(tmp_path, SMALL_TEXT)
result = normalize_for_fab(path, PROFILE)
assert result.text_resized == 1
text = path.read_text()
assert "(size 1 1)" in text
assert result.smallest_text_mm is not None
assert round(result.smallest_text_mm, 3) == 0.267
def test_text_with_no_thickness_gets_one_at_the_floor(tmp_path):
"""KiCad derives thickness from size when it is absent, and lands at
0.033mm — a fifth of what JLCPCB will print."""
path = _write(tmp_path, SMALL_TEXT)
result = normalize_for_fab(path, PROFILE)
assert result.text_thickened == 1
assert "(thickness 0.15)" in path.read_text()
def test_a_modern_stroke_wrapper_survives_being_widened(tmp_path):
"""The regression: rewriting across `(stroke (width N))` ate the closing
paren and produced a board kicad-cli could not load."""
path = _write(tmp_path, THIN_MODERN_STROKE)
result = normalize_for_fab(path, PROFILE)
text = path.read_text()
assert result.strokes_widened == 1
assert "(width 0.15)" in text
assert "(type default)" in text
assert _balanced(text), "the rewritten s-expression must still balance"
def test_a_legacy_bare_width_is_widened_too(tmp_path):
path = _write(tmp_path, THIN_LEGACY_STROKE)
assert normalize_for_fab(path, PROFILE).strokes_widened == 1
assert "(width 0.15)" in path.read_text()
def test_nothing_outside_the_silkscreen_layers_is_touched(tmp_path):
path = _write(tmp_path, COPPER_LINE)
before = path.read_text()
result = normalize_for_fab(path, PROFILE)
assert not result.changed
assert path.read_text() == before
def test_it_is_idempotent(tmp_path):
path = _write(tmp_path, SMALL_TEXT + "\n" + THIN_MODERN_STROKE)
first = normalize_for_fab(path, PROFILE)
after_first = path.read_text()
second = normalize_for_fab(path, PROFILE)
assert first.changed and not second.changed
assert path.read_text() == after_first
def test_text_already_at_the_floor_is_left_alone(tmp_path):
body = SMALL_TEXT.replace(
"(size 0.26666666666666666 0.26666666666666666)", "(size 1.2 1.2)"
).replace("(font", "(font\n (thickness 0.2)")
path = _write(tmp_path, body)
result = normalize_for_fab(path, PROFILE)
assert result.text_resized == 0
assert result.text_thickened == 0
def test_the_solder_mask_setting_is_not_written(tmp_path):
"""Measured and rejected: `solder_mask_min_width` removes no web. It turns
174 flashed apertures into 223 filled regions, so the same geometry then
reads as 92 sub-0.2mm gaps instead of 10, and the gerber check runs eight
times slower. A change that alters the representation and not the board is
a placebo."""
path = _write(tmp_path, SMALL_TEXT)
normalize_for_fab(path, PROFILE)
assert "solder_mask_min_width" not in path.read_text()
def test_a_missing_file_is_a_note_not_an_exception(tmp_path):
result = normalize_for_fab(tmp_path / "nope.kicad_pcb", PROFILE)
assert not result.changed
assert result.notes and "could not read" in result.notes[0]
def test_a_corrupt_board_is_left_exactly_as_it_was(tmp_path):
path = tmp_path / "board.kicad_pcb"
path.write_text("(kicad_pcb (fp_text (layer F.SilkS) (effects (font (size",
encoding="utf-8")
before = path.read_text()
normalize_for_fab(path, PROFILE)
assert path.read_text() == before
# ---------------------------------------------------------------------------
# Route dead-end vias: a B.Cu net that stops under a top-only F.Cu pad.
# ---------------------------------------------------------------------------
DEAD_END_BOARD = """ (footprint "test"
(property "Reference" "U1")
(at 100 100 0)
(pad "1" smd rect
(at 2 3 0)
(size 0.2 0.85)
(layers F.Cu F.Paste F.Mask)
(net 1 "V5")
)
(pad "2" smd rect
(at 2.6 3 0)
(size 0.2 0.85)
(layers F.Cu F.Paste F.Mask)
(net 2 "GND")
)
)
(segment
(start 100 102)
(end 102 103)
(width 0.15)
(layer B.Cu)
(net 1)
)"""
def test_a_b_cu_dead_end_under_a_top_only_pad_gets_a_via(tmp_path):
"""The router runs a net on B.Cu, stops it under an F.Cu-only SMD pad and
forgets the final via; KiCad then reports an unconnected_items DRC error.
The normalizer bridges the dead-end with a via touching both the pad and
the track, so the two connect."""
path = _write(tmp_path, DEAD_END_BOARD)
result = normalize_for_fab(path, PROFILE)
assert result.vias_bridged == 1
text = path.read_text()
assert _balanced(text), "the rewritten s-expression must still balance"
assert "(layers F.Cu B.Cu)" in text
assert "(net 1)" in text
# The via must sit at the dead-end inside the pad.
assert "(at 102 103)" in text
def test_the_repair_records_the_via_it_inserted(tmp_path):
"""The via is added **after** `circuit.json` is written, so every DFM check
downstream reads a design that does not contain it.
Measured on the corpus 2026-08-25: every `gerber_drill_extra` finding is one
of these vias — 32 of 32 boards, the counts match exactly — and on
weather-badge-28 the repair took the smallest candidate, 0.15mm, against
114 designed vias all at 0.3mm, with nothing reporting it. Recording the
geometry is what lets the caller grade it.
"""
path = _write(tmp_path, DEAD_END_BOARD)
result = normalize_for_fab(path, PROFILE)
assert result.vias_bridged == 1
assert len(result.via_geometry) == 1
pad, drill = result.via_geometry[0]
assert (pad, drill) in ((0.6, 0.3), (0.4, 0.2), (0.3, 0.15)), result.via_geometry
# and the summary says it out loud rather than only counting
assert f"{pad:g}/{drill:g}mm" in result.summary(), result.summary()
def test_a_board_the_repair_did_not_touch_records_no_geometry(tmp_path):
body = DEAD_END_BOARD.replace("(end 102 103)", "(end 104 105)")
path = _write(tmp_path, body)
result = normalize_for_fab(path, PROFILE)
assert result.vias_bridged == 0
assert result.via_geometry == []
def test_a_bridged_dead_end_is_not_bridged_twice(tmp_path):
path = _write(tmp_path, DEAD_END_BOARD)
first = normalize_for_fab(path, PROFILE)
after_first = path.read_text()
second = normalize_for_fab(path, PROFILE)
assert first.vias_bridged == 1
assert second.vias_bridged == 0
assert path.read_text() == after_first
def test_a_b_cu_track_ending_in_open_space_is_left_alone(tmp_path):
body = DEAD_END_BOARD.replace("(end 102 103)", "(end 104 105)")
path = _write(tmp_path, body)
result = normalize_for_fab(path, PROFILE)
assert result.vias_bridged == 0
assert "F.Cu B.Cu" not in path.read_text().replace("(layers F.Cu F.Paste F.Mask)", "")
def _no_room_board(tmp_path):
"""Two same-row pads whose neighbours leave 0.2mm gaps: no round via clears
both, so the dead-end must NOT be bridged with a shorting via."""
body = DEAD_END_BOARD.replace(
' (at 2.6 3 0)',
' (at 2.1 3 0)',
)
return _write(tmp_path, body)
def test_a_dead_end_with_no_room_for_a_via_is_skipped_and_reported(tmp_path):
result = normalize_for_fab(_no_room_board(tmp_path), PROFILE)
assert result.vias_bridged == 0
assert result.declined
assert "left as the router laid them" in result.declined[0]
def test_declining_to_place_a_via_is_not_a_failed_step(tmp_path):
"""The distinction this list exists for. `notes` means something the board
was entitled to did not happen and part of it is unexamined. This pass ran,
read every pad, trace, via and pour, and chose not to act — the safer of
the two options, and the one #11 was written in blood for.
Reported as a failure it put "a check could not finish" on weather-badge-12
and -13, both `fab.ready` with zero errors, and the app marked it blocking
while the pipeline did not. One verdict, two surfaces, opposite answers."""
result = normalize_for_fab(_no_room_board(tmp_path), PROFILE)
assert result.notes == []
def test_a_step_that_genuinely_could_not_run_still_lands_in_notes(tmp_path):
"""The other side of the split has to keep working, or this trades a false
alarm for a silence."""
missing = tmp_path / "nope.kicad_pcb"
result = normalize_for_fab(missing, PROFILE)
assert any("could not read" in n for n in result.notes)
assert result.declined == []
def test_the_reason_names_the_net_and_says_who_judges_it(tmp_path):
"""A declined repair still has to be actionable: which net, why nothing
was placed, and where the condition is still being measured."""
detail = normalize_for_fab(_no_room_board(tmp_path), PROFILE).declined[0]
assert "net" in detail
assert "clears every pad" in detail
assert "DRC" in detail
_ZONE = """ (zone
(net 2)
(net_name {net})
(layer {layer})
(uuid {uuid})
(hatch edge 0.5)
(connect_pads yes (clearance 0.15))
(min_thickness 0.25)
(fill yes (thermal_gap 0.5) (thermal_bridge_width 0.5))
(polygon (pts {pts}))
{fill} )
"""
def _zone(uuid, pts, *, net="GND", layer="F.Cu", fill=None):
xy = lambda ring: " ".join(f"(xy {x} {y})" for x, y in ring) # noqa: E731
filled = f" (filled_polygon (layer {layer}) (pts {xy(fill)}))\n" if fill else ""
return _ZONE.format(uuid=uuid, net=net, layer=layer, pts=xy(pts), fill=filled)
def test_same_net_islands_fold_into_their_plane(tmp_path):
# desk-cube-astra-run7, 2026-09-11: the converter wrote the top pour as
# one plane and 38 islands, each its own zone with its own fill, and
# `--refill-zones` exits -11 on that file while the same board with only
# the planes refills. The islands' outlines join the plane; their fills go.
sq = lambda x, y, s: [(x, y), (x + s, y), (x + s, y + s), (x, y + s)] # noqa: E731
body = (
"(kicad_pcb (version 20240108) (generator test)\n"
+ _zone("island1", sq(10, 10, 4), fill=sq(10.2, 10.2, 3.6))
+ _zone("plane", sq(0, 0, 50), fill=sq(0.2, 0.2, 49.6))
+ _zone("island2", sq(20, 20, 6), fill=sq(20.2, 20.2, 5.6))
+ _zone("bottom", sq(0, 0, 50), layer="B.Cu", fill=sq(0.2, 0.2, 49.6))
+ _zone("pocket", sq(30, 30, 5), net="V3_3", fill=sq(30.2, 30.2, 4.6))
+ ")\n"
)
pcb = _write(tmp_path, body)
result = normalize_for_fab(pcb, PROFILE)
assert result.islands_merged == 2
assert result.island_polygons_kept == 2
assert "2 pour island(s) folded" in result.summary()
text = pcb.read_text()
zones = [text[a:b] for a, b in _balanced_spans(text, "(zone")]
assert len(zones) == 3
plane = next(z for z in zones if "(uuid plane)" in z)
assert "(uuid island1)" not in text and "(uuid island2)" not in text
# the plane keeps its own outline and gains both islands' outlines …
assert plane.count("(polygon") == 3
assert "(xy 10 10)" in plane and "(xy 20 20)" in plane
# … but no island fill: KiCad's refill decides where copper goes
assert plane.count("(filled_polygon") == 1
assert "(xy 10.2 10.2)" not in plane
# other layers and other nets are their own zones, untouched
assert any("(uuid bottom)" in z for z in zones)
assert any("(uuid pocket)" in z for z in zones)
# the three that remain nest (V3_3 inside GND on F.Cu): still prioritised
assert result.zones_prioritised == 3
# idempotent
again = normalize_for_fab(pcb, PROFILE)
assert again.islands_merged == 0 and again.zones_prioritised == 0
assert pcb.read_text() == text
def test_a_zone_with_no_layer_or_net_name_is_never_folded(tmp_path):
body = (
"(kicad_pcb (version 20240108) (generator test)\n"
+ _zone("a", [(0, 0), (50, 0), (50, 50), (0, 50)])
+ _zone("b", [(10, 10), (14, 10), (14, 14), (10, 14)]).replace("(layer F.Cu)", "(layers F.Cu B.Cu)")
+ _zone("c", [(20, 20), (26, 20), (26, 26), (20, 26)]).replace("(net_name GND)", '(net_name "")')
+ ")\n"
)
pcb = _write(tmp_path, body)
result = normalize_for_fab(pcb, PROFILE)
assert result.islands_merged == 0
assert len(_balanced_spans(pcb.read_text(), "(zone")) == 3
def test_nested_zones_of_different_nets_get_distinct_priorities(tmp_path):
# desk-cube-astra-run7, 2026-09-11: zones nested on one layer with no
# priority — kicad-cli drc exit -11 together. Same-net islands now fold
# (above); what still nests is one net's pocket inside another's plane.
body = (
"(kicad_pcb (version 20240108) (generator test)\n"
+ _zone("a", [(0, 0), (50, 0), (50, 50), (0, 50)])
+ _zone("b", [(10, 10), (14, 10), (14, 14), (10, 14)], net="V3_3")
+ _zone("c", [(20, 20), (26, 20), (26, 26), (20, 26)], net="V5")
+ ")\n"
)
pcb = _write(tmp_path, body)
result = normalize_for_fab(pcb, PROFILE)
assert result.zones_prioritised == 3
assert "distinct priority" in result.summary()
text = pcb.read_text()
prios = re.findall(r"\(priority (\d+)\)", text)
assert sorted(prios) == ["0", "1", "2"], prios
# largest outline ranks first, then by area
assert text.index("(priority 0)") < text.index("(priority 2)")
# idempotent
again = normalize_for_fab(pcb, PROFILE)
assert again.zones_prioritised == 0
assert pcb.read_text() == text
def test_a_lone_zone_is_not_given_a_priority(tmp_path):
body = "(kicad_pcb (version 20240108) (generator test)\n" + _zone("a", [(0, 0), (5, 0), (5, 5), (0, 5)]) + ")\n"
pcb = _write(tmp_path, body)
result = normalize_for_fab(pcb, PROFILE)
assert result.zones_prioritised == 0
assert "(priority" not in pcb.read_text()
e4d010b16This file is pinned to the selected release. Download the original to open it in your design tool.