Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): warn when a Windows logon binary is missing
AkitaOnRails8fd66b4d1e21
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7beed4b1..8292e7b9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -73,7 +73,12 @@ version in [`docs/changelog/`](docs/changelog/):`ai-memory uninstall --apply` stops the host and removes the value when itstill has the shape `setup` writes and names this install's data dir, so anuninstall against another data dir (a second install, a test's temporary- one) leaves the entry alone. (#1271, #1280)+ one) leaves the entry alone. `ai-memory doctor` and `ai-memory status`+ warn (`logon_binary_missing`, also in their `--json` output and when+ `status` cannot reach the server) when that entry names an+ `ai-memory.exe` that no longer exists, which is what an antivirus+ quarantine leaves behind, and say how to restore the binary or remove the+ entry. (#1271, #1280, #1300, #1311)- Added `ai-memory setup --web`, which shows the setup plan as a page inyour browser and applies the agents you tick there by running `ai-memorysetup --yes --agent ...` and streaming its output to the page. The page isdiff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 4fadd4d2..06789410 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -195,6 +195,11 @@ struct DoctorReport {/// Meta Muse Code's settings file, when there is one: whether ai-memory's/// hooks and MCP entry are in it, and the two shapes that break Muse.muse: Option<MuseReport>,+ /// Set when the Windows logon entry `setup` wrote for this data dir names+ /// an `ai-memory.exe` that is no longer on disk (#1280). Omitted+ /// otherwise, so the JSON shape is unchanged when there is nothing to say.+ #[serde(skip_serializing_if = "Option::is_none")]+ windows_logon: Option<super::user_service::MissingLogonBinary>,}/// One installed ai-memory marketplace plugin and what else wires the same@@ -652,6 +657,9 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {.ok().and_then(|path| muse_report(&path));+ // Local, like the spool: a quarantined binary leaves no server to ask.+ let windows_logon = super::user_service::check_logon_binary(&config.data_dir);+let auth_posture = identity.as_ref().map(|identity| {crate::local_auth::AuthPosture::classify(identity.level == "anonymous", &ep.url)});@@ -675,6 +683,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {agentmemory_residue,plugins,muse,+ windows_logon,};if args.json {@@ -1119,6 +1128,10 @@ fn render_human(report: &DoctorReport) {println!(" recent window: last {} days\n", report.since_days);}+ if let Some(problem) = &report.windows_logon {+ println!("{}", problem.render_human());+ }+if let Some(problem) = &report.marker_capture_problem {println!("⚠ {}: the settings marker has an invalid `[capture]` section.\n \@@ -1241,9 +1254,37 @@ mod tests {agentmemory_residue: Vec::new(),plugins: Vec::new(),muse: None,+ windows_logon: None,}}+ /// The logon-binary warning is a key of its own in doctor's JSON, and+ /// absent when there is nothing to report.+ #[test]+ fn doctor_json_carries_a_missing_logon_binary_only_when_there_is_one() {+ let quiet = health_report(+ super::super::hook_spool::SpoolHealth::default(),+ false,+ None,+ );+ let json = serde_json::to_value(&quiet).unwrap();+ assert!(json.get("windows_logon").is_none(), "{json}");++ let mut report = quiet;+ report.windows_logon = Some(super::super::user_service::MissingLogonBinary {+ classification: super::super::user_service::LOGON_BINARY_MISSING,+ executable: r"C:\bin\ai-memory.exe".into(),+ detail: "gone".into(),+ fix: "restore it",+ });+ let json = serde_json::to_value(&report).unwrap();+ assert_eq!(+ json["windows_logon"]["classification"],+ "logon_binary_missing"+ );+ assert_eq!(json["windows_logon"]["executable"], r"C:\bin\ai-memory.exe");+ }+/// Doctor reads Muse's settings file: the wiring it finds, and the two/// shapes that break Muse (both server maps, no `schema_version`).#[test]diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rsindex 0b87ea75..5c9d4dfa 100644--- a/crates/ai-memory-cli/src/commands/status.rs+++ b/crates/ai-memory-cli/src/commands/status.rs@@ -210,6 +210,24 @@ fn report_offline_recovery_hint(config: &Config, spool: &SpoolHealth, json: bool);}+/// The missing logon binary while the server is down, on stderr like the+/// spool block, so `--json` consumers' stdout stays a single object.+fn report_offline_logon_binary(+ problem: Option<&super::user_service::MissingLogonBinary>,+ json: bool,+) {+ let Some(problem) = problem else {+ return;+ };+ if json {+ if let Ok(rendered) = serde_json::to_string(problem) {+ eprintln!("windows logon (server unreachable): {rendered}");+ }+ return;+ }+ eprint!("{}", problem.render_human());+}+/// Which capture mode the hook would enforce for this install (#446).////// Reads the same file the hook reads rather than keeping a second source of@@ -238,12 +256,16 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {// the one question this section exists for could not be asked in the one// situation that prompts it.let spool = spool_health(&spool_dir(&config.data_dir));+ // Also local, and for the same reason: a quarantined binary (#1280)+ // usually means nothing is listening.+ let windows_logon = super::user_service::check_logon_binary(&config.data_dir);let report: Report = match get_json::<Report>(&ep, "/admin/status", &[]).await {Ok(report) => report,Err(err) => {report_offline_spool(&spool, args.json);report_offline_recovery_hint(config, &spool, args.json);+ report_offline_logon_binary(windows_logon.as_ref(), args.json);return Err(err);}};@@ -266,6 +288,7 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {capture_mode,&ep,auth_posture,+ windows_logon.as_ref(),))?);} else {@@ -275,6 +298,9 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {println!(" db: {}", report.db_path);println!(" bind: {}", report.bind);println!(" auth: {}", auth_posture.line());+ if let Some(problem) = &windows_logon {+ print!("{}", problem.render_human());+ }println!(" pages: {} (all versions: {})",report.counts.pages_latest, report.counts.pages_all@@ -496,8 +522,9 @@ fn json_report(capture_mode: &str,endpoint: &ServerEndpoint,auth_posture: crate::local_auth::AuthPosture,+ windows_logon: Option<&super::user_service::MissingLogonBinary>,) -> serde_json::Value {- serde_json::json!({+ let mut value = serde_json::json!({"version": report.version,"data_dir": report.data_dir,"bind": report.bind,@@ -522,7 +549,13 @@ fn json_report("ingest": report.ingest,"client": { "server_url": endpoint.url, "auth": endpoint.auth_token.is_some() },"auth_posture": { "posture": auth_posture, "fix": auth_posture.fix() },- })+ });+ // Absent when there is nothing to say, so the shape consumers read is+ // unchanged.+ if let Some(problem) = windows_logon {+ value["windows_logon"] = serde_json::json!(problem);+ }+ value}fn provider_health_line(role: &ProviderRoleHealthSnapshot) -> String {@@ -581,7 +614,7 @@ mod tests {#[test]fn status_json_keeps_existing_fields_and_adds_recovery_compatibly() {- let report: Report = serde_json::from_value(serde_json::json!({+ let report_json = serde_json::json!({"version": "2.6.0","data_dir": "/data","bind": "127.0.0.1:49374",@@ -604,8 +637,8 @@ mod tests {"ingest": null,"write_queue": null,"wiki_format": null- }))- .unwrap();+ });+ let report: Report = serde_json::from_value(report_json.clone()).unwrap();let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:49374".into()), None);let value = json_report(report,@@ -617,7 +650,9 @@ mod tests {"denylist",&endpoint,crate::local_auth::AuthPosture::NoneLoopback,+ None,);+ assert!(value.get("windows_logon").is_none(), "{value}");assert_eq!(value["auth_posture"]["posture"], "none_loopback");assert_eq!(value["auth_posture"]["fix"], "ai-memory auth enable");for key in [@@ -638,6 +673,38 @@ mod tests {}assert_eq!(value["recovery"]["journal_pending"], 2);assert_eq!(value["counts"]["observations"], 4);++ // A missing logon binary (#1280) adds one key and changes no other.+ let problem = super::super::user_service::MissingLogonBinary {+ classification: super::super::user_service::LOGON_BINARY_MISSING,+ executable: r"C:\bin\ai-memory.exe".into(),+ detail: "gone".into(),+ fix: "restore it",+ };+ let warned = json_report(+ serde_json::from_value(report_json).unwrap(),+ SpoolHealth::default(),+ 2,+ 1,+ 1,+ None,+ "denylist",+ &endpoint,+ crate::local_auth::AuthPosture::NoneLoopback,+ Some(&problem),+ );+ assert_eq!(+ warned["windows_logon"]["classification"],+ "logon_binary_missing"+ );+ assert_eq!(+ warned["windows_logon"]["executable"],+ r"C:\bin\ai-memory.exe"+ );+ assert_eq!(warned["windows_logon"]["fix"], "restore it");+ let mut without = warned.clone();+ without.as_object_mut().unwrap().remove("windows_logon");+ assert_eq!(without, value);}#[test]diff --git a/crates/ai-memory-cli/src/commands/user_service.rs b/crates/ai-memory-cli/src/commands/user_service.rsindex 207abdd9..a4b02d50 100644--- a/crates/ai-memory-cli/src/commands/user_service.rs+++ b/crates/ai-memory-cli/src/commands/user_service.rs@@ -395,10 +395,7 @@ fn render_windows(spec: &ServiceSpec) -> Result<ServiceUnit> {/// `ai-memory.exe` followed by arguments that end in `service-host`. Anything/// else under the name was written by someone else and is left alone.pub(crate) fn is_setup_run_entry(data: &str) -> bool {- let Some(rest) = data.strip_prefix('"') else {- return false;- };- let Some((program, args)) = rest.split_once('"') else {+ let Some((program, args)) = split_run_entry(data) else {return false;};let file = program.rsplit(['\\', '/']).next().unwrap_or(program);@@ -408,13 +405,21 @@ pub(crate) fn is_setup_run_entry(data: &str) -> bool {&& !args.contains('|')}+/// A `Run` value split into the executable inside its leading quotes and the+/// arguments after them; `None` when the value does not start with a quoted+/// program. The executable needs no unescaping: `is_setup_run_entry` only+/// accepts one ending in `ai-memory.exe`, so no backslash precedes its quote.+fn split_run_entry(data: &str) -> Option<(&str, &str)> {+ data.strip_prefix('"')?.split_once('"')+}+/// The `--data-dir` a `setup` logon entry names, unquoted the way/// [`windows_arg`] quoted it; `None` when the entry names none. Only the/// first argument after the quoted executable is read, as `render_windows`/// writes it, so a `--data-dir` inside the executable's own path never/// counts.fn run_entry_data_dir(data: &str) -> Option<String> {- let (_program, args) = data.strip_prefix('"')?.split_once('"')?;+ let (_program, args) = split_run_entry(data)?;let quoted = args.trim_start().strip_prefix("--data-dir")?@@ -486,6 +491,78 @@ pub(crate) fn run_value(runner: &dyn CommandRunner) -> Option<String> {runner.run_key_value()}+/// `doctor`'s and `status`' token for [`MissingLogonBinary`], so a script can+/// match one string.+pub(crate) const LOGON_BINARY_MISSING: &str = "logon_binary_missing";++/// The logon entry `setup` wrote for this data dir names an `ai-memory.exe`+/// that is no longer on disk. Antivirus that quarantines the binary leaves the+/// `Run` value behind (#1280): the server then never starts at logon and every+/// hook calls a path that is gone, with nothing else saying why.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub(crate) struct MissingLogonBinary {+ /// Always [`LOGON_BINARY_MISSING`].+ pub(crate) classification: &'static str,+ /// The executable the logon entry names, as written in the value.+ pub(crate) executable: String,+ /// What happened, in one sentence.+ pub(crate) detail: String,+ /// What to do about it.+ pub(crate) fix: &'static str,+}++const MISSING_LOGON_BINARY_FIX: &str = "restore ai-memory.exe (or allow it in your antivirus) \+ and re-run `ai-memory setup`; or remove the logon entry with `ai-memory uninstall --apply` \+ (which removes all of ai-memory's wiring) or `Remove-ItemProperty -Path \+ HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run -Name ai-memory`";++impl MissingLogonBinary {+ /// The warning `doctor` and `status` print.+ pub(crate) fn render_human(&self) -> String {+ format!(+ "⚠ {}: {}\n Fix: {}. See docs/windows.md (Antivirus / EDR).\n",+ self.classification, self.detail, self.fix+ )+ }+}++/// The logon entry `setup` wrote for `data_dir`, when the `ai-memory.exe` it+/// names is not a file. An entry of another shape, or another data dir's, is+/// not this install's and says nothing.+pub(crate) fn missing_logon_binary(+ runner: &dyn CommandRunner,+ data_dir: &Path,+ is_file: &dyn Fn(&Path) -> bool,+) -> Option<MissingLogonBinary> {+ let data = run_value(runner)?;+ if !is_setup_run_entry_for(&data, data_dir) {+ return None;+ }+ let (executable, _args) = split_run_entry(&data)?;+ if is_file(Path::new(executable)) {+ return None;+ }+ Some(MissingLogonBinary {+ classification: LOGON_BINARY_MISSING,+ executable: executable.to_owned(),+ detail: format!(+ "the Windows logon entry for this data dir runs {executable}, which no longer \+ exists (likely quarantined by antivirus), so the server does not start at logon"+ ),+ fix: MISSING_LOGON_BINARY_FIX,+ })+}++/// [`missing_logon_binary`] against the signed-in user's registry, on+/// Windows only: elsewhere there is no `Run` key, and asking would spawn a+/// `reg` that does not exist.+pub(crate) fn check_logon_binary(data_dir: &Path) -> Option<MissingLogonBinary> {+ if ServiceManager::current() != Some(ServiceManager::WindowsRun) {+ return None;+ }+ missing_logon_binary(&SystemRunner, data_dir, &Path::is_file)+}+/// Pick the data out of `reg query <key> /v <name>`, which prints the key,/// then ` <name> REG_SZ <data>`.fn parse_reg_query(stdout: &str, name: &str) -> Option<String> {@@ -1882,3 +1959,114 @@ mod user_registry_tests {));}}++// Pure string and injected-runner checks, so they run on every platform.+#[cfg(test)]+mod logon_binary_tests {+ use super::*;++ /// A runner whose `Run` value is fixed and which never runs anything.+ struct FixedRunValue(Option<String>);++ impl CommandRunner for FixedRunValue {+ fn run(&self, program: &str, _args: &[&str]) -> Result<CommandOutcome> {+ bail!("{program} must not run in this test")+ }++ fn run_key_value(&self) -> Option<String> {+ self.0.clone()+ }+ }++ const DATA_DIR: &str = r"C:\Users\me\AppData\Local\ai-memory";+ const EXE: &str = r"C:\Users\me\AppData\Local\Programs\ai-memory\ai-memory.exe";++ fn entry(exe: &str, data_dir: &str) -> String {+ format!(r#""{exe}" --data-dir "{data_dir}" --config "{data_dir}\config.toml" service-host"#)+ }++ fn check(value: Option<String>, present: bool) -> Option<MissingLogonBinary> {+ missing_logon_binary(&FixedRunValue(value), Path::new(DATA_DIR), &|_| present)+ }++ #[test]+ fn a_quarantined_binary_in_this_data_dirs_entry_is_reported() {+ let problem = check(Some(entry(EXE, DATA_DIR)), false).expect("binary is gone");+ assert_eq!(problem.classification, LOGON_BINARY_MISSING);+ assert_eq!(problem.executable, EXE);+ assert!(problem.detail.contains(EXE), "{}", problem.detail);+ assert!(problem.detail.contains("quarantined"), "{}", problem.detail);++ let json = serde_json::to_value(&problem).unwrap();+ assert_eq!(json["classification"], LOGON_BINARY_MISSING);+ assert_eq!(json["executable"], EXE);+ assert_eq!(json["fix"], problem.fix);+ }++ #[test]+ fn the_executable_is_the_one_the_is_file_check_sees() {+ let seen = std::cell::RefCell::new(Vec::new());+ let value = entry(r"\\?\C:\Program Files\ai memory\ai-memory.exe", DATA_DIR);+ let problem =+ missing_logon_binary(&FixedRunValue(Some(value)), Path::new(DATA_DIR), &|path| {+ seen.borrow_mut().push(path.to_path_buf());+ false+ })+ .expect("binary is gone");+ assert_eq!(+ seen.into_inner(),+ vec![PathBuf::from(+ r"\\?\C:\Program Files\ai memory\ai-memory.exe"+ )]+ );+ assert_eq!(+ problem.executable,+ r"\\?\C:\Program Files\ai memory\ai-memory.exe"+ );+ }++ #[test]+ fn a_present_binary_or_no_entry_says_nothing() {+ assert_eq!(check(Some(entry(EXE, DATA_DIR)), true), None);+ assert_eq!(check(None, false), None);+ }++ #[test]+ fn only_setups_entry_for_this_data_dir_counts() {+ let cases = [+ entry(EXE, r"D:\another\data-dir"),+ format!(r#""C:\x\other.exe" --data-dir "{DATA_DIR}" service-host"#),+ format!(r#""{EXE}" --data-dir "{DATA_DIR}" serve"#),+ format!(r#""{EXE}" --data-dir "{DATA_DIR}" x & calc service-host"#),+ format!(r#"{EXE} --data-dir "{DATA_DIR}" service-host"#),+ ];+ for value in cases {+ assert_eq!(check(Some(value.clone()), false), None, "{value}");+ }+ }++ /// The hint must point at commands that remove or repair the entry;+ /// `setup --no-service` leaves an existing entry in place.+ #[test]+ fn the_fix_names_commands_that_act_on_the_entry() {+ let human = check(Some(entry(EXE, DATA_DIR)), false)+ .unwrap()+ .render_human();+ for needle in [+ LOGON_BINARY_MISSING,+ "re-run `ai-memory setup`",+ "`ai-memory uninstall --apply`",+ r"Remove-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Run -Name ai-memory",+ "Antivirus / EDR",+ ] {+ assert!(human.contains(needle), "missing {needle:?} in {human}");+ }+ assert!(!human.contains("--no-service"), "{human}");+ }++ #[cfg(not(windows))]+ #[test]+ fn the_live_check_is_quiet_off_windows() {+ assert_eq!(check_logon_binary(Path::new(DATA_DIR)), None);+ }+}diff --git a/docs/windows.md b/docs/windows.mdindex 68c8fed3..164ff9e2 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -394,6 +394,51 @@ user unit without lingering and a macOS LaunchAgent. For a server that runsbefore anyone signs in, or for other users of the machine, use a real Windowsservice through WinSW, below, and pass `--no-service` to `setup`.+### Antivirus / EDR++Behaviour-based endpoint protection watches for programs that make+themselves start at logon, and `ai-memory.exe` is unsigned. Bitdefender's+Advanced Threat Control has quarantined it after `setup` wrote the logon+entry ([#1280](https://github.com/akitaonrails/ai-memory/issues/1280)).+`setup` avoids the signals known to weigh in that decision:++- It writes and reads the `Run` value through the registry API. It never+ runs `reg.exe add` on the `Run` key.+- The value holds plain paths, without the `\\?\` prefix a canonical path+ carries.+- Stopping the host is cooperative (#1300): the host stops the server through+ a request file in the data dir, as described above, and `taskkill` runs+ only as the fallback for a host that does not answer.++That lowers the odds but guarantees nothing; a product can still flag an+unsigned binary on its own rules.++**How to tell.** A quarantine removes `ai-memory.exe` and leaves the `Run`+value behind. The server then never starts at logon, and the hooks keep+calling a path that is gone. `ai-memory doctor` and `ai-memory status` (from+any copy of the binary that still exists) check the entry `setup` wrote for+their data dir and warn with `logon_binary_missing` when the+`ai-memory.exe` it names is no longer there. The warning is also in their+`--json` output, and `status` prints it even when it cannot reach the+server, which is the usual state once the binary is gone. Your antivirus+console or quarantine list shows the detection itself.++**What to do.** Restore the binary from quarantine, or put it back by+reinstalling, and ask whoever runs the antivirus to allow it (on a managed+machine that is an administrator change). Then re-run `ai-memory setup`,+which points the entry at the binary you ran it from and starts the host.+To stop using the logon entry instead, remove it: `ai-memory uninstall+--apply` removes it along with the rest of ai-memory's wiring, or delete+only the value:++```powershell+Remove-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Run -Name ai-memory+```++`setup --no-service` skips writing the entry but does not remove one that+already exists. Without the entry, run `ai-memory serve --transport http`+in a terminal or use the WinSW service below.+### A real Windows serviceA Windows service, unlike the logon entry, runs without anyone signed in. It