main
Colby Knox 0.2.86: sch_batch and log_tail (the standard's last two), engine 0.22.0 (schematic_review design checks, placement scor… 2e9e947
//! log_tail: what Altium said about itself since an offset (EDA Bridge Standard #29), so a verb that looks
//! successful while Altium complains is caught. Altium's voice is its Messages panel (compile, ERC, DRC and script
//! messages) and its own log files (start-up and shut-down traces). The panel empties on every compile, so its
//! offsets would mean nothing: each call captures what is new into this bridge's own file, and offsets are bytes of
//! that file. The dialogs the bridge answered stay in dialog_log, so the two never double up.
use serde_json::{json, Value};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use std::time::Duration;

fn store() -> PathBuf {
    let base = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into());
    let d = PathBuf::from(base).join(".adom");
    let _ = std::fs::create_dir_all(&d);
    d
}
fn capture_path() -> PathBuf { store().join("altium-log-tail.jsonl") }
fn state_path() -> PathBuf { store().join("altium-log-tail.state.json") }

/// A Messages class or a log line, as the standard's level.
pub fn level(class_or_text: &str) -> &'static str {
    let l = class_or_text.to_ascii_lowercase();
    if l.contains("fatal") || l.contains("error") || l.contains("exception") || l.contains("access violation") { "error" }
    else if l.contains("warning") || l.contains("warn") { "warning" } else { "info" }
}

/// The messages new since the last snapshot: the panel only grows between compiles, so when the old snapshot is a
/// prefix of the new one the rest is new; otherwise the panel was cleared and refilled, and all of it is new. Pure.
pub fn new_messages<'a>(old: &[String], now: &'a [Value]) -> Vec<&'a Value> {
    let keys: Vec<String> = now.iter().map(|m| m.to_string()).collect();
    let skip = if old.len() <= keys.len() && old.iter().zip(&keys).all(|(a, b)| a == b) { old.len() } else { 0 };
    now[skip..].iter().collect()
}

/// Entries from the capture's text starting at a byte offset, at most max_bytes of it, whole lines only. Pure.
pub fn read_from(text: &str, since: usize, max_bytes: usize, errors_only: bool) -> (Vec<Value>, usize, bool) {
    let start = since.min(text.len());
    let mut at = start;
    let mut out = Vec::new();
    let mut truncated = false;
    for line in text[start..].split_inclusive('\n') {
        if !line.ends_with('\n') { break; } // a line still being written
        if at + line.len() - start > max_bytes { truncated = true; break; }
        at += line.len();
        let Ok(v) = serde_json::from_str::<Value>(line.trim_end()) else { continue };
        if errors_only && v["level"] == "info" { continue; }
        out.push(v);
    }
    (out, at, truncated)
}

/// Capture what is new into the file: the Messages panel (with Altium running) and Altium's own log files.
fn capture() -> Value {
    let mut state: Value = std::fs::read_to_string(state_path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}));
    let mut lines: Vec<Value> = Vec::new();
    let now = crate::support::now();
    let mut panel = "not running";
    if crate::health::is_running() && crate::agent::is_alive() {
        let r = crate::agent::call("messages", &[], None, Duration::from_secs(30));
        if let Some(msgs) = r.get("data").filter(|d| d["ok"] == json!(true)).and_then(|d| d["messages"].as_array()).cloned() {
            let old: Vec<String> = state["messages"].as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_string)).collect();
            for m in new_messages(&old, &msgs) {
                let class = m["class"].as_str().unwrap_or("");
                lines.push(json!({"at": now, "source": "messages", "level": level(class), "text": m["text"], "class": class, "document": m["document"], "from": m["source"]}));
            }
            state["messages"] = json!(msgs.iter().map(|m| m.to_string()).collect::<Vec<_>>());
            panel = "read";
        } else { panel = "agent did not answer"; }
    } else if crate::health::is_running() { panel = "agent not resident"; }
    // Altium's log files: the per-install folders under LOCALAPPDATA\Altium
    let la = std::env::var("LOCALAPPDATA").unwrap_or_default();
    let mut files_read = Vec::new();
    for d in std::fs::read_dir(PathBuf::from(&la).join("Altium")).into_iter().flatten().flatten() {
        if !d.file_name().to_string_lossy().starts_with("Altium Designer") { continue; }
        for f in std::fs::read_dir(d.path()).into_iter().flatten().flatten() {
            let p = f.path();
            if !p.extension().map(|x| x.eq_ignore_ascii_case("log")).unwrap_or(false) { continue; }
            let key = p.to_string_lossy().to_string();
            let len = f.metadata().map(|m| m.len()).unwrap_or(0);
            let seen = state["files"][&key].as_u64().unwrap_or(0);
            // a log Altium rewrote from the start is read again from the start
            let from = if len < seen { 0 } else { seen };
            if len > from {
                if let Ok(mut fh) = std::fs::File::open(&p) {
                    let mut buf = Vec::new();
                    if fh.seek(SeekFrom::Start(from)).is_ok() && fh.take(len - from).read_to_end(&mut buf).is_ok() {
                        for l in String::from_utf8_lossy(&buf).lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with("---")) {
                            lines.push(json!({"at": now, "source": p.file_name().map(|n| n.to_string_lossy().to_string()), "level": level(l), "text": l}));
                        }
                    }
                }
            }
            state["files"][&key] = json!(len);
            files_read.push(key);
        }
    }
    if !lines.is_empty() {
        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(capture_path()) {
            for l in &lines { let _ = writeln!(f, "{l}"); }
        }
    }
    let _ = std::fs::write(state_path(), state.to_string());
    json!({"messagesPanel": panel, "logFiles": files_read.len(), "captured": lines.len()})
}

/// altium_log_tail {sinceOffset?, maxBytes?, errorsOnly?}
pub fn log_tail(args: &Value) -> Value {
    let cap = capture();
    let since = args.get("sinceOffset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
    let max = args.get("maxBytes").and_then(|v| v.as_u64()).unwrap_or(200_000) as usize;
    let errors_only = args.get("errorsOnly").and_then(|v| v.as_bool()).unwrap_or(false);
    let text = std::fs::read_to_string(capture_path()).unwrap_or_default();
    let (entries, next, truncated) = read_from(&text, since, max, errors_only);
    json!({"success": true, "entries": entries, "next": next, "truncated": truncated, "sources": cap,
        "_hint": "Pass next as sinceOffset to see only what is new. Messages come from Altium's Messages panel (read while the agent is resident; compile, ERC and DRC fill it) and lines from Altium's own log files; dialogs the bridge answered are in altium_dialog_log, not here."})
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn levels_from_classes_and_lines() {
        assert_eq!(level("[Error]"), "error");
        assert_eq!(level("[Fatal Error]"), "error");
        assert_eq!(level("[Warning]"), "warning");
        assert_eq!(level("T+: 15  Closing Documents"), "info");
    }

    #[test]
    fn only_messages_not_seen_before() {
        let m = |t: &str| json!({"class": "[Warning]", "text": t});
        let now = vec![m("a"), m("b"), m("c")];
        let old: Vec<String> = vec![m("a").to_string(), m("b").to_string()];
        assert_eq!(new_messages(&old, &now).len(), 1);
        // the panel was cleared and refilled: everything is new
        let old: Vec<String> = vec![m("x").to_string()];
        assert_eq!(new_messages(&old, &now).len(), 3);
        assert_eq!(new_messages(&now.iter().map(|v| v.to_string()).collect::<Vec<_>>(), &now).len(), 0);
    }

    #[test]
    fn offsets_are_bytes_of_whole_lines() {
        let text = "{\"level\":\"info\",\"text\":\"a\"}\n{\"level\":\"error\",\"text\":\"b\"}\n{\"level\":\"warning\",\"te";
        let (all, next, t) = read_from(text, 0, 100_000, false);
        assert_eq!((all.len(), t), (2, false));
        assert_eq!(&text[next..], "{\"level\":\"warning\",\"te");
        let (errs, _, _) = read_from(text, 0, 100_000, true);
        assert_eq!(errs.len(), 1);
        let (none, again, _) = read_from(text, next, 100_000, false);
        assert_eq!((none.len(), again), (0, next));
        let (one, _, cut) = read_from(text, 0, 30, false);
        assert_eq!((one.len(), cut), (1, true));
    }
}