diff --git a/docs/assets/kicad-zcode-composite-long-run/01-fresh-chat-first-turn-pass.png b/docs/assets/kicad-zcode-composite-long-run/01-fresh-chat-first-turn-pass.png new file mode 100644 index 00000000..8427a793 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/01-fresh-chat-first-turn-pass.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/02-plugin-0.12.3-active.png b/docs/assets/kicad-zcode-composite-long-run/02-plugin-0.12.3-active.png new file mode 100644 index 00000000..e32bb9c1 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/02-plugin-0.12.3-active.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/03-composite-task-start.png b/docs/assets/kicad-zcode-composite-long-run/03-composite-task-start.png new file mode 100644 index 00000000..ea673d30 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/03-composite-task-start.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/04-capabilities-first-tool.png b/docs/assets/kicad-zcode-composite-long-run/04-capabilities-first-tool.png new file mode 100644 index 00000000..290f0ea9 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/04-capabilities-first-tool.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/05-three-examples-and-part-info.png b/docs/assets/kicad-zcode-composite-long-run/05-three-examples-and-part-info.png new file mode 100644 index 00000000..85f42b54 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/05-three-examples-and-part-info.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/06-spec-check-pass-and-build.png b/docs/assets/kicad-zcode-composite-long-run/06-spec-check-pass-and-build.png new file mode 100644 index 00000000..1aeb4333 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/06-spec-check-pass-and-build.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/07-drc-pass-render-checks-glb.png b/docs/assets/kicad-zcode-composite-long-run/07-drc-pass-render-checks-glb.png new file mode 100644 index 00000000..507211ec Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/07-drc-pass-render-checks-glb.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/08-board-panel-live-link.png b/docs/assets/kicad-zcode-composite-long-run/08-board-panel-live-link.png new file mode 100644 index 00000000..f2c8f4aa Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/08-board-panel-live-link.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/09-live-move-signature-changed.png b/docs/assets/kicad-zcode-composite-long-run/09-live-move-signature-changed.png new file mode 100644 index 00000000..0654a0a7 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/09-live-move-signature-changed.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/10-final-pass-and-ipc-restored.png b/docs/assets/kicad-zcode-composite-long-run/10-final-pass-and-ipc-restored.png new file mode 100644 index 00000000..f9c9a6ec Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/10-final-pass-and-ipc-restored.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/11-pcb-report.json b/docs/assets/kicad-zcode-composite-long-run/11-pcb-report.json new file mode 100644 index 00000000..fdb1d778 --- /dev/null +++ b/docs/assets/kicad-zcode-composite-long-run/11-pcb-report.json @@ -0,0 +1,1173 @@ +{ + "type": "pcb_report", + "title": "power_clock_shift_led_controller", + "generated_at": "2026-11-03T16:05:47+00:00", + "ready_to_order": true, + "blocking_problems": [], + "board": { + "width_mm": 70.0, + "height_mm": 48.0, + "layers": 2, + "corner_radius_mm": 1.5, + "mounting_holes": 4 + }, + "design_rules": { + "signal_width_mm": 0.25, + "power_width_mm": 0.5, + "clearance_mm": 0.2, + "via_diameter_mm": 0.6, + "via_drill_mm": 0.3, + "edge_clearance_mm": 0.3 + }, + "checks": { + "spec": { + "ok": true, + "n_errors": 0, + "n_warnings": 0, + "issues": [] + }, + "drc": { + "passed": true, + "errors": 0, + "warnings": 4, + "unconnected": 0, + "by_type": { + "silk_over_copper": 4 + }, + "violations": [ + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of H1", + "x_mm": 3.0, + "y_mm": 3.0 + }, + { + "what": "NPTH pad of H1", + "x_mm": 3.0, + "y_mm": 3.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of H2", + "x_mm": 67.0, + "y_mm": 3.0 + }, + { + "what": "NPTH pad of H2", + "x_mm": 67.0, + "y_mm": 3.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of H4", + "x_mm": 67.0, + "y_mm": 45.0 + }, + { + "what": "NPTH pad of H4", + "x_mm": 67.0, + "y_mm": 45.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of H3", + "x_mm": 3.0, + "y_mm": 45.0 + }, + { + "what": "NPTH pad of H3", + "x_mm": 3.0, + "y_mm": 45.0 + } + ] + } + ], + "unconnected_items": [], + "kicad_version": "10.0.6" + }, + "routing": { + "complete": true, + "unrouted": [], + "warnings": [], + "stats": { + "passes": 1, + "nets_routed": 26, + "vias": 49, + "segments": 269, + "unrouted_connections": 0, + "length_mm": 875.51, + "seconds": 7.62, + "grid_mm": 0.1, + "expansions": 1344313, + "searches": 65 + }, + "tracks": 269, + "vias": 49 + } + }, + "pin_table": [ + { + "ref": "C1", + "pin": "1", + "name": "~", + "type": "passive", + "net": "VIN" + }, + { + "ref": "C1", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "C2", + "pin": "1", + "name": "~", + "type": "passive", + "net": "+3V3" + }, + { + "ref": "C2", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "C3", + "pin": "1", + "name": "~", + "type": "passive", + "net": "THR" + }, + { + "ref": "C3", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "C4", + "pin": "1", + "name": "~", + "type": "passive", + "net": "VIN" + }, + { + "ref": "C4", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "C5", + "pin": "1", + "name": "~", + "type": "passive", + "net": "CTRL" + }, + { + "ref": "C5", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "C6", + "pin": "1", + "name": "~", + "type": "passive", + "net": "+3V3" + }, + { + "ref": "C6", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "D1", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D1", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L1" + }, + { + "ref": "D2", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D2", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L2" + }, + { + "ref": "D3", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D3", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L3" + }, + { + "ref": "D4", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D4", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L4" + }, + { + "ref": "D5", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D5", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L5" + }, + { + "ref": "D6", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D6", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L6" + }, + { + "ref": "D7", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D7", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L7" + }, + { + "ref": "D8", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D8", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L8" + }, + { + "ref": "J1", + "pin": "1", + "name": "Pin_1", + "type": "passive", + "net": "VIN" + }, + { + "ref": "J1", + "pin": "2", + "name": "Pin_2", + "type": "passive", + "net": "GND" + }, + { + "ref": "J2", + "pin": "1", + "name": "Pin_1", + "type": "passive", + "net": "+3V3" + }, + { + "ref": "J2", + "pin": "2", + "name": "Pin_2", + "type": "passive", + "net": "GND" + }, + { + "ref": "J3", + "pin": "1", + "name": "Pin_1", + "type": "passive", + "net": "SER" + }, + { + "ref": "J3", + "pin": "2", + "name": "Pin_2", + "type": "passive", + "net": "RCLK" + }, + { + "ref": "J3", + "pin": "3", + "name": "Pin_3", + "type": "passive", + "net": "SRCLR" + }, + { + "ref": "J3", + "pin": "4", + "name": "Pin_4", + "type": "passive", + "net": "QHP" + }, + { + "ref": "J4", + "pin": "1", + "name": "Pin_1", + "type": "passive", + "net": "+3V3" + }, + { + "ref": "J4", + "pin": "2", + "name": "Pin_2", + "type": "passive", + "net": "QA" + }, + { + "ref": "J4", + "pin": "3", + "name": "Pin_3", + "type": "passive", + "net": "QB" + }, + { + "ref": "J4", + "pin": "4", + "name": "Pin_4", + "type": "passive", + "net": "QC" + }, + { + "ref": "J4", + "pin": "5", + "name": "Pin_5", + "type": "passive", + "net": "QD" + }, + { + "ref": "J4", + "pin": "6", + "name": "Pin_6", + "type": "passive", + "net": "QE" + }, + { + "ref": "J4", + "pin": "7", + "name": "Pin_7", + "type": "passive", + "net": "QF" + }, + { + "ref": "J4", + "pin": "8", + "name": "Pin_8", + "type": "passive", + "net": "QG" + }, + { + "ref": "J4", + "pin": "9", + "name": "Pin_9", + "type": "passive", + "net": "QH" + }, + { + "ref": "R1", + "pin": "1", + "name": "~", + "type": "passive", + "net": "VIN" + }, + { + "ref": "R1", + "pin": "2", + "name": "~", + "type": "passive", + "net": "DISCH" + }, + { + "ref": "R2", + "pin": "1", + "name": "~", + "type": "passive", + "net": "DISCH" + }, + { + "ref": "R2", + "pin": "2", + "name": "~", + "type": "passive", + "net": "THR" + }, + { + "ref": "R3", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QA" + }, + { + "ref": "R3", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L1" + }, + { + "ref": "R4", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QB" + }, + { + "ref": "R4", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L2" + }, + { + "ref": "R5", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QC" + }, + { + "ref": "R5", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L3" + }, + { + "ref": "R6", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QD" + }, + { + "ref": "R6", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L4" + }, + { + "ref": "R7", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QE" + }, + { + "ref": "R7", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L5" + }, + { + "ref": "R8", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QF" + }, + { + "ref": "R8", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L6" + }, + { + "ref": "R9", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QG" + }, + { + "ref": "R9", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L7" + }, + { + "ref": "R10", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QH" + }, + { + "ref": "R10", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L8" + }, + { + "ref": "U1", + "pin": "1", + "name": "VIN", + "type": "power_in", + "net": "VIN" + }, + { + "ref": "U1", + "pin": "2", + "name": "GND", + "type": "power_in", + "net": "GND" + }, + { + "ref": "U1", + "pin": "3", + "name": "EN", + "type": "input", + "net": "VIN" + }, + { + "ref": "U1", + "pin": "4", + "name": "NC", + "type": "no_connect", + "net": "NC", + "hidden": true + }, + { + "ref": "U1", + "pin": "5", + "name": "VOUT", + "type": "power_out", + "net": "+3V3" + }, + { + "ref": "U2", + "pin": "1", + "name": "GND", + "type": "power_in", + "net": "GND" + }, + { + "ref": "U2", + "pin": "2", + "name": "TRIG", + "type": "input", + "net": "THR" + }, + { + "ref": "U2", + "pin": "3", + "name": "OUT", + "type": "output", + "net": "CLK" + }, + { + "ref": "U2", + "pin": "4", + "name": "RST", + "type": "input", + "net": "VIN" + }, + { + "ref": "U2", + "pin": "5", + "name": "CONT", + "type": "passive", + "net": "CTRL" + }, + { + "ref": "U2", + "pin": "6", + "name": "THRES", + "type": "input", + "net": "THR" + }, + { + "ref": "U2", + "pin": "7", + "name": "DISCH", + "type": "input", + "net": "DISCH" + }, + { + "ref": "U2", + "pin": "8", + "name": "VCC", + "type": "power_in", + "net": "VIN" + }, + { + "ref": "U3", + "pin": "1", + "name": "QB", + "type": "tri_state", + "net": "QB" + }, + { + "ref": "U3", + "pin": "2", + "name": "QC", + "type": "tri_state", + "net": "QC" + }, + { + "ref": "U3", + "pin": "3", + "name": "QD", + "type": "tri_state", + "net": "QD" + }, + { + "ref": "U3", + "pin": "4", + "name": "QE", + "type": "tri_state", + "net": "QE" + }, + { + "ref": "U3", + "pin": "5", + "name": "QF", + "type": "tri_state", + "net": "QF" + }, + { + "ref": "U3", + "pin": "6", + "name": "QG", + "type": "tri_state", + "net": "QG" + }, + { + "ref": "U3", + "pin": "7", + "name": "QH", + "type": "tri_state", + "net": "QH" + }, + { + "ref": "U3", + "pin": "8", + "name": "GND", + "type": "power_in", + "net": "GND" + }, + { + "ref": "U3", + "pin": "9", + "name": "QH'", + "type": "output", + "net": "QHP" + }, + { + "ref": "U3", + "pin": "10", + "name": "SRCLR", + "type": "input", + "net": "SRCLR" + }, + { + "ref": "U3", + "pin": "11", + "name": "SRCLK", + "type": "input", + "net": "CLK" + }, + { + "ref": "U3", + "pin": "12", + "name": "RCLK", + "type": "input", + "net": "RCLK" + }, + { + "ref": "U3", + "pin": "13", + "name": "OE", + "type": "input", + "net": "GND" + }, + { + "ref": "U3", + "pin": "14", + "name": "SER", + "type": "input", + "net": "SER" + }, + { + "ref": "U3", + "pin": "15", + "name": "QA", + "type": "tri_state", + "net": "QA" + }, + { + "ref": "U3", + "pin": "16", + "name": "VCC", + "type": "power_in", + "net": "+3V3" + } + ], + "pin_table_text": "Ref Pin Name Type Net\n--- --- ----- ---------- -----\nC1 1 ~ passive VIN\nC1 2 ~ passive GND\nC2 1 ~ passive +3V3\nC2 2 ~ passive GND\nC3 1 ~ passive THR\nC3 2 ~ passive GND\nC4 1 ~ passive VIN\nC4 2 ~ passive GND\nC5 1 ~ passive CTRL\nC5 2 ~ passive GND\nC6 1 ~ passive +3V3\nC6 2 ~ passive GND\nD1 1 K passive GND\nD1 2 A passive L1\nD2 1 K passive GND\nD2 2 A passive L2\nD3 1 K passive GND\nD3 2 A passive L3\nD4 1 K passive GND\nD4 2 A passive L4\nD5 1 K passive GND\nD5 2 A passive L5\nD6 1 K passive GND\nD6 2 A passive L6\nD7 1 K passive GND\nD7 2 A passive L7\nD8 1 K passive GND\nD8 2 A passive L8\nJ1 1 Pin_1 passive VIN\nJ1 2 Pin_2 passive GND\nJ2 1 Pin_1 passive +3V3\nJ2 2 Pin_2 passive GND\nJ3 1 Pin_1 passive SER\nJ3 2 Pin_2 passive RCLK\nJ3 3 Pin_3 passive SRCLR\nJ3 4 Pin_4 passive QHP\nJ4 1 Pin_1 passive +3V3\nJ4 2 Pin_2 passive QA\nJ4 3 Pin_3 passive QB\nJ4 4 Pin_4 passive QC\nJ4 5 Pin_5 passive QD\nJ4 6 Pin_6 passive QE\nJ4 7 Pin_7 passive QF\nJ4 8 Pin_8 passive QG\nJ4 9 Pin_9 passive QH\nR1 1 ~ passive VIN\nR1 2 ~ passive DISCH\nR2 1 ~ passive DISCH\nR2 2 ~ passive THR\nR3 1 ~ passive QA\nR3 2 ~ passive L1\nR4 1 ~ passive QB\nR4 2 ~ passive L2\nR5 1 ~ passive QC\nR5 2 ~ passive L3\nR6 1 ~ passive QD\nR6 2 ~ passive L4\nR7 1 ~ passive QE\nR7 2 ~ passive L5\nR8 1 ~ passive QF\nR8 2 ~ passive L6\nR9 1 ~ passive QG\nR9 2 ~ passive L7\nR10 1 ~ passive QH\nR10 2 ~ passive L8\nU1 1 VIN power_in VIN\nU1 2 GND power_in GND\nU1 3 EN input VIN\nU1 4 NC no_connect NC\nU1 5 VOUT power_out +3V3\nU2 1 GND power_in GND\nU2 2 TRIG input THR\nU2 3 OUT output CLK\nU2 4 RST input VIN\nU2 5 CONT passive CTRL\nU2 6 THRES input THR\nU2 7 DISCH input DISCH\nU2 8 VCC power_in VIN\nU3 1 QB tri_state QB\nU3 2 QC tri_state QC\nU3 3 QD tri_state QD\nU3 4 QE tri_state QE\nU3 5 QF tri_state QF\nU3 6 QG tri_state QG\nU3 7 QH tri_state QH\nU3 8 GND power_in GND\nU3 9 QH' output QHP\nU3 10 SRCLR input SRCLR\nU3 11 SRCLK input CLK\nU3 12 RCLK input RCLK\nU3 13 OE input GND\nU3 14 SER input SER\nU3 15 QA tri_state QA\nU3 16 VCC power_in +3V3", + "bom": [ + { + "comment": "1uF", + "designators": "C1,C2", + "refs": [ + "C1", + "C2" + ], + "footprint": "C_0805_2012Metric", + "footprint_id": "Capacitor_SMD:C_0805_2012Metric", + "quantity": 2, + "lcsc": "", + "symbol": "Device:C" + }, + { + "comment": "10uF", + "designators": "C3", + "refs": [ + "C3" + ], + "footprint": "C_0805_2012Metric", + "footprint_id": "Capacitor_SMD:C_0805_2012Metric", + "quantity": 1, + "lcsc": "", + "symbol": "Device:C" + }, + { + "comment": "100nF", + "designators": "C4,C6", + "refs": [ + "C4", + "C6" + ], + "footprint": "C_0603_1608Metric", + "footprint_id": "Capacitor_SMD:C_0603_1608Metric", + "quantity": 2, + "lcsc": "", + "symbol": "Device:C" + }, + { + "comment": "10nF", + "designators": "C5", + "refs": [ + "C5" + ], + "footprint": "C_0603_1608Metric", + "footprint_id": "Capacitor_SMD:C_0603_1608Metric", + "quantity": 1, + "lcsc": "", + "symbol": "Device:C" + }, + { + "comment": "green", + "designators": "D1,D2,D3,D4,D5,D6,D7,D8", + "refs": [ + "D1", + "D2", + "D3", + "D4", + "D5", + "D6", + "D7", + "D8" + ], + "footprint": "LED_0603_1608Metric", + "footprint_id": "LED_SMD:LED_0603_1608Metric", + "quantity": 8, + "lcsc": "", + "symbol": "Device:LED" + }, + { + "comment": "5V in", + "designators": "J1", + "refs": [ + "J1" + ], + "footprint": "PinHeader_1x02_P2.54mm_Vertical", + "footprint_id": "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical", + "quantity": 1, + "lcsc": "", + "symbol": "Connector_Generic:Conn_01x02" + }, + { + "comment": "3V3 out", + "designators": "J2", + "refs": [ + "J2" + ], + "footprint": "PinHeader_1x02_P2.54mm_Vertical", + "footprint_id": "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical", + "quantity": 1, + "lcsc": "", + "symbol": "Connector_Generic:Conn_01x02" + }, + { + "comment": "SER RCLK SRCLR QH'", + "designators": "J3", + "refs": [ + "J3" + ], + "footprint": "PinHeader_1x04_P2.54mm_Vertical", + "footprint_id": "Connector_PinHeader_2.54mm:PinHeader_1x04_P2.54mm_Vertical", + "quantity": 1, + "lcsc": "", + "symbol": "Connector_Generic:Conn_01x04" + }, + { + "comment": "3V3 QA QB QC QD QE QF QG QH", + "designators": "J4", + "refs": [ + "J4" + ], + "footprint": "PinHeader_1x09_P2.54mm_Vertical", + "footprint_id": "Connector_PinHeader_2.54mm:PinHeader_1x09_P2.54mm_Vertical", + "quantity": 1, + "lcsc": "", + "symbol": "Connector_Generic:Conn_01x09" + }, + { + "comment": "1k", + "designators": "R1", + "refs": [ + "R1" + ], + "footprint": "R_0603_1608Metric", + "footprint_id": "Resistor_SMD:R_0603_1608Metric", + "quantity": 1, + "lcsc": "", + "symbol": "Device:R" + }, + { + "comment": "68k", + "designators": "R2", + "refs": [ + "R2" + ], + "footprint": "R_0603_1608Metric", + "footprint_id": "Resistor_SMD:R_0603_1608Metric", + "quantity": 1, + "lcsc": "", + "symbol": "Device:R" + }, + { + "comment": "470", + "designators": "R3,R4,R5,R6,R7,R8,R9,R10", + "refs": [ + "R3", + "R4", + "R5", + "R6", + "R7", + "R8", + "R9", + "R10" + ], + "footprint": "R_0603_1608Metric", + "footprint_id": "Resistor_SMD:R_0603_1608Metric", + "quantity": 8, + "lcsc": "", + "symbol": "Device:R" + }, + { + "comment": "AP2112K-3.3", + "designators": "U1", + "refs": [ + "U1" + ], + "footprint": "SOT-23-5", + "footprint_id": "Package_TO_SOT_SMD:SOT-23-5", + "quantity": 1, + "lcsc": "", + "symbol": "Regulator_Linear:AP2112K-3.3" + }, + { + "comment": "NE555D", + "designators": "U2", + "refs": [ + "U2" + ], + "footprint": "SOIC-8_3.9x4.9mm_P1.27mm", + "footprint_id": "Package_SO:SOIC-8_3.9x4.9mm_P1.27mm", + "quantity": 1, + "lcsc": "", + "symbol": "Timer:NE555D" + }, + { + "comment": "74HC595", + "designators": "U3", + "refs": [ + "U3" + ], + "footprint": "SOIC-16_3.9x9.9mm_P1.27mm", + "footprint_id": "Package_SO:SOIC-16_3.9x9.9mm_P1.27mm", + "quantity": 1, + "lcsc": "", + "symbol": "74xx:74HC595" + } + ], + "nets": { + "VIN": [ + "J1.1", + "U1.1", + "U1.3", + "C1.1", + "U2.8", + "U2.4", + "R1.1", + "C4.1" + ], + "+3V3": [ + "U1.5", + "C2.1", + "J2.1", + "U3.16", + "C6.1", + "J4.1" + ], + "GND": [ + "J1.2", + "U1.2", + "C1.2", + "C2.2", + "J2.2", + "U2.1", + "C3.2", + "C4.2", + "C5.2", + "U3.8", + "U3.13", + "C6.2", + "D1.1", + "D2.1", + "D3.1", + "D4.1", + "D5.1", + "D6.1", + "D7.1", + "D8.1" + ], + "DISCH": [ + "U2.7", + "R1.2", + "R2.1" + ], + "THR": [ + "U2.6", + "U2.2", + "R2.2", + "C3.1" + ], + "CTRL": [ + "U2.5", + "C5.1" + ], + "CLK": [ + "U2.3", + "U3.11" + ], + "SER": [ + "J3.1", + "U3.14" + ], + "RCLK": [ + "J3.2", + "U3.12" + ], + "SRCLR": [ + "J3.3", + "U3.10" + ], + "QHP": [ + "J3.4", + "U3.9" + ], + "QA": [ + "U3.15", + "R3.1", + "J4.2" + ], + "QB": [ + "U3.1", + "R4.1", + "J4.3" + ], + "QC": [ + "U3.2", + "R5.1", + "J4.4" + ], + "QD": [ + "U3.3", + "R6.1", + "J4.5" + ], + "QE": [ + "U3.4", + "R7.1", + "J4.6" + ], + "QF": [ + "U3.5", + "R8.1", + "J4.7" + ], + "QG": [ + "U3.6", + "R9.1", + "J4.8" + ], + "QH": [ + "U3.7", + "R10.1", + "J4.9" + ], + "L1": [ + "R3.2", + "D1.2" + ], + "L2": [ + "R4.2", + "D2.2" + ], + "L3": [ + "R5.2", + "D3.2" + ], + "L4": [ + "R6.2", + "D4.2" + ], + "L5": [ + "R7.2", + "D5.2" + ], + "L6": [ + "R8.2", + "D6.2" + ], + "L7": [ + "R9.2", + "D7.2" + ], + "L8": [ + "R10.2", + "D8.2" + ] + }, + "fab": { + "gerber_files": [ + "power_clock_shift_led_controller-B_Cu.gbl", + "power_clock_shift_led_controller-B_Mask.gbs", + "power_clock_shift_led_controller-B_Paste.gbp", + "power_clock_shift_led_controller-B_Silkscreen.gbo", + "power_clock_shift_led_controller-Edge_Cuts.gm1", + "power_clock_shift_led_controller-F_Cu.gtl", + "power_clock_shift_led_controller-F_Mask.gts", + "power_clock_shift_led_controller-F_Paste.gtp", + "power_clock_shift_led_controller-F_Silkscreen.gto", + "power_clock_shift_led_controller-NPTH.drl", + "power_clock_shift_led_controller-PTH.drl", + "power_clock_shift_led_controller-job.gbrjob" + ], + "gerber_zip_sha256": "38c34566fc2695a031de36a3633e17964af7cf34980f8117bd3a606542c25ce9" + }, + "sources": { + "spec_artifact_id": "a_96931266", + "pcb_artifact_id": "a_a8d0d129", + "kicad_version": "10.0.6" + }, + "limitations": [ + "2-layer boards only; no RF/microwave, high-voltage/creepage, HDI/microvias, impedance control, differential pairs or length matching.", + "Automatic placement is NOT done: part positions come from the spec. Routing is a simple grid router (45-degree tracks, through vias).", + "Pin names/numbers come from the official KiCad libraries; they were NOT cross-checked against datasheets. Verify critical pins (power, polarity) yourself.", + "No schematic is produced; the spec checker replaces ERC. DRC does not check electrical correctness, only manufacturability rules.", + "BOM/pos files are bare-board helpers: part availability, LCSC numbers and pick-and-place rotation offsets are NOT verified (no PCBA support yet)." + ], + "human_signoff_checklist": [ + "I checked the pin table: every power/ground/polarity pin goes to the net I intend.", + "I reviewed the top and bottom renders and the board outline/size.", + "I understand custom boards are not refundable if the design is wrong." + ] +} \ No newline at end of file diff --git a/docs/assets/kicad-zcode-composite-long-run/12-final-spec.json b/docs/assets/kicad-zcode-composite-long-run/12-final-spec.json new file mode 100644 index 00000000..268ff4c2 --- /dev/null +++ b/docs/assets/kicad-zcode-composite-long-run/12-final-spec.json @@ -0,0 +1,658 @@ +{ + "name": "power_clock_shift_led_controller", + "outline": { + "width_mm": 70.0, + "height_mm": 48.0, + "corner_radius_mm": 1.5 + }, + "layers": 2, + "parts": [ + { + "ref": "J1", + "symbol": "Connector_Generic:Conn_01x02", + "footprint": "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical", + "value": "5V in", + "x_mm": 8.0, + "y_mm": 6.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "U1", + "symbol": "Regulator_Linear:AP2112K-3.3", + "footprint": "Package_TO_SOT_SMD:SOT-23-5", + "value": "AP2112K-3.3", + "x_mm": 13.0, + "y_mm": 9.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C1", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0805_2012Metric", + "value": "1uF", + "x_mm": 12.0, + "y_mm": 18.0, + "rotation": 90.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C2", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0805_2012Metric", + "value": "1uF", + "x_mm": 15.5, + "y_mm": 14.5, + "rotation": 90.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "J2", + "symbol": "Connector_Generic:Conn_01x02", + "footprint": "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical", + "value": "3V3 out", + "x_mm": 8.0, + "y_mm": 13.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "U2", + "symbol": "Timer:NE555D", + "footprint": "Package_SO:SOIC-8_3.9x4.9mm_P1.27mm", + "value": "NE555D", + "x_mm": 26.0, + "y_mm": 10.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R1", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "1k", + "x_mm": 20.0, + "y_mm": 5.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R2", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "68k", + "x_mm": 32.0, + "y_mm": 5.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C3", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0805_2012Metric", + "value": "10uF", + "x_mm": 33.0, + "y_mm": 15.0, + "rotation": 90.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C4", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0603_1608Metric", + "value": "100nF", + "x_mm": 26.0, + "y_mm": 4.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C5", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0603_1608Metric", + "value": "10nF", + "x_mm": 19.0, + "y_mm": 15.0, + "rotation": 90.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "U3", + "symbol": "74xx:74HC595", + "footprint": "Package_SO:SOIC-16_3.9x9.9mm_P1.27mm", + "value": "74HC595", + "x_mm": 40.0, + "y_mm": 22.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "C6", + "symbol": "Device:C", + "footprint": "Capacitor_SMD:C_0603_1608Metric", + "value": "100nF", + "x_mm": 48.0, + "y_mm": 15.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "J3", + "symbol": "Connector_Generic:Conn_01x04", + "footprint": "Connector_PinHeader_2.54mm:PinHeader_1x04_P2.54mm_Vertical", + "value": "SER RCLK SRCLR QH'", + "x_mm": 62.0, + "y_mm": 4.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "J4", + "symbol": "Connector_Generic:Conn_01x09", + "footprint": "Connector_PinHeader_2.54mm:PinHeader_1x09_P2.54mm_Vertical", + "value": "3V3 QA QB QC QD QE QF QG QH", + "x_mm": 66.0, + "y_mm": 14.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R3", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 22.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D1", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 22.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R4", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 25.4, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D2", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 25.4, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R5", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 28.8, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D3", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 28.8, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R6", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 32.2, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D4", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 32.2, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R7", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 35.6, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D5", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 35.6, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R8", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 39.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D6", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 39.0, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R9", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 42.4, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D7", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 42.4, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "R10", + "symbol": "Device:R", + "footprint": "Resistor_SMD:R_0603_1608Metric", + "value": "470", + "x_mm": 14.0, + "y_mm": 45.8, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + }, + { + "ref": "D8", + "symbol": "Device:LED", + "footprint": "LED_SMD:LED_0603_1608Metric", + "value": "green", + "x_mm": 8.0, + "y_mm": 45.8, + "rotation": 0.0, + "side": "top", + "lcsc": null, + "no_thermal_vias": false + } + ], + "nets": [ + { + "name": "VIN", + "pins": [ + "J1.1", + "U1.1", + "U1.3", + "C1.1", + "U2.8", + "U2.4", + "R1.1", + "C4.1" + ] + }, + { + "name": "+3V3", + "pins": [ + "U1.5", + "C2.1", + "J2.1", + "U3.16", + "C6.1", + "J4.1" + ] + }, + { + "name": "GND", + "pins": [ + "J1.2", + "U1.2", + "C1.2", + "C2.2", + "J2.2", + "U2.1", + "C3.2", + "C4.2", + "C5.2", + "U3.8", + "U3.13", + "C6.2", + "D1.1", + "D2.1", + "D3.1", + "D4.1", + "D5.1", + "D6.1", + "D7.1", + "D8.1" + ] + }, + { + "name": "DISCH", + "pins": [ + "U2.7", + "R1.2", + "R2.1" + ] + }, + { + "name": "THR", + "pins": [ + "U2.6", + "U2.2", + "R2.2", + "C3.1" + ] + }, + { + "name": "CTRL", + "pins": [ + "U2.5", + "C5.1" + ] + }, + { + "name": "CLK", + "pins": [ + "U2.3", + "U3.11" + ] + }, + { + "name": "SER", + "pins": [ + "J3.1", + "U3.14" + ] + }, + { + "name": "RCLK", + "pins": [ + "J3.2", + "U3.12" + ] + }, + { + "name": "SRCLR", + "pins": [ + "J3.3", + "U3.10" + ] + }, + { + "name": "QHP", + "pins": [ + "J3.4", + "U3.9" + ] + }, + { + "name": "QA", + "pins": [ + "U3.15", + "R3.1", + "J4.2" + ] + }, + { + "name": "QB", + "pins": [ + "U3.1", + "R4.1", + "J4.3" + ] + }, + { + "name": "QC", + "pins": [ + "U3.2", + "R5.1", + "J4.4" + ] + }, + { + "name": "QD", + "pins": [ + "U3.3", + "R6.1", + "J4.5" + ] + }, + { + "name": "QE", + "pins": [ + "U3.4", + "R7.1", + "J4.6" + ] + }, + { + "name": "QF", + "pins": [ + "U3.5", + "R8.1", + "J4.7" + ] + }, + { + "name": "QG", + "pins": [ + "U3.6", + "R9.1", + "J4.8" + ] + }, + { + "name": "QH", + "pins": [ + "U3.7", + "R10.1", + "J4.9" + ] + }, + { + "name": "L1", + "pins": [ + "R3.2", + "D1.2" + ] + }, + { + "name": "L2", + "pins": [ + "R4.2", + "D2.2" + ] + }, + { + "name": "L3", + "pins": [ + "R5.2", + "D3.2" + ] + }, + { + "name": "L4", + "pins": [ + "R6.2", + "D4.2" + ] + }, + { + "name": "L5", + "pins": [ + "R7.2", + "D5.2" + ] + }, + { + "name": "L6", + "pins": [ + "R8.2", + "D6.2" + ] + }, + { + "name": "L7", + "pins": [ + "R9.2", + "D7.2" + ] + }, + { + "name": "L8", + "pins": [ + "R10.2", + "D8.2" + ] + } + ], + "power_nets": [ + "VIN", + "+3V3" + ], + "ground_nets": [ + "GND" + ], + "ground_pour": true, + "no_connect": [], + "mounting_holes": [ + { + "x_mm": 3.0, + "y_mm": 3.0, + "drill_mm": 3.2, + "keepout_mm": 1.0 + }, + { + "x_mm": 67.0, + "y_mm": 3.0, + "drill_mm": 3.2, + "keepout_mm": 1.0 + }, + { + "x_mm": 3.0, + "y_mm": 45.0, + "drill_mm": 3.2, + "keepout_mm": 1.0 + }, + { + "x_mm": 67.0, + "y_mm": 45.0, + "drill_mm": 3.2, + "keepout_mm": 1.0 + } + ], + "fiducials": [], + "keepouts": [], + "rules": { + "signal_width_mm": 0.25, + "power_width_mm": 0.5, + "clearance_mm": 0.2, + "via_diameter_mm": 0.6, + "via_drill_mm": 0.3, + "edge_clearance_mm": 0.3 + } +} \ No newline at end of file diff --git a/docs/assets/kicad-zcode-composite-long-run/13-run-summary.json b/docs/assets/kicad-zcode-composite-long-run/13-run-summary.json new file mode 100644 index 00000000..af67a5fb --- /dev/null +++ b/docs/assets/kicad-zcode-composite-long-run/13-run-summary.json @@ -0,0 +1,144 @@ +{ + "date": "2026-11-04", + "plugin_version": "0.12.3", + "host": "ZCode Dev", + "model": { + "id": "GLM-5.3", + "successful_effort": "low", + "successful_wall_time_seconds": 506, + "max_effort_attempts": [ + { + "duration_ms": 148253, + "tool_calls": 0, + "result": "preempted after planning without calling the required first tool" + }, + { + "duration_ms": 138802, + "tool_calls": 0, + "result": "stopped after planning without calling the required first tool" + } + ] + }, + "fresh_chat_registration": { + "before_fix": { + "all_tools": 68, + "kicad_tools": 0, + "tool_search_available": false + }, + "after_fix": { + "all_tools": 94, + "kicad_tools": 25, + "first_tool": "kicad_capabilities", + "plugin_version_reported": "0.12.3" + } + }, + "environment": { + "requested_edition": "auto", + "resolved_edition": "standard", + "distribution": "official", + "kicad_version": "10.0.6", + "edition_ready": true + }, + "task": { + "name": "power_clock_shift_led_controller", + "description": "5 V input, AP2112K 3.3 V branch, NE555 astable clock, 74HC595, eight resistor-driven LEDs, serial and parallel headers, four mounting holes", + "board_width_mm": 70, + "board_height_mm": 48, + "layers": 2, + "parts": 31, + "footprints_including_holes": 35, + "mounting_holes": 4, + "nets": 27, + "pads": 98, + "tracks": 269, + "vias": 49, + "zones": 2, + "trace_length_mm": 875.51 + }, + "iterations": { + "spec_checks": [ + { "errors": 10, "warnings": 0, "action": "separate power, LED and mounting-hole keepout regions" }, + { "errors": 1, "warnings": 0, "action": "move C1 away from J2" }, + { "errors": 0, "warnings": 0, "ok": true } + ], + "builds": [ + { "drc_errors": 0, "unconnected": 0, "unrouted": 2, "action": "move C1, U3 and C6 to make room for GND stitching vias" }, + { "drc_errors": 0, "unconnected": 0, "unrouted": 1, "action": "move U3 upward by 2 mm" }, + { "drc_errors": 0, "unconnected": 0, "unrouted": 0, "ok": true } + ], + "final_build_seconds": { + "placement": 1.78, + "routing": 7.63, + "finish": 0.42, + "drc": 1.62, + "total": 11.45 + } + }, + "checks": { + "spec_errors": 0, + "spec_warnings": 0, + "drc_errors": 0, + "drc_unconnected": 0, + "drc_warnings": 4, + "warning_types": { + "silk_over_copper": 4 + }, + "routing_complete": true, + "ready_to_order": true, + "blocking_problems": [] + }, + "glb": { + "include_copper": true, + "size_bytes": 4990772, + "part_count": 31, + "parts_without_model": ["H1", "H2", "H3", "H4"] + }, + "ipc": { + "available": true, + "matches_session": true, + "reference": "R3", + "baseline_position_mm": [14.0, 22.0], + "baseline_signature": "207049d2b67d25d0", + "moved_position_mm": [14.25, 22.0], + "moved_signature": "a1f69e2d1d8ef1c8", + "restored_position_mm": [14.0, 22.0], + "restored_signature": "207049d2b67d25d0", + "saved_during_test": false, + "source_and_edit_sha256": "60acd5b4764c9610fe9a079e640987e6047aaad69db053b0491349672d75b288" + }, + "tool_calls": { + "total": 30, + "by_name": { + "kicad_capabilities": 1, + "pcb_spec_example": 4, + "pcb_part_info": 3, + "pcb_check_spec": 5, + "pcb_build": 3, + "pcb_render": 2, + "kicad_checks": 1, + "pcb_export_glb": 1, + "pcb_export_fab": 1, + "kicad_export_files": 1, + "kicad_board_view": 1, + "kicad_open_in_kicad": 1, + "kicad_live_status": 1, + "kicad_live_snapshot": 3, + "kicad_live_move_footprint": 2 + } + }, + "artifacts": { + "final_spec": "a_96931266", + "board": "a_a8d0d129", + "gerber_zip": "a_f94b4c78", + "bom": "a_d2885ad0", + "position_csv": "a_a5bcd9cc", + "step": "a_83084fe6", + "report": "a_2d4f3df9", + "top_png": "a_9ddf8ce6", + "bottom_png": "a_24522023", + "glb": "a_37e86ce1", + "project_zip": "a_f3f11006" + }, + "workspace_export": "kicad/out/composite-acceptance", + "result": "PASS" +} diff --git a/docs/assets/kicad-zcode-composite-long-run/board-bottom.png b/docs/assets/kicad-zcode-composite-long-run/board-bottom.png new file mode 100644 index 00000000..428792c1 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/board-bottom.png differ diff --git a/docs/assets/kicad-zcode-composite-long-run/board-top.png b/docs/assets/kicad-zcode-composite-long-run/board-top.png new file mode 100644 index 00000000..592f4bf2 Binary files /dev/null and b/docs/assets/kicad-zcode-composite-long-run/board-top.png differ diff --git a/docs/assets/kicad-zcode-live-ipc/01-zcode-complex-task-progress.jpg b/docs/assets/kicad-zcode-live-ipc/01-zcode-complex-task-progress.jpg new file mode 100644 index 00000000..e4cb12c2 Binary files /dev/null and b/docs/assets/kicad-zcode-live-ipc/01-zcode-complex-task-progress.jpg differ diff --git a/docs/assets/kicad-zcode-live-ipc/02-zcode-release-audit-result.jpg b/docs/assets/kicad-zcode-live-ipc/02-zcode-release-audit-result.jpg new file mode 100644 index 00000000..9d2ae674 Binary files /dev/null and b/docs/assets/kicad-zcode-live-ipc/02-zcode-release-audit-result.jpg differ diff --git a/docs/assets/kicad-zcode-live-ipc/03-zcode-live-move-restore.jpg b/docs/assets/kicad-zcode-live-ipc/03-zcode-live-move-restore.jpg new file mode 100644 index 00000000..a6a79f59 Binary files /dev/null and b/docs/assets/kicad-zcode-live-ipc/03-zcode-live-move-restore.jpg differ diff --git a/docs/assets/kicad-zcode-live-ipc/04-zcode-lock-detection.jpg b/docs/assets/kicad-zcode-live-ipc/04-zcode-lock-detection.jpg new file mode 100644 index 00000000..4a4e9289 Binary files /dev/null and b/docs/assets/kicad-zcode-live-ipc/04-zcode-lock-detection.jpg differ diff --git a/docs/assets/kicad-zcode-live-ipc/05-ne555-board-top.png b/docs/assets/kicad-zcode-live-ipc/05-ne555-board-top.png new file mode 100644 index 00000000..a72db411 Binary files /dev/null and b/docs/assets/kicad-zcode-live-ipc/05-ne555-board-top.png differ diff --git a/docs/assets/kicad-zcode-shift-register/00-zcode-new-task.png b/docs/assets/kicad-zcode-shift-register/00-zcode-new-task.png new file mode 100644 index 00000000..3ab5270b Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/00-zcode-new-task.png differ diff --git a/docs/assets/kicad-zcode-shift-register/01-task-start.png b/docs/assets/kicad-zcode-shift-register/01-task-start.png new file mode 100644 index 00000000..dae08f73 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/01-task-start.png differ diff --git a/docs/assets/kicad-zcode-shift-register/02-plan-and-capabilities.png b/docs/assets/kicad-zcode-shift-register/02-plan-and-capabilities.png new file mode 100644 index 00000000..67068b82 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/02-plan-and-capabilities.png differ diff --git a/docs/assets/kicad-zcode-shift-register/03-tool-registration-failure.png b/docs/assets/kicad-zcode-shift-register/03-tool-registration-failure.png new file mode 100644 index 00000000..c1381633 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/03-tool-registration-failure.png differ diff --git a/docs/assets/kicad-zcode-shift-register/04-second-run-start.jpg b/docs/assets/kicad-zcode-shift-register/04-second-run-start.jpg new file mode 100644 index 00000000..31896ff0 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/04-second-run-start.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/05-capabilities-and-spec.jpg b/docs/assets/kicad-zcode-shift-register/05-capabilities-and-spec.jpg new file mode 100644 index 00000000..4f291c10 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/05-capabilities-and-spec.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/06-build-result.jpg b/docs/assets/kicad-zcode-shift-register/06-build-result.jpg new file mode 100644 index 00000000..f44a0f95 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/06-build-result.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/07-render-and-open.jpg b/docs/assets/kicad-zcode-shift-register/07-render-and-open.jpg new file mode 100644 index 00000000..b46886e6 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/07-render-and-open.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/08-live-ipc-move.jpg b/docs/assets/kicad-zcode-shift-register/08-live-ipc-move.jpg new file mode 100644 index 00000000..19520c27 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/08-live-ipc-move.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/09-live-ipc-restore.jpg b/docs/assets/kicad-zcode-shift-register/09-live-ipc-restore.jpg new file mode 100644 index 00000000..1fd4b739 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/09-live-ipc-restore.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/10-checks-and-glb.jpg b/docs/assets/kicad-zcode-shift-register/10-checks-and-glb.jpg new file mode 100644 index 00000000..c1647672 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/10-checks-and-glb.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/11-fabrication-export.jpg b/docs/assets/kicad-zcode-shift-register/11-fabrication-export.jpg new file mode 100644 index 00000000..515fac0a Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/11-fabrication-export.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/12-final-summary.jpg b/docs/assets/kicad-zcode-shift-register/12-final-summary.jpg new file mode 100644 index 00000000..1bd44a74 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/12-final-summary.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/13-final-risks.jpg b/docs/assets/kicad-zcode-shift-register/13-final-risks.jpg new file mode 100644 index 00000000..b0c70444 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/13-final-risks.jpg differ diff --git a/docs/assets/kicad-zcode-shift-register/14-board-top.png b/docs/assets/kicad-zcode-shift-register/14-board-top.png new file mode 100644 index 00000000..1b6c29e3 Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/14-board-top.png differ diff --git a/docs/assets/kicad-zcode-shift-register/15-board-bottom.png b/docs/assets/kicad-zcode-shift-register/15-board-bottom.png new file mode 100644 index 00000000..969bc97f Binary files /dev/null and b/docs/assets/kicad-zcode-shift-register/15-board-bottom.png differ diff --git a/docs/assets/kicad-zcode-shift-register/16-pcb-report.json b/docs/assets/kicad-zcode-shift-register/16-pcb-report.json new file mode 100644 index 00000000..1902d270 --- /dev/null +++ b/docs/assets/kicad-zcode-shift-register/16-pcb-report.json @@ -0,0 +1,1094 @@ +{ + "type": "pcb_report", + "title": "shift_register_leds", + "generated_at": "2026-11-03T09:51:48+00:00", + "ready_to_order": true, + "blocking_problems": [], + "board": { + "width_mm": 48.0, + "height_mm": 32.0, + "layers": 2, + "corner_radius_mm": 1.5, + "mounting_holes": 0 + }, + "design_rules": { + "signal_width_mm": 0.25, + "power_width_mm": 0.5, + "clearance_mm": 0.2, + "via_diameter_mm": 0.6, + "via_drill_mm": 0.3, + "edge_clearance_mm": 0.3 + }, + "checks": { + "spec": { + "ok": true, + "n_errors": 0, + "n_warnings": 0, + "issues": [] + }, + "drc": { + "passed": true, + "errors": 0, + "warnings": 36, + "unconnected": 0, + "by_type": { + "silk_overlap": 12, + "silk_over_copper": 24 + }, + "violations": [ + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Reference field of R5", + "x_mm": 13.5, + "y_mm": 13.17 + }, + { + "what": "Segment of R4 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 12.722 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of D5 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 15.335 + }, + { + "what": "Reference field of D6", + "x_mm": 8.0, + "y_mm": 15.57 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of D4 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 12.935 + }, + { + "what": "Reference field of D5", + "x_mm": 8.0, + "y_mm": 13.17 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of R6 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 17.522 + }, + { + "what": "Reference field of R7", + "x_mm": 13.5, + "y_mm": 17.97 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of D6 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 17.735 + }, + { + "what": "Reference field of D7", + "x_mm": 8.0, + "y_mm": 17.97 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of R5 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 15.122 + }, + { + "what": "Reference field of R6", + "x_mm": 13.5, + "y_mm": 15.57 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of D2 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 8.135 + }, + { + "what": "Reference field of D3", + "x_mm": 8.0, + "y_mm": 8.37 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Reference field of R3", + "x_mm": 13.5, + "y_mm": 8.37 + }, + { + "what": "Segment of R2 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 7.922 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of R3 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 10.322 + }, + { + "what": "Reference field of R4", + "x_mm": 13.5, + "y_mm": 10.77 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of D1 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 5.735 + }, + { + "what": "Reference field of D2", + "x_mm": 8.0, + "y_mm": 5.97 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Segment of R1 on F.Silkscreen", + "x_mm": 13.263, + "y_mm": 5.523 + }, + { + "what": "Reference field of R2", + "x_mm": 13.5, + "y_mm": 5.97 + } + ] + }, + { + "type": "silk_overlap", + "severity": "warning", + "description": "Silkscreen clearance", + "items": [ + { + "what": "Reference field of D4", + "x_mm": 8.0, + "y_mm": 10.77 + }, + { + "what": "Segment of D3 on F.Silkscreen", + "x_mm": 6.515, + "y_mm": 10.535 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R5", + "x_mm": 13.5, + "y_mm": 13.17 + }, + { + "what": "Pad 2 [QE] of R4 on F.Cu", + "x_mm": 14.325, + "y_mm": 12.2 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R5", + "x_mm": 13.5, + "y_mm": 13.17 + }, + { + "what": "Pad 1 [L4] of R4 on F.Cu", + "x_mm": 12.675, + "y_mm": 12.2 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D5", + "x_mm": 8.0, + "y_mm": 13.17 + }, + { + "what": "Pad 1 [GND] of D4 on F.Cu", + "x_mm": 7.212, + "y_mm": 12.2 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D6", + "x_mm": 8.0, + "y_mm": 15.57 + }, + { + "what": "Pad 2 [L5] of D5 on F.Cu", + "x_mm": 8.788, + "y_mm": 14.6 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D5", + "x_mm": 8.0, + "y_mm": 13.17 + }, + { + "what": "Pad 2 [L4] of D4 on F.Cu", + "x_mm": 8.788, + "y_mm": 12.2 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D6", + "x_mm": 8.0, + "y_mm": 15.57 + }, + { + "what": "Pad 1 [GND] of D5 on F.Cu", + "x_mm": 7.212, + "y_mm": 14.6 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R7", + "x_mm": 13.5, + "y_mm": 17.97 + }, + { + "what": "Pad 1 [L6] of R6 on F.Cu", + "x_mm": 12.675, + "y_mm": 17.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D7", + "x_mm": 8.0, + "y_mm": 17.97 + }, + { + "what": "Pad 2 [L6] of D6 on F.Cu", + "x_mm": 8.788, + "y_mm": 17.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D7", + "x_mm": 8.0, + "y_mm": 17.97 + }, + { + "what": "Pad 1 [GND] of D6 on F.Cu", + "x_mm": 7.212, + "y_mm": 17.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R6", + "x_mm": 13.5, + "y_mm": 15.57 + }, + { + "what": "Pad 1 [L5] of R5 on F.Cu", + "x_mm": 12.675, + "y_mm": 14.6 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R7", + "x_mm": 13.5, + "y_mm": 17.97 + }, + { + "what": "Pad 2 [QG] of R6 on F.Cu", + "x_mm": 14.325, + "y_mm": 17.0 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of R6", + "x_mm": 13.5, + "y_mm": 15.57 + }, + { + "what": "Pad 2 [QF] of R5 on F.Cu", + "x_mm": 14.325, + "y_mm": 14.6 + } + ] + }, + { + "type": "silk_over_copper", + "severity": "warning", + "description": "Silkscreen clipped by solder mask", + "items": [ + { + "what": "Reference field of D3", + "x_mm": 8.0, + "y_mm": 8.37 + }, + { + "what": "Pad 1 [GND] of D2 on F.Cu", + "x_mm": 7.212, + "y_mm": 7.4 + } + ] + } + ], + "unconnected_items": [], + "kicad_version": "10.0.6" + }, + "routing": { + "complete": true, + "unrouted": [], + "warnings": [], + "stats": { + "passes": 2, + "nets_routed": 21, + "vias": 14, + "segments": 88, + "unrouted_connections": 0, + "length_mm": 216.99, + "seconds": 3.98, + "grid_mm": 0.1, + "expansions": 1297148, + "searches": 65 + }, + "tracks": 88, + "vias": 14 + } + }, + "pin_table": [ + { + "ref": "C1", + "pin": "1", + "name": "~", + "type": "passive", + "net": "VCC" + }, + { + "ref": "C1", + "pin": "2", + "name": "~", + "type": "passive", + "net": "GND" + }, + { + "ref": "D1", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D1", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L1" + }, + { + "ref": "D2", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D2", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L2" + }, + { + "ref": "D3", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D3", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L3" + }, + { + "ref": "D4", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D4", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L4" + }, + { + "ref": "D5", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D5", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L5" + }, + { + "ref": "D6", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D6", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L6" + }, + { + "ref": "D7", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D7", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L7" + }, + { + "ref": "D8", + "pin": "1", + "name": "K", + "type": "passive", + "net": "GND" + }, + { + "ref": "D8", + "pin": "2", + "name": "A", + "type": "passive", + "net": "L8" + }, + { + "ref": "J1", + "pin": "1", + "name": "Pin_1", + "type": "passive", + "net": "VCC" + }, + { + "ref": "J1", + "pin": "2", + "name": "Pin_2", + "type": "passive", + "net": "GND" + }, + { + "ref": "J1", + "pin": "3", + "name": "Pin_3", + "type": "passive", + "net": "SER" + }, + { + "ref": "J1", + "pin": "4", + "name": "Pin_4", + "type": "passive", + "net": "SRCLK" + }, + { + "ref": "J1", + "pin": "5", + "name": "Pin_5", + "type": "passive", + "net": "RCLK" + }, + { + "ref": "J1", + "pin": "6", + "name": "Pin_6", + "type": "passive", + "net": "QHP" + }, + { + "ref": "R1", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L1" + }, + { + "ref": "R1", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QB" + }, + { + "ref": "R2", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L2" + }, + { + "ref": "R2", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QC" + }, + { + "ref": "R3", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L3" + }, + { + "ref": "R3", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QD" + }, + { + "ref": "R4", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L4" + }, + { + "ref": "R4", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QE" + }, + { + "ref": "R5", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L5" + }, + { + "ref": "R5", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QF" + }, + { + "ref": "R6", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L6" + }, + { + "ref": "R6", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QG" + }, + { + "ref": "R7", + "pin": "1", + "name": "~", + "type": "passive", + "net": "L7" + }, + { + "ref": "R7", + "pin": "2", + "name": "~", + "type": "passive", + "net": "QH" + }, + { + "ref": "R8", + "pin": "1", + "name": "~", + "type": "passive", + "net": "QA" + }, + { + "ref": "R8", + "pin": "2", + "name": "~", + "type": "passive", + "net": "L8" + }, + { + "ref": "U1", + "pin": "1", + "name": "QB", + "type": "tri_state", + "net": "QB" + }, + { + "ref": "U1", + "pin": "2", + "name": "QC", + "type": "tri_state", + "net": "QC" + }, + { + "ref": "U1", + "pin": "3", + "name": "QD", + "type": "tri_state", + "net": "QD" + }, + { + "ref": "U1", + "pin": "4", + "name": "QE", + "type": "tri_state", + "net": "QE" + }, + { + "ref": "U1", + "pin": "5", + "name": "QF", + "type": "tri_state", + "net": "QF" + }, + { + "ref": "U1", + "pin": "6", + "name": "QG", + "type": "tri_state", + "net": "QG" + }, + { + "ref": "U1", + "pin": "7", + "name": "QH", + "type": "tri_state", + "net": "QH" + }, + { + "ref": "U1", + "pin": "8", + "name": "GND", + "type": "power_in", + "net": "GND" + }, + { + "ref": "U1", + "pin": "9", + "name": "QH'", + "type": "output", + "net": "QHP" + }, + { + "ref": "U1", + "pin": "10", + "name": "SRCLR", + "type": "input", + "net": "VCC" + }, + { + "ref": "U1", + "pin": "11", + "name": "SRCLK", + "type": "input", + "net": "SRCLK" + }, + { + "ref": "U1", + "pin": "12", + "name": "RCLK", + "type": "input", + "net": "RCLK" + }, + { + "ref": "U1", + "pin": "13", + "name": "OE", + "type": "input", + "net": "GND" + }, + { + "ref": "U1", + "pin": "14", + "name": "SER", + "type": "input", + "net": "SER" + }, + { + "ref": "U1", + "pin": "15", + "name": "QA", + "type": "tri_state", + "net": "QA" + }, + { + "ref": "U1", + "pin": "16", + "name": "VCC", + "type": "power_in", + "net": "VCC" + } + ], + "pin_table_text": "Ref Pin Name Type Net\n--- --- ----- --------- -----\nC1 1 ~ passive VCC\nC1 2 ~ passive GND\nD1 1 K passive GND\nD1 2 A passive L1\nD2 1 K passive GND\nD2 2 A passive L2\nD3 1 K passive GND\nD3 2 A passive L3\nD4 1 K passive GND\nD4 2 A passive L4\nD5 1 K passive GND\nD5 2 A passive L5\nD6 1 K passive GND\nD6 2 A passive L6\nD7 1 K passive GND\nD7 2 A passive L7\nD8 1 K passive GND\nD8 2 A passive L8\nJ1 1 Pin_1 passive VCC\nJ1 2 Pin_2 passive GND\nJ1 3 Pin_3 passive SER\nJ1 4 Pin_4 passive SRCLK\nJ1 5 Pin_5 passive RCLK\nJ1 6 Pin_6 passive QHP\nR1 1 ~ passive L1\nR1 2 ~ passive QB\nR2 1 ~ passive L2\nR2 2 ~ passive QC\nR3 1 ~ passive L3\nR3 2 ~ passive QD\nR4 1 ~ passive L4\nR4 2 ~ passive QE\nR5 1 ~ passive L5\nR5 2 ~ passive QF\nR6 1 ~ passive L6\nR6 2 ~ passive QG\nR7 1 ~ passive L7\nR7 2 ~ passive QH\nR8 1 ~ passive QA\nR8 2 ~ passive L8\nU1 1 QB tri_state QB\nU1 2 QC tri_state QC\nU1 3 QD tri_state QD\nU1 4 QE tri_state QE\nU1 5 QF tri_state QF\nU1 6 QG tri_state QG\nU1 7 QH tri_state QH\nU1 8 GND power_in GND\nU1 9 QH' output QHP\nU1 10 SRCLR input VCC\nU1 11 SRCLK input SRCLK\nU1 12 RCLK input RCLK\nU1 13 OE input GND\nU1 14 SER input SER\nU1 15 QA tri_state QA\nU1 16 VCC power_in VCC", + "bom": [ + { + "comment": "100nF", + "designators": "C1", + "refs": [ + "C1" + ], + "footprint": "C_0603_1608Metric", + "footprint_id": "Capacitor_SMD:C_0603_1608Metric", + "quantity": 1, + "lcsc": "", + "symbol": "Device:C" + }, + { + "comment": "green", + "designators": "D1,D2,D3,D4,D5,D6,D7,D8", + "refs": [ + "D1", + "D2", + "D3", + "D4", + "D5", + "D6", + "D7", + "D8" + ], + "footprint": "LED_0603_1608Metric", + "footprint_id": "LED_SMD:LED_0603_1608Metric", + "quantity": 8, + "lcsc": "", + "symbol": "Device:LED" + }, + { + "comment": "VCC GND SER SRCLK RCLK QH'", + "designators": "J1", + "refs": [ + "J1" + ], + "footprint": "PinHeader_1x06_P2.54mm_Vertical", + "footprint_id": "Connector_PinHeader_2.54mm:PinHeader_1x06_P2.54mm_Vertical", + "quantity": 1, + "lcsc": "", + "symbol": "Connector_Generic:Conn_01x06" + }, + { + "comment": "470", + "designators": "R1,R2,R3,R4,R5,R6,R7,R8", + "refs": [ + "R1", + "R2", + "R3", + "R4", + "R5", + "R6", + "R7", + "R8" + ], + "footprint": "R_0603_1608Metric", + "footprint_id": "Resistor_SMD:R_0603_1608Metric", + "quantity": 8, + "lcsc": "", + "symbol": "Device:R" + }, + { + "comment": "74HC595", + "designators": "U1", + "refs": [ + "U1" + ], + "footprint": "SOIC-16_3.9x9.9mm_P1.27mm", + "footprint_id": "Package_SO:SOIC-16_3.9x9.9mm_P1.27mm", + "quantity": 1, + "lcsc": "", + "symbol": "74xx:74HC595" + } + ], + "nets": { + "VCC": [ + "J1.1", + "U1.16", + "U1.10", + "C1.1" + ], + "GND": [ + "J1.2", + "U1.8", + "U1.13", + "C1.2", + "D1.1", + "D2.1", + "D3.1", + "D4.1", + "D5.1", + "D6.1", + "D7.1", + "D8.1" + ], + "SER": [ + "J1.3", + "U1.14" + ], + "SRCLK": [ + "J1.4", + "U1.11" + ], + "RCLK": [ + "J1.5", + "U1.12" + ], + "QHP": [ + "J1.6", + "U1.9" + ], + "QB": [ + "U1.1", + "R1.2" + ], + "L1": [ + "R1.1", + "D1.2" + ], + "QC": [ + "U1.2", + "R2.2" + ], + "L2": [ + "R2.1", + "D2.2" + ], + "QD": [ + "U1.3", + "R3.2" + ], + "L3": [ + "R3.1", + "D3.2" + ], + "QE": [ + "U1.4", + "R4.2" + ], + "L4": [ + "R4.1", + "D4.2" + ], + "QF": [ + "U1.5", + "R5.2" + ], + "L5": [ + "R5.1", + "D5.2" + ], + "QG": [ + "U1.6", + "R6.2" + ], + "L6": [ + "R6.1", + "D6.2" + ], + "QH": [ + "U1.7", + "R7.2" + ], + "L7": [ + "R7.1", + "D7.2" + ], + "QA": [ + "U1.15", + "R8.1" + ], + "L8": [ + "R8.2", + "D8.2" + ] + }, + "fab": { + "gerber_files": [ + "shift_register_leds-B_Cu.gbl", + "shift_register_leds-B_Mask.gbs", + "shift_register_leds-B_Paste.gbp", + "shift_register_leds-B_Silkscreen.gbo", + "shift_register_leds-Edge_Cuts.gm1", + "shift_register_leds-F_Cu.gtl", + "shift_register_leds-F_Mask.gts", + "shift_register_leds-F_Paste.gtp", + "shift_register_leds-F_Silkscreen.gto", + "shift_register_leds-PTH.drl", + "shift_register_leds-job.gbrjob" + ], + "gerber_zip_sha256": "ce3c23923117479f092d971937264845e2f8a13e73f8d82b176d7d8d847881a2" + }, + "sources": { + "spec_artifact_id": "a_fd7bda4d", + "pcb_artifact_id": "a_16215bd2", + "kicad_version": "10.0.6" + }, + "limitations": [ + "2-layer boards only; no RF/microwave, high-voltage/creepage, HDI/microvias, impedance control, differential pairs or length matching.", + "Automatic placement is NOT done: part positions come from the spec. Routing is a simple grid router (45-degree tracks, through vias).", + "Pin names/numbers come from the official KiCad libraries; they were NOT cross-checked against datasheets. Verify critical pins (power, polarity) yourself.", + "No schematic is produced; the spec checker replaces ERC. DRC does not check electrical correctness, only manufacturability rules.", + "BOM/pos files are bare-board helpers: part availability, LCSC numbers and pick-and-place rotation offsets are NOT verified (no PCBA support yet)." + ], + "human_signoff_checklist": [ + "I checked the pin table: every power/ground/polarity pin goes to the net I intend.", + "I reviewed the top and bottom renders and the board outline/size.", + "I understand custom boards are not refundable if the design is wrong." + ] +} \ No newline at end of file diff --git a/docs/assets/kicad-zcode-shift-register/17-run-summary.json b/docs/assets/kicad-zcode-shift-register/17-run-summary.json new file mode 100644 index 00000000..9cd26582 --- /dev/null +++ b/docs/assets/kicad-zcode-shift-register/17-run-summary.json @@ -0,0 +1,92 @@ +{ + "run": { + "date": "2026-11-03", + "task": "shift_register_leds end-to-end long-running acceptance", + "zcode_model": "GLM-5.3 Max", + "successful_run_duration": "4m37s", + "first_attempt": { + "result": "blocked", + "duration": "5m23s", + "reason": "KiCad skills were visible in a new chat, but the KiCad MCP tools were not injected into that chat's tool list" + } + }, + "capabilities": { + "requested_edition": "auto", + "resolved_edition": "standard", + "distribution": "official", + "kicad_version": "10.0.6", + "core_ready": true, + "edition_ready": true, + "live_ipc_before_open": false, + "live_ipc_after_open": true + }, + "design": { + "name": "shift_register_leds", + "board_width_mm": 48.0, + "board_height_mm": 32.0, + "layers": 2, + "components": 19, + "spec_nets": 22, + "routed_nets": 21, + "live_snapshot_nets": 22, + "pin_net_mappings": 58, + "tracks": 88, + "vias": 14, + "zones": 2, + "pads": 56, + "trace_length_mm": 216.99, + "build_seconds": 3.983 + }, + "checks": { + "spec_errors": 0, + "spec_warnings": 0, + "drc_errors": 0, + "drc_unconnected": 0, + "drc_warnings": 36, + "drc_warning_types": { + "silk_overlap": 12, + "silk_over_copper": 24 + }, + "erc": "not applicable: no .kicad_sch was generated" + }, + "live_ipc": { + "launched": true, + "live_ready": true, + "matches_session": true, + "footprint": "C1", + "original_position_mm": [29.0, 6.0], + "moved_position_mm": [29.25, 6.0], + "baseline_signature": "a48d6c7accf43673", + "moved_signature": "4a2a371ef4da6164", + "restored_signature": "a48d6c7accf43673", + "incremental_snapshot_unchanged": true, + "saved": false, + "source_and_edit_sha256": "52606e69c7a3ad30e4a7fe146276c999f4a23a8622e0d886f2d7ec620d375739" + }, + "3d": { + "include_copper": true, + "parts_with_model": 19, + "parts_without_model": 0, + "size_bytes": 2225900, + "mesh_classes": ["copper", "pads", "vias", "silkscreen", "solder-mask", "components"] + }, + "manufacturing": { + "ready_to_order": true, + "blocking_problems": [], + "exported_files": 9, + "export_directory": "kicad/out/shift_register_acceptance/" + }, + "artifacts": [ + {"type": "spec", "id": "a_fd7bda4d", "size_bytes": 6686}, + {"type": "pcb", "id": "a_16215bd2", "size_bytes": 159435}, + {"type": "top_render", "id": "a_d98bb6da", "size_bytes": 56901}, + {"type": "bottom_render", "id": "a_81f56144", "size_bytes": 25088}, + {"type": "glb", "id": "a_751b5dac", "size_bytes": 2225900}, + {"type": "gerber_and_drill", "id": "a_6d068556", "size_bytes": 29625}, + {"type": "kicad_project", "id": "a_cd0944ae", "size_bytes": 35004}, + {"type": "bom", "id": "a_212ae0fc", "size_bytes": 369}, + {"type": "position_csv", "id": "a_df5a7bf0", "size_bytes": 1068}, + {"type": "step", "id": "a_4ded4c8d", "size_bytes": 930047}, + {"type": "pcb_report", "id": "a_11892238", "size_bytes": 21184} + ] +} diff --git a/docs/kicad-zcode-composite-controller-long-run.md b/docs/kicad-zcode-composite-controller-long-run.md new file mode 100644 index 00000000..6d10a924 --- /dev/null +++ b/docs/kicad-zcode-composite-controller-long-run.md @@ -0,0 +1,103 @@ +# 修好新聊天工具注入后,ZCode 独立完成了一块 31 元件 KiCad 板 + +> 日期:2026-11-04;KiCad plugin 0.12.3;标准 KiCad 10.0.6;成功任务使用 GLM-5.3 Low,用时 8 分 26 秒。机器数据见 [`13-run-summary.json`](assets/kicad-zcode-composite-long-run/13-run-summary.json),原始制造报告见 [`11-pcb-report.json`](assets/kicad-zcode-composite-long-run/11-pcb-report.json),最终电路规格见 [`12-final-spec.json`](assets/kicad-zcode-composite-long-run/12-final-spec.json)。 + +上一轮长程测试暴露了一个基础问题:新建 ZCode 聊天时,三个 KiCad skill 能被加载,但模型的 68 个工具里没有一个 KiCad MCP 工具;该模型又没有 `ToolSearch`,因此 `kicad_capabilities`、`pcb_build` 和 `kicad_live_*` 实际不可达。已有会话能用,fresh chat 不能用,这不是 server 崩溃,而是插件清单没有要求宿主主动加载 MCP server。 + +0.12.3 在 `mcpServers.kicad` 上声明 `alwaysLoad: true`,并让 `kicad_capabilities` 返回 `plugin_version`。修复后,同一项目的新聊天首个请求包含 94 个工具,其中 25 个来自 KiCad;首个工具调用可以直接是 `kicad_capabilities`。 + +![新聊天首轮已经出现 KiCad Capabilities 工具](assets/kicad-zcode-composite-long-run/01-fresh-chat-first-turn-pass.png) + +![能力结果明确返回 plugin 0.12.3](assets/kicad-zcode-composite-long-run/02-plugin-0.12.3-active.png) + +## 任务不是再跑一次示例,而是合成一块新板 + +验收要求 ZCode 只使用 KiCad plugin 工具,把三个内置示例合成为一块新的 `power_clock_shift_led_controller`: + +- 5 V 输入,以及 AP2112K-3.3 LDO、输入/输出去耦和 3.3 V 输出接口; +- NE555 无稳态振荡器,OUT 直接连接 74HC595 的 SRCLK; +- DATA、LATCH、RESET、QH' 串行接口,以及 QA–QH 八路并行接口; +- 八组 LED 与独立 470 Ω 限流电阻; +- 70 × 48 mm 双层板和四个 3.2 mm 安装孔。 + +模型先读取 `ne555_blinker`、`ldo_3v3_breakout`、`shift_register_leds`。其中本地已有一份内容不同的 NE555 spec,插件拒绝覆盖;模型改写到 `kicad/examples/` 后继续。随后用 `pcb_part_info` 核对 NE555D、74HC595、AP2112K-3.3 的符号引脚、封装焊盘和 pin↔pad 映射,没有凭记忆猜编号。 + +![三个示例和三个关键器件均通过 KiCad 工具读取](assets/kicad-zcode-composite-long-run/05-three-examples-and-part-info.png) + +最终 spec 有 31 个电气元件、4 个安装孔和 27 条网络。第一次 `pcb_check_spec` 找到 10 个 courtyard/安装孔 keepout 碰撞;第二次只剩 C1 与 J2 一处重叠;第三次达到 `ok=true`、0 error、0 warning。最终 spec artifact 是 `a_96931266`。 + +![三轮修改后 spec 校验通过并进入构建](assets/kicad-zcode-composite-long-run/06-spec-check-pass-and-build.png) + +## 自动布线也经过了三轮,而不是把未布通项当成成功 + +首轮构建没有 DRC error,但 U1.2 和 U3.8 的 GND 缝合过孔找不到空间,留下 2 个 unrouted。模型移动 C1、U3、C6 后重建,第二轮缩减到 U3.8 一个;再把 U3 上移 2 mm,第三轮达到 0 error、0 unconnected、0 unrouted。 + +| 指标 | 最终结果 | +| --- | ---: | +| 板尺寸 | 70 × 48 mm | +| 电气元件 / 含安装孔封装 | 31 / 35 | +| 网络 / 已布通信号网络 | 27 / 26 | +| 走线 / 过孔 / 铜区 / 焊盘 | 269 / 49 / 2 / 98 | +| 总线长 | 875.51 mm | +| 第三轮构建耗时 | 11.45 s | +| DRC error / unconnected / unrouted | 0 / 0 / 0 | + +![第三轮构建、双面渲染和独立 DRC 复查通过](assets/kicad-zcode-composite-long-run/07-drc-pass-render-checks-glb.png) + +![最终顶层渲染](assets/kicad-zcode-composite-long-run/board-top.png) + +![最终底层渲染](assets/kicad-zcode-composite-long-run/board-bottom.png) + +这块板比上一轮 `shift_register_leds` 明显更复杂:元件从 19 增至 31,走线从 88 增至 269,过孔从 14 增至 49,总线长从 216.99 mm 增至 875.51 mm。它还跨越 5 V/3.3 V 两个电源域,包含时钟源、LDO、移位寄存器、串行输入和并行输出。 + +## 3D 与制造产物来自同一个最终 PCB artifact + +Top/Bottom 渲染和 `kicad_checks` 复核完成后,插件导出带铜的 4,990,772 字节 GLB。31 个电气元件都有 3D 模型;无模型的 H1–H4 是四个安装孔,符合预期。 + +`pcb_export_fab(include_step=true)` 返回 `ready_to_order=true`、`blocking_problems=[]`。`kicad_export_files` 向 `kicad/out/composite-acceptance/` 写入 11 个新文件:PCB、spec、Gerber/钻孔 ZIP、KiCad 工程 ZIP、BOM、坐标、STEP、GLB、顶/底渲染和 JSON 报告。 + +| 产物 | Artifact | 大小 | +| --- | --- | ---: | +| PCB | `a_a8d0d129` | 331,898 B | +| Gerber + drill | `a_f94b4c78` | 57,763 B | +| KiCad project | `a_f3f11006` | 75,580 B | +| BOM | `a_d2885ad0` | 908 B | +| Position CSV | `a_a5bcd9cc` | 1,748 B | +| STEP | `a_83084fe6` | 1,839,697 B | +| GLB | `a_37e86ce1` | 4,990,772 B | +| PCB report | `a_2d4f3df9` | 22,080 B | +| Top / bottom PNG | `a_9ddf8ce6` / `a_24522023` | 82,058 / 61,425 B | + +最终仍有 4 条 `silk_over_copper` 警告,全部是 H1–H4 位号丝印被安装孔阻焊开窗裁切。它们不阻塞裸板制造,但量产前最好把四个位号移开。没有原理图,所以 ERC 不适用;`ready_to_order` 也不等同于电路、BOM、板厂 DFM 和实板上电已经由工程师签核。 + +## 真实 IPC 完成了写入、读回和恢复 + +`kicad_open_in_kicad` 在用户已有 PCB Editor 进程中打开新板后,`kicad_live_status` 返回 `available=true`、`matches_session=true`。面板显示 70 × 48 mm、31 parts、27 nets 和 DRC 0/0。 + +![ZCode 板卡面板显示最终板与实时连接](assets/kicad-zcode-composite-long-run/08-board-panel-live-link.png) + +基线快照中 R3 位于 `(14.0, 22.0)`,签名是 `207049d2b67d25d0`。模型把 R3 沿 X 轴移动 0.25 mm,立即读回 `(14.25, 22.0)`、`saved=false`,签名变为 `a1f69e2d1d8ef1c8`。 + +![R3 实时移动后签名变化,且没有保存](assets/kicad-zcode-composite-long-run/09-live-move-signature-changed.png) + +恢复到 `(14.0, 22.0)` 后,签名精确回到 `207049d2b67d25d0`。源 PCB artifact 与编辑目录中的文件 SHA-256 都是 `60acd5b4764c9610fe9a079e640987e6047aaad69db053b0491349672d75b288`,证明两次 IPC 写入没有落盘。 + +![最终 PASS、量化结果和恢复后的 IPC 证据](assets/kicad-zcode-composite-long-run/10-final-pass-and-ipc-restored.png) + +## 模型档位本身也是 harness 数据 + +同一提示在 GLM-5.3 Max 下尝试了两次,分别运行 148.253 秒和 138.802 秒。两次都在工具调用前持续推演引脚与布局,工具调用数为 0;第二次即使收到“首个动作只调用 `kicad_capabilities`”的跟进指令,仍然继续规划。切换到 Low 后,模型约 12 秒发出首个工具,随后连续完成 30 次 KiCad 调用。 + +这不是插件不可用:fresh-chat 请求里 25 个工具都在,Low 档也立即调用成功。它说明硬件长程任务的 harness 不应只比较最终板,还应记录首工具延迟、是否遵循工具优先顺序、失败后的收敛轮数,以及模型是否在有权威库数据时仍凭记忆推演。 + +## 测试途中又修了一个面板竞态 + +模型把 `kicad_board_view` 与 `kicad_open_in_kicad` 放在同一轮并行调用。实时状态已连接新板,但先返回的面板结果短暂保留上一块板的编辑路径。后端 `edit-session.json`、目标板匹配和 IPC 写入都正确,问题只在面板没有因为“编辑会话路径变化”自动刷新。 + +面板现在只要显示着一块板,就轮询 `kicad_edit_status`;检测到会话新建、替换或关闭便重新读取板卡摘要。这个回归点进入静态测试,避免以后再次出现“标题是新板、编辑横幅还是旧路径”的混合状态。 + +## 结论 + +本轮证明了两件事。第一,0.12.3 修复了 fresh chat 的工具可达性:不需要先找到一条旧聊天,也不依赖模型支持 `ToolSearch`。第二,ZCode 能在一个连续任务里读取三个参考设计、核对库引脚、合成新 spec、迭代消除布局和布线问题、生成制造包,并通过真实 KiCad IPC 做一次未保存的双向往返。 + +最终判定是 PASS。但工程边界仍然清楚:没有原理图/ERC、没有 SPICE 或时序仿真、没有厂家 MPN 和供货校验、没有板厂专属 DFM,也没有实板上电。插件已经把“能自动证明的部分”闭环;余下判断仍应交给硬件工程师。 diff --git a/docs/kicad-zcode-live-ipc-acceptance.md b/docs/kicad-zcode-live-ipc-acceptance.md new file mode 100644 index 00000000..404b7298 --- /dev/null +++ b/docs/kicad-zcode-live-ipc-acceptance.md @@ -0,0 +1,102 @@ +# 让 ZCode 真正操作 KiCad:从实时 IPC 到制造文件的端到端验收 + +> 验收对象:ZCode KiCad plugin 0.12.2;环境:macOS、ZCode Dev、KiCad 10。本文记录的是一次真实的 Agent 长程任务,不是单元测试截图合集。 + +硬件 Agent 的演示很容易停在“生成了一份看起来像 PCB 的文本”。真正有用的插件还要回答另外几个问题:它能不能找到用户实际安装的 EDA?能不能确认自己连到的是当前工程,而不是另一个 KiCad 窗口?一次实时改动能不能被立即读回、撤回并保持未保存?最后,DRC、3D 模型和制造文件能不能形成同一条可追溯链路? + +这次验收围绕一块 NE555 闪烁灯板展开。ZCode 只使用 KiCad plugin 提供的工具,依次打开真实 PCB Editor、读取实时快照、执行检查、导出 3D 模型和制造文件,并在结束时核对产物谱系。最终结果是:目标板实时连接成立,DRC 为 0 错误 / 0 警告 / 0 未连接,9 个封装全部进入 GLB,制造包没有阻塞项。 + +![ZCode 执行实时快照、DRC、3D 和制造文件导出的过程](assets/kicad-zcode-live-ipc/01-zcode-complex-task-progress.jpg) + +## 为什么不能只看 “socket 可达” + +KiCad 10 的实时 API 通过本机 Unix socket 提供。最容易出现的误判是:API 能响应,甚至能返回 KiCad 版本,但用户要求打开的板子因为工程锁或恢复对话框并没有真正进入 PCB Editor。 + +因此插件把结果拆成两层: + +- `launched` 只说明精确的 PCB Editor 子进程已经启动; +- `live_ready` 还要求这个进程的 socket 可用,并且 `boards_open` 中确实存在本会话导出的目标板。 + +锁定态测试正好覆盖了这个边界。截图中进程已启动,API 也真实响应了 KiCad 10.0.6,但 `available=false`、`boards_open=[]`,所以 `live_ready=false`。插件没有把“旧 socket 还活着”或“另一个 KiCad 窗口存在”误报为目标板已连接。 + +![工程锁定时,launched 为 true,但 live_ready 仍为 false](assets/kicad-zcode-live-ipc/04-zcode-lock-detection.jpg) + +这条判断对 Agent 很重要。文件导出可以继续工作,但任何实时写操作都必须等到目标板匹配后才能执行;否则一次看似无害的元件移动,就可能落在用户正在编辑的另一块板上。 + +## 一个插件,对接两种 KiCad 发行版 + +插件提供 `auto`、`standard`、`huaqiu` 三种选择。默认的 `auto` 会在系统和用户 Applications 目录发现 KiCad 10,读取安装内容识别标准版或华秋版,再选择与请求匹配的最新版本。用户显式填写 app 路径时,该路径严格优先,配置错误不会被静默回退掩盖。 + +两种发行版共用同一套 PCB 生成、检查、渲染、导出和实时 IPC 能力;华秋版额外开放公共器件数据库的只读搜索、详情、供货和模型比较工具。它复用发行版中已经标准化的 `@huaqiu/part-search`,但不会启动 DSH 作为第二套 Agent harness。这样,ZCode 保持唯一的任务编排者,华秋能力作为受约束的工具进入同一条证据链。 + +自动识别、显式版本选择和缺失依赖都有结构化结果。基础实时用例已经分别在标准 KiCad 10.0.6 和华秋 KiCad 10.0.7 上完成:进程/socket 选择、快照、移动 0.25 mm、立即回读、移回原位,全程不保存。本次更长的制造验收任务运行在标准 KiCad 10.0.6;华秋版没有被这一条长程任务重复覆盖,因此不把两者混写成同一项证据。 + +## 实时写入必须可读回、可恢复、默认不保存 + +插件有意只提供一个实时写工具:`kicad_live_move_footprint`。它一次只移动一个封装,可选修改角度,在 KiCad 中形成一个可撤销步骤,但不调用保存。读取则由 `kicad_live_snapshot` 完成,避免用“原地移动”探测位置而污染撤销历史。 + +验收时先读取 C2 的位置 `(17, 11)`,再把 X 坐标改为 `17.25`,立即读取到新位置,最后移回 `17`。恢复后的签名是 `2c2a768043671620`;以该签名再做增量快照,结果是 `unchanged=true`,详细对象被省略。磁盘上的板文件哈希在任务前后保持一致,证明这组 IPC 操作没有偷偷保存。 + +![C2 移动并恢复后,增量快照确认板状态未再变化](assets/kicad-zcode-live-ipc/03-zcode-live-move-restore.jpg) + +这种约束比“Agent 可以控制 GUI”更重要:用户仍然在 KiCad 里看到变化、决定是否接受,并由自己按下保存;插件不会夺走工程文件的最终控制权。 + +## 长程任务:从当前板到可制造产物 + +用于验收的 NE555 板是 34 mm × 22 mm、双层,共 9 个封装、61 条走线、9 个过孔、2 个铜区、24 个焊盘和 7 个网络。 + +![NE555 验收板的顶层渲染](assets/kicad-zcode-live-ipc/05-ne555-board-top.png) + +ZCode 在一个连续任务中完成了六步: + +1. 用 `kicad_info` 建立初始产物清单; +2. 用 `kicad_open_in_kicad` 打开指定 PCB artifact; +3. 用 `kicad_live_status` 和 `kicad_live_snapshot` 校验目标会话与实时板状态; +4. 用 `kicad_checks` 执行 DRC; +5. 用 `pcb_export_glb` 验证 3D 模型覆盖; +6. 用 `pcb_export_fab` 生成 Gerber/钻孔、KiCad 工程、BOM、坐标文件和制造报告,再用 `kicad_info` 核对新增产物。 + +结果如下: + +| 检查项 | 结果 | +| --- | --- | +| 实时会话 | `matches_session=true`,目标板计数与 artifact 一致 | +| DRC | 0 errors、0 warnings、0 unconnected | +| ERC | 不适用;该输入只有 PCB,没有原理图 | +| 3D | 9/9 封装有模型,无缺失模型 | +| 制造包 | `ready_to_order=true`,`blocking_problems=[]` | +| 新增产物 | GLB、Gerber/钻孔、工程、BOM、坐标文件、制造报告,共 6 项 | + +![ZCode 给出的可制造结论、产物清单和风险说明](assets/kicad-zcode-live-ipc/02-zcode-release-audit-result.jpg) + +“通过”不等于隐藏风险。任务明确保留了三个结论:没有原理图就无法做 ERC;J1 伸出板边,需要结合外壳复核机械间隙;3D 模型尺寸和 BOM 料号仍要对照实物与 datasheet。这些不是工具失败,而是 PCB 自动化不应越过的工程判断边界。 + +## 实现中真正修掉的三个问题 + +第一,启动器以前容易把“有 KiCad socket”当作“目标板已经打开”。现在它监视精确启动的 PCB Editor 子进程与 `api-.sock`,并再次核对目标板路径。 + +第二,真实测试环境里曾出现 artifact 来自另一个测试 project 的情况。插件正确拒绝了跨 project artifact;测试随后把同一批产物复制到当前 project,而不是放宽隔离规则。对 Agent 工具而言,测试数据不方便不是削弱边界的理由。 + +第三,并发执行完整测试套件时,故意立即退出的假 PCB Editor 偶尔因为 CPU 调度延迟,在过短的观察窗口里被当成健康进程。测试现在为这类退出场景使用独立的稳定观察窗口,避免机器负载改变结论。完整测试随后重新运行通过。 + +## 安全边界与当前限制 + +实时 API 没有密码或令牌,同一 macOS 用户下的进程都可能访问它。插件因此遵守最小能力原则:socket 路径和 KiCad 发放的令牌不进入面板或工具结果;实时写入只允许单封装移动;不提供保存、删除、恢复、改变选择、执行任意编辑器动作或停止 KiCad 的工具。用户只应在需要实时联动时打开 KiCad API。 + +当前版本还有明确限制:自动启动只支持 macOS;实时标签页依赖轮询,KiCad API 也不能直接回答“是否存在未保存修改”;由 JSON spec 生成的是双层裸板,没有自动生成原理图,因此此类任务没有 ERC;高压、RF、HDI 和精确机械配合仍需要工程师审查。 + +## 可复现的仓库验收 + +代码级验收覆盖 Python 启动器与实时 IPC 测试、完整前端/服务端测试、构建、类型检查、lint、插件清单校验和发布包构建。仓库中的核心命令是: + +```bash +pnpm test +pnpm build +pnpm typecheck +pnpm lint +python3 scripts/validate.py +python3 scripts/build_dist.py +git diff --exit-code -- marketplace.json dist/marketplace.json dist/marketplace-cn.json +``` + +自动化测试负责证明边界条件可以重复;真实 ZCode + KiCad 长程任务负责证明这些工具能在同一个 Agent 上下文中协作。两类证据缺一不可。对硬件 Agent 来说,最重要的也不是“模型能画板”,而是每一次读取、写入、检查和导出都能说明自己操作了哪一个工程,并把不能自动判断的风险原样交还给工程师。 diff --git a/docs/kicad-zcode-shift-register-long-run.md b/docs/kicad-zcode-shift-register-long-run.md new file mode 100644 index 00000000..a3567813 --- /dev/null +++ b/docs/kicad-zcode-shift-register-long-run.md @@ -0,0 +1,154 @@ +# ZCode × KiCad 复杂长程验收:74HC595 八路 LED 状态板 + +> 日期:2026-11-03;插件:KiCad 0.12.2;模型:GLM-5.3 Max;成功任务用时约 4 分 37 秒。本文保留失败、恢复和最终结果的完整证据,不只记录“通过”的部分。 + +本轮选择插件内置的 `shift_register_leds` 作为基线。它包含 74HC595、8 组 LED 与限流电阻、去耦电容和接口排针,共 19 个器件;相比上一轮 NE555 板,器件数从 9 增至 19、网络从 7 增至 22、走线从 61 增至 88、板面积从 748 mm² 增至 1,536 mm²。 + +验收覆盖能力诊断、spec 生成和校验、自动布局布线、双面渲染、真实 KiCad 打开、实时 IPC 读写往返、DRC、含铜 GLB、STEP、Gerber/钻孔、BOM、坐标文件、制造报告、文件导出和 artifact lineage。 + +机器可读数据见 [`17-run-summary.json`](assets/kicad-zcode-shift-register/17-run-summary.json),插件生成的原始制造报告见 [`16-pcb-report.json`](assets/kicad-zcode-shift-register/16-pcb-report.json)。 + +## 0. 首次尝试:skill 可见,但 MCP 工具没有注入 + +第一次在项目中新建聊天时,ZCode 能加载 `kicad-board`、`kicad-standard`、`kicad-huaqiu` 三个 skill,但工具列表中没有 `kicad_capabilities`、`pcb_build`、`kicad_live_*` 等 KiCad MCP 工具。模型错误探测过 Documents、PDF 和 Spreadsheets 的 `get_view`,并执行过一次无副作用的 `echo`,随后主动停止。5 分 23 秒后,该轮被判定为会话配置阻塞。 + +![首次新聊天中 skill 已加载,但 KiCad MCP 工具未注入](assets/kicad-zcode-shift-register/03-tool-registration-failure.png) + +插件服务进程实际存在,因此不是 server 二进制崩溃。切换到此前已经成功绑定 KiCad MCP 的项目聊天后,同一任务立即出现 `MCP Kicad · Capabilities`,说明问题位于“新聊天的工具注入/会话绑定”,而不是 KiCad plugin 的工具实现。这是本轮最重要的 DevEx 缺陷,后续应单独修复。 + +## 1. 能力诊断与 spec + +`kicad_capabilities` 返回: + +| 字段 | 结果 | +| --- | --- | +| requested edition | `auto` | +| resolved edition | `standard` | +| distribution | `official` | +| KiCad | 10.0.6 | +| core / edition readiness | `true / true` | +| 初始实时 IPC | 不可用;当时没有目标 PCB Editor 打开 | + +随后 `pcb_spec_example(name=shift_register_leds)` 生成 48 × 32 mm 双层板 spec:19 个器件、22 个网络。`kicad_check_spec_file` 返回 0 错误、0 警告,58 个引脚—网络映射全部成立,spec artifact 为 `a_fd7bda4d`。 + +![能力诊断完成,并生成 19 器件、22 网络的 spec](assets/kicad-zcode-shift-register/05-capabilities-and-spec.jpg) + +## 2. 自动布局布线与 DRC + +`pcb_build` 在 3.983 秒内完成构建,PCB artifact 为 `a_16215bd2`: + +| 指标 | 数值 | +| --- | ---: | +| 尺寸 | 48 × 32 mm | +| 器件 | 19 | +| 已布通网络 | 21 | +| 走线 | 88 | +| 过孔 | 14 | +| 铜区 | 2 | +| 总线长 | 216.99 mm | +| DRC 错误 / 未连接 | 0 / 0 | +| DRC 警告 | 36 | + +36 条警告并非电气开路,而是丝印可读性问题:12 条 `silk_overlap` 和 24 条 `silk_over_copper`。它们集中在 R1–R7、D1–D7 的密集纵列,后续制造报告仍允许下单,但量产前应调整位号。 + +![自动布线成功,同时暴露 36 条丝印警告](assets/kicad-zcode-shift-register/06-build-result.jpg) + +## 3. 双面渲染与板卡面板 + +顶层渲染 artifact `a_d98bb6da`(56,901 字节),底层 `a_81f56144`(25,088 字节)。板卡面板正确显示 U1、C1、J1 和 8 组 LED/电阻的位置及走线。 + +![ZCode KiCad 面板中的顶层板和元件表](assets/kicad-zcode-shift-register/07-render-and-open.jpg) + +![最终顶层渲染](assets/kicad-zcode-shift-register/14-board-top.png) + +![最终底层渲染](assets/kicad-zcode-shift-register/15-board-bottom.png) + +## 4. 实时 IPC 双向往返 + +`kicad_open_in_kicad` 启动了新的精确 PCB Editor 子进程,随后 `kicad_live_status` 与 `kicad_live_snapshot` 返回: + +- `launched=true` +- `live_ready=true` +- `matches_session=true` +- 19 封装、88 走线、14 过孔、2 铜区、56 焊盘、22 网络 +- C1 初始位置 `(29.0, 6.0)` mm +- 基准签名 `a48d6c7accf43673` + +ZCode 将 C1 的 X 坐标右移 0.25 mm。立即读回得到 `(29.25, 6.0)`,`saved=false`,签名变为 `4a2a371ef4da6164`。 + +![C1 实时移动 0.25 mm,并由快照立即读回](assets/kicad-zcode-shift-register/08-live-ipc-move.jpg) + +随后 C1 被移回 `(29.0, 6.0)`,签名精确恢复为 `a48d6c7accf43673`。以恢复后的签名做增量快照,返回 `unchanged=true`。 + +![C1 恢复后签名回到基线,增量快照 unchanged=true](assets/kicad-zcode-shift-register/09-live-ipc-restore.jpg) + +源 PCB artifact 与编辑目录中的板文件 SHA-256 都是 `52606e69c7a3ad30e4a7fe146276c999f4a23a8622e0d886f2d7ec620d375739`,证明两次实时写入没有保存到磁盘。需要注意:两个移动步骤仍保留在 KiCad 撤销历史中;如需彻底清理编辑器内存状态,可在 KiCad 中撤销两次。 + +## 5. 检查与含铜 3D 模型 + +`kicad_checks` 再次得到 0 错误、0 未连接和同样的 36 条丝印警告。没有 `.kicad_sch`,因此 ERC 不适用。 + +`pcb_export_glb(include_copper=true)` 生成 `a_751b5dac`,大小 2,225,900 字节。19/19 器件具有 3D 模型,`parts_without_model=[]`;GLB 包含器件、铜、焊盘、过孔、丝印和阻焊 6 类网格。 + +![DRC 复检和含铜 GLB 导出结果](assets/kicad-zcode-shift-register/10-checks-and-glb.jpg) + +## 6. 制造文件与 artifact lineage + +`pcb_export_fab(include_step=true)` 返回 `ready_to_order=true`、`blocking_problems=[]`,并再次得到相同 DRC 结果。 + +| 产物 | Artifact | 大小 | +| --- | --- | ---: | +| spec | `a_fd7bda4d` | 6,686 B | +| PCB | `a_16215bd2` | 159,435 B | +| 顶层渲染 | `a_d98bb6da` | 56,901 B | +| 底层渲染 | `a_81f56144` | 25,088 B | +| 含铜 GLB | `a_751b5dac` | 2,225,900 B | +| Gerber + drill | `a_6d068556` | 29,625 B | +| KiCad project | `a_cd0944ae` | 35,004 B | +| BOM | `a_212ae0fc` | 369 B | +| Position CSV | `a_df5a7bf0` | 1,068 B | +| STEP | `a_4ded4c8d` | 930,047 B | +| PCB report | `a_11892238` | 21,184 B | + +`kicad_export_files` 将 9 个交付文件导出到 `kicad/out/shift_register_acceptance/`:6 个制造文件、GLB 和两张渲染图。最终 `kicad_info` 显示 artifact 总数从 10 增至 21,新增 lineage 闭合为: + +`a_fd7bda4d` spec → `a_16215bd2` PCB → 双面渲染 / GLB / 6 项制造产物。 + +![制造文件生成、文件导出与 lineage 核对](assets/kicad-zcode-shift-register/11-fabrication-export.jpg) + +![ZCode 汇总的十阶段结果表](assets/kicad-zcode-shift-register/12-final-summary.jpg) + +## 7. 结论与风险边界 + +![ZCode 最终给出的风险与不能自动证明事项](assets/kicad-zcode-shift-register/13-final-risks.jpg) + +本轮证明了 ZCode 能通过 plugin 完成复杂度高于 NE555 的完整 KiCad 闭环,并能在同一任务中把实时写入恢复到原状态。制造输出没有阻塞项,但“可下单”不等于“设计已经工程签核”: + +1. 36 条丝印警告应在量产前处理,特别是 R/D 纵列位号重叠和被阻焊裁切的问题。 +2. 没有原理图和 ERC,74HC595 的 OE、SRCLR 上拉/接地策略及完整逻辑仍需人工复核 spec。 +3. 没有仿真、实板上电和 LED 顺序点亮测试。 +4. BOM 只有通用值,没有厂家 MPN,采购选型尚未自动化。 +5. DRC 是插件规则集,不代表任意板厂的专属 DFM 审查。 +6. 新聊天出现“skill 有、MCP 工具无”的注入问题;在修复前,长程任务应从已确认工具可用的聊天开始。 + +综合结论:IPC 双向读写、恢复、检查、3D 和制造导出链路通过;制造文件可以交给板厂,但丝印、原理图逻辑、BOM 与板厂 DFM 仍需人工签核。 + +## 截图索引 + +| 文件 | 阶段 | +| --- | --- | +| `00-zcode-new-task.png` | 新任务入口 | +| `01-task-start.png` | 首轮任务启动 | +| `02-plan-and-capabilities.png` | 首轮计划与工具探测 | +| `03-tool-registration-failure.png` | 新聊天 MCP 工具未注入 | +| `04-second-run-start.jpg` | 已绑定聊天中重试 | +| `05-capabilities-and-spec.jpg` | 能力诊断与 spec | +| `06-build-result.jpg` | 构建、布线、首次 DRC | +| `07-render-and-open.jpg` | 板卡面板、渲染、打开 KiCad | +| `08-live-ipc-move.jpg` | C1 实时移动与读回 | +| `09-live-ipc-restore.jpg` | C1 恢复与增量快照 | +| `10-checks-and-glb.jpg` | DRC 复检与含铜 GLB | +| `11-fabrication-export.jpg` | STEP、制造文件和导出 | +| `12-final-summary.jpg` | 十阶段结果表 | +| `13-final-risks.jpg` | 风险与不能自动证明事项 | +| `14-board-top.png` / `15-board-bottom.png` | 最终双面渲染 | diff --git a/external_plugins/kicad/.zcode-plugin/plugin.json b/external_plugins/kicad/.zcode-plugin/plugin.json index 665a61c0..6be9d4fd 100644 --- a/external_plugins/kicad/.zcode-plugin/plugin.json +++ b/external_plugins/kicad/.zcode-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "kicad", - "version": "0.6.1", - "description": "KiCad 10 inside the conversation: agents design 2-layer boards from a circuit spec (real KiCad libraries, auto-route, DRC, Gerber/BOM/CPL); the side panel shows the 3D render and DRC verdict; one click opens the board in the real KiCad PCB Editor and every save syncs back.", + "version": "0.12.3", + "description": "Automatically connects to installed official or Huaqiu KiCad 10. Both design, check, render, and export boards; Huaqiu also adds safe public-part search and model comparison without starting DSH.", "author": { "name": "冯小平", "url": "https://github.com/fxp" @@ -16,21 +16,30 @@ "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" ], "cwd": "${ZCODE_PROJECT_DIR}", + "alwaysLoad": true, "timeoutMs": 300000, "env": { "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}", "ZCODE_PLUGIN_DATA": "${ZCODE_PLUGIN_DATA}", + "ZCODE_KICAD_EDITION": "${user_config.edition}", "ZCODE_KICAD_APP": "${user_config.kicadApp}", "ZCODE_KICAD_PYTHON": "${user_config.pythonPath}" } } }, "userConfig": { + "edition": { + "type": "string", + "default": "auto", + "required": true, + "title": "KiCad 版本", + "description": "默认 auto:自动发现并识别标准或华秋 KiCad。也可填写 standard 或 huaqiu,只选择对应发行版;显式设置不会静默切换。" + }, "kicadApp": { "type": "file", "default": "", "title": "KiCad.app 路径", - "description": "可选。KiCad 10 的 KiCad.app 完整路径。留空使用 /Applications/KiCad/KiCad.app;本插件用其中的 kicad-cli、自带 Python 和官方符号/封装库。" + "description": "可选。KiCad 10 的 KiCad.app 完整路径。留空时自动搜索系统和用户 Applications 目录并选择匹配发行版的最新安装;填写后该路径严格优先。" }, "pythonPath": { "type": "file", @@ -55,8 +64,8 @@ ] }, "description_i18n": { - "en": "KiCad 10 inside the conversation: agents design 2-layer boards from a circuit spec (real KiCad libraries, auto-route, DRC, Gerber/BOM/CPL); the side panel shows the 3D render and DRC verdict; one click opens the board in the real KiCad PCB Editor and every save syncs back.", - "zh-CN": "把 KiCad 10 嵌入对话:Agent 用电路 spec 设计双层板(真实 KiCad 库、自动布线、DRC、Gerber/BOM/贴片坐标),侧栏面板显示 3D 渲染和 DRC 结论;一键在真实的 KiCad PCB Editor 里继续编辑,保存后自动同步回对话。" + "en": "Automatically connects to installed official or Huaqiu KiCad 10. Both design, check, render, and export boards; Huaqiu also adds safe public-part search and model comparison without starting DSH.", + "zh-CN": "自动识别并连接已安装的标准或华秋 KiCad 10:两者均可设计、检查、渲染和导出电路板;华秋版还提供安全的公共器件搜索与模型比较,全程不启动 DSH。" }, "keywords": [ "kicad", diff --git a/external_plugins/kicad/README.md b/external_plugins/kicad/README.md index 3ff509ac..243139ac 100644 --- a/external_plugins/kicad/README.md +++ b/external_plugins/kicad/README.md @@ -3,9 +3,19 @@ KiCad 10 inside the conversation. Agents design a two-layer board from a JSON circuit spec — real KiCad symbol/footprint libraries, auto-route, DRC, Gerber/BOM/CPL — and the **KiCad board** side panel shows the 3D render, the DRC verdict, the part list and every artifact. +The plugin has two editions backed by one PCB engine, plus an automatic selector: + +| Plugin edition | KiCad distribution | Additional readiness checks | +| --- | --- | --- | +| `auto` (default) | Newest detected official or Huaqiu KiCad 10 | Resolves the edition from the installed app before enabling tools | +| `standard` | Official KiCad 10 | Core CLI, pcbnew Python, symbols and footprints | +| `huaqiu` | Huaqiu KiCad 10 | Core checks, bundled Huaqiu components, and the native public-part-database adapter | + +With an empty *KiCad.app path*, `auto` searches the system and user Applications directories, identifies each app without starting it, and selects the newest installation. Choosing `standard` or `huaqiu` filters automatic discovery to that distribution. An explicit app path always wins, even when it is missing, so a configuration error is reported instead of silently switching installations. + ## What you need -* macOS with **KiCad 10** (`/Applications/KiCad/KiCad.app`; or set *KiCad.app path* in the plugin settings). +* macOS with **official KiCad 10** or **Huaqiu KiCad 10** in the system/user Applications directory, or set an exact *KiCad.app path* in the plugin settings. * **uv** (recommended: dependencies are fetched on first start) or a Python with `fastmcp>=4,<5`, `pydantic`, `numpy` (setting *Python with fastmcp*). ## Use @@ -13,6 +23,23 @@ and the **KiCad board** side panel shows the 3D render, the DRC verdict, the par Ask: "Design a 555 LED blinker board with KiCad, check DRC, render it and open the board panel." The sample case is an NE555 astable flasher (about 1 Hz, 9 parts, 34 × 22 mm); the agent starts from `pcb_spec_example`, then `kicad_check_spec_file`, `pcb_build`, `pcb_render`, `pcb_export_fab`, `kicad_export_files` and `kicad_board_view` (see `skills/kicad-board/SKILL.md`). Open the panel manually from the session panel list at any time. +On first use, or after switching KiCad distributions, call `kicad_capabilities`. Continue only when `edition_ready=true`. It read-only reports automatic/explicit selection, every detected candidate, `requested_edition`, `resolved_edition`, the official/Huaqiu distribution, mismatch status, version, CLI, libraries, pcbnew Python, live IPC, bundled Huaqiu DSH components, currently available tools, and structured missing dependencies. Bundled DSH is detected for diagnostics only; the plugin never starts a second agent harness. + +The MCP server is eagerly loaded, so all 25 KiCad tools are present on the first model request of a fresh chat, including with models that do not provide deferred tool search. `kicad_capabilities` also reports the installed `plugin_version`, which lets an acceptance run prove which package actually served the call. + +### Huaqiu edition: native part lookup + +When `resolved_edition` is `huaqiu` and it is ready, these read-only ZCode tools use the normalized `@huaqiu/part-search` library already inside Huaqiu KiCad: + +* `search_hqsch_parts`: search by MPN, manufacturer, category, or keyword, with optional symbol/footprint/3D/simulation/supplier requirements. +* `get_hqsch_part`: component details, attributes, documents, images, lifecycle, and model metadata. +* `get_hqsch_part_models`: symbol, footprint, 3D, and simulation model metadata and URLs (metadata only; nothing is installed). +* `get_hqsch_supply_chain`: stock, MOQ, lead time, distributor links, currency, and price breaks for up to 50 parts. +* `resolve_hqsch_part_for_kicad`: fetch one selected part's normalized detail, search the installed KiCad libraries, verify symbol footprint filters and same-numbered pin/pad mapping, and return ranked candidates plus `spec_part_fields`. +* `compare_hqsch_models_with_kicad`: explicitly download the selected part's public `.kicad_sym` and `.kicad_mod` into memory and compare them with one resolver candidate: pin names/numbers, numbered-pad geometry and sizes, and courtyard dimensions. + +These calls go directly to Huaqiu's unauthenticated public endpoint at `https://kiapi.eda.cn`. They do not start DSH, load DSH skills, place an order, install a model, or write to the project. Only the explicit comparison tool downloads model text: it accepts HTTPS from `file.eda.cn` / `file1.eda.cn`, refuses redirects, caps each file at 2 MiB, parses it as untrusted data in memory, and returns hashes rather than model contents. A model match is stronger structural evidence, but both the resolver and comparison deliberately leave electrical pinout and exact physical package confirmation to datasheet review. The Standard edition rejects these tools explicitly. + ## The panel: tabs next to the real KiCad windows The panel is a companion to KiCad's own windows (PCB Editor, Schematic Editor), not an embedded editor. Its tabs show what `kicad-cli` produces headlessly for the newest board (the one you edited in KiCad, once you saved): @@ -27,13 +54,14 @@ The panel is a companion to KiCad's own windows (PCB Editor, Schematic Editor), ## Live link to the running PCB Editor (KiCad API) -With KiCad's own **"Enable KiCad API"** preference switched on, the panel and the agent can talk to the PCB Editor you already have open, without waiting for ⌘S: +With KiCad's own **"Enable KiCad API"** preference switched on, *Open in KiCad* starts the selected distribution's exact PCB Editor process and waits for its own API socket. The panel and the agent can then talk to that editor without waiting for ⌘S. Re-opening an already connected session reuses it instead of starting a duplicate: * **Live** indicator in the panel header and a **Live** tab: the parts (reference, footprint, value, x, y, rotation, side), nets and your current selection, read from the editor every 1.5 s while the tab is open (an unchanged board costs almost nothing). Unsaved moves show up at once, and a Δ column shows what changed since the tab was opened. Positions use the same frame as the spec: mm from the board's top-left corner. * `kicad_live_status` (agent and panel): is the API reachable, which board is open, is it this session's board. If not, one sentence says why and names the setting; every other tab and the ⌘S round trip keep working. If the editor has a different file open the panel says so instead of showing it as the session board. +* `kicad_live_snapshot` (agent and panel): a read-only snapshot of current parts, nets, selection and counts. The agent uses it to read positions before and after an adjustment, without adding a no-op move to KiCad's undo history. * `kicad_live_move_footprint` (agent only): moves **one** footprint (and optionally sets its rotation) in the open editor, as one undoable KiCad step (⌘Z). **Nothing is saved**: you press ⌘S as before and the panel imports the save and runs DRC. It refuses unless the editor has exactly this session's board open. There is deliberately no "save" tool. -**Security.** The KiCad API is a plain local Unix socket (`/tmp/kicad/api.sock`, `api-.sock` for further editors). KiCad asks for no password or token; only your macOS user can connect to the socket file, but *every* process of that user can: your shell, scripts, and a ZCode agent that may run shell commands or Python, with or without this plugin. The protocol has requests for all of the following (this plugin's tests exercised only reads, one move, undo and a zoom action): such a process can read the whole board, change or delete anything in it, save the board or a copy of it to any path it can write (`save_as` with overwrite), revert your unsaved edits, change the selection, run any editor action and (client library permitting) start export jobs. Switch the preference on only while you want it. This plugin uses the socket for reads (documents, footprints, tracks, vias, zones, pads, nets, selection) and for the one commit above; it never saves, reverts, deletes, changes the selection, runs actions or starts or stops KiCad, and it keeps the socket path and the token KiCad hands out inside the server process: neither goes to the panel page, a tool result or an error message. +**Security.** The KiCad API is a plain local Unix socket (`/tmp/kicad/api.sock`, `api-.sock` for further editors). KiCad asks for no password or token; only your macOS user can connect to the socket file, but *every* process of that user can: your shell, scripts, and a ZCode agent that may run shell commands or Python, with or without this plugin. The protocol has requests for all of the following (this plugin's tests exercised only reads and one move commit): such a process can read the whole board, change or delete anything in it, save the board or a copy of it to any path it can write (`save_as` with overwrite), revert your unsaved edits, change the selection, run any editor action and (client library permitting) start export jobs. Switch the preference on only while you want it. This plugin uses the socket for reads (documents, footprints, tracks, vias, zones, pads, nets, selection) and for the one commit above; it never saves, reverts, deletes, changes the selection, runs actions or stops KiCad. `kicad_open_in_kicad` is the sole operation that starts an editor. The socket path and the token KiCad hands out stay inside the server process: neither goes to the panel page, a tool result or an error message. ## A 3D model for other tools @@ -41,19 +69,19 @@ With KiCad's own **"Enable KiCad API"** preference switched on, the panel and th ## Keep editing in the real KiCad -**Open in KiCad** in the panel (or the agent calling `kicad_open_in_kicad`) exports the board to `./kicad/edit//` — an ordinary KiCad project you own — and opens it in your local **KiCad PCB Editor**. +**Open in KiCad** in the panel (or the agent calling `kicad_open_in_kicad`) exports the board to `./kicad/edit//` — an ordinary KiCad project you own — and opens it in a fresh process from the selected Standard or Huaqiu **KiCad PCB Editor**. It runs that distribution's exact `pcbnew` executable instead of asking Launch Services to reuse an unrelated standalone editor, then verifies both the process socket and the requested open board. The result separates `launched` from `live_ready`; a project-lock or recovery dialog can make the first true while the second remains false, and `launch_note` says what to check. Press ⌘S in KiCad and the panel imports the save by itself (a new board artifact plus a DRC run) and shows "edited in KiCad"; the agent can do the same with `kicad_sync_edits`. Re-opening never overwrites what you saved. Automatic launch is macOS-only for now. ## Known issues / not proven -* **Live link, not proven:** whether KiCad's canvas redraws right away after `kicad_live_move_footprint` was not seen with eyes (the editor's own read-back shows the new position and ⌘Z restores the old one, tested on a separate KiCad instance, not on yours). The API has no "unsaved changes" request and no change notification, so the Live tab polls and cannot tell saved from unsaved edits. It needs `kicad-python` (fetched by `uv` on first start; without it the plugin starts without the live link) and was tried on KiCad 10.0.6 on macOS only. Writes were only ever tried on a throwaway board copy in a separate KiCad process. +* **Live-link limits:** the API has no "unsaved changes" request and no change notification, so the Live tab polls and cannot tell saved from unsaved edits. It needs `kicad-python` (fetched by `uv` on first start; without it the plugin starts without the live link). Process/socket selection, live snapshots, a 0.25 mm move, immediate read-back and a restoring move were exercised without saving on throwaway board copies in both official KiCad 10.0.6 and Huaqiu KiCad 10.0.7 on macOS. Canvas redraw was not judged visually. * **Not an embedded editor.** The tabs are rendered by `kicad-cli`, not by KiCad's own canvas, and are separate from the PCB/Schematic Editor windows: edits still travel through the file (⌘S in KiCad, then the panel imports the save). The tab views do not follow your cursor or selection in KiCad. * **Schematic tab and ERC need a schematic you drew.** ERC runs with KiCad's stock library tables on a private config, not your own library tables: a symbol from a custom library shows up as a library warning. Several sheets are listed in a selector; only single-sheet schematics were tried. * **Layers, Schematic and Library are SVG from `kicad-cli`** in KiCad's default colour theme, not your theme. A big schematic is about 1 MB of SVG per sheet: the cat-feeder rev A schematic (0.9 MB) rendered in the real desktop sandbox test (real Electron host, CSP and bridge); a much larger design was not tried, and nothing was tried by hand in the ZCode Dev window. * **GLB**: tested on the sample board (9 parts, positions/rotations/bottom side checked against pcbnew) and the part table only describes parts that have a library 3D model. Mesh names are footprint names; the designator is the node name. -* **Settings of earlier versions.** Up to 0.4.2 the plugin ran `kicad-cli version` on your own KiCad settings, and KiCad then rewrote one value in `~/Library/Preferences/kicad/10.0/kicad_common.json` (the folder file dialogs start in). From 0.5.0 every KiCad program the plugin starts uses a private config; in a test of that call only this one value changed, and the GUI you open keeps your own settings. +* **Settings of earlier versions.** Up to 0.4.2 the plugin ran `kicad-cli version` on your own KiCad settings, and KiCad then rewrote one value in `~/Library/Preferences/kicad/10.0/kicad_common.json` (the folder file dialogs start in). From 0.5.0 every headless KiCad command uses a private config. The GUI intentionally keeps your own settings, including "Enable KiCad API". -* **"Open in KiCad" says KiCad was not started / PCB Editor crashes right away (macOS).** A KiCad copied into `/Applications` by hand or from a download keeps the download quarantine flag, and macOS then runs only the nested `pcbnew.app` from a temporary copy ("App Translocation"), where `libkicommon.*.dylib` is missing ("Library not loaded" in the crash report). The plugin waits for `pcbnew` to stay running and, if it does not, shows the reason and this fix, which you run yourself (it changes a security attribute, so the plugin never does): `xattr -dr com.apple.quarantine /Applications/KiCad`, then press *Open in KiCad* again. The "Editing in KiCad" banner only means an edit session exists; trust the warning line under the title over it. +* **"Open in KiCad" says KiCad was not started / PCB Editor crashes right away (macOS).** A KiCad copied from a download can retain the quarantine flag; macOS may block it or an older Launch Services attempt may have produced an App-Translocation crash where `libkicommon.*.dylib` was missing. The plugin watches the exact process it started and, if it exits, shows the crash reason and this fix, which you run yourself (it changes a security attribute, so the plugin never does): `xattr -dr com.apple.quarantine /Applications/KiCad`, then press *Open in KiCad* again. The "Editing in KiCad" banner only means an edit session exists; trust the warning line under the title over it. ## Notes @@ -64,15 +92,15 @@ Press ⌘S in KiCad and the panel imports the save by itself (a new board artifa ## Requirements, network and side effects -* **KiCad 10** must be installed (`/Applications/KiCad/KiCad.app`, or set *KiCad.app path*). The plugin runs its `kicad-cli`, its bundled Python (pcbnew scripts) and reads its symbol/footprint libraries; KiCad is neither bundled nor modified. -* **Python**: `uv` (recommended) or Python ≥ 3.11 with `fastmcp`, `pydantic`, `numpy` (and `kicad-python` for the live link, optional). **If neither uv nor such a Python is found, or uv cannot fetch the packages (offline first start), the plugin still starts: the panel opens and says what is missing, and the model gets one tool, `kicad_setup_help`.** uv runs with `UV_NO_CONFIG=1`, so a `uv.toml` or `pyproject.toml` in your workspace cannot change where packages come from. **Network**: on first start `uv` downloads those packages (plus kicad-python with pynng, protobuf and jsonschema) (and a Python if none ≥ 3.11 is installed). Nothing else uses the network; there is no telemetry. +* **KiCad 10** must be installed. By default the plugin discovers official and Huaqiu apps under the system/user Applications directories and selects the newest app compatible with the requested edition; an explicit *KiCad.app path* disables fallback. The plugin runs the selected app's `kicad-cli`, bundled Python (pcbnew scripts), and symbol/footprint libraries; KiCad is neither bundled nor modified. +* **Python**: `uv` (recommended) or Python ≥ 3.11 with `fastmcp`, `pydantic`, `numpy` (and `kicad-python` for the live link, optional). **If neither uv nor such a Python is found, or uv cannot fetch the packages (offline first start), the plugin still starts: the panel opens and says what is missing, and the model gets one tool, `kicad_setup_help`.** uv runs with `UV_NO_CONFIG=1`, so a `uv.toml` or `pyproject.toml` in your workspace cannot change where packages come from. **Network**: on first start `uv` downloads those packages (plus kicad-python with pynng, protobuf and jsonschema) (and a Python if none ≥ 3.11 is installed). In the Huaqiu edition, the Huaqiu part-data, resolver, and model-comparison tools above contact `https://kiapi.eda.cn`; search terms and requested manufacturer/MPN identifiers are sent there. The comparison tool additionally reads the two selected public text-model URLs from the allowlisted Huaqiu file hosts. There is no telemetry. CI prepares the Python runtime before starting the 60-second MCP handshake. Dependency preparation logs go to stderr; an unavailable runtime fails the artifact check rather than accepting the setup-help fallback. To prepare it manually, run `node dist/server.mjs --prepare-runtime` from the installed plugin directory; stdout returns `ready` on success. The artifact check uses the same isolated home and cached Python environment in offline mode for its handshake. -* **Commands run**: `kicad-cli` (DRC, render, SVG/GLB/STEP/Gerber export, `sch erc`, symbol/footprint SVG), KiCad's bundled Python, `uv`, and — only when you press *Open in KiCad* or the agent calls `kicad_open_in_kicad` — `open -a "PCB Editor.app"` (macOS), then read-only checks that it stays running: `pgrep -x pcbnew`, and after a failed start `xattr -p com.apple.quarantine` plus a look at `~/Library/Logs/DiagnosticReports/pcbnew-*.ips`. The plugin never changes the quarantine flag itself. +* **Commands run**: `kicad-cli` (DRC, render, SVG/GLB/STEP/Gerber export, `sch erc`, symbol/footprint SVG), KiCad's bundled Python, `uv`, and — only when you press *Open in KiCad* or the agent calls `kicad_open_in_kicad` — the selected distribution's `PCB Editor.app/Contents/MacOS/pcbnew ` (macOS). The launcher watches that exact child and its `api-.sock`; after a failed start it may read `xattr -p com.apple.quarantine` and `~/Library/Logs/DiagnosticReports/pcbnew-*.ips`. The plugin never changes the quarantine flag itself. * **Files read**: besides your boards and the KiCad libraries, the "Enable KiCad API" value of `~/Library/Preferences/kicad/*/kicad_common.json` (read only, to tell you whether the API is switched on). **Sockets**: while the panel is open and a board is shown, it asks every 3 s whether KiCad's API answers (a ping and the list of open documents, no board data) to draw the Live indicator, and the Live tab reads the board every 1.5 s; an agent's `kicad_live_*` calls connect to the same local socket (see Security above). Nothing connects while the panel is closed and no agent calls them. * **Files written**: `./kicad/` in the workspace (specs, exports incl. `kicad/out/.glb`, `kicad/edit//` KiCad project) and the plugin data directory (artifact store, cache of rendered tab views, KiCad's private config). The file tools (`pcb_spec_example`, `kicad_check_spec_file`, `kicad_export_files`, the GLB export) only use paths inside the workspace (symlinks are resolved, a path that leaves it is refused); `pcb_spec_example` does not replace a spec that differs from the example unless `overwrite=true`, and `kicad_open_in_kicad` never overwrites a board that is already in `kicad/edit/`: it starts `-r2`, `-r3`, … next to it. The bundled worker never reads `.env` or other configuration files. No hooks. ## Third-party -KiCad (GPL-3.0-or-later; its libraries are CC-BY-SA-4.0 with exceptions) is used from your installation and not redistributed. Runtime packages fetched by `uv`: fastmcp (Apache-2.0), pydantic (MIT), numpy (BSD-3-Clause and others), kicad-python (MIT) with pynng (MIT), protobuf (BSD-3-Clause) and jsonschema (MIT). The panel bundles the MCP Apps SDK packages; their licenses ship in `dist/THIRD_PARTY_NOTICES.txt`. +KiCad (GPL-3.0-or-later; its libraries are CC-BY-SA-4.0 with exceptions) is used from your installation and not redistributed. The Huaqiu edition uses `@huaqiu/part-search` (Apache-2.0) in place from the Huaqiu KiCad installation; this plugin does not redistribute it. Runtime packages fetched by `uv`: fastmcp (Apache-2.0), pydantic (MIT), numpy (BSD-3-Clause and others), kicad-python (MIT) with pynng (MIT), protobuf (BSD-3-Clause) and jsonschema (MIT). The panel bundles the MCP Apps SDK packages; their licenses ship in `dist/THIRD_PARTY_NOTICES.txt`. This plugin is independent of the KiCad project and is not affiliated with or endorsed by it; "KiCad" is used to describe compatibility. diff --git a/external_plugins/kicad/README_CN.md b/external_plugins/kicad/README_CN.md index 83a1cc0e..e86ace4e 100644 --- a/external_plugins/kicad/README_CN.md +++ b/external_plugins/kicad/README_CN.md @@ -3,15 +3,42 @@ 把 KiCad 10 嵌入对话。Agent 用 JSON 电路 spec 设计双层板——真实 KiCad 符号/封装库、自动布线、DRC、Gerber/BOM/贴片坐标—— 侧栏 **KiCad 电路板** 面板显示 3D 渲染、DRC 结论、元件表和全部产物。 +插件使用同一套 PCB 核心提供两个发行版本,并提供自动选择模式: + +| 插件版本 | 对应发行版 | 额外就绪检查 | +| --- | --- | --- | +| `auto`(默认) | 自动发现的最新标准或华秋 KiCad 10 | 先根据安装内容解析发行版,再开放对应工具 | +| `standard` | 标准 KiCad 10 | CLI、pcbnew Python、符号库和封装库 | +| `huaqiu` | 华秋 KiCad 10 | 核心检查、内置华秋组件,以及公共器件库原生适配层 | + +「KiCad.app 路径」留空时,`auto` 会搜索系统与用户 Applications 目录,不启动应用即可识别发行版,并选择最新安装。改选 `standard` 或 `huaqiu` 后,自动发现只会选择对应发行版。显式填写 app 路径后该路径始终优先,即使路径不存在也不会静默换用其他安装,而是明确报告配置错误。 + ## 前提 -* macOS 且已安装 **KiCad 10**(`/Applications/KiCad/KiCad.app`;或在插件设置里填「KiCad.app 路径」)。 +* macOS 且在系统/用户 Applications 目录安装了**标准 KiCad 10**或**华秋 KiCad 10**;也可在插件设置中填写精确的「KiCad.app 路径」。 * 推荐安装 **uv**(首次启动自动拉取依赖),或提供装有 `fastmcp>=4,<5`、`pydantic`、`numpy` 的 Python(设置项「带 fastmcp 的 Python」)。 ## 使用 对 Agent 说:「用 KiCad 设计一块 555 LED 闪烁器的板子,检查 DRC、渲染并打开电路板面板。」示例是 NE555 无稳态闪烁电路(约 1 Hz、9 个元件、34 × 22 mm);Agent 从 `pcb_spec_example` 开始,依次调用 `kicad_check_spec_file`、`pcb_build`、`pcb_render`、`pcb_export_fab`、`kicad_export_files`、`kicad_board_view`(见 `skills/kicad-board/SKILL.md`)。也可以随时在会话面板列表中手动打开该面板。 +首次使用或切换 KiCad 发行版时先调用 `kicad_capabilities`,只有 `edition_ready=true` 才继续。它会只读报告自动/显式选择方式、全部检测候选、`requested_edition`、`resolved_edition`、标准/华秋发行版、匹配状态、KiCad 版本、CLI、库、pcbnew Python、实时 IPC、华秋内置 DSH 组件、当前可用工具和结构化缺失依赖;检测到的 DSH 只做诊断,插件不会启动第二套 Agent Harness。 + +MCP 服务会被主动加载,因此新聊天的首个模型请求就能看到全部 25 个 KiCad 工具,即使模型不支持延迟工具搜索也不受影响。`kicad_capabilities` 还会返回当前安装包的 `plugin_version`,长程验收可以据此确认实际提供调用的插件版本。 + +### 华秋版:原生器件查询 + +`resolved_edition` 为 `huaqiu` 且已就绪时,以下只读 ZCode 工具会复用华秋 KiCad 内置、已做标准化的 `@huaqiu/part-search` 库: + +* `search_hqsch_parts`:按 MPN、制造商、分类或关键词搜索,可要求结果具备符号、封装、3D、仿真或供应链数据。 +* `get_hqsch_part`:读取器件详情、属性、文档、图片、生命周期和模型元数据。 +* `get_hqsch_part_models`:读取符号、封装、3D、仿真模型的元数据和 URL(只返回元数据,不安装任何内容)。 +* `get_hqsch_supply_chain`:批量读取最多 50 个器件的库存、MOQ、交期、分销链接、币种和阶梯价。 +* `resolve_hqsch_part_for_kicad`:读取所选器件的标准化详情,搜索本机 KiCad 库,校验符号的封装过滤规则和同编号引脚/焊盘映射,再返回排序后的候选和 `spec_part_fields`。 +* `compare_hqsch_models_with_kicad`:显式把所选器件的公共 `.kicad_sym` 和 `.kicad_mod` 下载到内存,与一个解析候选比较引脚名称/编号、带编号焊盘的几何及尺寸,以及 Courtyard 外形尺寸。 + +这些调用直接访问华秋无需登录的公共接口 `https://kiapi.eda.cn`。它们不会启动 DSH、加载 DSH skill、下单、安装模型或写入工程。只有显式比较工具会下载模型文本:仅接受 `file.eda.cn` / `file1.eda.cn` 的 HTTPS,拒绝重定向,单文件上限 2 MiB,在内存中按不可信数据解析,只返回哈希而不返回模型正文。模型一致是更强的结构证据,但解析和比较工具仍把电气引脚定义与精确物理封装确认标为必须对照 datasheet 复核。标准版会明确拒绝这些调用。 + ## 面板:与真实 KiCad 窗口并排的标签页 面板是 KiCad 自己窗口(PCB Editor、Schematic Editor)的"伴随面板",不是嵌入式编辑器。各标签页显示 `kicad-cli` 对最新板子(你在 KiCad 里保存过的就是编辑后的那块)无界面导出的内容: @@ -26,13 +53,14 @@ ## 与正在运行的 PCB 编辑器实时连接(KiCad API) -在 KiCad 自己的 **「Enable KiCad API」** 偏好设置打开后,面板和 Agent 可以不等 ⌘S 就和你已经打开的 PCB 编辑器通信: +在 KiCad 自己的 **「Enable KiCad API」** 偏好设置打开后,「在 KiCad 中编辑」会启动所选发行版的精确 PCB Editor 进程,并等待这个进程自己的 API socket。随后面板和 Agent 可以不等 ⌘S 就与它通信;再次打开已连接的会话会复用它,不会重复启动: * 面板顶部的**实时**指示和**实时**标签页:元件(位号、封装、值、x、y、角度、所在面)、网络和你当前的选择,标签页打开时每 1.5 秒从编辑器读取一次(板子没变时几乎没有开销)。未保存的移动会立刻显示,Δ 列显示自打开标签页以来的变化。坐标与 spec 相同:以板子左上角为原点的 mm。 * `kicad_live_status`(Agent 和面板):API 是否可达、打开的是哪块板、是否是本会话的板子。不可用时用一句话说明原因并点出设置名;其他标签页和 ⌘S 往返照常工作。编辑器里打开的是另一个文件时,面板会明说,而不是把它当成会话的板子显示。 +* `kicad_live_snapshot`(Agent 和面板):只读返回当前元件、网络、选择和数量。Agent 用它在调整前后读取位置,不再用“原地移动”污染 KiCad 的撤销历史。 * `kicad_live_move_footprint`(仅 Agent):在打开的编辑器里移动**一个**元件(可选同时设置角度),是 KiCad 里的一个可撤销步骤(⌘Z)。**不会保存任何东西**:你照常按 ⌘S,面板再导入并跑 DRC。只有当编辑器恰好打开的是本会话的板子时才会执行。有意不提供「保存」工具。 -**安全。** KiCad API 是本机的 Unix socket(`/tmp/kicad/api.sock`,其他编辑器是 `api-.sock`)。KiCad 不要求密码或令牌;只有你的 macOS 用户能连接这个 socket 文件,但该用户的**任何**进程都可以:你的 shell、脚本,以及能运行 shell 或 Python 的 ZCode Agent——不管有没有这个插件。协议里有下列全部请求(本插件的测试只实际用过读取、一次移动、撤销和一个缩放动作):这样的进程可以读取整块板子、修改或删除板上任何东西、把板子或副本保存到它能写入的任意路径(`save_as` 可覆盖)、撤销你未保存的编辑、改变选择、运行任意编辑器动作,以及(取决于客户端库)启动导出任务。只在需要时打开该偏好设置。本插件用它读取(文档、元件、走线、过孔、铜区、焊盘、网络、选择)和执行上述唯一的一次提交;它从不保存、还原、删除、改变选择、运行动作,也不启动或停止 KiCad,并且把 socket 路径和 KiCad 发放的令牌留在服务进程内:不会交给面板页面,也不会出现在工具结果或错误信息里。 +**安全。** KiCad API 是本机的 Unix socket(`/tmp/kicad/api.sock`,其他编辑器是 `api-.sock`)。KiCad 不要求密码或令牌;只有你的 macOS 用户能连接这个 socket 文件,但该用户的**任何**进程都可以:你的 shell、脚本,以及能运行 shell 或 Python 的 ZCode Agent——不管有没有这个插件。协议里有下列全部请求(本插件的测试只实际用过读取和一次移动提交):这样的进程可以读取整块板子、修改或删除板上任何东西、把板子或副本保存到它能写入的任意路径(`save_as` 可覆盖)、撤销你未保存的编辑、改变选择、运行任意编辑器动作,以及(取决于客户端库)启动导出任务。只在需要时打开该偏好设置。本插件用它读取(文档、元件、走线、过孔、铜区、焊盘、网络、选择)和执行上述唯一的一次提交;它从不保存、还原、删除、改变选择、运行动作或停止 KiCad。只有 `kicad_open_in_kicad` 会启动编辑器。socket 路径和 KiCad 发放的令牌留在服务进程内:不会交给面板页面,也不会出现在工具结果或错误信息里。 ## 给其他工具用的 3D 模型 @@ -40,19 +68,19 @@ ## 在真实 KiCad 里继续编辑 -面板里的「在 KiCad 中编辑」(或让 Agent 调用 `kicad_open_in_kicad`)会把当前板子导出到工作区 `./kicad/edit/<名称>/`(一个普通的 KiCad 工程,归你所有),并用本机的 **KiCad PCB Editor** 打开。 +面板里的「在 KiCad 中编辑」(或让 Agent 调用 `kicad_open_in_kicad`)会把当前板子导出到工作区 `./kicad/edit/<名称>/`(一个普通的 KiCad 工程,归你所有),并在所选标准版或华秋版 **KiCad PCB Editor** 的新进程中打开。它直接运行该发行版的精确 `pcbnew`,不会让 Launch Services 复用一个不相关、没有实时 API 的独立编辑器,然后分别校验进程 socket 与目标板是否真正打开。结果会区分 `launched` 和 `live_ready`:工程锁或恢复对话框可能让前者为真、后者为假,`launch_note` 会说明应检查什么。 你在 KiCad 里按 ⌘S,面板会自动导入这次保存(生成新的板子产物并跑 DRC),顶部显示「已在 KiCad 中编辑」;Agent 也可调用 `kicad_sync_edits`。重新打开时不会覆盖你已保存的内容。目前自动启动只支持 macOS。 ## 已知问题 / 未证实 -* **实时连接,未证实:** `kicad_live_move_footprint` 之后 KiCad 画布是否立刻重绘没有亲眼看到(编辑器自己的回读显示了新位置,⌘Z 能恢复旧位置,这是在一个独立的 KiCad 实例上测的,不是你的)。API 没有「有未保存修改」的请求,也没有变化通知,所以实时标签页只能轮询,分不清已保存和未保存的编辑。它需要 `kicad-python`(首次启动时由 `uv` 拉取;没有它插件照样启动,只是没有实时连接),只在 macOS 上的 KiCad 10.0.6 试过。写入只在独立 KiCad 进程里的一份临时板子副本上试过。 +* **实时连接的限制:** API 没有「有未保存修改」的请求,也没有变化通知,所以实时标签页只能轮询,分不清已保存和未保存的编辑。它需要 `kicad-python`(首次启动时由 `uv` 拉取;没有它插件照样启动,只是没有实时连接)。已经在 macOS 上用临时板副本分别验证标准 KiCad 10.0.6 和华秋 KiCad 10.0.7 的进程/socket 选择、实时快照、移动 0.25 mm、立即回读和移回原位,整个过程未保存;没有用肉眼判断画布重绘。 * **不是嵌入式编辑器。** 标签页由 `kicad-cli` 渲染,不是 KiCad 自己的画布,并且与 PCB/原理图编辑器窗口彼此独立:编辑仍然经由文件(在 KiCad 里按 ⌘S,面板再导入这次保存)。标签页不会跟随你在 KiCad 里的光标或选择。 * **原理图标签页和 ERC 需要你自己画的原理图。** ERC 使用 KiCad 自带的库表和私有配置,不是你自己的库表:来自自定义库的符号会显示为库警告。多页原理图用下拉选择页面,只试过单页。 * **图层、原理图、元件库是 `kicad-cli` 导出的 SVG**,用 KiCad 默认配色而不是你的主题。较大的原理图每页约 1 MB SVG:猫粮机 rev A 原理图(0.9 MB)已在真实桌面沙箱测试(真实 Electron 宿主、CSP 和桥)里渲染成功;更大的设计没有试过,也没有在 ZCode Dev 窗口里手工试过。 * **GLB**:在示例板(9 个元件,位置/旋转/底面已与 pcbnew 对照)上测试过,元件表只描述有库 3D 模型的元件。网格名是封装名,位号在节点名里。 -* **早期版本的设置问题。** 0.4.2 及之前,插件对你自己的 KiCad 设置运行 `kicad-cli version`,KiCad 随后会改写 `~/Library/Preferences/kicad/10.0/kicad_common.json` 里的一个值(文件对话框的起始文件夹)。0.5.0 起插件启动的所有 KiCad 程序都使用私有配置;对该调用的一次测试里只有这一个值发生了变化;你自己打开的 GUI 保持你的设置。 +* **早期版本的设置问题。** 0.4.2 及之前,插件对你自己的 KiCad 设置运行 `kicad-cli version`,KiCad 随后会改写 `~/Library/Preferences/kicad/10.0/kicad_common.json` 里的一个值(文件对话框的起始文件夹)。0.5.0 起所有无界面的 KiCad 命令都使用私有配置;GUI 会有意保留你的设置,包括「Enable KiCad API」。 -* **点「在 KiCad 中编辑」提示没有启动 KiCad / PCB Editor 一打开就崩溃(macOS)。** 手动拷贝或下载到 `/Applications` 的 KiCad 带有下载隔离标记(quarantine),macOS 会只把内层的 `pcbnew.app` 单独放到临时副本里运行(App Translocation),那里找不到 `libkicommon.*.dylib`(崩溃报告里是 “Library not loaded”)。插件会等待 `pcbnew` 保持运行;没有的话会显示原因和修复命令。修复需要你自己在终端执行(它会修改系统安全属性,插件不会代劳):`xattr -dr com.apple.quarantine /Applications/KiCad`,然后重新点「在 KiCad 中编辑」。面板里的「正在 KiCad 中编辑」横幅只表示编辑会话已创建,请以标题下方的警告行为准。 +* **点「在 KiCad 中编辑」提示没有启动 KiCad / PCB Editor 一打开就崩溃(macOS)。** 下载来的 KiCad 可能仍带有 quarantine;macOS 可能阻止它,旧版通过 Launch Services 启动时也可能出现 App Translocation,导致找不到 `libkicommon.*.dylib`。插件会监视自己启动的精确进程;进程退出时显示崩溃原因和修复命令。修复需要你自己在终端执行(它会修改系统安全属性,插件不会代劳):`xattr -dr com.apple.quarantine /Applications/KiCad`,然后重新点「在 KiCad 中编辑」。面板里的「正在 KiCad 中编辑」横幅只表示编辑会话已创建,请以标题下方的警告行为准。 ## 说明 @@ -63,15 +91,15 @@ ## 依赖、网络与副作用 -* 需要已安装 **KiCad 10**(`/Applications/KiCad/KiCad.app`,或设置「KiCad.app 路径」)。插件调用其中的 `kicad-cli`、自带 Python(pcbnew 脚本)并读取其符号/封装库;不打包、不修改 KiCad。 -* **Python**:推荐 `uv`,或装有 `fastmcp`、`pydantic`、`numpy` 的 Python ≥ 3.11(实时连接另需可选的 `kicad-python`)。**如果既没有 uv、也没有这样的 Python,或 uv 取不到依赖(首次启动时离线),插件仍会启动:面板能打开并说明缺什么,模型会得到一个工具 `kicad_setup_help`。** uv 以 `UV_NO_CONFIG=1` 运行,所以工作区里的 `uv.toml` 或 `pyproject.toml` 无法改变依赖来源。**网络**:首次启动时 `uv` 会下载这些依赖(加上 kicad-python 及 pynng、protobuf、jsonschema)(本机没有 ≥ 3.11 的 Python 时还会下载 Python)。除此之外不使用网络,没有遥测。 +* 需要已安装 **KiCad 10**。默认会在系统/用户 Applications 目录发现标准与华秋版本,并选择符合请求发行版的最新应用;显式填写「KiCad.app 路径」后不会回退。插件调用所选应用的 `kicad-cli`、自带 Python(pcbnew 脚本)并读取其符号/封装库;不打包、不修改 KiCad。 +* **Python**:推荐 `uv`,或装有 `fastmcp`、`pydantic`、`numpy` 的 Python ≥ 3.11(实时连接另需可选的 `kicad-python`)。**如果既没有 uv、也没有这样的 Python,或 uv 取不到依赖(首次启动时离线),插件仍会启动:面板能打开并说明缺什么,模型会得到一个工具 `kicad_setup_help`。** uv 以 `UV_NO_CONFIG=1` 运行,所以工作区里的 `uv.toml` 或 `pyproject.toml` 无法改变依赖来源。**网络**:首次启动时 `uv` 会下载这些依赖(加上 kicad-python 及 pynng、protobuf、jsonschema)(本机没有 ≥ 3.11 的 Python 时还会下载 Python)。华秋版中,上述华秋器件数据、解析和模型比较工具会访问 `https://kiapi.eda.cn`,搜索词及请求的制造商/MPN 标识会发送到该接口;比较工具还会从白名单内的华秋文件域名读取所选的两个公共文本模型;没有遥测。 CI 会先准备 Python 运行环境,再开始 60 秒的 MCP 握手。依赖准备日志写入 stderr;运行环境不可用时,产物检查会失败,不会把缺依赖的帮助面板当作正常服务。也可以在已安装插件目录运行 `node dist/server.mjs --prepare-runtime`,成功时 stdout 返回 `ready`。产物检查使用同一个隔离 HOME 和缓存的 Python 环境,以离线模式完成握手。 -* **执行的命令**:`kicad-cli`(DRC、渲染、SVG/GLB/STEP/Gerber 导出、`sch erc`、符号/封装 SVG)、KiCad 自带 Python、`uv`;只有当你点「在 KiCad 中编辑」或 Agent 调用 `kicad_open_in_kicad` 时,才会执行 `open -a "PCB Editor.app"`(macOS),随后只读地检查它是否保持运行:`pgrep -x pcbnew`,启动失败后再执行 `xattr -p com.apple.quarantine` 并查看 `~/Library/Logs/DiagnosticReports/pcbnew-*.ips`。插件本身不会修改隔离标记。 +* **执行的命令**:`kicad-cli`(DRC、渲染、SVG/GLB/STEP/Gerber 导出、`sch erc`、符号/封装 SVG)、KiCad 自带 Python、`uv`;只有当你点「在 KiCad 中编辑」或 Agent 调用 `kicad_open_in_kicad` 时,才会执行所选发行版的 `PCB Editor.app/Contents/MacOS/pcbnew <板子>`(macOS)。启动器会监视这个精确子进程及其 `api-.sock`;启动失败后可能只读地执行 `xattr -p com.apple.quarantine` 并查看 `~/Library/Logs/DiagnosticReports/pcbnew-*.ips`。插件本身不会修改隔离标记。 * **读取的文件**:除你的板子和 KiCad 库外,只读地读取 `~/Library/Preferences/kicad/*/kicad_common.json` 里「Enable KiCad API」的值(用来告诉你 API 是否打开)。**Socket**:只有当面板打开且显示着一块板子时,它每 3 秒问一次 KiCad 的 API 是否应答(一次 ping 和已打开文档列表,不含板子数据)来画实时指示,实时标签页每 1.5 秒读一次板子;Agent 的 `kicad_live_*` 调用连接的是同一个本机 socket(见上面的安全说明)。面板关闭、也没有 Agent 调用时,不会连接。 * **写入的文件**:工作区的 `./kicad/`(spec、导出文件含 `kicad/out/<名称>.glb`、`kicad/edit/<名称>/` KiCad 工程)和插件数据目录(产物库、标签页视图缓存、KiCad 私有配置)。文件类工具(`pcb_spec_example`、`kicad_check_spec_file`、`kicad_export_files`、GLB 导出)只使用工作区内的路径(符号链接会被解析,越出工作区的路径被拒绝);`pcb_spec_example` 不会替换与示例不同的 spec,除非 `overwrite=true`;`kicad_open_in_kicad` 从不覆盖 `kicad/edit/` 里已有的板子,而是在旁边新建 `<名称>-r2`、`-r3`……随包的工作器不读取 `.env` 或其他配置文件。没有 Hook。 ## 第三方 -KiCad(GPL-3.0-or-later;其库为 CC-BY-SA-4.0 并带例外条款)使用你本机的安装,不随包分发。`uv` 在运行时拉取:fastmcp(Apache-2.0)、pydantic(MIT)、numpy(BSD-3-Clause 等)、kicad-python(MIT)及 pynng(MIT)、protobuf(BSD-3-Clause)、jsonschema(MIT)。面板打包了 MCP Apps SDK 相关包,其许可证随构建产物放在 `dist/THIRD_PARTY_NOTICES.txt`。 +KiCad(GPL-3.0-or-later;其库为 CC-BY-SA-4.0 并带例外条款)使用你本机的安装,不随包分发。华秋版会就地使用华秋 KiCad 安装内的 `@huaqiu/part-search`(Apache-2.0),本插件不再分发该库。`uv` 在运行时拉取:fastmcp(Apache-2.0)、pydantic(MIT)、numpy(BSD-3-Clause 等)、kicad-python(MIT)及 pynng(MIT)、protobuf(BSD-3-Clause)、jsonschema(MIT)。面板打包了 MCP Apps SDK 相关包,其许可证随构建产物放在 `dist/THIRD_PARTY_NOTICES.txt`。 本插件独立于 KiCad 项目,与其无隶属或背书关系;「KiCad」仅用于说明兼容性。 diff --git a/external_plugins/kicad/skills/kicad-board/SKILL.md b/external_plugins/kicad/skills/kicad-board/SKILL.md index 1a34cbf8..bcd4433d 100644 --- a/external_plugins/kicad/skills/kicad-board/SKILL.md +++ b/external_plugins/kicad/skills/kicad-board/SKILL.md @@ -10,6 +10,7 @@ libraries, place and route it, run DRC, render it and export fabrication files. ## Workflow +0. **Diagnose the selected edition.** Call `kicad_capabilities` before the first board or after the user switches KiCad installations. Continue only when `edition_ready=true`; otherwise report the structured `missing_dependencies`. The default `requested_edition=auto` discovers installed apps; route by `resolved_edition`: `standard` uses the `kicad-standard` rules and `huaqiu` uses `kicad-huaqiu`. In the Huaqiu edition, only the explicit Huaqiu tools listed in `available_tools` are native adapters; the bundled DSH harness itself is never started. 1. **Start from an example.** `pcb_spec_example` writes a small, complete, DRC-clean spec to `./kicad/_spec.json`: `ne555_blinker` (default: an NE555 LED flasher, about 1 Hz, 9 parts, 34 × 22 mm), `led_indicator` (3 parts), `ldo_3v3_breakout`, `shift_register_leds`; it also documents every spec field. For your own circuit, copy its format and use `pcb_search_parts` / `pcb_part_info` to get library ids and **pin numbers/names/pads — never guess them**. @@ -21,10 +22,10 @@ libraries, place and route it, run DRC, render it and export fabrication files. 5. **Let the user keep editing in KiCad:** `kicad_open_in_kicad` exports the board to `./kicad/edit//` (a normal KiCad project) and opens it in the real **KiCad PCB Editor**. The user edits and presses ⌘S; the panel imports each save by itself, and `kicad_sync_edits` does the same on demand (new board artifact, DRC on it, `changed`/`violations` in the answer). After the user says they are done — or whenever the panel shows "edited in KiCad" — call `kicad_sync_edits`, read the DRC verdict, and continue from the edited board's `artifact_id`. - Never overwrite the user's files: re-opening imports pending saves first, and a board that is already in `kicad/edit/` is never replaced (the next export goes to `-r2`, `-r3`, …). File tools only use paths inside the workspace; `pcb_spec_example` keeps a spec you edited unless you pass `overwrite=true`. If the answer has `launched=false`, KiCad is **not** open: tell the user `launch_note` as it is (on macOS it names the `xattr -dr com.apple.quarantine …` fix the user must run themselves; never run it for them) and do not wait for saves. + Never overwrite the user's files: re-opening imports pending saves first, and a board that is already in `kicad/edit/` is never replaced (the next export goes to `-r2`, `-r3`, …). File tools only use paths inside the workspace; `pcb_spec_example` keeps a spec you edited unless you pass `overwrite=true`. If the answer has `launched=false`, KiCad is **not** open: tell the user `launch_note` as it is (on macOS it names the `xattr -dr com.apple.quarantine …` fix the user must run themselves; never run it for them) and do not wait for saves. If `launched=true` but `live_ready=false`, the GUI process exists but the requested board is not connected (often a project-lock/recovery dialog); report `launch_note` and do not use a live write until `kicad_live_status.available=true`. 6. **Check:** `kicad_checks` returns the DRC violations of the newest board with positions (board mm) and, when the user drew a schematic in the edit project, its ERC; the panel's Checks tab shows the same. A board built from a spec has no schematic, so "no schematic" is normal, not an error. 7. **3D model for the structure/enclosure work:** `pcb_export_glb` writes a `.glb` (stored artifact + `./kicad/out/.glb`) and returns the part table: designator, footprint, position/yaw/side and bounding box in board mm for every part that has a library 3D model. Use that table, not mesh names, to tell parts apart; parts listed in `parts_without_model` are not in the file, so size them from the courtyard; heights are nominal; through-hole pins reach below the board (z < 0). Say these limits when you hand the model over. -8. **Live with the user's open editor (only if KiCad's "Enable KiCad API" is on):** `kicad_live_status` says whether the running PCB Editor is reachable and has THIS session's board open; if not, tell the user its one-sentence `reason` and carry on with the file round trip. `kicad_live_move_footprint(ref, x_mm, y_mm, rotation_deg?)` moves ONE footprint in the user's open window (spec frame: mm from the top-left corner). It is one undoable step (⌘Z) and **nothing is saved**: say so, tell the user to look at the board and press ⌘S if they accept it, then `kicad_sync_edits` imports it with DRC. The user may be editing at that moment: use it for small requested adjustments, never to rework a board, and never move parts the user did not ask about. There is no save tool; do not try to save through any other route (the API socket is the user's). +8. **Live with the selected editor (only if KiCad's "Enable KiCad API" is on):** `kicad_open_in_kicad` starts the exact Standard/Huaqiu PCB Editor process selected by the plugin, waits for its socket, and separately verifies that THIS session's board opened; `kicad_live_status` reports the same state later. If unavailable, tell the user its one-sentence `reason` and carry on with the file round trip. Use the read-only `kicad_live_snapshot` to get the current part positions before and after a requested adjustment; never make a no-op move as a read probe. `kicad_live_move_footprint(ref, x_mm, y_mm, rotation_deg?)` moves ONE footprint in the user's open window (spec frame: mm from the top-left corner). It is one undoable step (⌘Z) and **nothing is saved**: say so, tell the user to look at the board and press ⌘S if they accept it, then `kicad_sync_edits` imports it with DRC. The user may be editing at that moment: use it for small requested adjustments, never to rework a board, and never move parts the user did not ask about. There is no save tool; do not try to save through any other route (the API socket is the user's). 9. **Export:** `pcb_export_fab` (Gerber + drill, BOM, pos, `pcb_report`), then `kicad_export_files` to copy what you need into `./kicad/out/` in the workspace. ## Rules of the road diff --git a/external_plugins/kicad/skills/kicad-huaqiu/SKILL.md b/external_plugins/kicad/skills/kicad-huaqiu/SKILL.md new file mode 100644 index 00000000..57ce4d37 --- /dev/null +++ b/external_plugins/kicad/skills/kicad-huaqiu/SKILL.md @@ -0,0 +1,16 @@ +--- +name: kicad-huaqiu +description: Use the Huaqiu KiCad edition of the ZCode KiCad plugin for PCB design and native Huaqiu public part lookup without starting the bundled DSH harness. +--- + +# Huaqiu KiCad edition + +Use this skill when `kicad_capabilities` resolves the Huaqiu KiCad distribution, whether `edition` is `auto` or `huaqiu`. + +1. Call `kicad_capabilities` before the first board. Continue only when `resolved_edition=huaqiu`, `distribution=huaqiu`, and `edition_ready=true`. +2. If `edition_ready=false`, report `missing_dependencies` and `edition.missing_dsh_plugins` exactly. Do not fall back to the official KiCad installation. +3. Follow the shared `kicad-board` workflow for part lookup, spec validation, build, DRC, render, GUI round-trip, and manufacturing export. +4. Prefer `search_hqsch_parts` for Huaqiu part selection, then use `get_hqsch_part` for details and `get_hqsch_part_models` for symbol/footprint/3D/simulation metadata. Use the returned manufacturer id and MPN exactly; never invent either. Use `get_hqsch_supply_chain` only when stock or pricing context is requested. +5. Call `resolve_hqsch_part_for_kicad` after choosing a Huaqiu part. If it recommends a pair, call `compare_hqsch_models_with_kicad` with that exact symbol and footprint before using `spec_part_fields`. The comparison safely reads the public KiCad text models into memory; never fetch a returned URL by another route. A model match still does not prove datasheet electrical or physical compatibility, so review `review.required`. If there is no recommended pair or the models disagree, fall back to `pcb_search_parts` / `pcb_part_info` and never invent a library id. +6. These tools are read-only native ZCode adapters over the public `kiapi.eda.cn` API, allowlisted Huaqiu model hosts, and the installed KiCad libraries. They never install a model or insert parts into the design. +7. Treat all other bundled DSH packages as installation evidence only. ZCode is the active harness; never start the bundled DSH harness or describe quoting, ordering, schematic generation, or symbol installation as callable ZCode features until dedicated tools appear in `available_tools`. diff --git a/external_plugins/kicad/skills/kicad-standard/SKILL.md b/external_plugins/kicad/skills/kicad-standard/SKILL.md new file mode 100644 index 00000000..77ced88d --- /dev/null +++ b/external_plugins/kicad/skills/kicad-standard/SKILL.md @@ -0,0 +1,13 @@ +--- +name: kicad-standard +description: Use the Standard KiCad edition of the ZCode KiCad plugin for PCB design, checking, rendering, fabrication export, or editing in the official KiCad 10 desktop app. +--- + +# Standard KiCad edition + +Use this skill when `kicad_capabilities` resolves the official KiCad distribution, whether `edition` is `auto` or `standard`. + +1. Call `kicad_capabilities` before the first board. Continue only when `resolved_edition=standard`, `distribution=official`, and `edition_ready=true`. +2. If `edition_ready=false`, report `missing_dependencies` exactly. Do not silently switch to a Huaqiu installation; ask the user to select the Huaqiu edition or configure the official `KiCad.app` path. +3. Follow the shared `kicad-board` workflow for part lookup, spec validation, build, DRC, render, GUI round-trip, and manufacturing export. +4. Do not claim Huaqiu part-search, quoting, ordering, or DSH capabilities in this edition. diff --git a/marketplace.json b/marketplace.json index c7f09a06..c6b79760 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1137,12 +1137,12 @@ { "name": "kicad", "source": "./external_plugins/kicad", - "description": "KiCad 10 inside the conversation: agents design 2-layer boards from a circuit spec (real KiCad libraries, auto-route, DRC, Gerber/BOM/CPL); the side panel shows the 3D render and DRC verdict; one click opens the board in the real KiCad PCB Editor and every save syncs back.", + "description": "Automatically connects to installed official or Huaqiu KiCad 10. Both design, check, render, and export boards; Huaqiu also adds safe public-part search and model comparison without starting DSH.", "description_i18n": { - "en": "KiCad 10 inside the conversation: agents design 2-layer boards from a circuit spec (real KiCad libraries, auto-route, DRC, Gerber/BOM/CPL); the side panel shows the 3D render and DRC verdict; one click opens the board in the real KiCad PCB Editor and every save syncs back.", - "zh-CN": "把 KiCad 10 嵌入对话:Agent 用电路 spec 设计双层板(真实 KiCad 库、自动布线、DRC、Gerber/BOM/贴片坐标),侧栏面板显示 3D 渲染和 DRC 结论;一键在真实的 KiCad PCB Editor 里继续编辑,保存后自动同步回对话。" + "en": "Automatically connects to installed official or Huaqiu KiCad 10. Both design, check, render, and export boards; Huaqiu also adds safe public-part search and model comparison without starting DSH.", + "zh-CN": "自动识别并连接已安装的标准或华秋 KiCad 10:两者均可设计、检查、渲染和导出电路板;华秋版还提供安全的公共器件搜索与模型比较,全程不启动 DSH。" }, - "version": "0.6.1", + "version": "0.12.3", "author": { "name": "冯小平", "url": "https://github.com/fxp" @@ -1445,4 +1445,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/ui-plugins/kicad/package.json b/ui-plugins/kicad/package.json index 72f32da0..373b83c1 100644 --- a/ui-plugins/kicad/package.json +++ b/ui-plugins/kicad/package.json @@ -1,8 +1,8 @@ { "name": "@zcode/plugin-kicad", - "version": "0.6.1", + "version": "0.12.3", "private": true, - "description": "ZCode KiCad plugin: agents design 2-layer boards from a circuit spec with real KiCad 10 libraries, auto-route, DRC and fab export; the side panel shows the 3D render and DRC verdict, and the board opens in the real KiCad PCB Editor for further editing.", + "description": "ZCode KiCad plugin: automatically connects to installed official or Huaqiu KiCad 10 for 2-layer PCB design, DRC, rendering, fabrication export and real-editor handoff.", "license": "MIT", "type": "module", "engines": { diff --git a/ui-plugins/kicad/server/huaqiu_kicad_resolver.py b/ui-plugins/kicad/server/huaqiu_kicad_resolver.py new file mode 100644 index 00000000..b4fa82ae --- /dev/null +++ b/ui-plugins/kicad/server/huaqiu_kicad_resolver.py @@ -0,0 +1,253 @@ +"""Resolve a Huaqiu part to candidates in the installed KiCad libraries. + +This adapter deliberately stops at a reviewed candidate. A matching name and +pin/pad count cannot prove that a footprint has the manufacturer's exact body, +pitch, or exposed-pad geometry. +""" +from __future__ import annotations + +import re +from typing import Any + +from kicad import library as kicad_library + + +def _key(value: Any) -> str: + return re.sub(r"[^a-z0-9]+", "", str(value or "").lower()) + + +def _package_values(part: dict[str, Any]) -> list[str]: + values: list[str] = [] + if part.get("package"): + values.append(str(part["package"]).strip()) + for attribute in part.get("attributes") or []: + if not isinstance(attribute, dict): + continue + name = _key(attribute.get("shortName") or attribute.get("name")) + if "package" in name or "封装" in str(attribute.get("name") or ""): + value = str(attribute.get("value") or "").strip() + if value: + values.append(value) + return list(dict.fromkeys(values)) + + +def package_queries(part: dict[str, Any]) -> list[str]: + """Return conservative KiCad search terms for Huaqiu package labels.""" + queries: list[str] = [] + for raw in _package_values(part): + queries.append(raw) + compact = re.sub(r"[ _]+", "-", raw.upper()).strip("-") + match = re.search(r"(?:SOP|SO)(?:IC)?-?(\d+)", compact) + if match: + pins = match.group(1) + queries.extend([f"SOIC-{pins}", f"SOP-{pins}"]) + for family in ("SSOP", "TSSOP", "MSOP", "QSOP", "DIP", "QFN", "DFN", "LQFP", "TQFP", "BGA"): + match = re.search(rf"{family}-?(\d+)", compact) + if match: + queries.append(f"{family}-{match.group(1)}") + match = re.search(r"SOT-?23-?(\d+)?", compact) + if match: + queries.append("SOT-23" + (f"-{match.group(1)}" if match.group(1) else "")) + for imperial in ("0201", "0402", "0603", "0805", "1206", "1210"): + if imperial in compact: + queries.append(imperial) + return list(dict.fromkeys(query for query in queries if query)) + + +def _symbol_queries(part: dict[str, Any]) -> list[str]: + mpn = str(part.get("mpn") or "").strip() + queries = [mpn] if mpn else [] + # Common manufacturer suffixes follow '-' or space. Keep the full MPN first + # and add only a useful family-sized prefix, never a one-character token. + family = re.split(r"[- /]", mpn, maxsplit=1)[0] + if len(family) >= 4 and family != mpn: + queries.append(family) + return list(dict.fromkeys(queries)) + + +def _collect_search(search, queries: list[str], limit: int) -> list[dict[str, Any]]: + found: dict[str, dict[str, Any]] = {} + for query in queries: + for hit in search(query, limit=limit, match_any=False): + found.setdefault(hit["lib_id"], dict(hit)) + return list(found.values()) + + +def _pin_dict(pin: Any) -> dict[str, Any]: + return { + "number": pin.number, + "name": pin.display_name or "~", + "type": pin.etype, + **({"hidden": True} if pin.hidden else {}), + } + + +def resolve_part( + part: dict[str, Any], + *, + limit: int = 5, + library: Any = kicad_library, +) -> dict[str, Any]: + """Return ranked, locally verified symbol/footprint pairs for one part.""" + limit = max(1, min(int(limit), 10)) + mpn = str(part.get("mpn") or "").strip() + if not mpn: + return {"ok": False, "error": "Huaqiu part detail has no MPN", "code": "huaqiu_part_missing_mpn"} + symbol_queries = _symbol_queries(part) + footprint_queries = package_queries(part) + symbol_hits = _collect_search(library.search_symbols, symbol_queries, 20) + + symbols: list[tuple[float, Any, dict[str, Any]]] = [] + for hit in symbol_hits: + try: + symbol = library.get_symbol(hit["lib_id"]) + except Exception: # diagnostics should survive one broken library item + continue + name = hit["lib_id"].partition(":")[2] + name_key, mpn_key = _key(name), _key(mpn) + score = 0.0 + reasons = [] + if name_key == mpn_key: + score += 120 + reasons.append("symbol name exactly matches the MPN") + elif name_key.startswith(mpn_key) or mpn_key.startswith(name_key): + score += 85 + reasons.append("symbol name matches the MPN family") + elif mpn_key in name_key: + score += 55 + reasons.append("symbol name contains the MPN") + if symbol.default_footprint: + score += 10 + reasons.append("symbol declares a default footprint") + summary = { + "id": symbol.lib_id, + "description": symbol.description, + "ref_prefix": symbol.ref_prefix, + "default_footprint": symbol.default_footprint or None, + "footprint_filters": list(symbol.fp_filters), + "pins": [_pin_dict(pin) for pin in sorted(symbol.pins, key=lambda item: library.natural_key(item.number))], + "match_reasons": reasons, + } + symbols.append((score, symbol, summary)) + symbols.sort(key=lambda item: (-item[0], item[1].lib_id)) + symbols = symbols[:10] + + footprint_hits = _collect_search(library.search_footprints, footprint_queries, 30) + footprint_ids = {hit["lib_id"] for hit in footprint_hits} + default_ids: set[str] = set() + for _, symbol, _ in symbols: + if symbol.default_footprint and library.footprint_exists(symbol.default_footprint): + default_ids.add(symbol.default_footprint) + footprint_ids.add(symbol.default_footprint) + compatible, _ = library.compatible_footprints(symbol, limit=30) + footprint_ids.update(compatible) + + package_keys = [_key(query) for query in footprint_queries] + pairs: list[dict[str, Any]] = [] + footprint_summaries: dict[str, dict[str, Any]] = {} + for footprint_id in sorted(footprint_ids): + try: + footprint = library.get_footprint(footprint_id) + except Exception: + continue + bb = footprint.bbox() + footprint_summaries[footprint_id] = { + "id": footprint.lib_id, + "description": footprint.description, + "tags": footprint.tags, + "pad_numbers": footprint.pad_numbers, + "courtyard_mm": { + "width": round(bb[2] - bb[0], 3), + "height": round(bb[3] - bb[1], 3), + }, + } + footprint_key = _key(footprint_id) + package_matches = [query for query, key in zip(footprint_queries, package_keys) if key and key in footprint_key] + for symbol_score, symbol, _ in symbols: + mapping = library.pin_pad_mapping(symbol, footprint) + filters_match = library.footprint_matches_filters(footprint_id, symbol.fp_filters) + score = symbol_score + reasons = [] + if footprint_id == symbol.default_footprint: + score += 80 + reasons.append("symbol's default footprint") + if filters_match: + score += 45 + reasons.append("matches the symbol's KiCad footprint filters") + if package_matches: + score += 55 + reasons.append(f"matches Huaqiu package query: {package_matches[0]}") + if not mapping["pins_without_pad"]: + score += 60 + reasons.append("every symbol pin has a same-numbered footprint pad") + else: + score -= 200 + if mapping["pads_without_pin"]: + score -= min(30, 5 * len(mapping["pads_without_pin"])) + reasons.append("footprint has additional pads that require review") + pairs.append( + { + "symbol": symbol.lib_id, + "footprint": footprint_id, + "score": round(score, 2), + "match_reasons": reasons, + "pin_pad_mapping": { + "consistent": not mapping["pins_without_pad"], + "pins_without_pad": mapping["pins_without_pad"], + "pads_without_pin": mapping["pads_without_pin"], + "filters_match": filters_match, + }, + "package_matches": package_matches, + } + ) + pairs.sort(key=lambda item: (-item["score"], item["symbol"], item["footprint"])) + safe_pairs = [ + pair + for pair in pairs + if pair["pin_pad_mapping"]["consistent"] + and not pair["pin_pad_mapping"]["pads_without_pin"] + and pair["pin_pad_mapping"]["filters_match"] + and (not footprint_queries or bool(pair["package_matches"])) + ][:limit] + recommended = safe_pairs[0] if safe_pairs else None + footprint_output = [] + seen_footprints = set() + for pair in safe_pairs: + footprint_id = pair["footprint"] + if footprint_id not in seen_footprints: + footprint_output.append(footprint_summaries[footprint_id]) + seen_footprints.add(footprint_id) + + model_files = part.get("models") if isinstance(part.get("models"), dict) else {} + result: dict[str, Any] = { + "ok": True, + "error": None, + "mpn": mpn, + "manufacturer": part.get("manufacturer"), + "huaqiu_package_values": _package_values(part), + "search_queries": {"symbols": symbol_queries, "footprints": footprint_queries}, + "symbols": [summary for _, _, summary in symbols[:limit]], + "footprints": footprint_output, + "verified_pairs": safe_pairs, + "recommended_pair": recommended, + "review": { + "local_pin_pad_mapping_verified": bool(recommended), + "electrical_compatibility_confirmed": False, + "physical_package_confirmed": False, + "required": [ + "Confirm the exact manufacturer package dimensions and pitch against the datasheet or Huaqiu model.", + "Confirm the selected symbol pinout against the manufacturer datasheet.", + ], + }, + "huaqiu_model_metadata": model_files, + "huaqiu_model_files_downloaded": False, + } + if recommended: + result["spec_part_fields"] = { + "symbol": recommended["symbol"], + "footprint": recommended["footprint"], + "value": mpn, + } + else: + result["note"] = "No locally consistent KiCad symbol/footprint pair was found; do not invent library ids." + return result diff --git a/ui-plugins/kicad/server/huaqiu_model_inspector.py b/ui-plugins/kicad/server/huaqiu_model_inspector.py new file mode 100644 index 00000000..767cc11d --- /dev/null +++ b/ui-plugins/kicad/server/huaqiu_model_inspector.py @@ -0,0 +1,481 @@ +"""Safely compare Huaqiu's public KiCad text models with local KiCad libraries. + +The model files are untrusted network input. They are downloaded into memory +from a small allowlist, parsed as data, and never installed, written to disk, or +executed. A model-to-library match is useful evidence, but is not a substitute +for the manufacturer's datasheet. +""" +from __future__ import annotations + +import hashlib +import math +import re +import urllib.error +import urllib.request +from dataclasses import dataclass +from typing import Any +from urllib.parse import urlsplit + +from kicad import library as kicad_library +from kicad.library import FootprintInfo, Pad, Pin, SymbolInfo +from kicad.sexpr import children, find, flag, numbers, parse, value + + +MAX_MODEL_BYTES = 2 * 1024 * 1024 +ALLOWED_MODEL_HOSTS = frozenset({"file.eda.cn", "file1.eda.cn"}) +MODEL_EXTENSIONS = {"symbol": ".kicad_sym", "footprint": ".kicad_mod"} +_URL_FIELDS = ("url", "downloadUrl", "download_url", "fileUrl", "file_url") + + +class ModelInspectionError(ValueError): + """A safe, user-facing model download or parse failure.""" + + def __init__(self, message: str, code: str): + super().__init__(message) + self.code = code + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ANN201 + return None + + +@dataclass(frozen=True) +class DownloadedModel: + kind: str + url: str + text: str + byte_count: int + sha256: str + content_type: str | None + + def metadata(self) -> dict[str, Any]: + return { + "url": self.url, + "bytes": self.byte_count, + "sha256": self.sha256, + "content_type": self.content_type, + "persisted": False, + } + + +def _safe_model_url(url: Any, kind: str) -> str: + if kind not in MODEL_EXTENSIONS: + raise ModelInspectionError(f"Unknown model kind: {kind}", "invalid_model_kind") + if not isinstance(url, str) or not url.strip(): + raise ModelInspectionError(f"Huaqiu detail has no {kind} model URL", f"huaqiu_{kind}_model_missing") + url = url.strip() + parsed = urlsplit(url) + host = (parsed.hostname or "").lower() + if parsed.scheme.lower() != "https" or host not in ALLOWED_MODEL_HOSTS: + raise ModelInspectionError( + f"Refused {kind} model URL outside the allowed Huaqiu HTTPS file hosts", + "huaqiu_model_url_refused", + ) + try: + port = parsed.port + except ValueError as error: + raise ModelInspectionError(f"Refused unsafe {kind} model URL", "huaqiu_model_url_refused") from error + if parsed.username or parsed.password or port not in (None, 443) or parsed.fragment: + raise ModelInspectionError(f"Refused unsafe {kind} model URL", "huaqiu_model_url_refused") + if not parsed.path.lower().endswith(MODEL_EXTENSIONS[kind]): + raise ModelInspectionError( + f"Huaqiu {kind} URL does not end in {MODEL_EXTENSIONS[kind]}", + "huaqiu_model_extension_refused", + ) + return url + + +def model_url(models: Any, kind: str) -> str: + """Extract only the requested model kind from normalized Huaqiu detail.""" + if not isinstance(models, dict): + raise ModelInspectionError("Huaqiu detail has no EDA model metadata", "huaqiu_model_metadata_missing") + entry = models.get(kind) + if isinstance(entry, str): + return _safe_model_url(entry, kind) + if isinstance(entry, dict): + for field in _URL_FIELDS: + if entry.get(field): + return _safe_model_url(entry[field], kind) + raise ModelInspectionError(f"Huaqiu detail has no {kind} model URL", f"huaqiu_{kind}_model_missing") + + +def download_text_model( + url: str, + kind: str, + *, + timeout: float = 20, + max_bytes: int = MAX_MODEL_BYTES, + opener: Any = None, +) -> DownloadedModel: + """Download one allowlisted KiCad text model into memory with a hard cap.""" + url = _safe_model_url(url, kind) + if not isinstance(max_bytes, int) or max_bytes < 1 or max_bytes > MAX_MODEL_BYTES: + raise ModelInspectionError("Invalid model size limit", "invalid_model_size_limit") + request = urllib.request.Request( + url, + headers={"Accept": "text/plain, application/octet-stream;q=0.9", "User-Agent": "ZCode-KiCad/0.11"}, + method="GET", + ) + client = opener or urllib.request.build_opener(_NoRedirect()) + try: + response = client.open(request, timeout=timeout) + with response: + final_url = response.geturl() + if final_url != url: + raise ModelInspectionError("Huaqiu model redirect was refused", "huaqiu_model_redirect_refused") + length = response.headers.get("Content-Length") + if length: + try: + declared_length = int(length) + except ValueError as error: + raise ModelInspectionError("Huaqiu model has an invalid Content-Length", "huaqiu_model_invalid_response") from error + if declared_length > max_bytes: + raise ModelInspectionError("Huaqiu model exceeds the 2 MiB limit", "huaqiu_model_too_large") + chunks: list[bytes] = [] + total = 0 + while True: + chunk = response.read(min(64 * 1024, max_bytes + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > max_bytes: + raise ModelInspectionError("Huaqiu model exceeds the 2 MiB limit", "huaqiu_model_too_large") + chunks.append(chunk) + raw = b"".join(chunks) + content_type = response.headers.get_content_type() if hasattr(response.headers, "get_content_type") else response.headers.get("Content-Type") + except ModelInspectionError: + raise + except urllib.error.HTTPError as error: + if 300 <= error.code < 400: + raise ModelInspectionError("Huaqiu model redirect was refused", "huaqiu_model_redirect_refused") from error + raise ModelInspectionError(f"Huaqiu model download failed with HTTP {error.code}", "huaqiu_model_download_failed") from error + except (urllib.error.URLError, TimeoutError, OSError) as error: + raise ModelInspectionError(f"Huaqiu model download failed: {error}", "huaqiu_model_download_failed") from error + try: + text = raw.decode("utf-8-sig") + except UnicodeDecodeError as error: + raise ModelInspectionError("Huaqiu model is not valid UTF-8 text", "huaqiu_model_not_text") from error + return DownloadedModel(kind, url, text, len(raw), hashlib.sha256(raw).hexdigest(), content_type) + + +def _symbol_root(text: str) -> list: + node = parse(text) + if not node: + raise ModelInspectionError("Huaqiu symbol model is empty", "huaqiu_symbol_model_invalid") + if node[0] == "symbol": + return node + if node[0] != "kicad_symbol_lib": + raise ModelInspectionError("Huaqiu symbol model is not a KiCad symbol library", "huaqiu_symbol_model_invalid") + candidates = list(children(node, "symbol")) + if not candidates: + raise ModelInspectionError("Huaqiu symbol library contains no symbol", "huaqiu_symbol_model_invalid") + # Top-level aliases can occur; prefer the first definition that owns units. + return next((candidate for candidate in candidates if any(True for _ in children(candidate, "symbol"))), candidates[0]) + + +def parse_symbol_model(text: str) -> SymbolInfo: + node = _symbol_root(text) + name = str(node[1]) if len(node) > 1 else "HuaqiuModel" + props = {str(p[1]): str(p[2]) for p in children(node, "property") if len(p) >= 3} + pins: list[Pin] = [] + seen: set[str] = set() + units = list(children(node, "symbol")) or [node] + for unit_node in units: + match = re.search(r"_(\d+)_(\d+)$", str(unit_node[1]) if len(unit_node) > 1 else "") + unit = int(match.group(1)) if match else 1 + style = int(match.group(2)) if match else 1 + if style == 2: + continue + for pin_node in children(unit_node, "pin"): + number = str(value(pin_node, "number", "")) + if not number or number in seen: + continue + seen.add(number) + pins.append( + Pin( + number=number, + name=str(value(pin_node, "name", "")), + etype=str(pin_node[1]) if len(pin_node) > 1 else "unspecified", + unit=max(unit, 1), + hidden=flag(pin_node, "hide"), + ) + ) + if not pins: + raise ModelInspectionError("Huaqiu symbol model contains no pins", "huaqiu_symbol_model_invalid") + return SymbolInfo( + lib_id=f"Huaqiu:{name}", + ref_prefix=props.get("Reference", "U"), + value=props.get("Value", name), + description=props.get("Description", ""), + keywords=props.get("ki_keywords", ""), + datasheet=props.get("Datasheet", ""), + default_footprint=props.get("Footprint", ""), + fp_filters=tuple(props.get("ki_fp_filters", "").split()), + pins=tuple(pins), + ) + + +def _points_of(item: list) -> list[tuple[float, float]]: + points: list[tuple[float, float]] = [] + for key in ("start", "end", "center", "mid"): + vals = numbers(find(item, key)) + if len(vals) >= 2: + points.append((vals[0], vals[1])) + point_list = find(item, "pts") + if point_list: + for xy in children(point_list, "xy"): + vals = numbers(xy) + if len(vals) >= 2: + points.append((vals[0], vals[1])) + if item and item[0] == "fp_circle": + center, end = numbers(find(item, "center")), numbers(find(item, "end")) + if len(center) >= 2 and len(end) >= 2: + radius = math.hypot(end[0] - center[0], end[1] - center[1]) + points = [(center[0] - radius, center[1] - radius), (center[0] + radius, center[1] + radius)] + return points + + +def parse_footprint_model(text: str) -> FootprintInfo: + node = parse(text) + if not node or node[0] not in ("footprint", "module"): + raise ModelInspectionError("Huaqiu footprint model is not a KiCad footprint", "huaqiu_footprint_model_invalid") + name = str(node[1]) if len(node) > 1 else "HuaqiuModel" + pads: list[Pad] = [] + for pad_node in children(node, "pad"): + if len(pad_node) < 4: + continue + at, size = numbers(find(pad_node, "at")), numbers(find(pad_node, "size")) + layers_node = find(pad_node, "layers") + drill = None + drill_node = find(pad_node, "drill") + if drill_node: + vals = [v for v in drill_node[1:] if isinstance(v, str)] + try: + if vals and vals[0] == "oval": + drill = (float(vals[1]), float(vals[2])) + elif vals: + drill = (float(vals[0]), float(vals[0])) + except (ValueError, IndexError): + drill = None + pads.append( + Pad( + number=str(pad_node[1]), + ptype=str(pad_node[2]), + shape=str(pad_node[3]), + x=at[0] if at else 0.0, + y=at[1] if len(at) > 1 else 0.0, + w=size[0] if size else 0.0, + h=size[1] if len(size) > 1 else (size[0] if size else 0.0), + rotation=at[2] if len(at) > 2 else 0.0, + layers=tuple(layers_node[1:]) if layers_node else (), + drill=drill, + ) + ) + numbered = [pad for pad in pads if pad.number and not pad.is_np] + if not numbered: + raise ModelInspectionError("Huaqiu footprint model contains no numbered pads", "huaqiu_footprint_model_invalid") + courtyard_points: list[tuple[float, float]] = [] + for item in node: + if not isinstance(item, list) or not item or item[0] not in ("fp_rect", "fp_line", "fp_poly", "fp_circle", "fp_arc"): + continue + layer = find(item, "layer") + if layer and len(layer) > 1 and layer[1] in ("F.CrtYd", "B.CrtYd"): + courtyard_points.extend(_points_of(item)) + courtyard = None + if courtyard_points: + courtyard = ( + min(point[0] for point in courtyard_points), + min(point[1] for point in courtyard_points), + max(point[0] for point in courtyard_points), + max(point[1] for point in courtyard_points), + ) + attr_node = find(node, "attr") + return FootprintInfo( + lib_id=f"Huaqiu:{name}", + description=str(value(node, "descr", "")), + tags=str(value(node, "tags", "")), + attr=tuple(attr_node[1:]) if attr_node else (), + pads=tuple(pads), + courtyard=courtyard, + ) + + +def _name_key(value: str) -> str: + value = re.sub(r"~\{([^}]*)\}", r"\1", value or "") + return re.sub(r"[^a-z0-9]+", "", value.lower()) + + +def compare_symbols(remote: SymbolInfo, local: SymbolInfo) -> dict[str, Any]: + remote_pins = {pin.number: pin for pin in remote.pins} + local_pins = {pin.number: pin for pin in local.pins} + numbers_match = set(remote_pins) == set(local_pins) + shared = sorted(set(remote_pins) & set(local_pins), key=kicad_library.natural_key) + name_mismatches = [ + {"number": number, "huaqiu": remote_pins[number].display_name, "local": local_pins[number].display_name} + for number in shared + if _name_key(remote_pins[number].display_name) != _name_key(local_pins[number].display_name) + ] + type_mismatches = [ + {"number": number, "huaqiu": remote_pins[number].etype, "local": local_pins[number].etype} + for number in shared + if remote_pins[number].etype != local_pins[number].etype + ] + return { + "pin_numbers_match": numbers_match, + "pin_names_match": numbers_match and not name_mismatches, + "pin_types_match": numbers_match and not type_mismatches, + "huaqiu_pin_numbers": sorted(remote_pins, key=kicad_library.natural_key), + "local_pin_numbers": sorted(local_pins, key=kicad_library.natural_key), + "name_mismatches": name_mismatches, + "type_mismatches": type_mismatches, + "model_matches_local_symbol": numbers_match and not name_mismatches, + } + + +def _numbered_pads(footprint: FootprintInfo) -> list[Pad]: + return [pad for pad in footprint.pads if pad.number and not pad.is_np] + + +def _pad_number_counts(pads: list[Pad]) -> dict[str, int]: + counts: dict[str, int] = {} + for pad in pads: + counts[pad.number] = counts.get(pad.number, 0) + 1 + return counts + + +def _distance_fingerprint(pads: list[Pad]) -> dict[tuple[str, str], list[float]]: + result: dict[tuple[str, str], list[float]] = {} + for index, left in enumerate(pads): + for right in pads[index + 1 :]: + key = tuple(sorted((left.number, right.number), key=kicad_library.natural_key)) + result.setdefault(key, []).append(math.hypot(left.x - right.x, left.y - right.y)) + for values in result.values(): + values.sort() + return result + + +def _max_fingerprint_delta(left: dict, right: dict) -> float | None: + if set(left) != set(right) or any(len(left[key]) != len(right[key]) for key in left): + return None + return max((abs(a - b) for key in left for a, b in zip(left[key], right[key])), default=0.0) + + +def _pad_size_fingerprint(pads: list[Pad]) -> dict[str, list[tuple[float, float]]]: + result: dict[str, list[tuple[float, float]]] = {} + for pad in pads: + result.setdefault(pad.number, []).append((min(pad.w, pad.h), max(pad.w, pad.h))) + for values in result.values(): + values.sort() + return result + + +def _max_size_delta(left: dict[str, list[tuple[float, float]]], right: dict[str, list[tuple[float, float]]]) -> float | None: + if set(left) != set(right) or any(len(left[key]) != len(right[key]) for key in left): + return None + return max((abs(a - b) for key in left for ls, rs in zip(left[key], right[key]) for a, b in zip(ls, rs)), default=0.0) + + +def _pad_style_fingerprint(pads: list[Pad]) -> dict[str, list[tuple[Any, ...]]]: + result: dict[str, list[tuple[Any, ...]]] = {} + for pad in pads: + drill = tuple(round(value, 4) for value in pad.drill) if pad.drill else None + result.setdefault(pad.number, []).append((pad.ptype, pad.shape, drill)) + for values in result.values(): + values.sort(key=str) + return result + + +def _courtyard_size(footprint: FootprintInfo) -> list[float] | None: + if not footprint.courtyard: + return None + x0, y0, x1, y1 = footprint.courtyard + return sorted((x1 - x0, y1 - y0)) + + +def compare_footprints(remote: FootprintInfo, local: FootprintInfo) -> dict[str, Any]: + remote_pads, local_pads = _numbered_pads(remote), _numbered_pads(local) + number_counts_match = _pad_number_counts(remote_pads) == _pad_number_counts(local_pads) + geometry_delta = _max_fingerprint_delta(_distance_fingerprint(remote_pads), _distance_fingerprint(local_pads)) if number_counts_match else None + size_delta = _max_size_delta(_pad_size_fingerprint(remote_pads), _pad_size_fingerprint(local_pads)) if number_counts_match else None + styles_match = number_counts_match and _pad_style_fingerprint(remote_pads) == _pad_style_fingerprint(local_pads) + remote_courtyard, local_courtyard = _courtyard_size(remote), _courtyard_size(local) + courtyard_delta = ( + max(abs(a - b) for a, b in zip(remote_courtyard, local_courtyard)) + if remote_courtyard is not None and local_courtyard is not None + else None + ) + geometry_match = geometry_delta is not None and geometry_delta <= 0.05 + sizes_match = size_delta is not None and size_delta <= 0.05 + courtyard_match = courtyard_delta is not None and courtyard_delta <= 0.15 + exact = number_counts_match and geometry_match and sizes_match and styles_match and courtyard_match + return { + "pad_number_counts_match": number_counts_match, + "pad_geometry_match": geometry_match, + "pad_geometry_max_delta_mm": None if geometry_delta is None else round(geometry_delta, 4), + "pad_sizes_match": sizes_match, + "pad_size_max_delta_mm": None if size_delta is None else round(size_delta, 4), + "pad_types_shapes_drills_match": styles_match, + "courtyard_available": {"huaqiu": remote_courtyard is not None, "local": local_courtyard is not None}, + "courtyard_dimensions_match": courtyard_match, + "courtyard_max_delta_mm": None if courtyard_delta is None else round(courtyard_delta, 4), + "huaqiu_courtyard_mm": remote_courtyard, + "local_courtyard_mm": local_courtyard, + "model_matches_local_footprint": exact, + } + + +def inspect_part_models( + part: dict[str, Any], + symbol_id: str, + footprint_id: str, + *, + library: Any = kicad_library, + downloader=download_text_model, +) -> dict[str, Any]: + """Download both public models and compare them with explicit local ids.""" + try: + local_symbol = library.get_symbol(symbol_id) + local_footprint = library.get_footprint(footprint_id) + models = part.get("models") + symbol_download = downloader(model_url(models, "symbol"), "symbol") + footprint_download = downloader(model_url(models, "footprint"), "footprint") + remote_symbol = parse_symbol_model(symbol_download.text) + remote_footprint = parse_footprint_model(footprint_download.text) + except ModelInspectionError as error: + return {"ok": False, "error": str(error), "code": error.code} + except Exception as error: # one broken local library entry must be a structured tool error + return {"ok": False, "error": f"Could not read the selected local KiCad model: {error}", "code": "local_kicad_model_unavailable"} + + symbol_comparison = compare_symbols(remote_symbol, local_symbol) + footprint_comparison = compare_footprints(remote_footprint, local_footprint) + consistent = symbol_comparison["model_matches_local_symbol"] and footprint_comparison["model_matches_local_footprint"] + result: dict[str, Any] = { + "ok": True, + "error": None, + "mpn": part.get("mpn"), + "manufacturer": part.get("manufacturer"), + "local_candidate": {"symbol": symbol_id, "footprint": footprint_id}, + "downloads": { + "symbol": symbol_download.metadata(), + "footprint": footprint_download.metadata(), + "written_to_disk": False, + }, + "symbol_comparison": symbol_comparison, + "footprint_comparison": footprint_comparison, + "model_consistency_confirmed": consistent, + "review": { + "huaqiu_model_matches_local_candidate": consistent, + "electrical_compatibility_confirmed": False, + "physical_package_confirmed": False, + "required": [ + "Confirm the symbol pinout against the manufacturer's datasheet.", + "Confirm package dimensions, pitch, and thermal-pad requirements against the manufacturer's datasheet.", + ], + }, + } + if consistent: + result["spec_part_fields"] = {"symbol": symbol_id, "footprint": footprint_id, "value": str(part.get("mpn") or "")} + else: + result["note"] = "The Huaqiu text models do not fully match this local candidate; do not use it without manual review." + return result diff --git a/ui-plugins/kicad/server/huaqiu_part_search.py b/ui-plugins/kicad/server/huaqiu_part_search.py new file mode 100644 index 00000000..01355d56 --- /dev/null +++ b/ui-plugins/kicad/server/huaqiu_part_search.py @@ -0,0 +1,187 @@ +"""ZCode-native adapter for the public Huaqiu part database. + +The Huaqiu KiCad distribution bundles the Apache-2.0 +``@huaqiu/part-search`` library. We call that library in a short-lived child +process and do not start DSH, load DSH skills, or hand control to another +agent harness. +""" +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path +from typing import Any, Callable + + +HUAQIU_NODE_RELATIVE = Path("Contents/Resources/edge-headless/bin/node") +HUAQIU_PART_SEARCH_RELATIVE = Path( + "Contents/Resources/edge-headless/dsh-plugins/@huaqiu/node_modules/" + "@huaqiu/part-search/dist/esm/index.js" +) +OPERATIONS = frozenset({"search", "detail", "models", "supply"}) +MAX_SUPPLY_PARTS = 50 + + +def adapter_paths(app: Path) -> dict[str, Path]: + app = Path(app) + return { + "node": app / HUAQIU_NODE_RELATIVE, + "library": app / HUAQIU_PART_SEARCH_RELATIVE, + "bridge": Path(__file__).with_name("huaqiu_part_search_bridge.mjs"), + } + + +def _error(message: str, code: str, **extra: Any) -> dict[str, Any]: + return {"ok": False, "error": message, "code": code, **extra} + + +def _text(value: Any, field: str, *, maximum: int = 200) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{field} must be a non-empty string") + value = value.strip() + if len(value) > maximum: + raise ValueError(f"{field} is too long ({len(value)} > {maximum})") + return value + + +def _language(value: Any) -> str: + if value not in ("zh", "en"): + raise ValueError("language must be 'zh' or 'en'") + return str(value) + + +def search_arguments( + query: Any, + *, + page: Any = 1, + page_size: Any = 10, + require_eda_model: Any = True, + requirements: Any = None, + language: Any = "zh", +) -> dict[str, Any]: + query = _text(query, "query") + if isinstance(page, bool) or not isinstance(page, int) or page < 1: + raise ValueError("page must be an integer >= 1") + if isinstance(page_size, bool) or not isinstance(page_size, int) or not 1 <= page_size <= 50: + raise ValueError("page_size must be an integer from 1 to 50") + if not isinstance(require_eda_model, bool): + raise ValueError("require_eda_model must be a boolean") + if requirements is None: + requirements = {} + if not isinstance(requirements, dict): + raise ValueError("requirements must be an object") + allowed = {"symbol", "footprint", "model3d", "simulation", "supplier"} + unknown = sorted(set(requirements) - allowed) + if unknown: + raise ValueError(f"unknown requirements: {', '.join(unknown)}") + if any(not isinstance(value, bool) for value in requirements.values()): + raise ValueError("every requirements value must be a boolean") + return { + "query": query, + "page": page, + "pageSize": page_size, + "requireEdaModel": require_eda_model, + "requirements": dict(requirements), + "language": _language(language), + } + + +def part_arguments(manufacturer_id: Any, mpn: Any, *, language: Any = "zh") -> dict[str, Any]: + return { + "manufacturerId": _text(manufacturer_id, "manufacturer_id"), + "mpn": _text(mpn, "mpn"), + "language": _language(language), + } + + +def supply_arguments(parts: Any) -> dict[str, Any]: + if not isinstance(parts, list) or not parts: + raise ValueError("parts must be a non-empty array") + if len(parts) > MAX_SUPPLY_PARTS: + raise ValueError(f"parts has too many entries ({len(parts)} > {MAX_SUPPLY_PARTS})") + normalized = [] + for index, part in enumerate(parts): + if not isinstance(part, dict): + raise ValueError(f"parts[{index}] must be an object") + unknown = sorted(set(part) - {"manufacturer_id", "mpn"}) + if unknown: + raise ValueError(f"parts[{index}] has unknown fields: {', '.join(unknown)}") + normalized.append( + { + "manufacturerId": _text(part.get("manufacturer_id"), f"parts[{index}].manufacturer_id"), + "mpn": _text(part.get("mpn"), f"parts[{index}].mpn"), + } + ) + return {"parts": normalized} + + +def execute( + operation: str, + arguments: dict[str, Any], + *, + app: Path, + edition: str | None = None, + timeout: float = 35, + runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run, +) -> dict[str, Any]: + """Execute one fixed operation through Huaqiu's bundled normalized client.""" + if operation not in OPERATIONS: + return _error("Unsupported Huaqiu part-search operation", "invalid_operation") + selected = (edition or os.environ.get("ZCODE_KICAD_EDITION") or "auto").strip().lower() + selected = {"hq": "huaqiu", "official": "standard", "": "auto"}.get(selected, selected) + if selected == "auto": + root = Path(app) / "Contents/Resources/edge-headless" + selected = "huaqiu" if (root / "dsh").is_dir() or (root / "dsh-plugins").is_dir() else "standard" + if selected != "huaqiu": + return _error( + "Huaqiu part search requires the huaqiu plugin edition", + "huaqiu_edition_required", + requested_edition=selected, + ) + locations = adapter_paths(Path(app)) + missing = [name for name, path in locations.items() if not path.is_file()] + if missing: + return _error( + "The selected Huaqiu KiCad installation is missing its native part-search adapter", + "huaqiu_part_search_unavailable", + missing=missing, + ) + try: + completed = runner( + [str(locations["node"]), str(locations["bridge"]), str(locations["library"])], + input=json.dumps({"operation": operation, "arguments": arguments}, ensure_ascii=False), + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except subprocess.TimeoutExpired: + return _error("Huaqiu part search timed out", "huaqiu_part_search_timeout") + except OSError as error: + return _error(f"Could not start Huaqiu part search: {error}", "huaqiu_part_search_start_failed") + try: + response = json.loads((completed.stdout or "").strip()) + except (json.JSONDecodeError, TypeError): + detail = " ".join((completed.stderr or completed.stdout or "").split())[:500] + return _error( + "Huaqiu part search returned an invalid response", + "huaqiu_part_search_invalid_response", + detail=detail or None, + ) + if completed.returncode != 0 or not response.get("ok"): + remote = response.get("error") if isinstance(response, dict) else None + message = remote.get("message") if isinstance(remote, dict) else None + return _error( + str(message or "Huaqiu part search failed")[:1000], + "huaqiu_part_search_failed", + upstream=remote if isinstance(remote, dict) else None, + ) + return { + "ok": True, + "error": None, + "edition": "huaqiu", + "source": "Huaqiu public part database", + "operation": operation, + "result": response.get("result"), + } diff --git a/ui-plugins/kicad/server/huaqiu_part_search_bridge.mjs b/ui-plugins/kicad/server/huaqiu_part_search_bridge.mjs new file mode 100644 index 00000000..b6ecf133 --- /dev/null +++ b/ui-plugins/kicad/server/huaqiu_part_search_bridge.mjs @@ -0,0 +1,60 @@ +#!/usr/bin/env node +/** + * Narrow bridge to the Apache-2.0 @huaqiu/part-search library bundled with + * Huaqiu KiCad. The Python MCP server owns validation and chooses both paths; + * this process accepts no module name, URL, command, or JavaScript from tools. + */ +import { pathToFileURL } from "node:url"; + +const modulePath = process.argv[2]; + +function answer(value) { + process.stdout.write(`${JSON.stringify(value)}\n`); +} + +async function readInput() { + let text = ""; + for await (const chunk of process.stdin) text += chunk; + return JSON.parse(text); +} + +try { + if (!modulePath) throw new Error("Huaqiu part-search module path is missing"); + const request = await readInput(); + const allowed = new Set(["search", "detail", "models", "supply"]); + if (!request || !allowed.has(request.operation) || typeof request.arguments !== "object") { + throw new Error("Invalid Huaqiu part-search bridge request"); + } + + const library = await import(pathToFileURL(modulePath).href); + const service = library.createPartSearchService(); + const args = request.arguments; + let result; + if (request.operation === "search") { + result = await service.searchParts(args); + } else if (request.operation === "detail") { + result = await service.getPart( + { manufacturerId: args.manufacturerId, mpn: args.mpn }, + args.language, + ); + } else if (request.operation === "models") { + result = await service.getEdaModels( + { manufacturerId: args.manufacturerId, mpn: args.mpn }, + args.language, + ); + } else { + result = await service.getSupplyChain(args.parts); + } + answer({ ok: true, result }); +} catch (error) { + answer({ + ok: false, + error: { + name: error?.name || "Error", + code: error?.code || null, + message: String(error?.message || error).slice(0, 1000), + status: Number.isInteger(error?.status) ? error.status : null, + }, + }); + process.exitCode = 1; +} diff --git a/ui-plugins/kicad/server/kicad/config.py b/ui-plugins/kicad/server/kicad/config.py index 8de4878a..71349436 100644 --- a/ui-plugins/kicad/server/kicad/config.py +++ b/ui-plugins/kicad/server/kicad/config.py @@ -1,9 +1,12 @@ -"""Where the worker finds its data and KiCad. Reads no file at all: both locations come from the environment the plugin server was started with.""" +"""Where the worker finds its data and KiCad.""" from __future__ import annotations import os +from functools import lru_cache from pathlib import Path +from kicad_installation import select_installation + def data_dir() -> Path: d = Path(os.environ["ZCODE_KICAD_DATA_DIR"]).resolve() @@ -11,5 +14,13 @@ def data_dir() -> Path: return d +@lru_cache(maxsize=1) +def kicad_installation() -> dict[str, object]: + return select_installation( + os.environ.get("ZCODE_KICAD_APP"), + os.environ.get("ZCODE_KICAD_EDITION"), + ) + + def kicad_app_dir() -> Path: - return Path(os.environ.get("ZCODE_KICAD_APP") or "/Applications/KiCad/KiCad.app") + return Path(str(kicad_installation()["selected"]["path"])) diff --git a/ui-plugins/kicad/server/kicad/paths.py b/ui-plugins/kicad/server/kicad/paths.py index c488ed1b..07834f1c 100644 --- a/ui-plugins/kicad/server/kicad/paths.py +++ b/ui-plugins/kicad/server/kicad/paths.py @@ -1,6 +1,6 @@ """Single place that knows where KiCad lives. -Override with env ``ZCODE_KICAD_APP`` (path to ``KiCad.app``; default ``/Applications/KiCad/KiCad.app``). +Override with env ``ZCODE_KICAD_APP`` (path to ``KiCad.app``); otherwise discover the newest installed app matching ``ZCODE_KICAD_EDITION``. On Linux (Docker) fall back to ``kicad-cli`` on PATH and ``/usr/share/kicad``. """ from __future__ import annotations @@ -11,7 +11,7 @@ from functools import lru_cache from pathlib import Path -from .config import kicad_app_dir +from .config import kicad_app_dir, kicad_installation class KiCadMissing(RuntimeError): @@ -29,6 +29,10 @@ def app_dir() -> Path: return kicad_app_dir() +def installation_selection() -> dict[str, object]: + return kicad_installation() + + def kicad_cli() -> Path: p = _first_existing( app_dir() / "Contents/MacOS/kicad-cli", diff --git a/ui-plugins/kicad/server/kicad_capabilities.py b/ui-plugins/kicad/server/kicad_capabilities.py new file mode 100644 index 00000000..2e91e399 --- /dev/null +++ b/ui-plugins/kicad/server/kicad_capabilities.py @@ -0,0 +1,407 @@ +"""Read-only KiCad installation and integration diagnostics. + +The Huaqiu distribution keeps the normal KiCad.app layout and adds its DSH +runtime below ``Contents/Resources/edge-headless``. Detect that layout without +starting DSH: ZCode remains the only agent harness. +""" +from __future__ import annotations + +import os +import plistlib +import subprocess +import sys +from pathlib import Path +from typing import Any + +from huaqiu_part_search import adapter_paths + + +EDITIONS = ("auto", "standard", "huaqiu") +HUAQIU_REQUIRED_PLUGINS = ( + "@huaqiu/dsh-kicad", + "@huaqiu/dsh-kicad-drc", + "@huaqiu/dsh-tool-kicad-schematic-gen", + "@huaqiu/dsh-tool-part-search", + "@huaqiu/dsh-tool-symbol-footprint", +) + + +def _edition(value: str | None) -> str: + normalized = (value or "auto").strip().lower() + return {"official": "standard", "hq": "huaqiu", "": "auto"}.get(normalized, normalized) + + +def _dsh_plugins(app: Path) -> tuple[Path, list[str]]: + root = app / "Contents/Resources/edge-headless/dsh-plugins" + if not root.is_dir(): + return root, [] + names: list[str] = [] + try: + for entry in root.iterdir(): + if not entry.is_dir(): + continue + if entry.name.startswith("@"): + names.extend( + f"{entry.name}/{child.name}" + for child in entry.iterdir() + if child.is_dir() and (child / "package.json").is_file() + ) + elif (entry / "package.json").is_file(): + names.append(entry.name) + except OSError: + return root, [] + return root, sorted(names) + + +def _bundle_version(app: Path) -> str: + try: + with (app / "Contents/Info.plist").open("rb") as stream: + info = plistlib.load(stream) + return str(info.get("CFBundleShortVersionString") or info.get("CFBundleVersion") or "") + except (OSError, ValueError, TypeError): + return "" + + +def _python_can_import_pcbnew(python: Path | None) -> tuple[bool, str | None]: + if python is None or not python.is_file(): + return False, "KiCad's bundled Python was not found" + try: + result = subprocess.run( + [str(python), "-c", "import pcbnew"], capture_output=True, text=True, timeout=20 + ) + except (OSError, subprocess.TimeoutExpired) as error: + return False, str(error) + if result.returncode == 0: + return True, None + detail = " ".join((result.stderr or result.stdout).split())[:240] + return False, detail or "the bundled Python cannot import pcbnew" + + +def inspect_installation( + app: Path, + *, + cli: Path | None, + version: str, + python: Path | None, + python_importable: bool | None = None, + python_error: str | None = None, + ipc: dict[str, Any] | None = None, + requested_edition: str = "standard", + selection: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Return a stable report for the Standard and Huaqiu plugin editions.""" + app = Path(app) + cli = Path(cli) if cli is not None else None + python = Path(python) if python is not None else None + share = app / "Contents/SharedSupport" + library_paths = { + "symbols": share / "symbols", + "footprints": share / "footprints", + "models_3d": share / "3dmodels", + } + library_available = {name: path.is_dir() for name, path in library_paths.items()} + dsh_root, dsh_plugins = _dsh_plugins(app) + dsh_runtime = app / "Contents/Resources/edge-headless/dsh" + huaqiu_adapter_paths = adapter_paths(app) + huaqiu_adapter_available = { + name: path.is_file() for name, path in huaqiu_adapter_paths.items() + } + if not version or version == "unavailable": + version = _bundle_version(app) or "unavailable" + + app_available = app.is_dir() + cli_available = bool(cli and cli.is_file()) + if python_importable is None: + python_importable, detected_error = _python_can_import_pcbnew(python) + python_error = python_error or detected_error + core_ready = bool( + app_available + and cli_available + and python_importable + and library_available["symbols"] + and library_available["footprints"] + ) + + if dsh_plugins or dsh_runtime.is_dir(): + distribution = "huaqiu" + elif app_available and cli_available: + distribution = "official" + elif app_available: + distribution = "unknown" + else: + distribution = "missing" + + requested_edition = _edition(requested_edition) + valid_edition = requested_edition in EDITIONS + resolved_edition = ( + "huaqiu" + if requested_edition == "auto" and distribution == "huaqiu" + else "standard" + if requested_edition == "auto" and distribution == "official" + else requested_edition + if requested_edition != "auto" + else None + ) + expected_distribution = {"standard": "official", "huaqiu": "huaqiu"}.get(resolved_edition) + edition_mismatch = bool( + core_ready + and expected_distribution + and distribution not in (expected_distribution, "unknown", "missing") + ) + huaqiu_selected = resolved_edition == "huaqiu" + required_dsh_plugins = list(HUAQIU_REQUIRED_PLUGINS) if huaqiu_selected else [] + missing_dsh_plugins = [name for name in required_dsh_plugins if name not in dsh_plugins] + + ipc = dict(ipc or {}) + live_available = bool(ipc.get("available")) + missing: list[dict[str, Any]] = [] + if not app_available: + missing.append({"id": "kicad_app", "optional": False, "reason": f"KiCad.app not found at {app}"}) + if not cli_available: + missing.append({"id": "kicad_cli", "optional": False, "reason": "kicad-cli was not found"}) + for name in ("symbols", "footprints"): + if not library_available[name]: + missing.append({"id": f"kicad_{name}", "optional": False, "reason": f"KiCad {name} library was not found"}) + if not python_importable: + missing.append({"id": "pcbnew_python", "optional": False, "reason": python_error or "Python cannot import pcbnew"}) + if ipc.get("kipy") is False: + missing.append({"id": "kicad_python", "optional": True, "reason": ipc.get("reason") or "live KiCad API client is unavailable"}) + if not valid_edition: + missing.append( + { + "id": "kicad_edition", + "optional": False, + "reason": f"Unknown edition '{requested_edition}'; choose standard or huaqiu", + } + ) + elif edition_mismatch: + missing.append( + { + "id": "kicad_edition_mismatch", + "optional": False, + "reason": f"The {requested_edition} edition expects {expected_distribution} KiCad, but detected {distribution}", + } + ) + if requested_edition == "auto" and resolved_edition is None: + missing.append( + { + "id": "kicad_edition_auto_detection", + "optional": False, + "reason": "No official or Huaqiu KiCad installation could be identified", + } + ) + if huaqiu_selected and not dsh_runtime.is_dir(): + missing.append( + { + "id": "huaqiu_dsh_runtime", + "optional": False, + "reason": "The Huaqiu DSH runtime was not found in this KiCad.app", + } + ) + if huaqiu_selected and missing_dsh_plugins: + missing.append( + { + "id": "huaqiu_dsh_plugins", + "optional": False, + "reason": "Required Huaqiu KiCad components are missing", + "missing": missing_dsh_plugins, + } + ) + if huaqiu_selected and not huaqiu_adapter_available["node"]: + missing.append( + { + "id": "huaqiu_node", + "optional": False, + "reason": "Huaqiu KiCad's bundled Node.js runtime was not found", + } + ) + if huaqiu_selected and not huaqiu_adapter_available["library"]: + missing.append( + { + "id": "huaqiu_part_search_library", + "optional": False, + "reason": "Huaqiu KiCad's @huaqiu/part-search library was not found", + } + ) + if huaqiu_selected and not huaqiu_adapter_available["bridge"]: + missing.append( + { + "id": "huaqiu_part_search_bridge", + "optional": False, + "reason": "The ZCode Huaqiu part-search bridge is missing from the plugin installation", + } + ) + + edition_ready = bool( + valid_edition + and resolved_edition in ("standard", "huaqiu") + and core_ready + and not edition_mismatch + and ( + not huaqiu_selected + or ( + dsh_runtime.is_dir() + and not missing_dsh_plugins + and huaqiu_adapter_available["node"] + and huaqiu_adapter_available["library"] + and huaqiu_adapter_available["bridge"] + ) + ) + ) + + available_tools = [ + "kicad_board_view", + "kicad_capabilities", + "kicad_export_files", + "kicad_info", + "kicad_live_status", + "kicad_sync_edits", + "pcb_spec_example", + ] + if library_available["symbols"] and library_available["footprints"]: + available_tools.extend(["kicad_check_spec_file", "pcb_check_spec", "pcb_part_info", "pcb_search_parts"]) + if cli_available: + available_tools.extend( + [ + "kicad_3d_image", + "kicad_board_image", + "kicad_checks", + "kicad_layer_svg", + "kicad_layers", + "kicad_library_preview", + "kicad_schematic", + "pcb_export_fab", + "pcb_export_glb", + "pcb_render", + ] + ) + if core_ready: + available_tools.extend(["kicad_open_in_kicad", "pcb_build"]) + if live_available: + available_tools.extend(["kicad_live_status", "kicad_live_snapshot", "kicad_live_move_footprint"]) + if huaqiu_selected and edition_ready: + available_tools.extend( + [ + "get_hqsch_part", + "get_hqsch_part_models", + "get_hqsch_supply_chain", + "compare_hqsch_models_with_kicad", + "resolve_hqsch_part_for_kicad", + "search_hqsch_parts", + ] + ) + + return { + "ok": True, + "core_ready": core_ready, + "edition_ready": edition_ready, + "requested_edition": requested_edition, + "resolved_edition": resolved_edition, + "edition_mismatch": edition_mismatch, + "distribution": distribution, + "version": version or "unavailable", + "application": { + "available": app_available, + "path": str(app), + "selection": selection, + }, + "cli": {"available": cli_available, "path": str(cli) if cli else None, "version": version or "unavailable"}, + "python": { + "available": bool(python and python.is_file()), + "path": str(python) if python else None, + "pcbnew_importable": bool(python_importable), + "error": None if python_importable else python_error, + }, + "libraries": { + "available": library_available["symbols"] and library_available["footprints"], + "root": str(share), + **library_available, + }, + "ipc": { + "available": live_available, + "reachable": bool(ipc.get("reachable")), + "client_available": ipc.get("kipy") is not False, + "api_enabled_in_preferences": ipc.get("api_enabled_in_preferences"), + "reason": ipc.get("reason"), + }, + "dsh": { + "bundled": bool(dsh_plugins or dsh_runtime.is_dir()), + "runtime_path": str(dsh_runtime) if dsh_runtime.is_dir() else None, + "plugins_path": str(dsh_root) if dsh_root.is_dir() else None, + "plugins": dsh_plugins, + "exposed_to_zcode": False, + "note": "Detected only; ZCode does not start the bundled DSH harness.", + }, + "huaqiu_native_adapter": { + "available": all(huaqiu_adapter_available.values()), + "node_path": str(huaqiu_adapter_paths["node"]), + "part_search_library_path": str(huaqiu_adapter_paths["library"]), + "components": huaqiu_adapter_available, + "network_origin": "https://kiapi.eda.cn", + "authentication_required": False, + "starts_dsh": False, + "tools": [ + "search_hqsch_parts", + "get_hqsch_part", + "get_hqsch_part_models", + "get_hqsch_supply_chain", + "compare_hqsch_models_with_kicad", + "resolve_hqsch_part_for_kicad", + ], + }, + "edition": { + "name": resolved_edition, + "requested": requested_edition, + "automatic": requested_edition == "auto", + "valid": valid_edition, + "ready": edition_ready, + "expected_distribution": expected_distribution, + "detected_distribution": distribution, + "required_dsh_plugins": required_dsh_plugins, + "missing_dsh_plugins": missing_dsh_plugins, + }, + "available_tools": sorted(set(available_tools)), + "missing_dependencies": missing, + } + + +def detect( + paths_module: Any, + ipc: dict[str, Any] | None = None, + edition: str | None = None, +) -> dict[str, Any]: + """Collect paths safely, then delegate to :func:`inspect_installation`.""" + app = Path(paths_module.app_dir()) + try: + selection = dict(paths_module.installation_selection()) + except (AttributeError, TypeError, ValueError): + selection = None + try: + cli = Path(paths_module.kicad_cli()) + except Exception: # noqa: BLE001 - diagnostics must survive incomplete installs + cli = None + try: + python = Path(paths_module.kicad_python()) + except Exception: # noqa: BLE001 + python = None + try: + version = str(paths_module.kicad_version()) + except Exception: # noqa: BLE001 + version = "unavailable" + return inspect_installation( + app, + cli=cli, + version=version, + python=python, + ipc=ipc, + requested_edition=edition or os.environ.get("ZCODE_KICAD_EDITION") or "auto", + selection=selection, + ) + + +if __name__ == "__main__": + import json + from kicad import paths + + json.dump(detect(paths), sys.stdout, indent=2, ensure_ascii=False) + sys.stdout.write("\n") diff --git a/ui-plugins/kicad/server/kicad_installation.py b/ui-plugins/kicad/server/kicad_installation.py new file mode 100644 index 00000000..a1a45278 --- /dev/null +++ b/ui-plugins/kicad/server/kicad_installation.py @@ -0,0 +1,140 @@ +"""Deterministic discovery of an installed KiCad application. + +The plugin supports the official and Huaqiu KiCad 10 distributions. A user +can still select an exact ``KiCad.app`` path, but the default is intentionally +automatic: inspect the usual macOS application roots, identify each +distribution without starting it, and choose the newest installation matching +the requested edition. + +This module only reads application metadata and directory names. It never +starts KiCad or DSH and never changes an installation. +""" +from __future__ import annotations + +import plistlib +import re +from pathlib import Path +from typing import Iterable + + +DEFAULT_APP = Path("/Applications/KiCad/KiCad.app") +EDITIONS = ("auto", "standard", "huaqiu") + + +def normalize_edition(value: str | None) -> str: + normalized = (value or "auto").strip().lower() + return {"official": "standard", "hq": "huaqiu", "": "auto"}.get(normalized, normalized) + + +def distribution(app: Path) -> str: + root = Path(app) / "Contents/Resources/edge-headless" + if (root / "dsh").is_dir() or (root / "dsh-plugins").is_dir(): + return "huaqiu" + if Path(app).is_dir(): + return "official" + return "missing" + + +def bundle_version(app: Path) -> str: + try: + with (Path(app) / "Contents/Info.plist").open("rb") as stream: + info = plistlib.load(stream) + return str(info.get("CFBundleShortVersionString") or info.get("CFBundleVersion") or "") + except (OSError, ValueError, TypeError): + return "" + + +def _version_key(version: str) -> tuple[int, ...]: + numbers = tuple(int(part) for part in re.findall(r"\d+", version)[:4]) + return numbers or (0,) + + +def _default_roots() -> tuple[Path, ...]: + return (Path("/Applications"), Path.home() / "Applications") + + +def _candidate_paths(roots: Iterable[Path]) -> list[Path]: + found: list[Path] = [] + seen: set[Path] = set() + for raw_root in roots: + root = Path(raw_root).expanduser() + direct = (root / "KiCad/KiCad.app", root / "KiCad.app") + globbed: list[Path] = [] + if root.is_dir(): + for pattern in ("KiCad*/KiCad.app", "*KiCad*/KiCad.app", "*KiCad*.app"): + try: + globbed.extend(root.glob(pattern)) + except OSError: + continue + for app in (*direct, *globbed): + try: + key = app.resolve(strict=False) + except OSError: + key = app.absolute() + if key in seen or not (app / "Contents/MacOS/kicad-cli").is_file(): + continue + seen.add(key) + found.append(app) + return found + + +def _record(app: Path) -> dict[str, object]: + return { + "path": str(app), + "version": bundle_version(app) or "unknown", + "distribution": distribution(app), + "cli_available": (app / "Contents/MacOS/kicad-cli").is_file(), + } + + +def select_installation( + explicit: str | Path | None = None, + edition: str | None = None, + *, + roots: Iterable[Path] | None = None, +) -> dict[str, object]: + """Select one KiCad.app and describe why it was selected. + + An explicit non-empty path always wins, including when it is missing; the + capability report must show that exact configuration error instead of + silently switching installations. Automatic selection prefers the newest + installation matching ``standard`` or ``huaqiu``. With ``auto`` it picks + the newest detected installation and resolves the edition from its layout. + """ + requested = normalize_edition(edition) + explicit_text = str(explicit).strip() if explicit is not None else "" + if explicit_text: + app = Path(explicit_text).expanduser() + item = _record(app) + return { + "mode": "explicit", + "reason": "user_config", + "requested_edition": requested, + "resolved_edition": "huaqiu" if item["distribution"] == "huaqiu" else "standard" if item["distribution"] == "official" else None, + "selected": item, + "candidates": [item] if app.is_dir() else [], + } + + records = [_record(app) for app in _candidate_paths(roots or _default_roots())] + records.sort( + key=lambda item: ( + _version_key(str(item["version"])), + bool(item["cli_available"]), + str(item["path"]), + ), + reverse=True, + ) + expected = {"standard": "official", "huaqiu": "huaqiu"}.get(requested) + matching = [item for item in records if item["distribution"] == expected] if expected else [] + selected = ((matching if expected else records) or records or [_record(DEFAULT_APP)])[0] + selected_distribution = str(selected["distribution"]) + resolved = "huaqiu" if selected_distribution == "huaqiu" else "standard" if selected_distribution == "official" else None + reason = "newest_matching_installation" if expected and matching else "newest_detected_installation" if records else "default_path_not_found" + return { + "mode": "automatic", + "reason": reason, + "requested_edition": requested, + "resolved_edition": resolved, + "selected": selected, + "candidates": records, + } diff --git a/ui-plugins/kicad/server/kicad_launch.py b/ui-plugins/kicad/server/kicad_launch.py index 6fb8ee3e..86a8058a 100644 --- a/ui-plugins/kicad/server/kicad_launch.py +++ b/ui-plugins/kicad/server/kicad_launch.py @@ -1,30 +1,41 @@ -"""Start the KiCad PCB Editor on macOS and say honestly whether it is running afterwards. +"""Start one exact KiCad PCB Editor process and verify its live-API socket. -`open -a` exits 0 as soon as Launch Services has accepted the request, even if the program dies a moment later. The case that motivated this module: a KiCad -copied into /Applications with the download quarantine flag is "translocated" by Launch Services (only the nested pcbnew.app is run from a random read-only -copy), dyld cannot find @rpath/libkicommon.*.dylib there and pcbnew aborts before any window appears, while `open` reports success. +Do not use ``open -a`` here. Launch Services is allowed to reuse an already running +standalone PCB Editor, which means the requested board can open in a process that has +no KiCad 10 API server. Executing the selected distribution's pcbnew binary creates a +fresh process and, when "Enable KiCad API" is on, a matching ``api-.sock`` (or the +first ``api.sock``). This is what lets ZCode and that exact editor communicate live. -So after `open` we wait for a `pcbnew` process that stays alive; if it never shows up, or dies again, we look for the crash report macOS wrote -(~/Library/Logs/DiagnosticReports/pcbnew-*.ips), put the reason into the note and, for the quarantine case, name the command the *user* must run. This code never -changes an attribute itself. +We still watch the child long enough to catch the quarantined/App-Translocation crash +that motivated the old launcher. Crash reports are diagnosed read-only and any xattr +command is merely shown to the user; this module never changes an attribute itself. -Standard library only: test/test_launch.py tests it with fake `open`, `pgrep` and `xattr` programs on PATH and a fixture crash report. +Standard library only; test/test_launch.py uses a fake pcbnew executable. """ from __future__ import annotations import json import os import shlex +import stat import subprocess import time from pathlib import Path +from typing import Any, Callable -PROCESS = "pcbnew" -APPEAR_S = 8.0 # how long pcbnew may take to show up after `open` STABLE_S = 2.0 # how long it must then stay alive REPORT_S = 4.0 # how long to wait for the crash reporter once pcbnew is gone POLL_S = 0.25 +SOCKET_S = 8.0 # the window may be visible shortly before the API server is listening +BOARD_S = 8.0 # the socket can exist before pcbnew has opened the requested board (or while a lock dialog is showing) +SOCKET_DIR = Path("/tmp/kicad") QUARANTINE = "com.apple.quarantine" +_children: list[subprocess.Popen] = [] # keep detached GUI Popen objects alive; otherwise Python warns while the intentional child is still running + + +def reap_children() -> None: + """Forget GUI children that have exited; live ones remain deliberately detached.""" + _children[:] = [child for child in _children if child.poll() is None] def reports_dir() -> Path: @@ -45,14 +56,6 @@ def _run(cmd: list[str], timeout: float) -> subprocess.CompletedProcess | None: return None -def _running() -> bool | None: - """Is a process named pcbnew alive? None when pgrep itself cannot tell (missing, blocked, failing).""" - r = _run(["pgrep", "-x", PROCESS], 5) - if r is None or r.returncode not in (0, 1): - return None - return r.returncode == 0 - - def newest_report(report_dir: Path, since: float) -> Path | None: """The newest pcbnew-*.ips written at or after `since` (epoch seconds), or None.""" best: tuple[float, Path] | None = None @@ -109,40 +112,107 @@ def _quarantine_hint(app_dir: Path, translocated: bool) -> str: return f" {cause} Fix it yourself in Terminal, then open the board again: xattr -dr {QUARANTINE} {shlex.quote(str(fix_dir(app_dir)))}" -def launch_editor(editor: Path, pcb: Path, app_dir: Path, *, report_dir: Path | None = None, appear_s: float = APPEAR_S, stable_s: float = STABLE_S, - report_s: float = REPORT_S, poll_s: float = POLL_S) -> tuple[bool, str]: - """`open -a editor pcb`, then check that pcbnew really runs. Returns (launched, note); launched is False when it never appeared or died again. - Takes up to appear_s + stable_s seconds (about 10 s with the defaults), a bit more when it has to wait for a crash report.""" +def pcbnew_executable(editor: Path) -> Path: + """The canonical executable inside either ``PCB Editor.app`` or nested ``pcbnew.app``. + + KiCad's macOS installer makes ``PCB Editor.app`` a symlink. Executing pcbnew + through that outer spelling opens the GUI but does not start its API server; + resolving it to the nested app before ``exec`` is therefore functional, not cosmetic. + """ + return (editor / "Contents" / "MacOS" / "pcbnew").resolve() + + +def _socket_ready(path: Path) -> bool: + try: + return stat.S_ISSOCK(path.stat().st_mode) + except OSError: + return False + + +def wait_for_live_board(pcb: Path, status: Callable[[str, Path | None], dict[str, Any]], workspace: Path | None = None, *, + board_s: float = BOARD_S, poll_s: float = POLL_S) -> tuple[bool, dict[str, Any]]: + """Wait until the live API reports that *pcb* is the open session board. + + A KiCad API socket only proves that an editor process is alive. The board can + still be unopened because pcbnew is starting or is displaying a project-lock + dialog. Keep this distinction explicit so callers never report a false live + connection. ``status`` is injected to keep this helper hermetic in tests. + """ + deadline = time.monotonic() + max(0.0, board_s) + last: dict[str, Any] = {} + while True: + try: + last = status(str(pcb), workspace) + except Exception as error: # noqa: BLE001 - a diagnostic callback must not turn a successful GUI launch into an exception + last = {"available": False, "reason": f"live board verification failed: {error}"} + if last.get("available"): + return True, last + # These states cannot become ready merely by waiting for this process. + if last.get("kipy") is False or last.get("api_enabled_in_preferences") is False: + return False, last + if time.monotonic() >= deadline: + return False, last + time.sleep(max(0.001, poll_s)) + + +def launch_editor(editor: Path, pcb: Path, app_dir: Path, *, report_dir: Path | None = None, socket_dir: Path = SOCKET_DIR, stable_s: float = STABLE_S, + socket_s: float = SOCKET_S, report_s: float = REPORT_S, poll_s: float = POLL_S, env: dict[str, str] | None = None, + api_expected: bool | None = None) -> tuple[bool, str]: + """Execute this distribution's pcbnew with ``pcb`` and watch that exact child. + + Returns ``(launched, note)``. ``launched`` means the GUI process survived the + stability window; the note separately says whether its live API socket appeared. + No socket is treated as a usable file-round-trip editor, not as a failed launch. + """ reports = report_dir if report_dir is not None else reports_dir() + reap_children() + exe = pcbnew_executable(editor) + if not exe.is_file() or not os.access(exe, os.X_OK): + return False, f"KiCad PCB Editor executable not found or not executable: {exe}" + try: + socket_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + default_socket = socket_dir / "api.sock" + default_existed = default_socket.exists() + except OSError as e: + return False, f"could not prepare the KiCad live API directory: {e}" started = time.time() try: - r = subprocess.run(["open", "-a", str(editor), str(pcb)], capture_output=True, text=True, timeout=30) - except (OSError, subprocess.TimeoutExpired) as e: - return False, f"could not start KiCad: {e}" - if r.returncode != 0: - return False, f"open failed: {r.stderr.strip()[:200]}" - - t0 = time.monotonic() - seen: float | None = None - died = False - while True: - alive = _running() - now = time.monotonic() - if alive is None: - return True, f"opened in {editor.name} (could not check that it stays running: pgrep is unavailable)" - if alive: - seen = now if seen is None else seen - if now - seen >= stable_s: - return True, f"opened in {editor.name}" - elif seen is not None: - died = True - break - elif newest_report(reports, started) is not None or now - t0 >= appear_s: # crashed before we ever saw it, or never started + child = subprocess.Popen( + [str(exe), str(pcb)], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + env=env, + ) + _children.append(child) + except OSError as e: + note = f"could not start KiCad: {e}" + if _quarantined(app_dir): + note += _quarantine_hint(app_dir, False) + return False, note + + pid_socket = socket_dir / f"api-{child.pid}.sock" + + stable_at = time.monotonic() + stable_s + while time.monotonic() < stable_at: + if child.poll() is not None: break time.sleep(poll_s) + if child.poll() is None: + deadline = time.monotonic() + socket_s + while time.monotonic() < deadline and child.poll() is None: + if _socket_ready(pid_socket) or (not default_existed and _socket_ready(default_socket)): + return True, f"opened in {editor.name}; live KiCad API socket ready" + time.sleep(poll_s) + if child.poll() is None: + if api_expected is True: + return True, (f'opened in {editor.name}, but its live API socket did not appear even though "Enable KiCad API" is on; ' + "close any older PCB Editor window or project-lock dialog for this board, then try again (file save/sync still works)") + return True, f'opened in {editor.name}, but its live API did not appear; enable "Enable KiCad API" in KiCad Preferences for real-time access (file save/sync still works)' report = newest_report(reports, started) - if report is None and died: # the crash reporter writes its file a moment after the process is gone + if report is None: deadline = time.monotonic() + report_s while report is None and time.monotonic() < deadline: time.sleep(poll_s) @@ -150,10 +220,9 @@ def launch_editor(editor: Path, pcb: Path, app_dir: Path, *, report_dir: Path | reason, translocated = crash_reason(report) if report else ("", False) if report is not None: what = f"PCB Editor crashed right after it was opened ({reason or report.name})." - elif died: - what = f"PCB Editor started but quit again within {stable_s:g} s (no crash report found)." else: - what = f"PCB Editor did not start within {appear_s:g} s (no pcbnew process and no crash report found)." + code = child.returncode + what = f"PCB Editor quit right after it was opened (exit {code}; no crash report found)." if translocated or _quarantined(app_dir): what += _quarantine_hint(app_dir, translocated) return False, what diff --git a/ui-plugins/kicad/server/kicad_live.py b/ui-plugins/kicad/server/kicad_live.py index 99d44e69..01fa936b 100644 --- a/ui-plugins/kicad/server/kicad_live.py +++ b/ui-plugins/kicad/server/kicad_live.py @@ -181,7 +181,8 @@ def _status_for(editors: list[dict], stale: int, cooling: int, session_pcb: str reason = f'No KiCad editor answers on the API. If it is off, tick "{SETTING}" in KiCad Preferences, then open the board in the PCB Editor.' return {**base, "reason": reason}, None, None ed, entry = _pick(editors, session_pcb) - base.update(reachable=True, kicad_version=editors[0]["version"], api_version=editors[0]["api_version"], editors=len(editors), boards_open=[Path(b[0]).name for e in editors for b in e["boards"]]) + reported = ed or editors[0] # with Standard and Huaqiu open together, report the edition that actually owns the selected/session board + base.update(reachable=True, kicad_version=reported["version"], api_version=reported["api_version"], editors=len(editors), boards_open=[Path(b[0]).name for e in editors for b in e["boards"]]) if entry is None: return {**base, "reason": "KiCad answers on the API, but no PCB Editor has a board open (a schematic editor or the project manager alone serves no boards)."}, None, None matches = _same_file(entry[0], session_pcb) if session_pcb else None diff --git a/ui-plugins/kicad/server/kicad_server.py b/ui-plugins/kicad/server/kicad_server.py index 4fb60ca8..ff65cfe2 100644 --- a/ui-plugins/kicad/server/kicad_server.py +++ b/ui-plugins/kicad/server/kicad_server.py @@ -6,7 +6,7 @@ Locations workspace ZCODE_WORKSPACE_ROOT files the agent can see; `kicad_export_files` writes to ./kicad/out here plugin data ZCODE_PLUGIN_DATA per-workspace artifact store (specs, boards, renders, fab files) and KiCad's private config - KiCad ZCODE_KICAD_APP default /Applications/KiCad/KiCad.app (kicad-cli, its bundled Python and the libraries are used from there) + KiCad ZCODE_KICAD_APP optional exact KiCad.app; otherwise the installed official/Huaqiu distribution is discovered automatically Tools: the worker's pcb_* tools (project_id bound here), kicad_* helpers, kicad_board_view (opens the panel), pcb_export_glb / kicad_checks, the app-only tools behind the panel tabs (layers, 3D views, schematic, library drawings: kicad-cli, see kicad_views.py), the KiCad GUI round trip and the live link to the running PCB Editor (kicad_live_*, see kicad_live.py). skills/kicad-board/SKILL.md is the @@ -32,6 +32,7 @@ WORKSPACE = Path(os.environ.get("ZCODE_WORKSPACE_ROOT") or os.getcwd()).resolve() PLUGIN_DATA = Path(os.environ.get("ZCODE_PLUGIN_DATA") or (WORKSPACE / ".kicad-plugin")).resolve() ROOT = PLUGIN_DATA / f"ws-{hashlib.sha1(str(WORKSPACE).encode()).hexdigest()[:10]}" +GUI_ENV = os.environ.copy() # captured before the worker's private KiCad config overrides below; the real GUI must use the user's settings (including Enable KiCad API) os.environ.setdefault("ZCODE_KICAD_DATA_DIR", str(PLUGIN_DATA / "kicad-env")) # Every KiCad program rewrites the settings it loads, even `kicad-cli version` (it stores the current directory as the working directory in kicad_common.json). So all # KiCad subprocesses of this server run on a private config and documents folder (the worker's own default, set early so no call can bypass it) and never touch the @@ -47,9 +48,13 @@ import kicad_live as live # noqa: E402 import kicad_views as kv # noqa: E402 -from kicad_launch import launch_editor # noqa: E402 +import kicad_capabilities as capabilities # noqa: E402 +import huaqiu_part_search as hq_parts # noqa: E402 +import huaqiu_kicad_resolver as hq_resolver # noqa: E402 +import huaqiu_model_inspector as hq_models # noqa: E402 +from kicad_launch import launch_editor, wait_for_live_board # noqa: E402 from kicad.store import ArtifactStore # noqa: E402 -from kicad import examples, paths, verify # noqa: E402 +from kicad import examples, library as kicad_library, paths, verify # noqa: E402 from kicad import mcp_server as worker # noqa: E402 from kicad.pipeline import ORIGIN_MM # noqa: E402 from kicad.service import PcbService # noqa: E402 @@ -136,10 +141,11 @@ def _in_workspace(raw: str | Path) -> Path: "kicad", version=PLUGIN_VERSION, instructions=( - "KiCad 10 inside ZCode. Design a 2-layer board from a JSON circuit spec: pcb_search_parts / pcb_part_info (never guess pin numbers or library ids) -> " + "KiCad 10 inside ZCode, automatically connected to an installed official or Huaqiu distribution. Design a 2-layer board from a JSON circuit spec: pcb_search_parts / pcb_part_info (never guess pin numbers or library ids) -> " "kicad_check_spec_file or pcb_check_spec -> pcb_build (place hints, auto-route, DRC) -> pcb_render -> pcb_export_fab -> kicad_export_files; kicad_checks gives DRC (and ERC) details, pcb_export_glb a 3D model with a part table. Coordinates are mm, " "origin top-left, +y down. A board is manufacturable only when pcb_build returns ok=true (DRC 0 errors, 0 unconnected). Start from pcb_spec_example (default: a 555 LED " - "blinker). kicad_board_view opens the board panel for the human; you cannot see pictures, so judge by the DRC and routing numbers." + "blinker). kicad_board_view opens the board panel for the human; you cannot see pictures, so judge by the DRC and routing numbers. " + "When kicad_capabilities reports resolved_edition=huaqiu and edition_ready=true, search_hqsch_parts and the get_hqsch_* tools provide Huaqiu's public part data; resolve_hqsch_part_for_kicad maps a chosen result to checked local KiCad candidates, and compare_hqsch_models_with_kicad safely compares Huaqiu's public text models with one candidate. DSH is never started." ), ) @@ -169,6 +175,136 @@ def kicad_info() -> dict: return _ok(kicad_version=paths.kicad_version(), workspace=str(WORKSPACE), store=str(store.root), artifacts=[_art(a) for a in arts[-MAX_LISTED_ARTIFACTS:]], artifacts_total=len(arts)) +@mcp.tool(annotations={"title": "KiCad capabilities", "readOnlyHint": True, "openWorldHint": False}) +def kicad_capabilities() -> dict: + """Diagnose KiCad without changing it: automatic/explicit app selection, requested and resolved edition (standard/Huaqiu), detected distribution, edition readiness, CLI, libraries, bundled + pcbnew Python, live IPC, bundled DSH runtime, tools that can run, and structured missing dependencies. Bundled DSH is reported but never started: ZCode remains the only agent harness.""" + return { + **capabilities.detect(paths, live.status(_session_pcb(), WORKSPACE)), + "plugin_version": PLUGIN_VERSION, + } + + +def _run_huaqiu_part_search(operation: str, arguments: dict[str, Any]) -> dict: + return hq_parts.execute( + operation, + arguments, + app=paths.app_dir(), + edition=os.environ.get("ZCODE_KICAD_EDITION"), + ) + + +@mcp.tool(annotations={"title": "Search Huaqiu parts", "readOnlyHint": True, "openWorldHint": True}) +def search_hqsch_parts( + query: str, + page: int = 1, + page_size: int = 10, + require_eda_model: bool = True, + requirements: dict[str, bool] | None = None, + language: str = "zh", +) -> dict: + """Search Huaqiu's public component database in the Huaqiu edition. Returns normalized part summaries and pagination. query is an MPN, manufacturer, category, or keyword (max 200 chars); page_size is 1..50. requirements may set symbol, footprint, model3d, simulation, or supplier booleans. Data is sent to kiapi.eda.cn; no Huaqiu login is used and DSH is not started.""" + try: + arguments = hq_parts.search_arguments( + query, + page=page, + page_size=page_size, + require_eda_model=require_eda_model, + requirements=requirements, + language=language, + ) + except ValueError as error: + return _err(str(error), code="invalid_arguments") + return _run_huaqiu_part_search("search", arguments) + + +@mcp.tool(annotations={"title": "Get a Huaqiu part", "readOnlyHint": True, "openWorldHint": True}) +def get_hqsch_part(manufacturer_id: str, mpn: str, language: str = "zh") -> dict: + """Get normalized Huaqiu component details: manufacturer, description, package, lifecycle, categories, attributes, documents, images, models, and tags. Use manufacturer_id and mpn from search_hqsch_parts. Huaqiu edition only; sends those identifiers to kiapi.eda.cn without login and never starts DSH.""" + try: + arguments = hq_parts.part_arguments(manufacturer_id, mpn, language=language) + except ValueError as error: + return _err(str(error), code="invalid_arguments") + return _run_huaqiu_part_search("detail", arguments) + + +@mcp.tool(annotations={"title": "Get Huaqiu EDA models", "readOnlyHint": True, "openWorldHint": True}) +def get_hqsch_part_models(manufacturer_id: str, mpn: str, language: str = "zh") -> dict: + """Get Huaqiu metadata for a part's symbol, footprint, 3D, and simulation models. This returns metadata and URLs; it does not download or install models. Use identifiers from search_hqsch_parts. Huaqiu edition only; no login or DSH harness.""" + try: + arguments = hq_parts.part_arguments(manufacturer_id, mpn, language=language) + except ValueError as error: + return _err(str(error), code="invalid_arguments") + return _run_huaqiu_part_search("models", arguments) + + +@mcp.tool(annotations={"title": "Get Huaqiu supply-chain offers", "readOnlyHint": True, "openWorldHint": True}) +def get_hqsch_supply_chain(parts: list[dict[str, str]]) -> dict: + """Get normalized Huaqiu supply-chain offers for 1..50 components. Each item must contain manufacturer_id and mpn from search_hqsch_parts. Results can include stock, MOQ, lead time, distributor URL, currency, and price breaks. Huaqiu edition only; sends identifiers to kiapi.eda.cn without login and never starts DSH.""" + try: + arguments = hq_parts.supply_arguments(parts) + except ValueError as error: + return _err(str(error), code="invalid_arguments") + return _run_huaqiu_part_search("supply", arguments) + + +@mcp.tool(annotations={"title": "Resolve a Huaqiu part for KiCad", "readOnlyHint": True, "openWorldHint": True}) +def resolve_hqsch_part_for_kicad( + manufacturer_id: str, + mpn: str, + language: str = "zh", + max_candidates: int = 5, +) -> dict: + """Resolve one Huaqiu part to ranked symbol/footprint pairs from the configured KiCad installation. It fetches normalized Huaqiu detail, searches only local KiCad libraries, and returns pairs only after checking the symbol's footprint filters and same-numbered pin/pad mapping. The result includes spec_part_fields when a candidate exists, but deliberately leaves electrical pinout and exact physical package confirmation to datasheet review. It does not download Huaqiu model files, modify libraries, write a project, or start DSH.""" + if not paths.libraries_available(): + return _err("KiCad symbol and footprint libraries are unavailable", code="kicad_libraries_unavailable") + try: + arguments = hq_parts.part_arguments(manufacturer_id, mpn, language=language) + if isinstance(max_candidates, bool) or not 1 <= int(max_candidates) <= 10: + raise ValueError("max_candidates must be an integer from 1 to 10") + except (TypeError, ValueError) as error: + return _err(str(error), code="invalid_arguments") + detail = _run_huaqiu_part_search("detail", arguments) + if not detail.get("ok"): + return detail + resolved = hq_resolver.resolve_part(detail.get("result") or {}, limit=int(max_candidates)) + return { + **resolved, + "edition": "huaqiu", + "source": "Huaqiu public part database + local KiCad libraries", + } + + +@mcp.tool(annotations={"title": "Compare Huaqiu and local KiCad models", "readOnlyHint": True, "openWorldHint": True}) +def compare_hqsch_models_with_kicad( + manufacturer_id: str, + mpn: str, + symbol: str, + footprint: str, + language: str = "zh", +) -> dict: + """Compare one explicit local KiCad symbol/footprint candidate with Huaqiu's public .kicad_sym and .kicad_mod text models. Use identifiers from search_hqsch_parts and a pair from resolve_hqsch_part_for_kicad. The files are accepted only from allowlisted Huaqiu HTTPS file hosts, limited to 2 MiB each, held in memory, parsed as untrusted data, and never installed or written. Pin names/numbers, numbered-pad geometry and sizes, and courtyard dimensions are compared; a match still does not replace manufacturer-datasheet review or confirm electrical/physical compatibility. Huaqiu edition only; never starts DSH.""" + if not paths.libraries_available(): + return _err("KiCad symbol and footprint libraries are unavailable", code="kicad_libraries_unavailable") + try: + arguments = hq_parts.part_arguments(manufacturer_id, mpn, language=language) + # Validate library-id shape before any network call. Actual existence is + # checked by the inspector after normalized Huaqiu detail is returned. + kicad_library.split_lib_id(symbol) + kicad_library.split_lib_id(footprint) + except (KeyError, TypeError, ValueError) as error: + return _err(str(error), code="invalid_arguments") + detail = _run_huaqiu_part_search("detail", arguments) + if not detail.get("ok"): + return detail + compared = hq_models.inspect_part_models(detail.get("result") or {}, symbol, footprint) + return { + **compared, + "edition": "huaqiu", + "source": "Huaqiu public KiCad text models + local KiCad libraries", + } + + @mcp.tool(annotations={"title": "Write an example circuit spec", "readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, "openWorldHint": False}) def pcb_spec_example(name: str = "ne555_blinker", write_to: str = "", inline: bool = False, overwrite: bool = False) -> dict: """A small, complete, DRC-clean circuit spec to start from, written into the workspace (default ./kicad/_spec.json). name: 'ne555_blinker' (NE555 astable LED flasher, about 1 Hz, @@ -292,16 +428,27 @@ def _editor_app() -> Path | None: return None -def _launch(pcb: Path) -> tuple[bool, str]: +def _launch(pcb: Path) -> tuple[bool, bool, str]: if NO_LAUNCH: - return False, "launch disabled (KICAD_PLUGIN_NO_LAUNCH=1)" + return False, False, "launch disabled (KICAD_PLUGIN_NO_LAUNCH=1)" if sys.platform != "darwin": - return False, "automatic launch is implemented for macOS only: open the file in KiCad yourself" + return False, False, "automatic launch is implemented for macOS only: open the file in KiCad yourself" + current = live.status(str(pcb), WORKSPACE) + if current.get("available"): + return True, True, "already open in PCB Editor; live KiCad API ready" editor = _editor_app() if editor is None: - return False, f"KiCad PCB Editor not found next to {paths.app_dir()}" - # `open` exits 0 even when pcbnew dies right away (quarantined KiCad -> App Translocation -> dyld error): launch_editor checks that it stays up and explains why not - return launch_editor(editor, pcb, paths.app_dir()) + return False, False, f"KiCad PCB Editor not found next to {paths.app_dir()}" + # Execute this distribution's exact pcbnew instead of `open -a`: Launch Services may reuse a standalone editor that has no live API. The helper watches this child and its socket. + launched, note = launch_editor(editor, pcb, paths.app_dir(), env=GUI_ENV, api_expected=live.preferences_enable_api()) + if not launched or "live KiCad API socket ready" not in note: + return launched, False, note + ready, status = wait_for_live_board(pcb, live.status, WORKSPACE) + if ready: + return True, True, note.replace("live KiCad API socket ready", "live KiCad API ready") + reason = status.get("reason") or "the requested board was not reported by the live API" + return True, False, (f"{note}, but the requested board did not open: {reason} " + "Check KiCad for a project-lock or recovery dialog; the file save/sync round trip still works after the board is open.") def _sync_locked() -> dict: @@ -369,8 +516,8 @@ def kicad_open_in_kicad(artifact_id: str = "") -> dict: verify.write_project_file(pcb, Rules.model_validate(art.meta.get("rules") or {}), art.meta.get("power_nets") or []) sess = {"pcb": str(pcb), "head_artifact_id": art.artifact_id, "imported_sha": _sha(pcb), "imports": [], "opened_at": _now()} _save_session(sess) - launched, note = _launch(pcb) # outside the lock: it can take ~10 s while the panel keeps polling - return _ok(pcb=str(pcb), project=str(pcb.with_suffix(".kicad_pro")), launched=launched, launch_note=note, board_artifact_id=art.artifact_id, + launched, live_ready, note = _launch(pcb) # outside the lock: it can take ~10 s while the panel keeps polling + return _ok(pcb=str(pcb), project=str(pcb.with_suffix(".kicad_pro")), launched=launched, live_ready=live_ready, launch_note=note, board_artifact_id=art.artifact_id, imported_pending_edits=bool(pending and pending.get("changed")), how_to="Edit in KiCad and press Cmd+S. The KiCad board panel syncs automatically; or call kicad_sync_edits.") @@ -681,10 +828,11 @@ def kicad_live_status() -> dict: return live.status(_session_pcb(), WORKSPACE) -@mcp.tool(app={"visibility": ["app"]}) +@mcp.tool(app={"visibility": ["app", "model"]}, annotations={"title": "Read the live KiCad board", "readOnlyHint": True, "openWorldHint": False}) def kicad_live_snapshot(since: str = "") -> dict: - """(panel only) The live board in the running PCB Editor, read through KiCad's API while the user edits (no ⌘S needed): parts, nets, selection, counts, a signature. Only when - the live editor has exactly this session's board open; otherwise live=false with the reason. since = the last signature: an unchanged board answers with just that.""" + """Read-only snapshot of the live board in the running PCB Editor (no ⌘S needed): parts, nets, selection, counts, and a signature. Use it before and after a requested live + move instead of making a no-op move just to read a position. Only works when the live editor has exactly this session's board open; otherwise live=false with the reason. + since = the last signature: an unchanged board answers with just that.""" return live.snapshot(_session_pcb(), ORIGIN_MM, WORKSPACE, since) diff --git a/ui-plugins/kicad/test/e2e-artifact.mjs b/ui-plugins/kicad/test/e2e-artifact.mjs index a9769cce..701b5d7f 100644 --- a/ui-plugins/kicad/test/e2e-artifact.mjs +++ b/ui-plugins/kicad/test/e2e-artifact.mjs @@ -80,7 +80,8 @@ try { const byName = Object.fromEntries(tools.map((t) => [t.name, t])); for (const n of ["pcb_search_parts", "pcb_part_info", "pcb_spec_example", "pcb_check_spec", "pcb_build", "pcb_render", "pcb_export_fab", "kicad_check_spec_file", "kicad_export_files", "kicad_info", "kicad_board_view", "kicad_board_image", "kicad_open_in_kicad", "kicad_sync_edits", "kicad_edit_status", - "pcb_export_glb", "kicad_checks", "kicad_layers", "kicad_layer_svg", "kicad_3d_image", "kicad_schematic", "kicad_library_preview"]) assert.ok(byName[n], `missing tool ${n}`); + "pcb_export_glb", "kicad_checks", "kicad_layers", "kicad_layer_svg", "kicad_3d_image", "kicad_schematic", "kicad_library_preview", + "kicad_live_status", "kicad_live_snapshot", "kicad_live_move_footprint"]) assert.ok(byName[n], `missing tool ${n}`); assert.ok(!("project_id" in (byName.pcb_build.inputSchema.properties || {})), "project_id must be hidden from the model"); const surface = manifest.ui.surfaces[0]; const view = byName.kicad_board_view._meta.ui; @@ -89,6 +90,8 @@ try { assert.deepEqual(view.visibility.sort(), ["app", "model"]); assert.deepEqual(byName.kicad_board_image._meta.ui.visibility, ["app"]); assert.deepEqual(byName.kicad_edit_status._meta.ui.visibility, ["app"]); + assert.deepEqual(byName.kicad_live_snapshot._meta.ui.visibility, ["app", "model"]); + assert.equal(byName.kicad_live_snapshot.annotations.readOnlyHint, true); for (const n of ["kicad_layers", "kicad_layer_svg", "kicad_3d_image", "kicad_schematic", "kicad_library_preview"]) assert.deepEqual(byName[n]._meta.ui.visibility, ["app"], `${n} is for the panel only`); for (const n of ["pcb_export_glb", "kicad_checks"]) assert.ok(!byName[n]._meta?.ui, `${n} is a model tool`); const resources = (await client.listResources()).resources; diff --git a/ui-plugins/kicad/test/static.test.mjs b/ui-plugins/kicad/test/static.test.mjs index da590e4c..3f8fdb3a 100644 --- a/ui-plugins/kicad/test/static.test.mjs +++ b/ui-plugins/kicad/test/static.test.mjs @@ -15,13 +15,32 @@ const read = (...p) => readFile(join(...p), "utf8"); const walk = async (d) => (await Promise.all((await readdir(d, { withFileTypes: true })).map((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)])))).flat(); test("build output exists and matches what the manifest points at", async () => { - for (const f of ["panel.html", "server.mjs", "py/kicad_server.py", "py/kicad_launch.py", "py/kicad_views.py", "py/kicad_live.py", "py/kicad/config.py", "py/kicad/service.py", "THIRD_PARTY_NOTICES.txt"]) + for (const f of ["panel.html", "server.mjs", "py/kicad_server.py", "py/kicad_capabilities.py", "py/kicad_installation.py", "py/huaqiu_part_search.py", "py/huaqiu_part_search_bridge.mjs", "py/huaqiu_kicad_resolver.py", "py/huaqiu_model_inspector.py", "py/kicad_launch.py", "py/kicad_views.py", "py/kicad_live.py", "py/kicad/config.py", "py/kicad/service.py", "THIRD_PARTY_NOTICES.txt"]) assert.ok((await stat(join(DIST, f))).isFile(), `dist/${f} missing: run pnpm build`); for (const server of Object.values(manifest.mcpServers)) for (const arg of server.args) if (arg.includes("${ZCODE_PLUGIN_ROOT}/dist/")) assert.ok((await stat(join(DIST, arg.split("${ZCODE_PLUGIN_ROOT}/dist/")[1]))).isFile(), arg); assert.ok((await stat(join(DIST, "panel.html"))).size < 4 * 1024 * 1024, "HTML resource limit of the host is 4 MiB"); }); +test("the KiCad MCP tools are available on the first model request", () => { + const server = manifest.mcpServers.kicad; + assert.ok(server, "manifest must declare the KiCad MCP server"); + assert.equal( + server.alwaysLoad, + true, + "KiCad skills require kicad_capabilities on the first turn, including for models without ToolSearch", + ); +}); + +test("capabilities report the installed plugin version", async () => { + const server = await read(DIST, "py/kicad_server.py"); + assert.match( + server, + /"plugin_version": PLUGIN_VERSION/, + "the first-turn diagnosis must distinguish plugin and KiCad application versions", + ); +}); + test("manifest, server source and page agree on the surface", async () => { const [surface] = manifest.ui.surfaces; assert.ok(manifest.mcpServers[surface.server], "surface.server must be a declared MCP server"); @@ -38,12 +57,18 @@ test("manifest, server source and page agree on the surface", async () => { for (const tool of ["pcb_search_parts", "pcb_part_info"]) assert.ok(page.includes(tool) && (await read(DIST, "py/kicad/mcp_server.py")).includes(`def ${tool}(`), `the Library tab calls the worker tool ${tool}`); }); +test("the panel refreshes when another tool replaces the KiCad edit session", async () => { + const source = await read(ROOT, "ui/src/main.js"); + assert.match(source, /const active = !!state\.info\?\.ok;/, "poll even before the first edit session exists"); + assert.match(source, /st\?\.session \? st\.pcb !== shownPcb : !!shownPcb;/, "refresh when the edit-session board changes or closes"); +}); + test("page tools exist in the server and are visible to the app", async () => { const server = await read(DIST, "py/kicad_server.py"); assert.match(server, /@mcp\.tool\(app=\{"visibility": \["app"\]\}\)\s+def kicad_board_image/); assert.match(server, /@mcp\.tool\(app=\{"visibility": \["app"\]\}\)\s+def kicad_edit_status/); for (const tool of ["kicad_layers", "kicad_layer_svg", "kicad_3d_image", "kicad_schematic", "kicad_library_preview"]) assert.match(server, new RegExp(`@mcp\\.tool\\(app=\\{"visibility": \\["app"\\]\\}\\)\\s+def ${tool}\\(`), `${tool} must be app-only`); - assert.match(server, /@mcp\.tool\(app=\{"visibility": \["app"\]\}\)\s+def kicad_live_snapshot\(/, "the live snapshot is for the panel"); + assert.match(server, /@mcp\.tool\(app=\{"visibility": \["app", "model"\]\}, annotations=\{"title": "Read the live KiCad board", "readOnlyHint": True,[^)]*\)\s+def kicad_live_snapshot\(/, "the read-only live snapshot is available to both panel and model"); assert.match(server, /@mcp\.tool\(app=\{"visibility": \["model"\]\}[^)]*\)\s+def kicad_live_move_footprint\(/, "the only write tool is for the model, never for the page"); assert.ok(!/kicad_live_move_footprint/.test(await read(DIST, "panel.html")), "the panel page must never call the write tool"); for (const tool of ["pcb_export_glb", "kicad_checks"]) assert.match(server, new RegExp(`@mcp\\.tool\\s+def ${tool}\\(`), `${tool} must be visible to the model`); @@ -76,27 +101,33 @@ test("the vendored worker never reads .env files and the repo has no machine-spe } }); -test("a failed GUI launch is reported as one: pcbnew must stay up, the quarantine fix is named but never run", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { +test("the exact GUI child and its API socket are checked; the quarantine fix is named but never run", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { const server = await read(DIST, "py/kicad_server.py"); const launch = server.slice(server.indexOf("def _launch("), server.indexOf("def _sync_locked(")); - assert.match(launch, /if NO_LAUNCH:\s+return False, "launch disabled \(KICAD_PLUGIN_NO_LAUNCH=1\)"/, "KICAD_PLUGIN_NO_LAUNCH must still short-circuit before anything is started"); + assert.match(launch, /if NO_LAUNCH:\s+return False, False, "launch disabled \(KICAD_PLUGIN_NO_LAUNCH=1\)"/, "KICAD_PLUGIN_NO_LAUNCH must still short-circuit before anything is started"); assert.match(launch, /sys\.platform != "darwin"/); - assert.match(launch, /return launch_editor\(/, "_launch must delegate to the checked launch"); + assert.match(launch, /launch_editor\(/, "_launch must delegate to the checked launch"); + assert.match(launch, /wait_for_live_board\(/, "a socket is not enough: the requested board must also be verified"); assert.ok(!/subprocess|xattr/.test(launch), "_launch itself starts and changes nothing"); const helper = await read(DIST, "py/kicad_launch.py"); + assert.match(helper, /subprocess\.Popen\(/, "launch the selected distribution's exact child"); + assert.match(helper, /api-\{child\.pid\}\.sock/, "the live socket must belong to that exact child"); + assert.ok(!/\[\s*["']open["']|pgrep/.test(helper), "Launch Services/process-name checks can reuse or mistake another standalone editor"); const xattrCalls = helper.match(/\["xattr"[^\]]*\]/g) ?? []; assert.ok(xattrCalls.length > 0 && xattrCalls.every((c) => c.startsWith('["xattr", "-p",')), `the plugin may only read the quarantine attribute (xattr -p), found ${xattrCalls}`); const r = spawnSync("python3", [join(ROOT, "test/test_launch.py")], { encoding: "utf8", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }); assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); }); -test("KiCad runs on a private config: the plugin never lets any KiCad program rewrite the user's ~/Library/Preferences/kicad", async () => { +test("headless KiCad runs on a private config while the GUI keeps the captured user environment", async () => { const server = await read(DIST, "py/kicad_server.py"); const set = server.indexOf('"KICAD_CONFIG_HOME"'); assert.ok(set > 0 && set < server.indexOf("from fastmcp import"), "KICAD_CONFIG_HOME must be set before anything can start a KiCad program"); assert.ok(server.includes('"KICAD_DOCUMENTS_HOME"')); assert.ok(!/KICAD_CONFIG_HOME["']\]\s*=\s*["']?[^\n]*Preferences/.test(server), "no path into the user's preferences"); assert.ok(/os\.environ\[_var\] = /.test(server) && !/os\.environ\.setdefault\(_var/.test(server), "assigned unconditionally: a KICAD_CONFIG_HOME exported by the user must not win"); + assert.ok(server.indexOf("GUI_ENV = os.environ.copy()") < set, "capture the user's GUI settings before installing the headless overrides"); + assert.match(server, /launch_editor\([^\n]+env=GUI_ENV/, "the real GUI must use the captured user environment so Enable KiCad API is honored"); const launcher = await read(DIST, "server.mjs"); assert.ok(launcher.includes('UV_NO_CONFIG: "1"'), "uv must not read a uv.toml / pyproject.toml from the workspace"); }); @@ -111,6 +142,35 @@ test("the views module: GLB part table, board text helpers, id validation", { sk assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); }); +test("capabilities distinguish official, Huaqiu and missing KiCad installations", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { + const selection = spawnSync("python3", [join(ROOT, "test/test_installation.py")], { encoding: "utf8", env: { ...process.env, PYTHONPATH: join(DIST, "py"), PYTHONDONTWRITEBYTECODE: "1" } }); + assert.equal(selection.status, 0, `${selection.stdout}\n${selection.stderr}`); + const r = spawnSync("python3", [join(ROOT, "test/test_capabilities.py")], { encoding: "utf8", env: { ...process.env, PYTHONPATH: join(DIST, "py"), PYTHONDONTWRITEBYTECODE: "1" } }); + assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); +}); + +test("the Huaqiu part adapter validates arguments, gates the edition and uses only fixed local paths", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { + const r = spawnSync("python3", [join(ROOT, "test/test_huaqiu_part_search.py")], { encoding: "utf8", env: { ...process.env, PYTHONPATH: join(DIST, "py"), PYTHONDONTWRITEBYTECODE: "1" } }); + assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); + const bridge = await read(DIST, "py/huaqiu_part_search_bridge.mjs"); + assert.ok(!/(eval|exec|spawn|child_process)/.test(bridge), "the bridge cannot execute caller-supplied code or commands"); + for (const operation of ["search", "detail", "models", "supply"]) assert.ok(bridge.includes(`"${operation}"`)); +}); + +test("the Huaqiu-to-KiCad resolver ranks only locally checked symbol/footprint pairs", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { + const r = spawnSync("python3", [join(ROOT, "test/test_huaqiu_kicad_resolver.py")], { encoding: "utf8", env: { ...process.env, PYTHONPATH: join(DIST, "py"), PYTHONDONTWRITEBYTECODE: "1" } }); + assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); +}); + +test("Huaqiu KiCad text models are allowlisted, bounded, parsed in memory and compared geometrically", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { + const r = spawnSync("python3", [join(ROOT, "test/test_huaqiu_model_inspector.py")], { encoding: "utf8", env: { ...process.env, PYTHONPATH: join(DIST, "py"), PYTHONDONTWRITEBYTECODE: "1" } }); + assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); + const source = await read(DIST, "py/huaqiu_model_inspector.py"); + assert.match(source, /ALLOWED_MODEL_HOSTS = frozenset\(\{"file\.eda\.cn", "file1\.eda\.cn"\}\)/); + assert.match(source, /MAX_MODEL_BYTES = 2 \* 1024 \* 1024/); + assert.ok(!/write_text|write_bytes|NamedTemporaryFile|mkstemp/.test(source), "public model files must remain in memory"); +}); + test("the live link: stub-kipy tests, and the module can only read the board plus open/push/drop one commit", { skip: spawnSync("python3", ["--version"]).status !== 0 && "python3 not available" }, async () => { const r = spawnSync("python3", [join(ROOT, "test/test_live.py")], { encoding: "utf8", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }); assert.equal(r.status, 0, `${r.stdout}\n${r.stderr}`); diff --git a/ui-plugins/kicad/test/test_capabilities.py b/ui-plugins/kicad/test/test_capabilities.py new file mode 100644 index 00000000..2149d4b9 --- /dev/null +++ b/ui-plugins/kicad/test/test_capabilities.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import plistlib +import tempfile +import unittest +from pathlib import Path + +from kicad_capabilities import inspect_installation + + +def make_app(root: Path, *, huaqiu: bool = False, complete_huaqiu: bool = True) -> tuple[Path, Path, Path]: + app = root / "KiCad.app" + cli = app / "Contents/MacOS/kicad-cli" + python = app / "Contents/Frameworks/Python.framework/Versions/Current/bin/python3" + for path in (cli, python): + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + for name in ("symbols", "footprints", "3dmodels"): + (app / "Contents/SharedSupport" / name).mkdir(parents=True) + if huaqiu: + base = app / "Contents/Resources/edge-headless" + (base / "dsh").mkdir(parents=True) + node = base / "bin/node" + node.parent.mkdir(parents=True) + node.touch() + names = ( + "dsh-kicad", + "dsh-kicad-drc", + "dsh-tool-kicad-schematic-gen", + "dsh-tool-part-search", + "dsh-tool-symbol-footprint", + ) if complete_huaqiu else ("dsh-kicad", "dsh-tool-part-search") + for name in names: + package = base / "dsh-plugins/@huaqiu" / name + package.mkdir(parents=True) + (package / "package.json").write_text("{}") + part_search = base / "dsh-plugins/@huaqiu/node_modules/@huaqiu/part-search/dist/esm/index.js" + part_search.parent.mkdir(parents=True) + part_search.touch() + with (app / "Contents/Info.plist").open("wb") as stream: + plistlib.dump({"CFBundleShortVersionString": "10.0.7-test" if huaqiu else "10.0.6-test"}, stream) + return app, cli, python + + +class CapabilitiesTest(unittest.TestCase): + def test_official_distribution_is_ready_without_dsh(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp)) + got = inspect_installation(app, cli=cli, version="10.0.6", python=python, python_importable=True, ipc={"available": False, "reachable": False}) + self.assertEqual(got["distribution"], "official") + self.assertTrue(got["core_ready"]) + self.assertTrue(got["edition_ready"]) + self.assertEqual(got["requested_edition"], "standard") + self.assertFalse(got["dsh"]["bundled"]) + self.assertIn("pcb_build", got["available_tools"]) + self.assertIn("kicad_check_spec_file", got["available_tools"]) + self.assertEqual(got["missing_dependencies"], []) + + def test_huaqiu_distribution_lists_bundled_plugins_but_does_not_expose_dsh(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp), huaqiu=True) + got = inspect_installation(app, cli=cli, version="unavailable", python=python, python_importable=True, ipc={"available": True, "reachable": True, "kipy": True}, requested_edition="huaqiu") + self.assertEqual(got["distribution"], "huaqiu") + self.assertEqual(got["version"], "10.0.7-test") + self.assertTrue(got["edition_ready"]) + self.assertEqual(got["edition"]["missing_dsh_plugins"], []) + self.assertIn("@huaqiu/dsh-kicad", got["dsh"]["plugins"]) + self.assertFalse(got["dsh"]["exposed_to_zcode"]) + self.assertTrue(got["huaqiu_native_adapter"]["available"]) + self.assertFalse(got["huaqiu_native_adapter"]["starts_dsh"]) + self.assertIn("search_hqsch_parts", got["available_tools"]) + self.assertIn("get_hqsch_supply_chain", got["available_tools"]) + self.assertIn("resolve_hqsch_part_for_kicad", got["available_tools"]) + self.assertIn("compare_hqsch_models_with_kicad", got["available_tools"]) + self.assertIn("kicad_live_move_footprint", got["available_tools"]) + + def test_auto_edition_resolves_from_the_selected_distribution(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp), huaqiu=True) + selection = { + "mode": "automatic", + "reason": "newest_detected_installation", + "requested_edition": "auto", + "resolved_edition": "huaqiu", + } + got = inspect_installation( + app, + cli=cli, + version="10.0.7", + python=python, + python_importable=True, + requested_edition="auto", + selection=selection, + ) + self.assertEqual(got["requested_edition"], "auto") + self.assertEqual(got["resolved_edition"], "huaqiu") + self.assertTrue(got["edition"]["automatic"]) + self.assertTrue(got["edition_ready"]) + self.assertEqual(got["application"]["selection"], selection) + self.assertIn("search_hqsch_parts", got["available_tools"]) + + def test_missing_installation_returns_structured_reasons(self): + with tempfile.TemporaryDirectory() as tmp: + got = inspect_installation(Path(tmp) / "missing.app", cli=None, version="unavailable", python=None, python_importable=False, python_error="not installed", ipc={"kipy": False, "reason": "client missing"}) + self.assertEqual(got["distribution"], "missing") + self.assertFalse(got["core_ready"]) + missing = {item["id"]: item for item in got["missing_dependencies"]} + self.assertFalse(missing["kicad_app"]["optional"]) + self.assertFalse(missing["pcbnew_python"]["optional"]) + self.assertTrue(missing["kicad_python"]["optional"]) + + def test_huaqiu_edition_rejects_official_distribution(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp)) + got = inspect_installation(app, cli=cli, version="10.0.6", python=python, python_importable=True, requested_edition="huaqiu") + self.assertTrue(got["core_ready"]) + self.assertFalse(got["edition_ready"]) + self.assertTrue(got["edition_mismatch"]) + missing = {item["id"]: item for item in got["missing_dependencies"]} + self.assertIn("kicad_edition_mismatch", missing) + self.assertIn("huaqiu_dsh_runtime", missing) + self.assertIn("@huaqiu/dsh-kicad-drc", missing["huaqiu_dsh_plugins"]["missing"]) + + def test_standard_edition_rejects_huaqiu_distribution(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp), huaqiu=True) + got = inspect_installation(app, cli=cli, version="10.0.7", python=python, python_importable=True, requested_edition="official") + self.assertEqual(got["requested_edition"], "standard") + self.assertFalse(got["edition_ready"]) + self.assertTrue(got["edition_mismatch"]) + + def test_incomplete_huaqiu_distribution_lists_missing_components(self): + with tempfile.TemporaryDirectory() as tmp: + app, cli, python = make_app(Path(tmp), huaqiu=True, complete_huaqiu=False) + got = inspect_installation(app, cli=cli, version="10.0.7", python=python, python_importable=True, requested_edition="huaqiu") + self.assertFalse(got["edition_ready"]) + self.assertFalse(got["edition_mismatch"]) + self.assertIn("@huaqiu/dsh-tool-symbol-footprint", got["edition"]["missing_dsh_plugins"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ui-plugins/kicad/test/test_huaqiu_kicad_resolver.py b/ui-plugins/kicad/test/test_huaqiu_kicad_resolver.py new file mode 100644 index 00000000..12712ac5 --- /dev/null +++ b/ui-plugins/kicad/test/test_huaqiu_kicad_resolver.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +from huaqiu_kicad_resolver import package_queries, resolve_part + + +def pin(number: str, name: str, etype: str = "input"): + return SimpleNamespace(number=number, display_name=name, etype=etype, hidden=False) + + +class FakeLibrary: + def __init__(self): + self.symbol = SimpleNamespace( + lib_id="Timer:NE555D", + description="Precision timer, SOIC-8", + ref_prefix="U", + default_footprint="Package_SO:SOIC-8_3.9x4.9mm_P1.27mm", + fp_filters=("SOIC*3.9x4.9mm*P1.27mm*",), + pins=tuple(pin(str(i), "GND" if i == 1 else "VCC" if i == 8 else f"P{i}") for i in range(1, 9)), + ) + self.footprint = SimpleNamespace( + lib_id="Package_SO:SOIC-8_3.9x4.9mm_P1.27mm", + description="SOIC, 8 Pin", + tags="SOIC", + pad_numbers=[str(i) for i in range(1, 9)], + bbox=lambda: (-2.5, -3.0, 2.5, 3.0), + ) + + def search_symbols(self, query, limit, match_any=False): + return [{"lib_id": self.symbol.lib_id}] if "ne555" in query.lower() else [] + + def search_footprints(self, query, limit, match_any=False): + return [{"lib_id": self.footprint.lib_id}] if "soic-8" in query.lower() else [] + + def get_symbol(self, lib_id): + if lib_id != self.symbol.lib_id: + raise KeyError(lib_id) + return self.symbol + + def get_footprint(self, lib_id): + if lib_id != self.footprint.lib_id: + raise KeyError(lib_id) + return self.footprint + + def footprint_exists(self, lib_id): + return lib_id == self.footprint.lib_id + + def compatible_footprints(self, symbol, limit=30): + return [self.footprint.lib_id], 1 + + def footprint_matches_filters(self, footprint_id, filters): + return footprint_id == self.footprint.lib_id + + def pin_pad_mapping(self, symbol, footprint): + return {"pins_without_pad": [], "pads_without_pin": [], "mapped": [str(i) for i in range(1, 9)]} + + @staticmethod + def natural_key(value): + return [int(value)] + + +class ResolverTest(unittest.TestCase): + def test_package_aliases_are_conservative(self): + part = {"mpn": "NE555", "attributes": [{"shortName": "package", "name": "制造商封装", "value": "SOP-8"}]} + self.assertEqual(package_queries(part), ["SOP-8", "SOIC-8"]) + self.assertIn("SOT-23-5", package_queries({"mpn": "X", "package": "SOT23-5"})) + self.assertIn("QFN-32", package_queries({"mpn": "X", "package": "QFN32"})) + + def test_resolver_returns_only_pin_pad_and_filter_checked_pair(self): + part = { + "mpn": "NE555", + "manufacturer": {"id": "9373", "name": "IDCHIP"}, + "attributes": [{"shortName": "package", "name": "制造商封装", "value": "SOP-8"}], + "models": {"symbol": {"url": "https://example.invalid/a.kicad_sym"}}, + } + got = resolve_part(part, library=FakeLibrary()) + self.assertTrue(got["ok"]) + self.assertEqual(got["recommended_pair"]["symbol"], "Timer:NE555D") + self.assertEqual(got["recommended_pair"]["footprint"], "Package_SO:SOIC-8_3.9x4.9mm_P1.27mm") + self.assertTrue(got["review"]["local_pin_pad_mapping_verified"]) + self.assertFalse(got["review"]["electrical_compatibility_confirmed"]) + self.assertFalse(got["review"]["physical_package_confirmed"]) + self.assertEqual(got["spec_part_fields"]["value"], "NE555") + self.assertFalse(got["huaqiu_model_files_downloaded"]) + + def test_no_symbol_never_invents_a_library_id(self): + library = FakeLibrary() + library.search_symbols = lambda *args, **kwargs: [] + got = resolve_part({"mpn": "UNKNOWN-123", "package": "QFN32"}, library=library) + self.assertIsNone(got["recommended_pair"]) + self.assertNotIn("spec_part_fields", got) + self.assertIn("do not invent", got["note"]) + + def test_package_mismatch_and_extra_pads_are_not_spec_candidates(self): + part = {"mpn": "NE555", "package": "SOP-8"} + package_mismatch = FakeLibrary() + package_mismatch.footprint.lib_id = "Package_DIP:DIP-8_W7.62mm" + package_mismatch.symbol.default_footprint = package_mismatch.footprint.lib_id + self.assertIsNone(resolve_part(part, library=package_mismatch)["recommended_pair"]) + + exposed_pad = FakeLibrary() + exposed_pad.pin_pad_mapping = lambda symbol, footprint: { + "pins_without_pad": [], + "pads_without_pin": ["9"], + "mapped": [str(i) for i in range(1, 9)], + } + self.assertIsNone(resolve_part(part, library=exposed_pad)["recommended_pair"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ui-plugins/kicad/test/test_huaqiu_model_inspector.py b/ui-plugins/kicad/test/test_huaqiu_model_inspector.py new file mode 100644 index 00000000..a4994e18 --- /dev/null +++ b/ui-plugins/kicad/test/test_huaqiu_model_inspector.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +import unittest +from email.message import Message + +from huaqiu_model_inspector import ( + DownloadedModel, + ModelInspectionError, + compare_footprints, + compare_symbols, + download_text_model, + inspect_part_models, + model_url, + parse_footprint_model, + parse_symbol_model, +) + + +SYMBOL_TEXT = r''' +(kicad_symbol_lib (version 20231120) (generator kicad_symbol_editor) + (symbol "NE555D" + (property "Reference" "U" (at 0 0 0) (effects (font (size 1.27 1.27)))) + (property "Value" "NE555D" (at 0 0 0) (effects (font (size 1.27 1.27)))) + (symbol "NE555D_1_1" + (pin power_in line (at 0 0 0) (length 2.54) (name "GND" (effects (font (size 1.27 1.27)))) (number "1" (effects (font (size 1.27 1.27))))) + (pin input line (at 0 2.54 0) (length 2.54) (name "TR" (effects (font (size 1.27 1.27)))) (number "2" (effects (font (size 1.27 1.27))))) + (pin output line (at 0 5.08 0) (length 2.54) (name "Q" (effects (font (size 1.27 1.27)))) (number "3" (effects (font (size 1.27 1.27))))) + (pin power_in line (at 0 7.62 0) (length 2.54) (name "VCC" (effects (font (size 1.27 1.27)))) (number "4" (effects (font (size 1.27 1.27))))) + ) + ) +) +''' + + +FOOTPRINT_TEXT = r''' +(footprint "SOIC-4_TEST" (version 20240108) (generator pcbnew) + (layer "F.Cu") + (fp_rect (start -2.5 -3) (end 2.5 3) (stroke (width 0.05) (type default)) (fill none) (layer "F.CrtYd")) + (pad "1" smd roundrect (at -2 1) (size 1.2 0.6) (layers "F.Cu" "F.Paste" "F.Mask")) + (pad "2" smd roundrect (at -2 -1) (size 1.2 0.6) (layers "F.Cu" "F.Paste" "F.Mask")) + (pad "3" smd roundrect (at 2 -1) (size 1.2 0.6) (layers "F.Cu" "F.Paste" "F.Mask")) + (pad "4" smd roundrect (at 2 1) (size 1.2 0.6) (layers "F.Cu" "F.Paste" "F.Mask")) +) +''' + + +class FakeResponse: + def __init__(self, url: str, body: bytes, length: str | None = None): + self.url = url + self.body = body + self.offset = 0 + self.headers = Message() + self.headers["Content-Type"] = "text/plain; charset=utf-8" + if length is not None: + self.headers["Content-Length"] = length + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def geturl(self): + return self.url + + def read(self, count: int): + chunk = self.body[self.offset : self.offset + count] + self.offset += len(chunk) + return chunk + + +class FakeOpener: + def __init__(self, response: FakeResponse): + self.response = response + + def open(self, request, timeout): + return self.response + + +class FakeLibrary: + def __init__(self, symbol, footprint): + self.symbol = symbol + self.footprint = footprint + + def get_symbol(self, lib_id): + if lib_id != "Timer:NE555D": + raise KeyError(lib_id) + return self.symbol + + def get_footprint(self, lib_id): + if lib_id != "Package_SO:TEST": + raise KeyError(lib_id) + return self.footprint + + +class InspectorTest(unittest.TestCase): + def test_model_url_accepts_only_the_requested_allowlisted_file(self): + models = { + "symbol": {"url": "https://file.eda.cn/web/a.kicad_sym"}, + "footprint": {"downloadUrl": "https://file1.eda.cn/web/a.kicad_mod?token=x"}, + } + self.assertEqual(model_url(models, "symbol"), models["symbol"]["url"]) + self.assertEqual(model_url(models, "footprint"), models["footprint"]["downloadUrl"]) + for refused in ( + "http://file.eda.cn/a.kicad_sym", + "https://example.com/a.kicad_sym", + "https://user@file.eda.cn/a.kicad_sym", + "https://file.eda.cn/a.kicad_mod", + ): + with self.subTest(refused=refused), self.assertRaises(ModelInspectionError): + model_url({"symbol": {"url": refused}}, "symbol") + + def test_download_is_in_memory_utf8_and_size_limited(self): + url = "https://file.eda.cn/web/a.kicad_sym" + response = FakeResponse(url, SYMBOL_TEXT.encode()) + got = download_text_model(url, "symbol", opener=FakeOpener(response)) + self.assertEqual(got.text, SYMBOL_TEXT) + self.assertEqual(len(got.sha256), 64) + self.assertEqual(got.metadata()["persisted"], False) + + too_large = FakeResponse(url, b"x", str(2 * 1024 * 1024 + 1)) + with self.assertRaisesRegex(ModelInspectionError, "2 MiB"): + download_text_model(url, "symbol", opener=FakeOpener(too_large)) + + redirected = FakeResponse("https://file1.eda.cn/web/a.kicad_sym", b"x") + with self.assertRaisesRegex(ModelInspectionError, "redirect"): + download_text_model(url, "symbol", opener=FakeOpener(redirected)) + + def test_parsers_and_comparisons_are_rotation_translation_invariant(self): + symbol = parse_symbol_model(SYMBOL_TEXT) + footprint = parse_footprint_model(FOOTPRINT_TEXT) + self.assertEqual([pin.number for pin in symbol.pins], ["1", "2", "3", "4"]) + self.assertEqual(footprint.pad_numbers, ["1", "2", "3", "4"]) + self.assertTrue(compare_symbols(symbol, symbol)["model_matches_local_symbol"]) + + # Rotate 90 degrees and translate. Pairwise pad distances and dimensions + # remain identical, so this is the same physical land pattern. + rotated_text = FOOTPRINT_TEXT.replace("-2 1", "9 18").replace("-2 -1", "11 18").replace("2 -1", "11 22").replace("2 1", "9 22") + rotated_text = rotated_text.replace("-2.5 -3", "-3 -2.5").replace("2.5 3", "3 2.5") + rotated = parse_footprint_model(rotated_text) + compared = compare_footprints(footprint, rotated) + self.assertTrue(compared["pad_geometry_match"]) + self.assertTrue(compared["courtyard_dimensions_match"]) + self.assertTrue(compared["model_matches_local_footprint"]) + + def test_mismatches_stay_unconfirmed(self): + symbol = parse_symbol_model(SYMBOL_TEXT) + changed_symbol = parse_symbol_model(SYMBOL_TEXT.replace('(name "TR"', '(name "THRESH"')) + self.assertFalse(compare_symbols(symbol, changed_symbol)["pin_names_match"]) + footprint = parse_footprint_model(FOOTPRINT_TEXT) + changed_footprint = parse_footprint_model(FOOTPRINT_TEXT.replace('(at 2 1)', '(at 2.5 1)')) + compared = compare_footprints(footprint, changed_footprint) + self.assertFalse(compared["pad_geometry_match"]) + self.assertFalse(compared["model_matches_local_footprint"]) + + def test_inspection_returns_hashes_but_never_model_text(self): + symbol = parse_symbol_model(SYMBOL_TEXT) + footprint = parse_footprint_model(FOOTPRINT_TEXT) + library = FakeLibrary(symbol, footprint) + urls = { + "symbol": "https://file.eda.cn/web/a.kicad_sym", + "footprint": "https://file.eda.cn/web/a.kicad_mod", + } + + def downloader(url, kind): + text = SYMBOL_TEXT if kind == "symbol" else FOOTPRINT_TEXT + raw = text.encode() + return DownloadedModel(kind, url, text, len(raw), "a" * 64, "text/plain") + + got = inspect_part_models( + {"mpn": "NE555", "models": {kind: {"url": url} for kind, url in urls.items()}}, + "Timer:NE555D", + "Package_SO:TEST", + library=library, + downloader=downloader, + ) + self.assertTrue(got["ok"]) + self.assertTrue(got["model_consistency_confirmed"]) + self.assertFalse(got["review"]["electrical_compatibility_confirmed"]) + self.assertFalse(got["review"]["physical_package_confirmed"]) + self.assertFalse(got["downloads"]["written_to_disk"]) + self.assertNotIn(SYMBOL_TEXT, str(got)) + self.assertEqual(got["spec_part_fields"]["footprint"], "Package_SO:TEST") + + +if __name__ == "__main__": + unittest.main() diff --git a/ui-plugins/kicad/test/test_huaqiu_part_search.py b/ui-plugins/kicad/test/test_huaqiu_part_search.py new file mode 100644 index 00000000..a01521ac --- /dev/null +++ b/ui-plugins/kicad/test/test_huaqiu_part_search.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + +import huaqiu_part_search as parts + + +def make_adapter(root: Path) -> Path: + app = root / "KiCad.app" + paths = parts.adapter_paths(app) + paths["node"].parent.mkdir(parents=True) + paths["node"].touch() + paths["library"].parent.mkdir(parents=True) + paths["library"].touch() + return app + + +class HuaqiuPartSearchTest(unittest.TestCase): + def test_search_arguments_are_normalized_and_bounded(self): + got = parts.search_arguments( + " STM32F103 ", + page=2, + page_size=25, + require_eda_model=False, + requirements={"symbol": True, "supplier": False}, + language="en", + ) + self.assertEqual(got["query"], "STM32F103") + self.assertEqual(got["pageSize"], 25) + self.assertFalse(got["requireEdaModel"]) + self.assertEqual(got["requirements"], {"symbol": True, "supplier": False}) + with self.assertRaisesRegex(ValueError, "page_size"): + parts.search_arguments("resistor", page_size=51) + with self.assertRaisesRegex(ValueError, "unknown requirements"): + parts.search_arguments("resistor", requirements={"arbitrary": True}) + + def test_part_and_supply_arguments_never_accept_arbitrary_fields(self): + self.assertEqual( + parts.part_arguments(" 42 ", " NE555 "), + {"manufacturerId": "42", "mpn": "NE555", "language": "zh"}, + ) + got = parts.supply_arguments([{"manufacturer_id": "42", "mpn": "NE555"}]) + self.assertEqual(got, {"parts": [{"manufacturerId": "42", "mpn": "NE555"}]}) + with self.assertRaisesRegex(ValueError, "unknown fields"): + parts.supply_arguments([{"manufacturer_id": "42", "mpn": "NE555", "url": "bad"}]) + + def test_standard_edition_is_rejected_before_starting_a_process(self): + with tempfile.TemporaryDirectory() as tmp: + called = False + + def runner(*args, **kwargs): + nonlocal called + called = True + raise AssertionError("runner must not be called") + + got = parts.execute("search", {"query": "x"}, app=Path(tmp), edition="standard", runner=runner) + self.assertFalse(got["ok"]) + self.assertEqual(got["code"], "huaqiu_edition_required") + self.assertFalse(called) + + def test_auto_edition_uses_a_detected_huaqiu_installation(self): + with tempfile.TemporaryDirectory() as tmp: + app = make_adapter(Path(tmp)) + (app / "Contents/Resources/edge-headless/dsh").mkdir(parents=True) + seen: list[list[str]] = [] + + def runner(command, **kwargs): + seen.append(command) + payload = json.dumps({"ok": True, "result": {"parts": []}}) + return subprocess.CompletedProcess(command, 0, payload, "") + + got = parts.execute("search", {"query": "NE555"}, app=app, edition="auto", runner=runner) + self.assertTrue(got["ok"]) + self.assertEqual(got["edition"], "huaqiu") + self.assertEqual(len(seen), 1) + + def test_huaqiu_call_uses_fixed_executable_bridge_and_library(self): + with tempfile.TemporaryDirectory() as tmp: + app = make_adapter(Path(tmp)) + seen = {} + + def runner(command, **kwargs): + seen.update(command=command, kwargs=kwargs) + return subprocess.CompletedProcess(command, 0, json.dumps({"ok": True, "result": {"total": 1}}), "") + + got = parts.execute("search", {"query": "NE555"}, app=app, edition="huaqiu", runner=runner) + locations = parts.adapter_paths(app) + self.assertTrue(got["ok"]) + self.assertEqual(got["result"], {"total": 1}) + self.assertEqual( + seen["command"], + [str(locations["node"]), str(locations["bridge"]), str(locations["library"])], + ) + self.assertFalse(seen["kwargs"]["check"]) + request = json.loads(seen["kwargs"]["input"]) + self.assertEqual(request, {"operation": "search", "arguments": {"query": "NE555"}}) + + def test_missing_runtime_timeout_and_upstream_errors_are_structured(self): + with tempfile.TemporaryDirectory() as tmp: + missing = parts.execute("search", {}, app=Path(tmp), edition="huaqiu") + self.assertEqual(missing["code"], "huaqiu_part_search_unavailable") + app = make_adapter(Path(tmp)) + + def timeout(*args, **kwargs): + raise subprocess.TimeoutExpired("node", 35) + + timed = parts.execute("search", {}, app=app, edition="huaqiu", runner=timeout) + self.assertEqual(timed["code"], "huaqiu_part_search_timeout") + + def failed(command, **kwargs): + payload = {"ok": False, "error": {"name": "PartNotFoundError", "message": "not found", "status": 404}} + return subprocess.CompletedProcess(command, 1, json.dumps(payload), "") + + failure = parts.execute("detail", {}, app=app, edition="huaqiu", runner=failed) + self.assertEqual(failure["code"], "huaqiu_part_search_failed") + self.assertEqual(failure["error"], "not found") + self.assertEqual(failure["upstream"]["status"], 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/ui-plugins/kicad/test/test_installation.py b/ui-plugins/kicad/test/test_installation.py new file mode 100644 index 00000000..1d2743dd --- /dev/null +++ b/ui-plugins/kicad/test/test_installation.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import plistlib +import tempfile +import unittest +from pathlib import Path + +from kicad_installation import select_installation + + +def make_app(root: Path, name: str, version: str, *, huaqiu: bool = False) -> Path: + app = root / name / "KiCad.app" + cli = app / "Contents/MacOS/kicad-cli" + cli.parent.mkdir(parents=True) + cli.touch() + with (app / "Contents/Info.plist").open("wb") as stream: + plistlib.dump({"CFBundleShortVersionString": version}, stream) + if huaqiu: + (app / "Contents/Resources/edge-headless/dsh").mkdir(parents=True) + return app + + +class InstallationSelectionTest(unittest.TestCase): + def test_auto_selects_newest_installation_and_resolves_huaqiu(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + official = make_app(root, "KiCad", "10.0.6") + huaqiu = make_app(root, "Huaqiu KiCad", "10.0.7", huaqiu=True) + got = select_installation("", "auto", roots=[root]) + self.assertEqual(got["mode"], "automatic") + self.assertEqual(got["resolved_edition"], "huaqiu") + self.assertEqual(got["selected"]["path"], str(huaqiu)) + self.assertEqual({item["path"] for item in got["candidates"]}, {str(official), str(huaqiu)}) + + def test_requested_edition_selects_matching_distribution(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + official = make_app(root, "KiCad", "10.0.6") + make_app(root, "Huaqiu KiCad", "10.0.7", huaqiu=True) + got = select_installation(None, "official", roots=[root]) + self.assertEqual(got["requested_edition"], "standard") + self.assertEqual(got["resolved_edition"], "standard") + self.assertEqual(got["selected"]["path"], str(official)) + + def test_explicit_path_wins_even_when_another_installation_is_newer(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + explicit = make_app(root, "KiCad", "10.0.5") + make_app(root, "Huaqiu KiCad", "10.0.9", huaqiu=True) + got = select_installation(explicit, "auto", roots=[root]) + self.assertEqual(got["mode"], "explicit") + self.assertEqual(got["selected"]["path"], str(explicit)) + self.assertEqual(got["resolved_edition"], "standard") + + def test_missing_explicit_path_is_reported_instead_of_silently_replaced(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + make_app(root, "KiCad", "10.0.6") + missing = root / "Not There.app" + got = select_installation(missing, "auto", roots=[root]) + self.assertEqual(got["selected"]["path"], str(missing)) + self.assertEqual(got["selected"]["distribution"], "missing") + self.assertEqual(got["candidates"], []) + + def test_automatic_discovery_ignores_similarly_named_apps_without_kicad_cli(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + real = make_app(root, "KiCad", "10.0.6") + mirror = root / "KiCadMirror.app" + mirror.mkdir() + with (mirror / "Info.plist").open("wb") as stream: + plistlib.dump({"CFBundleShortVersionString": "99.0.0"}, stream) + got = select_installation(None, "auto", roots=[root]) + self.assertEqual(got["selected"]["path"], str(real)) + self.assertEqual([item["path"] for item in got["candidates"]], [str(real)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ui-plugins/kicad/test/test_launch.py b/ui-plugins/kicad/test/test_launch.py index 09d62703..1f1b9bd9 100644 --- a/ui-plugins/kicad/test/test_launch.py +++ b/ui-plugins/kicad/test/test_launch.py @@ -1,10 +1,12 @@ -"""Hermetic tests for server/kicad_launch.py: fake `open`, `pgrep` and `xattr` programs on PATH, a fixture crash report, no KiCad, no GUI. -Run by test/static.test.mjs (`pnpm test`) or directly: python3 test/test_launch.py +"""Hermetic tests for server/kicad_launch.py: a fake pcbnew process and real Unix sockets, no KiCad and no GUI. + +Run by test/static.test.mjs (``pnpm test``) or directly: ``python3 test/test_launch.py``. """ from __future__ import annotations import os import shutil +import signal import stat import sys import tempfile @@ -17,36 +19,41 @@ import kicad_launch as kl # noqa: E402 FIXTURE = HERE / "fixtures" / "pcbnew-translocated.ips" -FAST = dict(appear_s=2.0, stable_s=0.5, report_s=2.0, poll_s=0.05) # the real defaults are 8 / 2 / 4 / 0.25 s - -OPEN = """#!/bin/sh -echo "$@" >> "$FAKE_DIR/open.log" -case "$FAKE_OPEN" in - fail) - echo "The application cannot be opened for an unexpected reason" >&2 - exit 1 ;; - stay) - touch "$FAKE_DIR/alive" ;; - crash) # dies before pgrep ever sees it; the crash reporter writes the report a moment later - ( sleep 0.15; cp "$FAKE_FIXTURE" "$FAKE_REPORTS/pcbnew-2026-10-19-190037.ips" ) >/dev/null 2>&1 & - ;; - die) # pgrep sees it for FAKE_ALIVE_CALLS polls and then never again (counted, not timed: no race on a loaded machine); the report (if any) arrives FAKE_REPORT_DELAY s later - touch "$FAKE_DIR/alive" - if [ -n "$FAKE_FIXTURE" ]; then - ( sleep "${FAKE_REPORT_DELAY:-0}"; cp "$FAKE_FIXTURE" "$FAKE_REPORTS/pcbnew-2026-10-19-190037.ips" ) >/dev/null 2>&1 & - fi - ;; -esac -exit 0 -""" -PGREP = """#!/bin/sh -echo "$@" >> "$FAKE_DIR/pgrep.log" -if [ -e "$FAKE_DIR/alive" ]; then - if [ -n "$FAKE_ALIVE_CALLS" ] && [ "$(wc -l < "$FAKE_DIR/pgrep.log")" -gt "$FAKE_ALIVE_CALLS" ]; then exit 1; fi - echo 4242; exit 0 -fi -exit 1 -""" +FAST = dict(stable_s=0.2, socket_s=0.4, report_s=0.5, poll_s=0.02) +SCHEDULE_S = 5.0 + +PCBNEW = r'''#!/usr/bin/env python3 +import os +import shutil +import socket +import sys +import time +from pathlib import Path + +root = Path(os.environ["FAKE_DIR"]) +with (root / "pids").open("a") as f: + f.write(str(os.getpid()) + "\n") +(root / "argv").write_text("\n".join(sys.argv[1:])) +(root / "child-env").write_text("KICAD_CONFIG_HOME=" + os.environ.get("KICAD_CONFIG_HOME", "") + "\nKICAD_DOCUMENTS_HOME=" + os.environ.get("KICAD_DOCUMENTS_HOME", "")) +mode = os.environ.get("FAKE_MODE", "stay") +if mode == "crash": + shutil.copyfile(os.environ["FAKE_FIXTURE"], Path(os.environ["FAKE_REPORTS"]) / "pcbnew-2026-10-19-190037.ips") + raise SystemExit(7) +if mode == "odd_crash": + shutil.copyfile(os.environ["FAKE_FIXTURE"], Path(os.environ["FAKE_REPORTS"]) / "pcbnew-2026-10-19-190037.ips") + raise SystemExit(8) +if mode == "die": + raise SystemExit(9) +sock = None +if mode == "stay": + socket_dir = Path(os.environ["FAKE_SOCKET_DIR"]) + socket_dir.mkdir(parents=True, exist_ok=True) + sock = socket.socket(socket.AF_UNIX) + sock.bind(str(socket_dir / ("api-" + str(os.getpid()) + ".sock"))) + sock.listen() +time.sleep(60) +''' + XATTR = """#!/bin/sh echo "$@" >> "$FAKE_DIR/xattr.log" for q in $FAKE_QUARANTINED; do @@ -60,97 +67,200 @@ class LaunchTest(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp(prefix="kicad-launch-test-")) - self.addCleanup(shutil.rmtree, self.tmp, True) + self.addCleanup(self.cleanup) self.bin = self.tmp / "bin" self.reports = self.tmp / "reports" + self.sockets = self.tmp / "sockets" + self.editor = self.tmp / "KiCad" / "PCB Editor.app" + self.app_dir = self.tmp / "KiCad" / "KiCad.app" + self.exe = kl.pcbnew_executable(self.editor) self.bin.mkdir() self.reports.mkdir() - for name, body in (("open", OPEN), ("pgrep", PGREP), ("xattr", XATTR)): - f = self.bin / name - f.write_text(body) - f.chmod(f.stat().st_mode | stat.S_IXUSR) - self.editor = Path("/fake/KiCad/PCB Editor.app") - self.app_dir = Path("/fake/KiCad/KiCad.app") + self.sockets.mkdir() + self.exe.parent.mkdir(parents=True) + self.exe.write_text(PCBNEW) + self.exe.chmod(self.exe.stat().st_mode | stat.S_IXUSR) + xattr = self.bin / "xattr" + xattr.write_text(XATTR) + xattr.chmod(xattr.stat().st_mode | stat.S_IXUSR) self.pcb = self.tmp / "board.kicad_pcb" + self.pcb.write_text("(kicad_pcb)") saved = dict(os.environ) self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved))) - os.environ.update(PATH=f"{self.bin}:/usr/bin:/bin", FAKE_DIR=str(self.tmp), FAKE_REPORTS=str(self.reports), FAKE_FIXTURE=str(FIXTURE), FAKE_OPEN="nothing", - FAKE_QUARANTINED="", FAKE_REPORT_DELAY="0") + os.environ.update( + PATH=f"{self.bin}:/usr/bin:/bin", + FAKE_DIR=str(self.tmp), + FAKE_REPORTS=str(self.reports), + FAKE_FIXTURE=str(FIXTURE), + FAKE_SOCKET_DIR=str(self.sockets), + FAKE_MODE="stay", + FAKE_QUARANTINED="", + ) + + def cleanup(self): + try: + for raw in (self.tmp / "pids").read_text().splitlines(): + try: + os.kill(int(raw), signal.SIGTERM) + except (ProcessLookupError, ValueError): + pass + except OSError: + pass + time.sleep(0.02) + kl.reap_children() + shutil.rmtree(self.tmp, ignore_errors=True) def launch(self, **kw): - return kl.launch_editor(self.editor, self.pcb, self.app_dir, report_dir=self.reports, **{**FAST, **kw}) + child_env = dict(os.environ) + timings = {**FAST, "stable_s": getattr(self, "stable_s", FAST["stable_s"]), **kw} + if os.environ.get("FAKE_MODE") in {"crash", "odd_crash", "die"}: + timings["stable_s"] = max(timings["stable_s"], SCHEDULE_S) + return kl.launch_editor(self.editor, self.pcb, self.app_dir, report_dir=self.reports, socket_dir=self.sockets, env=child_env, **timings) def log(self, name): - f = self.tmp / f"{name}.log" + f = self.tmp / name return f.read_text().splitlines() if f.exists() else [] - def test_stays_up(self): - os.environ["FAKE_OPEN"] = "stay" + def make_editor_exit_immediately(self, code=9): + """Avoid Python startup latency in tests whose only subject is an exited child. + + The full workspace test suite runs packages concurrently. Under that load a + newly spawned Python process can remain alive past the intentionally tiny + FAST stability window without having executed its first line, which makes a + deliberate exit look like a healthy GUI launch. A shell exit keeps these + tests about launch_editor's exit/report handling rather than scheduler speed. + """ + self.exe.write_text(f"#!/bin/sh\nexit {code}\n") + self.exe.chmod(self.exe.stat().st_mode | stat.S_IXUSR) + # The workspace runs packages concurrently. Give the deliberately short- + # lived child enough CPU scheduling time before calling it a healthy GUI. + self.stable_s = SCHEDULE_S + + def test_exact_child_stays_up_and_creates_live_socket(self): t = time.monotonic() - self.assertEqual(self.launch(), (True, "opened in PCB Editor.app")) - self.assertGreaterEqual(time.monotonic() - t, FAST["stable_s"], "must have watched the process for the whole stable window") - self.assertEqual(self.log("open"), [f"-a {self.editor} {self.pcb}"]) - self.assertIn("-x pcbnew", self.log("pgrep")[0]) - self.assertEqual(self.log("xattr"), [], "nothing to diagnose when it runs") - - def test_open_fails(self): - os.environ["FAKE_OPEN"] = "fail" + self.assertEqual(self.launch(socket_s=SCHEDULE_S), (True, "opened in PCB Editor.app; live KiCad API socket ready")) + self.assertGreaterEqual(time.monotonic() - t, FAST["stable_s"], "must watch the exact process for the whole stability window") + self.assertEqual(self.log("argv"), [str(self.pcb)]) + self.assertEqual(self.log("xattr.log"), [], "nothing to diagnose when it runs") + + def test_no_socket_is_honest_but_file_round_trip_still_launched(self): + os.environ["FAKE_MODE"] = "no_socket" + ok, note = self.launch() + self.assertTrue(ok) + self.assertIn("live API did not appear", note) + self.assertIn("Enable KiCad API", note) + self.assertIn("file save/sync still works", note) + + def test_no_socket_with_enabled_api_diagnoses_an_older_window_or_lock(self): + os.environ["FAKE_MODE"] = "no_socket" + ok, note = self.launch(api_expected=True) + self.assertTrue(ok) + self.assertIn('"Enable KiCad API" is on', note) + self.assertIn("older PCB Editor window", note) + self.assertIn("project-lock dialog", note) + self.assertIn("file save/sync still works", note) + + def test_passed_gui_environment_is_used(self): + child_env = dict(os.environ) + child_env.pop("KICAD_CONFIG_HOME", None) + child_env.pop("KICAD_DOCUMENTS_HOME", None) + ok, _ = kl.launch_editor( + self.editor, + self.pcb, + self.app_dir, + report_dir=self.reports, + socket_dir=self.sockets, + env=child_env, + **{**FAST, "socket_s": SCHEDULE_S}, + ) + self.assertTrue(ok) + self.assertEqual(self.log("child-env"), ["KICAD_CONFIG_HOME=", "KICAD_DOCUMENTS_HOME="]) + + def test_live_board_waits_past_socket_until_requested_board_is_reported(self): + seen = [] + + def status(path, workspace): + seen.append((path, workspace)) + return ({"available": False, "reason": "no board open"} if len(seen) == 1 + else {"available": True, "board": {"path": path, "matches_session": True}}) + + ready, result = kl.wait_for_live_board(self.pcb, status, self.tmp, board_s=0.2, poll_s=0.01) + self.assertTrue(ready) + self.assertTrue(result["available"]) + self.assertEqual(seen[-1], (str(self.pcb), self.tmp)) + + def test_live_board_does_not_confuse_socket_with_locked_board(self): + def status(_path, _workspace): + return {"available": False, "reachable": True, "reason": "KiCad answers, but no PCB Editor has a board open"} + + ready, result = kl.wait_for_live_board(self.pcb, status, self.tmp, board_s=0.025, poll_s=0.01) + self.assertFalse(ready) + self.assertIn("no PCB Editor has a board open", result["reason"]) + + def test_live_board_stops_immediately_when_client_is_unavailable(self): + calls = 0 + + def status(_path, _workspace): + nonlocal calls + calls += 1 + return {"available": False, "kipy": False, "reason": "client missing"} + + self.assertFalse(kl.wait_for_live_board(self.pcb, status, self.tmp, board_s=1, poll_s=0.01)[0]) + self.assertEqual(calls, 1) + + def test_missing_executable_fails_before_launch(self): + self.exe.unlink() ok, note = self.launch() self.assertFalse(ok) - self.assertEqual(note, "open failed: The application cannot be opened for an unexpected reason") + self.assertIn("not found or not executable", note) + self.assertFalse((self.tmp / "pids").exists()) + + def test_outer_editor_symlink_resolves_to_the_nested_executable(self): + app = self.tmp / "Distribution" / "KiCad.app" + nested = app / "Contents" / "Applications" / "pcbnew.app" + exe = nested / "Contents" / "MacOS" / "pcbnew" + exe.parent.mkdir(parents=True) + exe.write_text("binary") + outer = app.parent / "PCB Editor.app" + outer.symlink_to(nested) + self.assertEqual(kl.pcbnew_executable(outer), exe.resolve()) def test_translocation_crash_names_the_fix_and_never_runs_it(self): - os.environ.update(FAKE_OPEN="crash", FAKE_QUARANTINED="/fake/KiCad/KiCad.app /fake/KiCad") + os.environ.update(FAKE_MODE="crash", FAKE_QUARANTINED=f"{self.app_dir} {self.app_dir.parent}") ok, note = self.launch() self.assertFalse(ok) self.assertIn("crashed right after it was opened", note) self.assertIn("Library not loaded: @rpath/libkicommon.10.0.6.dylib", note) self.assertIn("App Translocation", note) - self.assertTrue(note.endswith("xattr -dr com.apple.quarantine /fake/KiCad"), note) + self.assertTrue(note.endswith(f"xattr -dr com.apple.quarantine {self.app_dir.parent}"), note) self.assertNotIn("Referenced from", note, "the note stays short") self.assertLess(len(note), 600) - self.assertTrue(all(line.startswith("-p com.apple.quarantine ") for line in self.log("xattr")), "xattr may only read: " + repr(self.log("xattr"))) + self.assertTrue(all(line.startswith("-p com.apple.quarantine ") for line in self.log("xattr.log")), "xattr may only read") def test_translocation_in_the_report_is_enough_without_the_flag(self): - os.environ.update(FAKE_OPEN="crash", FAKE_QUARANTINED="") + os.environ.update(FAKE_MODE="crash", FAKE_QUARANTINED="") ok, note = self.launch() self.assertFalse(ok) self.assertIn("temporary quarantined copy (App Translocation)", note) - self.assertIn("xattr -dr com.apple.quarantine /fake/KiCad", note) - - def test_started_then_died_waits_for_the_crash_report(self): - os.environ.update(FAKE_OPEN="die", FAKE_ALIVE_CALLS="2", FAKE_REPORT_DELAY="0.3", FAKE_QUARANTINED="/fake/KiCad") - ok, note = self.launch(stable_s=30.0) # never reached: the process is gone after two polls - self.assertFalse(ok) - self.assertIn("Library not loaded", note) - self.assertIn("xattr -dr com.apple.quarantine /fake/KiCad", note) + self.assertIn(f"xattr -dr com.apple.quarantine {self.app_dir.parent}", note) def test_died_without_report_and_without_quarantine(self): - os.environ.update(FAKE_OPEN="die", FAKE_ALIVE_CALLS="2", FAKE_FIXTURE="") - ok, note = self.launch(stable_s=30.0) - self.assertFalse(ok) - self.assertIn("quit again", note) - self.assertIn("no crash report found", note) - self.assertNotIn("xattr -dr", note, "no evidence of quarantine: do not send the user off to change attributes") - - def test_never_appears(self): - os.environ.update(FAKE_OPEN="nothing", FAKE_QUARANTINED="/fake/KiCad/KiCad.app") - t = time.monotonic() + self.make_editor_exit_immediately() + os.environ.update(FAKE_QUARANTINED="") ok, note = self.launch() self.assertFalse(ok) - self.assertGreaterEqual(time.monotonic() - t, FAST["appear_s"]) - self.assertIn("did not start within 2 s", note) - self.assertIn("quarantine flag", note) - self.assertIn("xattr -dr com.apple.quarantine /fake/KiCad", note) + self.assertIn("exit 9", note) + self.assertIn("no crash report found", note) + self.assertNotIn("xattr -dr", note) def test_report_from_before_the_launch_is_ignored(self): old = self.reports / "pcbnew-2026-10-18-101010.ips" shutil.copy(FIXTURE, old) os.utime(old, (time.time() - 3600, time.time() - 3600)) - os.environ["FAKE_OPEN"] = "nothing" + self.make_editor_exit_immediately() ok, note = self.launch() self.assertFalse(ok) - self.assertIn("did not start", note) + self.assertIn("exit 9", note) self.assertNotIn("Library not loaded", note) def test_odd_reports_never_raise(self): @@ -160,24 +270,25 @@ def test_odd_reports_never_raise(self): f.unlink() odd = self.tmp / "odd.ips" odd.write_text(content) - os.environ.update(FAKE_OPEN="crash", FAKE_FIXTURE=str(odd)) # written during the launch, like a real report + os.environ.update(FAKE_MODE="odd_crash", FAKE_FIXTURE=str(odd)) ok, note = self.launch() self.assertFalse(ok) self.assertIn("crashed right after it was opened", note) - self.assertIn("pcbnew-2026-10-19-190037.ips", note, "unreadable report: name the file instead") + self.assertIn("pcbnew-2026-10-19-190037.ips", note) def test_missing_report_directory(self): - os.environ["FAKE_OPEN"] = "nothing" - ok, note = kl.launch_editor(self.editor, self.pcb, self.app_dir, report_dir=self.tmp / "no-such-dir", **{**FAST, "appear_s": 0.2}) - self.assertEqual(ok, False) - self.assertIn("did not start", note) - - def test_pgrep_unavailable_is_not_reported_as_a_failure(self): - shutil.move(str(self.bin / "pgrep"), str(self.tmp / "pgrep-away")) - os.environ["PATH"] = str(self.bin) # no pgrep anywhere; the fake `open` only needs shell builtins in the "nothing" mode - ok, note = self.launch() - self.assertTrue(ok) - self.assertIn("could not check", note) + self.make_editor_exit_immediately() + ok, note = kl.launch_editor( + self.editor, + self.pcb, + self.app_dir, + report_dir=self.tmp / "no-such-dir", + socket_dir=self.sockets, + env=dict(os.environ), + **{**FAST, "stable_s": self.stable_s}, + ) + self.assertFalse(ok) + self.assertIn("exit 9", note) def test_crash_reason_of_the_real_report_shape(self): reason, translocated = kl.crash_reason(FIXTURE) diff --git a/ui-plugins/kicad/test/test_live.py b/ui-plugins/kicad/test/test_live.py index 4cd3a485..48117865 100644 --- a/ui-plugins/kicad/test/test_live.py +++ b/ui-plugins/kicad/test/test_live.py @@ -95,9 +95,9 @@ class Zone(Item): class Editor: """What one KiCad editor process looks like through the stub: a board path, its items, and a log of every call.""" - def __init__(self, board, fps, tracks=(), vias=(), pads=(), zones=0, nets=(), selection=(), version="10.0.6"): + def __init__(self, board, fps, tracks=(), vias=(), pads=(), zones=0, nets=(), selection=(), version="10.0.6", api_version="10.0.6-0-gtest"): self.board, self.fps, self.tracks, self.vias, self.pads, self.zones, self.nets, self.selection = board, fps, list(tracks), list(vias), list(pads), zones, nets, list(selection) - self.version, self.calls, self.commits, self.drops, self.pending, self.fail_update = version, [], [], 0, None, False + self.version, self.api_version, self.calls, self.commits, self.drops, self.pending, self.fail_update = version, api_version, [], [], 0, None, False self.swap_board_after = None # simulate the user opening another board between two requests self.boom = None # reading the footprints raises this @@ -128,7 +128,7 @@ def get_version(self): return self._ed().version def get_api_version(self): - return "10.0.6-0-gtest" + return self._ed().api_version def get_open_documents(self, doc_type): e = self._ed() @@ -346,13 +346,14 @@ def test_no_session_yet(self): self.assertIn("no KiCad edit session", st["reason"]) def test_two_editors_the_one_with_the_session_board_wins(self): - other = self.editor(board="/tmp/other/board.kicad_pcb") - mine = self.editor() + other = self.editor(board="/tmp/other/board.kicad_pcb", version="10.0.6", api_version="10.0.6-0-gstandard") + mine = self.editor(version="10.0.7-huaqiu", api_version="10.0.7-11-ghuaqiu") self.socket("api.sock", other) self.socket("api-77.sock", mine) st = kl.status(self.pcb) self.assertTrue(st["available"]) self.assertEqual(st["editors"], 2) + self.assertEqual((st["kicad_version"], st["api_version"]), ("10.0.7-huaqiu", "10.0.7-11-ghuaqiu")) self.assertEqual(sorted(st["boards_open"]), ["board.kicad_pcb", "demo.kicad_pcb"]) kl.snapshot(self.pcb, (50, 50)) self.assertIn("get_footprints", mine.calls) diff --git a/ui-plugins/kicad/ui/src/main.js b/ui-plugins/kicad/ui/src/main.js index 992a121e..2dd9592f 100644 --- a/ui-plugins/kicad/ui/src/main.js +++ b/ui-plugins/kicad/ui/src/main.js @@ -15,11 +15,11 @@ const state = { info: null, side: "top", tab: "board", img: null, err: null, bus const T = { en: { none: "no board yet", hint: "Ask the agent to run pcb_build, or press Refresh", top: "top", bottom: "bottom", refresh: "Refresh", parts: "Parts", artifacts: "Artifacts", rendering: "rendering…", ask: "Ask agent to review", open: "Open in KiCad", opening: "Opening…", sync: "Sync now", edited: "edited in KiCad", - session: (rel) => `Editing in KiCad — press ⌘S there and this panel updates by itself · ${rel}`, synced: (t) => `last sync ${t}`, nolaunch: (n) => `KiCad was not started: ${n}`, + session: (rel) => `Editing in KiCad — press ⌘S there and this panel updates by itself · ${rel}`, synced: (t) => `last sync ${t}`, nolaunch: (n) => `KiCad was not started: ${n}`, nolive: (n) => `KiCad started, but the requested board is not live: ${n}`, askText: (i) => `Review the KiCad board "${i.name}" (${i.width_mm}×${i.height_mm} mm): DRC ${i.drc_passed ? "passed" : "failed"}. What would you improve for rev B?` }, zh: { none: "还没有电路板", hint: "让 Agent 运行 pcb_build,或点「刷新」", top: "顶层", bottom: "底层", refresh: "刷新", parts: "元件", artifacts: "产物", rendering: "渲染中…", ask: "让 Agent 评审", open: "在 KiCad 中编辑", opening: "正在打开…", sync: "立即同步", edited: "已在 KiCad 中编辑", - session: (rel) => `正在 KiCad 中编辑 —— 在 KiCad 里按 ⌘S 保存,这里会自动同步 · ${rel}`, synced: (t) => `上次同步 ${t}`, nolaunch: (n) => `没有启动 KiCad:${n}`, + session: (rel) => `正在 KiCad 中编辑 —— 在 KiCad 里按 ⌘S 保存,这里会自动同步 · ${rel}`, synced: (t) => `上次同步 ${t}`, nolaunch: (n) => `没有启动 KiCad:${n}`, nolive: (n) => `KiCad 已启动,但目标板尚未接入实时连接:${n}`, askText: (i) => `评审 KiCad 电路板「${i.name}」(${i.width_mm}×${i.height_mm} mm),DRC ${i.drc_passed ? "通过" : "未通过"}。rev B 你会改进什么?` }, }; const isZh = () => (app.getHostContext?.()?.locale || "en").toLowerCase().startsWith("zh"); @@ -73,7 +73,10 @@ async function loadImage() { // ---- real KiCad GUI: open the board in the PCB Editor, then poll for saves (the server imports each save as a new artifact and runs DRC on it) let pollTimer = null; function syncPolling() { - const active = !!state.info?.edit?.active; + // A model may call kicad_board_view and kicad_open_in_kicad in parallel. + // Poll whenever a board is visible so a newly created/replaced edit session is + // reflected even when the first board-view result still contained the old one. + const active = !!state.info?.ok; if (active && !pollTimer) pollTimer = setInterval(pollEdits, 2500); if (!active && pollTimer) { clearInterval(pollTimer); pollTimer = null; } } @@ -82,7 +85,9 @@ async function pollEdits() { try { const r = await app.callServerTool({ name: "kicad_edit_status", arguments: {} }); const st = json(r); - if (st?.session && st.changed) { state.note = null; await refresh(); } + const shownPcb = state.info?.edit?.pcb; + const sessionChanged = st?.session ? st.pcb !== shownPcb : !!shownPcb; + if (st?.changed || sessionChanged) { state.note = null; await refresh(); } } catch { /* the next tick retries */ } } async function openInKicad() { @@ -92,6 +97,7 @@ async function openInKicad() { const d = json(r); if (!d?.ok) state.err = d?.error || "could not open KiCad"; else if (!d.launched) state.note = t().nolaunch(d.launch_note); + else if (!d.live_ready) state.note = t().nolive(d.launch_note); await refresh(); } catch (e) { state.err = String(e?.message || e); } state.opening = false; render();