Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/validate.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,19 @@ rule or net class below the fab limit → P1; a board rule left at 0 → P2.
ERC/DRC violations are grouped by type: one finding per type with a count and
up to 50 refs.

### Altium projects

When every design file in the folder is Altium (`.PrjPcb`, `.SchDoc`,
`.PcbDoc`), validate runs an Altium graph instead; a folder with KiCad files
keeps the graph above. `intake.project` sends one hosted turn that runs the
server's `export_altium_netlist` and `export_altium_bom` into
`.validate-scratch/altium-intake/`, and the index is built from those JSON
files (no `kicad-cli`). The checks that read KiCad files (`sch.erc`,
`pcb.drc`, `pcb.parity`, `pcb.rules`, `pcb.connector_edge`, `pcb.models_3d`,
`release.outputs`, `release.repo`) are left out: run ERC and DRC in Altium
(the agent's `run_altium_erc` / `run_altium_drc` on Windows). The agent
reviewers run as usual and read the design with the Altium tools.

## MCP and Python

The MCP server exposes `validate(workspace?, profile?, gate?, until?, only?,
Expand Down
148 changes: 146 additions & 2 deletions src/copper_pilot_cli/validate/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

from __future__ import annotations

import json
import re
from collections.abc import Callable
import shutil
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
Expand All @@ -17,7 +19,10 @@
Severity,
)
from copper_pilot_cli.validate.design import (
ALTIUM_BOM_PARAMETERS,
SCRATCH_DIR,
DesignContext,
build_altium_index,
build_index,
iter_design_files,
load_intent,
Expand Down Expand Up @@ -56,14 +61,19 @@ class CheckOutcome:
error: str | None = None


BuiltinFn = Callable[[DesignContext, CheckSpec, dict[str, Any]], CheckOutcome]
BuiltinFn = Callable[..., Any]
# A hosted builtin's one model turn: prompt in, (reply text, error message or None) out.
AskFn = Callable[[str], Awaitable[tuple[str, str | None]]]


@dataclass(frozen=True, slots=True)
class Builtin:
fn: BuiltinFn
cacheable: bool = True
description: str = ""
# async fn(design, check, limits, snapshot=..., ask=...): reads the design through
# CopperPilot's server tools in one turn on the snapshot (Altium intake)
hosted: bool = False


def _finding(
Expand Down Expand Up @@ -101,6 +111,15 @@ def _finding(

def check_tools(design: DesignContext, check: CheckSpec, limits: dict[str, Any]) -> CheckOutcome:
del check, limits
if design.altium:
return CheckOutcome(
summary=(
"Altium project: read by CopperPilot's native Altium reader, no kicad-cli "
"needed. ERC and DRC run in Altium itself (run_altium_erc / run_altium_drc "
"on Windows), so this graph has no kicad-cli ERC, DRC, parity, rules or "
"output checks."
)
)
cli = design.kicad
if cli is None:
return CheckOutcome(
Expand Down Expand Up @@ -207,6 +226,125 @@ def check_project(design: DesignContext, check: CheckSpec, limits: dict[str, Any
)


ALTIUM_INTAKE_DIR = f"{SCRATCH_DIR}/altium-intake"
_ALTIUM_INTAKE_PROMPT = """This is the intake step of a read-only validation run, not a review.
Call exactly these two tools, then stop. Do not read or edit anything else.
1. export_altium_netlist with schematic_path="{schematic}", output_path="{netlist}" and
format="json".
2. export_altium_bom with schematic_path="{schematic}", output_path="{bom}" and
parameters={parameters}.
Reply in one short paragraph with what each tool returned (success, or its error message)."""


async def check_altium_project(
design: DesignContext,
check: CheckSpec,
limits: dict[str, Any],
*,
snapshot: Path,
ask: AskFn,
) -> CheckOutcome:
"""Index an Altium project from the server's native netlist and BOM export (the
CLI has no Altium reader): one turn writes both as JSON into the scratch folder."""
del limits
schematic = design.context.schematic_path
if not schematic:
return CheckOutcome(
findings=[
_finding(
Severity.P0,
"No Altium schematic found",
"validate needs a .SchDoc to read the netlist.",
action="Point validate at the folder that contains the Altium project.",
)
],
summary="no schematic",
)
netlist_rel = f"{ALTIUM_INTAKE_DIR}/netlist.json"
bom_rel = f"{ALTIUM_INTAKE_DIR}/bom.json"
reply, error = await ask(
_ALTIUM_INTAKE_PROMPT.format(
schematic=schematic,
netlist=netlist_rel,
bom=bom_rel,
parameters=json.dumps(list(ALTIUM_BOM_PARAMETERS)),
)
)
if error:
return CheckOutcome(error=f"Altium intake turn failed: {error}")
artifacts = design.artifacts_dir(check.id)
documents: dict[str, Any] = {}
for name, rel in (("netlist", netlist_rel), ("bom", bom_rel)):
path = snapshot / rel
if not path.is_file():
continue
shutil.copyfile(path, artifacts / path.name)
try:
documents[name] = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
return CheckOutcome(error=f"{rel} is not valid JSON: {exc}")
netlist = documents.get("netlist")
if not isinstance(netlist, dict) or not isinstance(netlist.get("components"), list):
return CheckOutcome(
error="the native Altium netlist export did not run; the turn said: "
+ (reply.strip()[:400] or "nothing")
)
bom = documents.get("bom") if isinstance(documents.get("bom"), dict) else None
design.index = build_altium_index(netlist, bom)
design.intent = load_intent(design.workspace)
findings: list[Finding] = []
if bom is None:
findings.append(
_finding(
Severity.P2,
"The Altium BOM export did not run",
"Part values and parameters (MPN, LCSC) come from the BOM export.",
action="Rerun validate; if it repeats, export the BOM with export_altium_bom.",
)
)
unannotated = [str(ref) for ref in (bom or {}).get("unannotated") or []]
if unannotated:
findings.append(
_finding(
Severity.P1,
f"{len(unannotated)} part(s) are not annotated",
f"Unannotated parts ({', '.join(unannotated[:20])}) are left out of the "
"netlist and BOM.",
rule="Every part needs a unique designator",
action="Annotate the schematic in Altium (Tools > Annotation).",
)
)
conflicts = netlist.get("name_conflicts") or {}
if conflicts:
named = [f"{key}: {', '.join(map(str, value))}" for key, value in conflicts.items()]
findings.append(
_finding(
Severity.P2,
f"{len(conflicts)} net(s) carry more than one name",
"Altium keeps one name by its net-naming rules: " + "; ".join(named[:10]),
rule="One name per net",
action="Remove the extra net labels or power ports so each net has one name.",
)
)
if not design.index.parts:
findings.append(
_finding(
Severity.P1,
"The netlist has no components",
"The Altium schematic exported an empty component list.",
action="Check that the project lists its schematic sheets.",
)
)
summary = design.index.summary()
return CheckOutcome(
findings=findings,
summary=(
f"{summary['parts']} parts, {summary['nets']} nets, {summary['sheets']} sheets "
"(Altium, read by CopperPilot's native reader)"
),
)


def check_intent(design: DesignContext, check: CheckSpec, limits: dict[str, Any]) -> CheckOutcome:
del check, limits
intent = load_intent(design.workspace)
Expand Down Expand Up @@ -910,6 +1048,12 @@ def check_models_3d(
BUILTINS: dict[str, Builtin] = {
"tools": Builtin(check_tools, cacheable=False, description="kicad-cli presence and version"),
"project": Builtin(check_project, cacheable=False, description="project discovery and index"),
"altium_project": Builtin(
check_altium_project,
cacheable=False,
hosted=True,
description="Altium netlist and BOM through CopperPilot's native reader",
),
"intent": Builtin(check_intent, cacheable=False, description="design intent files"),
"bom_fields": Builtin(check_bom_fields, description="BOM field completeness"),
"erc": Builtin(check_erc, description="kicad-cli sch erc, grouped by type"),
Expand Down
48 changes: 48 additions & 0 deletions src/copper_pilot_cli/validate/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,49 @@ def packaged_default_raw() -> dict[str, Any]:
return loaded


# Builtins that read KiCad files or run kicad-cli: an Altium project's graph leaves
# them out (its ERC/DRC run in Altium itself: run_altium_erc / run_altium_drc).
KICAD_FILE_BUILTINS = frozenset(
{"erc", "drc", "parity", "rules", "connector_edge", "outputs", "models_3d", "repo"}
)


def altium_raw(raw: dict[str, Any]) -> dict[str, Any]:
"""The graph for an Altium-only workspace: the default one without the KiCad-file
builtins, with intake read by the server's native Altium netlist and BOM export."""
result = copy.deepcopy(raw)
dropped = {
check["id"]
for check in result.get("checks") or []
if check.get("builtin") in KICAD_FILE_BUILTINS
}
checks = []
for check in result.get("checks") or []:
if check["id"] in dropped:
continue
for key in ("requires", "after"):
if key in check:
check[key] = [other for other in check[key] if other not in dropped]
if check.get("builtin") == "tools":
check["title"] = "The design is an Altium project"
elif check.get("builtin") == "project":
check["builtin"] = "altium_project"
check["title"] = "Schematic and netlist can be read (CopperPilot's Altium reader)"
if check.get("prompt"):
check["prompt"] = check["prompt"].replace(
"with kicad-cli", "with export_altium_bom or export_altium_netlist"
)
checks.append(check)
result["checks"] = checks
reviewer = result.setdefault("reviewer", {})
reviewer["preamble"] = str(reviewer.get("preamble") or "").replace(
"validates a KiCad design",
"validates an Altium Designer design (.PrjPcb, .SchDoc, .PcbDoc; read them with "
"CopperPilot's Altium tools, never kicad-cli)",
)
return result


def _merge_by_id(base: list[Any], overrides: list[Any], label: str) -> list[Any]:
result = [copy.deepcopy(item) for item in base]
positions = {
Expand Down Expand Up @@ -297,7 +340,12 @@ def _apply_layer(current: dict[str, Any], layer: dict[str, Any], source: Path) -

def load_raw_graph(workspace: Path, config_path: Path | None = None) -> dict[str, Any]:
"""Layer packaged default, `.copperpilot/validate.yaml`, then `--config`."""
from copper_pilot_cli.copper_workspace import discover_workspace
from copper_pilot_cli.validate.design import is_altium_only

raw = packaged_default_raw()
if is_altium_only(discover_workspace(workspace)):
raw = altium_raw(raw)
project = workspace / PROJECT_CONFIG
if project.is_file():
raw = _apply_layer(raw, _load_yaml(project), project)
Expand Down
Loading
Loading