Skip to content

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

Rust

Merge branch 'fix/autowire-run-env' into fix/crush-launch-context

Éverton Toffanetto041899a1c064
diff --cc CHANGELOG.md
index d08cddec,3493c199..dde64fd5
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -177,30 -204,6 +208,27 @@@ and this project adheres to [Semantic V
- 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)
++- Two fresh managed Crush launches on one store could import each other's
++ transcript: Crush has no hooks to link its session, and after exit `ai-memory
++ run` took the newest session there. A fresh launch now claims only the one
++ top-level session created while it ran 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 --cc crates/ai-memory-cli/src/commands/run.rs
index c2053155,c3d78ca5..df914a7d
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@@ -2729,168 -2707,6 +2808,77 @@@ 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()),
++ native_session_linked: false,
+ 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();
diff --cc docs/managed-workstreams.md
index 00987efb,32e64bc8..d593e487
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@@ -395,32 -400,8 +400,23 @@@ An explicit native selector such as Cla
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
++Crush has no hooks to link its session: 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`,
diff --cc docs/security-boundaries.md
index f5fcd32f,b1af7bfc..5235eca6
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -45,8 -46,8 +46,8 @@@ 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 |
-| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), and never falls back to a link it set aside | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout |
++| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session 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 | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `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` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
+ | 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (inert V68 schema: `project_grants` + `projects.access_mode`, default `open`); consulted by `scope.rs` `ScopeResolver` read+write resolution (opt-in `with_project_authz`, reader-pool for reads, writer-actor for writes) and by `WriterHandle::authorize_project` as defense in depth | `tests/suite/project_authz.rs` — `authz_matrix_reader_and_writer_paths`, `ship_inert_open_admits_all_and_restricted_admits_root_and_creator`, `gate_is_skipped_when_operators_are_not_distinguished`, `scope_resolver_gates_restricted_projects`, `migration_applies_defaults_open_and_reopen_is_a_noop`, `authorize_decision_matrix` (each proven to fail with the gate neutralized) | PARTIAL — slice 2: choke point + inert schema exist and are always-allow (no project is `restricted` yet). `restricted` is **not safe end-to-end** until slice 3 closes the two bypass classes (unscoped/global reads must filter by readable projects **before** `LIMIT`; raw-id entry points — session/run/page id, `page_evidence_counts` — must resolve→`authorize_project`) and adds the root-only management surface that sets `restricted` and issues grants |
## Keeping this current (the standing protocol)