Skip to content

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

Rust

fix(run): find, layer onto and attribute Crush sessions as Crush does

Éverton Toffanetto6ca93eb27813
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e28a61e6..d08cddec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Both flags are wrapper-owned like `--yolo`/`--executable` and must precede
the harness name; a `--env` entry overrides a same-key `--env-file` line.
The resolved environment reaches the spawned process, ai-memory's own
- native-session resolution and first-launch auto-wire, so the session store,
+ native-session resolution, first-launch auto-wire and the global Crush
+ config the managed context packet is layered onto, so the session store,
hooks and MCP all follow a `CLAUDE_CONFIG_DIR`-style override, and
auto-wire warns when the override puts Pi and OMP in one extensions
directory. See `docs/managed-workstreams.md`. (#820)
@@ -169,10 +170,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
native session import. Blank now counts as unset everywhere, as it already
did for the `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and `PI_CODING_AGENT_DIR`
installers, and `ai-memory run` drops such a value from the harness it
- launches so the harness uses its default home as well. (#820)
+ launches so the harness uses its default home as well. Crush's managed
+ context likewise read a whitespace-only `CRUSH_GLOBAL_CONFIG` or
+ `XDG_CONFIG_HOME` as a directory, and now falls back to the default global
+ config. (#820)
- Native `ai-memory upgrade` no longer refuses every Linux install by probing
the running executable for write (Linux `ETXTBSY`); it only requires the
parent directory to be writable for rename-based replace. (#802)
+- A managed Crush launch with a context packet dropped the `CRUSH.md` and
+ `AGENTS.md` Crush loads by default: Crush only adds them while
+ `global_context_paths` is empty, and the packet filled it. The launcher now
+ adds them first when the user's config lists none, and no longer refuses to
+ start over a global `crush.json` Crush accepts (an empty file, `null`, or
+ `null` options), read from the path cleaned as Crush cleans it. The global
+ `crushrc` beside that config, which Crush stopped reading once the config
+ dir moved, is now sourced from its own directory as well. (#820)
+- Two fresh managed launches in one checkout could import each other's
+ transcript: after exit, `ai-memory run` took the newest session there even
+ when a hook in the child had already linked the run's own session. The
+ hook-linked session now wins when this checkout's store holds it (a process
+ the child starts inherits the run id). Crush, which has no hooks, claims only the
+ one top-level session created during a fresh run and imports nothing, with
+ a warning, when another launch created one too; its title and sub-agent
+ sessions are no longer taken for the conversation, and in a data directory
+ outside the project only a session that edited a file in the project is
+ claimed. (#820)
+- `ai-memory run crush`, `backfill` and `doctor` looked for Crush sessions only
+ in `<cwd>/.crush/crush.db`, so a launch from a project subdirectory, or a
+ project whose Crush config sets `options.data_directory`, imported nothing.
+ They now find the store as Crush does: `options.data_directory` from Crush's
+ JSON configs, else the closest `.crush` up to the git worktree root (not one
+ directly in the home), else `<cwd>/.crush`. (#820)
- Native `ai-memory upgrade` accepts release archives whose entries are
`./`-prefixed (`tar -C … -czf … .` as in `release.yml`), instead of
rejecting `Component::CurDir` as an unsafe path. (#802)
diff --git a/Cargo.lock b/Cargo.lock
index 0715ac6a..b4b4d65a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -60,6 +60,7 @@ dependencies = [
"reqwest 0.12.28",
"rmcp",
"rstest",
+ "rusqlite",
"rustls",
"secrecy",
"serde",
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index b2859925..bb26825c 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -94,6 +94,7 @@ tempfile.workspace = true
ai-memory-test-support.workspace = true
tempfile.workspace = true
rstest.workspace = true
+rusqlite.workspace = true
tower.workspace = true
tokio = { workspace = true, features = ["test-util"] }
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 4d322719..e8a3aede 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -40,8 +40,8 @@ use serde::{Deserialize, Serialize};
use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};
use ai_memory_workstream::{
- ManagedHarness, build_launch_plan, export_transcript, list_native_sessions,
- wait_for_transcript_flush,
+ LaunchRoots, ManagedHarness, build_launch_plan_with_env, export_transcript,
+ list_native_sessions, wait_for_transcript_flush,
};
use super::doctor::SCANNED_HARNESSES;
@@ -270,9 +270,11 @@ async fn collect_local_sessions(
) -> Vec<SessionRef> {
let mut out = Vec::new();
for &harness in SCANNED_HARNESSES {
- let session_dir = build_launch_plan(harness, None, Vec::new(), None)
- .ok()
- .and_then(|plan| plan.session_dir);
+ let roots = LaunchRoots { home, cwd };
+ let session_dir =
+ build_launch_plan_with_env(harness, None, Vec::new(), None, &[], Some(roots))
+ .ok()
+ .and_then(|plan| plan.session_dir);
let Ok(sessions) = list_native_sessions(
harness,
home,
@@ -328,9 +330,11 @@ async fn import_one(
cwd: &Path,
session: &SessionRef,
) -> Result<usize> {
- let session_dir = build_launch_plan(session.harness, None, Vec::new(), None)
- .ok()
- .and_then(|plan| plan.session_dir);
+ let roots = LaunchRoots { home, cwd };
+ let session_dir =
+ build_launch_plan_with_env(session.harness, None, Vec::new(), None, &[], Some(roots))
+ .ok()
+ .and_then(|plan| plan.session_dir);
// These are historical sessions, so the flush wait is a quick no-op; ignore
// its result and read whatever is on disk.
let _ = wait_for_transcript_flush(
diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rs
index 97c5d81b..785e14e0 100644
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@ -27,7 +27,9 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use ai_memory_core::AgentKind;
-use ai_memory_workstream::{ManagedHarness, build_launch_plan, list_native_sessions};
+use ai_memory_workstream::{
+ LaunchRoots, ManagedHarness, build_launch_plan_with_env, list_native_sessions,
+};
use crate::config::Config;
use crate::http_client::{ServerEndpoint, get_json};
@@ -181,9 +183,11 @@ pub(crate) async fn scan_local(home: &Path, cwd: &Path, since_days: u32) -> Vec<
// Honor harness home relocations (CODEX_HOME, KIMI_CODE_HOME, …) via the
// same launch-plan resolver `ai-memory run` uses; fall back to the
// default $HOME-relative store when a probe plan cannot be built.
- let session_dir = build_launch_plan(harness, None, Vec::new(), None)
- .ok()
- .and_then(|plan| plan.session_dir);
+ let roots = LaunchRoots { home, cwd };
+ let session_dir =
+ build_launch_plan_with_env(harness, None, Vec::new(), None, &[], Some(roots))
+ .ok()
+ .and_then(|plan| plan.session_dir);
let Ok(sessions) =
list_native_sessions(harness, home, cwd, session_dir.as_deref(), SCAN_LIMIT).await
else {
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 9b12e94f..c2053155 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -12,12 +12,14 @@ use ai_memory_core::{
PrepareManagedRunResponse,
};
use ai_memory_workstream::{
- ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,
- allows_native_session_adoption, apply_yolo, build_launch_plan, build_launch_plan_with_env,
+ AmbiguousNativeSession, ExportedTranscript, LaunchMode, LaunchPlan, LaunchRoots,
+ ManagedHarness, NativeSessionCandidate, allows_native_session_adoption, apply_yolo,
+ build_launch_plan, build_launch_plan_with_env, crush_global_config_path,
discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
- list_native_sessions, native_session_exists, store_override_vars, wait_for_transcript_flush,
+ list_native_sessions, native_session_exists, native_session_in_checkout, store_override_vars,
+ wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -282,6 +284,10 @@ pub(super) async fn run_from_with_wiring(
native_args.clone(),
Some(&candidate.session.native_session_id),
&run_env,
+ Some(LaunchRoots {
+ home: &home,
+ cwd: &repository.cwd,
+ }),
));
eprintln!(
"ai-memory: continuing newest checkout-local {} session {}",
@@ -325,6 +331,10 @@ pub(super) async fn run_from_with_wiring(
native_args,
Some(&native_session_id),
&run_env,
+ Some(LaunchRoots {
+ home: &home,
+ cwd: &repository.cwd,
+ }),
));
}
Ok(None) => {}
@@ -408,7 +418,8 @@ pub(super) async fn run_from_with_wiring(
}
let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {
- acquired_try!(prepare_crush_context(&endpoint, &run_path, &home).await)
+ let source = crush_context_source(&home, &repository.cwd, launch_env);
+ acquired_try!(prepare_crush_context(&endpoint, &run_path, &source).await)
} else {
None
};
@@ -460,8 +471,8 @@ pub(super) async fn run_from_with_wiring(
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
- // A blank home override is unset for session import and auto-wire; drop
- // it from the child as well, or the harness
+ // A blank home override is unset for session import, auto-wire and the
+ // Crush context config; drop it from the child as well, or the harness
// would read a blank-named directory under the checkout that nothing else
// follows.
for name in blank_home_overrides(harness, &launch_env) {
@@ -550,6 +561,7 @@ pub(super) async fn run_from_with_wiring(
&home,
&repository.cwd,
started_at,
+ prepared.native_session_id.as_deref(),
server_status.as_ref(),
)
.await
@@ -660,12 +672,16 @@ async fn cancel_managed_run_after_failure(endpoint: &ServerEndpoint, run_path: &
}
}
+/// The native session this run used. `prepared_session` is the session the
+/// run was prepared with, which the server reports until a hook in the child
+/// links another.
async fn resolve_native_session_after_run(
plan: &LaunchPlan,
harness: ManagedHarness,
home: &Path,
cwd: &Path,
started_at: SystemTime,
+ prepared_session: Option<&str>,
server_status: Option<&ManagedRunStatus>,
) -> Result<Option<String>> {
if plan.mode == LaunchMode::Passthrough {
@@ -674,10 +690,47 @@ async fn resolve_native_session_after_run(
if let Some(native_session_id) = &plan.expected_session_id {
return Ok(Some(native_session_id.clone()));
}
- let discovered =
- discover_native_session(harness, home, cwd, plan.session_dir.as_deref(), started_at)
- .await?;
- Ok(discovered.or_else(|| server_status.and_then(|status| status.native_session_id.clone())))
+ let reported = server_status.and_then(|status| status.native_session_id.as_deref());
+ // A hook links its session under this run's id, which a concurrent launch
+ // in the same checkout cannot do; discovery only sees the newest session.
+ // A descendant process inherits the id too, so the session must also be
+ // this checkout's.
+ let linked = reported.filter(|linked| Some(*linked) != prepared_session);
+ if let Some(linked) = linked
+ && native_session_in_checkout(harness, home, cwd, plan.session_dir.as_deref(), linked)
+ .unwrap_or(false)
+ {
+ return Ok(Some(linked.to_string()));
+ }
+ let fresh = !has_native_session_selector(harness, &plan.args);
+ let discovered = match discover_native_session(
+ harness,
+ home,
+ cwd,
+ plan.session_dir.as_deref(),
+ started_at,
+ fresh,
+ )
+ .await
+ {
+ Ok(discovered) => discovered,
+ // The session the run was prepared with is no evidence either: this
+ // launch may not have touched it while another one did.
+ Err(error) if error.is::<AmbiguousNativeSession>() => {
+ eprintln!(
+ "ai-memory: {error}, so its transcript was not imported; resume the session with its native selector to link it"
+ );
+ return Ok(None);
+ }
+ Err(error) => return Err(error),
+ };
+ // A linked session set aside above belongs to another checkout, so it is
+ // no fallback either.
+ Ok(discovered.or_else(|| {
+ reported
+ .filter(|reported| Some(*reported) != linked)
+ .map(str::to_string)
+ }))
}
async fn list_auto_sessions(home: &Path, cwd: &Path) -> Result<Vec<AutoSessionCandidate>> {
@@ -883,14 +936,20 @@ fn upsert_env(entries: &mut Vec<(String, String)>, key: String, value: String) {
}
}
-/// The launched harness's home variables (its store overrides) that are set
-/// but blank in the launch environment.
+/// The launched harness's home variables (its store overrides, plus the
+/// config home Crush's managed context is built from) that are set but blank
+/// in the launch environment.
fn blank_home_overrides(
harness: ManagedHarness,
get: &dyn Fn(&str) -> Option<OsString>,
) -> Vec<&'static str> {
+ let crush_config: &[&'static str] = match harness {
+ ManagedHarness::Crush => &["CRUSH_GLOBAL_CONFIG", "XDG_CONFIG_HOME"],
+ _ => &[],
+ };
store_override_vars(harness)
.iter()
+ .chain(crush_config)
.copied()
.filter(|name| {
let value = get(name);
@@ -923,6 +982,7 @@ fn build_preflighted_launch_plan(
native_args.clone(),
linked_session_id,
env_overrides,
+ Some(LaunchRoots { home, cwd }),
)?;
let Some(linked_session_id) = linked_session_id else {
return Ok((plan, None));
@@ -939,7 +999,14 @@ fn build_preflighted_launch_plan(
) {
Ok(true) => Ok((plan, None)),
Ok(false) => Ok((
- build_launch_plan_with_env(harness, executable, native_args, None, env_overrides)?,
+ build_launch_plan_with_env(
+ harness,
+ executable,
+ native_args,
+ None,
+ env_overrides,
+ Some(LaunchRoots { home, cwd }),
+ )?,
Some(linked_session_id.to_string()),
)),
Err(error) => {
@@ -1068,7 +1135,7 @@ async fn fetch_grok_context(endpoint: &ServerEndpoint, run_path: &str) -> Result
async fn prepare_crush_context(
endpoint: &ServerEndpoint,
run_path: &str,
- home: &Path,
+ source: &Path,
) -> Result<Option<tempfile::TempDir>> {
let response: ManagedRunContextResponse = post_json(
endpoint,
@@ -1081,7 +1148,19 @@ async fn prepare_crush_context(
return Ok(None);
};
- write_crush_context_config(&crush_global_config_path(home), &context).map(Some)
+ write_crush_context_config(source, &context).map(Some)
+}
+
+/// The global `crush.json` the launched Crush reads. Crush takes a relative
+/// `CRUSH_GLOBAL_CONFIG` from its working directory, and the generated config
+/// dir (and its `crushrc`) must name the user's files absolutely because the
+/// child reads them from elsewhere.
+fn crush_context_source(
+ home: &Path,
+ cwd: &Path,
+ get: impl Fn(&str) -> Option<OsString>,
+) -> PathBuf {
+ cwd.join(crush_global_config_path(home, get))
}
fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::TempDir> {
@@ -1092,27 +1171,61 @@ fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::
let context_path = temp.path().join("managed-workstream.md");
write_private(&context_path, context.as_bytes())?;
- let mut config = if source.is_file() {
- let raw = std::fs::read(source)
- .with_context(|| format!("reading Crush config {}", source.display()))?;
+ // Crush cleans the path (`filepath.Join`) before reading it, so a `..`
+ // after a missing directory still reaches the file.
+ let source = ai_memory_workstream::clean_path(source);
+ let raw = if source.is_file() {
+ std::fs::read(&source)
+ .with_context(|| format!("reading Crush config {}", source.display()))?
+ } else {
+ Vec::new()
+ };
+ // Crush skips an empty file and reads `null` as unset; do the same rather
+ // than refuse a config Crush itself accepts.
+ let mut config = if raw.is_empty() {
+ serde_json::Value::Null
+ } else {
serde_json::from_slice::<serde_json::Value>(&raw)
.with_context(|| format!("parsing Crush config {}", source.display()))?
- } else {
- serde_json::json!({})
};
+ if config.is_null() {
+ config = serde_json::json!({});
+ }
let root = config
.as_object_mut()
.context("Crush global config must be a JSON object")?;
- let options = root
- .entry("options")
- .or_insert_with(|| serde_json::json!({}))
+ let options = root.entry("options").or_insert(serde_json::Value::Null);
+ if options.is_null() {
+ *options = serde_json::json!({});
+ }
+ let options = options
.as_object_mut()
.context("Crush global config `options` must be a JSON object")?;
let paths = options
.entry("global_context_paths")
- .or_insert_with(|| serde_json::json!([]))
+ .or_insert(serde_json::Value::Null);
+ if paths.is_null() {
+ *paths = serde_json::json!([]);
+ }
+ let paths = paths
.as_array_mut()
.context("Crush `options.global_context_paths` must be an array")?;
+ // Crush fills an empty list with `CRUSH.md` beside its global config and
+ // `AGENTS.md` one level up, but only while the list is empty, and it would
+ // resolve them against this temp dir. Seed the user's own ones first so
+ // the packet does not replace them.
+ if paths.is_empty()
+ && let Some(config_dir) = source.parent()
+ {
+ paths.push(serde_json::Value::String(
+ config_dir.join("CRUSH.md").to_string_lossy().into_owned(),
+ ));
+ if let Some(parent) = config_dir.parent() {
+ paths.push(serde_json::Value::String(
+ parent.join("AGENTS.md").to_string_lossy().into_owned(),
+ ));
+ }
+ }
let context_path = context_path.to_string_lossy().into_owned();
if !paths
.iter()
@@ -1122,17 +1235,23 @@ fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::
}
let rendered = serde_json::to_vec_pretty(&config).context("rendering Crush config")?;
write_private(&temp.path().join("crush.json"), &rendered)?;
- Ok(temp)
-}
-
-fn crush_global_config_path(home: &Path) -> PathBuf {
- if let Some(dir) = std::env::var_os("CRUSH_GLOBAL_CONFIG").filter(|value| !value.is_empty()) {
- return PathBuf::from(dir).join("crush.json");
- }
- if let Some(dir) = std::env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {
- return PathBuf::from(dir).join("crush/crush.json");
+ // Crush also runs the `crushrc` beside its global config, and with the
+ // config dir moved here it would look for one in this dir. Source the
+ // user's own from the directory Crush runs it in, so its relative paths
+ // and `source` lines still resolve. Its settings merge over the JSON
+ // above and lists concatenate, so the packet stays loaded. Unlike Crush,
+ // the default context files above are seeded even when the script adds
+ // paths of its own.
+ if let Some(config_dir) = source.parent() {
+ let crushrc = config_dir.join("crushrc");
+ if crushrc.is_file() {
+ let quote =
+ |path: &Path| format!("'{}'", path.to_string_lossy().replace('\'', r"'\''"));
+ let wrapper = format!("cd {} && source {}\n", quote(config_dir), quote(&crushrc));
+ write_private(&temp.path().join("crushrc"), wrapper.as_bytes())?;
+ }
}
- home.join(".config/crush/crush.json")
+ Ok(temp)
}
fn write_private(path: &Path, content: &[u8]) -> Result<()> {
@@ -2327,9 +2446,15 @@ mod tests {
"CLAUDE_CONFIG_DIR".to_string(),
"/accounts/work".to_string(),
)];
- let plan =
- build_launch_plan_with_env(ManagedHarness::Claude, None, Vec::new(), None, &overrides)
- .unwrap();
+ let plan = build_launch_plan_with_env(
+ ManagedHarness::Claude,
+ None,
+ Vec::new(),
+ None,
+ &overrides,
+ None,
+ )
+ .unwrap();
assert_eq!(
plan.session_dir.as_deref(),
Some(Path::new("/accounts/work/projects"))
@@ -2579,6 +2704,7 @@ mod tests {
&cwd,
started_at,
None,
+ None,
)
.await
.unwrap()
@@ -2594,6 +2720,7 @@ mod tests {
&cwd,
started_at,
None,
+ None,
)
.await
.unwrap()
@@ -2602,6 +2729,168 @@ mod tests {
);
}
+ /// A hook links the run's own session under its run id, so a newer
+ /// session another launch made in the same checkout does not replace it.
+ /// A report that only repeats the session the run was prepared with is no
+ /// link, and discovery still decides.
+ #[tokio::test]
+ async fn hook_linked_session_wins_over_a_newer_concurrent_session() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let session_root = temp.path().join(".codex/sessions/2026/01/01");
+ std::fs::create_dir_all(&cwd).unwrap();
+ std::fs::create_dir_all(&session_root).unwrap();
+ let started_at = SystemTime::now();
+ let rollout = |name: &str, id: &str, cwd: &Path| {
+ std::fs::write(
+ session_root.join(format!("rollout-{name}.jsonl")),
+ format!(
+ "{}\n",
+ serde_json::json!({
+ "type": "session_meta",
+ "payload": {"id": id, "cwd": cwd}
+ })
+ ),
+ )
+ .unwrap();
+ };
+ rollout("linked", "hook-linked", &cwd);
+ // A descendant process in another checkout inherits the run id.
+ rollout("nested", "nested", &temp.path().join("other-checkout"));
+ rollout("concurrent", "concurrent-newer", &cwd);
+ let plan = build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();
+ let status = |native: &str| ManagedRunStatus {
+ run_id: ManagedRunId::new(),
+ workstream_id: WorkstreamId::new(),
+ agent: AgentKind::Codex,
+ native_session_id: Some(native.to_string()),
+ context_delivered: true,
+ state: "active".to_string(),
+ };
+ let resolve = async |native: &str, prepared: Option<&str>| {
+ resolve_native_session_after_run(
+ &plan,
+ ManagedHarness::Codex,
+ temp.path(),
+ &cwd,
+ started_at,
+ prepared,
+ Some(&status(native)),
+ )
+ .await
+ .unwrap()
+ };
+ assert_eq!(
+ resolve("hook-linked", None).await.as_deref(),
+ Some("hook-linked")
+ );
+ assert_eq!(
+ resolve("hook-linked", Some("earlier")).await.as_deref(),
+ Some("hook-linked")
+ );
+ assert_eq!(
+ resolve("hook-linked", Some("hook-linked")).await.as_deref(),
+ Some("concurrent-newer")
+ );
+ assert_eq!(
+ resolve("nested", Some("earlier")).await.as_deref(),
+ Some("concurrent-newer")
+ );
+ // With nothing to discover here, the other checkout's session is not
+ // taken as a fallback either; the prepared session still is.
+ let empty = temp.path().join("empty-checkout");
+ std::fs::create_dir_all(&empty).unwrap();
+ for (prepared, expected) in [(Some("earlier"), None), (Some("nested"), Some("nested"))] {
+ assert_eq!(
+ resolve_native_session_after_run(
+ &plan,
+ ManagedHarness::Codex,
+ temp.path(),
+ &empty,
+ started_at,
+ prepared,
+ Some(&status("nested")),
+ )
+ .await
+ .unwrap()
+ .as_deref(),
+ expected,
+ "prepared={prepared:?}"
+ );
+ }
+ }
+
+ /// Two new Crush sessions in one store cannot be told apart, and that is
+ /// reported without cancelling the finished run or falling back to the
+ /// session the run was prepared with, which another launch may have
+ /// moved. With no ambiguity a fresh run that created nothing keeps that
+ /// session, and `--continue` claims the session it resumed.
+ #[tokio::test]
+ async fn ambiguous_crush_discovery_keeps_the_run() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ std::fs::create_dir_all(&cwd).unwrap();
+ let started = 1_900_000_000_i64;
+ let started_at = SystemTime::UNIX_EPOCH + Duration::from_secs(started as u64);
+ let store = |name: &str, sessions: &[(&str, i64, i64)]| {
+ // Inside the checkout: a store only this project uses.
+ let data = cwd.join(name);
+ std::fs::create_dir_all(&data).unwrap();
+ let connection = rusqlite::Connection::open(data.join("crush.db")).unwrap();
+ connection
+ .execute_batch(
+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \
+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL);",
+ )
+ .unwrap();
+ for (id, created, updated) in sessions {
+ connection
+ .execute(
+ "INSERT INTO sessions VALUES (?1, NULL, ?2, ?3)",
+ rusqlite::params![id, started + updated, started + created],
+ )
+ .unwrap();
+ }
+ data
+ };
+ let crowded = store(
+ "crowded",
+ &[("continued", -1_000, 30), ("a", 5, 20), ("b", 8, 10)],
+ );
+ let quiet = store("quiet", &[("continued", -1_000, 30)]);
+ let status = ManagedRunStatus {
+ run_id: ManagedRunId::new(),
+ workstream_id: WorkstreamId::new(),
+ agent: AgentKind::Crush,
+ native_session_id: Some("prepared".to_string()),
+ context_delivered: false,
+ state: "active".to_string(),
+ };
+ let resolve = async |data: &Path, extra: &[&str]| {
+ let mut args = vec![OsString::from("--data-dir"), data.as_os_str().to_owned()];
+ args.extend(extra.iter().map(OsString::from));
+ let plan = build_launch_plan(ManagedHarness::Crush, None, args, None).unwrap();
+ resolve_native_session_after_run(
+ &plan,
+ ManagedHarness::Crush,
+ temp.path(),
+ &cwd,
+ started_at,
+ Some("prepared"),
+ Some(&status),
+ )
+ .await
+ .unwrap()
+ };
+ assert_eq!(resolve(&crowded, &[]).await, None);
+ assert_eq!(resolve(&crowded, &["--continue"]).await, None);
+ assert_eq!(resolve(&quiet, &[]).await.as_deref(), Some("prepared"));
+ assert_eq!(
+ resolve(&quiet, &["--continue"]).await.as_deref(),
+ Some("continued")
+ );
+ }
+
#[test]
fn crush_context_config_preserves_user_settings_and_adds_packet() {
let source_dir = tempfile::tempdir().unwrap();
@@ -2968,6 +3257,206 @@ mod tests {
),
["PI_CODING_AGENT_SESSION_DIR"]
);
+ assert_eq!(
+ blank_home_overrides(
+ ManagedHarness::Crush,
+ &env(&[("CRUSH_GLOBAL_CONFIG", " "), ("XDG_CONFIG_HOME", "/x")])
+ ),
+ ["CRUSH_GLOBAL_CONFIG"]
+ );
+ assert!(
+ blank_home_overrides(ManagedHarness::Claude, &env(&[("XDG_CONFIG_HOME", "")]))
+ .is_empty(),
+ "Crush's config home is Crush's alone"
+ );
+ }
+
+ /// The managed Crush context layers onto the global config the child
+ /// would read: `--env` over ai-memory's own environment, blank as unset.
+ /// A relative `CRUSH_GLOBAL_CONFIG` is read from the launch directory, as
+ /// Crush reads it, so the generated config and `crushrc` do not point at
+ /// paths the child would resolve from its temporary config dir.
+ #[test]
+ fn crush_context_source_is_anchored_at_the_launch_dir() {
+ let home = Path::new("/home/user");
+ let cwd = Path::new("/work/repo");
+ let env = |pairs: &'static [(&'static str, &'static str)]| {
+ move |name: &str| {
+ pairs
+ .iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, value)| OsString::from(value))
+ }
+ };
+ assert_eq!(
+ crush_context_source(home, cwd, env(&[("CRUSH_GLOBAL_CONFIG", "cfg")])),
+ cwd.join("cfg").join("crush.json")
+ );
+ assert_eq!(
+ crush_context_source(home, cwd, env(&[])),
+ home.join(".config").join("crush").join("crush.json")
+ );
+ }
+
+ #[test]
+ fn crush_global_config_path_follows_the_launch_env() {
+ let env = |pairs: &'static [(&'static str, &'static str)]| {
+ move |name: &str| {
+ pairs
+ .iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, value)| OsString::from(value))
+ }
+ };
+ let home = Path::new("/home/me");
+ let default = home.join(".config").join("crush").join("crush.json");
+ assert_eq!(
+ crush_global_config_path(
+ home,
+ env(&[
+ ("CRUSH_GLOBAL_CONFIG", "/team/crush"),
+ ("XDG_CONFIG_HOME", "/xdg")
+ ])
+ ),
+ Path::new("/team/crush").join("crush.json")
+ );
+ assert_eq!(
+ crush_global_config_path(home, env(&[("XDG_CONFIG_HOME", "/xdg")])),
+ Path::new("/xdg").join("crush").join("crush.json")
+ );
+ assert_eq!(
+ crush_global_config_path(
+ home,
+ env(&[("CRUSH_GLOBAL_CONFIG", " "), ("XDG_CONFIG_HOME", "")])
+ ),
+ default,
+ "blank counts as unset"
+ );
+ assert_eq!(crush_global_config_path(home, env(&[])), default);
+ }
+
+ /// Crush skips an empty config and reads `null` as unset, so neither may
+ /// stop a managed launch.
+ #[test]
+ fn crush_context_config_accepts_what_crush_accepts() {
+ let root = tempfile::tempdir().unwrap();
+ for (name, content) in [
+ ("empty", ""),
+ ("null-options", r#"{"options": null}"#),
+ (
+ "null-paths",
+ r#"{"options": {"global_context_paths": null}}"#,
+ ),
+ ("null", "null"),
+ ] {
+ let dir = root.path().join(name);
+ std::fs::create_dir_all(&dir).unwrap();
+ let source = dir.join("crush.json");
+ std::fs::write(&source, content).unwrap();
+ let generated = write_crush_context_config(&source, "managed packet")
+ .unwrap_or_else(|error| panic!("{name}: {error:#}"));
+ let config: serde_json::Value = serde_json::from_slice(
+ &std::fs::read(generated.path().join("crush.json")).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(
+ config["options"]["global_context_paths"]
+ .as_array()
+ .map(Vec::len),
+ Some(3),
+ "{name}: {config}"
+ );
+ }
+ }
+
+ /// Crush cleans the config path before reading it and deriving its default
+ /// context files, so a `..` in `CRUSH_GLOBAL_CONFIG` moves neither.
+ #[test]
+ fn crush_default_context_files_follow_the_cleaned_config_path() {
+ let root = tempfile::tempdir().unwrap();
+ let config_dir = root.path().join("cfg");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(config_dir.join("crush.json"), r#"{"marker": 1}"#).unwrap();
+ // `missing` does not exist: only a cleaned path reaches the file.
+ let source = config_dir.join("missing").join("..").join("crush.json");
+
+ let generated = write_crush_context_config(&source, "managed packet").unwrap();
+ let config: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(generated.path().join("crush.json")).unwrap())
+ .unwrap();
+ let paths: Vec<&str> = config["options"]["global_context_paths"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_str().unwrap())
+ .collect();
+ assert_eq!(Path::new(paths[0]), config_dir.join("CRUSH.md"));
+ assert_eq!(Path::new(paths[1]), root.path().join("AGENTS.md"));
+ assert_eq!(config["marker"], 1, "the user's config was read");
+ }
+
+ /// Crush only fills in its default `CRUSH.md` / `AGENTS.md` while
+ /// `global_context_paths` is empty, so the packet must not displace the
+ /// user's own files.
+ #[test]
+ fn crush_context_config_keeps_crush_default_context_files() {
+ let root = tempfile::tempdir().unwrap();
+ let config_dir = root.path().join("config").join("crush");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ let source = config_dir.join("crush.json");
+ std::fs::write(&source, r#"{"options": {"debug": true}}"#).unwrap();
+
+ let generated = write_crush_context_config(&source, "managed packet").unwrap();
+ let config: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(generated.path().join("crush.json")).unwrap())
+ .unwrap();
+ let paths: Vec<&str> = config["options"]["global_context_paths"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_str().unwrap())
+ .collect();
+ assert_eq!(paths.len(), 3, "{paths:?}");
+ assert_eq!(Path::new(paths[0]), config_dir.join("CRUSH.md"));
+ assert_eq!(
+ Path::new(paths[1]),
+ root.path().join("config").join("AGENTS.md")
+ );
+ assert_eq!(std::fs::read_to_string(paths[2]).unwrap(), "managed packet");
+ }
+
+ /// Crush runs the `crushrc` beside its global config, and moving the
+ /// config dir for the context packet would drop the user's. The generated
+ /// dir sources it from its own directory, so relative `source` lines keep
+ /// working, whatever the path contains.
+ #[cfg(unix)]
+ #[test]
+ fn crush_context_config_carries_the_global_crushrc() {
+ let root = tempfile::tempdir().unwrap();
+ let root = std::fs::canonicalize(root.path()).unwrap();
+ let config_dir = root.join("it's my crush");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ let source = config_dir.join("crush.json");
+
+ let generated = write_crush_context_config(&source, "managed packet").unwrap();
+ assert!(!generated.path().join("crushrc").exists());
+
+ std::fs::write(config_dir.join("crushrc"), "source ./extra\n").unwrap();
+ std::fs::write(config_dir.join("extra"), "pwd > \"$OUT\"\n").unwrap();
+ let generated = write_crush_context_config(&source, "managed packet").unwrap();
+ let out = root.join("out");
+ // Crush runs a crushrc from its own directory.
+ let status = std::process::Command::new("bash")
+ .arg(generated.path().join("crushrc"))
+ .current_dir(generated.path())
+ .env("OUT", &out)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ assert_eq!(
+ std::fs::read_to_string(&out).unwrap().trim_end(),
+ config_dir.to_str().unwrap()
+ );
}
/// The launched harness must not see a blank store override that session
diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rs
index 8fdcdeec..c2d5c8b8 100644
--- a/crates/ai-memory-cli/src/commands/run_autowire.rs
+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs
@@ -679,6 +679,7 @@ mod tests {
Vec::new(),
None,
&run_env,
+ None,
)
.unwrap();
assert_eq!(plan.session_dir, None, "{harness:?} session store");
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 5cd3f024..618830ac 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -203,7 +203,24 @@ pub fn build_launch_plan(
native_args: Vec<OsString>,
linked_session_id: Option<&str>,
) -> Result<LaunchPlan> {
- build_launch_plan_with_env(harness, executable, native_args, linked_session_id, &[])
+ build_launch_plan_with_env(
+ harness,
+ executable,
+ native_args,
+ linked_session_id,
+ &[],
+ None,
+ )
+}
+
+/// Where a launch runs: the home the harness resolves `~` against and the
+/// directory it starts in.
+#[derive(Debug, Clone, Copy)]
+pub struct LaunchRoots<'a> {
+ /// The native home.
+ pub home: &'a Path,
+ /// The harness's working directory.
+ pub cwd: &'a Path,
}
/// [`build_launch_plan`] with `--env`/`--env-file` overrides layered in front
@@ -215,28 +232,37 @@ pub fn build_launch_plan(
/// this same variable, so a caller-scoped override that only reached the
/// child process would make the two disagree about where the session lives
/// (see the `CLAUDE_CONFIG_DIR` note in `docs/managed-workstreams.md`).
+///
+/// `roots` name the native home and the launch directory. Crush needs both
+/// (its data directory is found from the launch directory, see
+/// [`crush_data_dir`]); without them that store falls back to the adapter's
+/// default root.
pub fn build_launch_plan_with_env(
harness: ManagedHarness,
executable: Option<OsString>,
native_args: Vec<OsString>,
linked_session_id: Option<&str>,
env_overrides: &[(String, String)],
+ roots: Option<LaunchRoots<'_>>,
) -> Result<LaunchPlan> {
let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));
let mut args = native_args;
+ let get = |name: &str| {
+ env_overrides
+ .iter()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| OsString::from(value))
+ .or_else(|| std::env::var_os(name))
+ };
let session_dir = match harness {
ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),
ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),
_ => None,
}
- .or_else(|| {
- environment_session_dir_with(harness, |name| {
- env_overrides
- .iter()
- .find(|(key, _)| key == name)
- .map(|(_, value)| OsString::from(value))
- .or_else(|| std::env::var_os(name))
- })
+ .or_else(|| environment_session_dir_with(harness, get))
+ .or_else(|| match (harness, roots) {
+ (ManagedHarness::Crush, Some(roots)) => Some(crush_data_dir(roots.cwd, roots.home, get)),
+ _ => None,
});
let mut expected = explicit_session_id(harness, &args);
let mode = launch_mode(harness, &args);
@@ -972,6 +998,201 @@ pub fn clean_path(path: &Path) -> PathBuf {
clean
}
+/// Crush's global `crush.json`, resolved as Crush's `GlobalConfig()` does:
+/// `$CRUSH_GLOBAL_CONFIG/crush.json`, else `$XDG_CONFIG_HOME/crush/crush.json`,
+/// else `~/.config/crush/crush.json`. `get` is the launch environment, and a
+/// blank value counts as unset, as for every other harness home; a managed
+/// launch drops such a value from Crush too.
+pub fn crush_global_config_path(home: &Path, get: impl Fn(&str) -> Option<OsString>) -> PathBuf {
+ let dir = |name| env_dir_override(get(name));
+ if let Some(dir) = dir("CRUSH_GLOBAL_CONFIG") {
+ return dir.join("crush.json");
+ }
+ dir("XDG_CONFIG_HOME")
+ .unwrap_or_else(|| home.join(".config"))
+ .join("crush")
+ .join("crush.json")
+}
+
+/// The directory Crush keeps `crush.db` in when no `--data-dir` is given,
+/// resolved as Crush's `setDefaults` does: the last `options.data_directory`
+/// among its JSON configs, else the closest `.crush` from `cwd` up to the git
+/// worktree root (not one directly in the home, and the walk stops at an
+/// entry another user owns), else `<cwd>/.crush`. A relative value is taken
+/// against `cwd`. `get` is the launch environment.
+///
+/// A `crushrc` can set the option as well, but reading it means running the
+/// user's shell script, so a data directory set only there is not seen; pass
+/// `--data-dir` to name it.
+pub fn crush_data_dir(cwd: &Path, home: &Path, get: impl Fn(&str) -> Option<OsString>) -> PathBuf {
+ let cwd = clean_path(&std::path::absolute(cwd).unwrap_or_else(|_| cwd.to_path_buf()));
+ let boundary = crate::repository::worktree_root(&cwd).unwrap_or_else(|| cwd.clone());
+ // Crush gives up on both upward searches when it cannot stat the start.
+ let walk = path_owner(&cwd)
+ .ok()
+ .map(|owner| (owner, crush_walk_up(&cwd, &boundary)));
+ let configured = crush_config_files(&cwd, home, walk.as_ref(), &get)
+ .iter()
+ .fold(None, |value, file| {
+ crush_config_data_directory(file).or(value)
+ })
+ .filter(|dir| !dir.is_empty())
+ .map(PathBuf::from);
+ let dir = configured
+ .or_else(|| {
+ let (owner, dirs) = walk.as_ref()?;
+ crush_closest_data_dir(dirs, *owner, home)
+ })
+ .unwrap_or_else(|| cwd.join(".crush"));
+ // Crush's `SmartJoin`: a path that starts with a slash is absolute on
+ // Windows too.
+ let rooted = cfg!(windows) && dir.to_string_lossy().starts_with(['/', '\\']);
+ if dir.is_absolute() || rooted {
+ clean_path(&dir)
+ } else {
+ clean_path(&cwd.join(dir))
+ }
+}
+
+/// [`crush_data_dir`] against ai-memory's own environment, for a store no
+/// launch plan named (automatic session discovery).
+pub(crate) fn crush_process_data_dir(cwd: &Path, home: &Path) -> PathBuf {
+ crush_data_dir(cwd, home, |name| std::env::var_os(name))
+}
+
+/// Crush's JSON configs in merge order, later ones winning: the system file,
+/// the global config, the global data config, then the project's
+/// `crush.json` and `.crush.json` from the walk's top down to `cwd`.
+fn crush_config_files(
+ cwd: &Path,
+ home: &Path,
+ walk: Option<&(Option<u32>, Vec<PathBuf>)>,
+ get: &impl Fn(&str) -> Option<OsString>,
+) -> Vec<PathBuf> {
+ // Crush tests these with `!= ""` and reads a relative path from its
+ // working directory.
+ let set = |name: &str| {
+ get(name)
+ .filter(|value| !value.is_empty())
+ .map(PathBuf::from)
+ };
+ let global_data = if let Some(dir) = set("CRUSH_GLOBAL_DATA") {
+ dir.join("crush.json")
+ } else if let Some(dir) = set("XDG_DATA_HOME") {
+ dir.join("crush").join("crush.json")
+ } else if cfg!(windows) {
+ set("LOCALAPPDATA")
+ .unwrap_or_else(|| {
+ PathBuf::from(get("USERPROFILE").unwrap_or_default())
+ .join("AppData")
+ .join("Local")
+ })
+ .join("crush")
+ .join("crush.json")
+ } else {
+ home.join(".local")
+ .join("share")
+ .join("crush")
+ .join("crush.json")
+ };
+ let mut files = Vec::new();
+ if cfg!(not(windows)) {
+ files.push(PathBuf::from("/etc/crush/crush.json"));
+ }
+ files.push(cwd.join(crush_global_config_path(home, get)));
+ files.push(cwd.join(global_data));
+ if let Some((owner, dirs)) = walk {
+ for dir in dirs.iter().rev() {
+ for name in ["crush.json", ".crush.json"] {
+ let file = dir.join(name);
+ if crush_probe(&file, *owner) == CrushProbe::Found {
+ files.push(file);
+ }
+ }
+ }
+ }
+ files
+}
+
+/// `options.data_directory` from one JSON config, when it sets one.
+fn crush_config_data_directory(file: &Path) -> Option<String> {
+ let raw = std::fs::read(file).ok()?;
+ let config = serde_json::from_slice::<serde_json::Value>(&raw).ok()?;
+ config
+ .get("options")?
+ .get("data_directory")?
+ .as_str()
+ .map(str::to_owned)
+}
+
+/// Crush's `LookupClosestBounded(cwd, boundary, ".crush")` over `dirs`.
+fn crush_closest_data_dir(dirs: &[PathBuf], owner: Option<u32>, home: &Path) -> Option<PathBuf> {
+ for dir in dirs {
+ let candidate = dir.join(".crush");
+ match crush_probe(&candidate, owner) {
+ CrushProbe::Missing => continue,
+ CrushProbe::Refused => return None,
+ CrushProbe::Found => return (dir != home).then_some(candidate),
+ }
+ }
+ None
+}
+
+/// `cwd` and each parent up to `boundary`, compared with symlinks resolved,
+/// or up to the filesystem root when `boundary` is not above `cwd` (Crush's
+/// `traverseUpBounded`).
+fn crush_walk_up(cwd: &Path, boundary: &Path) -> Vec<PathBuf> {
+ let resolved = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));
+ let stop = resolved(boundary);
+ let mut dirs = Vec::new();
+ let mut dir = Some(cwd);
+ while let Some(current) = dir {
+ dirs.push(current.to_path_buf());
+ if resolved(current) == stop {
+ break;
+ }
+ dir = current.parent();
+ }
+ dirs
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum CrushProbe {
+ Found,
+ Missing,
+ Refused,
+}
+
+/// Crush's `probeEnt`: an entry owned by someone other than the walk's
+/// owner, or one it cannot stat, is refused.
+fn crush_probe(path: &Path, owner: Option<u32>) -> CrushProbe {
+ match std::fs::metadata(path) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => CrushProbe::Missing,
+ Err(_) => CrushProbe::Refused,
+ Ok(metadata) if owner.is_none_or(|owner| metadata_owner(&metadata) == Some(owner)) => {
+ CrushProbe::Found
+ }
+ Ok(_) => CrushProbe::Refused,
+ }
+}
+
+/// The uid Crush compares while walking up (`fsext.Owner`); `None` on
+/// Windows, where Crush skips the check.
+fn path_owner(path: &Path) -> std::io::Result<Option<u32>> {
+ std::fs::metadata(path).map(|metadata| metadata_owner(&metadata))
+}
+
+#[cfg(unix)]
+fn metadata_owner(metadata: &std::fs::Metadata) -> Option<u32> {
+ use std::os::unix::fs::MetadataExt as _;
+ Some(metadata.uid())
+}
+
+#[cfg(not(unix))]
+fn metadata_owner(_metadata: &std::fs::Metadata) -> Option<u32> {
+ None
+}
+
fn environment_session_dir_with(
harness: ManagedHarness,
get: impl Fn(&str) -> Option<OsString>,
@@ -1457,6 +1678,161 @@ mod tests {
);
}
+ fn git_init(dir: &Path) {
+ let status = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(dir)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ }
+
+ /// Only Crush's global config names: the global JSON files under the temp
+ /// root, never the developer's.
+ fn crush_env(root: &Path) -> impl Fn(&str) -> Option<OsString> + use<> {
+ let config = root.join("global-config").into_os_string();
+ let data = root.join("global-data").into_os_string();
+ move |name| match name {
+ "CRUSH_GLOBAL_CONFIG" => Some(config.clone()),
+ "CRUSH_GLOBAL_DATA" => Some(data.clone()),
+ _ => None,
+ }
+ }
+
+ /// Without `--data-dir` Crush keeps `crush.db` in the closest `.crush`
+ /// between the working directory and the git worktree root, not always
+ /// in `<cwd>/.crush`; outside a worktree it looks only in the cwd.
+ #[test]
+ fn crush_data_dir_takes_the_closest_crush_dir_in_the_worktree() {
+ let root = tempfile::tempdir().unwrap();
+ let root = std::fs::canonicalize(root.path()).unwrap();
+ let home = root.join("home");
+ let repo = root.join("repo");
+ let cwd = repo.join("sub").join("deep");
+ std::fs::create_dir_all(&cwd).unwrap();
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir(root.join(".crush")).unwrap();
+ let resolve = |cwd: &Path| crush_data_dir(cwd, &home, crush_env(&root));
+
+ // `<root>/.crush` is above the cwd but outside any worktree bound.
+ assert_eq!(resolve(&cwd), cwd.join(".crush"));
+ git_init(&repo);
+ assert_eq!(
+ resolve(&cwd),
+ cwd.join(".crush"),
+ "the walk stops at the worktree root"
+ );
+ std::fs::create_dir(repo.join(".crush")).unwrap();
+ assert_eq!(resolve(&cwd), repo.join(".crush"));
+ std::fs::create_dir(repo.join("sub").join(".crush")).unwrap();
+ assert_eq!(resolve(&cwd), repo.join("sub").join(".crush"));
+ }
+
+ /// A `.crush` directly in the home is Crush's global state, never a
+ /// project's data dir.
+ #[test]
+ fn crush_data_dir_skips_a_crush_dir_in_the_home() {
+ let root = tempfile::tempdir().unwrap();
+ let root = std::fs::canonicalize(root.path()).unwrap();
+ let home = root.join("home");
+ let cwd = home.join("project");
+ std::fs::create_dir_all(&cwd).unwrap();
+ git_init(&home);
+ std::fs::create_dir(home.join(".crush")).unwrap();
+ assert_eq!(
+ crush_data_dir(&cwd, &home, crush_env(&root)),
+ cwd.join(".crush")
+ );
+ }
+
+ /// `options.data_directory` wins over the lookup. Later configs override
+ /// earlier ones: the global JSON files, then the project's from the
+ /// worktree root down, `.crush.json` over `crush.json` in one directory.
+ /// A relative value is taken against the cwd and an empty one falls back
+ /// to the lookup.
+ #[test]
+ fn crush_data_dir_follows_data_directory_in_crush_configs() {
+ let root = tempfile::tempdir().unwrap();
+ let root = std::fs::canonicalize(root.path()).unwrap();
+ let home = root.join("home");
+ let repo = root.join("repo");
+ let cwd = repo.join("sub");
+ std::fs::create_dir_all(&cwd).unwrap();
+ std::fs::create_dir_all(&home).unwrap();
+ git_init(&repo);
+ let write = |file: &Path, dir: &str| {
+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();
+ std::fs::write(
+ file,
+ serde_json::json!({"options": {"data_directory": dir}}).to_string(),
+ )
+ .unwrap();
+ };
+ let resolve = || crush_data_dir(&cwd, &home, crush_env(&root));
+
+ write(
+ &root.join("global-config").join("crush.json"),
+ "/from/global",
+ );
+ assert_eq!(resolve(), Path::new("/from/global"));
+ write(&root.join("global-data").join("crush.json"), "/from/data");
+ assert_eq!(resolve(), Path::new("/from/data"));
+ write(&repo.join(".crush.json"), "/from/repo-hidden");
+ write(&repo.join("crush.json"), "/from/repo");
+ assert_eq!(resolve(), Path::new("/from/repo-hidden"));
+ write(&cwd.join("crush.json"), "state/../store");
+ assert_eq!(resolve(), cwd.join("store"));
+ write(&cwd.join("crush.json"), "");
+ std::fs::create_dir(repo.join(".crush")).unwrap();
+ assert_eq!(resolve(), repo.join(".crush"));
+ }
+
+ /// The launch plan carries the resolved Crush store when it knows where
+ /// the launch runs; `--data-dir` still wins.
+ #[test]
+ fn crush_launch_plan_resolves_the_data_dir_from_the_launch_dir() {
+ let root = tempfile::tempdir().unwrap();
+ let root = std::fs::canonicalize(root.path()).unwrap();
+ let repo = root.join("repo");
+ let cwd = repo.join("sub");
+ std::fs::create_dir_all(&cwd).unwrap();
+ git_init(&repo);
+ std::fs::create_dir(repo.join(".crush")).unwrap();
+ let env = [
+ (
+ "CRUSH_GLOBAL_CONFIG".to_string(),
+ root.join("global-config").display().to_string(),
+ ),
+ (
+ "CRUSH_GLOBAL_DATA".to_string(),
+ root.join("global-data").display().to_string(),
+ ),
+ ];
+ let plan = |args: Vec<OsString>| {
+ build_launch_plan_with_env(
+ ManagedHarness::Crush,
+ None,
+ args,
+ None,
+ &env,
+ Some(LaunchRoots {
+ home: &root,
+ cwd: &cwd,
+ }),
+ )
+ .unwrap()
+ .session_dir
+ };
+ assert_eq!(plan(Vec::new()), Some(repo.join(".crush")));
+ assert_eq!(
+ plan(vec![
+ OsString::from("--data-dir"),
+ OsString::from("/pinned")
+ ]),
+ Some(PathBuf::from("/pinned"))
+ );
+ }
+
fn env_of(pairs: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> + use<> {
let pairs = pairs.to_vec();
move |name| {
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 284f2dd3..15e2886d 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -5,14 +5,16 @@ mod repository;
mod transcript;
pub use harness::{
- LaunchMode, LaunchPlan, ManagedHarness, allows_native_session_adoption, apply_yolo,
- build_launch_plan, build_launch_plan_with_env, clean_path, env_dir_override,
- has_native_session_selector, kiro_explicit_session_id, kiro_selects_non_default_engine,
- kiro_selects_v2_engine, kiro_selects_v3_engine, store_override_vars,
+ LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,
+ apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path, crush_data_dir,
+ crush_global_config_path, env_dir_override, has_native_session_selector,
+ kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,
+ kiro_selects_v3_engine, store_override_vars,
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
- ExportedTranscript, NativeSessionCandidate, discover_native_session, export_transcript,
- kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,
- native_session_exists, wait_for_transcript_flush,
+ AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,
+ export_transcript, kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store,
+ list_native_sessions, native_session_exists, native_session_in_checkout,
+ wait_for_transcript_flush,
};
diff --git a/crates/ai-memory-workstream/src/repository.rs b/crates/ai-memory-workstream/src/repository.rs
index c1108238..11f18838 100644
--- a/crates/ai-memory-workstream/src/repository.rs
+++ b/crates/ai-memory-workstream/src/repository.rs
@@ -78,6 +78,13 @@ fn checkpoint(cwd: &Path) -> WorkstreamCheckpoint {
}
}
+/// The git worktree root above `cwd`, or `None` outside a worktree.
+pub(crate) fn worktree_root(cwd: &Path) -> Option<PathBuf> {
+ git(cwd, &["rev-parse", "--show-toplevel"])
+ .filter(|root| !root.is_empty())
+ .map(PathBuf::from)
+}
+
fn git(cwd: &Path, args: &[&str]) -> Option<String> {
let output = git_bytes(cwd, args)?;
String::from_utf8(output)
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index a77cf886..89562767 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -16,7 +16,7 @@ use serde_json::{Value, json};
use sha2::{Digest as _, Sha256};
use uuid::Uuid;
-use crate::ManagedHarness;
+use crate::{ManagedHarness, clean_path};
const MAX_SCAN_FILES: usize = 50_000;
const MAX_EVENT_BYTES: usize = 128 * 1024;
@@ -120,7 +120,7 @@ pub async fn export_transcript(
return export_opencode2(home, session_dir, native_session_id, source_cursor);
}
if harness == ManagedHarness::Crush {
- return export_crush(cwd, session_dir, native_session_id, source_cursor);
+ return export_crush(home, cwd, session_dir, native_session_id, source_cursor);
}
if harness == ManagedHarness::Antigravity {
// The conversation store keeps every step as an undocumented protobuf
@@ -138,14 +138,48 @@ pub async fn export_transcript(
export_jsonl(harness, &path, native_session_id, source_cursor)
}
+/// New sessions appeared in a store that records no launch identity and none
+/// can be tied to this run, so a concurrent launch on the same store cannot
+/// be told apart and none is claimed.
+#[derive(Debug)]
+pub struct AmbiguousNativeSession {
+ harness: ManagedHarness,
+ sessions: usize,
+ /// For a store outside the project, how many of them edited a file in it.
+ placed: Option<usize>,
+}
+
+impl std::fmt::Display for AmbiguousNativeSession {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let (sessions, harness) = (self.sessions, self.harness.as_str());
+ match self.placed {
+ None => write!(
+ formatter,
+ "{sessions} new {harness} sessions were created during this run and none records which launch made it"
+ ),
+ Some(placed) => write!(
+ formatter,
+ "{sessions} new {harness} session(s) were created during this run in a data directory outside this project, and {placed} of them edited a file here"
+ ),
+ }
+ }
+}
+
+impl std::error::Error for AmbiguousNativeSession {}
+
/// Discover a session created after `started_at` when the harness could not be
-/// assigned an id before launch and SessionStart did not link one.
+/// assigned an id before launch and SessionStart did not link one. `fresh` is
+/// whether the launch started a new native session rather than continuing the
+/// newest one. Crush, which has no hooks to link its session, claims only the
+/// one session the run created (or, continuing, the one it touched) and fails
+/// with [`AmbiguousNativeSession`] when another launch did the same.
pub async fn discover_native_session(
harness: ManagedHarness,
home: &Path,
cwd: &Path,
session_dir: Option<&Path>,
started_at: SystemTime,
+ fresh: bool,
) -> Result<Option<String>> {
if harness == ManagedHarness::OpenCode {
return discover_opencode(home, session_dir, cwd, started_at);
@@ -154,7 +188,7 @@ pub async fn discover_native_session(
return discover_opencode2(home, session_dir, cwd, started_at);
}
if harness == ManagedHarness::Crush {
- return discover_crush(cwd, session_dir, started_at);
+ return discover_crush(home, cwd, session_dir, started_at, fresh);
}
let mut candidates = collect_session_files(harness, home, session_dir)?;
candidates.sort_by(|left, right| {
@@ -195,7 +229,7 @@ pub async fn list_native_sessions(
return list_opencode2_sessions(home, session_dir, cwd, limit);
}
if harness == ManagedHarness::Crush {
- return list_crush_sessions(cwd, session_dir, limit);
+ return list_crush_sessions(home, cwd, session_dir, limit);
}
let mut files = collect_session_files(harness, home, session_dir)?;
@@ -232,6 +266,36 @@ pub async fn list_native_sessions(
Ok(sessions)
}
+/// Whether the native store holds `native_session_id` for this checkout.
+/// [`native_session_exists`] answers for the store; OpenCode keeps every
+/// checkout's sessions in one database, so there the recorded directory must
+/// match `cwd` too.
+pub fn native_session_in_checkout(
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+) -> Result<bool> {
+ let table = match harness {
+ ManagedHarness::OpenCode => "session",
+ ManagedHarness::OpenCode2 => "session_v2",
+ _ => return native_session_exists(harness, home, cwd, session_dir, native_session_id),
+ };
+ let db = opencode_db(home, session_dir);
+ if !db.is_file() {
+ return Ok(false);
+ }
+ let connection = Connection::open_with_flags(
+ &db,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ let mut statement = connection.prepare(&format!(
+ "SELECT 1 FROM {table} WHERE id = ?1 AND directory = ?2"
+ ))?;
+ Ok(statement.exists(params![native_session_id, cwd.to_string_lossy()])?)
+}
+
/// Check whether one exact native session still exists in the harness's
/// read-only transcript store. `Ok(false)` means the resume target is
/// definitely absent; store access or schema failures remain errors so callers
@@ -250,7 +314,7 @@ pub fn native_session_exists(
return Ok(opencode2_updated(home, session_dir, native_session_id)?.is_some());
}
if harness == ManagedHarness::Crush {
- return Ok(crush_updated(cwd, session_dir, native_session_id)?.is_some());
+ return Ok(crush_updated(home, cwd, session_dir, native_session_id)?.is_some());
}
Ok(locate_session_file(harness, home, cwd, session_dir, native_session_id)?.is_some())
}
@@ -300,7 +364,7 @@ pub async fn wait_for_transcript_flush(
} else if harness == ManagedHarness::OpenCode2 {
opencode2_updated(home, session_dir, native_session_id)?.map(|value| value.to_string())
} else if harness == ManagedHarness::Crush {
- crush_updated(cwd, session_dir, native_session_id)?.map(|value| value.to_string())
+ crush_updated(home, cwd, session_dir, native_session_id)?.map(|value| value.to_string())
} else {
locate_session_file(harness, home, cwd, session_dir, native_session_id)?.and_then(
|path| {
@@ -1925,12 +1989,13 @@ fn export_opencode(
}
fn export_crush(
+ home: &Path,
cwd: &Path,
session_dir: Option<&Path>,
session: &str,
source_cursor: Option<&str>,
) -> Result<ExportedTranscript> {
- let db = crush_db(cwd, session_dir);
+ let db = crush_db(home, cwd, session_dir);
let connection = Connection::open_with_flags(
&db,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
@@ -2829,22 +2894,115 @@ fn list_opencode_sessions(
}
fn discover_crush(
+ home: &Path,
cwd: &Path,
session_dir: Option<&Path>,
started_at: SystemTime,
+ fresh: bool,
) -> Result<Option<String>> {
- Ok(list_crush_sessions(cwd, session_dir, 1)?
- .into_iter()
- .find(|candidate| candidate.updated_at + Duration::from_secs(2) >= started_at)
- .map(|candidate| candidate.native_session_id))
+ let db = crush_db(home, cwd, session_dir);
+ if !db.is_file() {
+ return Ok(None);
+ }
+ let connection = Connection::open_with_flags(
+ &db,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ // Title and sub-agent sessions name their session as parent. A fresh
+ // launch looks at what it created; `--continue` at what it resumed.
+ let order = if fresh { "created_at" } else { "updated_at" };
+ let mut statement = connection.prepare(&format!(
+ "SELECT id, {order} FROM sessions WHERE parent_session_id IS NULL \
+ ORDER BY {order} DESC LIMIT 64"
+ ))?;
+ let rows = statement.query_map([], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
+ })?;
+ let mut during_run = Vec::new();
+ for row in rows {
+ let (id, at) = row?;
+ let Some(at) = native_timestamp(at) else {
+ continue;
+ };
+ if at + Duration::from_secs(2) < started_at {
+ break;
+ }
+ if valid_native_session_id(&id) {
+ during_run.push(id);
+ }
+ }
+ // A data directory outside the project (a global `data_directory`) holds
+ // other projects' sessions too, and Crush keeps no directory per session.
+ // What it does keep is the absolute path of each file a session edited;
+ // only a session that edited a file here is known to be this project's.
+ // (`read_files` paths are relative to each session's own directory, so
+ // they place nothing.)
+ let project = crate::repository::worktree_root(cwd).unwrap_or_else(|| cwd.to_path_buf());
+ // Where the store really is: a `.crush` symlinked to a shared directory
+ // is shared.
+ let resolved = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));
+ let shared = db
+ .parent()
+ .is_some_and(|dir| !resolved(&cwd.join(dir)).starts_with(resolved(&project)));
+ let placed = if shared {
+ let mut placed = Vec::new();
+ for id in &during_run {
+ let edited = crush_edited_paths(&connection, id)?;
+ if edited.iter().any(|path| path_within(path, &project)) {
+ placed.push(id.clone());
+ }
+ }
+ Some(placed)
+ } else {
+ None
+ };
+ let sessions = during_run.len();
+ if sessions == 0 {
+ return Ok(None);
+ }
+ let placed_count = placed.as_ref().map(Vec::len);
+ let mut claimed = placed.unwrap_or(during_run);
+ if claimed.len() == 1 {
+ return Ok(claimed.pop());
+ }
+ Err(AmbiguousNativeSession {
+ harness: ManagedHarness::Crush,
+ sessions,
+ placed: placed_count,
+ }
+ .into())
+}
+
+/// The files a Crush session edited, as the absolute paths its edit tools
+/// record in `files`, including edits its sub-agent sessions made.
+fn crush_edited_paths(connection: &Connection, session: &str) -> Result<Vec<PathBuf>> {
+ let mut statement = connection.prepare(
+ "WITH RECURSIVE tree(id) AS ( \
+ SELECT ?1 UNION SELECT sessions.id FROM sessions \
+ JOIN tree ON sessions.parent_session_id = tree.id) \
+ SELECT path FROM files WHERE session_id IN (SELECT id FROM tree)",
+ )?;
+ let rows = statement.query_map([session], |row| row.get::<_, String>(0))?;
+ rows.map(|row| Ok(PathBuf::from(row?))).collect()
+}
+
+/// Whether absolute `path` lies under `root`, compared both as written and
+/// with symlinks resolved (Crush records the path it was given, which may go
+/// through a symlinked `/var` or checkout). A relative path cannot be placed.
+fn path_within(path: &Path, root: &Path) -> bool {
+ let resolved = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));
+ path.is_absolute()
+ && (clean_path(path).starts_with(clean_path(root))
+ || resolved(path).starts_with(resolved(root)))
}
fn list_crush_sessions(
+ home: &Path,
cwd: &Path,
session_dir: Option<&Path>,
limit: usize,
) -> Result<Vec<NativeSessionCandidate>> {
- let db = crush_db(cwd, session_dir);
+ let db = crush_db(home, cwd, session_dir);
if !db.is_file() {
return Ok(Vec::new());
}
@@ -2874,8 +3032,13 @@ fn list_crush_sessions(
Ok(sessions)
}
-fn crush_updated(cwd: &Path, session_dir: Option<&Path>, session: &str) -> Result<Option<i64>> {
- let db = crush_db(cwd, session_dir);
+fn crush_updated(
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ session: &str,
+) -> Result<Option<i64>> {
+ let db = crush_db(home, cwd, session_dir);
if !db.is_file() {
return Ok(None);
}
@@ -2894,8 +3057,11 @@ fn crush_updated(cwd: &Path, session_dir: Option<&Path>, session: &str) -> Resul
}
}
-fn crush_db(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {
- session_dir.unwrap_or(&cwd.join(".crush")).join("crush.db")
+fn crush_db(home: &Path, cwd: &Path, session_dir: Option<&Path>) -> PathBuf {
+ session_dir
+ .map(Path::to_path_buf)
+ .unwrap_or_else(|| crate::harness::crush_process_data_dir(cwd, home))
+ .join("crush.db")
}
fn native_timestamp(value: i64) -> Option<SystemTime> {
@@ -3745,6 +3911,271 @@ mod tests {
);
}
+ /// Crush has no hooks to link its session, and a store can be shared by
+ /// launches in several subdirectories. A fresh launch claims the one
+ /// top-level session created while it ran (title and sub-agent sessions
+ /// name a parent) and claims none when another launch created one too;
+ /// `--continue` claims the one session it touched, on the same terms.
+ #[tokio::test]
+ async fn crush_discovery_claims_only_the_session_the_run_created() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ fs::create_dir_all(cwd.join(".crush")).unwrap();
+ let connection = Connection::open(cwd.join(".crush").join("crush.db")).unwrap();
+ connection
+ .execute_batch(
+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \
+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL);",
+ )
+ .unwrap();
+ let started = 1_900_000_000_i64;
+ let started_at = UNIX_EPOCH + Duration::from_secs(started as u64);
+ let insert = |id: &str, parent: Option<&str>, created: i64, updated: i64| {
+ connection
+ .execute(
+ "INSERT INTO sessions VALUES (?1, ?2, ?3, ?4)",
+ params![id, parent, started + updated, started + created],
+ )
+ .unwrap();
+ };
+ let discover = |fresh: bool| discover_crush(temp.path(), &cwd, None, started_at, fresh);
+
+ let ambiguous = |fresh: bool| {
+ discover(fresh)
+ .unwrap_err()
+ .downcast::<AmbiguousNativeSession>()
+ .unwrap()
+ .sessions
+ };
+ insert("idle", None, -2_000, -1_000);
+ insert("continued", None, -1_000, 30);
+ insert("continued-task", Some("continued"), 3, 40);
+ assert_eq!(discover(true).unwrap(), None);
+ assert_eq!(discover(false).unwrap().as_deref(), Some("continued"));
+
+ insert("mine", None, 5, 20);
+ insert("mine-title", Some("mine"), 6, 25);
+ assert_eq!(discover(true).unwrap().as_deref(), Some("mine"));
+ assert_eq!(ambiguous(false), 2);
+
+ insert("theirs", None, 8, 10);
+ assert_eq!(ambiguous(true), 2);
+ }
+
+ /// A data directory outside the project can hold another project's
+ /// sessions, and Crush records no directory per session. Only a session
+ /// that edited a file here (an absolute path in `files`) is claimed, and
+ /// only when it is the one; a read (`read_files` keeps paths relative to
+ /// each session's own directory) or a file elsewhere places nothing. A
+ /// store inside the project keeps the plain one-new-session rule.
+ #[tokio::test]
+ async fn crush_discovery_in_a_shared_store_claims_only_an_edit_here() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = fs::canonicalize(temp.path()).unwrap();
+ let repo = root.join("repo");
+ fs::create_dir_all(repo.join("src")).unwrap();
+ let status = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&repo)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ let started = 1_900_000_000_i64;
+ let started_at = UNIX_EPOCH + Duration::from_secs(started as u64);
+ let store = |name: &str, sessions: &[(&str, &[&str])]| {
+ let dir = if name == ".crush" {
+ repo.join(name)
+ } else {
+ root.join(name)
+ };
+ fs::create_dir_all(&dir).unwrap();
+ let connection = Connection::open(dir.join("crush.db")).unwrap();
+ connection
+ .execute_batch(
+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \
+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL); \
+ CREATE TABLE files(id TEXT PRIMARY KEY, session_id TEXT NOT NULL, \
+ path TEXT NOT NULL); \
+ CREATE TABLE read_files(session_id TEXT NOT NULL, path TEXT NOT NULL, \
+ read_at INTEGER NOT NULL);",
+ )
+ .unwrap();
+ for (nth, (id, paths)) in sessions.iter().enumerate() {
+ let at = started + 5 + nth as i64;
+ // `parent/child` is a sub-agent session of `parent`.
+ let (parent, id) = match id.split_once('/') {
+ Some((parent, child)) => (Some(parent), child),
+ None => (None, *id),
+ };
+ connection
+ .execute(
+ "INSERT INTO sessions VALUES (?1, ?2, ?3, ?3)",
+ params![id, parent, at],
+ )
+ .unwrap();
+ for path in *paths {
+ // `read:` marks a file the session only read.
+ match path.strip_prefix("read:") {
+ Some(read) => connection.execute(
+ "INSERT INTO read_files VALUES (?1, ?2, 0)",
+ params![id, read],
+ ),
+ None => connection.execute(
+ "INSERT INTO files VALUES (?1, ?2, ?3)",
+ params![format!("{id}-{path}"), id, path],
+ ),
+ }
+ .unwrap();
+ }
+ }
+ dir
+ };
+ let discover = |dir: &Path| discover_crush(&root, &repo, Some(dir), started_at, true);
+ let placed = |dir: &Path| {
+ discover(dir)
+ .unwrap_err()
+ .downcast::<AmbiguousNativeSession>()
+ .unwrap()
+ .placed
+ };
+ let here = repo.join("src").join("main.rs").display().to_string();
+ let elsewhere = "/elsewhere/project-b/main.go";
+
+ let dir = store("shared-foreign", &[("theirs", &[elsewhere])]);
+ assert_eq!(placed(&dir), Some(0));
+
+ let dir = store(
+ "shared-mine",
+ &[
+ ("theirs", &[elsewhere]),
+ ("chat", &[]),
+ ("mine", &[elsewhere, &here]),
+ ],
+ );
+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("mine"));
+
+ // Reads place nothing: Crush keeps them relative to each session's own
+ // directory (absolute only when that fails), and neither does an edit
+ // whose path cannot be placed.
+ let read_here_absolute = format!("read:{here}");
+ let dir = store(
+ "shared-read",
+ &[
+ ("theirs", &["read:src/main.go", &read_here_absolute]),
+ ("relative", &["src/main.go"]),
+ ("chat", &[]),
+ ],
+ );
+ assert_eq!(placed(&dir), Some(0));
+
+ let dir = store("shared-both", &[("one", &[&here]), ("two", &[&here])]);
+ assert_eq!(placed(&dir), Some(2));
+
+ // An edit a sub-agent made places the session that ran it.
+ let dir = store(
+ "shared-task",
+ &[
+ ("theirs", &[elsewhere]),
+ ("mine", &[]),
+ ("mine/task", &[&here]),
+ ],
+ );
+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("mine"));
+
+ let dir = store(".crush", &[("dotfiles", &[elsewhere])]);
+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("dotfiles"));
+
+ // A project `.crush` that links to a shared store is shared.
+ #[cfg(unix)]
+ {
+ let dir = store("shared-linked", &[("theirs", &[elsewhere])]);
+ let linked = repo.join("linked-crush");
+ std::os::unix::fs::symlink(&dir, &linked).unwrap();
+ assert_eq!(placed(&linked), Some(0));
+ }
+ }
+
+ /// Session discovery with no store named by a launch plan finds Crush's
+ /// database where Crush keeps it: the closest `.crush` up to the worktree
+ /// root, not only `<cwd>/.crush`.
+ #[tokio::test]
+ async fn crush_discovery_finds_the_store_above_the_cwd() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = fs::canonicalize(temp.path()).unwrap();
+ let repo = root.join("repo");
+ let cwd = repo.join("sub");
+ fs::create_dir_all(repo.join(".crush")).unwrap();
+ fs::create_dir_all(&cwd).unwrap();
+ let status = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&repo)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ let connection = Connection::open(repo.join(".crush").join("crush.db")).unwrap();
+ connection
+ .execute_batch(
+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, updated_at INTEGER NOT NULL);\n\
+ INSERT INTO sessions VALUES ('above', 1800000000);",
+ )
+ .unwrap();
+
+ let candidates = list_native_sessions(ManagedHarness::Crush, &root, &cwd, None, 8)
+ .await
+ .unwrap();
+ assert_eq!(
+ candidates
+ .iter()
+ .map(|candidate| candidate.native_session_id.as_str())
+ .collect::<Vec<_>>(),
+ ["above"]
+ );
+ }
+
+ /// OpenCode keeps every checkout's sessions in one database, so a session
+ /// is this checkout's only when its recorded directory matches; other
+ /// harnesses answer as `native_session_exists` does.
+ #[test]
+ fn native_session_in_checkout_checks_the_opencode_directory() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ let store = temp.path().join("opencode");
+ fs::create_dir_all(&store).unwrap();
+ let connection = Connection::open(store.join("opencode.db")).unwrap();
+ connection
+ .execute_batch(
+ "CREATE TABLE session(id TEXT PRIMARY KEY, directory TEXT NOT NULL, \
+ time_updated INTEGER NOT NULL); \
+ CREATE TABLE session_v2(id TEXT PRIMARY KEY, directory TEXT NOT NULL, \
+ time_updated INTEGER NOT NULL);",
+ )
+ .unwrap();
+ for table in ["session", "session_v2"] {
+ for (id, dir) in [("here", &cwd), ("elsewhere", &other)] {
+ connection
+ .execute(
+ &format!("INSERT INTO {table} VALUES (?1, ?2, 1)"),
+ params![id, dir.to_string_lossy()],
+ )
+ .unwrap();
+ }
+ }
+ for harness in [ManagedHarness::OpenCode, ManagedHarness::OpenCode2] {
+ let in_checkout = |id: &str| {
+ native_session_in_checkout(harness, temp.path(), &cwd, Some(&store), id).unwrap()
+ };
+ assert!(in_checkout("here"), "{harness:?}");
+ assert!(!in_checkout("elsewhere"), "{harness:?}");
+ assert!(!in_checkout("missing"), "{harness:?}");
+ assert!(
+ native_session_exists(harness, temp.path(), &cwd, Some(&store), "elsewhere")
+ .unwrap(),
+ "{harness:?}: the store holds it"
+ );
+ }
+ }
+
#[tokio::test]
async fn crush_candidate_discovery_and_incremental_export_are_read_only() {
let temp = tempfile::tempdir().unwrap();
@@ -3797,7 +4228,7 @@ mod tests {
.unwrap()
);
- let first = export_crush(&cwd, None, "newer", None).unwrap();
+ let first = export_crush(temp.path(), &cwd, None, "newer", None).unwrap();
assert_eq!(first.events.len(), 1);
assert_eq!(first.events[0].content, "visible");
assert!(first.losses.iter().any(|loss| loss.contains("reasoning")));
@@ -3808,7 +4239,14 @@ mod tests {
[json!([{"type":"tool_result","data":{"name":"bash","content":"ok","is_error":false}}]).to_string()],
)
.unwrap();
- let second = export_crush(&cwd, None, "newer", first.source_cursor.as_deref()).unwrap();
+ let second = export_crush(
+ temp.path(),
+ &cwd,
+ None,
+ "newer",
+ first.source_cursor.as_deref(),
+ )
+ .unwrap();
assert_eq!(second.events.len(), 1);
assert_eq!(second.events[0].kind, WorkstreamEventKind::ToolResult);
assert_eq!(second.events[0].content, "ok");
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 59dcb110..00987efb 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -369,7 +369,7 @@ is labelled completed evidence and must never be replayed as a pending call.
| OpenCode | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only |
| OpenCode 2 beta | native default creation | `--session <id>` | same `opencode.db` as v1 (the beta channel keeps v1's filename; the beta adds `session_v2`/`session_message` tables beside v1's); launched via the `opencode2` binary |
| Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |
-| Crush | native default creation | `--session <id>` | `<project>/.crush/crush.db` opened read-only |
+| Crush | native default creation | `--session <id>` | `<data dir>/crush.db` opened read-only: `options.data_directory` from Crush's JSON configs, else the closest `.crush` up to the git worktree root, else `<cwd>/.crush` |
| Kimi Code | native default creation | `--session <id>` | `$KIMI_CODE_HOME/sessions/*/*/agents/main/wire.jsonl` |
| Command Code | native default creation | `--session <uuid>` | `~/.commandcode/projects/*/<uuid>.jsonl` |
| Kiro CLI v2 | native default creation | `--resume-id <uuid>` | `$KIRO_HOME/sessions/cli/<uuid>.jsonl` (+ sibling `<uuid>.json` metadata) |
@@ -395,8 +395,32 @@ An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,
Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.
ai-memory links the selected native session and resets an unrelated adapter
cursor rather than assuming it belongs to the old session.
+
+When a fresh launch cannot name its session up front, the session a hook in
+the child links under the run's `AI_MEMORY_RUN_ID` is the one imported when
+the native store holds it for this checkout (a process the child starts
+inherits that id too), so a concurrent launch in the same checkout cannot hand
+it a different transcript. Only without such a link does ai-memory look for
+the session after exit. A
+hook that links the very session the run was prepared with, as when a native
+picker resumes the workstream's current session without naming it, is not yet
+told apart from no link, so the look after exit still decides there.
+Crush has no hooks: a fresh Crush launch claims the one top-level session
+created while it ran (its title and sub-agent sessions do not count), and
+imports nothing, with a warning, when another launch on the same store created
+one too; resume that session with `--session <id>` to link it. `--continue`
+claims the one session it touched on the same terms. When the data directory
+lies outside the project, as a global `data_directory` does, other projects'
+sessions share it and Crush records no directory per session, so a run claims
+only a session that edited a file in this project (its sub-agents' edits
+count), and only when it is the one; otherwise it imports nothing, with the
+same warning. The store's real location decides, so a `.crush` symlinked to a
+shared directory is shared. Another project's session that edited a file here
+still counts as this project's.
Pi and OMP `--session-dir` values and Crush `--data-dir` values are passed
-through unchanged and used as the read-only import root. Native store
+through unchanged and used as the read-only import root. Without `--data-dir`,
+ai-memory finds Crush's data directory as Crush does, except that it does not
+run a `crushrc` to read one set only there; pass `--data-dir` in that case. Native store
environment overrides are also honored:
`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_DATA_HOME`,
`PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`, `KIMI_CODE_HOME`,
@@ -572,9 +596,17 @@ Antigravity CLI v1.1.7. Antigravity is not part of the no-argument
auto-detection set; name it explicitly.
Crush needs no ai-memory hook installation for managed mode. The launcher reads
-its one-time context from the server, copies the existing global Crush JSON into
-a private temporary directory, appends an ephemeral context path, and points the
-child at that directory with `CRUSH_GLOBAL_CONFIG`. Delivery is acknowledged
+its one-time context from the server, copies the global Crush JSON the launch
+would read (`$CRUSH_GLOBAL_CONFIG/crush.json`, else
+`$XDG_CONFIG_HOME/crush/crush.json`, else `~/.config/crush/crush.json`, with
+`--env` entries first and a blank value counting as unset) into a private
+temporary directory, appends an ephemeral context path, and points the child at
+that directory with `CRUSH_GLOBAL_CONFIG`. When that JSON lists no
+`global_context_paths`, the launcher first adds the `CRUSH.md` and `AGENTS.md`
+Crush would have loaded by default, so the packet does not replace them. A
+global `crushrc` next to that JSON is carried over by a generated `crushrc` in
+the temporary directory that sources it from its own directory, where Crush
+runs it. Delivery is acknowledged
only after the child starts, so a spawn failure cannot lose the packet. The
original config is not modified. ai-memory opens the project database read-only;
the launched Crush process continues its normal native session writes.
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index b838ec4e..f5fcd32f 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -45,6 +45,7 @@ boundary not yet built.
| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
+| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a session a hook linked under the run id (reported id differs from the prepared one) only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `run.rs` `hook_linked_session_wins_over_a_newer_concurrent_session` (newer concurrent session, another checkout's link refused, no fallback to it), `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here`, `native_session_in_checkout_checks_the_opencode_directory` | PARTIAL: a hook link that repeats the prepared session is not told apart from no link here (server-side stamp in #880), and a run whose child links nothing still depends on discovery |
| — | Per-project authorization (#708) | proposal only — `docs/design-per-project-authz.md` (`authorize_project` choke point + unscoped-read/raw-id bypass classes) | none yet — the design's "Verification plan" tests (authz matrix, unscoped-read-leak, raw-id-authz, ship-inert) land WITH the code | FUTURE |
## Keeping this current (the standing protocol)