main
Colby Knox altium-bridge 0.2.90: eleven new verbs, license never answers success for a press that didn't happen, update_pcb opens… dd28f04
#!/usr/bin/env python3
"""Run altium-bridge's edit verbs for real, and confirm each with a separate read.

The verb battery only dry-runs these, or accepts a named refusal, because it shares one board and sheet between all its
verbs. A dry run can't catch a verb that plans correctly and then changes nothing, so this drill builds its own board
and sheet and runs each edit for real. A step passes only when a second verb reads the change back.

    python3 edit_drill.py --target DESKTOP-BAR6S0F --thread altium-lane [--only a,b] [--json out.json]

Scratch only: everything lives in <Documents>/Adom/altium-bridge-drill on the target, emptied at the start.
"""
import argparse
import json
import os
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
ROWS = []


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--target", required=True)
    ap.add_argument("--thread", default="altium-lane")
    ap.add_argument("--only", default="")
    ap.add_argument("--json", default="")
    ap.add_argument("--install", default="develop")
    a = ap.parse_args()
    only = [x for x in a.only.split(",") if x]

    def call(verb, args=None, timeout=300):
        args = dict(args or {})
        args.setdefault("reason", "altium-bridge edit drill, on scratch copies")
        p = subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "altium_" + verb, json.dumps(args)], capture_output=True, text=True, timeout=timeout)
        try:
            d = json.loads(p.stdout)
        except ValueError:
            return {"success": False, "error": (p.stdout or p.stderr)[:400]}
        o = d.get("output")
        if isinstance(o, str) and o.startswith("{"):
            try:
                return json.loads(o)
            except ValueError:
                pass
        return d

    def shell(cmd):
        p = subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "shell_execute", json.dumps({"command": cmd, "reason": "altium-bridge edit drill scratch folder"})], capture_output=True, text=True, timeout=120)
        d = json.loads(p.stdout)
        o = d.get("output")
        if isinstance(o, str) and o.startswith("{"):
            d = json.loads(o)
        return d.get("stdout") or ""

    def step(verb, fn):
        if only and verb not in only:
            return
        t0 = time.time()
        try:
            good, detail = fn()
        except Exception as e:  # a read that came back in another shape is a failure of this step, not of the drill
            good, detail = False, f"{type(e).__name__}: {e}"
        ROWS.append(dict(verb=verb, ok=bool(good), detail=str(detail)[:400], sec=round(time.time() - t0, 1)))
        print(("PASS " if good else "FAIL ") + verb + ": " + str(detail)[:300], flush=True)

    home = shell('powershell -NoProfile -Command "[Environment]::GetFolderPath(\'UserProfile\')"').strip().replace("\\", "/")
    D = home + "/Documents/Adom/altium-bridge-drill"
    dw = D.replace("/", "\\")
    fx = [os.path.join(HERE, "fixtures", n) for n in ("Adom_Test.SchLib", "Adom_Test.PcbLib")]
    call("close_all_documents", {"save": True})
    shell(f'cmd /c rmdir /S /Q "{dw}" 2>nul & mkdir "{dw}"')
    subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "send_files", json.dumps({"filePaths": fx, "dest": D, "destIsFolder": True, "reason": "edit drill libraries"})], capture_output=True, text=True, timeout=300)
    SL, PL = D + "/Adom_Test.SchLib", D + "/Adom_Test.PcbLib"
    B, S, P = D + "/drill.PcbDoc", D + "/drill.SchDoc", D + "/drill.PrjPcb"
    call("launch", {"install": a.install})
    nets = {"N1": ["U1.8", "U2.1"], "N2": ["U2.8", "U3.1"], "GND": ["U1.4", "U2.5", "U3.5"]}
    parts = [{"ref": f"U{i}", "footprint": "TST_SOIC8", "x": 10 + 20 * (i - 1), "y": 20, "rotation": 0} for i in (1, 2, 3)]
    r = call("build_board", {"pcbPath": B, "libraryPath": PL, "outline": {"rect": [0, 0, 70, 40]}, "parts": parts, "nets": nets})
    if r.get("placed") != 3:
        sys.exit(f"build_board did not make the drill board: {json.dumps(r)[:400]}")
    r = call("build_schematic", {"schPath": S, "libraryPath": SL, "pcbLibPath": PL, "pcbPath": B, "projectPath": P, "title": "edit drill",
                                 "parts": [{"ref": f"U{i}", "symbol": "TST_SOIC8", "block": "core", "footprint": "TST_SOIC8"} for i in (1, 2, 3)], "nets": nets}, timeout=600)
    if not r.get("success"):
        sys.exit(f"build_schematic did not make the drill sheet: {json.dumps(r)[:400]}")

    # -- reads ----------------------------------------------------------------------------------------------------
    items = lambda: call("sch_items", {"sheet": S})
    n = lambda key: len(items().get(key) or [])
    state = lambda: call("routing_state", {"filePath": B})
    comps = lambda: {c["ref"]: c for c in state().get("components") or []}
    # a free corner of the sheet, each step on its own row
    Y = {"y": 170.0}
    def row():
        Y["y"] -= 5.08
        return Y["y"]

    # -- schematic ------------------------------------------------------------------------------------------------
    def sch_wire():
        y = row(); w0 = n("wires")
        r = call("sch_wire", {"sheet": S, "points": [[20.32, y], [40.64, y]]})
        return r.get("success") and n("wires") == w0 + 1, f"wires {w0} -> {w0 + 1}: {r.get('error') or 'read back'}"
    step("sch_wire", sch_wire)

    def sch_connect_pins():
        w0 = n("wires")
        r = call("sch_connect_pins", {"sheet": S, "pairs": [{"from": "U1.2", "to": "U1.3"}]})
        pins = call("sch_pins", {"sheet": S, "references": ["U1"]}).get("pins") or []
        pin2 = next((p for p in pins if str(p.get("pin") or p.get("number")) == "2"), {})
        return r.get("success") and n("wires") > w0 and "U1.3" in json.dumps(pin2), f"U1.2 reads {json.dumps(pin2)[:160]}"
    step("sch_connect_pins", sch_connect_pins)

    def sch_bus():
        b0, y = n("buses"), row()
        Y["bus"] = y
        r = call("sch_bus", {"sheet": S, "points": [[50.8, y], [101.6, y]], "label": "D[0..2]"})
        return r.get("success") and n("buses") == b0 + 1, f"buses {b0} -> {n('buses')}: {r.get('error')}"
    step("sch_bus", sch_bus)

    def sch_bus_entry():
        e0 = n("busEntries")
        r = call("sch_bus_entry", {"sheet": S, "entries": [{"at": [60.96, Y["bus"] - 2.54], "direction": "up-right"}]})
        return r.get("success") and n("busEntries") == e0 + 1, f"entries {e0} -> {n('busEntries')}: {r.get('error')}"
    step("sch_bus_entry", sch_bus_entry)

    def sch_connect_to_bus():
        pins = {str(p.get("number")): p["at"] for p in call("sch_pins", {"sheet": S, "references": ["U3"]}).get("pins") or []}
        x = pins["2"][0] - 10.16
        b = call("sch_bus", {"sheet": S, "points": [[x, pins["3"][1] - 7.62], [x, pins["2"][1] + 7.62]]})
        e0, w0 = n("busEntries"), n("wires")
        r = call("sch_connect_to_bus", {"sheet": S, "bus": (b.get("ids") or [""])[0], "pins": ["U3.2", "U3.3"], "prefix": "D", "start": 0})
        return r.get("success") and n("busEntries") == e0 + 2 and n("wires") >= w0 + 2, f"entries {e0} -> {n('busEntries')}, wires {w0} -> {n('wires')}: {r.get('error')}"
    step("sch_connect_to_bus", sch_connect_to_bus)

    def wire_at():
        y = row()
        call("sch_wire", {"sheet": S, "points": [[20.32, y], [40.64, y]]})
        return y

    def sch_junction():
        y = wire_at(); j0 = n("junctions")
        r = call("sch_junction", {"sheet": S, "points": [[30.48, y]]})
        up = n("junctions")
        i = (r.get("added") or [{}])[0].get("id")
        r2 = call("sch_junction", {"sheet": S, "remove": [i]})
        return r.get("success") and up == j0 + 1 and r2.get("success") and n("junctions") == j0, f"junctions {j0} -> {up} -> {n('junctions')}"
    step("sch_junction", sch_junction)

    def sch_split_wire():
        y = wire_at(); w0 = n("wires")
        r = call("sch_split_wire", {"sheet": S, "at": [30.48, y]})
        return r.get("success") and n("wires") == w0 + 1, f"wires {w0} -> {n('wires')}: {r.get('error')}"
    step("sch_split_wire", sch_split_wire)

    def sch_delete_wire():
        y = wire_at(); w0 = n("wires")
        r = call("sch_delete_wire", {"sheet": S, "at": [30.48, y]})
        return r.get("success") and n("wires") == w0 - 1, f"wires {w0} -> {n('wires')}: {r.get('error')}"
    step("sch_delete_wire", sch_delete_wire)

    def sch_edit_label():
        y = wire_at()
        a0 = call("sch_label", {"sheet": S, "text": "DRILL_A", "at": [30.48, y]})
        i = (a0.get("label") or {}).get("id")
        r = call("sch_edit_label", {"sheet": S, "edits": [{"id": i, "rename": "DRILL_B"}]})
        texts = [x.get("text") for x in items().get("labels") or []]
        return r.get("success") and "DRILL_B" in texts and "DRILL_A" not in texts, f"labels read {texts[-3:]}: {r.get('error')}"
    step("sch_edit_label", sch_edit_label)

    def sch_label():
        y = wire_at()
        r = call("sch_label", {"sheet": S, "text": "DRILL_L", "at": [30.48, y]})
        i = (r.get("label") or {}).get("id")
        here = i in [x.get("id") for x in items().get("labels") or []]
        r2 = call("sch_label", {"sheet": S, "remove": True, "id": i})
        gone = i not in [x.get("id") for x in items().get("labels") or []]
        # global is Altium's power port, hierarchical its port: each its own object, read back and taken away by text and place
        y2 = wire_at()
        g = call("sch_label", {"sheet": S, "text": "DRILL_G", "at": [30.48, y2], "kind": "global"})
        gnet = any(x.get("net") == "DRILL_G" for x in items().get("powerPorts") or [])
        call("sch_label", {"sheet": S, "remove": True, "text": "DRILL_G", "at": [30.48, y2]})
        ggone = not any(x.get("net") == "DRILL_G" for x in items().get("powerPorts") or [])
        h = call("sch_label", {"sheet": S, "text": "DRILL_H", "at": [40.64, y2], "kind": "hierarchical"})
        hport = any(x.get("text") == "DRILL_H" and x.get("kind") == "hierarchical" for x in items().get("labels") or [])
        return r.get("success") and here and r2.get("success") and gone and not r.get("offWire") and g.get("success") and gnet and ggone and h.get("success") and hport, f"local added {here}, removed {gone}; global {gnet}, removed {ggone}; hierarchical {hport}"
    step("sch_label", sch_label)

    def sch_no_connect():
        y = wire_at()
        r = call("sch_no_connect", {"sheet": S, "points": [[20.32, y]]})
        i = (r.get("added") or [{}])[0].get("id")
        here = i in [x.get("id") for x in items().get("noConnects") or []]
        r2 = call("sch_no_connect", {"sheet": S, "remove": True, "id": i})
        gone = i not in [x.get("id") for x in items().get("noConnects") or []]
        return r.get("success") and here and r2.get("success") and gone, f"added {here}, removed {gone}"
    step("sch_no_connect", sch_no_connect)

    def sch_move_region():
        y = wire_at()
        call("sch_label", {"sheet": S, "text": "DRILL_M", "at": [30.48, y]})
        r = call("sch_move_region", {"sheet": S, "box": [29, y - 1, 32, y + 1], "by": [2.54, 0]})
        lab = next((x for x in items().get("labels") or [] if x.get("text") == "DRILL_M"), {})
        return r.get("success") and abs((lab.get("at") or [0])[0] - 33.02) < 0.01, f"DRILL_M at {lab.get('at')}: {r.get('error')}"
    step("sch_move_region", sch_move_region)

    def sch_edit():
        before = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U3"]
        x0 = before[0]["xMil"]
        r = call("sch_edit", {"sheet": S, "edits": [{"designator": "U3", "action": "move", "x": x0 + 100, "y": before[0]["yMil"]}]})
        after = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U3"]
        return r.get("success") and abs(after[0]["xMil"] - (x0 + 100)) < 2, f"U3 x {x0} -> {after[0]['xMil']}: {r.get('error')}"
    step("sch_edit", sch_edit)

    def sch_place_part():
        c0 = len((call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []))
        r = call("sch_place_part", {"sheet": S, "library": SL, "symbol": "TST_SOIC8", "designator": "U9", "x": 8000, "y": 2000})
        got = (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", [])
        return r.get("success") and len(got) == c0 + 1 and any(c.get("designator") == "U9" for c in got), f"parts {c0} -> {len(got)}: {r.get('error')}"
    step("sch_place_part", sch_place_part)

    def sch_swap_part():
        r = call("sch_swap_part", {"sheet": S, "designator": "U9", "library": SL, "symbol": "TST_QFN24"})
        got = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U9"]
        return r.get("success") and got and got[0].get("libReference") == "TST_QFN24", f"U9 is {got and got[0].get('libReference')}: {r.get('error')}"
    step("sch_swap_part", sch_swap_part)

    def sch_reset_fields():
        r = call("sch_reset_fields", {"sheet": S, "all": True})
        return r.get("success"), f"reply {json.dumps({k: r.get(k) for k in ('reset', 'moved', 'unchanged', 'error')})[:200]} (no separate read: the fields have no verb of their own)"
    step("sch_reset_fields", sch_reset_fields)

    def sch_update_from_library():
        # change the library's symbol: an update compares pins, so the part is named to re-place it, and the placed part
        # must take the change
        params = lambda: json.dumps([c.get("params") for c in (call("schematic_data", {"filePath": S, "params": True}).get("data") or {}).get("components", []) if c.get("designator") == "U1"])
        before = params()
        call("set_params", {"libraryPath": SL, "symbolName": "TST_SOIC8", "params": {"DrillParam": "drilled"}})
        call("save", {"filePath": SL})
        plain = call("sch_update_from_library", {"sheet": S})
        r = call("sch_update_from_library", {"sheet": S, "symbols": ["TST_SOIC8"]})
        after = params()
        return r.get("success") and any(c.get("ref") == "U1" for c in plain.get("unchanged") or []) and "DrillParam" not in before and "drilled" in after, f"same pins read unchanged; named, U1 params {after[:170]}: {r.get('error')}"
    step("sch_update_from_library", sch_update_from_library)

    def cancel_run():
        # a long batch, stopped from another thread: it has to answer cancelled and leave the sheet as it was
        import threading
        y = row()
        w0 = n("wires")
        keep = lambda: [(x.get("from"), x.get("to"), x.get("points")) for x in items().get("wires") or []]
        k0 = keep()
        ops = [{"op": "sch_wire", "points": [[20.32 + i * 2.54, y], [20.32 + i * 2.54, y - 2.54]]} for i in range(30)]
        box = {}
        t = threading.Thread(target=lambda: box.update(call("sch_batch", {"filePath": S, "ops": ops, "erc": False}, timeout=500)))
        t.start()
        got = {}
        for _ in range(60):
            time.sleep(1)
            got = call("cancel_run", {})
            if got.get("cancelRequested"):
                break
        t.join()
        return got.get("cancelRequested") and box.get("errorCode") == "cancelled" and box.get("restored") is True and n("wires") == w0, f"asked at stage {got.get('stage')}; batch answered {box.get('errorCode')}, undone {box.get('undone')}, restored {box.get('restored')}, differs {box.get('differs')}, wires {w0} -> {n('wires')}, row y {y}, came back {[x for x in keep() if x not in k0][:3]}, lost {[x for x in k0 if x not in keep()][:3]}"
    step("cancel_run", cancel_run)

    # -- board ----------------------------------------------------------------------------------------------------
    def route_net():
        r = call("route_net", {"filePath": B, "net": "N1", "width": 0.254, "paths": [[{"pad": "U1.8"}, {"pad": "U2.1"}]]})
        t = [x for x in state().get("tracks") or [] if x["net"] == "N1"]
        return r.get("success") and len(t) >= 1, f"N1 tracks {len(t)}: {r.get('error')}"
    step("route_net", route_net)

    def place_parts():
        r = call("place_parts", {"filePath": B, "parts": [{"library": PL, "ref": "U9", "footprint": "TST_QFN24", "value": "DRILLQ", "x": 60, "y": 32, "rotation": 90, "side": "bottom", "nets": {"25": "GND"}}]})
        c = comps().get("U9") or {}
        pad = [p for p in state().get("pads") or [] if p["ref"] == "U9" and p["name"] == "25"]
        if not pad or pad[0].get("net") != "GND":
            return False, f"U9.25 reads {pad and pad[0].get('net')}: nets did not land"
        return r.get("success") and abs(c.get("x", 0) - 60) < 0.01 and abs(c.get("y", 0) - 32) < 0.01 and abs(c.get("rotation", 0) - 90) < 0.01 and c.get("side") == "bottom", f"U9 reads {json.dumps({k: c.get(k) for k in ('x', 'y', 'rotation', 'side')})}: {r.get('error')}"
    step("place_parts", place_parts)

    def edit_tracks():
        t = state()["tracks"][0]
        r = call("edit_tracks", {"tracks": [{"id": t["id"], "width": t["width"] + 0.1}]})
        hit = [x for x in state()["tracks"] if x["start"] == t["start"] and x["end"] == t["end"]]
        return r.get("success") and hit and abs(hit[0]["width"] - t["width"] - 0.1) < 0.001, f"width {t['width']} -> {hit and hit[0]['width']}: {r.get('error')}"
    step("edit_tracks", edit_tracks)

    def set_track_width():
        r = call("set_track_width", {"filePath": B, "nets": ["N1"], "widthMm": 0.4})
        ws = {x["width"] for x in state()["tracks"] if x["net"] == "N1"}
        # back to the default rule's own width (exactly 10 mil), so the copy below adds no DRC error
        call("set_track_width", {"filePath": B, "nets": ["N1"], "widthMm": 0.254})
        return r.get("success") and ws == {0.4}, f"N1 widths {ws}: {r.get('error')}"
    step("set_track_width", set_track_width)

    def copy_routing():
        t0 = len(state()["tracks"])
        r = call("copy_routing", {"filePath": B, "box": [0, 10, 40, 30], "offset": [0, 15], "keepUnmappedNets": True})
        t1 = len(state()["tracks"])
        return r.get("success") and t1 > t0, f"tracks {t0} -> {t1}: {r.get('error')}"
    step("copy_routing", copy_routing)

    def length_tune():
        l0 = call("net_lengths", {"filePath": B, "nets": ["N1"]})
        r = call("length_tune", {"filePath": B, "net": "N1", "targetMm": l0["nets"][0]["lengthMm"] + 1.9})
        l1 = call("net_lengths", {"filePath": B, "nets": ["N1"]})
        return r.get("success") and json.dumps(l0.get("nets")) != json.dumps(l1.get("nets")), f"before {json.dumps(l0.get('nets'))[:90]}, after {json.dumps(l1.get('nets'))[:90]}: {r.get('error') or r.get('errorCode')}"
    step("length_tune", length_tune)

    def edit_parts():
        r = call("edit_parts", {"filePath": B, "edits": [{"ref": "U3", "value": "DRILLV"}]})
        d = call("component_data", {"designator": "U3", "filePath": B})
        return r.get("success") and "DRILLV" in json.dumps(d), f"U3 reads value in {json.dumps(d)[:200]}: {r.get('error')}"
    step("edit_parts", edit_parts)

    def align_parts():
        call("move_parts", {"parts": [{"ref": "U2", "x": 30, "y": 24}], "filePath": B})
        r = call("align_parts", {"filePath": B, "refs": ["U2", "U3"], "mode": "top"})
        c = comps()
        return r.get("success") and abs(c["U2"]["y"] - c["U3"]["y"]) < 0.01, f"U2 y {c['U2']['y']}, U3 y {c['U3']['y']}: {r.get('error')}"
    step("align_parts", align_parts)

    def via_fence():
        v0 = len(state()["vias"])
        r = call("via_fence", {"filePath": B, "nets": ["N1"], "viaNet": "GND", "pitchMm": 3, "edge": True})
        v1 = len(state()["vias"])
        return r.get("success") and v1 > v0, f"vias {v0} -> {v1}: {r.get('error')}"
    step("via_fence", via_fence)

    def place_vias():
        v0 = len(state()["vias"])
        r = call("place_vias", {"vias": [{"net": "GND", "x": 65, "y": 5, "size": 0.6, "drill": 0.3}]})
        v1 = len(state()["vias"])
        return r.get("success") and v1 == v0 + 1, f"vias {v0} -> {v1}: {r.get('error')}"
    step("place_vias", place_vias)

    def thermal_vias():
        call("move_parts", {"parts": [{"ref": "U9", "x": 60, "y": 32, "side": "top"}], "filePath": B})
        v0 = len(state()["vias"])
        r = call("thermal_vias", {"filePath": B, "ref": "U9"})
        v1 = len(state()["vias"])
        return r.get("success") and v1 > v0, f"vias {v0} -> {v1}: {r.get('error') or r.get('errorCode')}"
    step("thermal_vias", thermal_vias)

    def remove_parts():
        r = call("remove_parts", {"filePath": B, "refs": ["U9"]})
        return r.get("success") and "U9" not in comps(), f"U9 gone: {'U9' not in comps()}: {r.get('error')}"
    step("remove_parts", remove_parts)

    def set_layer_count():
        r = call("set_layer_count", {"filePath": B, "count": 4}, timeout=400)
        d = call("layer_stack", {"filePath": B})
        n_cu = (d.get("data") or d).get("copperLayers")
        return r.get("success") and n_cu == 4, f"copper layers {n_cu}: {r.get('error')}"
    step("set_layer_count", set_layer_count)

    def set_outline():
        r = call("set_outline", {"filePath": B, "outline": {"rect": [0, 0, 72, 42]}})
        o = state().get("outline") or []
        xs = [p[0] for p in o]
        return r.get("success") and xs and abs(max(xs) - 72) < 0.01, f"outline reaches x {xs and max(xs)}: {r.get('error')}"
    step("set_outline", set_outline)

    call("save", {"filePath": B})
    call("save", {"filePath": S})

    def project_rename():
        call("close_all_documents", {"save": True})
        r0 = call("project_create", {"parentDir": D + "/renamed-parent", "name": "Drill"}, timeout=400)
        d2 = D + "/renamed-parent/Drill"
        call("close_all_documents", {"save": True})
        r = call("project_rename", {"project": d2 + "/Drill.PrjPcb", "newName": "Drill2"})
        listing = shell(f'cmd /c dir /b "{d2.replace("/", chr(92))}"')
        return r.get("success") and "Drill2.PrjPcb" in listing and "Drill.PrjPcb" not in listing.split(), f"folder holds {listing.split()[:6]}: {r0.get('error')} {r.get('error')}"
    step("project_rename", project_rename)

    # -- a real project, with parts and libraries this bridge did not make ----------------------------------------
    # A copy of Altium's own example. Fixtures the code generated are shaped the way the code expects, so they can't
    # catch what real libraries do differently.
    call("close_all_documents", {"save": True})
    examples = "C:\\Users\\Public\\Documents\\Altium\\{}\\Examples\\SpiritLevel-SL1"
    fw = dw + "\\foreign"
    shell(f'cmd /c (if exist "{examples.format("ADDevelop")}" (xcopy /E /I /Y /Q "{examples.format("ADDevelop")}" "{fw}") else (xcopy /E /I /Y /Q "{examples.format("AD26")}" "{fw}")) >nul')
    found = shell(f'cmd /c dir /s /b "{fw}"')
    pick = lambda ext: next((l.strip().replace("\\", "/") for l in found.splitlines() if l.strip().lower().endswith(ext)), "")
    FB, FP, FL, FS = pick(".pcbdoc"), pick(".prjpcb"), pick(".pcblib"), pick(".schlib")
    sheets = [l.strip().replace("\\", "/") for l in found.splitlines() if l.strip().lower().endswith(".schdoc")]
    if not (FB and FP and FL and sheets):
        ROWS.append(dict(verb="foreign project", ok=False, detail=f"the example was not copied: {found[:200]}", sec=0))
    else:
        def lib_first(path):
            d = call("list_library", {"libraryPath": path})
            names = (d.get("data") or d).get("names") or (d.get("data") or d).get("components") or [""]
            return names[0].get("name") if isinstance(names[0], dict) else names[0]
        fstate = lambda: call("routing_state", {"filePath": FB})
        fcomps = lambda: {c["ref"]: c for c in fstate().get("components") or []}
        first = fcomps()
        FR = sorted(first)[0] if first else ""

        def f_read():
            return len(first) > 0, f"{len(first)} parts read from {os.path.basename(FB)}"
        step("foreign:routing_state", f_read)

        def f_move():
            c = first[FR]
            r = call("move_parts", {"parts": [{"ref": FR, "x": c["x"] + 1.27, "y": c["y"]}], "filePath": FB})
            x1 = fcomps()[FR]["x"]
            call("move_parts", {"parts": [{"ref": FR, "x": c["x"], "y": c["y"]}], "filePath": FB})
            return r.get("success") and abs(x1 - c["x"] - 1.27) < 0.01, f"{FR} x {c['x']} -> {x1}: {r.get('error')}"
        step("foreign:move_parts", f_move)

        def f_edit_parts():
            r = call("edit_parts", {"filePath": FB, "edits": [{"ref": FR, "value": "DRILLV"}]})
            d = call("component_data", {"designator": FR, "filePath": FB})
            return r.get("success") and "DRILLV" in json.dumps(d), f"{FR} after: {json.dumps(r.get('edited'))[:180]}: {r.get('error')}"
        step("foreign:edit_parts", f_edit_parts)

        def f_edit_tracks():
            tr = fstate().get("tracks") or []
            t = next((x for x in tr if x.get("net")), tr[0])
            r = call("edit_tracks", {"tracks": [{"id": t["id"], "width": round(t["width"] + 0.05, 4)}]})
            hit = [x for x in fstate().get("tracks") or [] if x["start"] == t["start"] and x["end"] == t["end"] and x["layer"] == t["layer"]]
            return r.get("success") and hit and abs(hit[0]["width"] - t["width"] - 0.05) < 0.001 and hit[0].get("net") == t.get("net"), f"net {t.get('net')} width {t['width']} -> {hit and hit[0]['width']}, net kept {hit and hit[0].get('net')}: {r.get('error')}"
        step("foreign:edit_tracks", f_edit_tracks)

        def f_place_parts():
            fp = lib_first(FL)
            call("routing_state", {"filePath": FB})
            r = call("place_parts", {"filePath": FB, "parts": [{"library": FL, "ref": "DRILL1", "footprint": fp, "x": 5, "y": 5, "rotation": 90}]})
            c = fcomps().get("DRILL1") or {}
            pads = [p for p in fstate().get("pads") or [] if p["ref"] == "DRILL1"]
            good = r.get("success") and abs(c.get("x", 0) - 5) < 0.01 and abs(c.get("rotation", 0) - 90) < 0.01 and len(pads) > 0
            gone = call("remove_parts", {"filePath": FB, "refs": ["DRILL1"]})
            return good and gone.get("success") and "DRILL1" not in fcomps(), f"{fp}: {len(pads)} pads, at {c.get('x')},{c.get('y')} rot {c.get('rotation')}: {r.get('error')}"
        step("foreign:place_parts", f_place_parts)

        def f_model_check():
            # a board with real embedded STEP models too, not only extruded bodies
            f2 = shell(f'cmd /c xcopy /E /I /Y /Q "{examples.format("ADDevelop").replace("SpiritLevel-SL1", "Mini PC")}\\Mini PC - WiFi" "{dw}\\foreign-wifi" >nul & dir /s /b "{dw}\\foreign-wifi\\WiFi.PcbDoc"').strip().replace("\\", "/")
            m = call("model_check", {"filePath": f2, "limit": 500})
            real = [x for p in m.get("parts") or [] for x in p["models"] if x["kind"] == "model"]
            if not real or not all(x["location"] == "embedded" and x["found"] and x["sourceFileFound"] is None for x in real) or m.get("sourceFileMissing"):
                return False, f"WiFi.PcbDoc read {json.dumps(real[:1])[:200]}, sourceFileMissing {(m.get('sourceFileMissing') or [])[:3]}: {m.get('error')}"
            call("close_all_documents", {"save": True})
            r = call("model_check", {"filePath": FB, "limit": 500})
            withb = [p for p in r.get("parts") or [] if p.get("models")]
            return r.get("success") and r.get("checked") == len(first) and len(withb) > 0, f"{r.get('checked')} parts checked, {len(withb)} with bodies, noModel {len(r.get('noModel') or [])}, kinds {sorted({b['kind'] for p in withb for b in p['models']})}, sample {json.dumps(withb[0]['models'][0])[:120] if withb else ''}"
        step("foreign:model_check", f_model_check)

        def f_select():
            r = call("select_items", {"filePath": FB, "refs": [FR]})
            n = call("selection", {"filePath": FB}).get("count")
            call("select_items", {"filePath": FB, "clear": True})
            return r.get("verified") is True and n == 1, f"selected {r.get('selected')}, read {n}"
        step("foreign:select_items", f_select)

        FSH = next((x for x in sheets if call("sch_items", {"sheet": x}).get("wires")), sheets[0])
        fitems = lambda: call("sch_items", {"sheet": FSH})
        def f_sch_wire_label():
            it = fitems()
            w0, l0 = len(it.get("wires") or []), len(it.get("labels") or [])
            r = call("sch_wire", {"sheet": FSH, "points": [[2.54, 2.54], [12.7, 2.54]]})
            r2 = call("sch_label", {"sheet": FSH, "text": "DRILL_F", "at": [5.08, 2.54]})
            it2 = fitems()
            good = r.get("success") and r2.get("success") and len(it2.get("wires") or []) == w0 + 1 and len(it2.get("labels") or []) == l0 + 1
            call("sch_label", {"sheet": FSH, "remove": True, "id": (r2.get("label") or {}).get("id")})
            call("sch_delete_wire", {"sheet": FSH, "at": [5.08, 2.54]})
            it3 = fitems()
            return good and len(it3.get("wires") or []) == w0 and len(it3.get("labels") or []) == l0, f"wires {w0} -> {len(it2.get('wires') or [])} -> {len(it3.get('wires') or [])}, labels {l0} -> {len(it2.get('labels') or [])} -> {len(it3.get('labels') or [])} on {os.path.basename(FSH)}"
        step("foreign:sch_wire+label", f_sch_wire_label)

        def f_sch_edit_label():
            labs = [x for x in fitems().get("labels") or []]
            if not labs:
                return True, "no net labels on this sheet: nothing to rename"
            t = labs[0]
            r = call("sch_edit_label", {"sheet": FSH, "edits": [{"id": t["id"], "by": [0, 2.54]}]})
            hit = [x for x in fitems().get("labels") or [] if x.get("text") == t["text"] and abs(x["at"][1] - t["at"][1] - 2.54) < 0.01]
            call("sch_edit_label", {"sheet": FSH, "edits": [{"id": hit[0]["id"] if hit else "", "by": [0, -2.54]}]})
            return r.get("success") and len(hit) == 1, f"{t['text']} moved up: {len(hit) == 1}: {r.get('error')}"
        step("foreign:sch_edit_label", f_sch_edit_label)

        def f_update_pcb():
            # a real library's part from the sheet to the board, through Altium's own ECO: it must arrive named
            sym = lib_first(FS)
            n0 = set(fcomps())
            r = call("sch_place_part", {"sheet": FSH, "library": FS, "symbol": sym, "designator": "DRILL7", "x": 300, "y": 300})
            call("save", {"filePath": FSH})
            # Altium's example has parts on one side only (Logo5 on the board alone), so this copy takes the removal too
            u = call("update_pcb", {"projectPath": FP, "execute": True, "allowRemovals": True}, timeout=400)
            n1 = fcomps()
            new = sorted(set(n1) - n0)
            part = n1.get("DRILL7") or {}
            return r.get("success") and "DRILL7" in new and part.get("pattern"), f"{sym}: new on the board {new}, footprint {part.get('pattern')}: place {r.get('error')} update {json.dumps({k: u.get(k) for k in ('success', 'error', 'errorCode', 'added', 'applied')})[:160]}"
        step("foreign:update_pcb", f_update_pcb)
        call("save", {"filePath": FB})

    call("close_all_documents", {"save": True})
    bad = [r for r in ROWS if not r["ok"]]
    print(f"\n{len(ROWS) - len(bad)} of {len(ROWS)} real edits confirmed" + (": FAILED " + ", ".join(r["verb"] for r in bad) if bad else ""))
    if a.json:
        json.dump(ROWS, open(a.json, "w"), indent=1)
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()