← Commit history

0.2.93: engineParked reads the agent's own files (#30); crash log keeps Rust's fatal messages and names the verb a dead bridge was running

Colby Knox ·32fa3aa3ba · ·parent 822077c
12 files changed +365−41
CHANGELOG.md+19
@@ -1,5 +1,24 @@ # Changelog +## 0.2.93++- **`engineParked` sees a parked agent whatever document is in front** (#30, reported by Ivan Mendez). It used to require the agent's own script to be the document in front. On Ivan's machine the parked script sat behind the user's schematic, so `check_dialogs`, `readiness` and `agent_status` all said `engineParked: false` while Altium refused to exit. The bridge now reads the agent's own files: a loop that started in the running Altium and neither exited nor heartbeat for 15 s is parked.+  - A parked loop is no longer counted as `alive` in the minute after its last heartbeat. Agent verbs used to send their command into it and wait out their whole timeout.+  - `agent_start`, and every agent verb, stop a parked loop before starting a new one (`parkedLoopStopped`).+  - `agent_status` names the parked workspace (`parkedWorkspaces`).+- **A bridge that dies now leaves a record** (#30). The bridge still ended during `agent_start` on one machine on 0.2.92, with no crash log: a stack overflow or an allocation failure skips the panic hook, and ab rewrites the bridge's console log on every restart.+  - Rust's own fatal messages now go to `altium-bridge-crash.log` beside the bridge exe.+  - Each request and each step of starting, recovering and healing the agent is appended to `altium-bridge-trace.log`.+  - When a bridge process starts after one that died inside a verb, it writes which verb was running and its last 25 steps into `altium-bridge-crash.log`.+- Tested on Altium Designer 26.11.1 with the test laptop set to Spanish regional format (es-ES), to match the reporter's machine:+  - **The agent starts normally there.** The comma decimal separator alone does not make it halt.+  - **Ivan's state, reproduced.** The agent was made to halt on its first command and the bridge was ended at that moment. A board was put in front of the parked script, and the restarted bridge then:+    - reported `engineParked: true` in `check_dialogs`, `readiness` and `agent_status`;+    - wrote "ended while running altium_agent_start" with the last step (heartbeat, close_old_agents next) to the crash log.+  - **Recovery.** `agent_start` stopped the parked loop and started a new one in 11 s.+  - **The 0.2.91 halt case** still answers `agent_halted_after_start` with nothing left parked.+  - **Battery:** 13 of 13 lifecycle and board verbs pass.+ ## 0.2.92  - **Decimal numbers work on Windows set to a comma decimal separator** (#31, found and fixed by Carlos Ferri Pereira in PR #4). The agent read every number a caller passed (`-0.9100` in a footprint spec, a body offset, a board size) with Altium's `StrToFloat`, which uses the Windows region's decimal separator. On Portuguese, Spanish, German, French and other comma locales every such verb raised `EConvertError` and stopped the script: `build_footprint`, `footprint_from_land_pattern`, `import_part`, `create_footprint`, `edit_footprint`, `test_board`, `board_shape`, `import_step` and `add_symbol_art`. The agent now reads the digits itself, whatever the region says, and nothing has to change on the user's machine. Everything the agent writes back was already locale-proof (whole micrometres and mils).
bridge-rs/src/agent.rs+101−13
@@ -48,26 +48,85 @@ pub fn healing() -> bool {     HEALING.with(|h| h.get() > 0) } -/// Altium is running, the agent's own script is the document in front, and its loop stopped without exiting: a clean-/// exit (agent_stop, auto-stop, Altium closing) deletes hb.txt, a script parked in Altium's debugger (a breakpoint or a-/// runtime error) leaves it behind and it goes stale. Nothing in this state answers, and Altium refuses to close a-/// document or exit until the script is stopped. Every workspace is looked at, not only the selected one: a respawned-/// bridge has no instance selected yet, and the parked loop's hb.txt sits in its instance folder (found testing #30).+/// How many starts and recovers are nested on this thread (for the step trace).+pub fn heal_depth() -> u32 {+    HEALING.with(|h| h.get())+}++/// The agent's loop is stopped in Altium's script debugger: a runtime error or a breakpoint parked it, and it will+/// never answer. Altium then refuses to close a document or exit until the script is stopped.+///+/// The agent writes agent.json with `startedTick` when its loop starts and rewrites it with `stoppedTick` when the+/// loop exits by any clean path (agent_stop, auto-stop, Altium closing), deleting hb.txt. A loop that started in an+/// Altium still running and neither exited nor heartbeat for 15 s is parked. Every workspace is looked at (a+/// respawned bridge has no instance selected). The agent.json must be newer than the running Altium's start, so a+/// loop from an Altium that was killed is not taken for one parked in this Altium.+///+/// Until 0.2.93 this also required the agent's own script to be the document in front. On a user's machine (#30)+/// the parked script stayed behind their schematic, and every status verb said `engineParked: false` while Altium+/// refused to exit. The title is now one more way to see it, not a requirement.+/// /// A loop busy in one long command of THIS bridge also stops heartbeating, so a command in flight is not a park.-/// `recover` deletes hb.txt, so this reads false after a recover whatever happened.+/// `recover` marks the loops it stopped, so this reads false after a recover. pub fn engine_parked() -> bool {-    const PARKED_AFTER: Duration = Duration::from_secs(15);-    if IN_FLIGHT.lock().map(|g| g.is_some()).unwrap_or(false) {+    if IN_FLIGHT.lock().map(|g| g.is_some()).unwrap_or(false) || !crate::health::is_running() {         return false;     }+    !parked_workspaces().is_empty() || (is_agent_script_title(&main_title()) && stale_heartbeat_anywhere())+}++const PARKED_AFTER: Duration = Duration::from_secs(15);++fn all_workspaces() -> Vec<PathBuf> {     let root = agent_root();     let mut dirs = vec![root.clone()];     if let Ok(rd) = std::fs::read_dir(&root) {         dirs.extend(rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()));     }-    let ages: Vec<Duration> = dirs.iter().filter_map(|d| hb_age(d)).collect();+    dirs+}++fn stale_heartbeat_anywhere() -> bool {+    let ages: Vec<Duration> = all_workspaces().iter().filter_map(|d| hb_age(d)).collect();     !ages.is_empty() && ages.iter().all(|a| *a > PARKED_AFTER)-        && crate::health::is_running() && is_agent_script_title(&main_title())+}++/// When the oldest running Altium started. `None` when none runs or none can be read.+fn altium_started() -> Option<SystemTime> {+    crate::win32::pids_of("X2.EXE").unwrap_or_default().into_iter().filter_map(crate::win32::process_start_time).min()+}++/// Whether one workspace's loop looks parked. Pure over what was read from disk.+pub fn looks_parked(agent_json: &str, agent_json_age: Duration, agent_json_mtime: SystemTime, hb: Option<Duration>, altium_started: SystemTime) -> bool {+    agent_json.contains("\"startedTick\"") && !agent_json.contains("\"stoppedTick\"")+        && agent_json_age > PARKED_AFTER+        && hb.map(|a| a > PARKED_AFTER).unwrap_or(true)+        && agent_json_mtime > altium_started+}++/// The workspaces whose loop is parked (see engine_parked).+pub fn parked_workspaces() -> Vec<PathBuf> {+    let Some(started) = altium_started() else { return Vec::new() };+    all_workspaces().into_iter().filter(|d| {+        let f = d.join("agent.json");+        let Ok(text) = std::fs::read_to_string(&f) else { return false };+        let Some(mtime) = std::fs::metadata(&f).and_then(|m| m.modified()).ok() else { return false };+        let age = SystemTime::now().duration_since(mtime).unwrap_or_default();+        looks_parked(&text, age, mtime, hb_age(d), started)+    }).collect()+}++/// After recover has sent the stop: record each parked loop as stopped, the way the agent would on a clean exit.+pub fn mark_parked_stopped(why: &str) -> Vec<String> {+    let mut out = Vec::new();+    for d in parked_workspaces() {+        let body = json!({"stoppedTick": 0, "stoppedBy": why}).to_string();+        if std::fs::write(d.join("agent.json"), body).is_ok() {+            let _ = std::fs::remove_file(d.join("hb.txt"));+            out.push(d.to_string_lossy().to_string());+        }+    }+    out }  pub fn cache_dir() -> PathBuf {@@ -171,11 +230,15 @@ const PCB_EDIT_COMMANDS: &[&str] = &["add_body", "add_rule", "apply_pours", "app     "remove_pours", "set_outline", "set_rule", "swap_footprint", "test_board", "xcopy_footprint"];  pub fn call(command: &str, params: &[(&str, String)], payload: Option<&str>, timeout: Duration) -> Value {-    if !is_alive() && healing() {+    // a parked loop's heartbeat counts as alive for up to a minute after it stopped; posting into it would wait out+    // the whole timeout, so it counts as dead here (#30)+    let alive = is_alive() && !engine_parked();+    if !alive && healing() {+        crate::trace::step(&format!("call {command}: agent not running inside a start/recover, not healing"));         return json!({"success": false, "errorCode": "agent_not_running", "command": command,             "error": format!("the agent loop is not running, and '{command}' was asked for during an agent start or recover, which does not start another one")});     }-    if !is_alive() {+    if !alive {         // A dead agent with Altium still showing the agent's script is a script PARKED ON A         // BREAKPOINT: Altium's debugger breaks on any raised exception, even one the agent's own         // Try/Except handled, and Altium Develop does it with no error box. The command that raised@@ -183,12 +246,14 @@ pub fn call(command: &str, params: &[(&str, String)], payload: Option<&str>, tim         // script into a parked engine and block until ab's HTTP timeout, and so would every verb after         // it (the 30-verb cascade the battery found, 2026-09-20). Free the engine first.         let mut freed = Value::Null;-        if crate::health::is_running() && is_agent_script_title(&main_title()) {+        if crate::health::is_running() && (is_agent_script_title(&main_title()) || engine_parked()) {+            crate::trace::step(&format!("call {command}: agent dead and the engine parked, recovering first"));             freed = crate::lifecycle::recover(&format!("auto: agent dead and the engine parked on the agent script before '{command}'"));             crate::dialogs::note_event(json!({"title": "(silent script halt)", "category": "engine_parked_cleared", "pressed": "EditScript:Stop", "ok": true,                 "note": format!("the agent had stopped on a breakpoint without an error box; cleared before running '{command}'")}));         }         // parity with the Python bridge: bootstrap on demand, so a cold box needs no ceremony+        crate::trace::step(&format!("call {command}: agent not running, starting it"));         let started = crate::lifecycle::start(Duration::from_secs(45));         if !freed.is_null() {             let mut r = if started.get("success").and_then(|b| b.as_bool()) == Some(true) {@@ -325,6 +390,7 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p                     "_hint": "READ errorShot (PNG of Altium's box, e.g. 'Undeclared identifier: X at Line:N'). The bridge answered OK so the agent loop is still resident; fix the script text and send it again."});             }             if let Some(ev) = crate::dialogs::script_error_since(posted_unix_ms) {+                crate::trace::step(&format!("call_in {command}: script Error box seen (healing={})", healing()));                 if healing() {                     // inside a start or recover: that caller frees the engine; a recover from here would start the                     // agent, meet the same error and recover again (#30)@@ -380,6 +446,28 @@ pub fn is_agent_script_title(title: &str) -> bool { mod halt_tests {     use super::*; +    #[test]+    fn parked_means_started_here_and_never_exited() {+        use std::time::UNIX_EPOCH;+        let altium = UNIX_EPOCH + Duration::from_secs(1_000);+        let after = UNIX_EPOCH + Duration::from_secs(2_000);+        let before = UNIX_EPOCH + Duration::from_secs(500);+        let started = r#"{"version":"x","startedTick":123,"workspace":"C:\\a"}"#;+        let stopped = r#"{"version":"x","stoppedTick":456,"requests":3}"#;+        let old = Duration::from_secs(60);+        // started in this Altium, no heartbeat for a minute: parked (#30, the script behind the user's schematic)+        assert!(looks_parked(started, old, after, Some(old), altium));+        assert!(looks_parked(started, old, after, None, altium));+        // heartbeating: alive+        assert!(!looks_parked(started, old, after, Some(Duration::from_secs(1)), altium));+        // just written, the first heartbeat is still to come+        assert!(!looks_parked(started, Duration::from_secs(3), after, None, altium));+        // exited cleanly+        assert!(!looks_parked(stopped, old, after, None, altium));+        // a loop of an Altium that has since been closed or killed+        assert!(!looks_parked(started, old, before, None, altium));+    }+     #[test]     fn heal_guard_nests_and_clears() {         assert!(!healing());
bridge-rs/src/lifecycle.rs+25−1
@@ -455,7 +455,9 @@ fn start_modal_watcher() -> (std::sync::Arc<std::sync::atomic::AtomicBool>, std: pub fn start(wait: Duration) -> Value {     let top = !agent::healing();     let _g = agent::HealGuard::enter();+    crate::trace::step(&format!("start: enter (top={top})"));     let out = start_impl(wait);+    crate::trace::step(&format!("start: start_impl -> success={:?} errorCode={:?}", out.get("success"), out.get("errorCode")));     // #30: the agent came up and halted at once. A start that is not itself part of a recover frees the engine here,     // once, so Altium is not left parked on the agent's script (it then refuses to close documents or exit).     if top && out.get("errorCode").and_then(|c| c.as_str()) == Some("agent_halted_after_start") {@@ -521,10 +523,18 @@ fn start_impl(mut wait: Duration) -> Value {             }         }     }+    // a loop parked in the debugger holds the script engine: a new StartAgent would queue behind it and never run.+    // Free it first, without the verifying restart (this is the restart) (#30)+    let freed_parked = if agent::engine_parked() {+        crate::trace::step("start: the engine is parked, stopping the parked loop first");+        Some(recover_without_restart("agent_start: an earlier agent loop is parked in the script debugger"))+    } else { None };     let user_fg = foreground_hwnd();     let t0 = Instant::now();     let strays = kill_stray_helpers();+    crate::trace::step("start: sending StartAgent");     let mut lane = run_script_lane("StartAgent", 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);     }@@ -554,9 +564,14 @@ fn start_impl(mut wait: Duration) -> Value {                 }                 let mut out = json!({"success": true, "startedInSec": t0.elapsed().as_secs_f64(),                               "generation": resident_generation(), "install": inst});+                if let Some(f) = &freed_parked {+                    out["parkedLoopStopped"] = f.get("steps").cloned().unwrap_or(Value::Null);+                }                 // 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()));                 let c = agent::call("close_old_agents", &[], None, Duration::from_secs(30));+                crate::trace::step(&format!("start: close_old_agents -> success={:?} errorCode={:?}", c.get("success"), c.get("errorCode")));                 out["oldAgentProjectsClosed"] = c.get("data").and_then(|d| d.get("closed")).cloned().unwrap_or(Value::Null);                 // the first command after the heartbeat is the proof the loop serves: an agent that heartbeat once and                 // then raised a script error, or went quiet, is not running whatever its heartbeat file says (#30)@@ -578,6 +593,7 @@ fn start_impl(mut wait: Duration) -> Value {             std::thread::sleep(Duration::from_millis(250));         }         let dialogs = crate::dialogs::scan();+        crate::trace::step(&format!("start: no heartbeat after {:.1}s (retried={retried}, dialogs={})", t0.elapsed().as_secs_f64(), dialogs.len()));         // A dialog is a real answer (a compile error behind a modal): never paper over it.         if retried || !dialogs.is_empty() || !crate::health::is_running() {             return json!({"success": false, "errorCode": "no_heartbeat",@@ -726,6 +742,7 @@ pub fn recover_without_restart(reason: &str) -> Value {  fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {     let _g = agent::HealGuard::enter();+    crate::trace::step(&format!("recover: enter (verify={verify_by_restart}) {reason}"));     let mut steps: Vec<Value> = vec![json!({"reason": reason})];     // A modal orphan answers NOTHING: every -R below would bounce off "another instance is busy"     // and each bounce spawns a helper X2. Say so instead of thrashing for 10 s.@@ -842,15 +859,21 @@ fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {         }         steps.push(reap_busy_notice(Duration::from_secs(4)));     }-    // 3. stale files+    // 3. stale files; the loops just stopped are recorded as stopped, as the agent records a clean exit, so+    // engineParked reads false from here on (#30)     let ws = agent::workspace_dir();     for n in ["hb.txt", "stop", "request.txt", "request.payload", "request.txt.tmp"] {         let _ = std::fs::remove_file(ws.join(n));     }+    let marked = agent::mark_parked_stopped("bridge recover");+    if !marked.is_empty() {+        steps.push(json!({"parkedLoopsStopped": marked.len()}));+    }     // VERIFY, never assume: the engine is free only if a fresh agent loop can actually start.     instance::invalidate_snapshot();     let mut verified = Value::Null;     if verify_by_restart && crate::health::is_running() && instances_after <= 1 {+        crate::trace::step("recover: verifying by starting the agent");         let started = start(Duration::from_secs(45));         let mut ok = started.get("success").and_then(|b| b.as_bool()) == Some(true) && agent::is_alive();         steps.push(json!({"verifiedByRestartingTheAgent": ok}));@@ -883,6 +906,7 @@ fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {         verified = json!(ok);     }     let freed = verified.as_bool().unwrap_or(true);+    crate::trace::step(&format!("recover: exit (freed={freed})"));     // #30: the engine was freed, but the agent halts every time it starts. Not the same answer as a parked engine:     // Altium is usable by hand and closes normally, and nothing the caller clicks will change it.     let halts_on_start = !freed
bridge-rs/src/main.rs+39−14
@@ -61,6 +61,7 @@ mod review; mod route; mod routing; mod shot;+mod trace; mod silkplace; mod sim; mod support;@@ -79,7 +80,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.92";+pub const BRIDGE_VERSION: &str = "0.2.93";  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());@@ -95,21 +96,42 @@ fn crash_log_path() -> std::path::PathBuf {         .unwrap_or_else(std::env::temp_dir).join("altium-bridge-crash.log") } +fn stamp() -> u64 {+    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+}++fn append_crash_log(text: &str) {+    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(crash_log_path()) {+        use std::io::Write;+        let _ = f.write_all(text.as_bytes());+    }+}++/// Panics, Rust's own fatal messages and the request the previous process died in all go to one file beside the exe.+/// A panic runs the hook; a stack overflow or an allocation failure does not, it prints to stderr and ends the+/// process at once, so stderr is pointed at the same file (#30: 266 deaths on 0.2.92 and no file at all). fn install_crash_log() {+    let path = crash_log_path();+    // keep it small: start over past 256 KB (only here, before the stderr handle holds it open)+    if std::fs::metadata(&path).map(|m| m.len() > 256 * 1024).unwrap_or(false) {+        let _ = std::fs::remove_file(&path);+    }+    if let Some(r) = trace::previous_run_report() {+        append_crash_log(&format!("[{}] {r}\n", stamp()));+    }+    let redirected = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok()+        .map(|f| { let ok = win32::redirect_stderr(&f); std::mem::forget(f); ok }).unwrap_or(false);+    // through stderr when it is redirected: this line in the file is the proof a stack overflow's message will be too+    if redirected {+        eprintln!("[{}] bridge {BRIDGE_VERSION} started, pid {} (stderr goes here)", stamp(), std::process::id());+    } else {+        append_crash_log(&format!("[{}] bridge {BRIDGE_VERSION} started, pid {} (stderr NOT redirected: a stack overflow would leave no message)\n", stamp(), std::process::id()));+    }     std::panic::set_hook(Box::new(|info| {         let thread = std::thread::current().name().unwrap_or("?").to_string();-        let line = format!("[{}] bridge {BRIDGE_VERSION} panic in thread {thread}: {info}\n",-            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));-        eprint!("{line}");-        let path = crash_log_path();-        // keep it small: start over past 256 KB-        if std::fs::metadata(&path).map(|m| m.len() > 256 * 1024).unwrap_or(false) {-            let _ = std::fs::remove_file(&path);-        }-        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {-            use std::io::Write;-            let _ = f.write_all(line.as_bytes());-        }+        let line = format!("[{}] bridge {BRIDGE_VERSION} panic in thread {thread}: {info}\n", stamp());+        trace::step(&format!("PANIC {info}"));+        append_crash_log(&line);     })); } @@ -125,6 +147,8 @@ fn main() {     let server = Server::http(format!("{host}:{port}")).expect("bind");     let bound = server.server_addr();     println!("[altium] bridge {BRIDGE_VERSION} listening on {bound}");+    install_crash_log();+    trace::step(&format!("bridge {BRIDGE_VERSION} started, listening on {bound}"));     // Standing services, started separately so one failing cannot take the other down:     // the dialog reaper pre-empts Altium's nuisance modals (John: "always pre-empt these from     // ever showing up"), the idle watcher clears the taskbar overlay after 5 quiet minutes.@@ -137,7 +161,6 @@ fn main() {     // bridge kept grinding the abandoned request, and the queue only grew (the 30-verb cascades the     // verb battery found, 2026-09-20). Agent-bound work still serialises where it must: the agent's     // one-file inbox, which now answers a NAMED agent_busy instead of a dropped connection.-    install_crash_log();     for mut req in server.incoming_requests() {         // 16 MB, not the 2 MB default: a request runs Altium's whole lifecycle (start, recover, their checks) on its own         // thread, and a stack overflow ends the PROCESS with no log at all (adom/altium-bridge#30)@@ -163,6 +186,7 @@ fn main() {                         let command = v.get("command").and_then(|c| c.as_str()).unwrap_or("").to_string();                         let vargs = v.get("args").cloned().unwrap_or_else(|| serde_json::json!({}));                         // a panic answers as an error, never as a dropped connection the caller reads as a dead bridge (#30)+                        let tid = trace::begin(&command);                         let mut out = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| verbs::handle(&command, &vargs, &forwarded))) {                             Ok(v) => v,                             Err(p) => {@@ -174,6 +198,7 @@ fn main() {                                     "_hint": "A bug in altium-bridge, not in Altium. The bridge is still running. Please report it with this reply and the crash log's last lines."})                             }                         };+                        trace::end(tid, &command, t0.elapsed().as_millis(), out.get("success").and_then(|b| b.as_bool()));                         if let Some(o) = out.as_object_mut() {                             // Bridge SDK: invite the bug report IN THE OUTPUT, on every failure. The AI driving                             // this bridge is standing on the one machine where the failure happened and holds
bridge-rs/src/misc.rs+10−5
@@ -45,7 +45,9 @@ const PARKED_HINT: &str = "The agent's script is PARKED in Altium's script debug pub fn readiness(_args: &Value) -> Value {     let inst = support::first_install();     let lic = instance::licence_state();-    let alive = agent::is_alive();+    // a parked loop is not alive, whatever its last heartbeat says (#30)+    let parked = agent::engine_parked();+    let alive = agent::is_alive() && !parked;     // The UNION view: is a loop resident in ANY workspace, not just the selected one? In #6 a loop     // lived in the legacy workspace while the selected one was empty, and `agentAlive` (selected     // only) reported false while the engine was occupied. `agentAlive` still answers "can I drive@@ -63,7 +65,7 @@ pub fn readiness(_args: &Value) -> Value {     } else if licensed == Some(false) {         format!("Altium is running but the title says {:?} — scripting is refused without a licence. altium_license '{{}}' drives the trial/On-Demand flow.",             lic.get("state").and_then(|st| st.as_str()).unwrap_or("?"))-    } else if !alive && agent::engine_parked() {+    } else if parked {         PARKED_HINT.to_string()     } else if !alive {         "Licensed and running; the agent loop is not resident — altium_agent_start (≈8s), then drive.".to_string()@@ -73,7 +75,7 @@ pub fn readiness(_args: &Value) -> Value {     let mut out = json!({"success": true, "hostApp": support::HOST_APP, "installed": inst.is_some(), "install": inst,         "running": running, "licensed": licensed, "licenceState": lic.get("state"),         "adVersion": lic.get("adVersion"), "agentAlive": alive, "agentResidentAnywhere": resident_anywhere,-        "engineParked": running && !alive && agent::engine_parked(),+        "engineParked": running && parked,         "ready": ready, "engine": "rust", "_hint": hint});     // Surface a loop that is resident somewhere the current selection does not point at — the exact     // blind spot behind #6. It is a live freeze-on-close hazard until torn down (altium_close does@@ -114,7 +116,8 @@ pub fn diagnostics(_args: &Value) -> Value { }  pub fn agent_status(_args: &Value) -> Value {-    let alive = agent::is_alive();+    let parked = agent::engine_parked();+    let alive = agent::is_alive() && !parked;     let live_ws = agent::live_workspaces();     let resident_anywhere = !live_ws.is_empty();     let mut out = json!({"success": true, "alive": alive, "responsive": agent::is_responsive(),@@ -123,8 +126,10 @@ pub fn agent_status(_args: &Value) -> Value {             json!({"workspace": ws.to_string_lossy(), "heartbeatAgeSec": age})).collect::<Vec<_>>(),         "heartbeat": agent::heartbeat(), "workspace": agent::workspace_dir().to_string_lossy(),         "engine": "rust"});-    let parked = !alive && agent::engine_parked();     out["engineParked"] = json!(parked);+    if parked {+        out["parkedWorkspaces"] = json!(agent::parked_workspaces().iter().map(|p| p.to_string_lossy().to_string()).collect::<Vec<_>>());+    }     if parked {         out["_hint"] = json!(PARKED_HINT);     } else if alive && !agent::is_responsive() {
bridge-rs/src/trace.rsadded+120
@@ -0,0 +1,120 @@+//! A step trace that outlives the process (adom/altium-bridge#30).+//!+//! On one machine the bridge died during `altium_agent_start` 266 times with nothing left behind: no panic (the hook+//! never ran), and ab rewrites the bridge's console log on every respawn. So every request and every step of the+//! agent lifecycle is appended here, beside the exe, as it happens. When the next process starts it reads the trace:+//! a request that began and never ended is where the last process died, and that goes into the crash log with the+//! steps before it.+use std::io::Write;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{SystemTime, UNIX_EPOCH};++const CAP: u64 = 1024 * 1024;+static NEXT_ID: AtomicU64 = AtomicU64::new(1);++pub fn path() -> std::path::PathBuf {+    std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf()))+        .unwrap_or_else(std::env::temp_dir).join("altium-bridge-trace.log")+}++fn now_ms() -> u128 {+    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0)+}++/// The address of a local: how deep this thread's stack is, to within a frame. Steps that walk down by megabytes are+/// recursion.+#[inline(never)]+fn stack_addr() -> usize {+    let x = 0u8;+    std::hint::black_box(&x) as *const u8 as usize+}++fn write_line(line: &str) {+    let p = path();+    if std::fs::metadata(&p).map(|m| m.len() > CAP).unwrap_or(false) {+        let _ = std::fs::rename(&p, p.with_extension("log.1"));+    }+    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {+        let _ = f.write_all(line.as_bytes());+    }+}++/// One step: time, pid, thread, heal depth, stack address, what.+pub fn step(what: &str) {+    let t = std::thread::current();+    let line = format!("{} pid={} thread={}:{:?} heal={} sp={:#x} {}\n", now_ms(), std::process::id(),+        t.name().unwrap_or("?"), t.id(), crate::agent::heal_depth(), stack_addr(), what.replace('\n', " "));+    write_line(&line);+}++/// A request began: its id, to pair with `end`.+pub fn begin(verb: &str) -> u64 {+    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);+    step(&format!("BEGIN #{id} {verb}"));+    id+}++pub fn end(id: u64, verb: &str, ms: u128, ok: Option<bool>) {+    step(&format!("END #{id} {verb} {ms}ms success={}", ok.map(|b| b.to_string()).unwrap_or_else(|| "?".into())));+}++/// What the previous process was doing when it ended, if it ended inside a request. Pure over the trace text.+pub fn unfinished(text: &str, this_pid: u32) -> Option<String> {+    let lines: Vec<&str> = text.lines().collect();+    let pid_of = |l: &str| l.split_whitespace().nth(1).and_then(|f| f.strip_prefix("pid=")).and_then(|p| p.parse::<u32>().ok());+    let last_pid = lines.iter().rev().filter_map(|l| pid_of(l)).find(|p| *p != this_pid)?;+    let mine: Vec<&str> = lines.iter().copied().filter(|l| pid_of(l) == Some(last_pid)).collect();+    let mut open: Vec<(String, String)> = Vec::new();+    for l in &mine {+        if let Some(i) = l.find("BEGIN #") {+            let rest = &l[i + 7..];+            let id = rest.split_whitespace().next().unwrap_or("").to_string();+            let verb = rest.split_whitespace().nth(1).unwrap_or("?").to_string();+            open.push((id, verb));+        } else if let Some(i) = l.find("END #") {+            let id = l[i + 5..].split_whitespace().next().unwrap_or("");+            open.retain(|(o, _)| o != id);+        }+    }+    if open.is_empty() {+        return None;+    }+    let verbs: Vec<String> = open.iter().map(|(id, v)| format!("#{id} {v}")).collect();+    let tail: Vec<&str> = mine.iter().rev().take(25).rev().copied().collect();+    Some(format!("the previous bridge process (pid {last_pid}) ended while running {}; its last steps:\n  {}",+        verbs.join(", "), tail.join("\n  ")))+}++/// At startup: name the request the previous process died in, if any.+pub fn previous_run_report() -> Option<String> {+    let p = path();+    let len = std::fs::metadata(&p).ok()?.len();+    let mut f = std::fs::File::open(&p).ok()?;+    use std::io::{Read, Seek, SeekFrom};+    let from = len.saturating_sub(256 * 1024);+    f.seek(SeekFrom::Start(from)).ok()?;+    let mut buf = Vec::new();+    f.read_to_end(&mut buf).ok()?;+    let text = String::from_utf8_lossy(&buf);+    unfinished(&text, std::process::id())+}++#[cfg(test)]+mod tests {+    use super::unfinished;++    #[test]+    fn names_the_request_the_last_process_died_in() {+        let t = "1 pid=10 thread=a:ThreadId(2) heal=0 sp=0x1 BEGIN #1 altium_status\n\+                 2 pid=10 thread=a:ThreadId(2) heal=0 sp=0x1 END #1 altium_status 3ms success=true\n\+                 3 pid=10 thread=a:ThreadId(3) heal=0 sp=0x1 BEGIN #2 altium_agent_start\n\+                 4 pid=10 thread=a:ThreadId(3) heal=1 sp=0x1 start: enter\n";+        let r = unfinished(t, 99).unwrap();+        assert!(r.contains("pid 10") && r.contains("#2 altium_agent_start") && r.contains("start: enter"), "{r}");+        // every request finished: nothing to say+        let done = "1 pid=10 thread=a heal=0 sp=0x1 BEGIN #1 x\n2 pid=10 thread=a heal=0 sp=0x1 END #1 x 1ms success=true\n";+        assert!(unfinished(done, 99).is_none());+        // this process's own lines are not the previous one's+        assert!(unfinished("1 pid=99 thread=a heal=0 sp=0x1 BEGIN #1 x\n", 99).is_none());+    }+}
bridge-rs/src/verbs.rs+6−3
@@ -263,21 +263,24 @@ fn describe() -> Value {         // ---- agent / REPL ----         verb_doc("agent_start", "Bootstrap the resident DelphiScript agent inside Altium (renders the script, runs it through the -R lane, waits for the heartbeat). Optional: every agent-backed verb does this on demand.",             json!({"waitSec": "int, default 45 - how long to wait for the first heartbeat"}),-            json!({"startedInSec": "float", "alreadyRunning": "bool", "generation": "string - AdomAgent_<digest>", "install": "object - the rendered script", "strayHelpersKilled": "[pid]"}), 120,+            json!({"startedInSec": "float", "alreadyRunning": "bool", "generation": "string - AdomAgent_<digest>", "install": "object - the rendered script", "strayHelpersKilled": "[pid]", "parkedLoopStopped": "[step] - an earlier loop was parked in the debugger and was stopped first"}), 120,             "After success altium_eval / altium_run_command / altium_state go through the agent in milliseconds. Do NOT use altium_run_script while it is up.",             &["agent_status", "agent_stop", "agent_recover", "eval"],             &["The bootstrap ACTIVATES Altium for a moment (it opens the .PrjScr in the script editor); the bridge hands the user's foreground window back.",               "no_heartbeat = the engine halted behind a script Error modal: altium_check_dialogs, then altium_agent_recover.",               "agent_halted_after_start = the agent came up and stopped on its first command (errorShot is Altium's box). The bridge already stopped the script, so Altium is not left parked; it is a bug in the agent on this Altium build: report it with errorShot (#30).",+              "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,             "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!({}),-            json!({"alive": "bool - selected instance", "responsive": "bool", "residentAnywhere": "bool", "liveWorkspaces": "[{workspace, heartbeatAgeSec}]", "heartbeat": "{ageSec, tick, ...} | null", "workspace": "path", "engineParked": "bool"}), 10,+            json!({"alive": "bool - selected instance", "responsive": "bool", "residentAnywhere": "bool", "liveWorkspaces": "[{workspace, heartbeatAgeSec}]", "heartbeat": "{ageSec, tick, ...} | null", "workspace": "path", "engineParked": "bool", "parkedWorkspaces": "[path] - when parked"}), 10,             "alive with responsive:false = the loop is busy inside a long Altium process: wait, do not start a second agent. Not alive: call the verb you need, it bootstraps.",-            &["agent_start", "agent_recover", "readiness"], &["residentAnywhere:true with alive:false is a freeze-on-close hazard: altium_close tears every loop down before the app exits."], json!({})),+            &["agent_start", "agent_recover", "readiness"], &["residentAnywhere:true with alive:false is a freeze-on-close hazard: altium_close tears every loop down before the app exits.",+              "engineParked:true = a loop started in this Altium and stopped in its script debugger without exiting, whatever document is in front (read from the agent's own files, not the window title). alive is false then, even within a minute of its last heartbeat. altium_agent_recover, or the next agent verb, stops it."], json!({})),         verb_doc("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.",             json!({"reason": "string - optional, recorded in steps"}),             json!({"steps": "[{reason} | {dialog, pressed} | {editScriptStop, exited, sec} | busy-notice reap]", "engineFree": "bool - verified by starting a fresh agent"}), 240,
bridge-rs/src/win32.rs+41−1
@@ -169,6 +169,41 @@ mod proc_imp {         }     } +    #[repr(C)]+    #[derive(Default, Clone, Copy)]+    struct FileTime { lo: u32, hi: u32 }+    #[link(name = "kernel32")]+    extern "system" {+        fn GetProcessTimes(h: isize, create: *mut FileTime, exit: *mut FileTime, kernel: *mut FileTime, user: *mut FileTime) -> i32;+        fn SetStdHandle(id: u32, h: isize) -> i32;+    }+    const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;++    /// When `pid` started. `None` when it cannot be opened (gone, or no access).+    pub fn process_start_time(pid: u32) -> Option<std::time::SystemTime> {+        unsafe {+            let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);+            if h == 0 { return None; }+            let (mut c, mut e, mut k, mut u) = (FileTime::default(), FileTime::default(), FileTime::default(), FileTime::default());+            let ok = GetProcessTimes(h, &mut c, &mut e, &mut k, &mut u);+            CloseHandle(h);+            if ok == 0 { return None; }+            // 100 ns ticks since 1601-01-01+            let ticks = ((c.hi as u64) << 32) | c.lo as u64;+            let unix_100ns = ticks.checked_sub(116_444_736_000_000_000)?;+            Some(std::time::UNIX_EPOCH + std::time::Duration::from_nanos(unix_100ns * 100))+        }+    }++    /// Point this process's stderr at `file`. Rust's own fatal messages (a stack overflow, an allocation failure)+    /// go to stderr and then end the process with no panic hook; ab rewrites the bridge's console log on every+    /// respawn, so they were lost (#30). The file must stay open for the life of the process.+    pub fn redirect_stderr(file: &std::fs::File) -> bool {+        use std::os::windows::io::AsRawHandle;+        const STD_ERROR_HANDLE: u32 = -12i32 as u32;+        unsafe { SetStdHandle(STD_ERROR_HANDLE, file.as_raw_handle() as isize) != 0 }+    }+     /// Terminate `pid`. Returns whether the terminate call succeeded.     pub fn kill(pid: u32) -> bool {         unsafe {@@ -245,7 +280,12 @@ pub fn child_windows(_parent: i64) -> Vec<ChildWin> { vec![] } #[cfg(windows)] pub use imp::{post_message_close, post_quit_to_thread, visible_windows, WinRow}; #[cfg(windows)]-pub use proc_imp::{kill, pids_of};+pub use proc_imp::{kill, pids_of, process_start_time, redirect_stderr};++#[cfg(not(windows))]+pub fn process_start_time(_pid: u32) -> Option<std::time::SystemTime> { None }+#[cfg(not(windows))]+pub fn redirect_stderr(_file: &std::fs::File) -> bool { false }  #[cfg(not(windows))] pub fn pids_of(_image: &str) -> Option<Vec<u32>> {
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.92",+  "version": "0.2.93",   "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.92",+  "version": "0.2.93",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.92+0.2.93
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.92",+  "version": "0.2.93",   "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",