diff --git a/docs/validate.md b/docs/validate.md index caf5789..6072610 100644 --- a/docs/validate.md +++ b/docs/validate.md @@ -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?, diff --git a/src/copper_pilot_cli/validate/builtins.py b/src/copper_pilot_cli/validate/builtins.py index fe60957..3527993 100644 --- a/src/copper_pilot_cli/validate/builtins.py +++ b/src/copper_pilot_cli/validate/builtins.py @@ -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 @@ -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, @@ -56,7 +61,9 @@ 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) @@ -64,6 +71,9 @@ 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( @@ -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( @@ -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) @@ -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"), diff --git a/src/copper_pilot_cli/validate/config.py b/src/copper_pilot_cli/validate/config.py index 76936c2..0081980 100644 --- a/src/copper_pilot_cli/validate/config.py +++ b/src/copper_pilot_cli/validate/config.py @@ -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 = { @@ -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) diff --git a/src/copper_pilot_cli/validate/design.py b/src/copper_pilot_cli/validate/design.py index 613a3f4..09e2b7b 100644 --- a/src/copper_pilot_cli/validate/design.py +++ b/src/copper_pilot_cli/validate/design.py @@ -30,6 +30,25 @@ _SNAPSHOT_EXCLUDED_SUFFIXES = {".lck", ".kicad_prl", ".pyc"} _SNAPSHOT_EXCLUDED_NAMES = {"fp-info-cache", ".DS_Store"} _LIB_SUFFIXES = {".kicad_sym", ".kicad_mod"} +# Altium designs are read by the CopperPilot server's native readers +ALTIUM_SUFFIXES = { + "sch": ".schdoc", + "pcb": ".pcbdoc", + "pro": ".prjpcb", +} +_ALTIUM_LIB_SUFFIXES = {".schlib", ".pcblib", ".intlib"} +# BOM parameters asked of the Altium export (Part.fields, by any of these names) +ALTIUM_BOM_PARAMETERS = ( + "MPN", + "Manufacturer Part Number", + "Manufacturer", + "LCSC", + "LCSC Part", + "JLCPCB Part", + "Datasheet", + "ComponentLink1URL", + "HelpURL", +) _LIB_TABLES = {"fp-lib-table", "sym-lib-table"} _LAYER_BLOCK_RE = re.compile(r"\(layers\s*\n((?:\s*\(\d+\s+\"[^\"]+\"[^\n]*\n)+)", re.MULTILINE) _LAYER_LINE_RE = re.compile(r"\(\d+\s+\"([^\"]+)\"\s+(\w+)") @@ -101,13 +120,13 @@ def _matches_input(relative: str, kind: str) -> bool: if kind == "all": return True if kind == "sch": - return suffix == ".kicad_sch" + return suffix in {".kicad_sch", ALTIUM_SUFFIXES["sch"]} if kind == "pcb": - return suffix == ".kicad_pcb" + return suffix in {".kicad_pcb", ALTIUM_SUFFIXES["pcb"]} if kind == "pro": - return suffix == ".kicad_pro" + return suffix in {".kicad_pro", ALTIUM_SUFFIXES["pro"]} if kind == "libs": - return suffix in _LIB_SUFFIXES or path.name in _LIB_TABLES + return suffix in _LIB_SUFFIXES or suffix in _ALTIUM_LIB_SUFFIXES or path.name in _LIB_TABLES if kind == "intent": parts = path.parts return ( @@ -460,6 +479,60 @@ def build_index( return index +def build_altium_index(netlist: dict[str, Any], bom: dict[str, Any] | None) -> DesignIndex: + """Index from the server's export_altium_netlist JSON (copperpilot-altium-netlist-v1) + and export_altium_bom JSON: values and parameters come from the BOM rows.""" + rows: dict[str, dict[str, Any]] = {} + for row in (bom or {}).get("rows") or []: + for ref in row.get("designators") or []: + rows[str(ref).upper()] = row + left_out = {str(ref).upper() for ref in (bom or {}).get("not_in_bom") or []} + parts: list[Part] = [] + for comp in netlist.get("components") or []: + ref = str(comp.get("designator") or "") + if not ref: + continue + row = rows.get(ref.upper(), {}) + fields = { + str(key): str(value) for key, value in (row.get("parameters") or {}).items() if value + } + datasheet = next( + ( + fields[name] + for name in ("Datasheet", "ComponentLink1URL", "HelpURL") + if name in fields + ), + "", + ) + parts.append( + Part( + ref=ref, + value=str(row.get("value") or ""), + footprint=str(comp.get("footprint") or row.get("footprint") or ""), + lib=str(comp.get("library_reference") or ""), + datasheet=datasheet, + description=str(comp.get("description") or ""), + sheet=str(comp.get("sheet") or "/"), + exclude_from_bom=ref.upper() in left_out, + fields=fields, + ) + ) + nets: dict[str, Net] = {} + for name, nodes in (netlist.get("nets") or {}).items(): + net = Net(name=str(name)) + for node in nodes or []: + ref, _, pin = str(node).rpartition(".") + net.nodes.append((ref, pin)) + nets[net.name] = net + sheets = [str(sheet) for sheet in netlist.get("sheets") or []] or ["/"] + return DesignIndex( + parts=parts, + nets=nets, + sheets=sheets, + netclasses={"Default": {"name": "Default"}}, + ) + + # ------------------------------------------------------------------ context @@ -498,10 +571,22 @@ def artifacts_dir(self, check_id: str) -> Path: directory.mkdir(parents=True, exist_ok=True) return directory + @property + def altium(self) -> bool: + return is_altium_only(self.context) + def schematic_files(self) -> list[Path]: return [path for path in iter_design_files(self.workspace) if path.suffix == ".kicad_sch"] +def is_altium_only(context: WorkspaceContext) -> bool: + """Every design file found is an Altium one (mixed folders stay KiCad).""" + paths = [context.schematic_path, context.pcb_path, *context.project_files] + names = [str(path).lower() for path in paths if path] + altium = tuple(ALTIUM_SUFFIXES.values()) + return bool(names) and all(name.endswith(altium) for name in names) + + def load_intent(workspace: Path) -> dict[str, str]: """Read the project index, plans index and newest plan, when present.""" result: dict[str, str] = {} diff --git a/src/copper_pilot_cli/validate/runner.py b/src/copper_pilot_cli/validate/runner.py index 26e5b02..08c5e2f 100644 --- a/src/copper_pilot_cli/validate/runner.py +++ b/src/copper_pilot_cli/validate/runner.py @@ -60,6 +60,7 @@ consensus, fan_out_items, ground_findings, + is_usage_limit, make_broker, review_slice, ) @@ -268,9 +269,12 @@ async def run(self) -> RunOutcome: workspace=self.workspace, context=workspace_context, run_dir=self.run_dir, - kicad=self.kicad_finder(), ) - needs_agent = any(check.kind == "agent" for check in selected) + if not self.design.altium: # Altium is read on the server, never by kicad-cli + self.design.kicad = self.kicad_finder() + needs_agent = any( + check.kind == "agent" or BUILTINS[check.builtin or ""].hosted for check in selected + ) if needs_agent: self._prepare_hosted() try: @@ -465,7 +469,7 @@ async def _run_check(self, check: CheckSpec) -> CheckResult: return cached started = time.monotonic() if check.kind == "builtin": - result = self._run_builtin(check) + result = await self._run_builtin(check) else: result = await self._run_agent(check) result.seconds = round(time.monotonic() - started, 3) @@ -486,13 +490,19 @@ def _finish_check(self, check: CheckSpec, result: CheckResult) -> None: f"{' (cached)' if result.cached else ''}{' ' + extra if extra else ''}" ) - def _run_builtin(self, check: CheckSpec) -> CheckResult: + async def _run_builtin(self, check: CheckSpec) -> CheckResult: assert self.design is not None builtin = BUILTINS[check.builtin or ""] limits = self.config.fab_limits() limits["fab"] = self.config.limits.get("fab") try: - outcome = builtin.fn(self.design, check, limits) + if builtin.hosted: + assert self.snapshot is not None + outcome = await builtin.fn( + self.design, check, limits, snapshot=self.snapshot, ask=self._asker(check) + ) + else: + outcome = builtin.fn(self.design, check, limits) except Exception as exc: # noqa: BLE001 - a crashing builtin is an ERROR result outcome = CheckOutcome(error=f"{type(exc).__name__}: {exc}") findings = self._number(check, outcome.findings) @@ -507,6 +517,37 @@ def _run_builtin(self, check: CheckSpec) -> CheckResult: error=outcome.error, ) + def _asker(self, check: CheckSpec) -> Callable[[str], Any]: + """One plain hosted turn on the snapshot for a hosted builtin (no findings reply).""" + + async def ask(prompt: str) -> tuple[str, str | None]: + assert self.snapshot is not None and self.turn is not None + turn = ReviewTurn( + snapshot=self.snapshot, + prompt=prompt, + thread_id=f"validate-{self.run_id}-{check.id}", + effort=CopperEffort(self.options.effort or self.config.reviewer.effort), + broker=make_broker(self.snapshot), + check_id=check.id, + ) + timeout_s = self.config.reviewer.timeout_s + async with self.semaphore: + try: + async with asyncio.timeout(timeout_s if timeout_s > 0 else None): + outcome = await self.turn(turn) + except TimeoutError: + return "", f"timed out after {timeout_s} s (reviewer.timeout_s)" + artifacts = self.design.artifacts_dir(check.id) if self.design else self.run_dir + (artifacts / "prompt.md").write_text(prompt, encoding="utf-8") + (artifacts / "reply.md").write_text(outcome.text, encoding="utf-8") + if outcome.error is not None: + if is_usage_limit(outcome.error) and self.usage_limit is None: + self.usage_limit = outcome.error + return outcome.text, str(outcome.error.get("message") or "hosted turn failed") + return outcome.text, None + + return ask + def _number(self, check: CheckSpec, findings: list[Finding]) -> list[Finding]: findings.sort(key=lambda item: (SEVERITY_RANK[item.severity], item.title.lower())) for position, finding in enumerate(findings, start=1): diff --git a/tests/test_validate.py b/tests/test_validate.py index 9042529..e1c5bb7 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -2003,3 +2003,109 @@ def test_cli_names_skipped_checks_in_a_loud_incomplete_line(tmp_path, capsys) -> line.split(": ", 1)[1] for line in out.splitlines() if line.startswith("report: ") ) assert "check(s) skipped" in Path(report_path).read_text() + + +# ------------------------------------------------------------------ altium +ALTIUM_NETLIST = { + "format": "copperpilot-altium-netlist-v1", + "sheets": ["Main.SchDoc"], + "components": [ + { + "designator": "U1", + "library_reference": "LDO", + "sheet": "Main.SchDoc", + "footprint": "SOT-23", + }, + { + "designator": "R1", + "library_reference": "RES", + "sheet": "Main.SchDoc", + "footprint": "0603", + }, + ], + "nets": {"VCC": ["U1.1", "R1.1"], "GND": ["U1.2"]}, + "name_conflicts": {"VCC": ["VCC", "3V3"]}, +} +ALTIUM_BOM = { + "rows": [ + {"value": "AP2112K", "designators": ["U1"], "parameters": {"LCSC": "C51118"}}, + {"value": "10k", "designators": ["R1"], "parameters": {}}, + ], + "unannotated": [], + "not_in_bom": [], +} + + +def make_altium_project(root: Path) -> Path: + board = root / "board" + board.mkdir(parents=True, exist_ok=True) + for name in ("Board.PrjPcb", "Main.SchDoc", "Board.PcbDoc"): + (board / name).write_bytes(b"\xd0\xcf\x11\xe0") + return root + + +def altium_turn(*, netlist: bool = True) -> FakeTurn: + def intake(turn: ReviewTurn, _call: int) -> str: + scratch = turn.snapshot / SCRATCH_DIR / "altium-intake" + scratch.mkdir(parents=True, exist_ok=True) + if netlist: + (scratch / "netlist.json").write_text(json.dumps(ALTIUM_NETLIST), encoding="utf-8") + (scratch / "bom.json").write_text(json.dumps(ALTIUM_BOM), encoding="utf-8") + return "Both exports succeeded." + + return FakeTurn({"intake.project": intake}) + + +def test_altium_only_folder_gets_the_altium_graph(tmp_path) -> None: + make_altium_project(tmp_path) + checks = {check.id: check for check in load_config(tmp_path).checks} + assert checks["intake.project"].builtin == "altium_project" + assert "sch.erc" not in checks and "pcb.drc" not in checks + assert all( + check.builtin not in {"erc", "drc", "parity", "outputs"} for check in checks.values() + ) + assert "sch.erc" not in checks["sch.circuits"].requires + + +def test_mixed_kicad_and_altium_folder_keeps_the_kicad_graph(tmp_path) -> None: + make_project(tmp_path) + make_altium_project(tmp_path / "legacy") + checks = {check.id: check for check in load_config(tmp_path).checks} + assert checks["intake.project"].builtin == "project" + assert "sch.erc" in checks + + +@pytest.mark.asyncio +async def test_altium_intake_indexes_the_native_exports_without_kicad(tmp_path) -> None: + make_altium_project(tmp_path) + turn = altium_turn() + runner = Runner( + tmp_path, + load_config(tmp_path), + RunOptions(), + turn=turn, + kicad_finder=lambda: pytest.fail("kicad-cli must not be looked up for Altium"), + credential_loader=lambda: CREDENTIAL, + snapshot_root=tmp_path.parent / "snapshots", + ) + outcome = await runner.run() + results = by_id(outcome.results) + assert results["intake.tools"].status is Status.PASS + assert results["intake.project"].status is Status.WARN # P2 name conflict + assert any("more than one name" in f.title for f in results["intake.project"].findings) + assert runner.design is not None and runner.design.index is not None + parts = {part.ref: part for part in runner.design.index.parts} + assert parts["U1"].value == "AP2112K" and parts["U1"].fields["LCSC"] == "C51118" + assert runner.design.index.nets["VCC"].nodes == [("U1", "1"), ("R1", "1")] + assert "altium-intake/netlist.json" in turn.turns[0].prompt + assert all("kicad-cli" not in t.prompt.split("validates")[0] for t in turn.turns[1:]) + + +@pytest.mark.asyncio +async def test_altium_intake_without_a_netlist_is_an_error(tmp_path) -> None: + make_altium_project(tmp_path) + runner = runner_for(tmp_path, options=RunOptions(until="S0"), turn=altium_turn(netlist=False)) + outcome = await runner.run() + result = by_id(outcome.results)["intake.project"] + assert result.status is Status.ERROR + assert "Both exports succeeded." in (result.error or "")