← Commit history
Cargo.lock+11−11
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-sys",  "roxmltree",@@ -49,7 +49,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "serde",@@ -79,7 +79,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.155"+version = "0.2.156" dependencies = [  "aiflow-sys",  "serde",@@ -120,7 +120,7 @@ dependencies = [  [[package]] name = "aiflow-sys"-version = "0.2.155"+version = "0.2.156" dependencies = [  "serde_json", ]
Cargo.toml+1−1
@@ -15,7 +15,7 @@ members = [ ]  [workspace.package]-version = "0.2.155"+version = "0.2.156" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow
⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+11−2
@@ -1,5 +1,6 @@ //! adom-aiflow: the board loop as one command, with the clock, the negotiation and the finish line. //! Every reply starts with OK: or ERROR: and carries Hint: lines that depend on this board and run.+mod run_editor; mod bare_lands; mod part_follow; mod kicad_versions;@@ -4315,7 +4316,11 @@ fn main() {     };     if let Some(h) = input_hint { let _ = INPUT_HINT.set(h); }     // issue #223: the run's own editor (`capture open --isolated`) answers every live call of the run-    if let Some(sock) = run_kicad_socket(&run_dir(&cli)) { std::env::set_var("ADOM_AIFLOW_KICAD_SOCKET", sock); }+    if let Some(sock) = run_kicad_socket(&run_dir(&cli)) {+        std::env::set_var("ADOM_AIFLOW_KICAD_SOCKET", sock);+        // issue #296: when that editor has closed or exited, the first live call reopens it (or says why it could not)+        aiflow_bridge::revive::set(run_editor::reviver(run_dir(&cli)));+    }     // issue #170: the media worker writes nothing to the run's ledger or run.json itself (no turn either)     if let Cmd::MediaWorker = &cli.cmd { media_worker_run(&run_dir(&cli)); return; }     // A host stop hook must not open windows, start captures or append timing events.@@ -6677,7 +6682,8 @@ fn main() {             if !Bridge::ok(&zs) {                 r.outcome("measure", json!({"failed":true,"errorCode":zs["errorCode"],"reply":zs}));                 r.save().unwrap();-                err("native copper measurement did not settle", &["The refill request was not replayed. Inspect zone-state.json and the native board before retrying a read.".into()]);+                let (m, h) = run_editor::measure_failure(&zs, !r.data["kicadIsolated"].is_null());+                err(&m, &[h]);             }             r.outcome("measure", json!({"filledAreaByLayerMm2": zs["filledAreaByLayerMm2"], "coveragePercent": zs["filledCoverageByLayerPercent"], "zones": zs["zoneCount"]}));             r.save().unwrap();@@ -7639,6 +7645,9 @@ fn main() {                 }                 "open" => {                     let raise = screen_mode(&mut r).may_raise();+                    // issue #296: the run's own editor recorded from an earlier `capture open --isolated` and gone since: forget it,+                    // so this editor answers the run's live calls (a run's own editor still running keeps answering them)+                    if let Some(gone) = run_editor::forget_if_gone(&mut r, &br, &rb) { note(&gone, &[]); }                     let (hwnd, shown) = br.open_board(&rb, reason.as_deref().unwrap_or(&format!("aiflow run {engine} on the test box")), raise).unwrap_or_else(|rep| err(&format!("could not open the board: {}", rep["error"].as_str().filter(|_| rep.get("reply").is_some()).map(str::to_string).unwrap_or_else(|| rep.to_string().chars().take(300).collect::<String>())), &[]));                     r.data["captures"].as_array_mut().unwrap().push(json!({"opened": now(), "hwnd": hwnd, "window": shown}));                     r.save().unwrap();
crates/adom-aiflow/src/run_editor.rsadded+124
@@ -0,0 +1,124 @@+//! Issue #296 (Mohit Singh): the run's own KiCad editor (`capture open --isolated`) after it has closed or exited.+//! Its pipe stays in run.json, so before this every live call went to a pipe that cannot come back, `measure`+//! said only that the copper "did not settle", and opening the board the ordinary way did not help.+//! Now: the first live call of a command that finds the pipe gone reopens the run's editor (`reviver`), a+//! `capture open` forgets a gone editor so the shared one answers (`forget_if_gone`), and `measure` names the+//! editor when it is the reason (`measure_failure`).+use aiflow_bridge::isolated::Refusal;+use aiflow_bridge::revive;+use aiflow_bridge::Bridge;+use aiflow_run::{now, Run};+use serde_json::{json, Value};+use std::path::PathBuf;++/// "the run's own KiCad editor (pid N, opened by `capture open --isolated`)".+fn who(rec: &Value) -> String {+    let pid = rec["pid"].as_i64().map(|p| format!("pid {p}, ")).unwrap_or_default();+    format!("the run's own KiCad editor ({pid}opened by `capture open --isolated`)")+}++/// How this command reopens the run's editor when its pipe is gone: the same open `capture open --isolated`+/// makes (same board, same pinned KiCad, the screen mode's rule for raising it), recorded in run.json.+pub fn reviver(dir: PathBuf) -> revive::Reviver {+    Box::new(move |br: &Bridge| {+        let mut r = Run::open(&dir).ok_or_else(|| format!("the run in {} could not be read to reopen its KiCad editor", dir.display()))?;+        let rec = r.data["kicadIsolated"].clone();+        let old = rec["socketPath"].as_str().unwrap_or("").to_string();+        let board = rec["board"].as_str().or(r.data["remoteBoard"].as_str()).unwrap_or("").to_string();+        let gone = format!("{} no longer answers: its pipe {old} is gone, so it was closed or exited", who(&rec));+        if board.is_empty() { return Err(format!("{gone}. `adom-aiflow capture open --isolated` starts it again.")); }+        let raise = crate::screen_mode(&mut r).may_raise();+        let kv = rec["kicadVersion"].as_str().map(str::to_string);+        match br.open_isolated(&board, "aiflow: reopen the run's own KiCad editor (it had closed)", raise, kv.as_deref()) {+            Ok(iso) if iso.socket == old => Err(format!("{gone}; opening it again answered the same pipe, which still does not answer. Close that KiCad (`adom-aiflow capture close --discard`), then `adom-aiflow capture open --isolated`.")),+            Ok(iso) => {+                std::env::set_var("ADOM_AIFLOW_KICAD_SOCKET", &iso.socket);+                let mut now_rec = iso.record(&board, &now());+                if !rec["kicadVersion"].is_null() { now_rec["kicadVersion"] = rec["kicadVersion"].clone(); }+                r.data["kicadIsolated"] = now_rec.clone();+                if let Some(c) = r.data["captures"].as_array_mut() { c.push(json!({"opened": now(), "hwnd": iso.hwnd, "window": iso.title, "isolated": true, "reopened": true})); }+                r.log("isolated-editor-reopened", json!({"was": {"pid": rec["pid"], "socketPath": old}, "pid": iso.pid, "socketPath": iso.socket, "why": "its pipe was gone"}));+                // the command holds its own copy of run.json: its later saves write the new editor, not the gone one+                aiflow_run::pin("kicadIsolated", now_rec);+                r.save()?;+                crate::note(&format!("{} was no longer running; reopened it (pid {}, pipe {}) and the call went on", who(&rec), iso.pid.map(|p| p.to_string()).unwrap_or("?".into()), iso.socket), &[]);+                Ok(iso.socket)+            }+            // a KiCad that was ended rather than closed leaves its lock files beside the board: with no editor showing the+            // board, the lock is that one's, not another editor's+            Err(Refusal::BoardLocked(m)) if br.board_window_any(&board, None).is_none() => Err(format!("{gone}, and a new one was refused as locked ({m}), but no KiCad editor shows the board: the lock is most likely left over from the editor that exited. Delete {} beside the board (KiCad's lock files), then `adom-aiflow capture open --isolated`.", lock_files(&board))),+            Err(Refusal::BoardLocked(m)) => Err(format!("{gone}, and a new one was refused because another KiCad has the board open ({m}). Keep working in that editor with `adom-aiflow capture open` (the run then forgets its own), or save and close it and run `adom-aiflow capture open --isolated`.")),+            Err(Refusal::KicadVersion(m) | Refusal::Unsupported(m) | Refusal::UnsavedChanges(m) | Refusal::Other(m)) => Err(format!("{gone}; opening it again failed: {m}. `adom-aiflow capture open --isolated` starts it again.")),+        }+    })+}++/// KiCad's lock files for a board: `~b.kicad_pcb.lck` and `~b.kicad_pro.lck` in the board's folder.+fn lock_files(board: &str) -> String {+    let name = board.rsplit(['/', '\\']).next().unwrap_or(board);+    let stem = name.strip_suffix(".kicad_pcb").unwrap_or(name);+    format!("~{stem}.kicad_pcb.lck and ~{stem}.kicad_pro.lck")+}++/// Before a shared `capture open`: a run's own editor whose pipe is gone is forgotten (the line says so), so+/// the editor this open makes answers the run's live calls. A run's own editor that still answers is kept.+pub fn forget_if_gone(r: &mut Run, br: &Bridge, board: &str) -> Option<String> {+    let rec = r.data["kicadIsolated"].clone();+    let sock = rec["socketPath"].as_str().filter(|s| !s.trim().is_empty())?;+    // the call names its own pipe, so it is never reopened on the way+    let probe = br.call("kicad_routing_state", &json!({"filePath": board, "socketPath": sock}));+    if !revive::pipe_gone(&probe) { return None; }+    r.data["kicadIsolated"] = Value::Null;+    aiflow_run::pin("kicadIsolated", Value::Null);+    std::env::remove_var("ADOM_AIFLOW_KICAD_SOCKET");+    r.log("isolated-editor-forgotten", json!({"editor": rec, "why": "its pipe was gone when the shared editor was opened"}));+    // kept even when the open below fails: the record named an editor that cannot answer again+    let _ = r.save();+    Some(format!("{} no longer answers (its pipe is gone); the run forgot it, and the editor opened now answers the run's live calls", who(&rec)))+}++/// `measure`'s ERROR line and hint when the copper was not read: the editor when it is the reason.+pub fn measure_failure(zs: &Value, isolated: bool) -> (String, String) {+    if let Some(why) = revive::editor_gone(zs) {+        return ("native copper measurement did not run: the run's own KiCad editor is gone".into(), why);+    }+    let last = if zs["lastReply"].is_object() { &zs["lastReply"] } else { zs };+    if revive::pipe_gone(last) {+        let h = if isolated { "The run's own editor (`capture open --isolated`) does not answer on its pipe: `adom-aiflow capture open --isolated` starts it again." }+            else { "Open the board in the PCB editor with KiCad's API server on (`adom-aiflow capture open`), then `measure` again." };+        return ("native copper measurement did not run: the KiCad editor's API pipe does not answer".into(), h.into());+    }+    ("native copper measurement did not settle".into(),+     "The refill request was not replayed. The editor answered, but two reads of its copper did not match: look at the run's KiCad editor (a dialog open, a refill still running), then `measure` again. zone-state.json's lastReply holds its last answer.".into())+}++#[cfg(test)]+mod tests {+    use serde_json::json;++    #[test]+    fn measure_names_the_editor_when_it_is_the_reason() {+        let gone = json!({"success": false, "errorCode": "zone_readback_unsettled", "lastReply": {"errorCode": "ipc_unavailable", "runEditorGone": true, "error": "the run's own KiCad editor (pid 7) no longer answers; `adom-aiflow capture open --isolated` starts it again"}});+        let (m, h) = super::measure_failure(&gone, true);+        assert!(m.contains("editor is gone") && h.contains("capture open --isolated"));+        let dead = json!({"success": false, "errorCode": "zone_readback_unsettled", "lastReply": {"errorCode": "ipc_unavailable", "error": "KiCad IPC socket not available"}});+        assert!(super::measure_failure(&dead, true).1.contains("capture open --isolated"));+        assert!(super::measure_failure(&dead, false).1.contains("`adom-aiflow capture open`"));+        let unsettled = json!({"success": false, "errorCode": "zone_readback_unsettled", "lastReply": {"success": true}});+        let (m, h) = super::measure_failure(&unsettled, true);+        assert_eq!(m, "native copper measurement did not settle");+        assert!(h.contains("editor"));+    }++    #[test]+    fn a_left_over_lock_is_named() {+        assert_eq!(super::lock_files("C:/Users/x/b.kicad_pcb"), "~b.kicad_pcb.lck and ~b.kicad_pro.lck");+        assert_eq!(super::lock_files("C:\\Users\\x\\my board.kicad_pcb"), "~my board.kicad_pcb.lck and ~my board.kicad_pro.lck");+    }++    #[test]+    fn the_gone_editor_is_named_by_its_pid() {+        assert!(super::who(&json!({"pid": 4242})).contains("pid 4242"));+        assert!(!super::who(&json!({})).contains("pid"));+    }+}
crates/aiflow-bridge/src/lib.rs+21−5
@@ -15,6 +15,7 @@ pub mod focus; pub mod isolated; pub mod landing; pub mod recorder;+pub mod revive; pub use landing::Landing;  /// Pulls of one clip before the stop gives up and flags it `pullFailed`: the first and two retries.@@ -60,6 +61,7 @@ fn read_zone_state_with( ) -> Value {     let mut reply = call(refill);     if !retryable_read(&reply) { return reply; }+    if reply["runEditorGone"] == true { return reply; }     if !refill && Bridge::ok(&reply) && reply["filledAreaByLayerMm2"].is_object() && reply["revision"].is_string() && reply["revisionUsable"] != false { return reply; }     // Discard even old bridges' synchronous-looking refill reply. Mutation is     // requested only once. Repeated delayed snapshots are observed stability,@@ -69,6 +71,8 @@ fn read_zone_state_with(         wait();         reply = call(false);         if !retryable_read(&reply) { return reply; }+        // issue #296: the run's own editor is gone and could not be reopened: waiting will not bring it back+        if reply["runEditorGone"] == true { break; }         if Bridge::ok(&reply) && reply["filledAreaByLayerMm2"].is_object() && reply["revision"].is_string() && reply["revisionUsable"] != false {             if !refill || previous.as_ref().map(|p| p["revision"] == reply["revision"] && p["filledAreaByLayerMm2"] == reply["filledAreaByLayerMm2"]).unwrap_or(false) {                 reply["readbackEvidence"] = json!(if refill { "two delayed matching native snapshots after refill request" } else { "native snapshot" });@@ -370,7 +374,7 @@ fn read_socket_args(verb: &str, args: &Value, socket: Option<&str>) -> Value { }  /// The live (IPC) verbs a task-owned, isolated KiCad instance answers, reads and edits alike.-const LIVE_IPC_VERBS: &[&str] = &["kicad_routing_state", "kicad_routing_validate", "kicad_placement_state",+pub(crate) const LIVE_IPC_VERBS: &[&str] = &["kicad_routing_state", "kicad_routing_validate", "kicad_placement_state",     "kicad_placement_validate", "kicad_zone_state", "kicad_move_footprint", "kicad_route_net", "kicad_remove_route",     "kicad_apply_tracks", "kicad_apply_zone_plan", "kicad_add_zone", "kicad_select_net", "kicad_select_clear", "kicad_zoom_to",     // issue #223 (KiCad Bridge 1.1.5): save and reload answer on the isolated editor's pipe too@@ -452,14 +456,26 @@ impl Bridge {     pub fn call(&self, verb: &str, args: &Value) -> Value {         // every board operation goes to the run's EDA backend (eda.rs; docs/eda-backends.md): the flow's         // verbs keep their historical kicad_* names, and the backend answers them in its own tool-        let r = if verb.starts_with("kicad_") {-            let backend = eda::for_call(args);-            eda::dispatch(&*backend, &|v: &str, a: &Value| self.raw_call(v, a), verb, args)-        } else { self.raw_call(verb, args) };+        let mut r = self.call_once(verb, args);+        // issue #296: the run's own editor closed or exited: reopen it once and ask again, or say what happened+        if revive::applies(verb, args, &r, std::env::var("ADOM_AIFLOW_KICAD_SOCKET").ok().as_deref()) {+            match revive::revive(self) {+                Some(Ok(_)) => r = self.call_once(verb, args),+                Some(Err(why)) => revive::explain(&mut r, &why),+                None => {}+            }+        }         if let Some(w) = not_as_planned_warning(verb, &r) { eprintln!("{w}"); }         r     } +    fn call_once(&self, verb: &str, args: &Value) -> Value {+        if verb.starts_with("kicad_") {+            let backend = eda::for_call(args);+            eda::dispatch(&*backend, &|v: &str, a: &Value| self.raw_call(v, a), verb, args)+        } else { self.raw_call(verb, args) }+    }+     /// One adom-bridge verb with a hard wall-clock limit on the CLI process (issue #98): past it the     /// process is killed and the reply is `errorCode: aiflow_timeout`.     /// WASI has no threads: the host runs the call to completion (the host enforces its own timeout).
crates/aiflow-bridge/src/revive.rsadded+86
@@ -0,0 +1,86 @@+//! Issue #296 (Mohit Singh): the run's own KiCad editor (`capture open --isolated`) closed or exited, its pipe stayed in+//! run.json, and every live call of the run went on asking a pipe that cannot come back (`ipc_unavailable`, quoted as a+//! socket path, while a good editor could sit open on the default pipe). Now the first live call that finds the run's+//! pipe gone reopens the run's editor once (the command registers how, `set`) and is asked again; when it cannot be+//! reopened, the reply says which editor is gone and what to run instead of the bare socket error.+use serde_json::{json, Value};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Mutex, OnceLock};++/// Reopens the run's own editor: the new pipe, or why it could not (said to the AI as it is).+pub type Reviver = Box<dyn Fn(&crate::Bridge) -> Result<String, String> + Send + Sync>;++static REVIVER: OnceLock<Reviver> = OnceLock::new();+static OUTCOME: Mutex<Option<Result<String, String>>> = Mutex::new(None);+static BUSY: AtomicBool = AtomicBool::new(false);++/// Register how this command reopens the run's own editor (only when its pipe came from run.json).+pub fn set(f: Reviver) {+    let _ = REVIVER.set(f);+}++/// KiCad's API pipe does not exist: the editor that owned it closed or exited (a busy editor answers `ipc_timeout`).+pub fn pipe_gone(reply: &Value) -> bool {+    let code = |v: &Value| v["errorCode"].as_str().map(str::to_string);+    code(reply).or_else(|| code(&reply["data"])).as_deref() == Some("ipc_unavailable")+}++/// A live call that went to the run's pipe (no socketPath of its own) and found it gone.+pub(crate) fn applies(verb: &str, args: &Value, reply: &Value, run_socket: Option<&str>) -> bool {+    crate::LIVE_IPC_VERBS.contains(&verb) && args.get("socketPath").is_none() && run_socket.is_some_and(|s| !s.trim().is_empty()) && pipe_gone(reply)+}++/// Reopen the run's editor, once per command: later calls get the same outcome. None when no reviver is set (the+/// pipe came from ADOM_AIFLOW_KICAD_SOCKET itself) or while it is reopening (its own calls are never revived).+pub(crate) fn revive(br: &crate::Bridge) -> Option<Result<String, String>> {+    let f = REVIVER.get()?;+    if let Some(done) = OUTCOME.lock().ok()?.clone() { return Some(done); }+    if BUSY.swap(true, Ordering::SeqCst) { return None; }+    let out = f(br);+    BUSY.store(false, Ordering::SeqCst);+    if let Ok(mut g) = OUTCOME.lock() { *g = Some(out.clone()); }+    Some(out)+}++/// The reply of a call whose editor could not be reopened: the reason in `error`, the pipe's own answer kept.+pub fn explain(reply: &mut Value, why: &str) {+    let was = reply.get("error").cloned().unwrap_or(Value::Null);+    if let Some(o) = reply.as_object_mut() {+        o.insert("pipeError".into(), was);+        o.insert("error".into(), json!(why));+        o.insert("runEditorGone".into(), json!(true));+    }+}++/// A reply (or the last reply inside a `zone_readback_unsettled`) that says the run's own editor is gone.+pub fn editor_gone(reply: &Value) -> Option<String> {+    [reply, &reply["lastReply"]].into_iter().find(|r| r["runEditorGone"] == true).and_then(|r| r["error"].as_str()).map(str::to_string)+}++#[cfg(test)]+mod tests {+    use serde_json::json;++    #[test]+    fn only_a_gone_run_pipe_is_revived() {+        let gone = json!({"success": false, "errorCode": "ipc_unavailable", "error": "KiCad IPC socket not available at ipc://x/api.sock"});+        assert!(super::applies("kicad_zone_state", &json!({"filePath": "b"}), &gone, Some("ipc://x/api.sock")));+        assert!(super::applies("kicad_zone_state", &json!({}), &json!({"data": {"errorCode": "ipc_unavailable"}}), Some("s")));+        // a call naming its own pipe, a window verb, no run pipe, a busy editor: left as they are+        assert!(!super::applies("kicad_zone_state", &json!({"socketPath": "ipc://x/api.sock"}), &gone, Some("ipc://x/api.sock")));+        assert!(!super::applies("kicad_window_info", &json!({}), &gone, Some("s")));+        assert!(!super::applies("kicad_zone_state", &json!({}), &gone, None));+        assert!(!super::applies("kicad_zone_state", &json!({}), &json!({"errorCode": "ipc_timeout"}), Some("s")));+    }++    #[test]+    fn an_editor_that_could_not_be_reopened_is_said_plainly() {+        let mut r = json!({"success": false, "errorCode": "ipc_unavailable", "error": "KiCad IPC socket not available at ipc://x"});+        super::explain(&mut r, "the run's own KiCad editor (pid 7) is gone; `adom-aiflow capture open --isolated` starts it again");+        assert_eq!(r["errorCode"], "ipc_unavailable");+        assert_eq!(r["pipeError"], "KiCad IPC socket not available at ipc://x");+        let unsettled = json!({"success": false, "errorCode": "zone_readback_unsettled", "lastReply": r});+        assert!(super::editor_gone(&unsettled).unwrap().contains("capture open --isolated"));+        assert!(super::editor_gone(&json!({"errorCode": "ipc_unavailable"})).is_none());+    }+}
crates/aiflow-run/src/lib.rs+11
@@ -118,6 +118,14 @@ fn merge_steps(m: &mut serde_json::Map<String, Value>, d: &serde_json::Map<Strin     } } +static PINNED: std::sync::Mutex<Vec<(String, Value)>> = std::sync::Mutex::new(Vec::new());++/// Issue #296: every later save of this process writes `key` as `value`, whatever copy of run.json the+/// command holds (the run's KiCad editor reopened inside a live call, while the command keeps its own Run).+pub fn pin(key: &str, value: Value) {+    if let Ok(mut p) = PINNED.lock() { p.retain(|(k, _)| k != key); p.push((key.to_string(), value)); }+}+ impl Run {     pub fn open(dir: &Path) -> Option<Run> {         let f = dir.join("run.json");@@ -213,6 +221,9 @@ impl Run {     pub fn save(&self) -> Result<(), String> {         std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;         let mut data = self.data.clone();+        // issue #296: a key this process changed behind the command's own copy (the run's KiCad editor reopened+        // during a live call) is written as it is now, not as the command loaded it+        if let (Ok(p), Some(m)) = (PINNED.lock(), data.as_object_mut()) { for (k, v) in p.iter() { m.insert(k.clone(), v.clone()); } }         if let Some(disk) = std::fs::read_to_string(self.dir.join("run.json")).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) {             if let (Some(d), Some(m)) = (disk.as_object(), data.as_object_mut()) {                 for (k, v) in d {
docs/release-0.2.156.mdadded+17
@@ -0,0 +1,17 @@+# adom-aiflow 0.2.156++Issue #296 (Mohit Singh): the run's own KiCad editor after it has closed or exited.++- **The run's editor is reopened by itself.** When a live call finds the pipe of the run's own editor (`capture open --isolated`) gone, AI Flow reopens that editor once (same board, same pinned KiCad, the screen mode's rule for raising it) and asks again. A NOTE names the old and new pid, run.json records the new editor, and run.jsonl logs `isolated-editor-reopened`.+- **When it cannot be reopened, the error says why and what to run** instead of quoting a socket path that cannot come back:+  - another KiCad has the board open: keep working there with `capture open`, or close it and `capture open --isolated`;+  - KiCad left its lock files behind after being ended and no editor shows the board: delete `~<board>.kicad_pcb.lck` and `~<board>.kicad_pro.lck`, then `capture open --isolated`.+- **`capture open` forgets a gone run editor.** The editor it opens then answers the run's live calls; a run editor that still answers is kept.+- **`measure` names the editor when it is the reason.** "did not run: the run's own KiCad editor is gone" with the reason, or "the KiCad editor's API pipe does not answer" with the command to open it. A copper read that truly did not settle now points at the editor, not at zone-state.json.+- `measure` stops waiting at once when the run's editor is gone and could not be reopened (before, it retried for about 90 s).++Tested on Windows 11 with KiCad 10.0.8 and KiCad Bridge 1.1.17:+- the editor ended with its lock files left: the error named the lock files;+- the lock files deleted: `measure` reopened the editor and read the board;+- the editor closed normally: `measure` reopened it again;+- `capture open` after a close: the gone editor was forgotten.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.155",+  "version": "0.2.156",   "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.155",+  "version": "0.2.156",   "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.",
skills/adom-aiflow/SKILL.md+4
@@ -400,6 +400,10 @@ add a load only to get a solve.  The AI's time on a run is the sum of its sessions: one per human prompt, from the prompt to the AI's done, with idle gaps (over 15 min, no command running) cut out. The first prompt is `start --prompt-time`; every follow-up prompt is `prompt --text "..."` (`--at <time>` when you start late; `--rebaseline <board>` when the human's change moves the molecule interface: that board's fixed references become the baseline, in the same run, clock and ledger); the answer's end is `done --message "..."` (`deliver` is the done of the first task). Say `done` the moment an answer is complete, so nothing idle is charged; work after a done with no `prompt` mark is listed as an unmarked follow-up, one row per idle gap. The delivery number on the page is the AI time from the first prompt to `deliver`; follow-ups have their own rows. `sessions` prints the table. The per-step table and the video's run clock ("AI TIME, THIS RUN") count active seconds only. +## When the run's own editor has closed++A run's own KiCad editor (`capture open --isolated`) that was closed or exited is reopened by the first live call that finds its pipe gone: a NOTE says so with the new pid, run.json records it, and the command goes on. When it cannot be reopened the error says why and what to do: another KiCad has the board open (keep working there with `capture open`, which forgets the gone editor, or close it and `capture open --isolated`), or KiCad left its lock files (`~<board>.kicad_pcb.lck`, `~<board>.kicad_pro.lck`) behind after being ended, with no editor showing the board (delete them, then `capture open --isolated`).+ ## Reload after an offline edit  `capture reload` makes KiCad's editor match the board file after an edit made outside it (`kicad_reload_board`, KiCad's own Revert). A KiCad bridge without that verb (the macOS 2.0.x builds) gets the same result another way: AI Flow closes the board's editor and opens the file again, in the run's own isolated editor when the run has one. Closing never saves, so an editor with unsaved edits is refused as a reload refuses it; `capture reload --discard` drops them.