Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(windows): document owner-account service guidance and surface wiki git owner failures (#872)
AkitaOnRails93814c389ce9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3774e308..259b9ac5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- A Windows service running as `LocalSystem` over a user-owned data+ directory no longer breaks the wiki git history silently. libgit2's+ dubious-ownership guard (CVE-2022-24765) fails every wiki commit with+ `code=Owner` when the process account does not own the repository, but+ the failure was WARN-only, so capture and search kept working while no+ wiki checkpoint was ever committed. The startup baseline checkpoint now+ surfaces an owner-check failure at ERROR with the remedy (run the+ service as the owning user), and `docs/windows.md` Scenario E documents+ running the service under a `<serviceaccount>`, corrects the claim that+ only the data directory is account-sensitive, and notes the WinSW+ error-1069 / stale-password gotcha for Microsoft-account / PIN / Hello+ users. The owner check itself is deliberately left enabled. (#872)- A Windows folder no longer splits into two projects. The hook routerderived a project's *name* from the cwd after`normalize_project_path_key` had ASCII-lowercased the wholediff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex d2c1811b..d89c8d0e 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -27,7 +27,7 @@ use ai_memory_store::{ReaderPool, Store, TokenPepper, WriterHandle, hash_session_secret, hash_token,};use ai_memory_web::{WebMountSpec, normalize_prefix, split_web_routers, web_base_href};-use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};+use ai_memory_wiki::{WatcherHandle, Wiki, WikiError, WikiResult, migrations, run_wiki_migrations};use anyhow::{Context, Result};use axum::body::Body;use axum::extract::{DefaultBodyLimit, State};@@ -1042,12 +1042,30 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {Ok(n) => tracing::info!(count = n, "wrote _meta.md scope manifests"),Err(e) => tracing::warn!(error = %e, "scope-manifest backfill failed (non-fatal)"),}- match wiki.ensure_upgrade_baseline_checkpoint() {- Ok(Some(oid)) => {- tracing::info!(checkpoint = %oid, "created wiki upgrade baseline checkpoint")+ let baseline_checkpoint = wiki.ensure_upgrade_baseline_checkpoint();+ match classify_baseline_checkpoint(&baseline_checkpoint) {+ BaselineCheckpointLog::Created => {+ if let Ok(Some(oid)) = &baseline_checkpoint {+ tracing::info!(checkpoint = %oid, "created wiki upgrade baseline checkpoint");+ }+ }+ BaselineCheckpointLog::Clean => {}+ // An owner-check failure is silent-but-fatal to the wiki git history:+ // capture keeps working, but no checkpoint is ever committed, so it+ // must not hide in a WARN. This is the Windows LocalSystem-service /+ // user-owned-data-dir case (docs/windows.md Scenario E).+ BaselineCheckpointLog::OwnerFailure => tracing::error!(+ error = %baseline_checkpoint.as_ref().err().map(ToString::to_string).unwrap_or_default(),+ "wiki git commits are failing libgit2's owner check: the wiki repository is not \+ owned by the account running ai-memory. Run the service AS THE OWNING USER (see \+ docs/windows.md Scenario E) — capture continues, but no wiki checkpoints will be \+ committed until this is fixed."+ ),+ BaselineCheckpointLog::OtherFailure => {+ if let Err(e) = &baseline_checkpoint {+ tracing::warn!(error = %e, "wiki upgrade baseline checkpoint failed (non-fatal)");+ }}- Ok(None) => {}- Err(e) => tracing::warn!(error = %e, "wiki upgrade baseline checkpoint failed (non-fatal)"),}// Keep the guard alive for the lifetime of `serve`.@@ -2675,6 +2693,31 @@ async fn seed_active_project_fallback(reader: &ReaderPool, active_project: &Acti}}+/// How a wiki baseline-checkpoint attempt should be surfaced at startup.+/// Extracted from the logging call so the owner-vs-other classification is+/// unit-testable without standing up a server: a real LocalSystem-service+/// owner failure needs a native Windows box, which is out of scope here.+#[derive(Debug, PartialEq, Eq)]+enum BaselineCheckpointLog {+ /// A checkpoint commit was created (INFO).+ Created,+ /// Nothing to commit (silent).+ Clean,+ /// libgit2 refused on its ownership guard — actionable, logged at ERROR.+ OwnerFailure,+ /// Any other failure — non-fatal, logged at WARN as before.+ OtherFailure,+}++fn classify_baseline_checkpoint<T>(result: &WikiResult<Option<T>>) -> BaselineCheckpointLog {+ match result {+ Ok(Some(_)) => BaselineCheckpointLog::Created,+ Ok(None) => BaselineCheckpointLog::Clean,+ Err(WikiError::GitOwner(_)) => BaselineCheckpointLog::OwnerFailure,+ Err(_) => BaselineCheckpointLog::OtherFailure,+ }+}+fn host_without_port(host: &str) -> &str {if let Some(rest) = host.strip_prefix('[')&& let Some((inside, _)) = rest.split_once(']')@@ -2705,6 +2748,41 @@ mod tests {use tempfile::TempDir;use tower::ServiceExt;+ /// An owner-check failure of the startup wiki baseline checkpoint must be+ /// classified as an ERROR-worthy `OwnerFailure`, not the WARN-only+ /// `OtherFailure` that hid it before (#872). A generic error stays+ /// `OtherFailure`, and the success/clean cases are unchanged — this is the+ /// seam that decides the log level, so it bites here.+ ///+ /// A full native-Windows LocalSystem-service repro (the environment that+ /// actually raises `code=Owner`) is out of scope; this covers the mapping+ /// from `WikiError::GitOwner` to the ERROR branch.+ #[test]+ fn owner_failure_baseline_checkpoint_is_error_not_warn() {+ let owner: WikiResult<Option<()>> = Err(WikiError::GitOwner("not owned".into()));+ assert_eq!(+ classify_baseline_checkpoint(&owner),+ BaselineCheckpointLog::OwnerFailure,+ "owner-check failure must be surfaced at ERROR, not buried in a WARN"+ );++ let other: WikiResult<Option<()>> = Err(WikiError::Io(std::io::Error::other("disk gone")));+ assert_eq!(+ classify_baseline_checkpoint(&other),+ BaselineCheckpointLog::OtherFailure,+ "a non-owner failure stays a non-fatal WARN"+ );++ assert_eq!(+ classify_baseline_checkpoint(&Ok::<_, WikiError>(Some(()))),+ BaselineCheckpointLog::Created+ );+ assert_eq!(+ classify_baseline_checkpoint(&Ok::<Option<()>, WikiError>(None)),+ BaselineCheckpointLog::Clean+ );+ }+async fn wait_for_maintenance_success(store: &Store,job: ai_memory_store::MaintenanceJob,diff --git a/crates/ai-memory-wiki/src/error.rs b/crates/ai-memory-wiki/src/error.rsindex 59ac702e..4b4d6231 100644--- a/crates/ai-memory-wiki/src/error.rs+++ b/crates/ai-memory-wiki/src/error.rs@@ -60,6 +60,21 @@ pub enum WikiError {/// `409 Conflict` at the admin layer.#[error("destination page file already exists: {0}")]DestinationPageExists(String),++ /// libgit2 refused a wiki-repository operation because the repository is+ /// not owned by the account this process runs as (`code=Owner`, the+ /// CVE-2022-24765 dubious-ownership guard). Kept distinct from a generic+ /// I/O error so startup can surface it at ERROR with a fix: on a Windows+ /// LocalSystem service over a user-owned data dir every wiki commit fails+ /// this check, and it was previously logged WARN-only so nothing surfaced.+ /// The owner check is deliberately left enabled (disabling it is+ /// `unsafe` and reopens the CVE); the remedy is to run the service as the+ /// owning user.+ #[error(+ "wiki git repository is not owned by the current account \+ (libgit2 owner check, code=Owner): {0}"+ )]+ GitOwner(String),}impl From<serde_yaml::Error> for WikiError {diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rsindex 98329c54..fb1fbcaa 100644--- a/crates/ai-memory-wiki/src/git.rs+++ b/crates/ai-memory-wiki/src/git.rs@@ -708,6 +708,14 @@ fn should_try_commit_cli_fallback(error: &git2::Error) -> bool {return true;}+ // An owner-check failure must NOT fall back to the git CLI: the CLI runs+ // the same CVE-2022-24765 ownership guard and would refuse identically, so+ // a fallback would only mask the real cause. Let it map through to+ // `WikiError::GitOwner` and surface at ERROR instead.+ if matches!(error.code(), ErrorCode::Owner) {+ return false;+ }+#[cfg(windows)]{// On native Windows, libgit2 can fail to reopen a freshly initialised@@ -873,6 +881,14 @@ fn git_output<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<std::p}fn map_git_err(e: git2::Error) -> WikiError {+ // An owner-check failure (`code=Owner`, CVE-2022-24765 dubious-ownership+ // guard) is kept as a distinct variant so startup can log it at ERROR with+ // an actionable fix instead of burying it in a generic WARN. Everything+ // else stays an opaque I/O error, matching prior behaviour.+ if matches!(e.code(), ErrorCode::Owner) {+ warn!(error = %e, "libgit2 wiki owner-validation error");+ return WikiError::GitOwner(e.to_string());+ }warn!(error = %e, "libgit2 error");WikiError::Io(std::io::Error::other(e.to_string()))}@@ -1270,6 +1286,43 @@ mod tests {assert!(!is_racy_read(&other_message));}+ /// A libgit2 owner-check failure is not silently "recovered": it must not+ /// trigger the git CLI fallback (the CLI enforces the same CVE-2022-24765+ /// guard and would refuse identically), and it must map to the distinct+ /// `GitOwner` variant so startup can surface it at ERROR. A generic error+ /// still maps to the opaque I/O variant — proving the classification bites.+ #[test]+ fn owner_error_is_surfaced_not_recovered() {+ let owner = git2::Error::new(+ ErrorCode::Owner,+ git2::ErrorClass::Config,+ "repository path is not owned by current user",+ );+ assert!(+ !should_try_commit_cli_fallback(&owner),+ "an owner error must not fall back to the git CLI (same guard)"+ );+ assert!(+ matches!(map_git_err(owner), WikiError::GitOwner(_)),+ "an owner error must map to the distinct GitOwner variant"+ );++ // Control: a NotFound error still asks for the CLI fallback, and a+ // generic error is still the opaque I/O variant (not GitOwner).+ let not_found = git2::Error::new(+ ErrorCode::NotFound,+ git2::ErrorClass::Repository,+ "not found",+ );+ assert!(should_try_commit_cli_fallback(¬_found));+ let generic = git2::Error::new(+ ErrorCode::GenericError,+ git2::ErrorClass::Os,+ "some other failure",+ );+ assert!(matches!(map_git_err(generic), WikiError::Io(_)));+ }+/// A racy read keeps the commit path-scoped; any other failure walks.#[test]fn a_racy_read_failure_does_not_escalate_to_a_walk() {diff --git a/docs/windows.md b/docs/windows.mdindex 8f2e144c..4c853085 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -414,9 +414,51 @@ ai-memory status`stop`, `restart`, and `uninstall` are the remaining commands. Becausethe bind is loopback, the service account does not affect reachability:-agents running as your user still reach `127.0.0.1:49374`. Only the data-directory is account-sensitive, which is what the absolute path above-settles.+agents running as your user still reach `127.0.0.1:49374`.++### ⚠️ Run the service as the owning user when the data dir is in a profile++The absolute `--data-dir` above stops the *empty-directory* trap, but it+does **not** make a `LocalSystem` service safe over a data directory that+lives under your user profile (`C:\Users\you\AppData\Local\ai-memory`).+The data directory is account-sensitive, and so is the **wiki's git+repository inside it**. libgit2 enforces the same dubious-ownership guard+as Git itself (CVE-2022-24765): when the process account is not the owner+of the repository, every commit fails with `code=Owner (-36)`. The server+still starts, capture still works, and search still answers — but the+wiki git history silently stops advancing, because a wiki commit failure+is not fatal. As of ai-memory 2.4.x the server logs this at **ERROR** on+startup with the same remedy below; on older builds it was a WARN that was+easy to miss.++**Whenever the data directory lives under a user profile, run the service+as that user** rather than as `LocalSystem`. In the WinSW XML add a+`<serviceaccount>` block:++```xml+ <serviceaccount>+ <username>.\you</username>+ <password>your-account-password</password>+ </serviceaccount>+```++(or set it from the service's **Log On** tab in `services.msc` after+install, then `restart`). Use `.\you` for a local account or+`DOMAIN\you` for a domain account. `LocalSystem` is only appropriate when+the data directory is in a location that account owns outright (e.g. a+dedicated `C:\ProgramData\ai-memory` created and owned by the service+account).++> **WinSW error 1069 / stale password.** If `start` fails with *"The+> service did not start due to a logon failure"* (error 1069), the+> `<serviceaccount>` credentials are wrong or stale. This bites+> **Microsoft-account, PIN, and Windows Hello** users especially: the+> WinSW `<password>` must be your *account password*, which for a+> Microsoft account is your online Microsoft password (not your PIN or+> Hello gesture), and it must be updated in the service config whenever+> that password changes — Windows does not roll it forward. Consider a+> local account, or a dedicated service account with a non-expiring+> password, for an unattended service.Keep running `install-mcp` and `install-hooks` **as your own user**, notas the service — they write per-user agent config, and the rule at the