Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(install-hooks): preserve project strategy across agents

AkitaOnRails6d2c22927ab7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ecd1b5c..c7cbbd1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
including subdirectories and linked worktrees. (#259)
### Fixed
+- Bare `install-hooks --apply` re-runs, including the Docker wrapper's
+ post-upgrade refresh, now preserve an install's baked `repo-root` project
+ strategy for every supported hook integration. An explicit
+ `--project-strategy basename` still removes the install-wide default. (#267)
- Installer `--apply` modes now write through symlinked agent configuration
files instead of atomically replacing the symlink itself. Symlink chains and
dangling final targets are preserved, while backups remain next to the
diff --git a/README.md b/README.md
index c5f58d8a..e4224d89 100644
--- a/README.md
+++ b/README.md
@@ -392,7 +392,9 @@ does not leave an older default-path ai-memory installation behind.
If your agent often starts inside repository subdirectories or linked
worktrees, add `--project-strategy repo-root` to `install-hooks` so captures
collapse to the main git repo name; see [`docs/install.md`](docs/install.md)
-and [`docs/marker-file.md`](docs/marker-file.md) for details.
+and [`docs/marker-file.md`](docs/marker-file.md) for details. Later bare
+`--apply` refreshes, including `ai-memory upgrade`, preserve that choice;
+pass `--project-strategy basename` explicitly to remove it.
The Docker wrapper also bridges thin-client commands such as
`ai-memory status` and `ai-memory bootstrap` back to the host's
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 499c218b..5e960b08 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -394,48 +394,151 @@ fn install_project_strategy(args: &InstallHooksArgs) -> Option<ProjectStrategyAr
}
existing_agent_config(args)
.as_deref()
- .and_then(baked_project_strategy)
+ .and_then(|existing| baked_project_strategy(args.agent, existing))
}
-/// Read the config file `--apply` would write for `args`'s agent, when its path
-/// is resolvable up front. Returns the current contents, or `None` when the path
-/// isn't known here — in which case the agent keeps its prior behavior. Claude
-/// Code (the common case) and any agent pointed at `--config-file` are covered;
-/// other agents can be wired in as their paths get threaded through.
+/// Read the config file `--apply` will update for the selected agent.
fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
- let path = match &args.config_file {
- Some(p) => p.clone(),
- None if args.agent == AgentChoice::ClaudeCode => claude_settings_path().ok()?,
- None => return None,
+ let path = if let Some(path) = &args.config_file {
+ if args.agent == AgentChoice::Openclaw {
+ path.join(openclaw_plugin::ENTRYPOINT_TS)
+ } else {
+ path.clone()
+ }
+ } else {
+ match args.agent {
+ AgentChoice::ClaudeCode => claude_settings_path().ok()?,
+ AgentChoice::Codex => codex_hooks_path().ok()?,
+ AgentChoice::Cursor => cursor_hooks_path().ok()?,
+ AgentChoice::GeminiCli => gemini_settings_path().ok()?,
+ AgentChoice::OpenCode => opencode_plugin_path().ok()?,
+ AgentChoice::Pi => pi_extension_path().ok()?,
+ AgentChoice::Omp => omp_extension_path().ok()?,
+ AgentChoice::Openclaw => openclaw_plugin::default_plugin_dir()
+ .ok()?
+ .join(openclaw_plugin::ENTRYPOINT_TS),
+ AgentChoice::AntigravityCli => antigravity_hooks_path().ok()?,
+ AgentChoice::Grok => grok_hooks_path().ok()?,
+ AgentChoice::Zero => zero_hooks_path().ok()?,
+ AgentChoice::Devin => devin_hooks_path().ok()?,
+ AgentChoice::KimiCode => kimi_code_config_path().ok()?,
+ }
};
std::fs::read_to_string(path).ok()
}
-/// Recover the `ProjectStrategyArg` an earlier `--apply` baked into `existing`,
-/// so a re-apply without `--project-strategy` can keep it. Only `repo-root` is
-/// ever baked (`basename` bakes nothing), so it's the sole value we look for;
-/// the scan matches the shell env prefix, the PowerShell form, and the native
-/// flag spellings.
-fn baked_project_strategy(existing: &str) -> Option<ProjectStrategyArg> {
+/// Recover a strategy only from configuration entries ai-memory owns. Shared
+/// JSON/TOML config files may contain unrelated hooks, while generated
+/// TypeScript files carry an explicit ownership header.
+fn baked_project_strategy(agent: AgentChoice, existing: &str) -> Option<ProjectStrategyArg> {
+ match agent {
+ AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw => {
+ let marker = match agent {
+ AgentChoice::OpenCode => "--agent opencode --apply`.",
+ AgentChoice::Pi => "--agent pi --apply`.",
+ AgentChoice::Omp => "--agent omp --apply`.",
+ AgentChoice::Openclaw => "--agent openclaw --apply`.",
+ _ => return None,
+ };
+ existing
+ .lines()
+ .next()
+ .filter(|line| {
+ line.starts_with("// Auto-generated by `ai-memory install-hooks ")
+ && line.ends_with(marker)
+ })
+ .and_then(|_| project_strategy_from_text(existing))
+ }
+ AgentChoice::KimiCode => {
+ let document: toml_edit::DocumentMut = existing.parse().ok()?;
+ document
+ .get("hooks")
+ .and_then(toml_edit::Item::as_array_of_tables)
+ .and_then(|hooks| {
+ hooks.iter().find_map(|entry| {
+ if !is_ai_memory_toml_hook_entry(entry) {
+ return None;
+ }
+ entry
+ .get("command")
+ .and_then(|item| item.as_str())
+ .and_then(project_strategy_from_text)
+ })
+ })
+ }
+ _ => serde_json::from_str(existing)
+ .ok()
+ .as_ref()
+ .and_then(project_strategy_from_json),
+ }
+}
+
+fn project_strategy_from_json(value: &serde_json::Value) -> Option<ProjectStrategyArg> {
+ if is_ai_memory_hook_entry(value) {
+ if let Some(strategy) = value
+ .get("command")
+ .and_then(|command| command.as_str())
+ .and_then(project_strategy_from_text)
+ {
+ return Some(strategy);
+ }
+ if let Some(args) = value.get("args").and_then(|args| args.as_array()) {
+ let args: Vec<&str> = args.iter().filter_map(|arg| arg.as_str()).collect();
+ for (index, arg) in args.iter().enumerate() {
+ if let Some(value) = arg.strip_prefix("--project-strategy=")
+ && is_repo_root_strategy(value)
+ {
+ return Some(ProjectStrategyArg::RepoRoot);
+ }
+ if *arg == "--project-strategy"
+ && args
+ .get(index + 1)
+ .is_some_and(|value| is_repo_root_strategy(value))
+ {
+ return Some(ProjectStrategyArg::RepoRoot);
+ }
+ }
+ }
+ }
+
+ match value {
+ serde_json::Value::Array(values) => values.iter().find_map(project_strategy_from_json),
+ serde_json::Value::Object(values) => values.values().find_map(project_strategy_from_json),
+ _ => None,
+ }
+}
+
+/// Only `repo-root` is baked (`basename` removes the marker), so it is the sole
+/// value recovered from legacy shell commands and generated source.
+fn project_strategy_from_text(existing: &str) -> Option<ProjectStrategyArg> {
for marker in [
"AI_MEMORY_PROJECT_STRATEGY=",
"--project-strategy=",
"--project-strategy ",
+ "const DEFAULT_PROJECT_STRATEGY =",
] {
- let Some(rest) = existing.split(marker).nth(1) else {
- continue;
- };
- let token: String = rest
- .chars()
- .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
- .collect();
- if token == "repo-root" || token == "repo_root" {
- return Some(ProjectStrategyArg::RepoRoot);
+ for rest in existing.split(marker).skip(1) {
+ let token: String = rest
+ .trim_start_matches(|character: char| {
+ character.is_ascii_whitespace() || matches!(character, '\'' | '"')
+ })
+ .chars()
+ .take_while(|character| {
+ character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
+ })
+ .collect();
+ if is_repo_root_strategy(&token) {
+ return Some(ProjectStrategyArg::RepoRoot);
+ }
}
}
None
}
+fn is_repo_root_strategy(value: &str) -> bool {
+ matches!(value, "repo-root" | "repo_root")
+}
+
/// Reject `--as-user X` without a usable `--auth-token`. P1.8
/// metadata flag — without a token, the hook scripts would still
/// authenticate anonymously (or as root if the operator reused the
@@ -3607,35 +3710,127 @@ mod tests {
// ── #issue project-strategy preservation on re-apply ─────────────
#[test]
- fn baked_project_strategy_reads_every_form() {
+ fn project_strategy_from_text_reads_every_form() {
// Shell env prefix (Claude Code / POSIX script hooks).
assert_eq!(
- baked_project_strategy(
+ project_strategy_from_text(
"AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/s.sh"
),
Some(ProjectStrategyArg::RepoRoot)
);
// PowerShell form.
assert_eq!(
- baked_project_strategy("$env:AI_MEMORY_PROJECT_STRATEGY=repo-root; & /x/s.ps1"),
+ project_strategy_from_text("$env:AI_MEMORY_PROJECT_STRATEGY='repo-root'; & /x/s.ps1"),
Some(ProjectStrategyArg::RepoRoot)
);
// Native flag, both spellings.
assert_eq!(
- baked_project_strategy("ai-memory hook --project-strategy repo-root run"),
+ project_strategy_from_text("ai-memory hook --project-strategy repo-root run"),
+ Some(ProjectStrategyArg::RepoRoot)
+ );
+ assert_eq!(
+ project_strategy_from_text("ai-memory hook --project-strategy=repo_root"),
Some(ProjectStrategyArg::RepoRoot)
);
assert_eq!(
- baked_project_strategy("ai-memory hook --project-strategy=repo_root"),
+ project_strategy_from_text("const DEFAULT_PROJECT_STRATEGY = \"repo-root\";"),
Some(ProjectStrategyArg::RepoRoot)
);
}
#[test]
- fn baked_project_strategy_none_for_basename_or_absent() {
- // basename bakes nothing, so there is no marker to find.
- assert_eq!(baked_project_strategy(r#"{"hooks":{}}"#), None);
- assert_eq!(baked_project_strategy(""), None);
+ fn baked_project_strategy_reads_owned_json_for_every_json_agent() {
+ let existing = serde_json::json!({
+ "hooks": {
+ "SessionStart": [
+ { "hooks": [{
+ "command": "third-party",
+ "args": ["--project-strategy", "repo-root"]
+ }]},
+ { "hooks": [{
+ "command": "/bin/ai-memory",
+ "args": [
+ "hook", "--event", "session-start", "--agent", "claude-code",
+ "--server-url", "http://h", "--project-strategy", "repo-root"
+ ]
+ }]}
+ ]
+ }
+ })
+ .to_string();
+ for agent in [
+ AgentChoice::ClaudeCode,
+ AgentChoice::Codex,
+ AgentChoice::Cursor,
+ AgentChoice::GeminiCli,
+ AgentChoice::AntigravityCli,
+ AgentChoice::Grok,
+ AgentChoice::Zero,
+ AgentChoice::Devin,
+ ] {
+ assert_eq!(
+ baked_project_strategy(agent, &existing),
+ Some(ProjectStrategyArg::RepoRoot),
+ "{agent:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn baked_project_strategy_ignores_unowned_json_entry() {
+ let existing = serde_json::json!({
+ "hooks": {
+ "SessionStart": [{ "hooks": [{
+ "command": "third-party",
+ "args": ["--project-strategy", "repo-root"]
+ }]}]
+ }
+ })
+ .to_string();
+ assert_eq!(
+ baked_project_strategy(AgentChoice::ClaudeCode, &existing),
+ None
+ );
+ }
+
+ #[test]
+ fn baked_project_strategy_reads_owned_kimi_toml_only() {
+ let existing = r#"
+[[hooks]]
+event = "UserPromptSubmit"
+command = "third-party --project-strategy repo-root"
+
+[[hooks]]
+event = "UserPromptSubmit"
+command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/ai-memory/session-start.sh"
+"#;
+ assert_eq!(
+ baked_project_strategy(AgentChoice::KimiCode, existing),
+ Some(ProjectStrategyArg::RepoRoot)
+ );
+ }
+
+ #[test]
+ fn baked_project_strategy_reads_every_owned_generated_integration() {
+ for (agent, name) in [
+ (AgentChoice::OpenCode, "opencode"),
+ (AgentChoice::Pi, "pi"),
+ (AgentChoice::Omp, "omp"),
+ (AgentChoice::Openclaw, "openclaw"),
+ ] {
+ let existing = format!(
+ "// Auto-generated by `ai-memory install-hooks --agent {name} --apply`.\n\
+ const DEFAULT_PROJECT_STRATEGY = \"repo-root\";\n"
+ );
+ assert_eq!(
+ baked_project_strategy(agent, &existing),
+ Some(ProjectStrategyArg::RepoRoot),
+ "{agent:?}"
+ );
+ }
+
+ let unowned = "// user extension\nconst DEFAULT_PROJECT_STRATEGY = \"repo-root\";\n";
+ assert_eq!(baked_project_strategy(AgentChoice::OpenCode, unowned), None);
}
#[test]
@@ -3644,7 +3839,12 @@ mod tests {
let cfg = tmp.path().join("settings.json");
std::fs::write(
&cfg,
- "AI_MEMORY_PROJECT_STRATEGY=repo-root /x/session-start.sh",
+ serde_json::json!({
+ "hooks": { "SessionStart": [{ "hooks": [{
+ "command": "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/ai-memory/session-start.sh"
+ }]}] }
+ })
+ .to_string(),
)
.unwrap();
let args = InstallHooksArgs {
@@ -3664,7 +3864,16 @@ mod tests {
fn install_project_strategy_explicit_basename_overrides_existing() {
let tmp = TempDir::new().unwrap();
let cfg = tmp.path().join("settings.json");
- std::fs::write(&cfg, "AI_MEMORY_PROJECT_STRATEGY=repo-root /x/s.sh").unwrap();
+ std::fs::write(
+ &cfg,
+ serde_json::json!({
+ "hooks": { "SessionStart": [{ "hooks": [{
+ "command": "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/ai-memory/session-start.sh"
+ }]}] }
+ })
+ .to_string(),
+ )
+ .unwrap();
let args = InstallHooksArgs {
agent: AgentChoice::ClaudeCode,
config_file: Some(cfg),
@@ -3690,6 +3899,28 @@ mod tests {
assert_eq!(install_project_strategy(&args), None);
}
+ #[test]
+ fn install_project_strategy_reads_openclaw_entrypoint_below_config_dir() {
+ let tmp = TempDir::new().unwrap();
+ let entrypoint = tmp.path().join(openclaw_plugin::ENTRYPOINT_TS);
+ std::fs::write(
+ entrypoint,
+ "// Auto-generated by `ai-memory install-hooks --agent openclaw --apply`.\n\
+ const DEFAULT_PROJECT_STRATEGY = \"repo-root\";\n",
+ )
+ .unwrap();
+ let args = InstallHooksArgs {
+ agent: AgentChoice::Openclaw,
+ config_file: Some(tmp.path().to_path_buf()),
+ project_strategy: None,
+ ..default_hook_args()
+ };
+ assert_eq!(
+ install_project_strategy(&args),
+ Some(ProjectStrategyArg::RepoRoot)
+ );
+ }
+
// ── P1.8 validate_as_user ────────────────────────────────────────
/// No `--as-user` at all → always OK.
diff --git a/docs/install.md b/docs/install.md
index 7d34a530..6f44ac1d 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -162,10 +162,13 @@ strategy into the hooks:
ai-memory install-hooks --apply --agent claude-code --project-strategy repo-root
```
-`--project-strategy` accepts `basename` (the default; bakes nothing, so existing
-installs are unchanged) or `repo-root`. It works for every agent and delivery
-path. A per-repo `.ai-memory.toml` marker's own `project_strategy` / `project`
-still take precedence — see
+`--project-strategy` accepts `basename` (the new-install default; bakes nothing)
+or `repo-root`. Omitting it during a later `--apply` preserves the strategy
+already baked into that agent's ai-memory hooks, including during the wrapper's
+automatic post-upgrade refresh. Pass `basename` explicitly to remove an
+existing `repo-root` default. This works for every agent and delivery path. A
+per-repo `.ai-memory.toml` marker's own `project_strategy` / `project` still
+take precedence — see
[the marker-file reference](marker-file.md#install-wide-default-no-marker).
---
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 13384548..c037fac4 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -322,7 +322,9 @@ This is **install-time config**, written into the agent's hook command (and
the generated OpenCode / OMP / Pi / OpenClaw plugins) — the same status as the
`AI_MEMORY_AUTH_TOKEN` / `AI_MEMORY_HOOK_URL` it sits beside, *not* a user-set
runtime override (which was deliberately rejected in #16). The flag accepts
-`basename` (the default — bakes nothing, behavior unchanged) or `repo-root`.
+`basename` (the new-install default — bakes nothing) or `repo-root`. A later
+`install-hooks --apply` without the flag preserves the value already baked into
+ai-memory's hooks; pass `--project-strategy basename` explicitly to remove it.
Precedence is unchanged: a marker's explicit `project_strategy` or `project`
still wins over the install default.