Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): let a linked worktree adopt its main checkout's 2.x project (#1880)
Vinícius DS Andrade031044f34102
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12202b0f..9d05566b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- A 2.x project is now adopted whichever checkout of its repository captures+ first. When a linked worktree (`git worktree add`) captured before the main+ checkout, the repository identity created a new project, every checkout then+ followed the identity there, and the 2.x project with its pages and sessions+ was orphaned. A worktree now claims the identity-less project named after its+ main checkout, as the main checkout would. The server reads the worktree's+ git metadata to find it; `docs/upgrading-to-3.0.md` covers a server that+ cannot read the checkout (#1880).- Project search links now use the project's current stored name afterresolving a canonical or legacy key. Results, breadcrumbs, and the scopeselector stay on that project without renaming it (#1875).diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rsindex 46337c1c..b08712da 100644--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@ -899,6 +899,58 @@ fn discover_main_repo_root_fallback(start: &Path) -> Result<PathBuf, BootstrapErErr(BootstrapError::NotARepo(start.to_path_buf()))}+/// The main checkout of the linked worktree that contains `start`, or `None`+/// when `start` is anywhere else.+///+/// Only a worktree that `git worktree add` linked to a main checkout answers:+/// a main checkout, a submodule, a worktree of a bare repository, a checkout+/// with a separate git directory and a directory outside any repository all+/// return `None`. [`discover_main_repo_root`] takes the parent of any shared+/// git directory instead, which for a submodule is its superproject's+/// `.git/modules`; a caller that acts on the answer needs the shared+/// directory to be literally `<checkout>/.git`.+#[must_use]+pub fn linked_worktree_main_root(start: &Path) -> Option<PathBuf> {+ let common_dir = match git2::Repository::discover(start) {+ Ok(repo) if repo.is_worktree() => repo.commondir().to_path_buf(),+ Ok(_) => return None,+ Err(_) => linked_worktree_common_dir_fallback(start)?,+ };+ if common_dir.file_name()? != ".git" {+ return None;+ }+ common_dir.parent().map(Path::to_path_buf)+}++#[cfg(windows)]+fn linked_worktree_common_dir_fallback(start: &Path) -> Option<PathBuf> {+ let output = git_command()+ .arg("-C")+ .arg(start)+ .args([+ "rev-parse",+ "--path-format=absolute",+ "--git-dir",+ "--git-common-dir",+ ])+ .output()+ .ok()?;+ if !output.status.success() {+ return None;+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ let mut lines = stdout.lines().map(str::trim);+ let (git_dir, common_dir) = (lines.next()?, lines.next()?);+ // A linked worktree keeps its own git directory beside the shared one;+ // a main checkout or a submodule has a single directory.+ (git_dir != common_dir).then(|| PathBuf::from(common_dir))+}++#[cfg(not(windows))]+fn linked_worktree_common_dir_fallback(_start: &Path) -> Option<PathBuf> {+ None+}+#[cfg(any(windows, test))]fn main_root_from_common_dir(common_dir: &Path,@@ -2368,6 +2420,91 @@ mod tests {);}+ /// Only a worktree `git worktree add` linked to a main checkout names that+ /// checkout. The main checkout itself, a submodule (whose shared directory+ /// sits under the superproject's `.git/modules`), a worktree of a bare+ /// repository and a plain directory all answer `None`.+ #[test]+ fn linked_worktree_main_root_answers_only_for_a_linked_worktree() {+ let tmp = TempDir::new().unwrap();+ // A fixed identity and no signing, so the contributor's global git+ // config cannot decide whether the fixture commits succeed.+ let git = |dir: &Path, args: &[&str]| {+ let status = std::process::Command::new("git")+ .args(["-c", "user.name=test", "-c", "[email protected]"])+ .args(["-c", "protocol.file.allow=always"])+ .arg("-C")+ .arg(dir)+ .args(args)+ .status()+ .unwrap();+ assert!(status.success(), "git {args:?} in {dir:?} failed");+ };+ let path = |p: &Path| p.to_str().unwrap().to_owned();+ let initial = [+ "commit",+ "-q",+ "--no-gpg-sign",+ "--allow-empty",+ "-m",+ "init",+ ];++ let main = tmp.path().join("api");+ fs::create_dir_all(&main).unwrap();+ git(&main, &["init", "-q", "-b", "main"]);+ git(&main, &initial);+ let worktree = tmp.path().join("api-feature");+ git(+ &main,+ &["worktree", "add", "-q", "-b", "feature", &path(&worktree)],+ );+ fs::create_dir_all(worktree.join("src")).unwrap();+ let expected = Some(main.canonicalize().unwrap());+ for start in [worktree.clone(), worktree.join("src")] {+ assert_eq!(+ linked_worktree_main_root(&start).and_then(|root| root.canonicalize().ok()),+ expected,+ "{start:?}"+ );+ }+ assert_eq!(linked_worktree_main_root(&main), None);++ let library = tmp.path().join("library");+ fs::create_dir_all(&library).unwrap();+ git(&library, &["init", "-q", "-b", "main"]);+ git(&library, &initial);+ git(+ &main,+ &["submodule", "add", "-q", &path(&library), "vendor/library"],+ );+ assert_eq!(+ linked_worktree_main_root(&main.join("vendor").join("library")),+ None,+ "a submodule is not a linked worktree"+ );++ let bare = tmp.path().join("api.git");+ git(+ tmp.path(),+ &["clone", "-q", "--bare", &path(&main), &path(&bare)],+ );+ let bare_worktree = tmp.path().join("api-bare-feature");+ git(+ &bare,+ &["worktree", "add", "-q", &path(&bare_worktree), "main"],+ );+ assert_eq!(+ linked_worktree_main_root(&bare_worktree),+ None,+ "a bare repository has no main checkout"+ );++ let plain = tmp.path().join("plain");+ fs::create_dir_all(&plain).unwrap();+ assert_eq!(linked_worktree_main_root(&plain), None);+ }+// ----------------------------------------------------------------// Durable per-chunk progress + --resume (#621)// ----------------------------------------------------------------diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rsindex ade5a909..01a3f70f 100644--- a/crates/ai-memory-consolidate/src/lib.rs+++ b/crates/ai-memory-consolidate/src/lib.rs@@ -60,7 +60,8 @@ pub use bootstrap::{Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome, BootstrapSource,DEFAULT_CHUNK_INPUT_TOKENS, ProjectNameStrategy, SourceCounts, SourceKind, collect_sources,derive_project_name, discover_main_repo_root, discover_repo_root, effective_chunk_budget,- path_is_git_ignored, plan_bootstrap_chunks, prune_sources_to_budget, read_identity_remotes,+ linked_worktree_main_root, path_is_git_ignored, plan_bootstrap_chunks, prune_sources_to_budget,+ read_identity_remotes,};pub use cold_cluster::{adaptive_eps, cosine_distance, dbscan};pub use compaction::build_compacted_markdown;diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 6c2e49f7..f8091547 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -3758,6 +3758,54 @@ fn has_publishable_scope_hint(cwd: Option<&str>, project_override: Option<&str>)cwd.is_some_and(|value| !value.is_empty()) || project_override.is_some()}+/// The identity-less project a linked worktree's main checkout would claim,+/// offered as an identity capture's candidate from that worktree (#1880).+///+/// A 2.x project carries no identity and is named after the folder it was+/// captured from, so only a capture whose cwd-derived name matches that+/// folder claims it. A linked worktree sits in another folder: when it+/// captured first, its identity created a new project, every checkout then+/// followed the identity there, and the 2.x project was orphaned. Offering+/// the main checkout's project makes the first capture's checkout irrelevant.+/// A project that already holds an identity is not offered, and the writer+/// still decides whether this caller may claim the one that is.+async fn main_checkout_candidate(+ state: &HookState,+ workspace_id: WorkspaceId,+ cwd: &str,+) -> anyhow::Result<Option<ProjectId>> {+ let owned = cwd.to_owned();+ let main_name = state+ .cwd_probes+ .run(cwd, move || {+ ai_memory_consolidate::linked_worktree_main_root(std::path::Path::new(&owned))+ .and_then(|root| root.file_name()?.to_str().map(str::to_owned))+ })+ .await?;+ // A reserved scope is never captured into by name, and a main checkout+ // named like one must not hand it to a worktree either.+ let Some(main_name) =+ main_name.filter(|name| !ai_memory_core::profile::is_reserved_scope_project(name))+ else {+ return Ok(None);+ };+ let Some(project) = state+ .reader+ .find_project(workspace_id, main_name)+ .await+ .map_err(|e| anyhow::anyhow!("find_project: {e}"))?+ else {+ return Ok(None);+ };+ let unclaimed = state+ .reader+ .scope_row_by_ids(workspace_id, project)+ .await+ .map_err(|e| anyhow::anyhow!("scope_row_by_ids: {e}"))?+ .is_some_and(|row| row.identity.is_none());+ Ok(unclaimed.then_some(project))+}+/// Resolve the `(workspace_id, project_id)` pair for a hook event without/// publishing it as active. Callers decide separately whether the event is a/// foreground interaction allowed to advance fallback routing.@@ -4091,7 +4139,18 @@ async fn resolve_project_ids_inner(// name (or the cwd-prefix parent) is only the candidate for a project// that has not been claimed yet. One writer transaction, so two// captures racing on a new repository cannot both create it.- let candidate = parent.map(|(parent_id, _)| parent_id);+ let candidate = match (parent, cwd_raw) {+ (Some((parent_id, _)), _) => Some(parent_id),+ // A marker name or the repo-root strategy already names the main+ // checkout's project; the default basename names the worktree.+ (None, Some(cwd))+ if project_override.is_none()+ && matches!(project_strategy, ProjectStrategy::Basename) =>+ {+ main_checkout_candidate(state, ws, cwd).await?+ }+ (None, _) => None,+ };let resolved = if promote_alias {state.writer@@ -7615,6 +7674,176 @@ pub(crate) mod tests {assert_eq!(name(explicit).await.as_deref(), Some("site"));}+ /// A main checkout with one commit at `root/<main>` and a worktree linked+ /// to it at `root/<worktree>`, on a new `feature` branch.+ fn main_with_linked_worktree(+ root: &std::path::Path,+ main: &str,+ worktree: &str,+ ) -> (std::path::PathBuf, std::path::PathBuf) {+ let (main, worktree) = (root.join(main), root.join(worktree));+ #[cfg(windows)]+ {+ init_repo_with_commit(&main);+ let mut add = std::process::Command::new("git");+ add.arg("-C")+ .arg(&main)+ .args(["worktree", "add", "-q", "-b", "feature"])+ .arg(&worktree);+ assert_command_success(add);+ }+ #[cfg(not(windows))]+ {+ let repo = init_repo_with_commit(&main);+ let head = repo.head().unwrap().peel_to_commit().unwrap();+ let branch = repo.branch("feature", &head, false).unwrap();+ repo.worktree(+ "feature",+ &worktree,+ Some(git2::WorktreeAddOptions::new().reference(Some(&branch.into_reference()))),+ )+ .unwrap();+ }+ (main, worktree)+ }++ /// #1880: a 2.x project has no identity and the name of the folder it was+ /// captured from. A linked worktree in another folder that captures first+ /// adopts it, as its main checkout would, instead of creating a twin that+ /// every checkout of the repository then follows.+ #[tokio::test]+ async fn a_linked_worktree_adopts_the_v2_project_its_main_checkout_would() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let (main, worktree) = main_with_linked_worktree(tmp.path(), "api", "api-feature");+ let v2 = state+ .writer+ .get_or_create_project(+ state.workspace_id,+ "api",+ Some(main.to_string_lossy().into_owned()),+ )+ .await+ .unwrap();++ let adopted = capture_styled(&state, &worktree, "github.com/acme/api", Some("path")).await;+ assert_eq!(adopted, v2, "the worktree adopts the 2.x project in place");+ assert_eq!(+ state+ .reader+ .project_name_by_id(state.workspace_id, v2)+ .await+ .unwrap()+ .as_deref(),+ Some("acme-api")+ );+ let from_main = capture_styled(&state, &main, "github.com/acme/api", Some("path")).await;+ assert_eq!(from_main, v2, "the main checkout lands in the same project");+ }++ /// The main checkout's name held by another repository's identity is not+ /// the worktree's to take: the worktree resolves to a project of its own+ /// and the holder keeps its identity.+ #[tokio::test]+ async fn a_linked_worktree_never_takes_a_project_holding_another_identity() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let (_main, worktree) = main_with_linked_worktree(tmp.path(), "api", "api-feature");+ let other = tmp.path().join("other").join("api");+ std::fs::create_dir_all(&other).unwrap();+ let holder = capture_styled(&state, &other, "github.com/other/api", None).await;+ let identity = |project| {+ let reader = state.reader.clone();+ let ws = state.workspace_id;+ async move {+ reader+ .scope_row_by_ids(ws, project)+ .await+ .unwrap()+ .and_then(|row| row.identity)+ }+ };+ assert_eq!(+ identity(holder).await.as_deref(),+ Some("github.com/other/api")+ );++ let wt = capture_styled(&state, &worktree, "github.com/acme/api", Some("path")).await;+ assert_ne!(wt, holder);+ assert_eq!(+ identity(holder).await.as_deref(),+ Some("github.com/other/api")+ );+ assert_eq!(identity(wt).await.as_deref(), Some("github.com/acme/api"));+ }++ /// Adoption stays inside the capture's workspace: a 2.x project of the+ /// same name in another workspace is left alone.+ #[tokio::test]+ async fn a_linked_worktree_never_adopts_another_workspaces_project() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let (_main, worktree) = main_with_linked_worktree(tmp.path(), "api", "api-feature");+ let elsewhere = state+ .writer+ .get_or_create_workspace("elsewhere")+ .await+ .unwrap();+ let foreign = state+ .writer+ .get_or_create_project(elsewhere, "api", None)+ .await+ .unwrap();++ let wt = capture_styled(&state, &worktree, "github.com/acme/api", Some("path")).await;+ assert_ne!(wt, foreign);+ let row = state+ .reader+ .scope_row_by_ids(elsewhere, foreign)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(row.project_name, "api");+ assert!(+ row.identity.is_none(),+ "the other workspace's project is untouched"+ );+ }++ /// Capture never lands in a reserved scope by name, so a main checkout+ /// that happens to be named like one must not hand it to its worktree:+ /// the global preferences scope keeps its name and stays unclaimed.+ #[tokio::test]+ async fn a_linked_worktree_never_adopts_a_reserved_scope() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let (_main, worktree) = main_with_linked_worktree(+ tmp.path(),+ ai_memory_core::GLOBAL_SCOPE_PROJECT,+ "global-feature",+ );+ let global = state+ .writer+ .get_or_create_project(+ state.workspace_id,+ ai_memory_core::GLOBAL_SCOPE_PROJECT,+ None,+ )+ .await+ .unwrap();++ let wt = capture_styled(&state, &worktree, "github.com/acme/api", Some("path")).await;+ assert_ne!(wt, global);+ let row = state+ .reader+ .scope_row_by_ids(state.workspace_id, global)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(row.project_name, ai_memory_core::GLOBAL_SCOPE_PROJECT);+ assert!(row.identity.is_none(), "the reserved scope stays unclaimed");+ }+/// #708's collision, end to end: two unrelated repositories both checked/// out as `api/` used to land in one project. With the client's identity/// they land in two, and the same repository under a different folder namediff --git a/docs/marker-file.md b/docs/marker-file.mdindex 5b66b0fb..411c5461 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -1050,7 +1050,10 @@ undeclared checkout with a remote, or a checkout with an explicitare one project.- An existing project with that name and no identity yet is **claimed inplace** by the first capture that may write to it, so upgrading moves no- memory.+ memory. A linked worktree (`git worktree add`) claims the project named+ after its main checkout's folder, so it does not matter which checkout+ captures first. The server finds the main checkout from the worktree's git+ metadata, so this needs a server that can read the checkout.- If the name already belongs to a different identity, the new repositorygets its own project, named from its owner (`github.com/orgb/api` →`orgb-api`, then `orgb-api-2`, …).diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 6e86a21a..35670de0 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -136,7 +136,7 @@ the legitimate restricted-project control and the failed-query cases.| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch`; importer agentmemory routes `vault::plan`, `export::plan`, `export::replay_session`, `agentmemory::validate_id` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`, agentmemory `page_bodies_are_redacted_before_planning`, `text_is_redacted_before_the_plan_exists` (page bodies and replayed observations), `ids_that_look_like_credentials_or_carry_controls_are_refused`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative || 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional || 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control), `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused), `codex_compressed_rollout_still_exists_only_for_its_own_checkout` (a Codex rollout compressed to `.jsonl.zst` is located through the same header and checkout match: another checkout's compressed session is refused, and a copy whose header does not decode is skipped; exact-checkout control); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |-| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/workstream.rs` `resolve_run_scope` sends a managed run through the same transaction (identity holder, else the `$HOME`-guarded cwd-prefix candidate, inside the requested workspace only) only when the wire identity derives the requested name, then authorizes Write (#1182); `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; hooks `workstream.rs` `managed_run_by_remote_identity_refuses_a_viewer_without_write`, `managed_run_identity_never_claims_a_restricted_legacy_project`, `managed_run_identity_never_redirects_another_project_name`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |+| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/router.rs` `main_checkout_candidate` offers a linked worktree's main-checkout project as the claim candidate only when `linked_worktree_main_root` finds a `git worktree add` link (never a submodule, a bare repository's worktree or a separate git dir), the main checkout's name is not a reserved scope (`_global`, `_profile`, `_profile.*`), and that project, looked up in the resolved workspace, holds no identity; the transaction above still decides the claim (#1880); `ai-memory-hooks/src/workstream.rs` `resolve_run_scope` sends a managed run through the same transaction (identity holder, else the `$HOME`-guarded cwd-prefix candidate, inside the requested workspace only) only when the wire identity derives the requested name, then authorizes Write (#1182); `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; hooks `workstream.rs` `managed_run_by_remote_identity_refuses_a_viewer_without_write`, `managed_run_identity_never_claims_a_restricted_legacy_project`, `managed_run_identity_never_redirects_another_project_name`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored), `a_linked_worktree_never_takes_a_project_holding_another_identity`, `a_linked_worktree_never_adopts_another_workspaces_project` and `a_linked_worktree_never_adopts_a_reserved_scope` (control: `a_linked_worktree_adopts_the_v2_project_its_main_checkout_would`); consolidate `linked_worktree_main_root_answers_only_for_a_linked_worktree` (a main checkout, a submodule, a bare repository's worktree and a plain directory are refused); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14bb | Local marker aliases cannot cross repository or workspace boundaries (#1033) | `ai-memory-core/src/repository_identity.rs` owns the bounded `MarkerAliases` type and exact one-line/root-level portable grammar; native/POSIX/PowerShell/generated TypeScript clients forward one normalized JSON-array query value only with marker provenance and a hostful git-remote identity; `ai-memory-store/src/project_coordinates.rs` probes exact names only inside the selected workspace, deduplicates by UUID, and requires the selected row's full stored git-remote identity; `ops.rs` authorizes in the writer transaction and reuses Phase 1 `promotion_target`, additionally requiring marker `project` to equal the canonical path-style name derived from that remote; handoff uses the read-only path and capture uses the write-authorized path; `router.rs` includes aliases, provenance, and read/write mode in its cache key | Core/CLI shared `marker_aliases` fixture parity covers duplicate keys, table placement, multiline arrays, trailing junk/comma, escapes, max length and duplicate-heavy over-count; store `marker_aliases_require_same_remote_identity_and_preserve_uuid`, `marker_aliases_cannot_promote_to_an_arbitrary_marker_project`, `hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed`; hooks `hook_and_handoff_queries_validate_aliases_identically`, `malformed_aliases_are_rejected_before_subagent_scope_resolution`, `empty_aliases_preserve_marker_project_precedence`, `capture_promotes_an_alias_but_handoff_only_reads_it`, `project_cache_separates_alias_sets`; shell `marker aliases keep canonical project and forward remote identity`; Windows PowerShell parity and capture-only marker transparency run in Windows CI; OpenClaw `openclaw_runtime_preserves_marker_and_home_identity_precedence` proves no-marker remote routing sends explicit `path`, ordinary project markers keep name precedence and omit identity, while alias markers and home identity routes forward it | STRONG: hostile arbitrary-name, different-identity and ambiguous aliases refuse or resolve without rename with a legitimate canonical same-identity control; another workspace is never searched; no alias table or persistent fallback exists || 14bb2 | Operator-home route selectors cannot silently cross repository or path boundaries (#1033) | `ai-memory-cli/src/marker.rs` returns a typed invalid result for malformed/oversized maps; command scope resolution propagates it unless both CLI scope fields are explicit, while native hooks drop before spool/network. The native, POSIX, PowerShell, generated TypeScript and OpenClaw parsers enforce the shared 64-route/64-KiB/512-byte grammar, recognize malformed `[routes`, `routes =`, `routes.`, and orphan `route_*` syntax before any no-routes return, preserve legacy parsing for malformed root-only settings without route syntax, apply global duplicate-field/raw-selector/normalized-path checks, require exact hostful identities (including host-edge-dot refusal), match paths component-wise, and enforce a no-escape boundary for `~/` selectors. A route replaces only routing fields; root privacy/behavior flags survive. Bounded native/PowerShell/TypeScript reads reject before full-file allocation where their APIs permit. | `ai-memory-core/fixtures/home_route_cases.json` is executed by native `marker.rs`, POSIX, PowerShell, generated TypeScript, and OpenClaw runtime parity, including malformed route syntax and root-only malformed legacy behavior; shell `test_lib.sh` also exercises route selection, sibling refusal, root-setting retention and invalid-map drop; Windows `powershell_marker_aliases.rs` executes drive and UNC path routing independently of identity; generated TypeScript runtime tests assert marker versus repo-root `project_src`; CLI tests prove unscoped/partial refusal and complete-explicit bypass. | STRONG for native/POSIX/generated TypeScript/OpenClaw on this platform; PowerShell runtime evidence is enforced on Windows CI and skipped where PowerShell is unavailable || 14bc | Project-coordinate diagnostics are root-only, read-only and credential-safe (#1033) | `ai-memory-store/src/reader.rs` `diagnose_project_coordinate` and `project_coordinates.rs` share one bounded indexed matcher and the write path's canonical-only promotion predicate; `ai-memory-mcp/src/admin.rs` mounts `GET /admin/project-coordinate` behind the shared `Capability::Admin` middleware and returns no stored identity value; `ai-memory-cli/src/marker.rs` and `commands/hook_capture.rs` provide one strict typed local inspection consumed by `doctor`, which reports only marker/source classes, identity source/style and derived names. Ambiguous count lookup keeps local rows and marks captured counts unavailable | Store `identity_resolution.rs` `coordinate_diagnostic_classifies_exact_canonical_legacy_and_missing_without_mutation`, `coordinate_diagnostic_reports_cross_forge_and_identityless_collisions`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; MCP `admin_status_search.rs` `project_coordinate_reports_all_statuses_and_never_mutates`, `project_coordinate_is_root_only_after_multiuser_enablement`, `project_coordinate_single_user_admin_contract_remains_open`, plus the shared all-admin 403/401 route matrix; CLI `doctor.rs` `project_coordinate_renders_promotion_and_cross_forge_fallback_concisely`, `local_coordinate_reports_marker_precedence_invalid_toml_and_no_credentials`; `marker.rs` strict inspection tests; `doctor_e2e.rs` `ambiguous_coordinate_keeps_local_sessions_and_marks_capture_unavailable` | STRONG: project/audit/user/grant/page counts, names and manifest bytes are snapshotted; DB-user/anonymous refusal has a root control; sentinel repo paths, identities, users, grants, pages, malformed marker text, absolute marker paths and credential-bearing remotes do not appear in output; an ambiguous preferred candidate remains contextual only and is never rename-eligible |diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.mdindex 542bc867..a671a2e8 100644--- a/docs/upgrading-to-3.0.md+++ b/docs/upgrading-to-3.0.md@@ -140,6 +140,28 @@ Backfill and recovery replay now use reserved `recovery_*` idempotency keysai-memory 2.6.0 or older imported can store some of those observations asecond time. Avoid forcing a re-import of sessions you already imported.+### 2.x projects are adopted from any checkout++A 2.x project is named after the folder it was captured from and carries no+repository identity. The first 3.x capture that brings the repository's+identity claims that project in place and, with the default `identity_style`,+renames it after the repository path (`github.com/acme/api` becomes+`acme-api`). Its UUID, pages, sessions and grants stay attached. A capture from+a linked worktree (`git worktree add`) claims the project named after its main+checkout, so it does not matter which checkout captures first. When a+worktree also had a 2.x project under its own folder name, the main+checkout's project is the one claimed and the worktree's is left as it was;+fold it in with `ai-memory merge-project --from <worktree-project> --into+<project>`, which prints a dry run until you add `--confirm`.++The server finds the main checkout by reading the worktree's git metadata, so+it has to be able to read your checkouts. A server that cannot, such as one in+a container without the host paths mounted, cannot do it. There, send the first+capture after the upgrade from the main checkout, or set+`project_strategy = "repo-root"` in a marker so the hooks name the main+checkout's project on the host (see+[Git worktrees](marker-file.md#git-worktrees--repo-root-identity)).+### Library changeThe `ai-memory-llm` crate no longer exports `OPENCODE_ZEN_BASE_URL`. Use