Autonomous-Schematic-Generation (ASG)
ASG is the KiCad-based autonomous schematic generation and analysis skill.
Related Skills
| Skill |
Purpose |
bom |
BOM extraction, enrichment, ordering, and export workflows |
digikey |
Search DigiKey for parts (prototype sourcing) |
mouser |
Search Mouser for parts (secondary prototype source) |
lcsc |
Search LCSC for parts (production sourcing, JLCPCB) |
element14 |
Search Newark/Farnell/element14 (international sourcing, reliable datasheets) |
jlcpcb |
PCB fabrication & assembly ordering |
pcbway |
Alternative PCB fabrication & assembly |
spice |
SPICE simulation verification of detected subcircuits |
emc |
EMC pre-compliance risk analysis — consumes schematic + PCB analyzer output |
Handoff guidance: Use this skill to parse schematics/PCBs and extract structured data. Hand off to bom for BOM enrichment, pricing, and ordering. Hand off to digikey/mouser/lcsc/element14 for part searches and datasheet fetching. Hand off to jlcpcb/pcbway for fabrication ordering and DFM rule validation. Always run spice for simulation verification during design reviews when any SPICE simulator is installed (check with which ngspice ltspice xyce). Always run emc for EMC pre-compliance risk analysis during design reviews when both schematic and PCB analysis are available. These are not optional — skipping them leaves value-computation errors and EMC risks undetected.
Before analysis: When the user asks to analyze or review a KiCad project, check whether a datasheets/ directory exists in the project. If not, and DigiKey API keys are available (DIGIKEY_CLIENT_ID), offer to sync datasheets first: "I can download datasheets for your components before analysis — this enables pin-level verification and decoupling validation against manufacturer specs. Want me to sync them?" If the user declines or no API keys are set, proceed without datasheets — the analysis works without them but datasheet verification findings won't be available.
If you see a DS-001 finding in the analyzer output (severity high, detector audit_datasheet_coverage), the review cannot make any verified claim. Stop and either (a) run the datasheet sync via digikey / mouser / lcsc / element14 (whichever has credentials/stock), (b) populate MPNs on the BOM parts, or (c) state explicitly in the report that every pin-level, electrical, and regulator finding is consistency only — do not use the words "verified", "confirmed", or "per datasheet" anywhere. DS-002 (datasheets missing but MPNs set) and DS-003 (partial MPN coverage) are softer variants with the same implication for the parts they cite.
Schematic Creation (Drawing & Redraw)
Use this workflow when the user asks to create, add, redraw, or restyle a
schematic — e.g. "add a 5V/5A TPS54560 circuit", "把原理图画成可读风格",
"generate a buck schematic", "重画这块电源".
- Read the drawing standard in
references/schematic-drawing-standards.md.
Every board-level design must start with page 1 titled System_block.
Draw the actual system architecture, power and signal flows, physical board
and isolation boundaries, interconnects and detail-page references. Distinguish
drawn circuits from missing/optional requirements; a sheet index alone is
insufficient. Preserve this cover during regeneration.
For board-level work or a rejected generated board, also read
references/reference-driven-board-design.md. Record the actual datasheet
pages/figures read and a per-IC peripheral-circuit contract before designing
or changing electrical circuits. For layout-only edits to an existing
hierarchy, read references/existing-project-redraw.md; preserve electrical
identity and report inherited electrical gaps separately.
For authorized electrical replacement or module expansion, read
references/electrical-redesign.md and references/project-verification.md.
For requested CopperPilot assistance, use
references/copperpilot-reference-workflow.md; reference candidates still
require independent electrical review and native verification.
Read references/symbol-and-peripheral-contracts.md before choosing or
repairing symbols/peripherals. Inventory every active page's core devices,
bind exact MPN/package pin maps and electrical types to source evidence, and
map required functions to real fitted circuit stages and load endpoints.
An interface header or named MCU net cannot satisfy an absent functional stage.
Visually study the user's engineering PDF examples when supplied; separate
presentation lessons from device-specific electrical connections.
For structured generation, read references/circuit-ir.md for the modular
model, automatic placement, imports and locked baselines; use
references/schematic-generation.md for the low-level writer and geometry.
- Establish electrical intent independently of geometry. Use datasheets
for real symbol/footprint pin numbers, ratings, topology and computed values.
Account for every pin as connected or intentionally NC. A redraw preserves
references, values, footprints, assembly state and native net partitions.
Prefer Circuit IR v2: explicit module ports, reusable parameterized instances,
stable IDs/reference mappings, and a physical pin coverage ledger. Resolve
named pins against the real symbol; require explicit handling of repeated
names. Keep values, ratings, MPN and evidence distinct. Never infer sharing
from same-name nets across imported circuit-synth subcircuits.
- Choose a topology-specific layout. Buck, LDO, integrated-inductor module,
filter and MCU pages have different structures. Plan visible local wiring,
keepouts, fields, rails and page allocation on a grid compatible with the
actual pins. Do not invent a SW/inductor stage for a different topology.
When comparing an engineer reference, read
references/engineer-template-comparison.md: extract visible facts separately
from unknown material identity, preserve the baseline, and record electrical
changes. Use explicit local wire groups and fixed bank rails for compact
power stages; consistently rotated bank fields are allowed after native
visual verification. The TPS53355 example is a draft presentation recipe,
not a qualified electrical design or an automatic topology recognizer.
Account for every reference peripheral branch by function and population,
including optional RF/MODE settings, isolation links and local bypasses.
A component marked NC/DNP is not an IC no-connect pin: preserve its wired
pads and explicit DNP state. Record each control pin's datasheet basis,
default assembly and allowed alternatives; do not infer a required pull-up
from an unpopulated resistor in a reference image.
- Generate deterministically when supported. Prefer
scripts/build_circuit.py
with Circuit IR v2 and separate presentation JSON. Select functional roles
and templates; the program measures bodies/pins/fields, allocates cells,
packs blocks, and retries failed layouts with bounded spacing expansion.
Supported multi-unit symbols retain physical reference and unit identity.
Use scripts/generate_schematic.py when explicit positions are required.
Both use MST pairing, bounded A*, field obstacles and explicit label policy.
For a generated baseline use --baseline and --lock-block: keep the
electrical diff and reject changes to protected symbols, fields, wires or
UUIDs. Generate candidates in a new directory; apply a reviewed candidate to
an authorized existing project only after the baseline and delta checks in
references/existing-project-redraw.md. Native multi-page sheets, graphical
buses and unsupported hidden/stacked pins still require a dedicated writer;
the writer supports same-symbol coincident pads on one connected net, including
hidden passive copies, while retaining each physical pin in native verification.
Library NC pins require explicit NC; internal legends remain protected graphics.
The v2 pack mode is explicitly a one-sheet presentation of logical modules.
Never silently flatten an existing hierarchical project or replace a failed
visible route with labels.
- Verify independent outputs. New-design automated acceptance requires
native ERC with no unresolved errors or warnings. For a layout-only redraw,
retain the raw baseline and final ERC, reject unreviewed new violations and
disclose inherited findings; this does not qualify the electrical design.
Native XML net partitions must match all intended pins exactly
(including no accidental merges). Run
scripts/check_schematic_geometry.py
on the serialized file; inspect body overlap, wire-through-body, all visible
fields/labels (including same-owner Reference/Value), pin legs, page/title
regions and connection anchors. Unsupported geometry remains INSUFFICIENT.
Run the existing schematic analyzer, then render through KiCad and inspect
both the full page and crowded regions. Text estimates and JSON are not
visual proof. Keep the exact file hash, KiCad version and evidence.
Run scripts/audit_symbol_integrity.py against the saved hierarchy and native
XML: inner pin legs must meet actual symbol ink, not merely its bounding box.
NC is not a blanket graphics exemption; retain per-pin justified dispositions.
For artwork-only fixes, keep external pin tips and native partitions unchanged.
Both generation entrypoints run this check in native verification; supply
--reference-contract to gate declared source/pin/peripheral facts as well.
Test contracts with removed parts, wrong returns/types/packages, DNP changes
and missing stages. Source/functional coverage must be independently authored,
not reconstructed as expected results from the generated candidate.
Separately audit the assembled circuit after removing DNP parts and merging
fitted zero-ohm links, with mutual-exclusion rules for configurable inputs.
The native all-pads netlist cannot prove default population behavior.
A valid setting code is not a qualified alternate converter design; changing
frequency or mode requires the coupled calculations and physical validation.
- Close the review explicitly.
AUTOMATED_PASS is only the script gate;
datasheet review and native visual review remain pending until performed.
Report gaps honestly. On a failed layout, change the relevant layout block,
regenerate into a new run directory and repeat dependent checks.
For implementation provenance, local adaptations and upstream limitations, see
references/upstream-integration.md and references/improvement-ledger.md.
The runtime does not require any full
upstream repository, a new MCP server, Bun, or network access. EasyEDA execution
still hands off to easyeda-schematic-draw when that is the user's target.
The analysis and design-review workflows below still apply to whatever was
generated.
Design Review Contract
When the user asks for a design review, complete report, ready-to-fab assessment, or anything equivalent, do not stop at running one or two analyzers and summarizing their findings. A design review in this skill has a stricter contract:
- Read the full workflow in this
SKILL.md, not just the analyzer command sections.
- Read
references/report-generation.md before writing the report.
- Run every applicable analyzer for the files present in the project, then say explicitly which ones were and were not run.
- Perform raw-file and datasheet cross-verification before claiming anything is "verified".
- Triage likely analyzer false positives before elevating them into blockers.
- If a required step could not be done, state it as a review gap, not as silent omission.
Treat this as the minimum bar. Analyzer JSON alone is not the final review.
Minimum Review Checklist
For a full design review, explicitly account for each item below in the report:
datasheets/ present, synced, or verification gap stated
analyze_schematic.py
analyze_pcb.py --full
cross_analysis.py
analyze_emc.py
- SPICE simulation when any simulator is installed
analyze_thermal.py when both schematic and PCB JSON exist
analyze_gerbers.py when fabrication outputs exist
- lifecycle audit when network access and MPN coverage allow it
- prior review / prior run delta check
- raw schematic/PCB spot-verification elevated to full verification for critical parts
- explicit report sections for blockers, verification basis, false positives, and skipped analyses
If an item is not applicable, say why. If it was skipped, say why. If it failed, say how that limits confidence.
Common Review Failure Modes
These are the failure modes this contract is meant to prevent:
- Stopping after schematic + PCB + EMC output and calling it a complete review
- Reporting analyzer findings without checking whether they are expected layout artifacts
- Claiming "verified" without direct datasheet evidence or structured extraction evidence
- Omitting thermal, lifecycle, prior-review delta, or gerber checks without disclosure
- Writing a report that lacks a verdict, blockers table, verification basis, or skipped-analysis notes
- Reading only the first part of this skill and missing the design-review workflow later in the file
PDF Schematic Analysis
This skill also handles PDF schematics — reference designs, dev board schematics, eval board docs, application notes, and datasheet typical-application circuits. Common use cases:
- Analyze a manufacturer's reference design to understand the circuit
- Extract a subcircuit (power supply, USB interface, sensor front-end) to incorporate into your own KiCad design
- Compare a PDF reference design against your own schematic
- Extract a full BOM from a PDF schematic
- Validate component values in a PDF against current datasheets
Workflow: Read the PDF pages visually → identify components and connections → extract structured data → translate to KiCad symbols and nets → validate against datasheets.
For the full methodology — component extraction, notation conventions, net mapping, subcircuit extraction, KiCad translation, and validation — read references/pdf-schematic-extraction.md.
For deep validation of extracted circuits against datasheets (verifying values, checking patterns, detecting errors), use the methodology in references/schematic-analysis.md.
Analysis Scripts
This skill includes Python scripts that extract comprehensive structured JSON from KiCad files in a single pass. Run these first, then reason about the output.
Read analyzer JSON output directly rather than writing ad-hoc extraction scripts. The JSON schema has specific field names (documented below and in references/output-schema.md) that are easy to get wrong in custom code. To extract a specific section: python3 -c "import json; d=json.load(open('file.json')); print(json.dumps(d['key'], indent=2))".
When the JSON surprises you — an AttributeError, unexpected shape, field
returning None that "should" have a value — stop and run --schema before
writing a second extraction attempt. It prints the exact field names and
types for every top-level key:
python3 <skill-path>/scripts/analyze_schematic.py --schema
python3 <skill-path>/scripts/analyze_pcb.py --schema
python3 <skill-path>/scripts/analyze_gerbers.py --schema
JSON field cheat sheet — the most common mistakes when reading analyzer
output by hand:
| What you want |
Correct path and field |
Common mistake |
| Pins on a net |
nets[<name>].pins[].component / .pin_number / .pin_name / .pin_type |
ref, pin, type, number |
| Unnamed-net pretty display |
nets[<name>].display_name — when set, a Ref.PinName hint for an __unnamed_N net whose only named IC pin tells the story (e.g. __unnamed_36 → U1.VBOOT). Absent means the analyzer couldn't disambiguate. |
Ignoring display_name and pasting raw __unnamed_36 into the report |
| IC pin map |
ic_pin_analysis[] is a list of IC entries; each has .reference and .pins[] with .pin_number / .pin_name / .pin_type / .net / .connected_to[] |
Treating it as {ref: {...}} or pins[].number |
| Detected circuits |
Every pattern-matched circuit (power regulators, RC filters, crystal oscillators, bridges, …) lives in findings[] — filter with finding_schema.get_findings(data, Det.POWER_REGULATORS) etc. Do not read from subcircuits[]: that's an IC-neighborhood grouping ({center_ic, ic_value, neighbor_components, …}), not a categorized detection index |
Looking for subcircuits.power_regulators, subcircuits.rc_filters, or any subcircuits[type] key — these never existed in v1.3 output |
| Zone net |
pcb.zones[].net is an integer net ID, not a string. Use f"{net!r}" or convert first |
f"{net:20s}" — crashes with ValueError: Unknown format code 's' for object of type 'int' |
| Footprint position |
pcb.footprints[].x / .y at top level (no .position wrapper) |
footprints[].position.x |
| Findings |
findings[] flat list — each has rule_id, detector, severity, summary, report_context. Filter with finding_schema.get_findings(data, Det.*) or group_findings(data) |
Looking for keyed dicts like signal_analysis.power_regulators[] (pre-v1.3 format, removed) |
This prevents format-string bugs and wrong field names. Use f-strings or json.dumps() for output formatting — never %s with non-string types. See references/output-schema.md for the full schema with common extraction patterns.
In all commands below, <skill-path> refers to this skill's base directory (shown at the top of this file when loaded).
Schematic Analyzer
python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --analysis-dir analysis/
python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --analysis-dir analysis/ --compact
python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --output analysis.json # one-off, no cache
Outputs structured JSON (~60-220KB depending on board complexity) with:
- Components & BOM: inventory with reference, value, footprint, lib_id, type classification, MPN, datasheet; deduplicated BOM with quantities
- Nets: full connectivity map with pin-to-net mapping, wire counts, no-connects
- Detected subcircuits (pattern-matched circuits — all emitted as
findings[] entries with matching Det.* detectors; use get_findings(data, Det.POWER_REGULATORS) etc. to fetch):
- Power regulators — LDO/switching/inverting topology, Vout estimation via datasheet-verified Vref lookup (~60 families) with heuristic fallback and fixed-output suffix parsing,
vref_source (lookup/heuristic/fixed_suffix) and vout_net_mismatch fields
- Voltage dividers, RC/LC filters (cutoff frequency), feedback networks, crystal circuits (load cap analysis, IC pin-based detection)
- Op-amp circuits (configuration, gain, integrator/compensator), transistor circuits (net-name-aware load classification: motor/heater/fan/solenoid/valve/pump/relay/speaker/buzzer/lamp; FET level shifter topology)
- Bridge circuits (H-bridge, 3-phase, cross-sheet detection), protection devices (ESD/TVS), current sense, decoupling analysis
- Domain-specific: RF chains, RF matching networks, BMS, Ethernet (BFS PHY-to-connector tracing), HDMI/DVI interfaces, memory interfaces, key matrices (net-name and topology-based), isolation barriers, addressable LED chains (WS2812/SK6812/APA102), battery chargers (TP4056/MCP73831/BQ2404x), motor drivers (A4988/TMC2209/DRV8301), ESD protection coverage audit, debug interfaces (SWD/JTAG with MCU tracing), power path (load switches/ideal diodes/USB PD controllers), ADC signal conditioning (external ADCs + voltage references with anti-aliasing cross-ref), reset/supervisor circuits (voltage supervisors/watchdogs/RC reset networks), clock distribution (clock generators/PLLs/oscillator output tracing), display/touch interfaces (SSD1306/ILI9341/ST7789/FT6236/GT911), sensor fusion (IMU/environmental/magnetometer with interrupt validation and bus clustering), level shifters (IC-based + discrete BSS138 with supply domain mapping), audio circuits (amplifiers/codecs with I2S/class-D detection), LED driver ICs (PWM/matrix/constant-current), RTC circuits (battery backup/crystal pairing), LED lighting audit (current limiting validation), thermocouple/RTD interfaces (MAX31855/MAX31865), power sequencing validation (power tree/enable chain/PG daisy chain analysis)
- IC pinout analysis: pin-level connectivity, IC function classification (3-tier: library prefix, part number keywords, description fallback)
- Power analysis: PDN impedance (1kHz–1GHz with MLCC parasitics), power budget, power sequencing (EN/PG chains), sleep current audit (resistive paths + regulator Iq with EN detection), voltage derating, inrush estimation
- Design analysis: ERC warnings, power domains, bus detection (I2C/SPI/UART/CAN/RS-485 with COPI/CIPO/SDI/SDO), differential pairs (suffix-pair matching for USB/LVDS/Ethernet/HDMI/MIPI/PCIe/SATA/CAN/RS-485), cross-domain signals (voltage equivalence), BOM optimization, test coverage, assembly complexity, USB compliance
- Quality checks: annotation completeness, label validation, PWR_FLAG audit, footprint filter validation, sourcing audit, property pattern audit, generic transistor symbol detection (flags Q_NPN_*/Q_PNP_*/Q_NMOS_*/Q_PMOS_* symbols with datasheet availability check)
- Structural: MCU alternate pin summary, ground domain classification, bus topology, wire geometry, spatial clustering, pin coverage, hierarchical label validation
Supports modern .kicad_sch (KiCad 6+) and legacy .sch (KiCad 4/5). Hierarchical designs parsed recursively.
Legacy format: For KiCad 5 legacy .sch files, the analyzer parses .lib files (cache libraries and project libs) to populate pin data. Pin-to-net mapping, signal analysis, and subcircuit detection all work when .lib files are available. Coverage is typically 92–100% — components whose .lib files are missing (standard KiCad system libs not in the repo) will lack pin data. Built-in fallbacks cover 40+ common symbols (R, C, L, D, LED, transistors, MOSFETs, crystals, switches, polarized caps, connectors up to 20-pin, resistor packs) with mil-based pin offsets and automatic wire-snap correction for version-mismatched pin positions.
Supplementary Data for Legacy Designs
When analyze_schematic.py returns incomplete data (components with missing pins due to unavailable .lib files), use additional project files to recover full analysis capability. The most valuable source is the .net netlist file, which provides explicit pin-to-net mapping that closes any remaining gaps.
For detailed parsing instructions, data recovery workflows, and a priority matrix of supplementary sources (netlist, cache library, PCB cross-reference, PDF exports), read references/supplementary-data-sources.md.
Verify analyzer output against reality. The analyzer can silently produce plausible-looking but incorrect results — wrong voltage estimates, missing MPNs, wrong pin-to-net mappings. These don't cause script errors; they just produce bad data that flows into your report. In testing across multiple boards, every project had at least one misleading analyzer output. Cross-reference against the raw .kicad_sch file:
- Component count — grep for
(symbol (lib_id blocks, subtract power symbols. Must match analyzer count exactly.
- Pin-to-net mapping — verify the analyzer's pin-to-net mapping against the raw schematic for each component. Read the symbol block, trace wires/labels to confirm connections. Cross-reference IC pin assignments against the manufacturer's datasheet pin table. This is the highest-value verification step — a wrong pin mapping produces a non-functional board and is invisible to DRC/ERC.
- Physical correctness (not just consistency) — consistency checks (schematic=PCB=analyzer all agree) are necessary but not sufficient. They only confirm the design is internally coherent — not that it matches the real-world part. The most dangerous case: a transistor symbol encodes a pinout assumption (like
Q_NPN_BEC = pin 1=B, 2=E, 3=C) that doesn't match the actual part. Everything passes consistency checks, but the board is wrong. To catch this:
- For transistors (BJT/MOSFET) in SOT-23, SOT-223, TO-252 and similar packages, the KiCad
lib_id suffix encodes a pin ordering assumption. SOT-23 BJTs exist in at least 6 pinout variants (BEC, BCE, EBC, ECB, CBE, CEB); SOT-23 MOSFETs in GDS, GSD, SGD, DSG. If no MPN is specified, there's no way to verify the assumption — flag this as a critical ambiguity.
- When an MPN is specified, verify the symbol's pin-to-pad assignment against the datasheet's pinout diagram for that specific package.
- This principle extends beyond transistors — any component where multiple pin orderings exist for the same package (voltage regulators with different pin assignments, connectors with vendor-specific pinouts) needs MPN-level verification.
- When verification isn't possible, assess plausibility. Not all unverified choices carry equal risk. Some align with strong conventions (the most common SOT-23 NPN pinout is BCE; 2N2222 in SOT-23 is almost always BCE); others go against convention or are genuinely ambiguous (SOT-23 MOSFETs have no dominant standard). When an MPN is missing and you can't verify, use domain knowledge — typical pinouts for that device type and package, manufacturer conventions, what the majority of parts in that category do — to assess whether the assumed pinout is likely correct, unusual, or a coin flip. Report the confidence level: "matches the most common convention" is different from "could go either way." This same reasoning applies to passive values (is 4.7kΩ a typical pull-up value for this bus?), circuit topologies (is this a standard application circuit?), and component selection (is this part commonly used for this purpose?).
- Net trace — trace power rails and critical signal nets end-to-end through wires/labels. Verify the analyzer's pin list is complete for each net.
- Regulator Vout — check the
vref_source field. "lookup" means datasheet-verified (~60 families); "heuristic" means it's a guess that needs manual verification. The vout_net_mismatch field flags estimated Vout differing >15% from the output rail name voltage.
- Hierarchical connectivity — on multi-sheet designs, verify sub-sheet connections are reflected in the net data.
See references/schematic-analysis.md Step 2 for the full verification checklist. If the script fails or returns unexpected results, see references/manual-schematic-parsing.md for the complete fallback methodology.
PCB Layout Analyzer
python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --analysis-dir analysis/
python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --analysis-dir analysis/ --proximity # add crosstalk analysis
python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --output pcb.json # one-off, no cache
Outputs structured JSON (~50-300KB depending on board complexity) with:
- Core: footprint inventory (pads, courtyards, net assignments, extended attrs, schematic cross-reference), track/via statistics, zone summaries, board outline/dimensions, routing completeness
- Zones & copper presence: zone outline vs filled polygon bounding boxes, fill ratio, cross-layer copper presence at every pad (which components have zone copper on the opposite layer and which don't), same-layer foreign zone detection
- Via analysis: type breakdown (through/blind/micro), annular ring checks, via-in-pad detection, BGA/QFN fanout patterns, current capacity, stitching via identification, tenting
- Signal integrity: per-net trace length, layer transition tracking (ground return paths), trace proximity/crosstalk (with
--proximity)
- Power & thermal: current capacity per net, power net routing summary, ground domain identification (AGND/DGND), zone stitching via density, thermal pad detection and via counting
- Manufacturing: placement analysis (courtyard overlaps, edge clearance), decoupling cap distances, DFM scoring (JLCPCB standard/advanced tier), tombstoning risk (0201/0402 thermal asymmetry), thermal pad via adequacy, silkscreen documentation audit
Add --full to include individual track/via coordinates, per-segment trace impedance (microstrip Z0 from stackup), pad-to-pad routed distances, return path continuity analysis, and via stub lengths. The --full output feeds the spice skill's parasitic extraction (extract_parasitics.py) for PCB-aware simulation. Supports KiCad 5 legacy format.
Zone fills must be current. The copper presence analysis uses KiCad's filled polygon data, which is computed when the user runs Edit → Fill All Zones (shortcut B) and stored in the .kicad_pcb file. If the board was modified after the last fill, the filled polygon data may be stale and the copper presence results will be inaccurate. When reviewing copper presence data, note whether the fill_ratio seems reasonable — a zone with 0 filled area or is_filled: false likely hasn't been filled.
Zone outline ≠ actual copper. The zone outline_bbox is the user-drawn boundary; filled_bbox is where copper actually exists after clearances, keepouts, and priority cuts. The copper_presence section shows which components have zone copper on the opposite layer — use this for capacitive touch pad isolation, antenna keep-out, and thermal analysis instead of inferring copper presence from zone outlines.
Copper-sensitive components need deeper checks. For capacitive touch pads and antennas, confirming "no opposite-layer copper" is necessary but not sufficient. The copper absence could be accidental — one zone refill after a routing change could add copper and kill touch sensitivity or detune the antenna. Check for explicit keepout zones (rule areas) that enforce the copper-free area as a DRC rule. Also measure same-layer GND clearance around touch pads and compare against the controller's app note minimum. For touch pads, compare trace lengths across all pads — significant asymmetry shifts baseline readings per channel. Report physical details (pad size, position, clearance, trace width/length) for all copper-sensitive components. See references/pcb-layout-analysis.md → Copper-Sensitive Components for the full checklist.
Verify after every run: Confirm footprint count and board outline dimensions against the raw .kicad_pcb file. Verify pad-to-net assignments for IC footprints against the schematic's pin-to-net mapping — this catches library footprint errors where pad numbering doesn't match the symbol pinout. If the script fails, see references/manual-pcb-parsing.md for the fallback methodology.
PCB Rich Format and Assembly Checks
All PCB analysis sections now produce findings with the rich format (detector, rule_id, category, severity, confidence, summary, recommendation, report_context). Additionally, 7 new assembly/DFM checks run automatically:
- FD-001: Fiducial marker presence (>= 3 per SMD side)
- TE-001: Test point coverage across signal nets
- OR-001: Passive component orientation consistency
- SK-001: Silkscreen text overlapping exposed pads
- VP-001: Via-in-pad without tenting (--full mode)
- BV-001: Via clearance from board edges (--full mode)
- KO-001: Keepout zone violations
- CP-001: Same-layer foreign zone under a component. Severity is
warning when the foreign zone is a non-ground net or the component has no GND pad; severity is info when the foreign zone is GND and the component has a GND pad (the common case of a bypass cap sitting over the ground pour — expected layout, not a clearance issue).
Cross-Domain Analysis
After running both schematic and PCB analyzers, run the cross-domain analyzer.
Point --schematic and --pcb at the current run's JSON files and pass
--analysis-dir analysis/ so the result lands inside the same run folder
and the manifest tracks it:
# Recommended: integrate into the current run
python3 <skill-path>/scripts/cross_analysis.py \
--schematic analysis/<run_id>/schematic.json \
--pcb analysis/<run_id>/pcb.json \
--analysis-dir analysis/
# One-off (bypasses the cache)
python3 <skill-path>/scripts/cross_analysis.py \
--schematic schematic.json --pcb pcb.json --output cross.json
Checks: CC-001 connector current capacity, EG-001 ESD protection gaps, DA-001 decoupling adequacy, XV-001..003 schematic/PCB sync. PCB JSON optional.
Connectivity Graph (--full mode)
When --full is used with the PCB analyzer, the output includes a connectivity_graph section with per-net copper connectivity analysis via union-find over pads, tracks, vias, and zone fills. This enables deterministic plane split detection and return path validation in cross_analysis.py. Each net entry shows island count, component-to-island mapping, gap locations, and disconnected pad pairs.
Gerber & Drill Analyzer
# Recommended: integrate into the current run
python3 <skill-path>/scripts/analyze_gerbers.py <gerber_directory/> --analysis-dir analysis/
# One-off
python3 <skill-path>/scripts/analyze_gerbers.py <gerber_directory/> --output gerber.json
Outputs: layer identification (X2 attributes), component/net/pin mapping (KiCad 6+ TO attributes), aperture function classification, trace width distribution, board dimensions, drill classification (via/component/mounting), layer completeness, alignment verification, pad type summary (SMD/THT ratio). Add --full for complete pin-to-net connectivity dump. ~10KB JSON.
The gerber analyzer produces a findings list with rich format findings: GR-001 missing layers, GR-002 alignment issues, GR-003 drill problems, GR-004 paste aperture mismatches, GR-005 open board outlines.
If the script fails or returns unexpected results, see references/manual-gerber-parsing.md for the complete fallback methodology for parsing raw Gerber/Excellon files directly.
All scripts output JSON to stdout by default. Prefer --analysis-dir analysis/
to integrate output into the run-folder convention described in "Analysis
Cache Convention" below — every analyzer in a single session then co-locates
inside the same analysis/<run_id>/ folder and is tracked by the manifest.
Use --output file.json only for one-off runs where you don't want the
result cached. Add --compact for single-line JSON.
Analyzer JSON is worth keeping — these are expensive to regenerate (large
schematics take time). --analysis-dir preserves every run and is the form
downstream tools (kidoc, diff_analysis, what_if) expect. They're not worth
committing to git, but don't delete them between analysis steps.
Harmonized Output Format
All analyzers produce a uniform output envelope:
{
"analyzer_type": "schematic|pcb|emc|cross_analysis|thermal|gerber|lifecycle|spice",
"schema_version": "1.3.0",
"summary": {
"total_findings": 42,
"by_severity": {"error": 3, "warning": 15, "info": 24}
},
"findings": [
{"rule_id": "...", "detector": "...", "severity": "...", "confidence": "...", "evidence_source": "...", "summary": "...", ...}
],
"trust_summary": {
"total_findings": 42,
"trust_level": "high|mixed|low",
"by_confidence": {"deterministic": 20, "heuristic": 18, "datasheet-backed": 4},
"by_evidence_source": {"datasheet": 4, "topology": 10, "heuristic_rule": 18, ...},
"provenance_coverage_pct": 96.5
}
}
The findings list is the single authoritative source for all findings. Use finding_schema.get_findings() or finding_schema.group_findings() to filter by detector, rule prefix, or category. Detector names are available as constants in finding_schema.Det. Severities are error, warning, or info; confidence is deterministic, heuristic, or datasheet-backed.
All analyzers support --text for human-readable output, --analysis-dir for
integrated run-folder output (preferred), and --output for writing to a
specific file verbatim (one-off). When both are passed, the explicit
--output path wins — pick one form per invocation.
Stage and Audience Filtering
All analyzers support --stage and --audience flags:
Stages: schematic, layout, pre_fab, bring_up
Audiences: designer (default), reviewer, manager
# Show only layout-relevant findings for a reviewer
python3 <skill-path>/scripts/analyze_pcb.py board.kicad_pcb --stage layout --audience reviewer --text
# Manager summary of schematic review readiness
python3 <skill-path>/scripts/analyze_schematic.py design.kicad_sch --audience manager --text
# Pre-fab checklist for cross-domain analysis
python3 <skill-path>/scripts/cross_analysis.py -s sch.json -p pcb.json --stage pre_fab --text
JSON output always includes all findings. --stage adds stages and in_active_stage fields to each finding plus a stage_filter summary. audience_summary is always computed with designer/reviewer/manager views. --text output respects both flags.
Generated Files
Analysis outputs are stored in analysis/ with timestamped run folders managed by analysis_cache.py. The manifest (analysis/manifest.json) tracks all runs.
| File Type |
Location |
Regenerable? |
Commit to git? |
| Analyzer JSON |
analysis/<timestamp>/*.json |
Yes (expensive) |
Configured by track_in_git in .kicad-happy.json (default: no) |
| Manifest |
analysis/manifest.json |
Yes |
Always (tracked by default) |
| Design review report |
User-chosen path |
Yes |
Optional |
When creating design reviews, check the manifest for prior runs. If auto_diff is enabled and prior runs exist, automatically diff current vs previous using diff_analysis.py and include the delta in the "Previous Review Delta" section.
See also the bom skill's cleanup section for datasheets, order CSVs, and backups.
Analysis Cache Configuration
The analysis section in .kicad-happy.json controls the shared analysis output directory:
{
"analysis": {
"output_dir": "analysis",
"retention": 5,
"auto_diff": true,
"track_in_git": false,
"diff_threshold": "major"
}
}
| Field |
Default |
Description |
output_dir |
"analysis" |
Analysis directory path, relative to project root |
retention |
5 |
Max unpinned runs to keep. 0 = unlimited |
auto_diff |
true |
Auto-include delta section in design reviews |
track_in_git |
false |
When false, JSONs gitignored but manifest tracked |
diff_threshold |
"major" |
Severity that triggers new timestamped folder: minor, major, breaking |
All fields are optional. Missing fields use defaults.
Output JSON Schema Quick Reference
Schematic analyzer top-level keys:
analyzer_type, schema_version, summary, findings, trust_summary,
file, kicad_version, file_version, title_block, statistics,
bom, components, nets, subcircuits, ic_pin_analysis, design_analysis,
connectivity_issues, hierarchy_context, hierarchy_warning,
net_classifications, rail_voltages
Optional (present when non-empty): pdn_impedance, sleep_current_audit, voltage_derating, power_budget, power_sequencing, bom_optimization, test_coverage, assembly_complexity, usb_compliance, inrush_analysis, sheets (multi-sheet only), missing_info, bom_lock, project_settings
…(truncated)
1---2name: autonomous-schematic-generation3description: Autonomous-Schematic-Generation (ASG): create, add, redraw, and inspect KiCad schematics with topology-specific layouts, obstacle-aware orthogonal routing, readable fields, and native ERC/netlist/geometry/render verification. Includes a deterministic generator from reusable Circuit IR modules with explicit ports, real pin resolution, automatic functional placement, supported multi-unit symbols and protected regeneration. Includes SKiDL/circuit-synth data adapters and geometry checks. Analyze KiCad schematics, PCB layouts, Gerbers, PDF schematics, netlists, BOMs, power trees, and DRC/ERC findings with evidence and confidence labels. Use for .kicad_sch, .kicad_pcb, .kicad_pro, schematic generation or redraw, 原理图自动生成、画原理图、原理图排版、信号追踪、电源检查 and KiCad design reviews.4---56# Autonomous-Schematic-Generation (ASG)78ASG is the KiCad-based autonomous schematic generation and analysis skill.910## Related Skills1112| Skill | Purpose |13|-------|---------|14| `bom` | BOM extraction, enrichment, ordering, and export workflows |15| `digikey` | Search DigiKey for parts (prototype sourcing) |16| `mouser` | Search Mouser for parts (secondary prototype source) |17| `lcsc` | Search LCSC for parts (production sourcing, JLCPCB) |18| `element14` | Search Newark/Farnell/element14 (international sourcing, reliable datasheets) |19| `jlcpcb` | PCB fabrication & assembly ordering |20| `pcbway` | Alternative PCB fabrication & assembly |21| `spice` | SPICE simulation verification of detected subcircuits |22| `emc` | EMC pre-compliance risk analysis — consumes schematic + PCB analyzer output |2324**Handoff guidance:** Use this skill to parse schematics/PCBs and extract structured data. Hand off to `bom` for BOM enrichment, pricing, and ordering. Hand off to `digikey`/`mouser`/`lcsc`/`element14` for part searches and datasheet fetching. Hand off to `jlcpcb`/`pcbway` for fabrication ordering and DFM rule validation. **Always run `spice`** for simulation verification during design reviews when any SPICE simulator is installed (check with `which ngspice ltspice xyce`). **Always run `emc`** for EMC pre-compliance risk analysis during design reviews when both schematic and PCB analysis are available. These are not optional — skipping them leaves value-computation errors and EMC risks undetected.2526**Before analysis:** When the user asks to analyze or review a KiCad project, check whether a `datasheets/` directory exists in the project. If not, and DigiKey API keys are available (`DIGIKEY_CLIENT_ID`), offer to sync datasheets first: "I can download datasheets for your components before analysis — this enables pin-level verification and decoupling validation against manufacturer specs. Want me to sync them?" If the user declines or no API keys are set, proceed without datasheets — the analysis works without them but datasheet verification findings won't be available.2728**If you see a `DS-001` finding in the analyzer output** (severity `high`, detector `audit_datasheet_coverage`), the review cannot make any verified claim. Stop and either (a) run the datasheet sync via `digikey` / `mouser` / `lcsc` / `element14` (whichever has credentials/stock), (b) populate MPNs on the BOM parts, or (c) state explicitly in the report that every pin-level, electrical, and regulator finding is *consistency only* — do not use the words "verified", "confirmed", or "per datasheet" anywhere. `DS-002` (datasheets missing but MPNs set) and `DS-003` (partial MPN coverage) are softer variants with the same implication for the parts they cite.2930## Schematic Creation (Drawing & Redraw)3132Use this workflow when the user asks to **create, add, redraw, or restyle a33schematic** — e.g. "add a 5V/5A TPS54560 circuit", "把原理图画成可读风格",34"generate a buck schematic", "重画这块电源".35361. **Read the drawing standard** in `references/schematic-drawing-standards.md`.37 **Every board-level design must start with page 1 titled `System_block`.**38 Draw the actual system architecture, power and signal flows, physical board39 and isolation boundaries, interconnects and detail-page references. Distinguish40 drawn circuits from missing/optional requirements; a sheet index alone is41 insufficient. Preserve this cover during regeneration.42 For board-level work or a rejected generated board, also read43 `references/reference-driven-board-design.md`. Record the actual datasheet44 pages/figures read and a per-IC peripheral-circuit contract before designing45 or changing electrical circuits. For layout-only edits to an existing46 hierarchy, read `references/existing-project-redraw.md`; preserve electrical47 identity and report inherited electrical gaps separately.48 For authorized electrical replacement or module expansion, read49 `references/electrical-redesign.md` and `references/project-verification.md`.50 For requested CopperPilot assistance, use51 `references/copperpilot-reference-workflow.md`; reference candidates still52 require independent electrical review and native verification.53 Read `references/symbol-and-peripheral-contracts.md` before choosing or54 repairing symbols/peripherals. Inventory every active page's core devices,55 bind exact MPN/package pin maps and electrical types to source evidence, and56 map required functions to real fitted circuit stages and load endpoints.57 An interface header or named MCU net cannot satisfy an absent functional stage.58 Visually study the user's engineering PDF examples when supplied; separate59 presentation lessons from device-specific electrical connections.60 For structured generation, read `references/circuit-ir.md` for the modular61 model, automatic placement, imports and locked baselines; use62 `references/schematic-generation.md` for the low-level writer and geometry.632. **Establish electrical intent independently of geometry.** Use datasheets64 for real symbol/footprint pin numbers, ratings, topology and computed values.65 Account for every pin as connected or intentionally NC. A redraw preserves66 references, values, footprints, assembly state and native net partitions.67 Prefer Circuit IR v2: explicit module ports, reusable parameterized instances,68 stable IDs/reference mappings, and a physical pin coverage ledger. Resolve69 named pins against the real symbol; require explicit handling of repeated70 names. Keep values, ratings, MPN and evidence distinct. Never infer sharing71 from same-name nets across imported circuit-synth subcircuits.723. **Choose a topology-specific layout.** Buck, LDO, integrated-inductor module,73 filter and MCU pages have different structures. Plan visible local wiring,74 keepouts, fields, rails and page allocation on a grid compatible with the75 actual pins. Do not invent a SW/inductor stage for a different topology.76 When comparing an engineer reference, read77 `references/engineer-template-comparison.md`: extract visible facts separately78 from unknown material identity, preserve the baseline, and record electrical79 changes. Use explicit local wire groups and fixed bank rails for compact80 power stages; consistently rotated bank fields are allowed after native81 visual verification. The TPS53355 example is a draft presentation recipe,82 not a qualified electrical design or an automatic topology recognizer.83 Account for every reference peripheral branch by function and population,84 including optional RF/MODE settings, isolation links and local bypasses.85 A component marked NC/DNP is not an IC no-connect pin: preserve its wired86 pads and explicit DNP state. Record each control pin's datasheet basis,87 default assembly and allowed alternatives; do not infer a required pull-up88 from an unpopulated resistor in a reference image.894. **Generate deterministically when supported.** Prefer `scripts/build_circuit.py`90 with Circuit IR v2 and separate presentation JSON. Select functional roles91 and templates; the program measures bodies/pins/fields, allocates cells,92 packs blocks, and retries failed layouts with bounded spacing expansion.93 Supported multi-unit symbols retain physical reference and unit identity.94 Use `scripts/generate_schematic.py` when explicit positions are required.95 Both use MST pairing, bounded A*, field obstacles and explicit label policy.96 For a generated baseline use `--baseline` and `--lock-block`: keep the97 electrical diff and reject changes to protected symbols, fields, wires or98 UUIDs. Generate candidates in a new directory; apply a reviewed candidate to99 an authorized existing project only after the baseline and delta checks in100 `references/existing-project-redraw.md`. Native multi-page sheets, graphical101 buses and unsupported hidden/stacked pins still require a dedicated writer;102 the writer supports same-symbol coincident pads on one connected net, including103 hidden passive copies, while retaining each physical pin in native verification.104 Library NC pins require explicit NC; internal legends remain protected graphics.105 The v2 pack mode is explicitly a one-sheet presentation of logical modules.106 Never silently flatten an existing hierarchical project or replace a failed107 visible route with labels.1085. **Verify independent outputs.** New-design automated acceptance requires109 native ERC with no unresolved errors or warnings. For a layout-only redraw,110 retain the raw baseline and final ERC, reject unreviewed new violations and111 disclose inherited findings; this does not qualify the electrical design.112 Native XML net partitions must match all intended pins exactly113 (including no accidental merges). Run `scripts/check_schematic_geometry.py`114 on the serialized file; inspect body overlap, wire-through-body, all visible115 fields/labels (including same-owner Reference/Value), pin legs, page/title116 regions and connection anchors. Unsupported geometry remains INSUFFICIENT.117 Run the existing schematic analyzer, then render through KiCad and inspect118 both the full page and crowded regions. Text estimates and JSON are not119 visual proof. Keep the exact file hash, KiCad version and evidence.120 Run `scripts/audit_symbol_integrity.py` against the saved hierarchy and native121 XML: inner pin legs must meet actual symbol ink, not merely its bounding box.122 NC is not a blanket graphics exemption; retain per-pin justified dispositions.123 For artwork-only fixes, keep external pin tips and native partitions unchanged.124 Both generation entrypoints run this check in native verification; supply125 `--reference-contract` to gate declared source/pin/peripheral facts as well.126 Test contracts with removed parts, wrong returns/types/packages, DNP changes127 and missing stages. Source/functional coverage must be independently authored,128 not reconstructed as expected results from the generated candidate.129 Separately audit the assembled circuit after removing DNP parts and merging130 fitted zero-ohm links, with mutual-exclusion rules for configurable inputs.131 The native all-pads netlist cannot prove default population behavior.132 A valid setting code is not a qualified alternate converter design; changing133 frequency or mode requires the coupled calculations and physical validation.1346. **Close the review explicitly.** `AUTOMATED_PASS` is only the script gate;135 datasheet review and native visual review remain pending until performed.136 Report gaps honestly. On a failed layout, change the relevant layout block,137 regenerate into a new run directory and repeat dependent checks.138139For implementation provenance, local adaptations and upstream limitations, see140`references/upstream-integration.md` and `references/improvement-ledger.md`.141The runtime does not require any full142upstream repository, a new MCP server, Bun, or network access. EasyEDA execution143still hands off to `easyeda-schematic-draw` when that is the user's target.144145The analysis and design-review workflows below still apply to whatever was146generated.147148## Design Review Contract149150When the user asks for a **design review**, **complete report**, **ready-to-fab assessment**, or anything equivalent, do not stop at running one or two analyzers and summarizing their findings. A design review in this skill has a stricter contract:1511521. Read the full workflow in this `SKILL.md`, not just the analyzer command sections.1532. Read `references/report-generation.md` before writing the report.1543. Run every applicable analyzer for the files present in the project, then say explicitly which ones were and were not run.1554. Perform raw-file and datasheet cross-verification before claiming anything is "verified".1565. Triage likely analyzer false positives before elevating them into blockers.1576. If a required step could not be done, state it as a review gap, not as silent omission.158159Treat this as the minimum bar. Analyzer JSON alone is not the final review.160161### Minimum Review Checklist162163For a full design review, explicitly account for each item below in the report:164165- `datasheets/` present, synced, or verification gap stated166- `analyze_schematic.py`167- `analyze_pcb.py --full`168- `cross_analysis.py`169- `analyze_emc.py`170- SPICE simulation when any simulator is installed171- `analyze_thermal.py` when both schematic and PCB JSON exist172- `analyze_gerbers.py` when fabrication outputs exist173- lifecycle audit when network access and MPN coverage allow it174- prior review / prior run delta check175- raw schematic/PCB spot-verification elevated to full verification for critical parts176- explicit report sections for blockers, verification basis, false positives, and skipped analyses177178If an item is not applicable, say why. If it was skipped, say why. If it failed, say how that limits confidence.179180### Common Review Failure Modes181182These are the failure modes this contract is meant to prevent:183184- Stopping after schematic + PCB + EMC output and calling it a complete review185- Reporting analyzer findings without checking whether they are expected layout artifacts186- Claiming "verified" without direct datasheet evidence or structured extraction evidence187- Omitting thermal, lifecycle, prior-review delta, or gerber checks without disclosure188- Writing a report that lacks a verdict, blockers table, verification basis, or skipped-analysis notes189- Reading only the first part of this skill and missing the design-review workflow later in the file190191## PDF Schematic Analysis192193This skill also handles **PDF schematics** — reference designs, dev board schematics, eval board docs, application notes, and datasheet typical-application circuits. Common use cases:194195- Analyze a manufacturer's reference design to understand the circuit196- Extract a subcircuit (power supply, USB interface, sensor front-end) to incorporate into your own KiCad design197- Compare a PDF reference design against your own schematic198- Extract a full BOM from a PDF schematic199- Validate component values in a PDF against current datasheets200201**Workflow:** Read the PDF pages visually → identify components and connections → extract structured data → translate to KiCad symbols and nets → validate against datasheets.202203For the full methodology — component extraction, notation conventions, net mapping, subcircuit extraction, KiCad translation, and validation — read `references/pdf-schematic-extraction.md`.204205For deep validation of extracted circuits against datasheets (verifying values, checking patterns, detecting errors), use the methodology in `references/schematic-analysis.md`.206207## Analysis Scripts208209This skill includes Python scripts that extract comprehensive structured JSON from KiCad files in a single pass. Run these first, then reason about the output.210211Read analyzer JSON output directly rather than writing ad-hoc extraction scripts. The JSON schema has specific field names (documented below and in `references/output-schema.md`) that are easy to get wrong in custom code. To extract a specific section: `python3 -c "import json; d=json.load(open('file.json')); print(json.dumps(d['key'], indent=2))"`.212213**When the JSON surprises you** — an AttributeError, unexpected shape, field214returning `None` that "should" have a value — stop and run `--schema` before215writing a second extraction attempt. It prints the exact field names and216types for every top-level key:217218```bash219python3 <skill-path>/scripts/analyze_schematic.py --schema220python3 <skill-path>/scripts/analyze_pcb.py --schema221python3 <skill-path>/scripts/analyze_gerbers.py --schema222```223224**JSON field cheat sheet** — the most common mistakes when reading analyzer225output by hand:226227| What you want | Correct path and field | Common mistake |228|---------------|-----------------------|----------------|229| Pins on a net | `nets[<name>].pins[].component / .pin_number / .pin_name / .pin_type` | `ref`, `pin`, `type`, `number` |230| Unnamed-net pretty display | `nets[<name>].display_name` — when set, a `Ref.PinName` hint for an `__unnamed_N` net whose only named IC pin tells the story (e.g. `__unnamed_36 → U1.VBOOT`). Absent means the analyzer couldn't disambiguate. | Ignoring `display_name` and pasting raw `__unnamed_36` into the report |231| IC pin map | `ic_pin_analysis[]` is a **list** of IC entries; each has `.reference` and `.pins[]` with `.pin_number / .pin_name / .pin_type / .net / .connected_to[]` | Treating it as `{ref: {...}}` or `pins[].number` |232| Detected circuits | Every pattern-matched circuit (power regulators, RC filters, crystal oscillators, bridges, …) lives in `findings[]` — filter with `finding_schema.get_findings(data, Det.POWER_REGULATORS)` etc. **Do not read from `subcircuits[]`**: that's an IC-neighborhood grouping (`{center_ic, ic_value, neighbor_components, …}`), not a categorized detection index | Looking for `subcircuits.power_regulators`, `subcircuits.rc_filters`, or any `subcircuits[type]` key — these never existed in v1.3 output |233| Zone net | `pcb.zones[].net` is an **integer net ID**, not a string. Use `f"{net!r}"` or convert first | `f"{net:20s}"` — crashes with `ValueError: Unknown format code 's' for object of type 'int'` |234| Footprint position | `pcb.footprints[].x / .y` at top level (no `.position` wrapper) | `footprints[].position.x` |235| Findings | `findings[]` flat list — each has `rule_id`, `detector`, `severity`, `summary`, `report_context`. Filter with `finding_schema.get_findings(data, Det.*)` or `group_findings(data)` | Looking for keyed dicts like `signal_analysis.power_regulators[]` (pre-v1.3 format, removed) |236237This prevents format-string bugs and wrong field names. Use f-strings or `json.dumps()` for output formatting — never `%s` with non-string types. See `references/output-schema.md` for the full schema with common extraction patterns.238239In all commands below, `<skill-path>` refers to this skill's base directory (shown at the top of this file when loaded).240241### Schematic Analyzer242```bash243python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --analysis-dir analysis/244python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --analysis-dir analysis/ --compact245python3 <skill-path>/scripts/analyze_schematic.py <file.kicad_sch> --output analysis.json # one-off, no cache246```247Outputs structured JSON (~60-220KB depending on board complexity) with:248- **Components & BOM**: inventory with reference, value, footprint, lib_id, type classification, MPN, datasheet; deduplicated BOM with quantities249- **Nets**: full connectivity map with pin-to-net mapping, wire counts, no-connects250- **Detected subcircuits** (pattern-matched circuits — all emitted as `findings[]` entries with matching `Det.*` detectors; use `get_findings(data, Det.POWER_REGULATORS)` etc. to fetch):251 - Power regulators — LDO/switching/inverting topology, Vout estimation via datasheet-verified Vref lookup (~60 families) with heuristic fallback and fixed-output suffix parsing, `vref_source` (`lookup`/`heuristic`/`fixed_suffix`) and `vout_net_mismatch` fields252 - Voltage dividers, RC/LC filters (cutoff frequency), feedback networks, crystal circuits (load cap analysis, IC pin-based detection)253 - Op-amp circuits (configuration, gain, integrator/compensator), transistor circuits (net-name-aware load classification: motor/heater/fan/solenoid/valve/pump/relay/speaker/buzzer/lamp; FET level shifter topology)254 - Bridge circuits (H-bridge, 3-phase, cross-sheet detection), protection devices (ESD/TVS), current sense, decoupling analysis255 - Domain-specific: RF chains, RF matching networks, BMS, Ethernet (BFS PHY-to-connector tracing), HDMI/DVI interfaces, memory interfaces, key matrices (net-name and topology-based), isolation barriers, addressable LED chains (WS2812/SK6812/APA102), battery chargers (TP4056/MCP73831/BQ2404x), motor drivers (A4988/TMC2209/DRV8301), ESD protection coverage audit, debug interfaces (SWD/JTAG with MCU tracing), power path (load switches/ideal diodes/USB PD controllers), ADC signal conditioning (external ADCs + voltage references with anti-aliasing cross-ref), reset/supervisor circuits (voltage supervisors/watchdogs/RC reset networks), clock distribution (clock generators/PLLs/oscillator output tracing), display/touch interfaces (SSD1306/ILI9341/ST7789/FT6236/GT911), sensor fusion (IMU/environmental/magnetometer with interrupt validation and bus clustering), level shifters (IC-based + discrete BSS138 with supply domain mapping), audio circuits (amplifiers/codecs with I2S/class-D detection), LED driver ICs (PWM/matrix/constant-current), RTC circuits (battery backup/crystal pairing), LED lighting audit (current limiting validation), thermocouple/RTD interfaces (MAX31855/MAX31865), power sequencing validation (power tree/enable chain/PG daisy chain analysis)256- **IC pinout analysis**: pin-level connectivity, IC function classification (3-tier: library prefix, part number keywords, description fallback)257- **Power analysis**: PDN impedance (1kHz–1GHz with MLCC parasitics), power budget, power sequencing (EN/PG chains), sleep current audit (resistive paths + regulator Iq with EN detection), voltage derating, inrush estimation258- **Design analysis**: ERC warnings, power domains, bus detection (I2C/SPI/UART/CAN/RS-485 with COPI/CIPO/SDI/SDO), differential pairs (suffix-pair matching for USB/LVDS/Ethernet/HDMI/MIPI/PCIe/SATA/CAN/RS-485), cross-domain signals (voltage equivalence), BOM optimization, test coverage, assembly complexity, USB compliance259- **Quality checks**: annotation completeness, label validation, PWR_FLAG audit, footprint filter validation, sourcing audit, property pattern audit, generic transistor symbol detection (flags Q_NPN_*/Q_PNP_*/Q_NMOS_*/Q_PMOS_* symbols with datasheet availability check)260- **Structural**: MCU alternate pin summary, ground domain classification, bus topology, wire geometry, spatial clustering, pin coverage, hierarchical label validation261262Supports modern `.kicad_sch` (KiCad 6+) and legacy `.sch` (KiCad 4/5). Hierarchical designs parsed recursively.263264**Legacy format:** For KiCad 5 legacy `.sch` files, the analyzer parses `.lib` files (cache libraries and project libs) to populate pin data. Pin-to-net mapping, signal analysis, and subcircuit detection all work when `.lib` files are available. Coverage is typically 92–100% — components whose `.lib` files are missing (standard KiCad system libs not in the repo) will lack pin data. Built-in fallbacks cover 40+ common symbols (R, C, L, D, LED, transistors, MOSFETs, crystals, switches, polarized caps, connectors up to 20-pin, resistor packs) with mil-based pin offsets and automatic wire-snap correction for version-mismatched pin positions.265266### Supplementary Data for Legacy Designs267268When `analyze_schematic.py` returns incomplete data (components with missing pins due to unavailable `.lib` files), use additional project files to recover full analysis capability. The most valuable source is the `.net` netlist file, which provides explicit pin-to-net mapping that closes any remaining gaps.269270For detailed parsing instructions, data recovery workflows, and a priority matrix of supplementary sources (netlist, cache library, PCB cross-reference, PDF exports), read `references/supplementary-data-sources.md`.271272**Verify analyzer output against reality.** The analyzer can silently produce plausible-looking but incorrect results — wrong voltage estimates, missing MPNs, wrong pin-to-net mappings. These don't cause script errors; they just produce bad data that flows into your report. In testing across multiple boards, every project had at least one misleading analyzer output. Cross-reference against the raw `.kicad_sch` file:2732741. **Component count** — grep for `(symbol (lib_id` blocks, subtract power symbols. Must match analyzer count exactly.2752. **Pin-to-net mapping** — verify the analyzer's pin-to-net mapping against the raw schematic for each component. Read the symbol block, trace wires/labels to confirm connections. Cross-reference IC pin assignments against the manufacturer's datasheet pin table. This is the highest-value verification step — a wrong pin mapping produces a non-functional board and is invisible to DRC/ERC.2763. **Physical correctness (not just consistency)** — consistency checks (schematic=PCB=analyzer all agree) are necessary but not sufficient. They only confirm the design is internally coherent — not that it matches the real-world part. The most dangerous case: a transistor symbol encodes a pinout assumption (like `Q_NPN_BEC` = pin 1=B, 2=E, 3=C) that doesn't match the actual part. Everything passes consistency checks, but the board is wrong. To catch this:277 - For transistors (BJT/MOSFET) in SOT-23, SOT-223, TO-252 and similar packages, the KiCad `lib_id` suffix encodes a pin ordering assumption. SOT-23 BJTs exist in at least 6 pinout variants (BEC, BCE, EBC, ECB, CBE, CEB); SOT-23 MOSFETs in GDS, GSD, SGD, DSG. If no MPN is specified, there's no way to verify the assumption — flag this as a critical ambiguity.278 - When an MPN is specified, verify the symbol's pin-to-pad assignment against the datasheet's pinout diagram for that specific package.279 - This principle extends beyond transistors — any component where multiple pin orderings exist for the same package (voltage regulators with different pin assignments, connectors with vendor-specific pinouts) needs MPN-level verification.280 - **When verification isn't possible, assess plausibility.** Not all unverified choices carry equal risk. Some align with strong conventions (the most common SOT-23 NPN pinout is BCE; 2N2222 in SOT-23 is almost always BCE); others go against convention or are genuinely ambiguous (SOT-23 MOSFETs have no dominant standard). When an MPN is missing and you can't verify, use domain knowledge — typical pinouts for that device type and package, manufacturer conventions, what the majority of parts in that category do — to assess whether the assumed pinout is likely correct, unusual, or a coin flip. Report the confidence level: "matches the most common convention" is different from "could go either way." This same reasoning applies to passive values (is 4.7kΩ a typical pull-up value for this bus?), circuit topologies (is this a standard application circuit?), and component selection (is this part commonly used for this purpose?).2814. **Net trace** — trace power rails and critical signal nets end-to-end through wires/labels. Verify the analyzer's pin list is complete for each net.2825. **Regulator Vout** — check the `vref_source` field. `"lookup"` means datasheet-verified (~60 families); `"heuristic"` means it's a guess that needs manual verification. The `vout_net_mismatch` field flags estimated Vout differing >15% from the output rail name voltage.2836. **Hierarchical connectivity** — on multi-sheet designs, verify sub-sheet connections are reflected in the net data.284285See `references/schematic-analysis.md` Step 2 for the full verification checklist. If the script fails or returns unexpected results, see `references/manual-schematic-parsing.md` for the complete fallback methodology.286287### PCB Layout Analyzer288```bash289python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --analysis-dir analysis/290python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --analysis-dir analysis/ --proximity # add crosstalk analysis291python3 <skill-path>/scripts/analyze_pcb.py <file.kicad_pcb> --output pcb.json # one-off, no cache292```293Outputs structured JSON (~50-300KB depending on board complexity) with:294- **Core**: footprint inventory (pads, courtyards, net assignments, extended attrs, schematic cross-reference), track/via statistics, zone summaries, board outline/dimensions, routing completeness295- **Zones & copper presence**: zone outline vs filled polygon bounding boxes, fill ratio, cross-layer copper presence at every pad (which components have zone copper on the opposite layer and which don't), same-layer foreign zone detection296- **Via analysis**: type breakdown (through/blind/micro), annular ring checks, via-in-pad detection, BGA/QFN fanout patterns, current capacity, stitching via identification, tenting297- **Signal integrity**: per-net trace length, layer transition tracking (ground return paths), trace proximity/crosstalk (with `--proximity`)298- **Power & thermal**: current capacity per net, power net routing summary, ground domain identification (AGND/DGND), zone stitching via density, thermal pad detection and via counting299- **Manufacturing**: placement analysis (courtyard overlaps, edge clearance), decoupling cap distances, DFM scoring (JLCPCB standard/advanced tier), tombstoning risk (0201/0402 thermal asymmetry), thermal pad via adequacy, silkscreen documentation audit300301Add `--full` to include individual track/via coordinates, per-segment trace impedance (microstrip Z0 from stackup), pad-to-pad routed distances, return path continuity analysis, and via stub lengths. The `--full` output feeds the `spice` skill's parasitic extraction (`extract_parasitics.py`) for PCB-aware simulation. Supports KiCad 5 legacy format.302303**Zone fills must be current.** The copper presence analysis uses KiCad's filled polygon data, which is computed when the user runs Edit → Fill All Zones (shortcut `B`) and stored in the `.kicad_pcb` file. If the board was modified after the last fill, the filled polygon data may be stale and the copper presence results will be inaccurate. When reviewing copper presence data, note whether the `fill_ratio` seems reasonable — a zone with 0 filled area or `is_filled: false` likely hasn't been filled.304305**Zone outline ≠ actual copper.** The zone `outline_bbox` is the user-drawn boundary; `filled_bbox` is where copper actually exists after clearances, keepouts, and priority cuts. The `copper_presence` section shows which components have zone copper on the opposite layer — use this for capacitive touch pad isolation, antenna keep-out, and thermal analysis instead of inferring copper presence from zone outlines.306307**Copper-sensitive components need deeper checks.** For capacitive touch pads and antennas, confirming "no opposite-layer copper" is necessary but not sufficient. The copper absence could be accidental — one zone refill after a routing change could add copper and kill touch sensitivity or detune the antenna. Check for explicit **keepout zones** (rule areas) that enforce the copper-free area as a DRC rule. Also measure same-layer GND clearance around touch pads and compare against the controller's app note minimum. For touch pads, compare trace lengths across all pads — significant asymmetry shifts baseline readings per channel. Report physical details (pad size, position, clearance, trace width/length) for all copper-sensitive components. See `references/pcb-layout-analysis.md` → Copper-Sensitive Components for the full checklist.308309**Verify after every run:** Confirm footprint count and board outline dimensions against the raw `.kicad_pcb` file. Verify pad-to-net assignments for IC footprints against the schematic's pin-to-net mapping — this catches library footprint errors where pad numbering doesn't match the symbol pinout. If the script fails, see `references/manual-pcb-parsing.md` for the fallback methodology.310311### PCB Rich Format and Assembly Checks312313All PCB analysis sections now produce findings with the rich format (detector, rule_id, category, severity, confidence, summary, recommendation, report_context). Additionally, 7 new assembly/DFM checks run automatically:314315- **FD-001**: Fiducial marker presence (>= 3 per SMD side)316- **TE-001**: Test point coverage across signal nets317- **OR-001**: Passive component orientation consistency318- **SK-001**: Silkscreen text overlapping exposed pads319- **VP-001**: Via-in-pad without tenting (--full mode)320- **BV-001**: Via clearance from board edges (--full mode)321- **KO-001**: Keepout zone violations322- **CP-001**: Same-layer foreign zone under a component. Severity is `warning` when the foreign zone is a non-ground net or the component has no GND pad; severity is `info` when the foreign zone is GND and the component has a GND pad (the common case of a bypass cap sitting over the ground pour — expected layout, not a clearance issue).323324### Cross-Domain Analysis325326After running both schematic and PCB analyzers, run the cross-domain analyzer.327Point `--schematic` and `--pcb` at the current run's JSON files and pass328`--analysis-dir analysis/` so the result lands inside the same run folder329and the manifest tracks it:330331```332# Recommended: integrate into the current run333python3 <skill-path>/scripts/cross_analysis.py \334 --schematic analysis/<run_id>/schematic.json \335 --pcb analysis/<run_id>/pcb.json \336 --analysis-dir analysis/337338# One-off (bypasses the cache)339python3 <skill-path>/scripts/cross_analysis.py \340 --schematic schematic.json --pcb pcb.json --output cross.json341```342343Checks: CC-001 connector current capacity, EG-001 ESD protection gaps, DA-001 decoupling adequacy, XV-001..003 schematic/PCB sync. PCB JSON optional.344345### Connectivity Graph (--full mode)346347When `--full` is used with the PCB analyzer, the output includes a `connectivity_graph` section with per-net copper connectivity analysis via union-find over pads, tracks, vias, and zone fills. This enables deterministic plane split detection and return path validation in cross_analysis.py. Each net entry shows island count, component-to-island mapping, gap locations, and disconnected pad pairs.348349### Gerber & Drill Analyzer350```bash351# Recommended: integrate into the current run352python3 <skill-path>/scripts/analyze_gerbers.py <gerber_directory/> --analysis-dir analysis/353354# One-off355python3 <skill-path>/scripts/analyze_gerbers.py <gerber_directory/> --output gerber.json356```357Outputs: layer identification (X2 attributes), component/net/pin mapping (KiCad 6+ TO attributes), aperture function classification, trace width distribution, board dimensions, drill classification (via/component/mounting), layer completeness, alignment verification, pad type summary (SMD/THT ratio). Add `--full` for complete pin-to-net connectivity dump. ~10KB JSON.358359The gerber analyzer produces a `findings` list with rich format findings: GR-001 missing layers, GR-002 alignment issues, GR-003 drill problems, GR-004 paste aperture mismatches, GR-005 open board outlines.360361If the script fails or returns unexpected results, see `references/manual-gerber-parsing.md` for the complete fallback methodology for parsing raw Gerber/Excellon files directly.362363All scripts output JSON to stdout by default. Prefer `--analysis-dir analysis/`364to integrate output into the run-folder convention described in "Analysis365Cache Convention" below — every analyzer in a single session then co-locates366inside the same `analysis/<run_id>/` folder and is tracked by the manifest.367Use `--output file.json` only for one-off runs where you don't want the368result cached. Add `--compact` for single-line JSON.369370**Analyzer JSON is worth keeping** — these are expensive to regenerate (large371schematics take time). `--analysis-dir` preserves every run and is the form372downstream tools (kidoc, diff_analysis, what_if) expect. They're not worth373committing to git, but don't delete them between analysis steps.374375### Harmonized Output Format376377All analyzers produce a uniform output envelope:378379```json380{381 "analyzer_type": "schematic|pcb|emc|cross_analysis|thermal|gerber|lifecycle|spice",382 "schema_version": "1.3.0",383 "summary": {384 "total_findings": 42,385 "by_severity": {"error": 3, "warning": 15, "info": 24}386 },387 "findings": [388 {"rule_id": "...", "detector": "...", "severity": "...", "confidence": "...", "evidence_source": "...", "summary": "...", ...}389 ],390 "trust_summary": {391 "total_findings": 42,392 "trust_level": "high|mixed|low",393 "by_confidence": {"deterministic": 20, "heuristic": 18, "datasheet-backed": 4},394 "by_evidence_source": {"datasheet": 4, "topology": 10, "heuristic_rule": 18, ...},395 "provenance_coverage_pct": 96.5396 }397}398```399400The `findings` list is the single authoritative source for all findings. Use `finding_schema.get_findings()` or `finding_schema.group_findings()` to filter by detector, rule prefix, or category. Detector names are available as constants in `finding_schema.Det`. Severities are `error`, `warning`, or `info`; confidence is `deterministic`, `heuristic`, or `datasheet-backed`.401402All analyzers support `--text` for human-readable output, `--analysis-dir` for403integrated run-folder output (preferred), and `--output` for writing to a404specific file verbatim (one-off). When both are passed, the explicit405`--output` path wins — pick one form per invocation.406407### Stage and Audience Filtering408409All analyzers support `--stage` and `--audience` flags:410411**Stages:** `schematic`, `layout`, `pre_fab`, `bring_up`412**Audiences:** `designer` (default), `reviewer`, `manager`413414```bash415# Show only layout-relevant findings for a reviewer416python3 <skill-path>/scripts/analyze_pcb.py board.kicad_pcb --stage layout --audience reviewer --text417418# Manager summary of schematic review readiness419python3 <skill-path>/scripts/analyze_schematic.py design.kicad_sch --audience manager --text420421# Pre-fab checklist for cross-domain analysis422python3 <skill-path>/scripts/cross_analysis.py -s sch.json -p pcb.json --stage pre_fab --text423```424425JSON output always includes all findings. `--stage` adds `stages` and `in_active_stage` fields to each finding plus a `stage_filter` summary. `audience_summary` is always computed with designer/reviewer/manager views. `--text` output respects both flags.426427### Generated Files428429Analysis outputs are stored in `analysis/` with timestamped run folders managed by `analysis_cache.py`. The manifest (`analysis/manifest.json`) tracks all runs.430431| File Type | Location | Regenerable? | Commit to git? |432|-----------|----------|-------------|----------------|433| Analyzer JSON | `analysis/<timestamp>/*.json` | Yes (expensive) | Configured by `track_in_git` in `.kicad-happy.json` (default: no) |434| Manifest | `analysis/manifest.json` | Yes | Always (tracked by default) |435| Design review report | User-chosen path | Yes | Optional |436437When creating design reviews, check the manifest for prior runs. If `auto_diff` is enabled and prior runs exist, automatically diff current vs previous using `diff_analysis.py` and include the delta in the "Previous Review Delta" section.438439See also the `bom` skill's cleanup section for datasheets, order CSVs, and backups.440441### Analysis Cache Configuration442443The `analysis` section in `.kicad-happy.json` controls the shared analysis output directory:444445```json446{447 "analysis": {448 "output_dir": "analysis",449 "retention": 5,450 "auto_diff": true,451 "track_in_git": false,452 "diff_threshold": "major"453 }454}455```456457| Field | Default | Description |458|-------|---------|-------------|459| `output_dir` | `"analysis"` | Analysis directory path, relative to project root |460| `retention` | `5` | Max unpinned runs to keep. `0` = unlimited |461| `auto_diff` | `true` | Auto-include delta section in design reviews |462| `track_in_git` | `false` | When false, JSONs gitignored but manifest tracked |463| `diff_threshold` | `"major"` | Severity that triggers new timestamped folder: `minor`, `major`, `breaking` |464465All fields are optional. Missing fields use defaults.466467### Output JSON Schema Quick Reference468469**Schematic analyzer top-level keys:**470```471analyzer_type, schema_version, summary, findings, trust_summary,472file, kicad_version, file_version, title_block, statistics,473bom, components, nets, subcircuits, ic_pin_analysis, design_analysis,474connectivity_issues, hierarchy_context, hierarchy_warning,475net_classifications, rail_voltages476```477Optional (present when non-empty): `pdn_impedance`, `sleep_current_audit`, `voltage_derating`, `power_budget`, `power_sequencing`, `bom_optimization`, `test_coverage`, `assembly_complexity`, `usb_compliance`, `inrush_analysis`, `sheets` (multi-sheet only), `missing_info`, `bom_lock`, `project_settings`478479480…(truncated)