Skip to content

hashgraph-online/awesome-codex-plugins / plugins/aklofas/kicad-happy/skills/kicad

Analyze KiCad projects and PDF schematics: schematics, PCB layouts, Gerbers, footprints, symbols, netlists, and design rules. Reviews designs for bugs, traces nets, cross-references schematic to PCB, extracts BOM data, checks DRC/ERC, DFM, power trees, and regulator circuits. Every finding carries a confidence label and evidence source with trust_summary rollup. Analyzes PDF schematics from dev boards, reference designs, eval kits, and datasheets. Supports KiCad 5–10. Use whenever the user mentions .kicad_sch, .kicad_pcb, .kicad_pro, PCB design review, schematic analysis, PDF schematics, reference designs, Gerber files, DRC/ERC, netlist issues, BOM extraction, signal tracing, power budget, DFM, or wants to understand, debug, compare, or review any hardware design. Also for "check my board", "review before fab", "what's wrong with my schematic", "is this ready to order", "check my power supply", "verify this circuit", OSHWA certification readiness, or any electronics/PCB design question.

FileKindSize
SKILL.mdskill md79.1 KB
references/config-reference.mdmarkdown19.1 KB
references/datasheet-verification.mdmarkdown16.5 KB
references/deep-review.mdmarkdown9.7 KB
references/design-intent.mdmarkdown5.6 KB
references/diff-analysis.mdmarkdown17.6 KB
references/file-formats.mdmarkdown15.1 KB
references/gerber-parsing.mdmarkdown33.5 KB
references/manual-gerber-parsing.mdmarkdown24.5 KB
references/manual-pcb-parsing.mdmarkdown17.2 KB
references/manual-schematic-parsing.mdmarkdown12.8 KB
references/net-tracing.mdmarkdown12.0 KB
references/oshwa-certification.mdmarkdown4.5 KB
references/output-schema.mdmarkdown33.4 KB
references/pcb-layout-analysis.mdmarkdown27.3 KB
references/pdf-schematic-extraction.mdmarkdown15.2 KB
references/report-generation.mdmarkdown56.3 KB
references/schematic-analysis.mdmarkdown63.9 KB
references/standards-compliance.mdmarkdown33.5 KB
references/supplementary-data-sources.mdmarkdown12.5 KB
references/what-if.mdmarkdown19.5 KB
review/README.mdmarkdown4.1 KB
review/fixtures/deep_review.example.jsonconfig1.2 KB
review/fixtures/design_context.example.jsonconfig388 B
review/fixtures/review_annotations.example.jsonconfig707 B
review/prompts/design_context.mdmarkdown4.9 KB
review/schemas/deep_review.schema.jsonconfig3.3 KB
review/schemas/design_context.schema.jsonconfig2.2 KB
review/schemas/review_annotations.schema.jsonconfig1.9 KB
review/scripts/_mini_jsonschema.pyscript6.6 KB
review/scripts/build_review_plan.pyscript2.3 KB
review/scripts/deep_review_gate.pyscript27.3 KB
review/scripts/merge_annotations.pyscript7.0 KB
review/scripts/validate_review.pyscript2.6 KB
scripts/.gitignoreother13 B
scripts/README.mdmarkdown23.4 KB
scripts/analysis_cache.pyscript42.1 KB
scripts/analyze_gerbers.pyscript90.9 KB
scripts/analyze_pcb.pyscript7.4 KB
scripts/analyze_schematic.pyscript6.7 KB
scripts/analyze_thermal.pyscript48.5 KB
scripts/analyzer_envelope.pyscript15.5 KB
scripts/capability_mode.pyscript10.2 KB
scripts/check_report_sections.pyscript10.6 KB
scripts/cross_analysis.pyscript69.4 KB
scripts/cross_verify.pyscript23.1 KB
scripts/design_intent.pyscript13.5 KB
scripts/detection_schema.pyscript26.0 KB
scripts/detector_helpers.pyscript15.2 KB
scripts/diff_analysis.pyscript23.5 KB
scripts/diff_engine.pyscript47.2 KB
scripts/domain_detectors.pyscript260.5 KB
scripts/envelopes/__init__.pyscript0 B
scripts/envelopes/cross_analysis.pyscript5.9 KB
scripts/envelopes/gerber.pyscript16.1 KB
scripts/envelopes/pcb.pyscript25.9 KB
scripts/envelopes/schematic.pyscript23.1 KB
scripts/envelopes/thermal.pyscript7.4 KB
scripts/export_issues.pyscript27.6 KB
scripts/fab_release_gate.pyscript29.8 KB
scripts/finding_schema.pyscript25.7 KB
scripts/gen_output_schema_md.pyscript9.2 KB
scripts/inputs_builder.pyscript4.0 KB
scripts/kicad_core/__init__.pyscript0 B
scripts/kicad_core/classify.pyscript32.5 KB
scripts/kicad_core/cli.pyscript4.2 KB
scripts/kicad_core/coords.pyscript2.0 KB
scripts/kicad_core/diagnostics.pyscript1.9 KB
scripts/kicad_core/executables.pyscript1.0 KB
scripts/kicad_core/fields.pyscript5.9 KB
scripts/kicad_core/fileio.pyscript5.4 KB
scripts/kicad_core/hotloop.pyscript3.1 KB
scripts/kicad_core/instances.pyscript5.7 KB
scripts/kicad_core/model.pyscript4.8 KB
scripts/kicad_core/netnames.pyscript19.1 KB
scripts/kicad_core/netquery.pyscript6.7 KB
scripts/kicad_core/pairing.pyscript1.9 KB
scripts/kicad_core/parts.pyscript28.9 KB
scripts/kicad_core/passives.pyscript10.0 KB
scripts/kicad_core/pdn.pyscript1011 B
scripts/kicad_core/project.pyscript43.2 KB
scripts/kicad_core/render.pyscript2.7 KB
scripts/kicad_core/sexp.pyscript12.6 KB
scripts/kicad_core/textvars.pyscript5.4 KB
scripts/kicad_core/token_cache.pyscript2.2 KB
scripts/kicad_core/values.pyscript14.1 KB
scripts/kicad_types.pyscript15.1 KB
scripts/lifecycle_audit.pyscript6.7 KB
scripts/lifecycle_engine.pyscript52.8 KB
scripts/lookup_detectors.pyscript29.9 KB
scripts/lookup_helpers.pyscript3.0 KB
scripts/methodology_gerbers.mdmarkdown23.1 KB
scripts/methodology_pcb.mdmarkdown22.2 KB
scripts/methodology_schematic.mdmarkdown43.1 KB
scripts/netlist_queries.pyscript4.2 KB
scripts/output_filters.pyscript16.8 KB
scripts/output_io.pyscript5.3 KB
scripts/pcb/__init__.pyscript0 B
scripts/pcb/assembly.pyscript58.3 KB
scripts/pcb/connectivity.pyscript27.7 KB
scripts/pcb/copper.pyscript61.0 KB
scripts/pcb/dfm.pyscript56.9 KB
scripts/pcb/geometry.pyscript59.5 KB
scripts/pcb/pipeline.pyscript30.3 KB
scripts/pcb/presentation.pyscript24.3 KB
scripts/pcb/reader.pyscript87.1 KB
scripts/pcb/routing.pyscript53.5 KB
scripts/project_config.pyscript23.1 KB
scripts/risk_summary.pyscript3.1 KB
scripts/run_id.pyscript1.7 KB
scripts/schema_codec.pyscript5.0 KB
scripts/schematic/__init__.pyscript0 B
scripts/schematic/audits.pyscript56.0 KB
scripts/schematic/bom_stats.pyscript6.1 KB
scripts/schematic/connectivity.pyscript62.9 KB
scripts/schematic/erc_pins.pyscript8.4 KB
scripts/schematic/hierarchy.pyscript21.5 KB
scripts/schematic/ic_analysis.pyscript21.4 KB
scripts/schematic/legacy_reader.pyscript49.4 KB
scripts/schematic/net_analysis.pyscript75.5 KB
scripts/schematic/pipeline.pyscript72.2 KB
scripts/schematic/presentation.pyscript20.9 KB
scripts/schematic/reader.pyscript64.7 KB
scripts/schematic/system_analyses.pyscript126.9 KB
scripts/signal_detectors.pyscript248.0 KB
scripts/summarize_findings.pyexecutablescript17.4 KB
scripts/validation_detectors.pyscript75.3 KB
scripts/what_if.pyscript68.4 KB

scripts/cross_analysis.py

View on GitHub
#!/usr/bin/env python3
"""Cross-domain analysis — checks requiring both schematic and PCB data.

Consumes schematic and PCB analyzer JSON outputs. Produces rich findings
for checks that span the schematic-PCB boundary: connector current capacity,
ESD coverage gaps, decoupling adequacy, and schematic/PCB cross-validation.

Usage:
    python3 cross_analysis.py --schematic sch.json --pcb pcb.json [--output cross_analysis.json]
    python3 cross_analysis.py --schematic sch.json  # PCB-less mode (limited checks)
    python3 cross_analysis.py --schema               # Print output schema
"""

from __future__ import annotations

import argparse
import json
import math
import os
import re
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from finding_schema import make_finding, compute_trust_summary, assign_finding_ids, show_decoded_names
from kicad_core.fileio import atomic_write_text, json_load
from kicad_core.fields import merge_unit_fields
from kicad_core.netnames import (RAIL_SIGNAL_SUFFIXES, _VOLTAGE_SIGNAL_SUFFIXES, is_ground_name,
                                 is_pin_guarded_signal, is_power_net_name, net_leaf)
from kicad_core.netquery import build_net_id_map as _build_net_id_map
from kicad_core.pairing import pair_by_path
from envelopes.cross_analysis import CrossAnalysisEnvelope
from schema_codec import emit_schema
from inputs_builder import build_inputs, build_upstream_artifact, build_compat
from capability_mode import get_capability_mode_ref
from kicad_core.cli import (add_only_deterministic_arg, add_output_arg, add_schema_arg,
                            add_stage_audience_args, add_text_arg, envelope_type_error,
                            utf8_text_stdout)

ANALYZER_SOURCE = "cross"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def is_cross_analysis_ground_name(name: str) -> bool:
    """Ground net: the shared schematic rule (kicad_core.netnames.is_ground_name) plus EARTH and CHASSIS."""
    if not name:
        return False
    return is_ground_name(name) or net_leaf(name).upper() in ('EARTH', 'CHASSIS')


def _is_power_net(name: str) -> bool:
    if not name:
        return False
    n = name.upper()
    if is_cross_analysis_ground_name(name):
        return True
    # A signal about a rail (VBUS_DET, VIN_EN, +5V_SENSE, 5VEN) is not the rail.
    if '_' in n and n.rsplit('_', 1)[-1] in RAIL_SIGNAL_SUFFIXES:
        return False
    m = re.match(r'^\+?\d+V\d*([A-Z]+)$', n)
    if m and m.group(1) in _VOLTAGE_SIGNAL_SUFFIXES:
        return False
    if n.startswith(('+', 'VCC', 'VDD', 'VBUS', 'VIN', 'VBAT', 'VSYS')):
        return True
    if re.match(r'^\+?\d+V\d*', n):
        return True
    return False


def _parse_voltage_from_name(name: str) -> float | None:
    if not name:
        return None
    m = re.search(r'(\d+)V(\d+)', name.upper())
    if m:
        return float(m.group(1)) + float(m.group(2)) / (10 ** len(m.group(2)))
    m = re.search(r'(\d+\.?\d*)V', name.upper())
    if m:
        return float(m.group(1))
    return None


def _flagged_return_path_entries(pcb: dict, threshold_pct: float = 95.0) -> dict[str, dict]:
    """Return nets with measured return-plane coverage below threshold."""
    flagged: dict[str, dict] = {}
    for entry in pcb.get('return_path_continuity', []) or []:
        net_name = entry.get('net', '')
        coverage = entry.get('reference_plane_coverage_pct', 100)
        if net_name and isinstance(coverage, (int, float)) and coverage < threshold_pct:
            flagged[net_name] = entry
    return flagged


def _island_size_map(graph: dict) -> dict[int, int]:
    """Return {island_id: member_count} for a connectivity graph."""
    sizes: dict[int, int] = {}
    for island_id in (graph.get('components', {}) or {}).values():
        if isinstance(island_id, int):
            sizes[island_id] = sizes.get(island_id, 0) + 1
    return sizes


# ---------------------------------------------------------------------------
# CC-001: Connector current capacity
# ---------------------------------------------------------------------------

_IPC2152_1OZ_10C = {
    0.5: 0.25, 1.0: 0.50, 2.0: 1.10, 3.0: 1.80,
    5.0: 3.50, 7.0: 5.50, 10.0: 9.0,
}


def _reg_iout(reg: dict) -> float:
    return (reg.get('estimated_iout_A')
            or (reg.get('power_dissipation') or {}).get('estimated_iout_A')
            or 0)


def _reg_iin(reg: dict) -> float:
    """Estimated input current of a regulator: its output current for a linear regulator,
    Iout * |Vout| / (Vin * efficiency) for a switcher whose estimate carries them. Vout is
    read from the output rail's name when the name carries a voltage."""
    iout = _reg_iout(reg)
    pd = reg.get('power_dissipation') or {}
    vin, vout, eff = pd.get('vin_estimated_V'), pd.get('vout_V'), pd.get('efficiency_assumed')
    vout = _parse_voltage_from_name(reg.get('output_rail', '')) or vout
    if iout and all(isinstance(v, (int, float)) for v in (vin, vout, eff)) and vin > 0 and eff > 0:
        return iout * abs(vout) / (vin * eff)
    return iout


def _path_min_width(pad_paths: dict, net_name: str, conn_ref: str, reg_refs: set) -> float | None:
    """Narrowest track on the routed paths between a connector's pads and the pads of the
    regulators it feeds on one net (pad_to_pad_distances, keyed "REF.pad-REF.pad");
    None when no such path was measured."""
    widths = []
    for key, entry in pad_paths.items():
        w = entry.get('min_width_mm')
        if entry.get('net') != net_name or not isinstance(w, (int, float)) or w <= 0:
            continue
        if any((key.startswith(conn_ref + '.') and f'-{r}.' in key)
               or (key.startswith(r + '.') and f'-{conn_ref}.' in key) for r in reg_refs):
            widths.append(w)
    return min(widths) if widths else None


def _attached_min_width(segments: list, net_id_map: dict, net_name: str, fp: dict) -> float | None:
    """Narrowest track of net_name with an end inside the footprint's courtyard (the track
    leaving the connector); None without a courtyard or such a track."""
    cy = fp.get('courtyard') or {}
    if not all(isinstance(cy.get(k), (int, float)) for k in ('min_x', 'min_y', 'max_x', 'max_y')):
        return None
    widths = []
    for seg in segments:
        net_id = seg.get('net', 0)
        if (net_id_map.get(net_id, '') if isinstance(net_id, int) else str(net_id)) != net_name:
            continue
        w = seg.get('width', 0) or 0
        if w > 0 and any(cy['min_x'] <= x <= cy['max_x'] and cy['min_y'] <= y <= cy['max_y']
                         for x, y in ((seg.get('x1'), seg.get('y1')), (seg.get('x2'), seg.get('y2')))
                         if isinstance(x, (int, float)) and isinstance(y, (int, float))):
            widths.append(w)
    return min(widths) if widths else None


def _min_trace_width_for_current(current_a: float) -> float:
    prev_i, prev_w = 0.0, 0.0
    for i, w in sorted(_IPC2152_1OZ_10C.items()):
        if current_a <= i:
            frac = (current_a - prev_i) / (i - prev_i)
            return prev_w + frac * (w - prev_w)
        prev_i, prev_w = i, w
    return prev_w


_NET_NAME_HEURISTICS = [
    (re.compile(r'(?i)CLK|CLOCK|XTAL|OSC'), 'clock'),
    (re.compile(r'(?i)USB_D[PM]|USB_D\+|USB_D.|USBDP|USBDM'), 'usb'),
    (re.compile(r'(?i)ETH_|MDIO|MDC|TX[PN]|RX[PN]'), 'ethernet'),
    (re.compile(r'(?i)DDR_|DQ\d|DQS|DM\d|CKE|ODT'), 'memory'),
    (re.compile(r'(?i)^SDA$|^SCL$|I2C'), 'i2c'),
    (re.compile(r'(?i)CAN[HL]|CAN_[HL]'), 'can'),
    (re.compile(r'(?i)MISO|MOSI|SCK|SPI'), 'spi'),
    (re.compile(r'(?i)\bSW$|SW_NODE|^LX$'), 'switching_node'),
    (re.compile(r'(?i)LVDS|MIPI'), 'lvds'),
]

_HIGH_SPEED_TYPES = {'clock', 'usb', 'ethernet', 'memory', 'hdmi', 'lvds', 'rf'}


def _get_net_classification(net_name, schematic):
    if schematic:
        classifications = schematic.get('net_classifications') or {}
        if net_name in classifications:
            return classifications[net_name]
    for pattern, net_type in _NET_NAME_HEURISTICS:
        if pattern.search(net_name):
            return {'type': net_type, 'source': 'name_heuristic'}
    return None


def _get_highest_frequency(schematic):
    highest = 0.0
    if not schematic:
        return highest
    findings = schematic.get('findings', [])
    for f in findings:
        det = f.get('detector', '')
        if det == 'detect_crystal_circuits':
            freq = f.get('frequency')
            if isinstance(freq, (int, float)) and freq > highest:
                highest = freq
        elif det == 'detect_power_regulators':
            freq = f.get('switching_frequency_hz')
            if isinstance(freq, (int, float)) and freq > highest:
                highest = freq
    return highest


def _point_to_segment_distance(px, py, x1, y1, x2, y2):
    dx, dy = x2 - x1, y2 - y1
    length_sq = dx * dx + dy * dy
    if length_sq == 0:
        return math.sqrt((px - x1) ** 2 + (py - y1) ** 2)
    t = max(0, min(1, ((px - x1) * dx + (py - y1) * dy) / length_sq))
    proj_x = x1 + t * dx
    proj_y = y1 + t * dy
    return math.sqrt((px - proj_x) ** 2 + (py - proj_y) ** 2)


# ---------------------------------------------------------------------------
# checks_run recorder
# ---------------------------------------------------------------------------

class _CheckRecorder:
    """Accumulates checks_run[] entries in call order.

    Determinism comes from call order, not dict-iteration order:
    run_all_checks() invokes each check_* function in a fixed sequence,
    and every check_* function calls record() exactly once (every
    early-return guard, and every terminal return, records before
    returning).
    """

    def __init__(self):
        self.entries: list[dict] = []

    def record(self, check, ran, reason_skipped, items_examined, findings_count):
        self.entries.append({
            'check': check,
            'ran': ran,
            'reason_skipped': reason_skipped,
            'items_examined': items_examined,
            'findings': findings_count,
        })


def _record(recorder, check, ran, reason_skipped, items_examined, findings):
    if recorder is not None:
        recorder.record(check, ran, reason_skipped, items_examined, len(findings))


def check_connector_current(schematic: dict, pcb: dict | None, recorder=None) -> list[dict]:
    """CC-001: Check connector pin current capacity vs trace width."""
    findings: list[dict] = []
    if not pcb:
        _record(recorder, 'CC-001', False, 'no PCB data provided', 0, findings)
        return findings

    footprints = pcb.get('footprints', [])
    fp_map = {fp.get('reference', ''): fp for fp in footprints}
    pad_paths = pcb.get('pad_to_pad_distances') or {}

    segments = (pcb.get('tracks') or {}).get('segments') or []
    if not segments:
        _record(recorder, 'CC-001', False, 'no PCB track segments present', 0, findings)
        return findings
    net_id_map = _build_net_id_map(pcb)

    components = schematic.get('components', [])
    connectors = [c for c in components if c.get('type') == 'connector']
    regulators = [f for f in schematic.get('findings', [])
                  if f.get('detector') == 'detect_power_regulators']

    for conn in connectors:
        ref = conn['reference']
        fp = fp_map.get(ref)
        if not fp:
            continue
        pad_nets = {e.get('net') for e in (fp.get('pad_nets') or {}).values()}
        for net_name in sorted(n for n in pad_nets if n):
            if is_cross_analysis_ground_name(net_name) or not _is_power_net(net_name):
                continue
            voltage = _parse_voltage_from_name(net_name)
            if voltage is None:
                continue
            fed = [reg for reg in regulators if reg.get('input_rail') == net_name]
            total_current = sum(_reg_iin(reg) for reg in fed)
            if total_current <= 0:
                continue
            # The routed connector-to-regulator path when it was measured, else the
            # track leaving the connector.
            trace_w = _path_min_width(pad_paths, net_name, ref,
                                      {reg.get('ref') for reg in fed if reg.get('ref')})
            where = 'between the connector and those regulators'
            if trace_w is None:
                trace_w = _attached_min_width(segments, net_id_map, net_name, fp)
                where = 'leaving the connector'
            if trace_w is None:
                continue
            min_w = _min_trace_width_for_current(total_current)
            if trace_w < min_w * 0.8:
                findings.append(make_finding(
                    detector='check_connector_current', rule_id='CC-001',
                    category='current_capacity',
                    summary=f'Connector {ref}: trace on {net_name} too narrow for ~{total_current:.1f}A (est.)',
                    description=(
                        f'Power net {net_name} at connector {ref} carries an estimated '
                        f'{total_current:.1f}A into the regulators it feeds (from their '
                        f'output capacitance), but the narrowest trace {where} is {trace_w:.2f}mm. '
                        f'IPC-2152 recommends >= {min_w:.2f}mm (1oz Cu, 10C rise).'
                    ),
                    severity='warning', confidence='heuristic', evidence_source='topology',
                    components=[ref], nets=[net_name],
                    recommendation=f'Widen trace on {net_name} to >= {min_w:.1f}mm or use copper pour.',
                    standard_ref='IPC-2152', impact='Trace overheating and voltage drop',

                    source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'CC-001', True, None, len(connectors), findings)
    return findings


# ---------------------------------------------------------------------------
# EG-001: ESD coverage gap analysis
# ---------------------------------------------------------------------------

_EXTERNAL_CONNECTOR_KEYWORDS = (
    'usb', 'rj45', 'rj11', 'ethernet', 'hdmi', 'displayport',
    'barrel', 'dc_jack', 'bnc', 'sma', 'din', 'dsub', 'db9', 'db25',
    'screw_terminal', 'phoenix', 'molex',
)


def check_esd_coverage_gaps(schematic: dict, pcb: dict | None, recorder=None) -> list[dict]:
    """EG-001: Check for external connector pins missing ESD protection."""
    findings: list[dict] = []
    protection = [f for f in schematic.get('findings', [])
                  if f.get('detector') == 'detect_protection_devices']

    protected_nets: set[str] = set()
    for pd in protection:
        pnet = pd.get('protected_net', '')
        if pnet:
            protected_nets.add(pnet)
        for pn in pd.get('protected_nets', []):
            protected_nets.add(pn)

    components = schematic.get('components', [])
    connectors = [c for c in components if c.get('type') == 'connector']
    comp_type = {c.get('reference'): c.get('type') for c in components}
    all_nets = schematic.get('nets') or {}
    # A clamp behind one series resistor, ferrite or inductor still protects the pin; the
    # far side must be a clamped signal (a pull-up to a clamped rail protects nothing, and a
    # fuse or a reverse-polarity diode is no ESD clamp).
    clamped = {n for pd in protection if pd.get('type') in ('esd_ic', 'diode', 'varistor', 'surge_arrester')
               for n in [pd.get('protected_net', '')] + list(pd.get('protected_nets') or []) if n}
    # The pin's own net must reach no IC, or that IC sits in front of the clamp.
    via_series: set[str] = set()
    for c in components:
        if (c.get('type') not in ('resistor', 'ferrite_bead', 'inductor')
                or c.get('dnp') or c.get('on_board') is False):
            continue
        ends = {n for n in (c.get('pin_nets') or {}).values() if n}
        if len(ends) != 2:
            continue
        a, b = sorted(ends)
        for near, far in ((a, b), (b, a)):
            if (far in clamped and not _is_power_net(far)
                    and not is_ground_name(far) and not is_power_net_name(far)
                    and not any(comp_type.get(p.get('component')) == 'ic'
                                for p in (all_nets.get(near) or {}).get('pins', []))):
                via_series.add(near)
    rails = {n for n, info in all_nets.items()
             if any(str(p.get('component', '')).startswith(('#PWR', '#FLG'))
                    for p in info.get('pins', []))}
    pin_signals = {n for n, info in all_nets.items()
                   if n not in rails and is_pin_guarded_signal(n, [(p.get('pin_type'), comp_type.get(p.get('component')) == 'ic')
                                                for p in info.get('pins', [])])}

    for conn in connectors:
        val_lib = (conn.get('value', '') + ' ' + conn.get('lib_id', '')).lower()
        if not any(k in val_lib for k in _EXTERNAL_CONNECTOR_KEYWORDS):
            continue
        ref = conn['reference']

        unprotected_nets = []
        pin_nets = conn.get('pin_nets') or {}
        for _, net in sorted(pin_nets.items()):
            if (not net or _is_power_net(net) or is_cross_analysis_ground_name(net)
                    or is_ground_name(net) or (is_power_net_name(net) and net not in pin_signals)):
                continue
            nc_pins = (all_nets.get(net) or {}).get('pins') or []
            if nc_pins and all(p.get('pin_type') == 'no_connect' for p in nc_pins):
                continue  # an unused pin typed no-connect, alone on its net
            if net not in protected_nets and net not in via_series:
                unprotected_nets.append(net)

        # Deduplicate
        unprotected_nets = list(dict.fromkeys(unprotected_nets))

        if unprotected_nets:
            findings.append(make_finding(
                detector='check_esd_coverage_gaps', rule_id='EG-001',
                category='esd_protection',
                summary=f'Connector {ref}: {len(unprotected_nets)} unprotected signal pin(s)',
                description=(
                    f'External connector {ref} ({conn.get("value", "")}) has '
                    f'{len(unprotected_nets)} unprotected signal net(s): '
                    f'{", ".join(unprotected_nets[:5])}{"..." if len(unprotected_nets) > 5 else ""}.'
                ),
                severity='info', confidence='heuristic', evidence_source='topology',
                components=[ref], nets=unprotected_nets[:10],
                recommendation='Add TVS or ESD clamp diodes on unprotected external nets.',
                fix_params={
                    'type': 'add_protection',
                    'components': [{'type': 'tvs_diode', 'nets': unprotected_nets[:5]}],
                    'basis': 'IEC 61000-4-2 requires ESD protection on accessible pins',
                },
                standard_ref='IEC 61000-4-2', impact='ESD damage on unprotected pins',

                source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'EG-001', True, None, len(connectors), findings)
    return findings


def _multi_unit(c: dict, units_by_ref: dict) -> bool:
    """Whether *c* is a unit of a multi-unit part. KiCad's netlist merges every symbol of one
    reference only for multi-unit library symbols; a placed unit above 1 is the sign of one
    (the output carries no unit count). Unannotated references stay one part per symbol."""
    ref = c.get('reference') or ''
    if not ref or ref.endswith('?'):
        return False
    return any((u.get('unit') or 1) != 1 for u in units_by_ref.get(ref, ()))


def _package_key(c: dict, units_by_ref: dict) -> tuple:
    if _multi_unit(c, units_by_ref):
        return ('ref', c['reference'])
    return ('symbol', c.get('instance_path') or c.get('uuid') or str(id(c)))


def _package_keys(components, units_by_ref: dict) -> set:
    """One key per package: the units of a multi-unit part share one; every other symbol is
    its own package, even when it shares a reference with another."""
    return {_package_key(c, units_by_ref) for c in components}


# ---------------------------------------------------------------------------
# DA-001: Decoupling strategy adequacy
# ---------------------------------------------------------------------------

def check_decoupling_adequacy(schematic: dict, pcb: dict | None, recorder=None) -> list[dict]:
    """DA-001: Per-IC decoupling assessment — count, value, and placement."""
    findings: list[dict] = []
    rails = [f for f in schematic.get('findings', [])
             if f.get('detector') == 'detect_decoupling']
    if not rails:
        _record(recorder, 'DA-001', False, 'no decoupling detector findings in schematic analysis', 0, findings)
        return findings

    # A DNP or excluded-from-board IC is not fitted, so it needs no decoupling.
    ics = [c for c in schematic.get('components', [])
           if c.get('type') == 'ic' and not c.get('dnp') and c.get('on_board') is not False]
    by_ref = _units_by_ref(schematic)
    for rail in rails:
        rail_name = rail.get('rail', '')
        caps = rail.get('capacitors') or []
        ic_count = len(_package_keys(
            [c for c in ics if rail_name in set((c.get('pin_nets') or {}).values())], by_ref))
        if ic_count == 0:
            continue
        cap_count = len(caps)
        if cap_count < ic_count:
            findings.append(make_finding(
                detector='check_decoupling_adequacy', rule_id='DA-001',
                category='power_integrity',
                summary=f'Rail {rail_name}: {cap_count} caps for {ic_count} ICs',
                description=(
                    f'Power rail {rail_name} has {cap_count} decoupling cap(s) for '
                    f'{ic_count} IC(s). Best practice: at least one 100nF per IC.'
                ),
                severity='warning' if cap_count == 0 else 'info',
                confidence='heuristic', evidence_source='topology',
                nets=[rail_name],
                recommendation=f'Add {ic_count - cap_count} more 100nF caps on {rail_name}.',
                fix_params={
                    'type': 'add_component',
                    'components': [{'type': 'capacitor', 'value': '100n',
                                    'net_from': rail_name, 'net_to': 'GND'}] * min(ic_count - cap_count, 5),
                    'basis': 'One 100nF per IC power pin pair minimum',
                },
                impact='Increased power supply noise and EMI',

                source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'DA-001', True, None, len(rails), findings)
    return findings


# ---------------------------------------------------------------------------
# XV-001..004: Schematic/PCB cross-validation
# ---------------------------------------------------------------------------

def _xv_ref(ref) -> bool:
    return isinstance(ref, str) and bool(ref) and not ref.startswith('#')


def _units_by_ref(schematic: dict) -> dict[str, list[dict]]:
    units: dict[str, list[dict]] = {}
    for c in schematic.get('components', []):
        ref = c.get('reference', '')
        if _xv_ref(ref):
            units.setdefault(ref, []).append(c)
    return units


def _legacy_schematic(schematic: dict) -> bool:
    """True for analyzer output read from a legacy .sch (schematic/presentation.py)."""
    return schematic.get('kicad_version') == '5 (legacy)'


def _package_fields(units: list[dict], legacy: bool = False) -> dict[str, str]:
    """Value, Footprint and MPN of one reference, merged across its units as KiCad's
    netlist merges them (kicad_core.fields.merge_unit_fields). In a legacy .sch a `~`
    Value or Footprint is unassigned (KiCad 4/5 assigned footprints outside the schematic)."""
    def fields(c):
        out = {name: c.get(key) for name, key in (('Value', 'value'), ('Footprint', 'footprint'))
               if isinstance(c.get(key), str) and not (legacy and c.get(key) == '~')}
        mpn = c.get('mpn')
        if isinstance(mpn, str) and mpn.strip():
            out['MPN'] = mpn
        return out
    merged = merge_unit_fields((c.get('unit') or 1, fields(c)) for c in units)
    return {'value': merged.get('Value', ''), 'footprint': merged.get('Footprint', ''),
            'mpn': merged.get('MPN', '')}


def _pair_fields(schematic: dict, pairs) -> list[tuple[str, dict, dict]]:
    """(reference, footprint, merged fields of the paired part) per pair. A footprint paired by
    path compares with its own symbol (with the other units of a multi-unit part); one paired
    by reference compares with every symbol of that reference."""
    units = _units_by_ref(schematic)
    legacy = _legacy_schematic(schematic)
    by_path = {}
    for c in schematic.get('components', []):
        path = c.get('instance_path')
        if _xv_ref(c.get('reference', '')) and isinstance(path, str) and path:
            by_path.setdefault(path.lower(), c)
    cache: dict = {}
    out = []
    for ref, fp in pairs:
        path = fp.get('sch_path')
        c = by_path.get(path.lower()) if isinstance(path, str) and path else None
        if c is not None and not _multi_unit(c, units):
            key, members = ('symbol', id(c)), [c]
        else:
            key, members = ('ref', ref), units[ref]
        if key not in cache:
            cache[key] = _package_fields(members, legacy)
        out.append((ref, fp, cache[key]))
    return out


def _fpid_name(fpid: str) -> str:
    return fpid.partition(':')[2] if ':' in fpid else fpid


def _fpid_equivalent(board_fpid: str, sch_fpid: str) -> bool:
    """KiCad's fpidsEquivalent: a schematic footprint without a library nickname matches
    on the footprint name alone; otherwise library and name must both be equal."""
    if ':' not in sch_fpid:
        return _fpid_name(board_fpid) == sch_fpid
    return board_fpid == sch_fpid


def check_cross_validation(schematic: dict, pcb: dict | None, recorder=None) -> list[dict]:
    """XV-001..003: references, values and footprints of each schematic part and its PCB
    footprint, paired by schematic path (kicad_core.pairing.pair_by_path)."""
    findings: list[dict] = []
    if not pcb:
        _record(recorder, 'XV-001..003', False, 'no PCB data provided', 0, findings)
        return findings

    pairs, in_sch_not_pcb, in_pcb_not_sch = pair_by_path(schematic, pcb)
    sch_refs = set(_units_by_ref(schematic))
    pcb_refs = {fp.get('reference', '') for fp in pcb.get('footprints', [])
                if _xv_ref(fp.get('reference', ''))}

    # XV-001: Components in schematic but not PCB
    real_missing = {r for r in in_sch_not_pcb if not r.startswith(('TP', 'MH', 'NT', 'FID'))}
    if real_missing:
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-001', category='design_sync',
            summary=f'{len(real_missing)} component(s) in schematic but not PCB',
            description=f'Missing from PCB: {", ".join(sorted(real_missing)[:20])}{"..." if len(real_missing) > 20 else ""}.',
            severity='warning', confidence='deterministic', evidence_source='topology',
            components=sorted(real_missing)[:20],
            recommendation='Update PCB from schematic (Tools > Update PCB from Schematic).',
            impact='Missing components on manufactured board',
        
            source=ANALYZER_SOURCE, schema_era="v3.0",))

    # XV-001: Components in PCB but not schematic
    extra = {r for r in in_pcb_not_sch if not r.startswith(('TP', 'MH', 'NT', 'FID', 'H', 'G'))}
    unlinked = extra & sch_refs
    real_extra = extra - unlinked
    if real_extra:
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-001', category='design_sync',
            summary=f'{len(real_extra)} component(s) in PCB but not schematic',
            description=f'Extra in PCB: {", ".join(sorted(real_extra)[:20])}{"..." if len(real_extra) > 20 else ""}.',
            severity='info', confidence='deterministic', evidence_source='topology',
            components=sorted(real_extra)[:20],
            recommendation='Verify these are intentional (mounting holes, test points, fiducials).',
        
            source=ANALYZER_SOURCE, schema_era="v3.0",))
    if unlinked:
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-001', category='design_sync',
            summary=f'{len(unlinked)} footprint(s) not linked to any schematic symbol',
            description=(f'Not linked to a symbol (each reference is used by a different symbol): '
                         f'{", ".join(sorted(unlinked)[:20])}{"..." if len(unlinked) > 20 else ""}.'),
            severity='info', confidence='deterministic', evidence_source='topology',
            components=sorted(unlinked)[:20],
            recommendation='Update PCB from schematic; KiCad replaces or removes footprints its symbols do not own.',
            source=ANALYZER_SOURCE, schema_era="v3.0", reason='unlinked_footprint'))

    # XV-001: a footprint paired by path carries another reference (annotation not synced)
    renamed = sorted({(ref, fp['reference']) for ref, fp in pairs if fp['reference'] != ref})
    if renamed:
        refs = sorted({ref for ref, _ in renamed})
        listed = ', '.join(f'{ref} (PCB {pcb_ref})' for ref, pcb_ref in renamed[:20])
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-001', category='design_sync',
            summary=f'{len(refs)} component(s) with a different reference on the PCB',
            description=(f'Footprints placed for these symbols carry another reference: {listed}'
                         f'{"..." if len(renamed) > 20 else ""}.'),
            severity='warning', confidence='deterministic', evidence_source='topology',
            components=refs[:20],
            recommendation='Update PCB from schematic (or back-annotate) so both use the same references.',
            impact='Assembly files and the schematic name different parts',
            source=ANALYZER_SOURCE, schema_era="v3.0", reason='reference_mismatch'))

    checked = _pair_fields(schematic, pairs)

    # Copies of a footprint, or one reference on several symbols, report one difference once.
    reported = set()

    # XV-002: Value consistency
    for ref, pcb_fp, fields in checked:
        sch_val = fields['value']
        pcb_val = pcb_fp.get('value', '')
        # Skip cross-check if either value is malformed (not a string).
        # Parser edge case in analyze_pcb.py footprint parsing can yield a list.
        if not isinstance(sch_val, str) or not isinstance(pcb_val, str):
            continue
        if sch_val and pcb_val and sch_val != pcb_val:
            if sch_val.replace(' ', '') == pcb_val.replace(' ', ''):
                continue
            if ('XV-002', ref, sch_val, pcb_val) in reported:
                continue
            reported.add(('XV-002', ref, sch_val, pcb_val))
            pcb_footprint = pcb_fp.get('library') or pcb_fp.get('footprint') or ''
            if pcb_val in (pcb_footprint, _fpid_name(pcb_footprint)):
                summary = f'{ref}: value never synchronised to the PCB — "{sch_val}" vs footprint name "{pcb_val}"'
            else:
                summary = f'{ref}: value mismatch — "{sch_val}" vs "{pcb_val}"'
            findings.append(make_finding(
                detector='check_cross_validation', rule_id='XV-002', category='design_sync',
                summary=summary,
                description=f'{ref} has "{sch_val}" in schematic but "{pcb_val}" in PCB.',
                severity='warning', confidence='deterministic', evidence_source='topology',
                components=[ref],
                recommendation='Sync PCB with schematic to resolve value differences.',
                impact='Wrong component may be placed during assembly',

                source=ANALYZER_SOURCE, schema_era="v3.0",))

    # XV-003: Footprint consistency (Update PCB replaces a footprint whose FPID differs)
    relinked = []
    for ref, pcb_fp, fields in checked:
        sch_fp = fields['footprint']
        board_fp = pcb_fp.get('library') or pcb_fp.get('footprint') or ''
        if not isinstance(board_fp, str) or not sch_fp or not board_fp:
            continue
        if _fpid_equivalent(board_fp, sch_fp) or ('XV-003', ref, sch_fp, board_fp) in reported:
            continue
        reported.add(('XV-003', ref, sch_fp, board_fp))
        if _fpid_name(board_fp) == _fpid_name(sch_fp):
            relinked.append((ref, sch_fp, board_fp))
            continue
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-003', category='design_sync',
            summary=f'{ref}: footprint mismatch — "{sch_fp}" vs "{board_fp}"',
            description=(f'{ref} is assigned "{sch_fp}" in the schematic but the PCB carries '
                         f'"{board_fp}"; Update PCB from schematic would replace it.'),
            severity='warning', confidence='deterministic', evidence_source='topology',
            components=[ref],
            recommendation='Update PCB from schematic, or assign the PCB footprint to the symbol.',
            impact='Wrong land pattern on the manufactured board',
            source=ANALYZER_SOURCE, schema_era="v3.0",))
    if relinked:
        refs = sorted({ref for ref, _, _ in relinked})
        listed = ', '.join(f'{ref} ("{s}" vs "{b}")' for ref, s, b in relinked[:20])
        findings.append(make_finding(
            detector='check_cross_validation', rule_id='XV-003', category='design_sync',
            summary=f'{len(refs)} footprint(s) differ from the schematic only in the library name',
            description=f'Same footprint name, different library: {listed}{"..." if len(relinked) > 20 else ""}.',
            severity='info', confidence='deterministic', evidence_source='topology',
            components=refs[:20],
            recommendation='Update PCB from schematic to link these footprints to the schematic\'s libraries.',
            source=ANALYZER_SOURCE, schema_era="v3.0",))

    _record(recorder, 'XV-001..003', True, None, len(sch_refs | pcb_refs), findings)
    return findings


def check_mpn_parity(schematic: dict, pcb: dict | None, recorder=None, notes=None) -> list[dict]:
    """XV-004: a footprint's MPN differs from its symbol's (both non-blank; Update PCB
    copies symbol fields to the footprint exactly). With a *notes* list, a line counting the
    pairs not compared is appended to it."""
    findings: list[dict] = []
    if not pcb:
        _record(recorder, 'XV-004', False, 'no PCB data provided', 0, findings)
        return findings
    pairs, _, _ = pair_by_path(schematic, pcb)
    compared = 0
    skipped = 0
    reported = set()
    for ref, pcb_fp, fields in _pair_fields(schematic, pairs):
        sch_mpn = fields['mpn'].strip()
        pcb_mpn = pcb_fp.get('mpn')
        pcb_mpn = pcb_mpn.strip() if isinstance(pcb_mpn, str) else ''
        if not sch_mpn or not pcb_mpn:
            skipped += 1
            continue
        compared += 1
        if sch_mpn == pcb_mpn or (ref, sch_mpn, pcb_mpn) in reported:
            continue
        reported.add((ref, sch_mpn, pcb_mpn))
        findings.append(make_finding(
            detector='check_mpn_parity', rule_id='XV-004', category='design_sync',
            summary=f'{ref}: MPN mismatch — "{sch_mpn}" vs "{pcb_mpn}"',
            description=f'{ref} has MPN "{sch_mpn}" in the schematic but "{pcb_mpn}" on the PCB.',
            severity='warning', confidence='deterministic', evidence_source='topology',
            components=[ref],
            recommendation='Update PCB from schematic so the footprint fields match the symbol.',
            impact='Assembly may source a different part than the schematic specifies',
            source=ANALYZER_SOURCE, schema_era="v3.0",))
    if skipped and notes is not None:
        notes.append(f'XV-004: {skipped} paired part(s) not compared (MPN blank on the schematic or the PCB)')
    _record(recorder, 'XV-004', True, None, compared, findings)
    return findings


# ---------------------------------------------------------------------------
# NR-001: Critical net routing near board edges
# ---------------------------------------------------------------------------

_EDGE_DISTANCE_ERROR_MM = 1.0
_EDGE_DISTANCE_WARN_MM = 2.0


def _point_to_outline_min_distance(px, py, edges):
    """Minimum distance from a point to the board outline edges.

    Mirrors emc_rules._point_to_edges_min_distance:
    a 'rect' edge is two opposite corners of the outline rectangle, not a
    diagonal line, so it's expanded to its 4 sides. 'circle'/'polygon'/
    'curve' edges are skipped explicitly rather than falling through to a
    generic branch that would read their (nonexistent) 'start'/'end' keys
    via .get() defaults and silently measure against a bogus (0,0)-origin
    segment.
    """
    min_dist = float('inf')
    for edge in edges:
        etype = edge.get('type', 'line')
        if etype == 'rect':
            start = edge.get('start', [0, 0])
            end = edge.get('end', [0, 0])
            x1, y1 = start[0], start[1]
            x2, y2 = end[0], end[1]
            d = min(
                _point_to_segment_distance(px, py, x1, y1, x2, y1),
                _point_to_segment_distance(px, py, x2, y1, x2, y2),
                _point_to_segment_distance(px, py, x2, y2, x1, y2),
                _point_to_segment_distance(px, py, x1, y2, x1, y1),
            )
        elif etype == 'line':
            start = edge.get('start', [0, 0])
            end = edge.get('end', [0, 0])
            d = _point_to_segment_distance(px, py, start[0], start[1], end[0], end[1])
        elif etype == 'arc':
            start = edge.get('start', [0, 0])
            end = edge.get('end', [0, 0])
            mid = edge.get('mid')
            if mid:
                d = min(
                    _point_to_segment_distance(px, py, start[0], start[1], mid[0], mid[1]),
                    _point_to_segment_distance(px, py, mid[0], mid[1], end[0], end[1]),
                )
            else:
                d = _point_to_segment_distance(px, py, start[0], start[1], end[0], end[1])
        else:
            # circle / polygon / curve: not yet implemented for NR-001.
            continue
        if d < min_dist:
            min_dist = d
    return min_dist


def check_critical_net_routing(schematic, pcb, recorder=None):
    """NR-001: Flag high-speed/clock signal traces routed near board edges."""
    findings = []
    if not pcb:
        _record(recorder, 'NR-001', False, 'no PCB data provided', 0, findings)
        return findings
    segments = (pcb.get('tracks') or {}).get('segments') or []
    if not segments:
        _record(recorder, 'NR-001', False, 'no PCB track segments present', 0, findings)
        return findings
    outline = pcb.get('board_outline') or {}
    outline_edges = outline.get('edges', [])
    if not outline_edges:
        _record(recorder, 'NR-001', False, 'no board outline edge geometry present', 0, findings)
        return findings
    net_id_map = _build_net_id_map(pcb)
    flagged_nets = {}
    for seg in segments:
        net_id = seg.get('net', 0)
        net_name = net_id_map.get(net_id, '') if isinstance(net_id, int) else str(net_id)
        if not net_name or _is_power_net(net_name) or is_cross_analysis_ground_name(net_name):
            continue
        classification = _get_net_classification(net_name, schematic)
        if not classification or classification.get('type') not in _HIGH_SPEED_TYPES:
            continue
        mx = (seg.get('x1', 0) + seg.get('x2', 0)) / 2
        my = (seg.get('y1', 0) + seg.get('y2', 0)) / 2
        min_dist = _point_to_outline_min_distance(mx, my, outline_edges)
        if min_dist < _EDGE_DISTANCE_WARN_MM:
            if net_name not in flagged_nets or min_dist < flagged_nets[net_name]:
                flagged_nets[net_name] = min_dist
    for net_name, dist in flagged_nets.items():
        classification = _get_net_classification(net_name, schematic)
        net_type = classification.get('type', 'signal') if classification else 'signal'
        severity = 'error' if dist < _EDGE_DISTANCE_ERROR_MM else 'warning'
        findings.append(make_finding(
            detector='check_critical_net_routing', rule_id='NR-001',
            category='signal_routing',
            summary=f'{net_type} net {net_name}: {dist:.1f}mm from board edge',
            description=f'High-speed {net_type} net {net_name} is routed {dist:.1f}mm from the board edge. Signals near edges radiate more effectively.',
            severity=severity, confidence='deterministic', evidence_source='topology',
            nets=[net_name],
            recommendation=f'Re-route {net_name} at least {_EDGE_DISTANCE_WARN_MM}mm from board edges.',
            impact='Increased EMI radiation and susceptibility',

            source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'NR-001', True, None, len(segments), findings)
    return findings


# ---------------------------------------------------------------------------
# RP-002: Enhanced return path validation
# ---------------------------------------------------------------------------

def check_return_path_enhanced(schematic, pcb, recorder=None):
    """RP-002: Check for reference plane gaps under classified signal nets."""
    findings = []
    if not pcb:
        _record(recorder, 'RP-002', False, 'no PCB data provided', 0, findings)
        return findings
    segments = (pcb.get('tracks') or {}).get('segments') or []
    if not segments:
        _record(recorder, 'RP-002', False, 'no PCB track segments present', 0, findings)
        return findings
    conn_graph = pcb.get('connectivity_graph') or {}
    net_id_map = _build_net_id_map(pcb)
    rpc_flagged = _flagged_return_path_entries(pcb, threshold_pct=95.0)
    # [] means coverage was measured and no net is short; an absent key means
    # zone fills were unavailable, so no crossing can be confirmed.
    has_rpc_data = isinstance(pcb.get('return_path_continuity'), list)
    plane_gaps = []
    for net_name, graph in conn_graph.items():
        if not (is_cross_analysis_ground_name(net_name) or _is_power_net(net_name)):
            continue
        for gap in graph.get('gaps', []):
            plane_gaps.append({**gap, 'net': net_name})
    if not has_rpc_data:
        _record(recorder, 'RP-002', False,
                'no return-path coverage in PCB analysis (zone fills unavailable)', 0, findings)
        return findings
    if not plane_gaps:
        for entry in pcb['return_path_continuity']:
            coverage = entry.get('reference_plane_coverage_pct', 100)
            if coverage < 90:
                net_name = entry.get('net', '')
                classification = _get_net_classification(net_name, schematic)
                if classification and classification.get('type') in _HIGH_SPEED_TYPES:
                    findings.append(make_finding(
                        detector='check_return_path_enhanced', rule_id='RP-002',
                        category='return_path',
                        summary=f'Net {net_name}: {coverage:.0f}% reference plane coverage',
                        description=f'High-speed net {net_name} has only {coverage:.0f}% reference plane coverage.',
                        severity='warning', confidence='heuristic', evidence_source='topology',
                        nets=[net_name],
                        recommendation='Re-route signal to avoid reference plane gaps.',
                        impact='Increased loop area and EMI',

                        source=ANALYZER_SOURCE, schema_era="v3.0",))
        _record(recorder, 'RP-002', True, None, len(segments), findings)
        return findings
    flagged = set()
    for seg in segments:
        net_id = seg.get('net', 0)
        net_name = net_id_map.get(net_id, '') if isinstance(net_id, int) else str(net_id)
        if not net_name or _is_power_net(net_name) or is_cross_analysis_ground_name(net_name):
            continue
        if net_name in flagged:
            continue
        # A gap is the rectangle between two islands' bounding boxes, so a
        # crossing is reported only where measured plane coverage is short.
        if net_name not in rpc_flagged:
            continue
        classification = _get_net_classification(net_name, schematic)
        if not classification:
            continue
        sx1, sy1 = seg.get('x1', 0), seg.get('y1', 0)
        sx2, sy2 = seg.get('x2', 0), seg.get('y2', 0)
        seg_min_x, seg_max_x = min(sx1, sx2), max(sx1, sx2)
        seg_min_y, seg_max_y = min(sy1, sy2), max(sy1, sy2)
        for gap in plane_gaps:
            bbox = gap.get('bbox', [0, 0, 0, 0])
            if (seg_max_x >= bbox[0] and seg_min_x <= bbox[2] and
                    seg_max_y >= bbox[1] and seg_min_y <= bbox[3]):
                net_type = classification.get('type', 'signal')
                severity = 'error' if net_type in _HIGH_SPEED_TYPES else 'warning'
                findings.append(make_finding(
                    detector='check_return_path_enhanced', rule_id='RP-002',
                    category='return_path',
                    summary=f'{net_type} net {net_name} crosses {gap["net"]} plane gap',
                    description=f'{net_type} signal {net_name} crosses a gap in {gap["net"]} plane on layer {gap.get("layer", "?")}.',
                    severity=severity, confidence='heuristic', evidence_source='topology',
                    nets=[net_name, gap['net']],
                    recommendation=f'Re-route {net_name} to avoid the {gap["net"]} plane gap, or bridge with a stitching capacitor.',
                    impact='Increased EMI from enlarged return path loop',

                    source=ANALYZER_SOURCE, schema_era="v3.0",))
                flagged.add(net_name)
                break
    _record(recorder, 'RP-002', True, None, len(segments), findings)
    return findings


# ---------------------------------------------------------------------------
# TW-001: Trace width validation
# ---------------------------------------------------------------------------

def check_trace_width_power(schematic, pcb, recorder=None):
    """TW-001: Check all power net trace widths against IPC-2152."""
    findings = []
    if not pcb or not schematic:
        _record(recorder, 'TW-001', False, 'no PCB or schematic data provided', 0, findings)
        return findings
    segments = (pcb.get('tracks') or {}).get('segments') or []
    if not segments:
        _record(recorder, 'TW-001', False, 'no PCB track segments present', 0, findings)
        return findings
    net_id_map = _build_net_id_map(pcb)
    regulators = [f for f in schematic.get('findings', [])
                  if f.get('detector') == 'detect_power_regulators']
    net_current = {}
    for reg in regulators:
        output_rail = reg.get('output_rail', '')
        iout = _reg_iout(reg)
        if output_rail and iout > 0:
            net_current[output_rail] = max(net_current.get(output_rail, 0), iout)
        input_rail = reg.get('input_rail', '')
        iin = _reg_iin(reg)
        if input_rail and iin > 0:
            net_current[input_rail] = net_current.get(input_rail, 0) + iin
    if not net_current:
        _record(recorder, 'TW-001', False, 'no power regulator current estimates in schematic analysis', 0, findings)
        return findings
    net_min_width = {}
    for seg in segments:
        net_id = seg.get('net', 0)
        net_name = net_id_map.get(net_id, '') if isinstance(net_id, int) else str(net_id)
        w = seg.get('width', 0) or 0
        if net_name in net_current and w > 0:
            if net_name not in net_min_width or w < net_min_width[net_name]:
                net_min_width[net_name] = w
    for net_name, current in net_current.items():
        trace_w = net_min_width.get(net_name)
        if trace_w is None:
            continue
        min_w = _min_trace_width_for_current(current)
        if trace_w < min_w * 0.8:
            findings.append(make_finding(
                detector='check_trace_width_power', rule_id='TW-001',
                category='current_capacity',
                summary=f'Power net {net_name}: trace {trace_w:.2f}mm too narrow for ~{current:.1f}A (est.)',
                description=f'Power net {net_name} carries ~{current:.1f}A (estimated from regulator output capacitance) but narrowest trace is {trace_w:.2f}mm. IPC-2152 recommends >= {min_w:.2f}mm.',
                severity='warning', confidence='heuristic', evidence_source='topology',
                nets=[net_name],
                recommendation=f'Widen {net_name} traces to >= {min_w:.1f}mm or use copper pour.',
                fix_params={'type': 'resistor_value_change', 'change': f'trace width -> {min_w:.1f}mm', 'basis': f'IPC-2152: {current:.1f}A'},
                standard_ref='IPC-2152', impact='Trace overheating and voltage drop',

                source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'TW-001', True, None, len(net_current), findings)
    return findings


# ---------------------------------------------------------------------------
# PS-002: Plane split detection
# ---------------------------------------------------------------------------

def check_plane_splits(schematic, pcb, recorder=None):
    """PS-002: Detect ground/power plane splits and signal traces crossing them."""
    findings = []
    if not pcb:
        _record(recorder, 'PS-002', False, 'no PCB data provided', 0, findings)
        return findings
    conn_graph = pcb.get('connectivity_graph') or {}
    if not conn_graph:
        _record(recorder, 'PS-002', False, 'no connectivity_graph in PCB analysis (--full required)', 0, findings)
        return findings
    segments = (pcb.get('tracks') or {}).get('segments') or []
    net_id_map = _build_net_id_map(pcb)
    rpc_flagged = _flagged_return_path_entries(pcb, threshold_pct=95.0)
    # A net without a copper zone has no plane to split: its islands are
    # unrouted connections, not plane gaps.
    zone_nets = {z.get('net_name') for z in pcb.get('zones') or []}
    for plane_net, graph in conn_graph.items():
        if not (is_cross_analysis_ground_name(plane_net) or _is_power_net(plane_net)):
            continue
        if plane_net not in zone_nets:
            continue
        if graph.get('islands', 1) <= 1:
            continue
        island_sizes = _island_size_map(graph)
        significant_islands = [size for size in island_sizes.values() if size >= 2]
        is_intentional = any(plane_net.upper().startswith(p) for p in ('AGND', 'DGND', 'PGND', 'GNDA', 'GNDD'))
        gaps = graph.get('gaps', [])
        if not gaps:
            continue
        crossing_signals = []
        for seg in segments:
            seg_net_id = seg.get('net', 0)
            seg_net = net_id_map.get(seg_net_id, '') if isinstance(seg_net_id, int) else str(seg_net_id)
            if not seg_net or _is_power_net(seg_net) or is_cross_analysis_ground_name(seg_net):
                continue
            sx1, sy1 = seg.get('x1', 0), seg.get('y1', 0)
            sx2, sy2 = seg.get('x2', 0), seg.get('y2', 0)
            for gap in gaps:
                bbox = gap.get('bbox', [0, 0, 0, 0])
                if (max(sx1, sx2) >= bbox[0] and min(sx1, sx2) <= bbox[2] and
                        max(sy1, sy2) >= bbox[1] and min(sy1, sy2) <= bbox[3]):
                    if seg_net not in crossing_signals:
                        crossing_signals.append(seg_net)
                    break
        crossing_signals_rpc = [s for s in crossing_signals if s in rpc_flagged]
        if len(significant_islands) <= 1 and not crossing_signals_rpc:
            continue
        if is_intentional:
            severity = 'info'
        elif crossing_signals_rpc:
            has_hs = any(_get_net_classification(s, schematic) and
                         _get_net_classification(s, schematic).get('type') in _HIGH_SPEED_TYPES
                         for s in crossing_signals_rpc)
            severity = 'error' if has_hs else 'warning'
        else:
            severity = 'info'
        desc_signals = f' Signals crossing: {", ".join(crossing_signals_rpc[:5])}.' if crossing_signals_rpc else ''
        findings.append(make_finding(
            detector='check_plane_splits', rule_id='PS-002',
            category='plane_integrity',
            summary=f'{plane_net} plane split: {graph["islands"]} islands{", " + str(len(crossing_signals_rpc)) + " signals crossing" if crossing_signals_rpc else ""}',
            description=f'{plane_net} plane has {graph["islands"]} disconnected islands.{desc_signals}',
            # The island count is measured; a crossing is a track overlapping
            # the rectangle between two islands' bounding boxes.
            severity=severity, confidence='heuristic' if crossing_signals_rpc else 'deterministic',
            evidence_source='topology',
            nets=[plane_net] + crossing_signals_rpc[:5],
            recommendation=(
                'Bridge the plane gap with copper pour or stitching vias. '
                'If zones were modified after the last fill, run KiCad '
                'Edit → Fill All Zones (B) and re-run the analyzer first — '
                'stale zone fills are a common cause of apparent plane splits.'
            ),
            impact='Return path discontinuity increases EMI',

            source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'PS-002', True, None, len(conn_graph), findings)
    return findings


# ---------------------------------------------------------------------------
# VS-002: Via stitching density
# ---------------------------------------------------------------------------

_SPEED_OF_LIGHT = 3e8
_EFFECTIVE_ER = 4.2


def check_via_stitching_density(schematic, pcb, recorder=None):
    """VS-002: Check ground via stitching density against frequency requirements."""
    findings = []
    if not pcb:
        _record(recorder, 'VS-002', False, 'no PCB data provided', 0, findings)
        return findings
    via_list = (pcb.get('vias') or {}).get('vias') or []
    if not via_list:
        _record(recorder, 'VS-002', False, 'no vias in PCB analysis', 0, findings)
        return findings
    net_id_map = _build_net_id_map(pcb)
    outline = pcb.get('board_outline') or {}
    bbox = outline.get('bounding_box') or {}
    board_w = bbox.get('width', 0)
    board_h = bbox.get('height', 0)
    if board_w <= 0 or board_h <= 0:
        _record(recorder, 'VS-002', False, 'board outline bounding box unavailable or zero-sized', 0, findings)
        return findings
    highest_freq = _get_highest_frequency(schematic)
    if highest_freq <= 0:
        highest_freq = 100e6
    wavelength_mm = (_SPEED_OF_LIGHT / math.sqrt(_EFFECTIVE_ER) / highest_freq) * 1000
    max_spacing_mm = wavelength_mm / 20
    board_x0 = bbox.get('x', bbox.get('min_x', 0))
    board_y0 = bbox.get('y', bbox.get('min_y', 0))
    gnd_vias = []
    for via in via_list:
        net_id = via.get('net', 0)
        net_name = net_id_map.get(net_id, '') if isinstance(net_id, int) else str(net_id)
        if is_cross_analysis_ground_name(net_name):
            gnd_vias.append((via.get('x', 0), via.get('y', 0)))
    if not gnd_vias:
        findings.append(make_finding(
            detector='check_via_stitching_density', rule_id='VS-002',
            category='via_stitching',
            summary='No ground stitching vias found',
            description='The board has no ground vias. Ground stitching vias are important for EMC.',
            severity='warning', confidence='deterministic', evidence_source='topology',
            recommendation=f'Add ground stitching vias at <= {max_spacing_mm:.0f}mm spacing.',
            impact='Poor ground plane connectivity between layers',

            source=ANALYZER_SOURCE, schema_era="v3.0",))
        _record(recorder, 'VS-002', True, None, len(via_list), findings)
        return findings
    cell_size = max_spacing_mm
    if cell_size <= 0:
        _record(recorder, 'VS-002', False, 'computed via-stitching grid cell size is zero or negative', len(via_list), findings)
        return findings
    cells_x = max(1, int(math.ceil(board_w / cell_size)))
    cells_y = max(1, int(math.ceil(board_h / cell_size)))
    cell_counts = {}
    total_cells = cells_x * cells_y
    for vx, vy in gnd_vias:
        cx = max(0, min(int((vx - board_x0) / cell_size), cells_x - 1))
        cy = max(0, min(int((vy - board_y0) / cell_size), cells_y - 1))
        cell_counts[(cx, cy)] = cell_counts.get((cx, cy), 0) + 1
    empty_cells = total_cells - len(cell_counts)
    empty_pct = (empty_cells / total_cells * 100) if total_cells > 0 else 0
    if empty_pct > 30:
        findings.append(make_finding(
            detector='check_via_stitching_density', rule_id='VS-002',
            category='via_stitching',
            summary=f'Via stitching sparse: {empty_pct:.0f}% of board lacks ground vias',
            description=f'{empty_pct:.0f}% of board area (at {cell_size:.1f}mm grid) has no ground stitching vias. For {highest_freq/1e6:.0f}MHz, lambda/20 = {max_spacing_mm:.1f}mm.',
            severity='warning' if empty_pct > 50 else 'info',
            confidence='heuristic', evidence_source='topology',
            recommendation=f'Add ground stitching vias at <= {max_spacing_mm:.0f}mm intervals.',
            impact='Degraded ground plane connectivity at high frequencies',

            source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'VS-002', True, None, len(via_list), findings)
    return findings


# ---------------------------------------------------------------------------
# DP-005: Differential pair routing quality
# ---------------------------------------------------------------------------

_DIFF_PAIR_SUFFIXES = [
    (re.compile(r'(.+)[_]?P$'), re.compile(r'(.+)[_]?N$')),
    (re.compile(r'(.+)\+$'), re.compile(r'(.+)-$')),
    (re.compile(r'(.+)_DP$'), re.compile(r'(.+)_DN$')),
    (re.compile(r'(.+)_TXP$'), re.compile(r'(.+)_TXN$')),
    (re.compile(r'(.+)_RXP$'), re.compile(r'(.+)_RXN$')),
    (re.compile(r'(.+)DP$'), re.compile(r'(.+)DM$')),
]


def _find_diff_pairs(schematic):
    """Return pairs of net names that are explicitly marked differential.

    There is no suffix-only fallback that pairs any nets matching
    `<base>P`/`<base>N`: on gate-driver designs (INH/INL, HIN/LIN) and
    op-amp current-sense circuits (OUTP/OUTN, INP/INN) it would fire DP-005
    on every conventional naming pair. DP-005 only fires when
    ``schematic['net_classifications'][<net>]['differential']`` is True
    for both endpoints. Conservative loss: any genuine diff pair the
    schematic analyzer failed to classify won't get a DP-005 finding.
    But every real differential interface (USB / LVDS / Ethernet / HDMI /
    CAN / etc.) is already classified by `_build_net_classifications`, so
    the loss is small relative to the false-positive reduction.
    """
    pairs = []
    if not schematic:
        return pairs
    classifications = schematic.get('net_classifications') or {}
    diff_nets = [n for n, c in classifications.items() if c.get('differential')]
    if not diff_nets:
        return pairs
    seen = set()
    for p_pat, n_pat in _DIFF_PAIR_SUFFIXES:
        for net in diff_nets:
            if net in seen:
                continue
            m = p_pat.match(net)
            if m:
                base = m.group(1)
                for net2 in diff_nets:
                    if net2 in seen:
                        continue
                    m2 = n_pat.match(net2)
                    if m2 and m2.group(1) == base:
                        pairs.append((net, net2))
                        seen.add(net)
                        seen.add(net2)
                        break
    return pairs


def check_diff_pair_quality(schematic, pcb, recorder=None):
    """DP-005: Check differential pair routing quality."""
    findings = []
    if not pcb:
        _record(recorder, 'DP-005', False, 'no PCB data provided', 0, findings)
        return findings
    segments = (pcb.get('tracks') or {}).get('segments') or []
    if not segments:
        _record(recorder, 'DP-005', False, 'no PCB track segments present', 0, findings)
        return findings
    pairs = _find_diff_pairs(schematic)
    if not pairs:
        _record(recorder, 'DP-005', False, 'no differential pairs classified in schematic net_classifications', 0, findings)
        return findings
    # net_lengths counts arcs as well as straight segments
    net_stats = {}
    for entry in pcb.get('net_lengths') or []:
        layers = entry.get('layers') or {}
        if entry.get('net') and layers:
            net_stats[entry['net']] = {'length_mm': entry.get('total_length_mm', 0) or 0,
                                       'via_count': entry.get('via_count', 0) or 0,
                                       'layers': set(layers)}
    for p_net, n_net in pairs:
        p_stats = net_stats.get(p_net)
        n_stats = net_stats.get(n_net)
        if not p_stats or not n_stats:
            continue
        issues = []
        p_vias = p_stats.get('via_count', 0)
        n_vias = n_stats.get('via_count', 0)
        if p_vias != n_vias:
            issues.append(f'via asymmetry ({p_vias} vs {n_vias})')
        p_layers = len(p_stats.get('layers', set()))
        n_layers = len(n_stats.get('layers', set()))
        if p_layers != n_layers:
            issues.append(f'layer transition asymmetry ({p_layers} vs {n_layers} layers)')
        p_len = p_stats.get('length_mm', 0)
        n_len = n_stats.get('length_mm', 0)
        avg_len = (p_len + n_len) / 2
        if avg_len > 0:
            mismatch_pct = abs(p_len - n_len) / avg_len * 100
            if mismatch_pct > 5:
                issues.append(f'length mismatch {abs(p_len - n_len):.1f}mm ({mismatch_pct:.0f}%)')
        if issues:
            findings.append(make_finding(
                detector='check_diff_pair_quality', rule_id='DP-005',
                category='differential_pair',
                summary=f'Diff pair {p_net}/{n_net}: {", ".join(issues)}',
                description=f'Differential pair {p_net}/{n_net} has routing issues: {"; ".join(issues)}.',
                severity='warning', confidence='deterministic', evidence_source='topology',
                nets=[p_net, n_net],
                recommendation='Match via counts, layer transitions, and trace lengths between P and N.',
                impact='Degraded signal integrity and increased common-mode EMI',

                source=ANALYZER_SOURCE, schema_era="v3.0",))
    _record(recorder, 'DP-005', True, None, len(pairs), findings)
    return findings


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def run_all_checks(schematic: dict, pcb: dict | None, notes=None) -> tuple[list[dict], list[dict]]:
    """Run every cross-domain check in a fixed order.

    Returns (findings, checks_run) — checks_run is the manifest
    recording whether each check executed, in call order (see
    _CheckRecorder). A *notes* list collects the run's stderr notes.
    """
    findings: list[dict] = []
    recorder = _CheckRecorder()
    findings.extend(check_connector_current(schematic, pcb, recorder=recorder))
    findings.extend(check_esd_coverage_gaps(schematic, pcb, recorder=recorder))
    findings.extend(check_decoupling_adequacy(schematic, pcb, recorder=recorder))
    findings.extend(check_cross_validation(schematic, pcb, recorder=recorder))
    findings.extend(check_mpn_parity(schematic, pcb, recorder=recorder, notes=notes))
    # PCB intelligence checks
    findings.extend(check_critical_net_routing(schematic, pcb, recorder=recorder))
    findings.extend(check_return_path_enhanced(schematic, pcb, recorder=recorder))
    findings.extend(check_trace_width_power(schematic, pcb, recorder=recorder))
    findings.extend(check_plane_splits(schematic, pcb, recorder=recorder))
    findings.extend(check_via_stitching_density(schematic, pcb, recorder=recorder))
    findings.extend(check_diff_pair_quality(schematic, pcb, recorder=recorder))
    return findings, recorder.entries


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description='Cross-domain analysis — schematic + PCB combined checks')
    parser.add_argument('--schematic', '-s', default=None,
                        help='Schematic analyzer JSON. Auto-resolved from --analysis-dir current run when omitted.')
    parser.add_argument('--pcb', '-p', default=None,
                        help='PCB analyzer JSON (optional). Auto-resolved from --analysis-dir current run when omitted.')
    add_output_arg(parser, help='Output JSON file path')
    add_schema_arg(parser, help='Print output schema and exit')
    add_text_arg(parser, help='Print human-readable text report')
    parser.add_argument('--analysis-dir', default=None, help='Write into analysis cache directory')
    add_stage_audience_args(parser)
    add_only_deterministic_arg(parser)

    args = parser.parse_args(argv)
    if args.text:
        utf8_text_stdout()

    if args.schema:
        emit_schema(CrossAnalysisEnvelope)

    if args.analysis_dir and (not args.schematic or not args.pcb):
        from analysis_cache import get_current_run
        from pathlib import Path as _AutoPath
        _current = get_current_run(args.analysis_dir)
        if _current is not None:
            _run_dir, _ = _current
            if not args.schematic:
                _sch = _AutoPath(_run_dir) / "schematic.json"
                if _sch.is_file():
                    args.schematic = str(_sch)
            if not args.pcb:
                _pcb = _AutoPath(_run_dir) / "pcb.json"
                if _pcb.is_file():
                    args.pcb = str(_pcb)

    if not args.schematic:
        parser.error('--schematic is required (or pass --analysis-dir with a current run containing schematic.json)')

    def _load_analyzer_json(flag, path, writer, expected):
        # A first-time user naturally passes the project folder or the
        # .kicad_sch / .kicad_pcb itself; give a usage error, not a traceback.
        if not os.path.isfile(path):
            what = 'a directory' if os.path.isdir(path) else 'not found'
            parser.error(f'{flag} {path}: {what}; expected the JSON file '
                         f'{writer} writes (--output)')
        try:
            with open(path, 'r', encoding="utf-8") as f:
                data = json_load(f)
        except json.JSONDecodeError as e:
            parser.error(f'{flag} {path}: not JSON ({e}); expected the JSON '
                         f'file {writer} writes (--output)')
        type_error = envelope_type_error(flag, path, data, expected, writer)
        if type_error:
            parser.error(type_error)
        return data

    t0 = time.time()

    schematic = _load_analyzer_json('--schematic', args.schematic,
                                    'analyze_schematic.py', 'schematic')

    if 'signal_analysis' in schematic and 'findings' not in schematic:
        print(f'Error: {args.schematic} uses the pre-v1.3 '
              f'signal_analysis wrapper format.\n'
              f'Re-run analyze_schematic.py to produce the current '
              f'findings[] format.', file=sys.stderr)
        return 1

    pcb = None
    if args.pcb:
        pcb = _load_analyzer_json('--pcb', args.pcb, 'analyze_pcb.py', 'pcb')

    # Build inputs provenance block.
    from pathlib import Path as _Path
    _upstream_artifacts = {
        "schematic": build_upstream_artifact(_Path(args.schematic), schematic),
    }
    _source_files = [_Path(args.schematic)]
    if pcb is not None and args.pcb:
        _upstream_artifacts["pcb"] = build_upstream_artifact(_Path(args.pcb), pcb)
        _source_files.append(_Path(args.pcb))

    # Resolve the canonical analysis_dir once.
    if args.analysis_dir:
        _analysis_dir = _Path(args.analysis_dir)
    elif args.output:
        _analysis_dir = _Path(args.output).parent
    else:
        _analysis_dir = _Path("analysis")

    # Resolve capability_mode_ref BEFORE build_inputs so inputs.run_id matches it.
    _capability_mode_ref = get_capability_mode_ref(_analysis_dir)

    inputs = build_inputs(
        source_files=_source_files,
        upstream_artifacts=_upstream_artifacts,
        run_id=_capability_mode_ref["run_id"],
    )
    compat = build_compat()

    notes: list[str] = []
    findings, checks_run = run_all_checks(schematic, pcb, notes=notes)
    for note in notes:
        print(note, file=sys.stderr)
    show_decoded_names(findings)
    elapsed = time.time() - t0

    sev_counts = {'error': 0, 'warning': 0, 'info': 0}
    for f_item in findings:
        sev = f_item.get('severity', 'info')
        sev_counts[sev] = sev_counts.get(sev, 0) + 1

    result = {
        'analyzer_type': 'cross_analysis',
        'schema_version': '1.4.0',
        'inputs': inputs,
        'compat': compat,
        'diagnostics': [],
        'elapsed_s': round(elapsed, 3),
        'summary': {'total_findings': len(findings), 'by_severity': sev_counts},
        'findings': findings,
        'assessments': [],
        'checks_run': checks_run,
        'trust_summary': compute_trust_summary(findings),
    }

    from output_filters import apply_output_filters
    apply_output_filters(result, args.stage)

    # Guarantee every finding carries a stable finding_id (Layer 2 merge keys
    # on it). Runs after filtering; before any output branch.
    assign_finding_ids(result.get("findings", []), "cross_analysis")

    # Wire capability_mode_ref. Resolved early so
    # inputs.run_id and capability_mode_ref.run_id match.
    result["capability_mode_ref"] = _capability_mode_ref

    if args.text:
        from output_filters import format_text
        print(format_text(result.get('findings', []), args.audience or 'designer', args.stage))
        return 0

    if args.output:
        atomic_write_text(args.output, json.dumps(result, indent=2), follow_symlinks=False)
        print(f'Cross-analysis: {len(findings)} findings -> {args.output}', file=sys.stderr)
    elif args.analysis_dir:
        from output_io import write_derived_output
        out_path = write_derived_output(args.analysis_dir, json.dumps(result, indent=2), analyzer='cross_analysis')
        if out_path:
            print(f'Cross-analysis: {len(findings)} findings -> {out_path}', file=sys.stderr)
    else:
        print(json.dumps(result, indent=2))

    return 0


if __name__ == '__main__':
    from kicad_core.cli import utf8_stdio
    utf8_stdio()
    sys.exit(main())
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 321kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 321kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 321kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 197kUpdated Claude CodeCodexVerifiedInstall