by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
← Commit history
0.2.107: set_design_rules scope:board and raiseOnly (adom-aiflow#228)
9 files changed
+144−33
CHANGELOG.md+8@@ -1,5 +1,13 @@ # Changelog +## 0.2.107++- **`altium_set_design_rules` can leave a board's own rules alone** (adom-aiflow#228). It wrote each value into every rule of its kind, so raising a fab floor also overwrote a board's tighter hand-set rules and its net-class width rules. Two options, both off by default:+ - `scope:"board"` writes only the board-wide rule of each kind (scope All). Net-class, net and query rules keep their own values (`scopedLeft`). `all-only` means the same. A kind that has only scoped rules is left alone and listed in `skipped[]`: a new board-wide rule would land first in Altium's priority order and override them.+ - `raiseOnly:true` raises a minimum only where it is below the value given, and never lowers a tighter one (`rulesKept`). Preferred and maximum values move only when they would fall below the new minimum.+- Each `landed[]` entry now gives `rulesWritten`, `rulesKept`, `scopedLeft` and `created`.+- Tested on Altium Designer 26.11.1 with a board-wide width and clearance rule plus an N1 width rule and a GND clearance rule. With both options, the board-wide width rose from 0.254 to 0.3 mm, the clearance and hole-to-hole rules already tighter were kept, a missing annular-ring rule was created, and the N1 and GND rules kept 0.4 and 0.5 mm. Without them, every rule is still written as before.+ ## 0.2.106 - Includes 0.2.105 (Altium on any drive, #40).
bridge-rs/src/main.rs+1−1@@ -82,7 +82,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.106";+pub const BRIDGE_VERSION: &str = "0.2.107"; fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> { let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/routing.rs+48−3@@ -1346,15 +1346,27 @@ pub fn set_design_rules(args: &Value) -> Value { plan.push(("polyconnect", vec![("a", a.to_string()), ("b", w.to_string()), ("c", e.to_string())])); } if plan.is_empty() { return err("bad_args", "no rule values given".into(), "Pass any of clearance, trackWidth{min,preferred,max}, via{diameter{...}, drill{...}}, hole{min,max}, annularRing, holeToHole, edgeClearance (mm), polygonConnect (direct|relief|none or {style, reliefWidth, reliefEntries})."); }+ let (board_only, raise_only) = match rule_mode(args) { Ok(m) => m, Err(e) => return e }; let mut landed = Vec::new(); let mut failed = Vec::new();+ let mut skipped = Vec::new(); let mut first_shot: Option<Value> = None; for (kind, vals) in plan { let mut params: Vec<(&str, String)> = vec![("kind", kind.to_string())]; params.extend(vals);+ if board_only { params.push(("scope", "board".into())); }+ if raise_only { params.push(("raise", "1".into())); } let r = agent::call("set_rule", ¶ms, None, Duration::from_secs(60)); match r.get("data") {- Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => landed.push(json!({"kind": kind, "rulesWritten": d["rulesWritten"]})),+ Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => {+ let scoped = d["scopedLeft"].as_i64().unwrap_or(0);+ if board_only && d["rulesWritten"].as_i64() == Some(0) && d["rulesKept"].as_i64() == Some(0) && scoped > 0 {+ skipped.push(json!({"kind": kind, "reason": "no_board_wide_rule", "scopedRules": scoped,+ "note": "this board has only scoped rules of this kind (net class, net or query) and no board-wide one: nothing was written, since a new rule would outrank them"}));+ } else {+ landed.push(json!({"kind": kind, "rulesWritten": d["rulesWritten"], "rulesKept": d["rulesKept"], "scopedLeft": scoped, "created": d["created"]}));+ }+ } _ => { if let Some(shot) = r.get("errorShot") { first_shot.get_or_insert(shot.clone()); } failed.push(json!({"kind": kind, "errorCode": r.get("errorCode").cloned().unwrap_or(Value::Null), "error": r.get("error").cloned().or_else(|| r.get("data").and_then(|d| d.get("error")).cloned()).unwrap_or(Value::Null)}));@@ -1364,10 +1376,43 @@ pub fn set_design_rules(args: &Value) -> Value { } } let rules = agent::call("read_rules", &[], None, Duration::from_secs(60));- json!({"success": failed.is_empty(), "errorCode": if failed.is_empty() { Value::Null } else { json!("partial_rules") }, "landed": landed, "failed": failed,+ let hint = match (board_only, raise_only) {+ (false, false) => "Every rule of each kind now carries these values (scopes kept). failed[] names any kind this Altium build refused; the rest landed.",+ (true, false) => "Each kind's board-wide rule (scope All) carries these values; net-class, net and query rules kept their own (scopedLeft). skipped[] names kinds with no board-wide rule.",+ (false, true) => "Minimums were raised where they were below these values and never lowered (rulesKept: already as tight or tighter); every rule of each kind was considered.",+ (true, true) => "Each kind's board-wide rule was raised where it was below these values, never lowered (rulesKept: already as tight or tighter); scoped rules kept their own (scopedLeft). skipped[] names kinds with no board-wide rule.",+ };+ json!({"success": failed.is_empty(), "errorCode": if failed.is_empty() { Value::Null } else { json!("partial_rules") }, "landed": landed, "failed": failed, "skipped": skipped,+ "scope": if board_only { "board" } else { "all" }, "raiseOnly": raise_only, "rules": rules.get("data").and_then(|d| d.get("rules")).cloned().unwrap_or(Value::Null), "errorShot": first_shot.unwrap_or(Value::Null),- "_hint": "Every rule of each kind now carries the fab's values (scopes kept). failed[] names any kind this Altium build refused; the rest landed."})+ "_hint": hint})+}++/// set_design_rules' scope ("all", the default: every rule of a kind; "board": only its board-wide rule) and raiseOnly.+/// "all-only" (AI Flow's name) means "board". Pure.+pub fn rule_mode(args: &Value) -> Result<(bool, bool), Value> {+ let board = match args.get("scope").and_then(|v| v.as_str()).map(|s| s.trim().to_lowercase()) {+ None => false,+ Some(s) if s.is_empty() || s == "all" || s == "every" => false,+ Some(s) if s == "board" || s == "all-only" || s == "board-wide" => true,+ Some(s) => return Err(err("bad_args", format!("scope \"{s}\" is not all or board"), "scope: \"all\" (every rule of each kind, the default) or \"board\" (only the board-wide rule, scope All; net-class and net rules keep their own)")),+ };+ Ok((board, args.get("raiseOnly").and_then(|v| v.as_bool()) == Some(true)))+}++#[cfg(test)]+mod rule_mode_tests {+ use super::*;++ #[test]+ fn scope_and_raise_only_read_as_documented() {+ assert_eq!(rule_mode(&json!({})).unwrap(), (false, false));+ assert_eq!(rule_mode(&json!({"scope": "board", "raiseOnly": true})).unwrap(), (true, true));+ assert_eq!(rule_mode(&json!({"scope": "all-only"})).unwrap(), (true, false), "AI Flow's name");+ assert_eq!(rule_mode(&json!({"scope": "All"})).unwrap(), (false, false));+ assert!(rule_mode(&json!({"scope": "nets"})).is_err());+ } } #[cfg(test)]
bridge-rs/src/verbs.rs+2−2@@ -603,8 +603,8 @@ fn describe() -> Value { json!({"vertices": "int", "revision": "string", "outlineEdges": "[{kind: line|arc, ...}]"}), 120, "Rounding corners: pass the same rectangle with cornerRadius (1 mm is a common default).", &["build_board", "routing_state", "repour"], &["Needs the board current."], json!({"outline": {"rect": [0, 0, 28, 20], "cornerRadius": 1}})), verb_doc("set_design_rules", "Write a fab's design rules into the current board: clearance, track width, routing via style, hole size, annular ring, hole-to-hole and board-edge clearance (mm).",- json!({"fab": "jlcpcb - fill every value left out from JLCPCB's published limits for this board's layers and copper weight", "costlier": "with fab: allow JLCPCB's surcharged small vias (0.15/0.25 mm) instead of 0.3/0.5", "clearance": "mm", "trackWidth": "{min, preferred?, max?} mm", "via": "{diameter:{min, preferred?, max?}, drill:{min, preferred?, max?}} mm", "hole": "{min, max?} mm", "annularRing": "mm", "holeToHole": "mm", "edgeClearance": "mm - copper to the board edge (the rule it creates is scoped OnCopper; silkscreen keeps its own rules)", "polygonConnect": "the board's catch-all polygon connect style: direct|relief|none, or {style, reliefWidth: mm, reliefEntries: 2|4} (per-pour rules from apply_pours keep theirs)"}),- json!({"landed": "[{kind, rulesWritten}]", "failed": "[{kind, error}]", "rules": "the board's rules after"}), 300,+ json!({"fab": "jlcpcb - fill every value left out from JLCPCB's published limits for this board's layers and copper weight", "costlier": "with fab: allow JLCPCB's surcharged small vias (0.15/0.25 mm) instead of 0.3/0.5", "scope": "all (default): every rule of each kind, each keeping its own scope | board: only the board-wide rule of each kind (scope All), so net-class, net and query rules keep their own values; a kind with only scoped rules is skipped, not created (a new rule would outrank them). all-only is the same as board", "raiseOnly": "bool, default false: raise a minimum only where it is below the value given, never lower a tighter one; preferred and maximum values move only when they would fall below the new minimum", "clearance": "mm", "trackWidth": "{min, preferred?, max?} mm", "via": "{diameter:{min, preferred?, max?}, drill:{min, preferred?, max?}} mm", "hole": "{min, max?} mm", "annularRing": "mm", "holeToHole": "mm", "edgeClearance": "mm - copper to the board edge (the rule it creates is scoped OnCopper; silkscreen keeps its own rules)", "polygonConnect": "the board's catch-all polygon connect style: direct|relief|none, or {style, reliefWidth: mm, reliefEntries: 2|4} (per-pour rules from apply_pours keep theirs)"}),+ json!({"landed": "[{kind, rulesWritten, rulesKept, scopedLeft, created}]", "failed": "[{kind, error}]", "skipped": "[{kind, reason: no_board_wide_rule, scopedRules}] with scope board", "scope": "all|board", "raiseOnly": "bool", "rules": "the board's rules after"}), 300, "AI Flow's `rules use` calls this with the fab pack's numbers (adom/pcb-design-rules). Each kind is written separately, so one this Altium build lacks fails alone.", &["read_rules", "rules_by_kind", "build_board"], &["Needs the board current.", "Every existing rule of a kind gets the values; rule scopes are kept, except an Adom edge rule an earlier bridge scoped to All, which becomes OnCopper (#26)."], json!({"clearance": 0.15, "trackWidth": {"min": 0.15}, "via": {"diameter": {"min": 0.45}, "drill": {"min": 0.2}}, "hole": {"min": 0.2}, "edgeClearance": 0.3})), verb_doc("add_rule", "Add one SCOPED design rule that set_design_rules' board-wide values cannot express: a net's or class's clearance or width, a length limit, a matched-length group, a differential pair's width and gap, a routing via style, or how a net's pads join a pour (direct, relief, none).",
package.json+1−1@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.106",+ "version": "0.2.107", "type": "app", "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.", "tags": [
page.json+1−1@@ -4,7 +4,7 @@ "type": "app", "title": "Altium Bridge: AI for Altium Designer", "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",- "version": "0.2.106",+ "version": "0.2.107", "hero": { "type": "image", "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.106+0.2.107
src/agent/AdomAgent.pas.tmpl+81−23@@ -7599,24 +7599,39 @@ Begin Result := '{' + JRaw('ok', JBool(N >= 3)) + ',' + JRaw('vertices', IntToStr(N)) + '}'; End; -{ set_rule: write ONE design rule kind on the current board, every rule of that kind (each scope- keeps its own scope; the values are the fab's floor). One kind per call, so a property this- Altium build does not know fails alone. kind = clearance | width | via | hole | ring |- holetohole | edge. Values are RAW units: a, b, c (min / preferred / max where they apply),- d, e, f (via drill min / preferred / max). }+{ set_rule: write ONE design rule kind on the current board. One kind per call, so a property this+ Altium build does not know fails alone. kind = clearance | width | via | hole | ring | holetohole | edge | polyconnect.+ Values are RAW units: a, b, c (min / preferred / max where they apply), d, e, f (via drill min / preferred / max).+ scope = all (default): every rule of the kind, each keeping its own scope. scope = board: only the board-wide rule+ (All / All; an edge rule's OnCopper / All), so net-class, net and query rules keep their own values (aiflow#228).+ raise = 1: a minimum is only raised, never lowered; preferred and maximum values move only when they would fall+ below the new minimum. A rule left as it was counts in kept, not written. }+Function RuleIsBoardWide(Rule : IPCB_Rule) : Boolean;+Begin+ Result := ((Rule.Scope1Expression = 'All') Or (Rule.Scope1Expression = 'OnCopper')) And+ ((Rule.Scope2Expression = 'All') Or (Rule.Scope2Expression = ''));+End;++Function MaxI(X, Y : Integer) : Integer;+Begin+ If X > Y Then Result := X Else Result := Y;+End;+ Function CmdSetRule(Lines : TStringList) : String; Var Board : IPCB_Board; BIt : IPCB_BoardIterator; Rule : IPCB_Rule; Kind : String;- A, B, C, D, E, F, N, Want : Integer;- Created : Boolean;+ A, B, C, D, E, F, N, Want, Kept, Scoped, L, V0, V1, V2 : Integer;+ Created, BoardOnly, RaiseOnly, Changed : Boolean; Begin Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End; Created := False; Kind := Param(Lines, 'kind');+ BoardOnly := (Param(Lines, 'scope') = 'board') Or (Kind = 'polyconnect');+ RaiseOnly := (Param(Lines, 'raise') = '1') And (Kind <> 'polyconnect'); A := StrToIntDef(Param(Lines, 'a'), 0); B := StrToIntDef(Param(Lines, 'b'), 0); C := StrToIntDef(Param(Lines, 'c'), 0); D := StrToIntDef(Param(Lines, 'd'), 0); E := StrToIntDef(Param(Lines, 'e'), 0); F := StrToIntDef(Param(Lines, 'f'), 0); If Kind = 'clearance' Then Want := eRule_Clearance@@ -7628,7 +7643,7 @@ Begin Else If Kind = 'edge' Then Want := eRule_BoardOutlineClearance Else If Kind = 'polyconnect' Then Want := eRule_PolygonConnectStyle Else Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','unknown rule kind: ' + Kind) + '}'; Exit; End;- N := 0;+ N := 0; Kept := 0; Scoped := 0; PCBServer.PreProcess; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRuleObject));@@ -7637,26 +7652,67 @@ Begin Rule := BIt.FirstPCBObject; While Rule <> Nil Do Begin- { polyconnect sets the board's catch-all (All / All) rule only: per-pour rules keep theirs }- If (Rule.RuleKind = Want) And ((Kind <> 'polyconnect') Or ((Rule.Scope1Expression = 'All') And (Rule.Scope2Expression = 'All'))) Then+ If (Rule.RuleKind = Want) And BoardOnly And (Not RuleIsBoardWide(Rule)) Then Scoped := Scoped + 1+ Else If Rule.RuleKind = Want Then Begin+ Changed := True; Rule.BeginModify;- If Kind = 'clearance' Then Rule.Gap := A+ If Kind = 'clearance' Then+ Begin+ If RaiseOnly Then Begin Changed := Rule.Gap < A; Rule.Gap := MaxI(Rule.Gap, A); End Else Rule.Gap := A;+ End Else If Kind = 'width' Then Begin- SetWidthAllLayers(Rule, A, B, C);+ If RaiseOnly Then+ Begin+ Changed := False;+ For L := eTopLayer To eBottomLayer Do+ Begin+ V0 := MaxI(Rule.MinWidth[L], A); V1 := MaxI(Rule.FavoredWidth[L], V0); V2 := MaxI(Rule.MaxWidth[L], V1);+ If (V0 <> Rule.MinWidth[L]) Or (V1 <> Rule.FavoredWidth[L]) Or (V2 <> Rule.MaxWidth[L]) Then Changed := True;+ Rule.MinWidth[L] := V0; Rule.FavoredWidth[L] := V1; Rule.MaxWidth[L] := V2;+ End;+ End+ Else SetWidthAllLayers(Rule, A, B, C); End Else If Kind = 'via' Then Begin- Rule.MinWidth := A; Rule.PreferedWidth := B; Rule.MaxWidth := C;- Rule.MinHoleWidth := D; Rule.PreferedHoleWidth := E; Rule.MaxHoleWidth := F;+ If RaiseOnly Then+ Begin+ V0 := MaxI(Rule.MinWidth, A); V1 := MaxI(Rule.PreferedWidth, V0); V2 := MaxI(Rule.MaxWidth, V1);+ Changed := (V0 <> Rule.MinWidth) Or (V1 <> Rule.PreferedWidth) Or (V2 <> Rule.MaxWidth);+ Rule.MinWidth := V0; Rule.PreferedWidth := V1; Rule.MaxWidth := V2;+ V0 := MaxI(Rule.MinHoleWidth, D); V1 := MaxI(Rule.PreferedHoleWidth, V0); V2 := MaxI(Rule.MaxHoleWidth, V1);+ If (V0 <> Rule.MinHoleWidth) Or (V1 <> Rule.PreferedHoleWidth) Or (V2 <> Rule.MaxHoleWidth) Then Changed := True;+ Rule.MinHoleWidth := V0; Rule.PreferedHoleWidth := V1; Rule.MaxHoleWidth := V2;+ End+ Else+ Begin+ Rule.MinWidth := A; Rule.PreferedWidth := B; Rule.MaxWidth := C;+ Rule.MinHoleWidth := D; Rule.PreferedHoleWidth := E; Rule.MaxHoleWidth := F;+ End;+ End+ Else If Kind = 'hole' Then+ Begin+ If RaiseOnly Then+ Begin+ V0 := MaxI(Rule.MinLimit, A); V2 := MaxI(Rule.MaxLimit, V0);+ Changed := (V0 <> Rule.MinLimit) Or (V2 <> Rule.MaxLimit);+ Rule.MinLimit := V0; Rule.MaxLimit := V2;+ End+ Else Begin Rule.MinLimit := A; Rule.MaxLimit := C; End;+ End+ Else If Kind = 'ring' Then+ Begin+ If RaiseOnly Then Begin Changed := Rule.Minimum < A; Rule.Minimum := MaxI(Rule.Minimum, A); End Else Rule.Minimum := A;+ End+ Else If Kind = 'holetohole' Then+ Begin+ If RaiseOnly Then Begin Changed := Rule.Gap < A; Rule.Gap := MaxI(Rule.Gap, A); End Else Rule.Gap := A; End- Else If Kind = 'hole' Then Begin Rule.MinLimit := A; Rule.MaxLimit := C; End- Else If Kind = 'ring' Then Rule.Minimum := A- Else If Kind = 'holetohole' Then Rule.Gap := A Else If Kind = 'edge' Then Begin- Rule.Gap := A;+ If RaiseOnly Then Begin Changed := Rule.Gap < A; Rule.Gap := MaxI(Rule.Gap, A); End Else Rule.Gap := A; { the fab's edge clearance is copper to edge (KiCad's edge_clearance): an Adom edge rule an earlier bridge scoped to All also caught silkscreen (adom/altium-bridge#26) } If (Rule.Name = 'Adom edge') And (Rule.Scope1Expression = 'All') Then Rule.Scope1Expression := 'OnCopper';@@ -7674,14 +7730,15 @@ Begin End; End; Rule.EndModify;- N := N + 1;+ If Changed Then N := N + 1 Else Kept := Kept + 1; End; Rule := BIt.NextPCBObject; End; Board.BoardIterator_Destroy(BIt);- { a board with no rule of this kind (a new board has no annular-ring or edge rule) gets one,- scoped to everything }- If N = 0 Then+ { a board with no rule of this kind (a new board has no annular-ring or edge rule) gets one, scoped to everything.+ Not beside scoped rules of the kind: a new rule lands at priority 1 and a script cannot reorder it, so it would+ outrank the board's own net-class rules }+ If (N = 0) And (Kept = 0) And (Scoped = 0) Then Begin Rule := PCBServer.PCBRuleFactory(Want); Rule.Name := 'Adom ' + Kind;@@ -7698,7 +7755,8 @@ Begin Created := True; End; PCBServer.PostProcess;- Result := '{' + JRaw('ok','true') + ',' + JStr('kind', Kind) + ',' + JRaw('rulesWritten', IntToStr(N)) + ',' + JRaw('created', JBool(Created)) + '}';+ Result := '{' + JRaw('ok','true') + ',' + JStr('kind', Kind) + ',' + JRaw('rulesWritten', IntToStr(N)) + ',' + JRaw('rulesKept', IntToStr(Kept)) + ',' ++ JRaw('scopedLeft', IntToStr(Scoped)) + ',' + JRaw('created', JBool(Created)) + '}'; End; { zoom_rect: frame the current board's view on a rectangle, RAW units (l b r t). }
src/bridge.json+1−1@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.106",+ "version": "0.2.107", "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.", "homepage": "https://wiki.adom.inc/adom/altium-bridge", "docs": "https://wiki.adom.inc/adom/altium-bridge",