← Commit history

0.2.132: repair Altium libraries with 1024 mechanical layers (altium-bridge#44); compose names a missing ffmpeg (#275)

Colby Knox ·7ede938c01 · ·parent 099c549
10 files changed +292−18
Cargo.lock+11−11
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-sys",  "roxmltree",@@ -49,7 +49,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "serde",@@ -79,7 +79,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.131"+version = "0.2.132" dependencies = [  "aiflow-sys",  "serde",@@ -120,7 +120,7 @@ dependencies = [  [[package]] name = "aiflow-sys"-version = "0.2.131"+version = "0.2.132" dependencies = [  "serde_json", ]
Cargo.toml+1−1
@@ -15,7 +15,7 @@ members = [ ]  [workspace.package]-version = "0.2.131"+version = "0.2.132" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
crates/adom-aiflow/src/main.rs+35−4
@@ -1749,6 +1749,8 @@ fn stop_running_clip(r: &mut Run, br: &Bridge, dir: &Path, why: &str) -> Option< /// The tools every clip check and cut runs. Missing ones are an error naming the tool, never a verdict /// on the footage (issue #48: with no ffprobe every clip read as "no frames" and compose dropped them all). const MEDIA_TOOLS: &[&str] = &["ffprobe", "ffmpeg"];+/// How to install the media tools (issue #275).+const MEDIA_INSTALL_HINT: &str = "ffmpeg is not installed (or not on PATH): install it, which brings ffprobe too (Debian/Ubuntu `sudo apt-get install -y ffmpeg`, macOS `brew install ffmpeg`, Windows `winget install Gyan.FFmpeg`), then compose again.";  /// The macOS KiCad bridge's window screenshots carry no `canvas` analysis: count the distinct colours /// (4 bits per channel) in the middle 60 % of the saved screenshot, where the 3D canvas is. A white or@@ -1765,8 +1767,12 @@ fn screenshot_distinct_colors(path: &str) -> Option<u64> { /// Err names the first tool of `tools` that cannot be started. fn media_tools_missing(tools: &[&str]) -> Result<(), String> {     for t in tools {-        if let Err(e) = aiflow_sys::process::Command::new(t).arg("-version").stdout(aiflow_sys::process::Stdio::null()).stderr(aiflow_sys::process::Stdio::null()).status() {-            return Err(format!("{t} is not installed or not runnable ({e}); the clips cannot be checked, cut or composed without it"));+        match aiflow_sys::process::Command::new(t).arg("-version").stdout(aiflow_sys::process::Stdio::null()).stderr(aiflow_sys::process::Stdio::null()).status() {+            Err(e) => return Err(format!("{t} is not installed or not runnable ({e}); the clips cannot be checked, cut or composed without it")),+            // issue #275 (Jinwon Kim): something answered for the name but exited 127 (not found behind a shell or a+            // wrapper) or otherwise failed `-version`: the tool is not usable either+            Ok(st) if !st.success() => return Err(format!("{t} is not installed or not runnable (`{t} -version` {st}{}); the clips cannot be checked, cut or composed without it", if st.code() == Some(127) { ", which means not found" } else { "" })),+            Ok(_) => {}         }     }     Ok(())@@ -2624,8 +2630,16 @@ fn compose_error(what: &str, outp: &Path, stderr: &str) -> String {     format!("{what} (output {}); ffmpeg said:\n{shown}", outp.display()) } +/// Issue #275: an ffmpeg failure that says the program was not there (exit status 127, or it could not start).+fn ffmpeg_missing_said(stderr: &str) -> bool {+    stderr.contains("exit status: 127") || stderr.starts_with("ffmpeg could not start")+}+ fn compose_fail(what: &str, outp: &Path) -> ! {     let stderr = FFMPEG_LAST_ERROR.with(|l| l.borrow().clone());+    if ffmpeg_missing_said(&stderr) {+        err(&compose_error(what, outp, &stderr), &[MEDIA_INSTALL_HINT.to_string()]);+    }     err(&compose_error(what, outp, &stderr), &[format!("Check that {} can be written (a relative --out is resolved against the current working directory; without --out the video is final.mp4 in the run directory), then compose again.", outp.display())]) } @@ -5935,7 +5949,7 @@ fn main() {             // the lane's pure helpers (tools/altium-lane.py: the symbol check, project-library parts), then the Altium half             let run = Run::open(&dir);             let target = target.clone().or_else(|| run.as_ref().and_then(|r| r.data["target"].as_str().map(str::to_string))).or_else(|| std::env::var("AIFLOW_TARGET").ok()).unwrap_or_default();-            let script = format!("{}\n{}\n{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-spice.py"), include_str!("../../../tools/altium-sim.py"), include_str!("../../../tools/altium-project.py"));+            let script = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-spice.py"), include_str!("../../../tools/altium-sim.py"), include_str!("../../../tools/altium-libfix.py"), include_str!("../../../tools/altium-project.py"));             let status = aiflow_sys::process::Command::new("python3").arg(lane_script("altium", &script)).args(args)                 .env("AIFLOW_RUN", &dir).env("AIFLOW_TARGET", &target).env("AIFLOW_THREAD", thread(&cli)).env("AIFLOW_EXE", std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default())                 .status().unwrap_or_else(|e| err(&format!("altium steps need python3: {e}"), &[]));@@ -7455,7 +7469,7 @@ fn main() {         }         Cmd::Compose { out, max_seconds, still_seconds, with, script } => {             thread(&cli);-            if let Err(e) = media_tools_missing(MEDIA_TOOLS) { err(&e, &["Install ffmpeg (it brings ffprobe) on this machine, then `adom-aiflow recut` (clips flagged blank only because the tools were missing are re-checked) and compose again.".into()]); }+            if let Err(e) = media_tools_missing(MEDIA_TOOLS) { err(&e, &[MEDIA_INSTALL_HINT.to_string(), "Then `adom-aiflow recut` (clips flagged blank only because the tools were missing are re-checked) and compose again.".into()]); }             let mut r = load_run(&cli);             if recover_capture_files(&mut r, &dir) > 0 { r.save().unwrap(); }             // issue #170: clips a step left for later (too big to check inside it) are checked and cut now@@ -9509,6 +9523,23 @@ mod clip_stop_tests { mod media_tools_tests {     use super::*; +    #[test]+    fn a_tool_that_answers_but_fails_is_missing_too() {+        // issue #275 (Jinwon Kim): a name that resolves but exits 127 (not found behind a wrapper) passed the check+        let dir = std::env::temp_dir().join(format!("aiflow-media-127-{}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        let shim = dir.join("aiflow-fake-ffmpeg");+        std::fs::write(&shim, "#!/bin/sh\nexit 127\n").unwrap();+        #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap(); }+        let e = media_tools_missing(&[shim.to_str().unwrap()]).unwrap_err();+        assert!(e.contains("not installed") && e.contains("which means not found"), "{e}");+        let _ = std::fs::remove_dir_all(&dir);+        assert!(ffmpeg_missing_said("ffmpeg exited with exit status: 127"));+        assert!(ffmpeg_missing_said("ffmpeg could not start: No such file or directory (os error 2)"));+        assert!(!ffmpeg_missing_said("final.mp4: Permission denied"));+        assert!(MEDIA_INSTALL_HINT.contains("apt-get install -y ffmpeg"));+    }+     #[test]     fn a_missing_ffprobe_is_an_error_naming_it_not_a_blank_clip() {         let e = media_tools_missing(&["aiflow-no-such-ffprobe"]).unwrap_err();
docs/altium-lane.md+5
@@ -173,3 +173,8 @@ adom-aiflow altium simulate --sources sim/altium-sources.json [--loads sim/altiu - `--expect NET=value+-tol` checks the result (`NET.ripple=` for a transient's peak to peak); a mismatch answers ERROR with both numbers. - The result goes to `altium/sim/altium-<analysis>.json` in the run with the copy's path and Altium's netlist (diff it against your ngspice deck). Record it with `adom-aiflow evidence add --kind simulation --file <it>`. - A part with no model and no generic stand-in (an IC whose vendor model is encrypted) stops the analysis and is named: attach an unencrypted model in the library step, or simulate that block in ngspice.++## Libraries with 1024 mechanical layers (altium-bridge#44)++altium-bridge before 0.2.119 filled a PcbLib its footprint and layer-map verbs touched with all 1024 mechanical layers (1048 layer records instead of about 56), and Altium could hang attaching a STEP to such a library. `altium library` checks a library it reuses: the saved file names its layers and footprints, so a library whose mechanical layers reach 1000 or more is copied footprint by footprint into a fresh one (`altium_xcopy_footprint`), checked, and swapped in at the same path, with the old file kept as `<name>.bloated.PcbLib`. The library's folder is closed (saved) in Altium before the copy and before the swap, so Altium's in-memory copy cannot write the old library back. The repair needs altium-bridge 0.2.120; on an older bridge a bloated library is named and left alone, and a bridge before 0.2.119 is warned about, since it adds the layers again.+
docs/release-0.2.132.mdadded+16
@@ -0,0 +1,16 @@+# adom-aiflow 0.2.132++## Altium libraries: repair the 1024 mechanical layers (altium-bridge#44)++altium-bridge up to 0.2.118 wrote all 1024 mechanical layers into any PcbLib its footprint or layer-map verbs touched: a fresh library grew from 56 layer records to 1048, and Altium hung attaching a STEP to one. 0.2.119 fixes the bridge; this release fixes the libraries AI Flow already has.++- `altium library` reads a library it reuses from the desktop: the saved file names its layer records and footprints. When its mechanical layers reach 1000 or more, the library's folder is closed (saved) in Altium, every footprint is copied into a fresh library with `altium_xcopy_footprint` (which carries only the layers each footprint uses, with pads, pad stacks, 3D bodies, height and description), the copy is read back and checked (no extra layers, every footprint present), the folder is closed again, and the fresh library takes the old one's path. The old file stays beside it as `<name>.bloated.PcbLib`.+- Nothing is replaced unless the copy checks out: a failed copy, a fresh library that is still bloated or missing a footprint, or a file Altium will not let go stops with the library untouched and says where the attempt is.+- A clean library is only read and left alone.+- The repair needs altium-bridge 0.2.120 (it makes the fresh library and keeps the footprint height). On an older bridge a bloated library is named with a warning and left as it is, and a bridge before 0.2.119 is named before the library step writes anything, since it adds the layers again.++Tested live on the test desktop (Altium Designer 26, altium-bridge 0.2.120), with the library open in Altium: the folder closed, the footprint copied, checked (56 layer records, mechanical up to 32, the 3D model reference kept), and swapped in with the old file kept. The bloat check was forced for that run, since the bridge no longer makes a bloated library; the census and every refusal are covered by tests/altium-libfix.py.++## compose: a missing ffmpeg says so (#275)++`compose` checked only that ffmpeg could be started, so a name that answered but exited 127 (not found behind a shell or a wrapper) passed, every segment then failed, and the hint pointed at the output path. Now a tool whose `-version` fails counts as missing, and a compose failure that says ffmpeg was not there (exit status 127, or it could not start) gives the install command (Debian/Ubuntu `sudo apt-get install -y ffmpeg`, macOS `brew install ffmpeg`, Windows `winget install Gyan.FFmpeg`) instead.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.131",+  "version": "0.2.132",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.131",+  "version": "0.2.132",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
tests/altium-libfix.pyadded+101
@@ -0,0 +1,101 @@+"""tools/altium-libfix.py without Altium: the layer census, the old-bridge note and the repair's steps (altium-bridge#44).+  python3 tests/altium-libfix.py"""+import re, sys, tempfile+from pathlib import Path++TOOLS = Path(__file__).resolve().parent.parent / 'tools'+++class Stop(Exception):+    pass+++def lib(records, high, fps):+    """The bytes a saved PcbLib carries for its layers and footprints (the rest does not matter here)."""+    b = b''.join(b'|LAYER_V8_%dNAME=Mechanical %d|' % (i, i) for i in range(records))+    b += b''.join(b'|LAYER_V8_%dLAYERID=MECHANICAL%d|' % (i, i + 1) for i in range(high))+    return b + b''.join(b'|PATTERN=' + f.encode() + b'|' for f in fps)+++def harness(files, fail_copy=None, swap_ok=True):+    """The module with ab/err/say/win/STATE stand-ins: `files` maps a desktop path to the bytes a pull returns."""+    ns = {'re': re, 'json': __import__('json')}+    calls, said = [], []+    tmp = Path(tempfile.mkdtemp(prefix='aiflow-libfix-'))+    def ab(verb, args, timeout=600):+        calls.append((verb, args))+        if verb == 'pull_file':+            src = args['filePaths'][0].replace('\\', '/')+            if src in files: (Path(args['saveTo']) / src.split('/')[-1]).write_bytes(files[src])+            return {'success': True}+        if verb == 'altium_xcopy_footprint':+            if args['from'] == fail_copy: return {'success': False, 'error': 'no such footprint'}+            return {'success': True, 'data': {'ok': True}}+        if verb == 'shell_execute' and 'move' in args['command']:+            return {'stdout': 'AIFLOW-SWAPPED' if swap_ok else '', 'stderr': '' if swap_ok else 'in use'}+        return {'success': True}+    def err(msg, hints=()):+        said.append('ERROR: ' + msg); raise Stop(msg)+    ns.update(ab=ab, err=err, say=lambda m: said.append(m), win=lambda p: p.replace('/', '\\'), STATE=tmp)+    exec((TOOLS / 'altium-libfix.py').read_text(), ns)+    return ns, calls, said+++def main():+    lib_path = 'C:/Box/library/Proj.PcbLib'+    clean, bloated = lib(56, 32, ['PCBComponent_1', 'R0603']), lib(1048, 1024, ['R0603', 'SOT-23'])+    ns, _, _ = harness({})+    assert ns['layer_census'](clean) == (56, 32, ['PCBComponent_1', 'R0603'])+    assert not ns['is_bloated'](clean) and ns['is_bloated'](bloated)+    # the note names a bridge that still bloats, and only that+    assert '0.2.118' in ns['old_bridge_note']('0.2.118') and 'bridge_update' in ns['old_bridge_note']('0.2.118')+    assert ns['old_bridge_note']('0.2.119') is None and ns['old_bridge_note']('0.2.120') is None and ns['old_bridge_note'](None) is None+    assert not ns['can_repair']('0.2.119') and ns['can_repair']('0.2.120') and not ns['can_repair'](None)+    # an older bridge: a bloated library is named, nothing is copied or moved+    ns, calls, said = harness({lib_path: bloated})+    out = ns['repair_pcblib'](lib_path, repair=False)+    assert out == {'bloated': True, 'repaired': False, 'records': 1048, 'highestMechanical': 1024}, out+    assert [c[0] for c in calls] == ['pull_file'] and any('0.2.120' in s for s in said)++    # a clean library is read and left alone+    ns, calls, _ = harness({lib_path: clean})+    assert ns['repair_pcblib'](lib_path) == {'bloated': False, 'records': 56, 'highestMechanical': 32}+    assert [c[0] for c in calls] == ['pull_file']+    # no library on the desktop: nothing to do+    ns, _, _ = harness({})+    assert ns['repair_pcblib'](lib_path) is None++    # a bloated one: every footprint copied (the factory stray left), the copy checked, both closed, swapped+    fresh = 'C:/Box/library/Proj_repaired.PcbLib'+    ns, calls, said = harness({lib_path: bloated, fresh: lib(56, 32, ['R0603', 'SOT-23'])})+    out = ns['repair_pcblib'](lib_path)+    assert out['repaired'] and out['footprints'] == 2 and out['after'] == {'records': 56, 'highestMechanical': 32}, out+    assert out['kept'] == 'C:/Box/library/Proj.bloated.PcbLib'+    assert [c[1]['from'] for c in calls if c[0] == 'altium_xcopy_footprint'] == ['R0603', 'SOT-23']+    move = [c[1]['command'] for c in calls if c[0] == 'shell_execute' and 'move' in c[1]['command']][0]+    assert move.index('Proj.bloated.PcbLib') < move.index('Proj_repaired.PcbLib'), move+    assert any('altium-bridge#44' in s for s in said), said+    # the library folder is closed (saved) in Altium before the copy and again before the swap+    verbs = [c[0] for c in calls]+    assert verbs.count('altium_close_all_documents') == 2 and verbs.index('altium_close_all_documents') < verbs.index('altium_xcopy_footprint')+    assert [c[1] for c in calls if c[0] == 'altium_close_all_documents'][0] == {'under': 'C:\\Box\\library', 'save': True}++    # a copy that fails stops before anything is swapped+    ns, calls, said = harness({lib_path: bloated, fresh: lib(56, 32, ['R0603'])}, fail_copy='SOT-23')+    try: ns['repair_pcblib'](lib_path); raise AssertionError('should stop')+    except Stop as e: assert 'SOT-23' in str(e)+    assert not any(c[0] == 'shell_execute' and 'move' in c[1]['command'] for c in calls)+    # a fresh library still bloated, or missing a footprint, is refused before the swap+    ns, calls, _ = harness({lib_path: bloated, fresh: lib(56, 32, ['R0603'])})+    try: ns['repair_pcblib'](lib_path); raise AssertionError('should stop')+    except Stop as e: assert 'missing SOT-23' in str(e), e+    assert not any(c[0] == 'shell_execute' and 'move' in c[1]['command'] for c in calls)+    # a swap Altium blocks says where the fresh library is+    ns, _, _ = harness({lib_path: bloated, fresh: lib(56, 32, ['R0603', 'SOT-23'])}, swap_ok=False)+    try: ns['repair_pcblib'](lib_path); raise AssertionError('should stop')+    except Stop as e: assert 'could not swap' in str(e)+    print('OK')+++if __name__ == '__main__':+    main()
tools/altium-libfix.pyadded+109
@@ -0,0 +1,109 @@+"""altium-libfix: a project PcbLib that altium-bridge before 0.2.119 filled with all 1024 mechanical layers+(altium-bridge#44: its footprint and layer-map verbs looked layers up by number, which creates them, and the next+save kept them; a library went from 56 layer records to 1048 and Altium hung attaching a STEP to one).++`altium library` checks a library it reuses: the saved file names its layers (`LAYER_V8_<n>NAME=`) and its+footprints (`PATTERN=<name>`). A library whose mechanical layers reach MECHANICAL1000 or more is copied footprint by+footprint into a fresh library with `altium_xcopy_footprint` (which carries only the layers each footprint's+graphics use), checked, and swapped in at the same path; the old file is kept beside it as <name>.bloated.PcbLib.+A bridge before 0.2.119 is named before the library step writes anything, since every footprint it writes adds+the layers again.+"""++FIXED_IN = (0, 2, 119)+# the repair needs 0.2.120: xcopy_footprint makes the fresh library itself and keeps the footprint's height+REPAIR_FROM = (0, 2, 120)+BLOAT_MECH = 1000+FACTORY_STRAY = 'PCBComponent_1'+++def layer_census(blob):+    """(layer records, highest mechanical layer, footprint names) of a saved PcbLib's bytes."""+    recs = len(re.findall(rb'LAYER_V8_\d+NAME=', blob))+    mech = [int(x) for x in re.findall(rb'MECHANICAL(\d+)', blob)]+    fps = sorted(set(m.decode('latin1') for m in re.findall(rb'PATTERN=([^|\x00\r\n]{1,80})', blob)))+    return recs, (max(mech) if mech else 0), fps+++def is_bloated(blob):+    return layer_census(blob)[1] >= BLOAT_MECH+++def version_tuple(v):+    return tuple(int(x) for x in re.findall(r'\d+', str(v or ''))[:3])+++def old_bridge_note(ver):+    """The library step's warning for a bridge that still adds the 1024 layers, else None."""+    t = version_tuple(ver)+    if not t or t >= FIXED_IN: return None+    return ('altium-bridge %s writes every mechanical layer (1024) into a library its footprint verbs touch (altium-bridge#44, '+            'fixed in 0.2.119 and later): update it when that reaches your channel, `adom-bridge bridge_update \'{"name":"altium"}\'`; '+            'from 0.2.120 the library step repairs a library that already has them' % ver)+++def can_repair(ver):+    t = version_tuple(ver)+    return bool(t) and t >= REPAIR_FROM+++def close_folder(path):+    """Close (saving) every document Altium holds under the library's folder: Altium works on its in-memory copy, and a+    later save of it would write the old library back over the new file."""+    folder = path.replace('/', '\\').rsplit('\\', 1)[0]+    ab('altium_close_all_documents', {'under': folder, 'save': True}, timeout=300)+++def pull_lib(path, into):+    """The desktop file `path` copied into the local folder `into`; its bytes, or None when it cannot be read."""+    into.mkdir(parents=True, exist_ok=True)+    name = path.replace('\\', '/').split('/')[-1]+    local = into / name+    if local.exists(): local.unlink()+    ab('pull_file', {'filePaths': [win(path)], 'saveTo': str(into.resolve())}, timeout=600)+    return local.read_bytes() if local.is_file() else None+++def repair_pcblib(pcb_lib, repair=True):+    """Check the project PcbLib at `pcb_lib` (a desktop path) and, when `repair` (altium-bridge 0.2.120+), repair it when it+    carries the 1024 layers. Returns None when there is no library to read, else what was found and done."""+    work = STATE / 'libcheck'+    blob = pull_lib(pcb_lib, work)+    if blob is None: return None+    recs, high, fps = layer_census(blob)+    if high < BLOAT_MECH:+        return {'bloated': False, 'records': recs, 'highestMechanical': high}+    if not repair:+        say('WARNING: %s carries %d layer records, mechanical layers up to %d (altium-bridge#44); AI Flow repairs it from altium-bridge 0.2.120'+            % (pcb_lib, recs, high))+        return {'bloated': True, 'repaired': False, 'records': recs, 'highestMechanical': high}+    names = [f for f in fps if f != FACTORY_STRAY]+    if not names: err('%s carries %d layer records (mechanical up to %d) and names no footprint to copy out' % (pcb_lib, recs, high),+                      ['Rebuild it: `altium library --again`.'])+    stem = pcb_lib[:-len('.PcbLib')] if pcb_lib.endswith('.PcbLib') else pcb_lib+    fresh, kept = stem + '_repaired.PcbLib', stem + '.bloated.PcbLib'+    say('%s carries %d layer records, mechanical layers up to %d (altium-bridge#44): copying its %d footprint(s) into a fresh library'+        % (pcb_lib, recs, high, len(names)))+    close_folder(pcb_lib)+    ab('shell_execute', {'command': 'if exist "%s" del /f /q "%s"' % (win(fresh), win(fresh))})+    for n in names:+        r = ab('altium_xcopy_footprint', {'fromLib': win(pcb_lib), 'from': n, 'to': n, 'toLib': win(fresh)}, timeout=600)+        d = r.get('data') if isinstance(r.get('data'), dict) else r+        if not r.get('success') or d.get('ok') is False:+            err('repairing %s: altium_xcopy_footprint %s failed: %s' % (pcb_lib, n, str(r.get('error') or r.get('errorCode') or d)[:300]),+                ['The library is untouched. Needs altium-bridge 0.2.119 or newer; `altium library --again` rebuilds it from the parts instead.'])+    ab('altium_save', {'path': win(fresh)}, timeout=300)+    fb = pull_lib(fresh, work)+    if fb is None: err('repairing %s: the fresh library %s could not be read back' % (pcb_lib, fresh), ['The library is untouched.'])+    frecs, fhigh, ffps = layer_census(fb)+    missing = sorted(set(names) - set(ffps))+    if fhigh >= BLOAT_MECH or missing:+        err('repairing %s: the fresh library is not right (%d layer records, mechanical up to %d%s)' % (pcb_lib, frecs, fhigh, ('; missing ' + ', '.join(missing)) if missing else ''),+            ['The library is untouched; %s is the attempt. Update altium-bridge to 0.2.119 or newer.' % fresh])+    close_folder(pcb_lib)+    r = ab('shell_execute', {'command': 'move /Y "%s" "%s" && move /Y "%s" "%s" && echo AIFLOW-SWAPPED' % (win(pcb_lib), win(kept), win(fresh), win(pcb_lib))})+    if 'AIFLOW-SWAPPED' not in str(r.get('stdout') or r.get('output') or ''):+        err('repairing %s: could not swap the fresh library in (Altium may still hold the file): %s' % (pcb_lib, str(r.get('stderr') or r.get('error') or r)[:300]),+            ['The fresh library is %s. Close the library in Altium, then run `altium library` again.' % fresh])+    return {'bloated': True, 'repaired': True, 'records': recs, 'highestMechanical': high, 'footprints': len(names),+            'after': {'records': frecs, 'highestMechanical': fhigh}, 'kept': kept}
tools/altium-project.py+12
@@ -124,6 +124,15 @@ def cmd_library(a):     kept_specs = STATE / 'symbols'; kept_specs.mkdir(parents=True, exist_ok=True)     bdir, sch_lib, pcb_lib = lib_paths(st)     added, kept, unverified, from_lib = [], [], {}, []+    # altium-bridge#44: a bridge before 0.2.119 writes all 1024 mechanical layers into a library; a library it already+    # bloated is copied into a fresh one (only on a bridge that no longer does it)+    ver = ab('altium_status', {}, timeout=120).get('bridgeVersion')+    old_note = old_bridge_note(ver)+    if old_note: say('WARNING: ' + old_note)+    fix = None+    if st.get('pcbLib'):+        fix = repair_pcblib(pcb_lib, repair=can_repair(ver))+        if fix: st['pcbLibCheck'] = fix; save_state(st)     # the `parts` step's choice per MPN: the wiki page it matched, or the board's project library     rows = parts_rows(run_data())     work = {}@@ -189,6 +198,9 @@ def cmd_library(a):     st['schLib'], st['pcbLib'] = sch_lib, pcb_lib     save_state(st)     prove('library', {'name': name, 'parts': len(st['parts']), 'tool': 'altium', 'projectLibParts': from_lib, 'spiceModels': sum(1 for p in st['parts'].values() if (p.get('sim') or {}).get('attached'))})+    if fix and fix.get('repaired'):+        say('repaired %s: %d layer records (mechanical up to %d) became %d (up to %d), %d footprint(s) copied; the old file is kept as %s'+            % (pcb_lib, fix['records'], fix['highestMechanical'], fix['after']['records'], fix['after']['highestMechanical'], fix['footprints'], fix['kept']))     ok('library %s: %d part(s) (%d added, %d kept%s): %s and %s' % (name, len(st['parts']), len(added), len(kept),                                                                     '; %d from the board\'s project library: %s' % (len(from_lib), ', '.join(from_lib)) if from_lib else '', pcb_lib, sch_lib),        spice_summary(st['parts']) + ['No distributor number yet: ' + '; '.join('%s %s' % (m, ' '.join(v)) for m, v in unverified.items()) + '. Run `altium library` again when the services are back, or add the numbers to the part\'s wiki page (a project-library part: "mouser"/"digikey"/"lcsc" in its provenance.json entry).' if unverified else '',