← Commit history

0.2.102: the agent's workspace is chosen once (#36): no script written for the legacy folder, stale scripts never reused, a stranded loop stopped before a start, eval or run_script

Colby Knox ·3acb6a6055 · ·parent 5b44673
10 files changed +126−34
CHANGELOG.md+9
@@ -1,5 +1,14 @@ # Changelog +## 0.2.102++- **Script verbs no longer refuse with `agent_resident` after the agent lands in the wrong folder** (#36). The bridge chose the instance's agent folder once and then asked again when it wrote the path into the agent script. If the selected Altium was lost between the two (while Altium was starting, or when another request changed it), the script was written into the instance's folder but told to work in the shared legacy folder. Its loop then heartbeated where `altium_agent_status` and `altium_agent_stop` never looked, and every script verb (`altium_build_schematic`, `altium_create_symbol`, `altium_open_document`) waited and refused. Because the script was only written once per agent version, the wrong path survived Altium and bridge restarts.+- The folder is now chosen once and used for the script's contents, its file and the start that runs it. A start whose instance is lost meanwhile refuses with `instance_unresolved` instead of landing in the legacy folder.+- The script's file name now covers the folder written into it, so a script written for the wrong folder on an earlier version is never reused: affected installs repair themselves on the first start.+- A loop stranded in the legacy folder is stopped before a start, `altium_eval` or `altium_run_script`, and `altium_agent_stop` stops it too (`strandedLoopStopped`). Another Altium's own loop is left alone.+- Thanks to Jelle Jocque for the root cause.+- Tested on Altium Designer 26.11.1 with a loop started from a script pointing at the legacy folder: `altium_agent_stop`, `altium_eval` and `altium_agent_start` each stopped it in 0.2 s and carried on, the new agent ran in the instance's folder, and `altium_build_schematic` returned in 10 s.+ ## 0.2.101  - **`altium_assembly_check` gives the right JLCPCB Economic answer for small two-pad parts, ball grids and power FETs** (eda-bridge-standard#30, the engine side of kicad-bridge#144). The check now runs the standard's shared engine (adom-eda-checks 0.25.0, vendored) instead of this bridge's own copy, which had the same faults.
README.md+1−1
@@ -194,7 +194,7 @@ All 281 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca ### Scripting: DelphiScript, Altium commands, documents  - `altium_agent_start`: Bootstrap the resident DelphiScript agent inside Altium (renders the script, runs it through the -R lane, waits for the heartbeat).-- `altium_agent_stop`: Stop the selected instance's resident agent loop (drops a stop file and waits up to 12 s for the heartbeat to go stale).+- `altium_agent_stop`: Stop the selected instance's resident agent loop, and a loop stranded in the shared legacy workspace (drops a stop file and waits up to 12 s for the heartbeat to go stale). - `altium_agent_status`: Is the agent loop alive and responsive, in which workspace, and is any loop resident anywhere? Read-only; never starts the agent. - `altium_agent_recover`: Un-halt the script engine: clear the PCB transaction, press OK on open Altium dialogs, send EditScript:Stop, reap the busy notice and delete stale request files. - `altium_eval`: Run a DelphiScript snippet inside Altium (optional Var block, then Begin ...
bridge-rs/src/agent.rs+1−1
@@ -164,7 +164,7 @@ pub fn cache_dir() -> PathBuf {     PathBuf::from(r"C:\Users\Public").join("Adom Bridge").join("bridges-cache").join("altium") } -fn agent_root() -> PathBuf {+pub(crate) fn agent_root() -> PathBuf {     cache_dir().join("agent") } 
bridge-rs/src/lifecycle.rs+108−25
@@ -39,8 +39,9 @@ fn agent_base(raw: &str) -> String {     format!("AdomAgent_{}", &sha256_hex(raw.as_bytes())[..10]) } -fn ws_str() -> String {-    let s = agent::workspace_dir().to_string_lossy().to_string();+/// The workspace as the script writes it: a trailing backslash. Pure.+fn ws_str(ws: &std::path::Path) -> String {+    let s = ws.to_string_lossy().to_string();     if s.ends_with('\\') { s } else { format!("{s}\\") } } @@ -65,11 +66,23 @@ pub fn pascal_literal_inner(s: &str) -> String {     out } -fn rendered(raw: &str) -> String {-    raw.replace("__WORKSPACE__", &pascal_literal_inner(&ws_str()))+/// The script for one workspace. The workspace is passed in, never read again here: `workspace_dir()` follows the+/// selected instance, which another request can change between two calls, and a second read once wrote the legacy+/// root into a script installed in the instance's folder, so its loop heartbeated where status and stop never look+/// (#36). Pure.+fn rendered(raw: &str, ws: &std::path::Path) -> String {+    raw.replace("__WORKSPACE__", &pascal_literal_inner(&ws_str(ws)))         .replace("__GEN__", &agent_base(raw)) } +/// The script's file name in a workspace: `AdomAgent_<digest>` over the RENDERED script, so it names the template+/// AND the workspace written into it. A script rendered for another folder (#36) has another name and is never+/// reused; it is not rewritten in place either, since Altium may hold it open. The generation the loop reports+/// (AGENT_GEN, `agent_base`) stays the template's digest. Pure.+fn script_base(raw: &str, ws: &std::path::Path) -> String {+    format!("AdomAgent_{}", &sha256_hex(rendered(raw, ws).as_bytes())[..10])+}+ /// Write the script project into the workspace. Idempotent per digest. pub fn install() -> Value {     let raw = match template_source() {@@ -81,12 +94,12 @@ pub fn install() -> Value {     if let Err(e) = std::fs::create_dir_all(&ws) {         return json!({"success": false, "error": format!("cannot create workspace: {e}")});     }-    let base = agent_base(&raw);+    let base = script_base(&raw, &ws);     let pas = ws.join(format!("{base}.pas"));     let prj = ws.join(format!("{base}.PrjScr"));     let changed = !pas.exists();     if changed {-        if let Err(e) = std::fs::write(&pas, rendered(&raw)) {+        if let Err(e) = std::fs::write(&pas, rendered(&raw, &ws)) {             return json!({"success": false, "error": format!("cannot write {}: {e}", pas.display())});         }         let prj_body = std::fs::read_to_string(agent_dir().join("AdomAgent.PrjScr"))@@ -95,10 +108,10 @@ pub fn install() -> Value {         if let Err(e) = std::fs::write(&prj, prj_body) {             return json!({"success": false, "error": format!("cannot write {}: {e}", prj.display())});         }-        prune_generations(3);+        prune_generations(&ws, 3);     }-    json!({"installed": true, "changed": changed, "prjscr": prj.to_string_lossy(),-           "pas": pas.to_string_lossy(), "digest": &base[base.len() - 10..]})+    json!({"installed": true, "changed": changed, "prjscr": prj.to_string_lossy(), "workspace": ws.to_string_lossy(),+           "pas": pas.to_string_lossy(), "digest": &base[base.len() - 10..], "generation": agent_base(&raw)}) }  /// After a start: the agent's script project joined the open workspace. When it is the only difference from the@@ -137,9 +150,8 @@ fn leave_workspace_unchanged() -> Value { }  /// Keep the newest `keep` generations so an open editor tab never dangles.-fn prune_generations(keep: usize) {-    let ws = agent::workspace_dir();-    let mut gens: Vec<(std::time::SystemTime, PathBuf)> = match std::fs::read_dir(&ws) {+fn prune_generations(ws: &std::path::Path, keep: usize) {+    let mut gens: Vec<(std::time::SystemTime, PathBuf)> = match std::fs::read_dir(ws) {         Ok(rd) => rd             .filter_map(|e| e.ok())             .filter(|e| {@@ -162,7 +174,8 @@ fn prune_generations(keep: usize) {  pub fn prjscr_path() -> Option<PathBuf> {     let raw = template_source().ok()?;-    Some(agent::workspace_dir().join(format!("{}.PrjScr", agent_base(&raw))))+    let ws = agent::workspace_dir();+    Some(ws.join(format!("{}.PrjScr", script_base(&raw, &ws)))) }  fn resident_generation() -> Option<String> {@@ -389,6 +402,7 @@ pub fn run_script_lane_in(proc_name: &str, prjscr: Option<&str>, timeout: Durati  /// -R RunScriptText: STATEMENTS ONLY (Begin ... End;). Refused while any agent is resident. pub fn run_script_text_lane(text: &str, timeout: Duration) -> Value {+    let stranded = stop_stranded();     if let Some((ws, age)) = agent::any_agent_alive() {         return json!({"success": false, "errorCode": "agent_resident",             "liveWorkspace": ws.to_string_lossy(), "heartbeatAgeSec": age,@@ -409,7 +423,9 @@ pub fn run_script_text_lane(text: &str, timeout: Duration) -> Value {     };     let t0 = Instant::now();     if wait_helper(&mut child, timeout) {-        return json!({"success": true, "helperSec": t0.elapsed().as_secs_f64()});+        let mut out = json!({"success": true, "helperSec": t0.elapsed().as_secs_f64()});+        if let Some(st) = stranded { out["strandedLoopStopped"] = st; }+        return out;     }     let _ = child.kill();     let _ = child.wait();@@ -432,7 +448,9 @@ pub fn run_script_lane(proc_name: &str, timeout: Duration) -> Value { fn run_script_lane_impl(proc_name: &str, prj: String, timeout: Duration) -> Value {     // ANY live loop refuses the lane, not just this instance's: Altium raises "Another script     // executing now" for the second script regardless of which workspace the first one polls-    // (an upgraded bridge leaves the OLD loop heartbeating under the legacy path).+    // (an upgraded bridge leaves the OLD loop heartbeating under the legacy path). A loop stranded there is stopped+    // first (#36); this instance's own loop, or another instance's, still refuses.+    let _ = stop_stranded();     if let Some((ws, age)) = agent::any_agent_alive() {         return json!({"success": false, "errorCode": "agent_resident",             "error": "an Adom agent loop is resident; a second script would raise Altium's 'Another script executing now' modal",@@ -555,6 +573,14 @@ fn start_impl(mut wait: Duration) -> Value {     if inst.get("success").and_then(|b| b.as_bool()) == Some(false) {         return inst;     }+    // the folder install() wrote to is the one this start uses throughout: never the legacy root (#6, #36)+    let ws = PathBuf::from(inst["workspace"].as_str().unwrap_or(""));+    if ws.as_os_str().is_empty() || ws == agent::agent_root() {+        return json!({"success": false, "errorCode": "instance_unresolved",+            "error": "the Altium instance was lost while the agent was being installed, so it would have landed in the shared legacy workspace where status and stop cannot see it (#36)",+            "_hint": "altium_status, then retry; pass instance:<pid|key> if several run"});+    }+    let prjscr = inst["prjscr"].as_str().unwrap_or("").to_string();     let want = template_source().map(|r| agent_base(&r)).unwrap_or_default();     if agent::is_alive() {         match resident_generation() {@@ -566,8 +592,10 @@ fn start_impl(mut wait: Duration) -> Value {             }         }     }+    // a loop stranded in the legacy root (#36: an earlier install wrote the root into the script) would refuse this+    // bootstrap as a second script: stop it first. stop() leaves other instances' folders alone.+    let stranded = stop_stranded();     // a stale heartbeat / inbox / response from a previous life must not confuse this one-    let ws = agent::workspace_dir();     for n in ["hb.txt", "stop", "request.txt", "request.payload", "request.txt.tmp", "request.payload.tmp"] {         let _ = std::fs::remove_file(ws.join(n));     }@@ -590,7 +618,7 @@ fn start_impl(mut wait: Duration) -> Value {     let strays = kill_stray_helpers();     agent::mark_start_sent();     crate::trace::step("start: sending StartAgent");-    let mut lane = run_script_lane("StartAgent", Duration::from_secs(30));+    let mut lane = run_script_lane_impl("StartAgent", prjscr.clone(), Duration::from_secs(30));     crate::trace::step(&format!("start: StartAgent lane -> success={:?} errorCode={:?}", lane.get("success"), lane.get("errorCode")));     if !strays.is_empty() {         lane["strayHelpersKilled"] = json!(strays);@@ -624,6 +652,7 @@ fn start_impl(mut wait: Duration) -> Value {                 if let Some(f) = &freed_parked {                     out["parkedLoopStopped"] = f.get("steps").cloned().unwrap_or(Value::Null);                 }+                if let Some(st) = &stranded { out["strandedLoopStopped"] = st.clone(); }                 // earlier generations' script projects close (each start opens a new one in Altium's                 // Projects panel; ten were stacked there by 2026-10-15)                 crate::trace::step(&format!("start: heartbeat after {:.1}s, close_old_agents next", t0.elapsed().as_secs_f64()));@@ -664,7 +693,7 @@ fn start_impl(mut wait: Duration) -> Value {                    "_hint": "Altium is wedged inside a modal loop whose dialog is gone, so it can never run the agent script: its main window is DISABLED and nothing is on screen to answer. altium_close {discardChanges:true} ends it gracefully and RELEASES the licence seat."});         }         retried = true;-        let again = run_script_lane("StartAgent", Duration::from_secs(30));+        let again = run_script_lane_impl("StartAgent", prjscr.clone(), Duration::from_secs(30));         if again.get("success").and_then(|b| b.as_bool()) != Some(true) {             return json!({"success": false, "errorCode": "no_heartbeat",                    "error": "the agent did not heartbeat, and re-sending the bootstrap failed",@@ -678,22 +707,55 @@ fn start_impl(mut wait: Duration) -> Value {     } } +/// A loop in the shared legacy root is always stranded: no start bootstraps there since #6, so one runs only from a+/// script that wrote the wrong folder (#36) or an older bridge. While it heartbeats every script lane on every+/// instance refuses with agent_resident. Stop it (and only it); None when there is none.+pub fn stop_stranded() -> Option<Value> {+    let root = agent::agent_root();+    let live = |r: &PathBuf| agent::live_workspaces().iter().any(|(w, _)| w == r);+    if !live(&root) { return None; }+    crate::trace::step("a loop is stranded in the legacy workspace: stopping it");+    let _ = std::fs::write(root.join("stop"), "1");+    let t0 = Instant::now();+    while t0.elapsed() < Duration::from_secs(HB_STALE_SEC + 4) {+        if !live(&root) {+            return Some(json!({"stopped": root.to_string_lossy(), "inSec": t0.elapsed().as_secs_f64()}));+        }+        std::thread::sleep(Duration::from_millis(200));+    }+    Some(json!({"stopped": Value::Null, "stillAlive": root.to_string_lossy(), "error": "the stranded loop did not exit"}))+}++/// Stop this instance's loop, and a loop stranded in the shared legacy root: one lands there only by a bug (#6, #36),+/// no instance owns it, and while it runs every script verb on every instance refuses with agent_resident. Another+/// instance's own folder is left alone. pub fn stop() -> Value {-    let ws = agent::workspace_dir();-    if !agent::is_alive() {+    let mine = agent::workspace_dir();+    let root = agent::agent_root();+    let live = agent::live_workspaces();+    let targets: Vec<PathBuf> = live.into_iter().map(|(w, _)| w).filter(|w| *w == mine || *w == root).collect();+    if targets.is_empty() {         return json!({"success": true, "wasRunning": false});     }-    if let Err(e) = std::fs::write(ws.join("stop"), "1") {-        return json!({"success": false, "error": format!("cannot drop the stop file: {e}")});+    for w in &targets {+        if let Err(e) = std::fs::write(w.join("stop"), "1") {+            return json!({"success": false, "error": format!("cannot drop the stop file in {}: {e}", w.display())});+        }     }+    let stopped: Vec<String> = targets.iter().map(|w| w.to_string_lossy().to_string()).collect();+    let still = || agent::live_workspaces().into_iter().any(|(w, _)| targets.contains(&w));     let t0 = Instant::now();     while t0.elapsed() < Duration::from_secs(HB_STALE_SEC + 4) {-        if !agent::is_alive() {-            return json!({"success": true, "stoppedInSec": t0.elapsed().as_secs_f64()});+        if !still() {+            let mut out = json!({"success": true, "stoppedInSec": t0.elapsed().as_secs_f64(), "stopped": stopped});+            if targets.contains(&root) && root != mine {+                out["strandedLoopStopped"] = json!(root.to_string_lossy());+            }+            return out;         }         std::thread::sleep(Duration::from_millis(200));     }-    json!({"success": false, "error": "the loop did not exit", "_hint": "agent_recover"})+    json!({"success": false, "error": "the loop did not exit", "stopped": stopped, "_hint": "agent_recover"}) }  /// Stop EVERY resident loop, in every workspace (legacy root + per-instance subdirs), not just the@@ -1303,6 +1365,27 @@ mod tests {     } } +#[cfg(test)]+mod workspace_tests {+    use super::{agent_base, rendered, script_base};+    use std::path::Path;++    const RAW: &str = "WORKSPACE = '__WORKSPACE__';\r\nAGENT_GEN = '__GEN__';\r\n";++    /// #36: the script names the folder it was rendered for, and a script rendered for another folder has another+    /// file name, so a stale one (the legacy root written into the instance's folder) is never reused.+    #[test]+    fn the_script_names_its_own_workspace_and_is_named_by_it() {+        let inst = Path::new("C:\\Users\\u\\AppData\\Local\\Adom Bridge\\bridges-cache\\altium\\agent\\ADDevelop");+        let root = Path::new("C:\\Users\\u\\AppData\\Local\\Adom Bridge\\bridges-cache\\altium\\agent");+        assert!(rendered(RAW, inst).contains("agent\\ADDevelop\\';"));+        assert!(rendered(RAW, inst).contains(&agent_base(RAW)));+        assert_ne!(script_base(RAW, inst), script_base(RAW, root));+        assert_eq!(script_base(RAW, inst), script_base(RAW, inst));+        assert!(script_base(RAW, inst).starts_with("AdomAgent_"));+    }+}+ #[cfg(test)] mod interop_tests {     use super::{agent_base, sha256_hex};
bridge-rs/src/main.rs+1−1
@@ -81,7 +81,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.101";+pub const BRIDGE_VERSION: &str = "0.2.102";  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/verbs.rs+2−2
@@ -272,8 +272,8 @@ fn describe() -> Value {               "An earlier loop parked in Altium's script debugger (engineParked) is stopped first, so the new one can run: parkedLoopStopped lists what was done.",               "If the bridge itself ever ends during a verb, the next bridge process writes which verb and its last steps to altium-bridge-crash.log beside the bridge exe (with Rust's own message for a stack overflow). Attach that file to a report.",               "The loop exits by itself 15 s after the last request (while it runs Altium ignores the user's clicks, #27); the next verb restarts it in 2.5-4 s. Call altium_agent_stop when you hand Altium back to the user."], json!({})),-        verb_doc("agent_stop", "Stop the selected instance's resident agent loop (drops a stop file and waits up to 12 s for the heartbeat to go stale).", json!({}),-            json!({"wasRunning": "bool", "stoppedInSec": "float"}), 20,+        verb_doc("agent_stop", "Stop the selected instance's resident agent loop, and a loop stranded in the shared legacy workspace (drops a stop file and waits up to 12 s for the heartbeat to go stale).", json!({}),+            json!({"wasRunning": "bool", "stoppedInSec": "float", "stopped": "[workspace]", "strandedLoopStopped": "path - a loop in the legacy workspace was stopped too"}), 20,             "Call it when you hand Altium back to the user: while the loop is resident Altium ignores their clicks (it also stops by itself 15 s after the last verb). Needed before altium_run_script (the -R lanes refuse while a loop is resident). altium_close stops every workspace's loop itself. The next agent-backed verb restarts the agent. Clears the 'Adom is driving' taskbar badge.",             &["agent_start", "agent_status", "run_script", "close"], &["'the loop did not exit' -> altium_agent_recover.", "With several Altiums running pass instance: to stop the right loop."], json!({})),         verb_doc("agent_status", "Is the agent loop alive and responsive, in which workspace, and is any loop resident anywhere? Read-only; never starts the agent.", json!({}),
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.101",+  "version": "0.2.102",   "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.101",+  "version": "0.2.102",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.101+0.2.102
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.101",+  "version": "0.2.102",   "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",